コード例 #1
0
 private void Awake()
 {
     if (instance == null)
     {
         instance = this;
     }
     else
     {
         Destroy(this);
     }
 }
コード例 #2
0
        public void Loading_WithNullResponseData_ThrowsException()
        {
            string rawResponseData = null;

            var loader = new JsonLoader();

            Assert.Throws <ArgumentNullException>(() =>
            {
                loader.Load(rawResponseData);
            });
        }
コード例 #3
0
        public void Constructing_WithJsonSerializerOptionsProvided_MakesHalResponseConvertorAvailable()
        {
            var serializerOptions = new JsonSerializerOptions();

            var loader = new JsonLoader(serializerOptions);

            var convertorLoaded =
                loader.JsonSerializerOptions.Converters.Any(
                    convertor => convertor.GetType() == typeof(HalResponseConvertor));

            Assert.True(convertorLoaded);
        }
コード例 #4
0
        public void Constructing_WithJsonSerializerOptionsProvided_SetsTheOptionsToUseToTheInstanceProvided()
        {
            var serializerOptions = new JsonSerializerOptions();

            var loader = new JsonLoader(serializerOptions);

            var convertorLoaded =
                loader.JsonSerializerOptions.Converters.Any(
                    convertor => convertor.GetType() == typeof(HalResponseConvertor));

            Assert.Same(serializerOptions, loader.JsonSerializerOptions);
        }
コード例 #5
0
 private void loadGameShopList()
 {
     m_ShopItemList = JsonLoader.LoadJsonInResource <List <ShopItem> >("Json/shopItem");
     // foreach (var item in m_ShopItemList)
     // {
     //     if (item.prefabPath == null || item.prefabPath == "")
     //     {
     //         m_ShopItemList.Remove(item);
     //     }
     // }
     Debug.Log("Load avaliable shop item, count: " + m_ShopItemList.Count);
 }
コード例 #6
0
        public static MainConfig LoadMainConfig(string path = null)
        {
            var config = JsonLoader.Load <MainConfig>(path ?? MainConfig.MainConfigPath, false);

            if (String.IsNullOrWhiteSpace(config.OverrideOauth))
            {
                config.OverrideBotUser = Dont.Do1;
                config.OverrideOauth   = Dont.Do2;
            }
            config.Channel = config.Channel.ToLower();
            return(config);
        }
コード例 #7
0
    public void Init()
    {
        SceneRoot = GameObject.Find("SceneRoot").transform;
        UIRoot    = GameObject.Find("UIRoot").transform;
        OtherRoot = GameObject.Find("OtherRoot").transform;

        _child  = new Child(childPressValue, childHarmonyValue, childMoneyValue, childHealthyValue);
        _father = new Father(fatherPressValue, fatherHarmonyValue, fatherMoneyValue, fatherHealthyValue);
        _loader = JsonLoader.getInstance();

        _state = GameState.Menu;
    }
コード例 #8
0
ファイル: JsonLoaderTests.cs プロジェクト: Batanick/libra
        public void NoId_Throw()
        {
            var assembly = typeof(LibraTests).Assembly;
            var loader   = new JsonLoader(_logger);

            loader.Register(_allTypes);

            var resource = assembly.GetManifestResourceNames().First(r => r.EndsWith("no_id.json"));
            var stream   = assembly.GetManifestResourceStream(resource);

            Throws <ResourceSystemException>(() => loader.Parse(stream));
        }
