Exemple #1
0
      public void Rowset_FromJSON_FieldMissed(bool rowsAsMap)
      {
        var row = new Person { Name = "Henry", Age = 43 };
        var rowSet = new Rowset(row.Schema);
        rowSet.Add(row);
        var options = new NFX.Serialization.JSON.JSONWritingOptions
                          {
                            RowsetMetadata = true,
                            RowsAsMap = rowsAsMap 
                          };
        var json = rowSet.ToJSON(options);
        var map = JSONReader.DeserializeDataObject( json ) as JSONDataMap;
        var rows = (map["Rows"] as IList<object>);
        if (rowsAsMap)
        {
          var pers = rows[0] as IDictionary<string, object>;
          pers.Remove("Age");
        }
        else
        {
          var pers = rows[0] as IList<object>;
          pers.RemoveAt(1);
        }

        bool allMatched;
        var trg = RowsetBase.FromJSON(map, out allMatched);

        Assert.IsFalse(allMatched);
        var trgRow = trg[0];
        Assert.AreEqual(trgRow.Schema.FieldCount, 2);
        Assert.AreEqual(trgRow["Name"], "Henry");
        Assert.IsNull(trgRow["Age"]);
      }
Exemple #2
0
        /// <summary>
        /// This method is called only once as it touches the input streams
        /// </summary>
        protected virtual JSONDataMap ParseRequestBodyAsJSONDataMap()
        {
            if (!Request.HasEntityBody)
            {
                return(null);
            }

            JSONDataMap result = null;

            var ctp = Request.ContentType;

            //Multipart
            if (ctp.IndexOf(ContentType.FORM_MULTIPART_ENCODED) >= 0)
            {
                var boundary = Multipart.ParseContentType(ctp);
                var mp       = Multipart.ReadFromStream(Request.InputStream, ref boundary, Request.ContentEncoding);
                result = mp.ToJSONDataMap();
            }
            else //Form URL encoded
            if (ctp.IndexOf(ContentType.FORM_URL_ENCODED) >= 0)
            {
                result = JSONDataMap.FromURLEncodedStream(new NFX.IO.NonClosingStreamWrap(Request.InputStream),
                                                          Request.ContentEncoding);
            }
            else//JSON
            if (ctp.IndexOf(ContentType.JSON) >= 0)
            {
                result = JSONReader.DeserializeDataObject(new NFX.IO.NonClosingStreamWrap(Request.InputStream),
                                                          Request.ContentEncoding) as JSONDataMap;
            }

            return(result);
        }
Exemple #3
0
        private void jsonMapAndPrimitives(string actionName)
        {
            var initialMap = new JSONDataMap();

            initialMap["ID"]   = 100;
            initialMap["Name"] = "Initial Name";
            var str = initialMap.ToJSON(JSONWritingOptions.CompactRowsAsMap);

            var values = new NameValueCollection();

            values.Add("n", "777");
            values.Add("s", "sss");

            using (var wc = CreateWebClient())
            {
                wc.QueryString = values;
                wc.Headers[HttpRequestHeader.ContentType] = NFX.Web.ContentType.JSON;
                var res = wc.UploadString(INTEGRATION_HTTP_ADDR + actionName, str);

                var gotMap = JSONReader.DeserializeDataObject(res) as JSONDataMap;

                Assert.AreEqual(gotMap["ID"], 777);
                Assert.AreEqual(gotMap["Name"], "sss");
            }
        }
Exemple #4
0
        private void rowAndPrimitive(string actionName)
        {
            var initalRow = new TestRow()
            {
                ID = 0, Name = "Name"
            };
            var str = initalRow.ToJSON(JSONWritingOptions.CompactRowsAsMap);

            var values = new NameValueCollection();

            values.Add("n", "777");
            values.Add("s", "sss");

            using (var wc = CreateWebClient())
            {
                wc.QueryString = values;
                wc.Headers[HttpRequestHeader.ContentType] = NFX.Web.ContentType.JSON;
                var res = wc.UploadString(INTEGRATION_HTTP_ADDR + actionName, str);

                var map    = JSONReader.DeserializeDataObject(res) as JSONDataMap;
                var gotRow = JSONReader.ToRow <TestRow>(map);

                Assert.AreEqual(gotRow.ID, 777);
                Assert.AreEqual(gotRow.Name, "sss");
            }
        }
