示例#1
0
        public async Task Init(string routeConfigFilePath)
        {
            dynamic router = await JsonLoader.LoadFromFileAsync <dynamic>(routeConfigFilePath);

            Routes = JsonLoader.Deserialize <List <Route> >(Convert.ToString(router.routes));
            AuthenticationService = JsonLoader.Deserialize <Destination>(Convert.ToString(router.authenticationService));
        }
示例#2
0
        public Router(string routeConfigFilePath)
        {
            var router = JsonLoader.LoadFromFile <dynamic>(routeConfigFilePath);

            Routes = JsonLoader.Deserialize <List <Route> >(Convert.ToString(router.routes));
            AuthenticationService = JsonLoader.Deserialize <Destination>(Convert.ToString(router.authenticationService));
        }
示例#3
0
        public ReverseProxyMiddleware(RequestDelegate nextMiddleware)
        {
            _nextMiddleware = nextMiddleware;
            dynamic router = JsonLoader.LoadFromFile <dynamic>("routes.json");

            _routes = JsonLoader.Deserialize <List <Route> >(Convert.ToString(router.routes));
        }
        public Router(string routeConfigFilePath, ILoggerManager logger)
        {
            dynamic router = JsonLoader.LoadFromFile <dynamic>(routeConfigFilePath);

            Routes = JsonLoader.Deserialize <List <Route> >(Convert.ToString(router.routes));
            AuthenticationService = JsonLoader.Deserialize <Destination>(Convert.ToString(router.authenticationService));
            this.logger           = logger;
        }
示例#5
0
        public void TestPreAndPost()
        {
            var src = "{ \"mrew\" : 42 }";

            var instance = JsonLoader.Deserialize <MethodTest>(JObject.Parse(src));

            Assert.True(instance.BeforeTriggered);
            Assert.True(instance.AfterTriggered);
        }
示例#6
0
        /// <summary>
        /// Search asset subfolder for JSON documents and try to interpret
        /// them as terrain type descriptions
        /// </summary>
        private static void LoadTypes()
        {
            // Retrieve asset path and build terrain type database path
            var path = Path.Combine(Paths.DataDirectory, "json", "terrain");

            // Inspect every JSON document and parse
            foreach (var file in Directory.GetFiles(path, "*.json", SearchOption.AllDirectories))
            {
                // File is a full path to the particular document
                try
                {
                    // Parse JSON file
                    using (var fileReader = File.OpenText(file))
                        using (var jsonReader = new JsonTextReader(fileReader))
                        {
                            // Since we want to allow multiple terrain definitions in a single file, we require
                            // the top level structure to be an array.
                            var dataSource = JArray.ReadFrom(jsonReader) as JArray;

                            // Loop through all terrain type definitions. They have to be objects.
                            foreach (var entry in dataSource)
                            {
                                // Ignore entries that are not objects
                                if (entry.Type != JTokenType.Object)
                                {
                                    Logger.PostMessageTagged(SeverityLevel.Warning, "TerrainTypeManager",
                                                             $"Ignoring non-object entry in terrain definition file \"{Path.GetFileName(file)}\"");

                                    continue;
                                }

                                // Deserialize terrain type instance from the JSON entry
                                var instance = JsonLoader.Deserialize <TerrainType>(entry as JObject);

                                // Check for uniquen ID
                                if (_terrainTypes.ContainsKey(instance.Identifier))
                                {
                                    throw new ArgumentException($"Terrain type with unique id \"{instance.Identifier}\" already exists, but is redefined in file \"{Path.GetFileName(file)}\"");
                                }

                                _terrainTypes.Add(instance.Identifier, instance);
                            }
                        }
                }
                catch (Exception e)
                {
                    Logger.PostMessageTagged(SeverityLevel.Fatal, "TerrainTypeManager",
                                             String.Format("Failed to load terrain type definition file \"{0}\": {1}", Path.GetFileName(file), e.Message));

                    throw;
                }
            }

            Logger.PostMessageTagged(SeverityLevel.Debug, "TerrainTypeManager",
                                     $"Loaded {_terrainTypes.Count} terrain types");
        }