コード例 #9
0
ファイル: TrimmingCommand.cs プロジェクト: JRY-Zheng/ligral
 public override void Run()
 {
     try
     {
         ControlInput.IsOpenLoop = true;
         Settings settings = Settings.GetInstance();
         settings.GetDefaultSettings();
         logger.Info($"Ligral (R) Simulation Engine version {Program.Version}.\nCopyright (C) Ligral Tech. All rights reserved.");
         PluginLoader pluginLoader = new PluginLoader();
         pluginLoader.Load();
         if (IsJsonFile is bool isJsonFile && isJsonFile)
         {
             JsonLoader jsonLoader = new JsonLoader();
             jsonLoader.Load(FileName);
         }
         else
         {
             Interpreter interpreter = Interpreter.GetInstance(FileName);
             interpreter.Interpret();
         }
         Inspector    inspector   = new Inspector();
         List <Model> routine     = inspector.Inspect(ModelManager.ModelPool);
         string       problemName = Path.GetFileNameWithoutExtension(FileName);
         Problem      problem     = new Problem(problemName, routine);
         Trimmer      trimmer     = new Trimmer();
         if (settings.TrimmerConfiguration != null)
         {
             trimmer.Configure(settings.TrimmerConfiguration);
         }
         else
         {
             logger.Warn("No trimming configuration is set. The model will be trimmed at zero.");
         }
         settings.ApplySetting();
         trimmer.GetCondition();
         trimmer.Trim(problem);
         if (OutputFile is string outputFile)
         {
             try
             {
                 File.WriteAllText(outputFile, trimmer.ToString());
             }
             catch (Exception e)
             {
                 logger.Prompt(trimmer.ToString());
                 throw logger.Error(new LigralException($"Cannot write to {outputFile}, got error: {e.Message}"));
             }
         }
         else
         {
             logger.Prompt(trimmer.ToString());
         }
     }
コード例 #10
0
    // Use this for initialization
    void Start()
    {
        n_poses    = poses.Length;
        loaders    = new JsonLoader <Pose> [n_poses];
        poseModels = new Pose[n_poses];

        for (int i = 0; i < n_poses; ++i)
        {
            loaders[i] = new JsonLoader <Pose>(poses[i]);
            loaders[i].LoadJson(OnPoseWeightLoaded(i));
        }
    }
コード例 #11
0
        new public bool TryReloadConfiguratorState()
        {
            BuildingModifierState state;

            if (!JsonLoader.TryLoadConfiguration(this.StateFilePath, out state))
            {
                return(false);
            }

            State = state;
            return(true);
        }
コード例 #12
0
ファイル: LevelProgress.cs プロジェクト: asmCode/pix_it_all_2
    public void Save()
    {
        var path = GetFilePath(BundleId, ImageId);

        m_data.Version = Version;

        bool success = JsonLoader.SaveToFile(path, m_data);

        if (!success)
        {
            Debug.LogFormat("Couldn't save progress for level: {0}", path);
        }
    }
コード例 #13
0
ファイル: SpecialtyService.cs プロジェクト: jtdunlop/eve-api
        public static List <SpecialtyDTO> GetSpecialties()
        {
            const string url    = "http://public-crest.eveonline.com/industry/specialities/";
            var          json   = JsonLoader.Load(url);
            var          result = JsonConvert.DeserializeObject <RootObject>(json);

            return(result.items.Select(f => new SpecialtyDTO
            {
                SpecialtyId = f.id,
                Name = f.name,
                GroupIds = f.groups.Select(g => g.id).ToList()
            }).ToList());
        }
コード例 #14
0
 private void Awake()
 {
     DontDestroyOnLoad(this.gameObject);
     var savedStarNum = JsonLoader.LoadSaveData().stageStarNum;
     if (savedStarNum == null)
     {
         stageStarNum = new List<int>();
     }
     else
     {
         stageStarNum = savedStarNum.ToList();
         originalStarNum = new List<int>(stageStarNum);
     }
 }
コード例 #15
0
        public static void Example()
        {
            var loader = new JsonLoader();
            var data   = loader.LoadObject <Data>("TestLoader/config");

            foreach (var actor in data.Actors)
            {
                Logger.Log(actor.Value.GetType().ToString());
            }

            var zombie = data.Actors.Values.First(actor => actor is Zombie) as Zombie;

            Logger.Log(zombie?.SomeZombieField);
        }
コード例 #16
0
        public static Dictionary <string, GameEvent> loadGameEvents(string path)
        {
            Dictionary <string, GameEvent> eventDict = new Dictionary <string, GameEvent>();

            var files = Utility.RetrieveFilePathForFilesInDirectory(path, "*.json");

            foreach (var file in files)
            {
                var evt = JsonLoader.Load <GameEvent>(file, false);
                eventDict.Add(Path.GetFileNameWithoutExtension(file), evt);
            }

            return(eventDict);
        }
コード例 #17
0
    /// <summary>
    /// Setup scene based on currenntHive (loaded from PlayerPrefs path)
    /// </summary>
    void SetupCurrentHive()
    {
        HiveData currentHive =
            JsonLoader.LoadFromJSON <HiveData>(PlayerPrefs.GetString("CurrentHivePath"));

        // Setup texts
        hiveNameLabel.text = "Beute " + currentHive.number;
        hiveInfoLabel.text =
            "Beute " + currentHive.number + "\n" +
            currentHive.location;

        hiveGalleryItem.Setup(currentHive);
        checkupGallery.Setup(currentHive.id);
    }
コード例 #18
0
ファイル: PageManager.cs プロジェクト: HaKDMoDz/4DBlockEngine
	    public async void Initialize()
	    {
	        if (File.Exists(Path.Combine(m_dataDirectory, "SaveDirectory.json")))
	        {
	            var loader = new JsonLoader(m_dataDirectory);
                m_directory = await loader.Load<SaveDirectory>("SaveDirectory", "SaveDirectory");
	        }
	        else
	        {
                m_directory = new SaveDirectory();
                m_jsonWriter.Write("SaveDirectory", m_directory);
	        }
	        IsInitialized = true;
	    }
コード例 #19
0
ファイル: InputMapper.cs プロジェクト: nshcat/roguelikeNET
        /// <summary>
        /// Load the schema from JSON document
        /// </summary>
        /// <exception cref="ArgumentException">If the schema file does not exist or is otherwise incorrect</exception>
        protected void LoadSchema()
        {
            // Check if the schema file actually exists
            if (!File.Exists(SchemaFilePath))
            {
                Logger.PostMessageTagged(SeverityLevel.Fatal, "InputMapper", String.Format("Schema file for input mapping \"{0}\" does not exist!", Identifier));
                throw new ArgumentException("Input mapping schema file not found");
            }

            try
            {
                // Parse schema file as JSON object
                using (var fileReader = File.OpenText(SchemaFilePath))
                    using (var jsonReader = new JsonTextReader(fileReader))
                    {
                        // Since the readonly dictionary does not support insertion, we need to collect our schema data in a temporary
                        // mutable dictionary and later assign it to the property
                        var temporarySchema = new Dictionary <string, KeySchemaEntry>();

                        var array = JToken.ReadFrom(jsonReader) as JArray;

                        if (array == null)
                        {
                            throw new ArgumentException("Failed to load top level array from schema file");
                        }

                        // Parse each schema entry
                        foreach (var entry in array)
                        {
                            // All entries need to be objects
                            if (entry.Type != JTokenType.Object)
                            {
                                Logger.PostMessageTagged(SeverityLevel.Fatal, "InputMapper", String.Format("Expected JSON object in schema definition, got \"{0}\" instead", entry.Type.ToString()));
                                throw new ArgumentException("Expected JSON object in schema definition");
                            }

                            var schemaEntry = JsonLoader.Deserialize <KeySchemaEntry>(entry as JObject);

                            temporarySchema.Add(schemaEntry.Identifier, schemaEntry);
                        }

                        Schema = new ReadOnlyDictionary <string, KeySchemaEntry>(temporarySchema);
                    }
            }
            catch (Exception e)
            {
                Logger.PostMessageTagged(SeverityLevel.Fatal, "InputMapper", String.Format("Failed to load input mapping schema file: {0}", e.Message));
                throw;
            }
        }
コード例 #20
0
ファイル: MainTest.cs プロジェクト: nshcat/roguelikeNET
        public void TestSerialize()
        {
            var element = new Test2(TestEnum.Nyan, 1337, new Test3(42));

            var json = JsonWriter.Serialize(element);

            var result = JsonLoader.Deserialize <Test2>(json);

            Console.WriteLine(json.ToString());

            Assert.Equal(element, result);

            File.WriteAllText("test_out", json.ToString());
        }
コード例 #21
0
ファイル: InputMapper.cs プロジェクト: nshcat/roguelikeNET
        /// <summary>
        /// Load the key map override file if it exists.
        /// </summary>
        /// <exception cref="ArgumentException">If the key map override file is in invalid format</exception>
        protected void LoadOverrides()
        {
            // Only load overrides if the file actually exists
            if (!File.Exists(OverrideFilePath))
            {
                return;
            }

            try
            {
                // Parse schema file as JSON object
                using (var fileReader = File.OpenText(OverrideFilePath))
                    using (var jsonReader = new JsonTextReader(fileReader))
                    {
                        var array = JToken.ReadFrom(jsonReader) as JObject;

                        if (array == null)
                        {
                            throw new ArgumentException("Failed to load top level object from key binding override file");
                        }

                        // Parse each key binding
                        foreach (var entry in array)
                        {
                            // All entries need to be objects
                            if (entry.Value.Type != JTokenType.Object)
                            {
                                Logger.PostMessageTagged(SeverityLevel.Fatal, "InputMapper", String.Format("Expected JSON object in key binding override file, got \"{0}\" instead", entry.Value.Type.ToString()));
                                throw new ArgumentException("Expected JSON object in schema definition");
                            }

                            // Check that a schema entry actually exists for given identifier
                            if (!Schema.ContainsKey(entry.Key))
                            {
                                Logger.PostMessageTagged(SeverityLevel.Fatal, "InputMapper", String.Format("Unknown action identifier \"{0}\" in override file for key map \"{1}\"", entry.Key, Identifier));
                                throw new ArgumentException("Unknown action identifier in override file");
                            }

                            var binding = JsonLoader.Deserialize <KeyBinding>(entry.Value as JObject);

                            OverrideBindings.Add(entry.Key, binding);
                        }
                    }
            }
            catch (Exception e)
            {
                Logger.PostMessageTagged(SeverityLevel.Fatal, "InputMapper", String.Format("Failed to load input mapping schema file: {0}", e.Message));
                throw;
            }
        }
コード例 #22
0
ファイル: TeamService.cs プロジェクト: jtdunlop/eve-api
        public List <TeamDTO> GetAuctions()
        {
            const string url    = "http://public-crest.eveonline.com/industry/teams/auction/";
            var          json   = JsonLoader.Load(url);
            var          result = JsonConvert.DeserializeObject <AuctionRoot>(json);

            return(result.items.Select(f => new TeamDTO
            {
                TeamId = f.id,
                SolarSystemId = f.solarSystem.id,
                StartDate = DateTime.Parse(f.creationTime).AddDays(7),
                TeamDescription = f.name,
                Bonuses = GetBonuses(f.workers).ToList()
            }).ToList());
        }
コード例 #23
0
ファイル: TestFactory.cs プロジェクト: dkoleev/GameFramework
        private void TestWithRemoteConfig()
        {
            LoadConfig();

            void LoadConfig()
            {
                var loader = new JsonLoader();
                var data   = loader.LoadObject <ConfigData>("config");//objects creating by factory inside TypeBaseConverter

                foreach (var item in data.Components)
                {
                    Logger.Log(item.Value.GetType().ToString());
                }
            }
        }
コード例 #24
0
        public void Loading_WithResponseData_ReturnsPopulatedDictionary()
        {
            var rawResponseData = "{ \"some-Property\": \"Some Value\" }";

            var loader = new JsonLoader();

            var result = loader.Load(rawResponseData);

            var expectedDictionary = new Dictionary <string, object>
            {
                { "some-Property", "Some Value" }
            };

            Assert.Equal(expected: expectedDictionary, actual: result);
        }
コード例 #25
0
        private void DataGridView1_DragDrop(object sender, DragEventArgs e)
        {
            // still check if the associated data from the file(s) can be used for this purpose
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                // Fetch the file(s) names with full path here to be processed
                var files = (string[])e.Data.GetData(DataFormats.FileDrop);

                // Your desired code goes here to process the file(s) being dropped
                var r = JsonLoader.LoadJson(files);
                if (r.Items.Any())
                {
                    this.Bind(r);
                }
            }
        }