Exemple #5
0
        /// <summary>
        /// Converts request into JSONDataMap
        /// </summary>
        protected JSONDataMap GetRequestAsJSONDataMap(WorkContext work)
        {
            if (!work.Request.HasEntityBody)
            {
                return(work.MatchedVars);
            }

            JSONDataMap result = null;

            var ctp = work.Request.ContentType;

            //Multipart
            if (ctp.IndexOf(ContentType.FORM_MULTIPART_ENCODED) >= 0)
            {
                result = MultiPartContent.ToJSONDataMap(work.Request.InputStream, ctp, work.Request.ContentEncoding);
            }
            else //Form URL encoded
            if (ctp.IndexOf(ContentType.FORM_URL_ENCODED) >= 0)
            {
                result = JSONDataMap.FromURLEncodedStream(new NFX.IO.NonClosingStreamWrap(work.Request.InputStream),
                                                          work.Request.ContentEncoding);
            }
            else//JSON
            if (ctp.IndexOf(ContentType.JSON) >= 0)
            {
                result = JSONReader.DeserializeDataObject(new NFX.IO.NonClosingStreamWrap(work.Request.InputStream),
                                                          work.Request.ContentEncoding) as JSONDataMap;
            }

            return(result == null ? work.MatchedVars : result.Append(work.MatchedVars));
        }
Exemple #6
0
        public Record(string init) : base()
        {
            if (init.IsNullOrWhiteSpace())
            {
                throw new WaveException(StringConsts.ARGUMENT_ERROR + "Record.ctor(init==null|empty)");
            }

            JSONDataMap initMap = null;

            try
            {
                initMap = JSONReader.DeserializeDataObject(init) as JSONDataMap;
            }
            catch (Exception error)
            {
                throw new WaveException(StringConsts.ARGUMENT_ERROR + "Record.ctor(init is bad): " + error.ToMessageWithType(), error);
            }

            if (initMap == null)
            {
                throw new WaveException(StringConsts.ARGUMENT_ERROR + "Record.ctor(init isnot map)");
            }

            ctor(initMap);
        }
        public void Rowset_FromJSON_DefMissed(bool rowsAsMap)
        {
            var row = new Person {
                Name = "Henry", Age = 43
            };
            var rowSet = new Rowset(row.Schema);

            rowSet.Add(row);
            var options = new NFX.Serialization.JSON.JSONWritingOptions
            {
                RowsetMetadata = true,
                RowsAsMap      = rowsAsMap
            };
            var json   = rowSet.ToJSON(options);
            var map    = JSONReader.DeserializeDataObject(json) as JSONDataMap;
            var schema = (map["Schema"] as IDictionary <string, object>);
            var defs   = schema["FieldDefs"] as IList <object>;

            defs.RemoveAt(1);

            bool allMatched;
            var  trg = RowsetBase.FromJSON(map, out allMatched);

            Aver.IsFalse(allMatched);
            var trgRow = trg[0];

            Aver.AreEqual(trgRow.Schema.FieldCount, 1);
            Aver.AreObjectsEqual(trgRow["Name"], "Henry");
        }
Exemple #8
0
        public void JSONDoubleTest()
        {
            var map = JSONReader.DeserializeDataObject("{ pi: 3.14159265359, exp1: 123e4, exp2: 2e-5 }") as JSONDataMap;

            Aver.AreEqual(3, map.Count);
            Aver.AreObjectsEqual(3.14159265359D, map["pi"]);
            Aver.AreObjectsEqual(123e4D, map["exp1"]);
            Aver.AreObjectsEqual(2e-5D, map["exp2"]);
        }
Exemple #9
0
        /// <summary>
        /// Reads either Table or Rowset from JSON created by WriteAsJSON.
        /// </summary>
        /// <returns>Total number of rows found in JSON. If this number is less than
        /// result.Count, then not all rows matched the schema of the resulting rowset.</returns>
        /// <remarks>
        /// The schema of "result" must match the schema of the typed row T.
        /// It's the responsibility of the caller to clear the "result" prior to
        /// calling this function - the function appends rows to existing rowset.
        /// </remarks>
        public static int FromJSON <T>(string json,
                                       ref RowsetBase result,
                                       SetFieldFunc setFieldFunc = null)
            where T : TypedRow, new()
        {
            var map = JSONReader.DeserializeDataObject(json) as JSONDataMap;

            return(FromJSON <T>(map, ref result, setFieldFunc));
        }