示例#7
0
        /// <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;
            }
        }
示例#8
0
        /// <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;
            }
        }
示例#9
0
        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());
        }
示例#10
0
    public void PopulateFrom(string jsonPath)
    {
        var jsonRoot = JsonLoader.Deserialize(jsonPath);

        _forceDirectedGraph = new Springy.ForceDirectedGraph {
            Stiffness         = jsonRoot.parameters.stiffness,
            Repulsion         = jsonRoot.parameters.repulsion,
            Convergence       = jsonRoot.parameters.convergence,
            Damping           = jsonRoot.parameters.damping,
            EnergyThreshold   = -1f,
            SimulationEnabled = true
        };

        AddNodes(jsonRoot);
        AddEdges(jsonRoot);

        AdjustNodesSize();
    }
示例#11
0
        public void GivenRouteFileIsSupplied_RoutesAreExtractedFromTheFile()
        {
            var routes = _loader.Deserialize <List <Route> >(Convert.ToString(_router.routes));

            Assert.AreEqual("http://backendserviceurl.com", Convert.ToString(_router.backendServiceApiUrl));
            Assert.AreEqual(2, routes.Count);

            int routeIndex = 0;

            Assert.AreEqual("http://newbackendserviceurl.com", Convert.ToString(routes[routeIndex].Destination.Url));
            Assert.AreEqual("/rootEndpoint/endpoint1", Convert.ToString(routes[routeIndex].Endpoint));
            Assert.AreEqual("/endpoint1", Convert.ToString(routes[routeIndex].Destination.Endpoint));
            Assert.AreEqual(false, Convert.ToBoolean(routes[routeIndex].Destination.RequiresAuthentication));
            Assert.AreEqual(false, Convert.ToBoolean(routes[routeIndex].Destination.RequiresMemberId));

            routeIndex = 1;
            Assert.AreEqual(null, routes[routeIndex].Destination.Url);
            Assert.AreEqual("/rootEndpoint", Convert.ToString(routes[routeIndex].Endpoint));
            Assert.AreEqual(null, routes[routeIndex].Destination.Endpoint);
            Assert.AreEqual(true, Convert.ToBoolean(routes[routeIndex].Destination.RequiresAuthentication));
            Assert.AreEqual(true, Convert.ToBoolean(routes[routeIndex].Destination.RequiresMemberId));
        }
示例#12
0
        private void Deserialize(JObject obj)
        {
            // Populate palette if needed
            if (IsVaried)
            {
                try
                {
                    Palette = new WeightedDistribution <Tile>();

                    foreach (var token in obj["palette"] as JArray)
                    {
                        if (token.Type != JTokenType.Object)
                        {
                            throw new ArgumentException("Expected JSON object in palette array");
                        }

                        var entry = token as JObject;

                        var probability = entry["probability"].Value <double>();
                        var tile        = JsonLoader.Deserialize <Tile>(entry["tile"] as JObject);

                        Palette.Add(probability, tile);
                    }
                }
                catch (Exception e)
                {
                    Logger.PostMessageTagged(SeverityLevel.Fatal, "TerrainType", $"Failed to load terrain type \"{Identifier}\": {e.Message}");
                    throw;
                }
            }
            else if (Tile == null) // If IsVaried is false, the document has to supply tile information.
            {
                Logger.PostMessageTagged(SeverityLevel.Fatal, "TerrainType", $"Terrain type \"{Identifier}\" is not set to use varied tiles, but has no tile defined");
                throw new ArgumentException($"Terrain type \"{Identifier}\" is not set to use varied tiles, but has no tile defined");
            }
        }
示例#13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="UsersService"/> class.
        /// </summary>
        public UsersService()
        {
            dynamic users = JsonLoader.LoadFromFile <dynamic>("users.json");

            this.Users = JsonLoader.Deserialize <List <User> >(Convert.ToString(users));
        }
示例#14
0
 private Test Deserialize(string src)
 {
     return(JsonLoader.Deserialize <Test>(JObject.Parse(src)));
 }