コード例 #26
0
    // inicializacion de atributos y lectura de todos los niveles
    // le indicamos que este objeto no debe destruirse entre escenas
    void Awake()
    {
        instance   = this;
        jsonLoader = new JsonLoader();
        jsonLoader.SetJson(rawJsonLevels.text);
        jsonLoader.LoadAllLevels();

        money             = 0;
        medals            = 0;
        challengeTimeLeft = 0;
        giftTimeLeft      = 0;
        currentTime       = 0;
        day = 1;

        DontDestroyOnLoad(this.gameObject);
    }
コード例 #27
0
    // Load map information, possible tiles and tile sprites
    public void LoadMapResources()
    {
        // Parse Json map data
        MapJsonData data = JsonLoader.LoadMapJsonFile(worldMap.fileName);

        mapWidth       = data.map_width;
        mapHeight      = data.map_height;
        numberOfHouses = data.number_of_houses;

        // Find and add all possible tile types
        TileJsonData[] loadedTileTypes = data.tiles;
        foreach (TileJsonData td in loadedTileTypes)
        {
            // Tile type is unique
            // Check if the type is already loaded
            if (!tileTypes.Contains(td.type))
            {
                Tile newPossibleTile = new Tile();

                // Register new tile type
                tileTypes.Add(td.type);

                int typeIndex = tileTypes.Count - 1;
                newPossibleTile.typeID = (ushort)typeIndex;

                // Load sprites for the given tile type, tile images have the same name as tile types.
                string spritePath = "Images/" + td.type;
                Sprite newSprite  = Resources.Load <Sprite>(spritePath);
                loadedSprites.Add(newSprite);

                // Tile names are not unique
                // Register tile name if it is new
                if (!tileNames.Contains(td.name))
                {
                    tileNames.Add(td.name);
                }

                int nameIndex = tileNames.IndexOf(td.name);
                newPossibleTile.nameID = (ushort)nameIndex;

                // Register tile level, tiles with no given level are level 0
                newPossibleTile.level = (byte)td.level;

                possibleTiles.Add(newPossibleTile);
            }
        }
    }