Exemple #10
0
        protected override RequestMsg DoDecodeRequest(WireFrame frame, MemoryStream ms, ISerializer serializer)
        {
            var utf8 = ms.GetBuffer();
            var json = Encoding.UTF8.GetString(utf8, (int)ms.Position, (int)ms.Length - (int)ms.Position);
            var data = JSONReader.DeserializeDataObject(json) as JSONDataMap;

            if (data == null)
            {
                throw new ProtocolException(StringConsts.GLUE_BINDING_REQUEST_ERROR.Args(nameof(AppTermBinding), "data==null"));
            }

            var reqID    = new FID(data["request-id"].AsULong(handling: ConvertErrorHandling.Throw)); //kuda ego vstavit?
            var instance = data["instance"].AsNullableGUID(handling: ConvertErrorHandling.Throw);
            var oneWay   = data["one-way"].AsBool();
            var method   = data["method"].AsString();

            MethodSpec mspec;

            if (method.EqualsOrdIgnoreCase(nameof(Contracts.IRemoteTerminal.Connect)))
            {
                mspec = AppTermBinding.METHOD_CONNECT;
            }
            else if (method.EqualsOrdIgnoreCase(nameof(Contracts.IRemoteTerminal.Execute)))
            {
                mspec = AppTermBinding.METHOD_EXECUTE;
            }
            else if (method.EqualsOrdIgnoreCase(nameof(Contracts.IRemoteTerminal.Disconnect)))
            {
                mspec = AppTermBinding.METHOD_DISCONNECT;
            }
            else
            {
                throw new ProtocolException(StringConsts.GLUE_BINDING_REQUEST_ERROR.Args(nameof(AppTermBinding), "unknown method `{0}`".Args(method)));
            }

            var args = data["command"] == null ? new object[0] : new object[] { data["command"].AsString() };

            var result = new RequestAnyMsg(AppTermBinding.TYPE_CONTRACT, mspec, oneWay, instance, args);

            var autht = data["auth-token"].AsString();

            if (autht != null)
            {
                var hdr = new AuthenticationHeader(Security.SkyAuthenticationTokenSerializer.Deserialize(autht));
                result.Headers.Add(hdr);
            }
            var authc = data["auth-cred"].AsString();

            if (authc != null)
            {
                var hdr = new AuthenticationHeader(Azos.Security.IDPasswordCredentials.FromBasicAuth(authc));
                result.Headers.Add(hdr);
            }

            return(result);
        }
Exemple #11
0
        public void Action_ComplexRow(WebClient wc)
        {
            var initalRow = new TestComplexRow();

            initalRow.ID = 777;

            initalRow.Row1 = new TestRow()
            {
                ID = 101, Name = "Test Row 1", Date = DateTime.Now
            };
            initalRow.Row2 = new TestRow()
            {
                ID = 102, Name = "Test Row 2", Date = DateTime.Now
            };

            initalRow.ErrorRows = new TestRow[] {
                new TestRow()
                {
                    ID = 201, Name = "Err Row 1", Date = DateTime.Now
                },
                new TestRow()
                {
                    ID = 202, Name = "Err Row 2", Date = DateTime.Now
                },
                new TestRow()
                {
                    ID = 203, Name = "Err Row 3", Date = DateTime.Now
                }
            };

            var str = initalRow.ToJSON(JSONWritingOptions.CompactRowsAsMap);

            //using (var wc = CreateWebClient())
            {
                wc.Headers[HttpRequestHeader.ContentType] = NFX.Web.ContentType.JSON;
                var res = wc.UploadString(m_ServerURI + "ComplexRowSet", str);

                var map    = JSONReader.DeserializeDataObject(res) as JSONDataMap;
                var gotRow = JSONReader.ToRow <TestComplexRow>(map);

                if (initalRow.ID + 1 != gotRow.ID)
                {
                    throw new Exception();
                }
                if (initalRow.Row1.ID + 2 != gotRow.Row1.ID)
                {
                    throw new Exception();
                }
                if (gotRow.ErrorRows[2].Date - initalRow.ErrorRows[2].Date.AddDays(-2) >= TimeSpan.FromMilliseconds(1))
                {
                    throw new Exception();
                }
            }
        }
