Ejemplo n.º 1
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType != JsonToken.Null)
            {
                // Load JObject from stream
                var jObject = JObject.Load(reader);

                //if (objectType == typeof(IEntity)) {
                //  JToken typeNameToken;
                //  if (jObject.TryGetValue("$type", out typeNameToken)) {
                //    if (_normalizeTypeNameFn == null) {
                //      throw new Exception("NormalizeTypeNameFn not defined");
                //    }
                //    var entityTypeName = _normalizeTypeNameFn(typeNameToken.Value<String>());
                //    objectType = MetadataStore.Instance.GetEntityType(entityTypeName).ClrType;
                //  }
                //}

                var jsonContext = new JsonContext {
                    JObject = jObject, ObjectType = objectType, Serializer = serializer
                };
                // Create target object based on JObject
                var target = CreateAndPopulate(jsonContext);
                return(target);
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 2
0
        public void Save()
        {
            try
            {
                using (var db = new JsonContext())
                {
                    FieldsMetadatas.ToList()
                    .ForEach(field =>
                    {
                        field.OperatorId = OperatorId;
                        db.FieldsMetadatas.AddOrUpdate(e => e.FieldMetadataId, field);
                    });

                    var result = db.SaveChanges();

                    if (result == 1)
                    {
                        TryClose(true);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Какая то ошибочка : {ex.Message} {ex.StackTrace}");
            }
        }
Ejemplo n.º 3
0
        public void Setup()
        {
            _serialized = JsonSerializer.SerializeToUtf8Bytes(Program.Get());

            _oldPatternOptions = new JsonSerializerOptions();
            _newPatternContext = new JsonContext(new JsonSerializerOptions());
        }
Ejemplo n.º 4
0
        protected static JsonObject ParseJson(Request req)
        {
            JsonContext ctx = new JsonContext();

            ctx.Val = (string)req.Data;
            return((JsonObject)Json.ParseStream(ctx));
        }
Ejemplo n.º 5
0
        public void Setup()
        {
            _result = Program.Get();

            _oldPatternOptions = new JsonSerializerOptions();
            _newPatternContext = new JsonContext(new JsonSerializerOptions());
        }
Ejemplo n.º 6
0
        protected virtual Object PopulateEntity(JsonContext jsonContext, IEntity entity)
        {
            var aspect = entity.EntityAspect;

            if (aspect.EntityManager == null)
            {
                // new to this entityManager
                ParseObject(jsonContext, aspect);
                aspect.Entity.Initialize();
                // TODO: This is a nit.  Wierd case where a save adds a new entity will show up with
                // a AttachOnQuery operation instead of AttachOnSave
                _entityManager.AttachQueriedEntity(entity, (EntityType)jsonContext.StructuralType);
            }
            else if (_mergeStrategy == MergeStrategy.OverwriteChanges || aspect.EntityState == EntityState.Unchanged)
            {
                // overwrite existing entityManager
                ParseObject(jsonContext, aspect);
                aspect.OnEntityChanged(_loadingOperation == LoadingOperation.Query ? EntityAction.MergeOnQuery : EntityAction.MergeOnSave);
            }
            else
            {
                // preserveChanges handling - we still want to handle expands.
                ParseObject(jsonContext, null);
            }

            return(entity);
        }
Ejemplo n.º 7
0
    protected virtual Object CreateAndPopulate(JsonContext jsonContext) {
      var jObject = jsonContext.JObject;

      JToken refToken = null;
      if (jObject.TryGetValue("$ref", out refToken)) {
        return _refMap[refToken.Value<String>()];
      }

      var objectType = jsonContext.ObjectType;
      var entityType =  _metadataStore.GetEntityType(objectType);

      // an entity type
      jsonContext.StructuralType = entityType;
      var keyValues = entityType.KeyProperties
        .Select(p => jObject[p.Name].ToObject(p.ClrType))
        .ToArray();
      var entityKey = EntityKey.Create(entityType, keyValues);
      var entity = _entityManager.FindEntityByKey(entityKey);
      if (entity == null) {
        entity = (IEntity)Activator.CreateInstance(objectType);
      }
      // must be called before populate
      UpdateRefMap(jObject, entity);
      _allEntities.Add(entity);
      return PopulateEntity(jsonContext, entity);

    }
Ejemplo n.º 8
0
        protected virtual Object CreateAndPopulate(JsonContext jsonContext)
        {
            var jObject = jsonContext.JObject;

            JToken refToken = null;

            if (jObject.TryGetValue("$ref", out refToken))
            {
                return(_refMap[refToken.Value <String>()]);
            }

            var objectType = jsonContext.ObjectType;
            var entityType = _metadataStore.GetEntityType(objectType);

            // an entity type
            jsonContext.StructuralType = entityType;
            var keyValues = entityType.KeyProperties
                            .Select(p => jObject[p.Name].ToObject(p.ClrType))
                            .ToArray();
            var entityKey = EntityKey.Create(entityType, keyValues);
            var entity    = _entityManager.FindEntityByKey(entityKey);

            if (entity == null)
            {
                entity = (IEntity)Activator.CreateInstance(objectType);
            }
            // must be called before populate
            UpdateRefMap(jObject, entity);
            _allEntities.Add(entity);
            return(PopulateEntity(jsonContext, entity));
        }
Ejemplo n.º 9
0
        public void SaveDataSet_Entity_Test()
        {
            string connectionString = TestHelper.GetTestDataOuputFolder(TestContext.CurrentContext);
            var    context          = new JsonContext(connectionString);
            var    entities         = new Dictionary <string, TestEntityOne>
            {
                { "3c0b80ed-6542-42c0-a3df-eef2d784011f", new TestEntityOne {
                      Id = "3c0b80ed-6542-42c0-a3df-eef2d784011f", FieldA = "Field_A_1", FieldB = 101, FieldC = "Field_C_1", FieldD = false
                  } },
                { "caab946b-a155-4297-a8a6-aaaa5aedf76d", new TestEntityOne {
                      Id = "caab946b-a155-4297-a8a6-aaaa5aedf76d", FieldA = "Field_A_2", FieldB = 202, FieldC = "Field_C_2", FieldD = true
                  } },
                { "3e627ea2-27e6-48a3-9846-3f27008edd6b", new TestEntityOne {
                      Id = "3e627ea2-27e6-48a3-9846-3f27008edd6b", FieldA = "Field_A_3", FieldB = 303, FieldC = "Field_C_3", FieldD = false
                  } },
                { "77a906b7-46ca-4e9a-b94b-5cf816f4d984", new TestEntityOne {
                      Id = "77a906b7-46ca-4e9a-b94b-5cf816f4d984", FieldA = "Field_A_4", FieldB = 404, FieldC = "Field_C_4", FieldD = true
                  } }
            };

            context.SaveDataSet(entities);

            var file = new FileInfo(Path.Combine(connectionString, "TestEntityOnes.json"));

            Assert.IsTrue(file.Exists);
        }
Ejemplo n.º 10
0
 static void ParseWhitespace(JsonContext c)
 {
     while (c[c.index] == ' ' || c[c.index] == '\t' || c[c.index] == '\n' || c[c.index] == '\r')
     {
         c++;
     }
 }
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            //メタデータ取得
            JsonContext context = new JsonContext();
            IEnumerable <MetaDataModel> metaData = context.Select <MetaDataModel>("JsonMetaData.json");

            //データ取得
            IEnumerable <TestModel> testModel = context.Select <TestModel>("JsonData.json");

            //変換用ホルダー作成
            //TODO 複数の場合は? => modelが必ずしもcollectionではないことを考えると外から繰り返し処理
            //collectionはどこにもつ? => holderもしくはもたずにシナリオで外から順に与える
            ModelInfoHolder holder = new ModelInfoHolder(testModel, metaData);

            //変換処理の実行
            FromModelToDictionaryBuilder builder = new FromModelToDictionaryBuilder();
            //FromModelToJsonBuilder builder = new FromModelToJsonBuilder();
            //FromModelToDuplicateKeyDictionaryBuilder builder = new FromModelToDuplicateKeyDictionaryBuilder();
            //FromModelToDuplicateKVBuilder builder = new FromModelToDuplicateKVBuilder();
            Director director = new Director(builder, holder);

            director.ConvertModel();

            IModel toModel = holder.GetToModel();
            IEnumerable <IModel> toModelCollection = holder.GetToModelCollection();

            Console.WriteLine(toModel);
        }
Ejemplo n.º 12
0
        public override void Use(Player p, string message, CommandData data) {
            if (message.Length == 0) {
                if (p.IsSuper) { SuperRequiresArgs(p, "player name or IP"); return; }
                message = p.name;
            }
            
            string name, ip = ModActionCmd.FindIP(p, message, "Location", out name);
            if (ip == null) return;
            
            if (HttpUtil.IsPrivateIP(ip)) {
                p.Message("%WPlayer has an internal IP, cannot trace"); return;
            }

            JsonContext ctx = new JsonContext();
            using (WebClient client = HttpUtil.CreateWebClient()) {
                ctx.Val = client.DownloadString(https://geoip.pw/" + ip);
            }
            
            JsonObject obj = (JsonObject)Json.ParseStream(ctx);
            GeoInfo info = new GeoInfo();
            if (obj == null || !ctx.Success) {
                p.Message("%WError parsing GeoIP info"); return;
            }
            
            if (elems == null) elems = ConfigElement.GetAll(typeof(GeoInfo));
            obj.Deserialise(elems, info);
            
            string target = name == null ? ip : "of " + PlayerInfo.GetColoredName(p, name);
            p.Message("The IP {0} %Shas been traced to: &b{1}%S/&b{2}", 
                      target, info.region, info.country);
        }
Ejemplo n.º 13
0
    internal static JsonSerializerOptions CreateSerializerOptions(JsonContext context, bool isStreamingOptions = false)
    {
        // Streaming is line delimited between messages. That means JSON can't be indented as it adds new lines.
        // For streaming to work, indenting must be disabled when streaming.
        var writeIndented = !isStreamingOptions ? context.Settings.WriteIndented : false;

        var typeInfoResolver = JsonTypeInfoResolver.Combine(
            new MessageTypeInfoResolver(context),
            new DefaultJsonTypeInfoResolver());

        var options = new JsonSerializerOptions
        {
            WriteIndented    = writeIndented,
            NumberHandling   = JsonNumberHandling.AllowNamedFloatingPointLiterals,
            Encoder          = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
            TypeInfoResolver = typeInfoResolver
        };

        options.Converters.Add(new NullValueConverter());
        options.Converters.Add(new ByteStringConverter());
        options.Converters.Add(new Int64Converter(context));
        options.Converters.Add(new UInt64Converter(context));
        options.Converters.Add(new BoolConverter());
        options.Converters.Add(new JsonConverterFactoryForEnum(context));
        options.Converters.Add(new JsonConverterFactoryForWrappers(context));
        options.Converters.Add(new JsonConverterFactoryForWellKnownTypes(context));

        return(options);
    }
Ejemplo n.º 14
0
        static bool ParseHex4(JsonContext c, out uint number)
        {
            int i;

            number = 0;
            for (i = 0; i < 4; i++)
            {
                char ch = c[c.index++];
                number <<= 4;
                if (ch >= '0' && ch <= '9')
                {
                    number |= (uint)(ch - '0');
                }
                else if (ch >= 'A' && ch <= 'F')
                {
                    number |= (uint)(ch - ('A' - 10));
                }
                else if (ch >= 'a' && ch <= 'f')
                {
                    number |= (uint)(ch - ('a' - 10));
                }
                else
                {
                    return(false);
                }
            }
            return(true);
        }
Ejemplo n.º 15
0
            internal static List <EffectSpawner> ReadAll(string json)
            {
                List <EffectSpawner> spawners = new List <EffectSpawner>();

                if (elems == null)
                {
                    elems = ConfigElement.GetAll(typeof(EffectSpawner));
                }

                JsonContext ctx   = new JsonContext(); ctx.Val = json;
                JsonArray   array = (JsonArray)Json.ParseStream(ctx);

                if (array == null)
                {
                    return(spawners);
                }

                foreach (object raw in array)
                {
                    JsonObject obj = (JsonObject)raw;
                    if (obj == null)
                    {
                        continue;
                    }

                    EffectSpawner data = new EffectSpawner();
                    obj.Deserialise(elems, data);

                    spawners.Add(data);
                }
                return(spawners);
            }
Ejemplo n.º 16
0
        static string GetError(string json)
        {
            JsonContext ctx = new JsonContext(); ctx.Val = json;
            JsonObject  obj = (JsonObject)Json.ParseStream(ctx);

            if (obj == null)
            {
                return(null);
            }

            for (int i = 0; i < obj.Keys.Count; i++)
            {
                if (!obj.Keys[i].CaselessEq("errors"))
                {
                    continue;
                }
                object value = obj.Values[i];
                if (value == null)
                {
                    return(null);
                }

                // silly design, but form of json is: "errors": [ ["Error1"], ["Error2"] ]
                JsonArray errors = (JsonArray)value;
                foreach (object raw in errors)
                {
                    JsonArray error = raw as JsonArray;
                    if (error != null && error.Count > 0)
                    {
                        return((string)error[0]);
                    }
                }
            }
            return(null);
        }
Ejemplo n.º 17
0
        public async Task <IEnumerable <Items> > GetAsync()
        {
            var itemIds = await JsonContext.GetAsync <int[]>("https://hacker-news.firebaseio.com/v0/newstories.json");

            var items = await GetListOfItems(itemIds);

            return(items.ToArray());
        }
Ejemplo n.º 18
0
        private static ParseResult ParseObject(JsonContext c, out JsonObject v)
        {
            v = null;
            c++;
            ParseWhitespace(c);
            if (c[c.index] == '}')
            {
                c++;
                v = new JsonObject(JsonObjectType.Object);
                return(ParseResult.OK);
            }

            var ret = new JsonObject();

            for (;;)
            {
                if (c[c.index] != '"')
                {
                    return(ParseResult.MISS_KEY);
                }
                JsonObject keyObj    = null;
                var        keyResult = ParseString(c, out keyObj);
                if (keyResult != ParseResult.OK)
                {
                    return(keyResult);
                }
                ParseWhitespace(c);
                if (c[c.index] != ':')
                {
                    return(ParseResult.MISS_COLON);
                }
                c++;
                ParseWhitespace(c);
                JsonObject valueObj    = null;
                var        valueResult = ParseValue(c, out valueObj);
                if (valueResult != ParseResult.OK)
                {
                    return(valueResult);
                }
                ret.Add(keyObj.GetString(), valueObj);
                ParseWhitespace(c);
                if (c[c.index] == ',')
                {
                    c++;
                    ParseWhitespace(c);
                }
                else if (c[c.index] == '}')
                {
                    c++;
                    v = ret;
                    return(ParseResult.OK);
                }
                else
                {
                    return(ParseResult.MISS_COMMA_OR_CURLY_BRACKET);
                }
            }
        }
Ejemplo n.º 19
0
        protected void SaveJsonState(string name, IJsonConvertible state)
        {
            var json = new JsonContext().ToJson(state);

            using (var sw = new StringWriter()) {
                JsonValue.WriteMin(json, sw);
                State[name] = sw.GetStringBuilder().ToString();
            }
        }
Ejemplo n.º 20
0
        static ParseResult ParseNumber(JsonContext c, out JavaScriptObject v)
        {
            v = null;
            int index = c.index;

            if (c[index] == '-')
            {
                index++;
            }
            if (c[index] == '0')
            {
                index++;
            }
            else
            {
                if (!IsDigit1To9(c[index]))
                {
                    return(ParseResult.INVALID_VALUE);
                }
                for (index++; IsDigit(c[index]); index++)
                {
                    ;
                }
            }
            if (c[index] == '.')
            {
                index++;
                if (!IsDigit(c[index]))
                {
                    return(ParseResult.INVALID_VALUE);
                }
                for (index++; IsDigit(c[index]); index++)
                {
                    ;
                }
            }
            if (c[index] == 'e' || c[index] == 'E')
            {
                index++;
                if (c[index] == '+' || c[index] == '-')
                {
                    index++;
                }
                if (!IsDigit(c[index]))
                {
                    return(ParseResult.INVALID_VALUE);
                }
                for (index++; IsDigit(c[index]); index++)
                {
                    ;
                }
            }
            try { v = new JavaScriptObject(Convert.ToDouble(c.Substring(c.index, index - c.index))); }
            catch (OverflowException) { return(ParseResult.NUMBER_TOO_BIG); }
            c.index = index;
            return(ParseResult.OK);
        }
Ejemplo n.º 21
0
        public override void Use(Player p, string message, CommandData data)
        {
            if (message.Length == 0)
            {
                if (p.IsSuper)
                {
                    SuperRequiresArgs(p, "player name or IP"); return;
                }
                message = p.name;
            }

            string name, ip = ModActionCmd.FindIP(p, message, "Location", out name);

            if (ip == null)
            {
                return;
            }

            if (HttpUtil.IsPrivateIP(ip))
            {
                p.Message("%WPlayer has an internal IP, cannot trace"); return;
            }

            JsonContext ctx = new JsonContext();

            using (WebClient client = HttpUtil.CreateWebClient())
            {
                ctx.Val = client.DownloadString("http://geoip.pw/api/" + ip);
            }

            JsonObject obj  = (JsonObject)Json.ParseStream(ctx);
            GeoInfo    info = new GeoInfo();

            if (obj == null || !ctx.Success)
            {
                p.Message("%WError parsing GeoIP info"); return;
            }

            if (elems == null)
            {
                elems = ConfigElement.GetAll(typeof(GeoInfo));
            }
            obj.Deserialise(elems, info);

            string target = name == null ? ip : "of " + PlayerInfo.GetColoredName(p, name);

            p.Message("The IP {0} %Shas been traced to: ", target);
            p.Message("  Continent: &f{1}&S ({0})", info.continent_abbr, info.continent);
            p.Message("  Country: &f{1}&S ({0})", info.country_abbr, info.country);
            p.Message("  Region/State: &f{0}", info.subdivision);
            p.Message("  City: &f{0}", info.city);
            p.Message("  Time Zone: &f{0}", info.timezone);
            p.Message("  Hostname: &f{0}", info.host);
            p.Message("  Is using proxy: &f{0}", info.proxy);
            p.Message("Geoip information by: &9http://geoip.pw/");
        }
Ejemplo n.º 22
0
        public void Init()
        {
            rootPath = Path.Combine(UnityEngine.Application.persistentDataPath, DB_FOLDER);
            json     = new JsonContext();

            new FileInfo(Path.Combine(rootPath, COLLECTION_MIDIS, "test")).Directory.Create();
            new FileInfo(Path.Combine(rootPath, COLLECTION_SONGS, "test")).Directory.Create();
            new FileInfo(Path.Combine(rootPath, COLLECTION_ALBUMS, "test")).Directory.Create();
            new FileInfo(Path.Combine(rootPath, COLLECTION_PERSONS, "test")).Directory.Create();
        }
 public void OneTimeTearDown()
 {
     using (FiguresContext context = new FiguresContext())
         context.Database.EnsureDeleted();
     using (JsonContext context = new JsonContext())
         context.Database.EnsureDeleted();
     using (WorldContext context = new WorldContext())
         context.Database.EnsureDeleted();
     context.Database.EnsureDeleted();
 }
Ejemplo n.º 24
0
 protected Parser(JsonContext context, Itemizer itemizer)
 {
     this.context               = context;
     this.itemizer              = itemizer;
     this.keyCache              = new Dictionary <Key, Key>(Constants.BufferSize, KeyComparer.Instance);
     this.parseKeys             = new BufferBank <Key>();
     this.parseValues           = new BufferBank <JsonValue>();
     this.values                = new Dictionary <ValueData, JsonValue>(Constants.BufferSize, ValueDataComparer.Instance);
     this.emptyValuesArray      = new ValueList(Parser.EmptyValues, this.context);
     this.emptyValuesDictionary = new ValueList(Parser.EmptyKeys, Parser.EmptyValues, this.context);
     this.context.InvalidValue  = new JsonValue(new ValueData(default, this.emptyValuesArray));
Ejemplo n.º 25
0
        private static async Task <List <Items> > GetListOfItems(IEnumerable <int> itemIds)
        {
            var items = new List <Items>();

            foreach (var itemId in itemIds)
            {
                items.Add(await JsonContext.GetAsync <Items>($"https://hacker-news.firebaseio.com/v0/item/{itemId}.json"));
            }

            return(items);
        }
Ejemplo n.º 26
0
        public static BlockDefinition[] Load(string path)
        {
            BlockDefinition[] defs = new BlockDefinition[Block.ExtendedCount];
            if (!File.Exists(path))
            {
                return(defs);
            }
            if (elems == null)
            {
                elems = ConfigElement.GetAll(typeof(BlockDefinition));
            }

            try {
                JsonContext ctx = new JsonContext();
                ctx.Val = File.ReadAllText(path);
                JsonArray array = (JsonArray)Json.ParseStream(ctx);
                if (array == null)
                {
                    return(defs);
                }

                foreach (object raw in array)
                {
                    JsonObject obj = (JsonObject)raw;
                    if (obj == null)
                    {
                        continue;
                    }

                    BlockDefinition def = new BlockDefinition();
                    obj.Deserialise(elems, def);
                    if (String.IsNullOrEmpty(def.Name))
                    {
                        continue;
                    }

                    BlockID block = def.GetBlock();
                    if (block >= defs.Length)
                    {
                        Logger.Log(LogType.Warning, "Invalid block ID: " + def.RawID);
                    }
                    else
                    {
                        defs[block] = def;
                    }

                    // In case user manually edited fallback in the json file
                    def.FallBack = Math.Min(def.FallBack, Block.CpeMaxBlock);
                }
            } catch (Exception ex) {
                Logger.LogError("Error Loading block defs from " + path, ex);
            }
            return(defs);
        }
Ejemplo n.º 27
0
        static void Main(string[] args)
        {
            MemberView       memberView       = new MemberView();
            IDbContext       context          = new JsonContext();
            Repository       repository       = new Repository(context);
            BoatController   boatController   = new BoatController(new BoatView(), repository);
            MemberController memberController = new MemberController(new MemberView(), repository);
            MainController   mainController   = new MainController(boatController, memberController);


            mainController.DisplayMainNav();
        }
Ejemplo n.º 28
0
        public JsonController(JsonContext context)
        {
            _context = context;

            if (_context.JsonItems.Count() == 0)
            {
                _context.JsonItems.Add(new JsonItem {
                    Data = "[value1]"
                });
                _context.SaveChanges();
            }
        }
Ejemplo n.º 29
0
        public static BlockDefinition[] Load(bool global, string mapName)
        {
            BlockDefinition[] defs = new BlockDefinition[Block.ExtendedCount];
            string            path = global ? GlobalPath : "blockdefs/lvl_" + mapName + ".json";

            if (!File.Exists(path))
            {
                return(defs);
            }
            if (elems == null)
            {
                elems = ConfigElement.GetAll(typeof(BlockDefinition));
            }

            try {
                JsonContext ctx = new JsonContext();
                ctx.Val = File.ReadAllText(path);
                JsonArray array = (JsonArray)Json.ParseStream(ctx);
                if (array == null)
                {
                    return(defs);
                }

                foreach (object raw in array)
                {
                    JsonObject obj = (JsonObject)raw;
                    if (obj == null)
                    {
                        continue;
                    }

                    BlockDefinition def = new BlockDefinition();
                    obj.Deserialise(elems, def);
                    if (String.IsNullOrEmpty(def.Name))
                    {
                        continue;
                    }

                    BlockID block = def.GetBlock();
                    if (block >= defs.Length)
                    {
                        Logger.Log(LogType.Warning, "Invalid block ID: " + def.RawID);
                    }
                    else
                    {
                        defs[block] = def;
                    }
                }
            } catch (Exception ex) {
                Logger.LogError("Error Loading block defs from " + path, ex);
            }
            return(defs);
        }
        public void JsonDataTest()
        {
            if (!TestUtils.IsAtLeast(5, 7, 0))
            {
                Assert.Ignore();
            }

            using (JsonContext context = new JsonContext())
            {
                var model = context.Model;
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();

                using (MySqlConnection conn = (MySqlConnection)context.Database.GetDbConnection())
                {
                    conn.Open();
                    MySqlCommand cmd = new MySqlCommand("SHOW CREATE TABLE JsonEntity", conn);
                    string       jsonTableDesc;
                    using (MySqlDataReader reader = cmd.ExecuteReader())
                    {
                        reader.Read();
                        jsonTableDesc = reader.GetString(1);
                    }
                    string charset       = "latin1";
                    string smallintWidth = "(6)";
                    if (conn.driver.Version.isAtLeast(8, 0, 1))
                    {
                        charset       = "utf8mb4";
                        smallintWidth = string.Empty;
                    }
                    //Adding "COLLATION" to the string validation at table creation (this happens since MySql 8.0.5 Server)
                    if (jsonTableDesc.Contains("COLLATE=utf8mb4_0900_ai_ci"))
                    {
                        StringAssert.AreEqualIgnoringCase($"CREATE TABLE `jsonentity` (\n  `Id` smallint{smallintWidth} NOT NULL AUTO_INCREMENT," +
                                                          $"\n  `jsoncol` json DEFAULT NULL,\n  PRIMARY KEY (`Id`)\n) ENGINE=InnoDB DEFAULT CHARSET={charset} COLLATE=utf8mb4_0900_ai_ci", jsonTableDesc);
                    }
                    else
                    {
                        StringAssert.AreEqualIgnoringCase($"CREATE TABLE `jsonentity` (\n  `Id` smallint{smallintWidth} NOT NULL AUTO_INCREMENT,\n  `jsoncol` json DEFAULT NULL,\n  PRIMARY KEY (`Id`)\n) " +
                                                          $"ENGINE=InnoDB DEFAULT CHARSET={charset}", jsonTableDesc);
                    }
                }

                context.JsonEntity.Add(new JsonData()
                {
                    jsoncol = "{ \"name\": \"Ronald\", \"city\": \"Austin\" }"
                });
                context.SaveChanges();
                JsonData json = context.JsonEntity.First();
                Assert.AreEqual("{ \"name\": \"Ronald\", \"city\": \"Austin\" }", json.jsoncol);
            }
        }
Ejemplo n.º 31
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var context = new JsonContext(Application.StartupPath);

            var appController = new ApplicationController(context);
            var view          = new ViewMain();
            var presenter     = new ViewMainPresenter(view, appController);

            presenter.Run();
        }
Ejemplo n.º 32
0
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
      if (reader.TokenType != JsonToken.Null) {
        // Load JObject from stream
        var jObject = JObject.Load(reader);

        var jsonContext = new JsonContext { JObject = jObject, ObjectType = objectType, Serializer = serializer };
        // Create target object based on JObject
        var target = CreateAndPopulate( jsonContext);
        return target;
      } else {
        return null;
      }
    }
        public static void ProductsInRange(JsonContext context)
        {
            var productsByRange = context.Products
                .Where(p => (p.Price >= 500 && p.Price <= 1000) && p.BuyerId == null)
                .Select(u => new
                {
                    name = u.Name,
                    price = u.Price,
                    seller = u.Seller.FirstName + " " + u.Seller.LastName
                });

            var serializer = new JavaScriptSerializer();
            var digitsInJson = serializer.Serialize(productsByRange);
            Console.WriteLine(digitsInJson);

            System.IO.File.WriteAllText(@"E:\SoftUni\Database Applications\7.1. Processing-JSON-in-.NET-Homework/products-in-range.json", digitsInJson);
        }
Ejemplo n.º 34
0
    protected virtual Object PopulateEntity(JsonContext jsonContext, IEntity entity) {
      
      var aspect = entity.EntityAspect;
      if (aspect.EntityManager == null) {
        // new to this entityManager
        ParseObject(jsonContext, aspect);
        _entityManager.AttachQueriedEntity(entity, (EntityType) jsonContext.StructuralType);
      } else if (_mergeStrategy == MergeStrategy.OverwriteChanges || aspect.EntityState == EntityState.Unchanged) {
        // overwrite existing entityManager
        ParseObject(jsonContext, aspect);
      } else {
        // preserveChanges handling - we still want to handle expands.
        ParseObject(jsonContext, null );
      }

      return entity;
    }
Ejemplo n.º 35
0
    protected virtual Object CreateAndPopulate(JsonContext jsonContext) {
      var jObject = jsonContext.JObject;

      JToken refToken = null;
      if (jObject.TryGetValue("$ref", out refToken)) {
        return _refMap[refToken.Value<String>()];
      }

      EntityType entityType;
      Type objectType;
      JToken typeToken = null;
      if (jObject.TryGetValue("$type", out typeToken)) {
        var clrTypeName = typeToken.Value<String>();
        var entityTypeName = StructuralType.ClrTypeNameToStructuralTypeName(clrTypeName);
        entityType = _metadataStore.GetEntityType(entityTypeName);
        objectType = entityType.ClrType;
        if (!jsonContext.ObjectType.IsAssignableFrom(objectType)) {
          throw new Exception("Unable to convert returned type: " + objectType.Name + " into type: " + jsonContext.ObjectType.Name);
        }
        jsonContext.ObjectType = objectType;
      } else {
        objectType = jsonContext.ObjectType;
        entityType =  _metadataStore.GetEntityType(objectType);
      }

      // an entity type
      jsonContext.StructuralType = entityType;
      var keyValues = entityType.KeyProperties
        .Select(p => jObject[p.Name].ToObject(p.ClrType))
        .ToArray();
      var entityKey = EntityKey.Create(entityType, keyValues);
      var entity = _entityManager.FindEntityByKey(entityKey);
      if (entity == null) {
        entity = (IEntity)Activator.CreateInstance(objectType);
      }
      // must be called before populate
      UpdateRefMap(jObject, entity);
      _allEntities.Add(entity);
      return PopulateEntity(jsonContext, entity);

    }
Ejemplo n.º 36
0
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
      if (reader.TokenType != JsonToken.Null) {
        // Load JObject from stream
        var jObject = JObject.Load(reader);

        if (objectType == typeof(IEntity)) {
          JToken typeNameToken;
          if (jObject.TryGetValue("$type", out typeNameToken)) {
            if (_normalizeTypeNameFn == null) {
              throw new Exception("NormalizeTypeNameFn not defined");
            }
            var entityTypeName = _normalizeTypeNameFn(typeNameToken.Value<String>());
            objectType = MetadataStore.Instance.GetEntityType(entityTypeName).ClrType;
          }
        }

        var jsonContext = new JsonContext { JObject = jObject, ObjectType = objectType, Serializer = serializer };
        // Create target object based on JObject
        var target = CreateAndPopulate( jsonContext);
        return target;
      } else {
        return null;
      }
    }
        static void Main()
        {
            var context = new JsonContext();

            GetProducts.ProductsInRange(context);
        }
Ejemplo n.º 38
0
	public JsonContext json() {
		JsonContext _localctx = new JsonContext(Context, State);
		EnterRule(_localctx, 0, RULE_json);
		int _la;
		try {
			EnterOuterAlt(_localctx, 1);
			{
			State = 52; pair();
			State = 57;
			ErrorHandler.Sync(this);
			_la = TokenStream.La(1);
			while (_la==Comma) {
				{
				{
				State = 53; Match(Comma);
				State = 54; pair();
				}
				}
				State = 59;
				ErrorHandler.Sync(this);
				_la = TokenStream.La(1);
			}
			}
		}
		catch (RecognitionException re) {
			_localctx.exception = re;
			ErrorHandler.ReportError(this, re);
			ErrorHandler.Recover(this, re);
		}
		finally {
			ExitRule();
		}
		return _localctx;
	}
Ejemplo n.º 39
0
        void FetchJSON(HttpsRequest request, Action<JsonValue> completion, Action<Exception> errorHandler, CancellationToken token)
        {
            var op = System.ComponentModel.AsyncOperationManager.CreateOperation(null);

            request.UserAgent = "FlashcardsWP7/0.1 (" + Environment.OSVersion + "; .NET " + Environment.Version + ")";

            try {
                token.Register(delegate { throw new OperationCanceledException(); });

                ThreadPool.QueueUserWorkItem(
                    _ => {
                        Exception error;
                        try {
                            var client = new HttpsClient(Host.Host, Host.Port, Configuration.VerifyCertificates);
                            var response = client.MakeRequest(request);

                            var text = response.DecodeTextBody();

                            if (response.StatusCode == 204) {
                                op.PostOperationCompleted(delegate { completion(null); }, null);
                                return;
                            }

                            var json = JsonValue.Parse(new StringReader(text));

                            if (response.StatusCode / 100 != 2) {
                                var dict = (JsonDictionary) json;
                                var errorCode = new JsonContext().FromJson<string>(dict.Items["error"]);
                                var errorText = new JsonContext().FromJson<string>(dict.Items["error_description"]);
                                if (errorCode != null && errorText != null) {
                                    // TODO: find error code for needing password
                                    if (errorCode == "invalid_access")
                                        throw new AccessDeniedException(errorText);
                                    if (errorCode == "item_not_found")
                                        throw new ItemNotFoundException(errorText);
                                    if (errorCode == "item_deleted")
                                        throw new ItemDeletedException(errorText);
                                    throw new QuizletException(errorText);
                                }
                                throw new QuizletException("The Quizlet request failed (HTTP error " + response.StatusCode.ToString(CultureInfo.InvariantCulture) + ").");
                            }

                            op.PostOperationCompleted(delegate { completion(json); }, null);
                            return;
                        }
                        catch (QuizletException e) {
                            error = e;
                        }
                        catch (OperationCanceledException e) {
                            error = e;
                        }
                        catch (HttpException e) {
                            error = e;
                        }
                        catch (System.Net.Sockets.SocketException e) {
                            error = e;
                        }
                        catch (IOException e) {
                            error = e;
                        }
                        catch (ArgumentException e) {
                            error = e;
                        }
                        catch (InvalidOperationException e) {
                            error = e;
                        }
                        catch (NotSupportedException e) {
                            error = e;
                        }
                        catch (FormatException e) {
                            error = new QuizletException("The Quizlet server returned an invalid document.", e);
                        }
                        catch (JsonConvertException e) {
                            error = new QuizletException("The Quizlet server returned an invalid document.", e);
                        }
                        catch (InvalidCastException e) {
                            error = new QuizletException("The Quizlet server returned an invalid document.", e);
                        }
                        catch (KeyNotFoundException e) {
                            error = new QuizletException("The Quizlet server returned an invalid document.", e);
                        }

                        op.PostOperationCompleted(delegate { errorHandler(error); }, null);
                    });
            } catch (OperationCanceledException e) {
                errorHandler(e);
            }
        }
Ejemplo n.º 40
0
        /// <summary>
        /// Takes an OAuth code and turns it into an API token.
        /// </summary>
        /// <param name="code">A code returned from the OAuth page (https://quizlet.com/authorize/)</param>
        /// <param name="success">A delegate to be called when the authentication succeeds.</param>
        /// <param name="failure">What to do when the authentication fails.</param>
        /// <param name="token">A CancellationToken, which is currently useless.</param>
        public void Authenticate(string code, Action success, Action<Exception> failure, CancellationToken token)
        {
            var fields = "grant_type=authorization_code&code=" + code + "&redirect_uri=https://q.asztal.net/";

            var req = new HttpsRequest("POST", "/oauth/token");
            req.BasicAuthorization(ClientID, SecretKey);

            req.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            req.PostData = Encoding.UTF8.GetBytes(fields);

            FetchJSON(req,
            json => {
                try {
                    if (json is JsonDictionary) {
                        var ctx = new JsonContext();

                        var accessToken = ctx.FromJson<string>((json as JsonDictionary).Items["access_token"]);
                        var userName = ctx.FromJson<string>((json as JsonDictionary).Items["user_id"]);
                        var tokenExpiry = DateTime.Now.AddSeconds(ctx.FromJson<double>((json as JsonDictionary).Items["expires_in"]));
                        Credentials = new Credentials(accessToken, userName, tokenExpiry);

                        success();
                    } else {
                        failure(new FormatException("Quizlet server returned an invalid response."));
                    }
                } catch (KeyNotFoundException) {
                    failure(new FormatException("Quizlet server returned an invalid response."));
                } catch (JsonConvertException) {
                    failure(new FormatException("Quizlet server returned an invalid response."));
                }
            },
            failure,
            token);
        }
Ejemplo n.º 41
0
 public void GetSetInfo(long setID, Action<SetInfo> completion, Action<Exception> errorHandler, CancellationToken token)
 {
     FetchJSON(
         new HttpsRequest("GET", "/2.0/sets/" + setID.ToString(CultureInfo.InvariantCulture) + "?client_id=" + Uri.EscapeDataString(ClientID)),
         json => {
             try {
                 var set = new JsonContext().FromJson<SetInfo>(json);
                 completion(set);
             }
             catch (JsonConvertException e) {
                 errorHandler(e);
             }
         },
         errorHandler,
         token);
 }
Ejemplo n.º 42
0
        public void SearchSets(string query, bool searchTerms, Action<List<SetInfo>> completion, Action<Exception> errorHandler, CancellationToken token)
        {
            var req = new HttpsRequest("GET", "/2.0/search/sets?sort=most_studied&" + (searchTerms ? "term=" : "q=") + Uri.EscapeDataString(query));

            AuthorizeRequest(req, false);

            FetchJSON(
                req,
                json => {
                    try {
                        var sets = new JsonContext().FromJson<List<SetInfo>>(((JsonDictionary)json).Items["sets"]);
                        completion(sets);
                    } catch (JsonConvertException e) {
                        errorHandler(e);
                    }
                },
                errorHandler,
                token);
        }
Ejemplo n.º 43
0
        public void FetchUserGroups(string userName, Action<List<GroupInfo>> completion, Action<Exception> errorHandler, CancellationToken token)
        {
            var req = new HttpsRequest("GET", string.Format(CultureInfo.InvariantCulture, "/2.0/users/{0}/groups", Uri.EscapeUriString(userName)));

            AuthorizeRequest(req, false);

            FetchJSON(
                req,
                json => {
                    try {
                        var groups = new JsonContext { RelaxedNumericConversion = true }.FromJson<List<GroupInfo>>(json);
                        completion(groups);
                    } catch (JsonConvertException e) {
                        errorHandler(e);
                    }
                },
                errorHandler,
                token);
        }
Ejemplo n.º 44
0
        public void FetchUserSets(string userName, Action<List<SetInfo>> completion, Action<Exception> errorHandler, CancellationToken token)
        {
            var req = new HttpsRequest("GET", "/2.0/users/" + Uri.EscapeUriString(userName) + "/sets");

            AuthorizeRequest(req, true);

            FetchJSON(
                req,
                json => {
                    try {
                        var sets = new JsonContext().FromJson<List<SetInfo>>(json);
                        completion(sets);
                    } catch (JsonConvertException e) {
                        errorHandler(e);
                    }
                },
                errorHandler,
                token);
        }
Ejemplo n.º 45
0
        public void CreateSet(SetInfo si, string password, IEnumerable<long> groupIDs, Action<long, Uri> completion, Action<Exception> errorHandler, CancellationToken token)
        {
            var req = new HttpsRequest("POST", "/2.0/sets");

            var postData = new MemoryStream();
            using (var writer = new StreamWriter(postData))
                WriteSetInfo(si, writer, password, si.Visibility, si.Editable, groupIDs);

            req.ContentType = "application/x-www-form-urlencoded";
            req.PostData = postData.ToArray();
            AuthorizeRequest(req, true);

            FetchJSON(
                req,
                json => {
                    try {
                        if (!(json is JsonDictionary))
                            throw new JsonConvertException("Expected a JSON dictionary");

                        var ctx = new JsonContext();
                        var dict = (json as JsonDictionary).Items;
                        var uri = new Uri(ctx.FromJson<string>(dict["url"]));
                        var id = ctx.FromJson<long>(dict["set_id"]);

                        completion(id, uri);
                    } catch (JsonConvertException err) {
                        errorHandler(err);
                    } catch (KeyNotFoundException err) {
                        errorHandler(new QuizletException("Invalid response from server", err));
                    }
                },
                errorHandler,
                token);
        }
Ejemplo n.º 46
0
    protected virtual Object PopulateEntity(JsonContext jsonContext, IEntity entity) {
      
      var aspect = entity.EntityAspect;
      if (aspect.EntityManager == null) {
        // new to this entityManager
        ParseObject(jsonContext, aspect);
        aspect.Entity.Initialize();
        // TODO: This is a nit.  Wierd case where a save adds a new entity will show up with
        // a AttachOnQuery operation instead of AttachOnSave
        _entityManager.AttachQueriedEntity(entity, (EntityType) jsonContext.StructuralType);
      } else if (_mergeStrategy == MergeStrategy.OverwriteChanges || aspect.EntityState == EntityState.Unchanged) {
        // overwrite existing entityManager
        ParseObject(jsonContext, aspect);
        aspect.OnEntityChanged(_loadingOperation == LoadingOperation.Query ? EntityAction.MergeOnQuery : EntityAction.MergeOnSave);
      } else {
        // preserveChanges handling - we still want to handle expands.
        ParseObject(jsonContext, null );
      }

      return entity;
    }
Ejemplo n.º 47
0
        public async Task<Credentials> Authenticate(string code, CancellationToken cancel, IProgress<ProgressChangedEventArgs> progress = null) {
            var fields = new Dictionary<string, string>();
            fields["grant_type"] = "authorization_code";
            fields["code"] = code;
            fields["redirect_uri"] = "flashcards://complete-oauth";

            var basicAuth = new KeyValuePair<string, string>(clientID, secretKey);

            var json = await Fetch(new Uri("/oauth/token", UriKind.Relative), RequestType.Post, false, cancel, progress, fields, basicAuth);
            var dict = JsonDictionary.FromValue(json);
            var ctx = new JsonContext();
            
            // TODO Should probably check token_type and scope properties to check we have the right type of token!
            return new Credentials(
                ctx.FromJson<string>(dict["user_id"]),
                DateTime.UtcNow.AddSeconds(ctx.FromJson<double>(dict["expires_in"])),
                ctx.FromJson<string>(dict["access_token"]));
        }
Ejemplo n.º 48
0
 private void ParseObject(JsonContext jsonContext, EntityAspect targetAspect) {
   // backingStore will be null if not allowed to overwrite the entity.
   var backingStore = (targetAspect == null) ? null : targetAspect.BackingStore;
   var dict = (IDictionary<String, JToken>) jsonContext.JObject;
   var structuralType = jsonContext.StructuralType;
   dict.ForEach(kvp => {
     var key = kvp.Key;
     var prop = structuralType.GetProperty(key);
     if (prop != null) {         
       if (prop.IsDataProperty) {
         if (backingStore != null) {
           var dp = (DataProperty)prop;
           if (dp.IsComplexProperty) {
             var newCo = (IComplexObject) kvp.Value.ToObject(dp.ClrType);
             var co = (IComplexObject)backingStore[key];
             var coBacking = co.ComplexAspect.BackingStore;
             newCo.ComplexAspect.BackingStore.ForEach(kvp2 => {
               coBacking[kvp2.Key] = kvp2.Value;
             });
           } else {
             backingStore[key] = kvp.Value.ToObject(dp.ClrType);
           }
         }
       } else {
         // prop is a ComplexObject
         var np = (NavigationProperty)prop;
         
         if (kvp.Value.HasValues) {
           JsonContext newContext;
           if (np.IsScalar) {
             var nestedOb = (JObject)kvp.Value;
             newContext = new JsonContext() { JObject = nestedOb, ObjectType = prop.ClrType, Serializer = jsonContext.Serializer }; 
             var entity = (IEntity)CreateAndPopulate(newContext);
             if (backingStore != null) backingStore[key] = entity;
           } else {
             var nestedArray = (JArray)kvp.Value;
             var navSet = (INavigationSet) TypeFns.CreateGenericInstance(typeof(NavigationSet<>), prop.ClrType);
             
             nestedArray.Cast<JObject>().ForEach(jo => {
               newContext = new JsonContext() { JObject=jo, ObjectType = prop.ClrType, Serializer = jsonContext.Serializer };
               var entity = (IEntity)CreateAndPopulate(newContext);
               navSet.Add(entity);
             });
             // add to existing nav set if there is one otherwise just set it. 
             object tmp;
             if (backingStore.TryGetValue(key, out tmp)) {
               var backingNavSet = (INavigationSet) tmp;
               navSet.Cast<IEntity>().ForEach(e => backingNavSet.Add(e));
             } else {
               navSet.NavigationProperty = np;
               navSet.ParentEntity = targetAspect.Entity;
               backingStore[key] = navSet;
             }
           }
         } else {
           // do nothing
           //if (!np.IsScalar) {
           //  return TypeFns.ConstructGenericInstance(typeof(NavigationSet<>), prop.ClrType);
           //} else {
           //  return null;
           //}
         }
       }
     } else {
       if (backingStore != null) backingStore[key] = kvp.Value.ToObject<Object>();
     }
   });
   
 }
Ejemplo n.º 49
0
        protected async Task<JsonValue> Fetch(
            Uri endPoint, 
            RequestType requestType, 
            bool needsToken, 
            CancellationToken cancel, 
            IProgress<ProgressChangedEventArgs> progress = null, 
            IDictionary<string, string> postData = null,
            KeyValuePair<string,string>? overrideAuth = null)
        {
            
            if (endPoint == null)
                throw new ArgumentNullException("endPoint");
            
            var wc = new WebClient();
            if (needsToken && !Credentials.HasValue)
                throw new InvalidOperationException("Cannot access this part of the Quizlet service without logging in.");

            wc.Headers["User-Agent"] = "FlashcardsWP8/0.1 (" + Environment.OSVersion + "; .NET " + Environment.Version + ")";

            // Overriding is used for basic authentication for OAuth process.
            bool useClientID = false;
            if (overrideAuth != null)
                wc.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(overrideAuth.Value.Key + ":" + overrideAuth.Value.Value));
            else if (Credentials != null)
                wc.Headers["Authorization"] = "Bearer " + Credentials.Value.ApiToken;
            else
                useClientID = true;

			try {
                string result;
                if (requestType == RequestType.Get) {
                    var uri = new Uri(ServiceUri, endPoint);
                    uri = new Uri(uri + (uri.Query == "" ? "?" : "&") + "client_id=" + clientID);
				    result = await wc.DownloadStringAsTask(uri, cancel, progress);
                } else {
                    var sb = new StringBuilder();
                    wc.Headers["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
                    wc.Encoding = Encoding.UTF8;
                    if (postData != null) {
                        if (useClientID)
                            postData["client_id"] = clientID;
                        foreach (var kvp in postData) {
                            if (sb.Length > 0)
                                sb.Append('&');
                            sb.Append(kvp.Key).Append('=').Append(Uri.EscapeDataString(kvp.Value));
                        }
                    }

                    result = await wc.UploadStringAsTask(new Uri(ServiceUri, endPoint), requestType.ToString().ToUpperInvariant(), sb.ToString(), cancel, progress);
                }

				JsonValue json = null;

                // In case of HTTP status 204 (no content). This is produced, for example, as the result of 
                // a DELETE call to an endpoint.
				if (!string.IsNullOrWhiteSpace(result))
					json = JsonValue.Parse(new StringReader(result));

				return json;
            } catch (WebException e) {
				// The Quizlet API returns a JSON document explaining the error if there is one,
                // so try to use that if possible.

				try {
                    if (e.Response != null) {
                        var response = (e.Response as HttpWebResponse).GetResponseStream();
                        using (var reader = new StreamReader(response)) {
                            var dict = JsonDictionary.FromValue(JsonValue.Parse(reader));
                            var ctx = new JsonContext();
                            var errorCode = ctx.FromJson<string>(dict["error"]);
                            var errorText = ctx.FromJson<string>(dict["error_description"]);

                            if (errorCode != null && errorText != null) {
                                switch (errorCode) {
                                    case "invalid_access": throw new AccessDeniedException(errorText);
                                    case "item_not_found": throw new ItemNotFoundException(errorText);
                                    case "item_deleted": throw new ItemDeletedException(errorText);
                                    default: throw new QuizletException(errorText);
                                }
                            }
                        }
                    }

                    throw new QuizletException(string.Format("Unable to contact the Quizlet server ({0}).", e.Message), e);
                } catch (FormatException) {
					// Not JSON or invalid - just wrap the original exception
					throw new QuizletException(e.Message, e);
                } catch (KeyNotFoundException) {
					throw new QuizletException(e.Message, e);
                }
            }
        }