コード例 #28
0
ファイル: ShopManager.cs プロジェクト: Juul1501/Miner
    void Awake()
    {
        CheckPanels();

        //Instantiate or load Json File
        jsonLoader = new JsonLoader();
        if (System.IO.File.Exists(Application.persistentDataPath + upgradeSavepath))
        {
            Data d = jsonLoader.LoadJson(upgrades, upgradeSavepath);
            if (d is Upgrades)
            {
                upgrades = (Upgrades)d;
            }
        }
        else
        {
            upgrades = new Upgrades();
            jsonLoader.SaveJson(upgrades, upgradeSavepath);
            Debug.Log("created new json");
        }

        if (System.IO.File.Exists(Application.persistentDataPath + "/money.cash"))
        {
            Data m = jsonLoader.LoadJson(MoneyManager.Instance.money, "/money.cash");
            if (m is Money)
            {
                MoneyManager.Instance.money = (Money)m;
            }
        }
        else
        {
            MoneyManager.Instance.money = new Money(0);
            jsonLoader.SaveJson(MoneyManager.Instance.money, "/money.cash");
            Debug.Log("created new json");
        }


        upgrades.MaxFuelUpgrade.Price     = 150;
        upgrades.MoveSpeedUpgrade.Price   = 200;
        upgrades.SlideLengthUpgrade.Price = 100;
        upgradePriceText.text             = "$ " + upgrades.MoveSpeedUpgrade.Price;


        InitiateIndicators();
        Debug.Log(MoneyManager.Instance.money.Amount);
    }