Exemple #12
0
        protected virtual void LoadData()
        {
            OK        = m_Init["OK"].AsNullableBool();
            ID        = m_Init["ID"].AsNullableGUID();
            ISOLang   = m_Init["ISOLang"].AsString();
            FormMode  = m_Init[FormModel.JSON_MODE_PROPERTY].AsString();
            CSRFToken = m_Init[FormModel.JSON_CSRF_PROPERTY].AsString();
            var roundtrip = m_Init[FormModel.JSON_ROUNDTRIP_PROPERTY].AsString();

            Roundtrip = roundtrip != null?JSONReader.DeserializeDataObject(roundtrip) as JSONDataMap : null;

            var error     = m_Init["error"].AsString();
            var errorText = m_Init["errorText"].AsString();

            if (error.IsNotNullOrWhiteSpace() || errorText.IsNotNullOrWhiteSpace())
            {
                m_Errors.Add(new ServerError(null, error, errorText));
            }

            var fields = m_Init["fields"] as JSONDataArray;

            if (fields != null)
            {
                foreach (var item in fields)
                {
                    var field = item as JSONDataMap;
                    if (field == null)
                    {
                        continue;
                    }

                    var def = field["def"] as JSONDataMap;
                    if (def == null)
                    {
                        continue;
                    }

                    var name = def["Name"].AsString();
                    if (name.IsNullOrWhiteSpace())
                    {
                        continue;
                    }

                    this[name] = field["val"];

                    var fError     = field["error"].AsString();
                    var fErrorText = field["errorText"].AsString();
                    if (fError.IsNotNullOrWhiteSpace() || fErrorText.IsNotNullOrWhiteSpace())
                    {
                        m_Errors.Add(new ServerError(name, fError, fErrorText));
                    }
                }
            }
        }
Exemple #13
0
        public void TypeRowConversion()
        {
            var r = new WaveTestSite.Controllers.IntegrationTester.SpanRow()
            {
                Span = TimeSpan.FromTicks(1)
            };

            var str = r.ToJSON(JSONWritingOptions.CompactRowsAsMap);

            var map    = JSONReader.DeserializeDataObject(str) as JSONDataMap;
            var gotRow = JSONReader.ToRow <WaveTestSite.Controllers.IntegrationTester.SpanRow>(map);
        }
Exemple #14
0
        public override IEnumerable <KeyValuePair <string, string> > MapGaugeDimensions(string tEntity, string dimensions)
        {
            var allDims   = DIMENSIONS[tEntity];
            var dimConfig = JSONReader.DeserializeDataObject(dimensions) as JSONDataMap;

            foreach (var kvp in dimConfig)
            {
                if (!allDims.Contains(kvp.Key))
                {
                    continue;                     // ERROR
                }
                yield return(new KeyValuePair <string, string>(kvp.Key, (string)kvp.Value));
            }
        }
Exemple #15
0
        public static AuthenticationToken Deserialize(string token)
        {
            try
            {
                var dataMap = JSONReader.DeserializeDataObject(token) as JSONDataMap;
                var realm   = dataMap["r"].AsString();
                var data    = dataMap["d"].AsString();

                return(new AuthenticationToken(realm, data));
            }
            catch (Exception error)
            {
                throw new SecurityException("AgniAuthenticationTokenSerializer can not deserialize unexpected data", error);
            }
        }
Exemple #16
0
        public void Action_RowGet_TypeRow()
        {
            DateTime start = DateTime.Now;

            using (var wc = CreateWebClient())
            {
                string str = wc.DownloadString(INTEGRATION_HTTP_ADDR + "RowGet");


                Assert.AreEqual("application/json", wc.ResponseHeaders[HttpResponseHeader.ContentType]);

                var map    = JSONReader.DeserializeDataObject(str) as JSONDataMap;
                var gotRow = JSONReader.ToRow <TestRow>(map);
            }
        }
Exemple #17
0
        public void Action_ComplexRow()
        {
            var initalRow = new TestComplexRow();

            initalRow.ID = 777;

            initalRow.Row1 = new TestRow()
            {
                ID = 101, Name = "Test Row 1", Date = DateTime.Now
            };
            initalRow.Row2 = new TestRow()
            {
                ID = 102, Name = "Test Row 2", Date = DateTime.Now
            };

            initalRow.ErrorRows = new TestRow[] {
                new TestRow()
                {
                    ID = 201, Name = "Err Row 1", Date = DateTime.Now
                },
                new TestRow()
                {
                    ID = 202, Name = "Err Row 2", Date = DateTime.Now
                },
                new TestRow()
                {
                    ID = 203, Name = "Err Row 3", Date = DateTime.Now
                }
            };

            var str = initalRow.ToJSON(JSONWritingOptions.CompactRowsAsMap);

            Console.WriteLine(str);

            using (var wc = CreateWebClient())
            {
                wc.Headers[HttpRequestHeader.ContentType] = NFX.Web.ContentType.JSON;
                var res = wc.UploadString(INTEGRATION_HTTP_ADDR + "ComplexRowSet", str);

                var map    = JSONReader.DeserializeDataObject(res) as JSONDataMap;
                var gotRow = JSONReader.ToRow <TestComplexRow>(map);

                Assert.AreEqual(initalRow.ID + 1, gotRow.ID);
                Assert.AreEqual(initalRow.Row1.ID + 2, gotRow.Row1.ID);
                Assert.IsTrue(gotRow.ErrorRows[2].Date - initalRow.ErrorRows[2].Date.AddDays(-2) < TimeSpan.FromMilliseconds(1)); // dlat 20140617: date string format preservs 3 signs after decimal second instead of 7 digits preserved by .NET DateTime type
            }
        }
Exemple #18
0
        public void Action_RowGet_TypeRow(WebClient wc)
        {
            var start = DateTime.Now;

            //using (var wc = CreateWebClient())
            {
                string str = wc.DownloadString(m_ServerURI + "RowGet");

                if ("application/json" != wc.ResponseHeaders[HttpResponseHeader.ContentType])
                {
                    throw new Exception();
                }

                var map    = JSONReader.DeserializeDataObject(str) as JSONDataMap;
                var gotRow = JSONReader.ToRow <TestRow>(map);
            }
        }
Exemple #19
0
        private JSONDataMap compileTemplate(string template)
        {
            JSONDataMap result;

            try
            {
                result = JSONReader.DeserializeDataObject(template) as JSONDataMap;
                if (result == null)
                {
                    throw new BSONException("template is not JSONDataMap");
                }
            }
            catch (Exception error)
            {
                throw new BSONException(StringConsts.BSON_TEMPLATE_COMPILE_ERROR.Args(error.ToMessageWithType(), template), error);
            }

            return(result);
        }
Exemple #20
0
        public void Options_RowMapTargetName()
        {
            var row = new OptRow {
                ID = "id123", LongName = "Long string", Hidden = "Cant see"
            };

            var json = JW.Write(row, new JSONWritingOptions {
                RowsAsMap = true, RowMapTargetName = "AAA"
            });

            var map = JSONReader.DeserializeDataObject(json) as JSONDataMap;

            Aver.IsNotNull(map);
            Aver.AreEqual(2, map.Count);
            Aver.AreEqual("id123", map["ID"].AsString().AsString());
            Aver.AreEqual("Long string", map["aln"].AsString());

            json = JW.Write(row, new JSONWritingOptions {
                RowsAsMap = true, RowMapTargetName = "BBB"
            });

            map = JSONReader.DeserializeDataObject(json) as JSONDataMap;

            Aver.IsNotNull(map);
            Aver.AreEqual(3, map.Count);
            Aver.AreEqual("id123", map["ID"].AsString());
            Aver.AreEqual("Long string", map["bln"].AsString());
            Aver.AreEqual("Cant see", map["Hidden"].AsString());

            json = JW.Write(row, new JSONWritingOptions {
                RowsAsMap = true
            });

            map = JSONReader.DeserializeDataObject(json) as JSONDataMap;

            Aver.IsNotNull(map);
            Aver.AreEqual(3, map.Count);
            Aver.AreEqual("id123", map["ID"].AsString());
            Aver.AreEqual("Long string", map["LongName"].AsString());
            Aver.AreEqual("Cant see", map["Hidden"].AsString());
        }