コード例 #29
0
ファイル: Program.cs プロジェクト: Carayaca/LordsBotStat
        private static void Run(ProgramOptions options)
        {
            try
            {
                var report = JsonLoader.LoadDir(options.InputDirectory);
                if (!string.IsNullOrEmpty(options.Members))
                {
                    report.Imbue(options.Members);
                }

                View.Render(report, options.PlainText);
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }
コード例 #30
0
ファイル: AnimatedEntity.cs プロジェクト: Tankooni/zeebs
        public bool CreateHead(string headName, bool isAvatar)
        {
            try
            {
                var       newHeadImage = Library.GetTexture((isAvatar ? "twitchAvatar//" : "twitch//") + headName);
                var       animDataPath = string.Format("{0}{1}.json", Indigo.Content.TwitchEmoteProvider.TWITCH_CACHE_PATH, headName);
                Spritemap tempSp       = null;
                if (!File.Exists(animDataPath))
                {
                    Head = new Image(newHeadImage);
                }
                else
                {
                    var animationData = JsonLoader.Load <FramePacker.PackedSpriteMapMeta>(animDataPath, false);
                    var headSpriteMap = new Spritemap(newHeadImage, animationData.FrameWidth, animationData.FrameHeight);
                    headSpriteMap.Add("Default", FP.MakeFrames(0, animationData.TotalFrames - 1), 24, true);
                    headSpriteMap.Play("Default");                    //animationData.FPS
                    Head   = headSpriteMap;
                    tempSp = headSpriteMap;
                }
                AddComponent(Head);

                Head.CenterOrigin();
                Head.Scale = AnimatedEntityData.Animations[Sprite.CurrentAnim].HeadWidth / (float)Head.Width;

                Head.X = AnimatedEntityData.Animations[Sprite.CurrentAnim].HeadPositionX;
                Head.Y = AnimatedEntityData.Animations[Sprite.CurrentAnim].HeadPositionY;

                currentHeadTween = Tweener.Tween(Head, new { Y = AnimatedEntityData.Animations[Sprite.CurrentAnim].HeadPositionY - 4 }, .7f);
                currentHeadTween.Ease(Ease.ToAndFro);
                currentHeadTween.Repeat();

                currentHeadName = headName;
                return(true);
            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine("Cannot Find: " + headName);
                Console.WriteLine(ex);
#endif
                //throw (ex);
                return(false);
            }
        }
コード例 #31
0
    /// <summary>
    /// Initialize references, initialize dataObject
    /// </summary>
    protected virtual void Awake()
    {
        obligatoryFieldFilled   = new Dictionary <string, bool>();
        inputDisplaysByDataType = new Dictionary <string, InputDisplay>();

        // load existing dataObject if PlayerPrefs variable is set
        if (PlayerPrefs.GetString(dataModifier.currentDataObjectPath, "") != "")
        {
            dataObject = JsonLoader.LoadFromJSON <T>(
                PlayerPrefs.GetString(dataModifier.currentDataObjectPath));
            OnDataObjectLoaded();
        }
        // create new dataObject
        else
        {
            dataObject = CreateNewDataObject();
        }
    }
コード例 #32
0
ファイル: JsonLoaderTests.cs プロジェクト: acraven/saucy
        public void EmptyFileThrowsJsonReaderException()
        {
            var testSubject = new JsonLoader();

             Assert.That(() => testSubject.Load(@"TestData\EmptyJsonFile.json"), Throws.InstanceOf<JsonReaderException>());
        }
コード例 #33
0
ファイル: JsonLoaderTests.cs プロジェクト: acraven/saucy
        public void MissingFileThrowsFileNotFoundException()
        {
            var testSubject = new JsonLoader();

             Assert.That(() => testSubject.Load("ThisDoesNotExist.json"), Throws.InstanceOf<FileNotFoundException>());
        }
コード例 #34
0
ファイル: Graph.cs プロジェクト: xire-/graphulus
    private void AddNodes(JsonLoader.JsonRoot jsonRoot)
    {
        Destroy(_nodesObject);
        _nodesObject = new GameObject("Nodes");
        _nodesObject.transform.parent = transform;

        foreach (var jsonNode in jsonRoot.nodes) {
            var springyNode = _forceDirectedGraph.CreateNewNode();

            var nodeObject = CreateNode(springyNode, jsonNode.name);
            nodeObject.transform.parent = _nodesObject.transform;
        }
    }
コード例 #35
0
ファイル: Graph.cs プロジェクト: xire-/graphulus
    private void AddEdges(JsonLoader.JsonRoot jsonRoot)
    {
        Destroy(_edgesObject);
        _edgesObject = new GameObject("Edges");
        _edgesObject.transform.parent = transform;

        foreach (var jsonEdge in jsonRoot.edges) {
            var sourceNode = _nodesObject.transform.GetChild(jsonEdge.source).gameObject;
            var targetNode = _nodesObject.transform.GetChild(jsonEdge.target).gameObject;
            var springyEdge = _forceDirectedGraph.CreateNewEdge(sourceNode.GetComponent<Node>().springyNode, targetNode.GetComponent<Node>().springyNode, jsonEdge.value);

            var edgeObject = CreateEdge(springyEdge, sourceNode, targetNode);
            edgeObject.transform.parent = _edgesObject.transform;
        }
    }