Exemple #21
0
        public void Schema_FromMap()
        {
            var src  = new TestRow().Schema;
            var json = src.ToJSON();
            var trg  = Schema.FromJSON(JSONReader.DeserializeDataObject(json) as JSONDataMap, true);

            Assert.IsTrue(trg.Name.StartsWith("JSON"));
            Assert.IsTrue(trg.ReadOnly);
            Assert.AreEqual(trg.FieldDefs.Count(), src.FieldDefs.Count());

            Assert.AreEqual(trg["BoolField"].Type, typeof(Boolean?));
            Assert.AreEqual(trg["CharField"].Type, typeof(Char?));
            Assert.AreEqual(trg["DateTimeField"].Type, typeof(DateTime?));
            Assert.AreEqual(trg["GDIDField"].Type, typeof(string));

            Assert.AreEqual(trg["ByteField"].Type, typeof(Int32?));
            Assert.AreEqual(trg["SByteField"].Type, typeof(Int32?));
            Assert.AreEqual(trg["ShortField"].Type, typeof(Int32?));
            Assert.AreEqual(trg["Int16Field"].Type, typeof(Int32?));
            Assert.AreEqual(trg["UShortField"].Type, typeof(Int32?));
            Assert.AreEqual(trg["UInt16Field"].Type, typeof(Int32?));
            Assert.AreEqual(trg["IntField"].Type, typeof(Int32?));
            Assert.AreEqual(trg["Int32Field"].Type, typeof(Int32?));

            Assert.AreEqual(trg["UIntField"].Type, typeof(Int64?));
            Assert.AreEqual(trg["UInt32Field"].Type, typeof(Int64?));
            Assert.AreEqual(trg["LongField"].Type, typeof(Int64?));
            Assert.AreEqual(trg["Int64Field"].Type, typeof(Int64?));

            Assert.AreEqual(trg["ULongField"].Type, typeof(UInt64?));
            Assert.AreEqual(trg["UInt64Field"].Type, typeof(UInt64?));

            Assert.AreEqual(trg["FloatField"].Type, typeof(Double?));
            Assert.AreEqual(trg["SingleField"].Type, typeof(Double?));
            Assert.AreEqual(trg["DoubleField"].Type, typeof(Double?));

            Assert.AreEqual(trg["DecimalField"].Type, typeof(Decimal?));

            Assert.AreEqual(trg["FieldWithAttrs"].Attrs, src["FieldWithAttrs"].Attrs);
        }
Exemple #22
0
        public void Record_MapJSToCLRTypes()
        {
            var json =
                @"{
  'fields': 
   [
     {
       'def': {
         'Name': 'STR',
         'Type': 'string'
       },
       'val': 'ABBA'
     },
     {
       'def': {
         'Name': 'INT',
         'Type': 'int'
       },
       'val': -23
     },
     {
       'def': {
         'Name': 'NUM',
         'Type': 'real'
       },
       'val': -123.456
     },
     {
       'def': {
         'Name': 'BOOL',
         'Type': 'bool'
       },
       'val': true
     },
     {
       'def': {
         'Name': 'DATE',
         'Type': 'datetime'
       },
       'val': '2016-03-23 12:23:59'
     },
     {
       'def': {
         'Name': 'OBJ',
         'Type': 'object'
       },
       'val': { 'n': 'name', 'age': 23 }
     },
     {
       'def': {
         'Name': 'DFT'
       },
       'val': 'Default type is string'
     }
   ]
}";

            var rec    = new Record(json);
            var errors = rec.ServerErrors.ToList();

            Assert.AreEqual(0, errors.Count);

            Assert.AreEqual(7, rec.Schema.FieldCount);

            var fdef = rec.Schema["STR"];

            Assert.IsNotNull(fdef);
            Assert.AreEqual("STR", fdef.Name);
            Assert.AreEqual(typeof(string), fdef.Type);
            Assert.AreEqual("ABBA", rec["STR"]);

            fdef = rec.Schema["INT"];
            Assert.IsNotNull(fdef);
            Assert.AreEqual("INT", fdef.Name);
            Assert.AreEqual(typeof(long), fdef.Type);
            Assert.AreEqual(-23, rec["INT"]);

            fdef = rec.Schema["NUM"];
            Assert.IsNotNull(fdef);
            Assert.AreEqual("NUM", fdef.Name);
            Assert.AreEqual(typeof(double), fdef.Type);
            Assert.AreEqual(-123.456, rec["NUM"]);

            fdef = rec.Schema["BOOL"];
            Assert.IsNotNull(fdef);
            Assert.AreEqual("BOOL", fdef.Name);
            Assert.AreEqual(typeof(bool), fdef.Type);
            Assert.AreEqual(true, rec["BOOL"]);

            fdef = rec.Schema["DATE"];
            Assert.IsNotNull(fdef);
            Assert.AreEqual("DATE", fdef.Name);
            Assert.AreEqual(typeof(DateTime), fdef.Type);
            Assert.AreEqual("2016-03-23 12:23:59".AsDateTime(), rec["DATE"]);

            fdef = rec.Schema["OBJ"];
            Assert.IsNotNull(fdef);
            Assert.AreEqual("OBJ", fdef.Name);
            Assert.AreEqual(typeof(object), fdef.Type);
            var value = JSONReader.DeserializeDataObject("{ 'n': 'name', 'age': 23 }") as JSONDataMap;

            Assert.AreEqual(value, rec["OBJ"]);

            fdef = rec.Schema["DFT"];
            Assert.IsNotNull(fdef);
            Assert.AreEqual("DFT", fdef.Name);
            Assert.AreEqual(typeof(string), fdef.Type);
            Assert.AreEqual("Default type is string", rec["DFT"]);
        }
Exemple #23
0
 public override object Deserialize(Stream inputStream)
 {
     inputStream.Seek(0, SeekOrigin.Begin);
     return(JSONReader.DeserializeDataObject(inputStream).ConvertTo <object>());
 }
Exemple #24
0
 public override object Deserialize(string serialized)
 {
     return(JSONReader.DeserializeDataObject(serialized).ConvertTo <object>());
 }
Exemple #25
0
 /// <summary>
 /// Reads either Table or Rowset from JSON created by WriteAsJSON. Metadata must be present
 /// </summary>
 public static RowsetBase FromJSON(string json, bool schemaOnly = false, bool readOnlySchema = false)
 {
     return(FromJSON(JSONReader.DeserializeDataObject(json) as JSONDataMap, schemaOnly, readOnlySchema));
 }
Exemple #26
0
        private void readFromString(string content)
        {
            var data = JSONReader.DeserializeDataObject(content, caseSensitiveMaps: false) as JSONDataMap;

            read(data);
        }
Exemple #27
0
        public void Record_ValidInitJSON()
        {
            var json =
                @"{
  'OK': true,
  'ID': '39a833dd-b48f-46c1-83a6-96603cc962a6',
  'ISOLang': 'eng',
  '__FormMode': 'Edit',
  '__CSRFToken': '1kk_qzXPLyScAa2A5y5GLTo9IlCqjuP',
  '__Roundtrip': '{\'GDID\':\'0:1:5\'}',
  'fields': [
      {
        'def': {
          'Name': 'Mnemonic',
          'Type': 'string',
          'Description': 'Mnemonic',
          'Required': true,
          'MinSize': 1,
          'Size': 25,
          'Placeholder': 'Mnemonic',
          'Stored': false
        },
        'val': 'Dns'
      },
      {
        'def': {
          'Name': 'Vertical_ID',
          'Type': 'string',
          'Description': 'Vertical',
          'Required': false,
          'Visible': false,
          'Size': 15,
          'DefaultValue': 'HAB',
          'Key': true,
          'Case': 'Upper',
          'LookupDict': {
            'HAB': 'HAB.rs Health and Beauty',
            'READRS': 'READ.rs Book Business',
            'SLRS': 'SL.RS General Business'
          }
        },
        'val': 'HAB'
      },
      {
        'def': {
          'Name': 'Table_ID',
          'Type': 'int',
          'Key': true,
          'Description': 'Table',
          'Required': true,
          'Visible': false,
          'MinValue': 1,
          'MaxValue': 123,
          'DefaultValue': 15,
          'Kind': 'Number',
          'Stored': true
        },
        'val': 2
      }
    ]
}";

            var init = JSONReader.DeserializeDataObject(json) as JSONDataMap;
            var rec  = new Record(init);

            Assert.AreEqual(0, rec.ServerErrors.Count());

            Assert.AreEqual(true, rec.OK);
            Assert.AreEqual("eng", rec.ISOLang);
            Assert.AreEqual(new Guid("39a833dd-b48f-46c1-83a6-96603cc962a6"), rec.ID);
            Assert.AreEqual("Edit", rec.FormMode);
            Assert.AreEqual("1kk_qzXPLyScAa2A5y5GLTo9IlCqjuP", rec.CSRFToken);

            var roundtrip = rec.Roundtrip;

            Assert.IsNotNull(roundtrip);
            Assert.AreEqual(roundtrip.Count, 1);
            Assert.AreEqual("0:1:5", roundtrip["GDID"]);

            Assert.AreEqual(3, rec.Schema.FieldCount);

            var fdef = rec.Schema["Mnemonic"];

            Assert.IsNotNull(fdef);
            Assert.AreEqual("Mnemonic", fdef.Name);
            Assert.AreEqual(typeof(string), fdef.Type);
            Assert.AreEqual(false, fdef.AnyTargetKey);
            Assert.IsNotNull(fdef.Attrs);
            Assert.AreEqual(1, fdef.Attrs.Count());
            var attr = fdef.Attrs.First();

            Assert.AreEqual("Mnemonic", attr.Description);
            Assert.AreEqual(true, attr.Required);
            Assert.AreEqual(true, attr.Visible);
            Assert.AreEqual(null, attr.Min);
            Assert.AreEqual(null, attr.Max);
            Assert.AreEqual(1, attr.MinLength);
            Assert.AreEqual(25, attr.MaxLength);
            Assert.AreEqual(null, attr.Default);
            Assert.AreEqual(0, attr.ParseValueList().Count);
            Assert.AreEqual(StoreFlag.OnlyLoad, attr.StoreFlag);
            Assert.AreEqual(@"''{Name=Mnemonic Type=string Description=Mnemonic Required=True MinSize=1 Size=25 Placeholder=Mnemonic Stored=False}", attr.MetadataContent);
            Assert.AreEqual("Dns", rec["Mnemonic"]);

            fdef = rec.Schema["Vertical_ID"];
            Assert.IsNotNull(fdef);
            Assert.AreEqual("Vertical_ID", fdef.Name);
            Assert.AreEqual(typeof(string), fdef.Type);
            Assert.AreEqual(true, fdef.AnyTargetKey);
            Assert.IsNotNull(fdef.Attrs);
            Assert.AreEqual(1, fdef.Attrs.Count());
            attr = fdef.Attrs.First();
            Assert.AreEqual("Vertical", attr.Description);
            Assert.AreEqual(false, attr.Required);
            Assert.AreEqual(false, attr.Visible);
            Assert.AreEqual(null, attr.Min);
            Assert.AreEqual(null, attr.Max);
            Assert.AreEqual(0, attr.MinLength);
            Assert.AreEqual(15, attr.MaxLength);
            Assert.AreEqual(CharCase.Upper, attr.CharCase);
            Assert.AreEqual("HAB", attr.Default);
            Assert.AreEqual(FieldAttribute.ParseValueListString("HAB:HAB.rs Health and Beauty,READRS:READ.rs Book Business,SLRS:SL.RS General Business", true), attr.ParseValueList(true));
            Assert.AreEqual("''{Name=Vertical_ID Type=string Description=Vertical Required=False Visible=False Size=15 DefaultValue=HAB Key=True Case=Upper LookupDict=\"{\\\"HAB\\\":\\\"HAB.rs Health and Beauty\\\",\\\"READRS\\\":\\\"READ.rs Book Business\\\",\\\"SLRS\\\":\\\"SL.RS General Business\\\"}\"}", attr.MetadataContent);
            Assert.AreEqual("HAB", rec["Vertical_ID"]);

            fdef = rec.Schema["Table_ID"];
            Assert.IsNotNull(fdef);
            Assert.AreEqual("Table_ID", fdef.Name);
            Assert.AreEqual(typeof(long), fdef.Type);
            Assert.AreEqual(true, fdef.AnyTargetKey);
            Assert.IsNotNull(fdef.Attrs);
            Assert.AreEqual(1, fdef.Attrs.Count());
            attr = fdef.Attrs.First();
            Assert.AreEqual("Table", attr.Description);
            Assert.AreEqual(true, attr.Required);
            Assert.AreEqual(false, attr.Visible);
            Assert.AreEqual(1, attr.Min);
            Assert.AreEqual(123, attr.Max);
            Assert.AreEqual(15, attr.Default);
            Assert.AreEqual(DataKind.Number, attr.Kind);
            Assert.AreEqual(StoreFlag.LoadAndStore, attr.StoreFlag);
            Assert.AreEqual(0, attr.ParseValueList(true).Count);
            Assert.AreEqual("''{Name=Table_ID Type=int Key=True Description=Table Required=True Visible=False MinValue=1 MaxValue=123 DefaultValue=15 Kind=Number Stored=True}", attr.MetadataContent);
            Assert.AreEqual(2, rec["Table_ID"]);
        }
Exemple #28
0
 public static Schema FromJSON(string json, bool readOnly = false)
 {
     return(FromJSON(JSONReader.DeserializeDataObject(json) as JSONDataMap, readOnly));
 }
Exemple #29
0
 public override object ParallelDeserialize(Stream stream)
 {
     return(JSONReader.DeserializeDataObject(stream));
 }