protected override object SubImport(JsonReader reader)
        {
            if (reader == null)
                throw new ArgumentNullException("reader");

            if (reader.TokenClass == JsonTokenClass.String)
            {
                return XmlConvert.ToDateTime(reader.Text);
            }
            else if (reader.TokenClass == JsonTokenClass.Number)
            {
                try
                {
                    return UnixTime.ToDateTime(Convert.ToInt64(reader.Text, CultureInfo.InvariantCulture));
                }
                catch (FormatException e)
                {
                    throw new JsonSerializationException(null, e); // TODO: Supply an exception message.
                }
                catch (OverflowException e)
                {
                    throw new JsonSerializationException(null, e); // TODO: Supply an exception message.
                }
            }
            else
            {
                throw new JsonSerializationException(string.Format("Found {0} where expecting a string in ISO 8601 time format or a number expressed in Unix time.", reader.TokenClass));
            }
        }
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            DataTable dt = existingValue as DataTable;

            if (dt == null)
            {
                // handle typed datasets
                dt = (objectType == typeof(DataTable))
                    ? new DataTable()
                    : (DataTable)Activator.CreateInstance(objectType);
            }

            if (reader.TokenType == JsonToken.PropertyName)
            {
                dt.TableName = (string)reader.Value;

                reader.Read();
            }

            if (reader.TokenType == JsonToken.StartArray)
                reader.Read();

            while (reader.TokenType != JsonToken.EndArray)
            {
                CreateRow(reader, dt);

                reader.Read();
            }

            return dt;
        }
Beispiel #3
0
        protected override object ImportFromString(ImportContext context, JsonReader reader)
        {
            Debug.Assert(context != null);
            Debug.Assert(reader != null);

            return ReadReturning(reader, reader.Text);
        }
 protected override object ImportValue(ImportContext context, JsonReader reader)
 {
     if (reader == null)
         throw new ArgumentNullException("reader");
     
     bool value;
     
     if (reader.TokenClass == JsonTokenClass.Number)
     {
         try
         {
             value = Convert.ToInt64(reader.Text, CultureInfo.InvariantCulture) != 0;
         }
         catch (FormatException e)
         {
             throw new JsonException(string.Format("The JSON Number {0} must be an integer to be convertible to System.Boolean.", reader.Text), e);
         }
     }
     else if (reader.TokenClass == JsonTokenClass.Boolean)
     {
         value = reader.Text == JsonBoolean.TrueText;
     }
     else
     {
         throw new JsonException(string.Format("Found {0} where expecting a JSON Boolean.", reader.TokenClass));
     }
     
     return value ? BooleanObject.True : BooleanObject.False;
 }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            NameContainer nameContainer = new NameContainer();
            nameContainer.Value = (string)reader.Value;

            return nameContainer;
        }
Beispiel #6
0
        protected override object ImportFromString(ImportContext context, JsonReader reader)
        {
            Debug.Assert(context != null);
            Debug.Assert(reader != null);

            string s = reader.Text.Trim();

            if (s.Length > 0)
            {
                char ch = s[0];

                if (Char.IsDigit(ch) || ch == '+' || ch == '-')
                    throw Error(s, null);
            }

            try
            {
                return ReadReturning(reader, Enum.Parse(OutputType, s, true));
            }
            catch (ArgumentException e)
            {
                //
                // Value is either an empty string ("") or only contains
                // white space. Value is a name, but not one of the named
                // constants defined for the enumeration.
                //

                throw Error(s, e);
            }
        }
 /// <summary>
 /// Reads the JSON representation of the object.
 /// </summary>
 /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
 /// <param name="objectType">Type of the object.</param>
 /// <param name="existingValue">The existing property value of the JSON that is being converted.</param>
 /// <param name="serializer">The calling serializer.</param>
 /// <returns>The object value.</returns>
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     if (reader.TokenType == JsonToken.Null)
     {
         return null;
     }
     else
     {
         if (reader.TokenType == JsonToken.String)
         {
             try
             {
                 Version v = new Version((string)reader.Value);
                 return v;
             }
             catch (Exception ex)
             {
                 throw JsonSerializationException.Create(reader, "Error parsing version string: {0}".FormatWith(CultureInfo.InvariantCulture, reader.Value), ex);
             }
         }
         else
         {
             throw JsonSerializationException.Create(reader, "Unexpected token or value when parsing version. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value));
         }
     }
 }
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            // handle typed datasets
            DataSet ds = (objectType == typeof(DataSet))
                ? new DataSet()
                : (DataSet)Activator.CreateInstance(objectType);

            DataTableConverter converter = new DataTableConverter();

            reader.Read();

            while (reader.TokenType == JsonToken.PropertyName)
            {
                DataTable dt = ds.Tables[(string)reader.Value];
                bool exists = (dt != null);

                dt = (DataTable)converter.ReadJson(reader, typeof(DataTable), dt, serializer);

                if (!exists)
                    ds.Tables.Add(dt);

                reader.Read();
            }

            return ds;
        }
 // Token: 0x06000685 RID: 1669
 // RVA: 0x0003758C File Offset: 0x0003578C
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     if (reader.TokenType == JsonToken.Null)
     {
         if (!ReflectionUtils.IsNullable(objectType))
         {
             throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Cannot convert null value to {0}.", CultureInfo.InvariantCulture, objectType));
         }
         return null;
     }
     else
     {
         if (reader.TokenType != JsonToken.StartConstructor || !string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal))
         {
             throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Unexpected token or value when parsing date. Token: {0}, Value: {1}", CultureInfo.InvariantCulture, reader.TokenType, reader.Value));
         }
         reader.Read();
         if (reader.TokenType != JsonToken.Integer)
         {
             throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Unexpected token parsing date. Expected Integer, got {0}.", CultureInfo.InvariantCulture, reader.TokenType));
         }
         long javaScriptTicks = (long)reader.Value;
         DateTime dateTime = DateTimeUtils.ConvertJavaScriptTicksToDateTime(javaScriptTicks);
         reader.Read();
         if (reader.TokenType != JsonToken.EndConstructor)
         {
             throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Unexpected token parsing date. Expected EndConstructor, got {0}.", CultureInfo.InvariantCulture, reader.TokenType));
         }
         return dateTime;
     }
 }
Beispiel #10
0
 private static void ReadJsonHelper(string jsonStr)
 {
     var reader = new JsonReader(jsonStr);
     while (reader.Read())
     {
         var tokenType = reader.TokenType;
         switch (tokenType)
         {
             case JsonReader.JsonTokenType.ObjectStart:
             case JsonReader.JsonTokenType.ObjectEnd:
             case JsonReader.JsonTokenType.ArrayStart:
             case JsonReader.JsonTokenType.ArrayEnd:
                 break;
             case JsonReader.JsonTokenType.Property:
                 // ReSharper disable once UnusedVariable
                 var name = reader.GetName();
                 var value = reader.GetValue();
                 break;
             case JsonReader.JsonTokenType.Value:
                 value = reader.GetValue();
                 break;
             default:
                 throw new ArgumentOutOfRangeException();
         }
     }
 }
    private static void ReadAndAssertProperty(JsonReader reader, string propertyName)
    {
      ReadAndAssert(reader);

      if (reader.TokenType != JsonToken.PropertyName || reader.Value.ToString() != propertyName)
        throw new JsonSerializationException("Expected JSON property '{0}'.".FormatWith(CultureInfo.InvariantCulture, propertyName));
    }
Beispiel #12
0
    public static int GetJsonValueInt(string data, string key)
    {
        try
        {
#if !UNITY_IOS
            //iOS build 에서는 안통하는 코드 
            JsonData jdata = JsonMapper.ToObject(data);
            return int.Parse(jdata[key].ToString());
#else
			//iOS android 에서 다 통하는 코드 
			JsonReader reader = new JsonReader (data);
			
			while (reader.Read()) 
			{
				
				if (reader.Token.ToString () == "PropertyName" && 
				    reader.Value.ToString () == key) 
				{
					reader.Read ();
					return int.Parse(reader.Value.ToString ());				
				}			
				
			}
#endif
        }
        catch
        {
            UnityEngine.Debug.LogWarning("json parsing error : " + data);
        }
        return -1;
    }
            public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
            {
                User user = new User();
                user.UserName = (string)reader.Value;

                return user;
            }
 protected override object ImportFromBoolean(ImportContext context, JsonReader reader)
 {
     Debug.Assert(context != null);
     Debug.Assert(reader != null);
     
     return BooleanObject.Box(reader.ReadBoolean());
 }
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            DataTable dt = existingValue as DataTable;

            if (dt == null)
            {
                // handle typed datasets
                dt = (objectType == typeof(DataTable))
                    ? new DataTable()
                    : (DataTable)Activator.CreateInstance(objectType);
            }

            if (reader.TokenType == JsonToken.PropertyName)
            {
                dt.TableName = (string)reader.Value;

                CheckedRead(reader);
            }

            if (reader.TokenType != JsonToken.StartArray)
                throw JsonSerializationException.Create(reader, "Unexpected JSON token when reading DataTable. Expected StartArray, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));

            CheckedRead(reader);

            while (reader.TokenType != JsonToken.EndArray)
            {
                CreateRow(reader, dt);

                CheckedRead(reader);
            }

            return dt;
        }
        protected override object ImportValue(ImportContext context, JsonReader reader)
        {
            if (context == null)
                throw new ArgumentNullException("reader");

            if (reader == null)
                throw new ArgumentNullException("reader");
            
            if (reader.TokenClass != JsonTokenClass.Number && reader.TokenClass != JsonTokenClass.String)
                throw new JsonException(string.Format("Found {0} where expecting a number.", reader.TokenClass));

            string text = reader.Text;
            
            try
            {
                return ConvertFromString(text);
            }
            catch (FormatException e)
            {
                throw NumberError(e, text);
            }
            catch (OverflowException e)
            {
                throw NumberError(e, text);
            }
        }
Beispiel #17
0
        protected override object ImportFromNumber(ImportContext context, JsonReader reader)
        {
            Debug.Assert(context != null);
            Debug.Assert(reader != null);

            string text = reader.Text;

            double time;

            try
            {
                time = Convert.ToDouble(text, CultureInfo.InvariantCulture);
            }
            catch (FormatException e)
            {
                throw NumberError(e, text);
            }
            catch (OverflowException e)
            {
                throw NumberError(e, text);
            }

            try
            {
                return ReadReturning(reader, UnixTime.ToDateTime(time));
            }
            catch (ArgumentException e)
            {
                throw NumberError(e, text);
            }
        }
 // Token: 0x06000682 RID: 1666
 // RVA: 0x00037464 File Offset: 0x00035664
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     bool flag = ReflectionUtils.IsNullableType(objectType);
     if (reader.TokenType == JsonToken.Null)
     {
         if (!ReflectionUtils.IsNullableType(objectType))
         {
             throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Cannot convert null value to {0}.", CultureInfo.InvariantCulture, objectType));
         }
         return null;
     }
     else
     {
         if (reader.TokenType == JsonToken.Date)
         {
             return reader.Value;
         }
         if (reader.TokenType != JsonToken.String)
         {
             throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Unexpected token parsing date. Expected String, got {0}.", CultureInfo.InvariantCulture, reader.TokenType));
         }
         string text = reader.Value.ToString();
         if (string.IsNullOrEmpty(text) && flag)
         {
             return null;
         }
         if (!string.IsNullOrEmpty(this._dateTimeFormat))
         {
             return DateTime.ParseExact(text, this._dateTimeFormat, this.Culture, this._dateTimeStyles);
         }
         return DateTime.Parse(text, this.Culture, this._dateTimeStyles);
     }
 }
        private JsonObject CreateJsonObject(JsonReader reader)
        {
            JsonObject o = new JsonObject();
              string propertyName = null;

              while (reader.Read())
              {
            switch (reader.TokenType)
            {
              case JsonToken.PropertyName:
            propertyName = (string)reader.Value;
            break;
              case JsonToken.EndObject:
            return o;
              case JsonToken.Comment:
            break;
              default:
            IJsonValue propertyValue = CreateJsonValue(reader);
            o.Add(propertyName, propertyValue);
            break;
            }
              }

              throw JsonSerializationException.Create(reader, "Unexpected end.");
        }
Beispiel #20
0
        object IJsonSerializable.Deserialize(JsonReader reader)
        {
            string property;
            while (reader.ReadProperty(out property))
            {
                switch (property)
                {
                    case "type":
                        Type = reader.ReadValue<string>();
                        break;
                    case "message":
                        Message = reader.ReadValue<string>();
                        break;
                    case "stackTrace":
                        StackTrace = reader.ReadValue<string>();
                        break;
                    case "url":
                        Url = reader.ReadValue<string>();
                        break;
                    case "refererUrl":
                        RefererUrl = reader.ReadValue<string>();
                        break;
                    case "additionalInfo":
                        AdditionalInfo = reader.ReadValue<Dictionary<string, object>>();
                        break;
                    default:
                        throw new ArgumentException("The specified property could not be deserialized.", property);
                }
            }

            return this;
        }
        public void CanDecryptCurrentStringValueAndAccessDecryptedNodes(string plainTextJson, params JsonNodeType[] expectedNodeTypes)
        {
            var cipherTextJson = @"""" + Convert.ToBase64String(Encoding.UTF8.GetBytes(plainTextJson)) + @"""";

            var info = new JsonSerializeOperationInfo
            {
                EncryptionMechanism = new Base64EncryptionMechanism(),
            };

            var reader = new JsonReader(new StringReader(cipherTextJson), info);
            Assert.That(reader.NodeType, Is.EqualTo(JsonNodeType.None));

            reader.Read("");
            Assert.That(reader.NodeType, Is.EqualTo(JsonNodeType.String));

            reader.SetDecryptReads(true, "");

            foreach (var expectedNodeType in expectedNodeTypes)
            {
                Assert.That(reader.NodeType, Is.EqualTo(expectedNodeType));
                reader.Read("");
            }

            reader.SetDecryptReads(false, "");

            Assert.That(reader.NodeType, Is.EqualTo(JsonNodeType.EndOfString));
        }
 private void onReqStrenSuccess(BaseWWWRequest obj)
 {
     try
     {
         StrengthenData data = new JsonReader().Read<StrengthenData>(base.UTF8String);
         base.responseData = data;
         if (data.eid != 0)
         {
             this.onReqStrenFail(obj);
         }
         else
         {
             if (data.shipVO != null)
             {
                 GameData.instance.UpdateUserShip(data.shipVO);
             }
             this.DeleteMaterials();
             if (data.detailInfo != null)
             {
                 GameData.instance.UserInfo.UpdateDetailInfo(data.detailInfo);
             }
             if (data.equipmentVo != null)
             {
                 GameData.instance.SetUserEquipments(data.equipmentVo);
             }
             this.OnStrengthenSuccess(EventArgs.Empty);
         }
     }
     catch (Exception exception)
     {
         z.log(exception.Message);
         this.onReqStrenFail(obj);
     }
 }
        private void DeserializeNode(JsonReader reader, XmlDocument document, XmlNamespaceManager manager, XmlNode currentNode)
        {
            do
              {
            switch (reader.TokenType)
            {
              case JsonToken.PropertyName:
            string propertyName = reader.Value.ToString();
            reader.Read();

            if (reader.TokenType == JsonToken.StartArray)
            {
              while (reader.Read() && reader.TokenType != JsonToken.EndArray)
              {
                DeserializeValue(reader, document, manager, propertyName, currentNode);
              }
            }
            else
            {
              DeserializeValue(reader, document, manager, propertyName, currentNode);
            }
            break;
              //case JsonToken.String:
              //    DeserializeValue(reader, document, manager, TextName, currentNode);
              //    break;
              case JsonToken.EndObject:
              case JsonToken.EndArray:
            return;
              default:
            throw new JsonSerializationException("Unexpected JsonToken when deserializing node: " + reader.TokenType);
            }
              } while (reader.TokenType == JsonToken.PropertyName || reader.Read());
              // don't read if current token is a property. token was already read when parsing element attributes
        }
 // Token: 0x06000181 RID: 385
 // RVA: 0x0002B488 File Offset: 0x00029688
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     Type type = ReflectionUtils.IsNullableType(objectType) ? Nullable.GetUnderlyingType(objectType) : objectType;
     if (reader.TokenType == JsonToken.Null)
     {
         if (!ReflectionUtils.IsNullable(objectType))
         {
             throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Cannot convert null value to {0}.", CultureInfo.InvariantCulture, objectType));
         }
         return null;
     }
     else
     {
         byte[] value;
         if (reader.TokenType == JsonToken.StartArray)
         {
             value = this.ReadByteArray(reader);
         }
         else
         {
             if (reader.TokenType != JsonToken.String)
             {
                 throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Unexpected token parsing binary. Expected String or StartArray, got {0}.", CultureInfo.InvariantCulture, reader.TokenType));
             }
             string s = reader.Value.ToString();
             value = Convert.FromBase64String(s);
         }
         if (type == typeof(SqlBinary))
         {
             return new SqlBinary(value);
         }
         throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Unexpected object type when writing binary: {0}", CultureInfo.InvariantCulture, objectType));
     }
 }
 public override object Read(JsonReader reader)
 {
     var p = (EnumerableProperty)base.Read(reader);
     var length = int.Parse(reader.ReadProperty().Value.ToString());
     p.Length = length;
     return p;
 }
        public void Populate(JsonReader reader, object target)
        {
            ValidationUtils.ArgumentNotNull(target, "target");

              Type objectType = target.GetType();

              JsonContract contract = _serializer.ContractResolver.ResolveContract(objectType);

              if (reader.TokenType == JsonToken.None)
            reader.Read();

              if (reader.TokenType == JsonToken.StartArray)
              {
            PopulateList(CollectionUtils.CreateCollectionWrapper(target), reader, null, GetArrayContract(objectType));
              }
              else if (reader.TokenType == JsonToken.StartObject)
              {
            CheckedRead(reader);

            string id = null;
            if (reader.TokenType == JsonToken.PropertyName && string.Equals(reader.Value.ToString(), JsonTypeReflector.IdPropertyName, StringComparison.Ordinal))
            {
              CheckedRead(reader);
              id = reader.Value.ToString();
              CheckedRead(reader);
            }

            if (contract is JsonDictionaryContract)
              PopulateDictionary(CollectionUtils.CreateDictionaryWrapper(target), reader, (JsonDictionaryContract) contract, id);
            else if (contract is JsonObjectContract)
              PopulateObject(target, reader, (JsonObjectContract) contract, id);
            else
              throw new Exception("dfsdfsdf");
              }
        }
        private static void ReadAndAssertProperty(JsonReader reader, string propertyName)
        {
            ReadAndAssert(reader);

            if (reader.TokenType != JsonToken.PropertyName || !string.Equals(reader.Value.ToString(), propertyName, StringComparison.OrdinalIgnoreCase))
                throw new JsonSerializationException("Expected JSON property '{0}'.".FormatWith(CultureInfo.InvariantCulture, propertyName));
        }
Beispiel #28
0
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType)
        {
            Type t = (ReflectionUtils.IsNullableType(objectType))
            ? Nullable.GetUnderlyingType(objectType)
            : objectType;

              if (reader.TokenType == JsonToken.Null)
              {
            if (!ReflectionUtils.IsNullable(objectType))
              throw new Exception("Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));

            return null;
              }

              if (reader.TokenType != JsonToken.String)
            throw new Exception("Unexpected token parsing binary. Expected String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));

              string encodedData = reader.Value.ToString();

              byte[] data = Convert.FromBase64String(encodedData);

              if (t == typeof(byte[]))
            return data;

            #if !SILVERLIGHT && !PocketPC
              if (typeof(Binary).IsAssignableFrom(t))
            return new Binary(data);
            #endif
            #if !SILVERLIGHT
              if (typeof(SqlBinary).IsAssignableFrom(t))
            return new SqlBinary(data);
            #endif
              throw new Exception("Unexpected object type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, objectType));
        }
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing property value of the JSON that is being converted.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var t = (ReflectionUtils.IsNullableType(objectType)) ? Nullable.GetUnderlyingType(objectType) : objectType;

            if (reader.TokenType == JsonToken.Null)
            {
                if (!ReflectionUtils.IsNullable(objectType))
                    throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));

                return null;
            }

            if (reader.TokenType != JsonToken.StartConstructor || !string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal))
                throw JsonSerializationException.Create(reader, "Unexpected token or value when parsing date. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value));

            reader.Read();

            if (reader.TokenType != JsonToken.Integer)
                throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected Integer, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));

            var ticks = (long)reader.Value;

            var d = DateTimeUtils.ConvertJavaScriptTicksToDateTime(ticks);

            reader.Read();

            if (reader.TokenType != JsonToken.EndConstructor)
                throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected EndConstructor, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));

            if (t == typeof(DateTimeOffset))
                return new DateTimeOffset(d);

            return d;
        }
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            bool isNullable = ReflectionUtils.IsNullableType(objectType);

            Type t = (isNullable)
                         ? Nullable.GetUnderlyingType(objectType)
                         : objectType;

            ReflectionObject reflectionObject = ReflectionObjectPerType.Get(t);

            if (reader.TokenType == JsonToken.Null)
            {
                if (!isNullable)
                    throw JsonSerializationException.Create(reader, "Cannot convert null value to Matrix4x4.");

                return null;
            }

            object[] values = new object[PropNames.Length];

            ReadAndAssert(reader);

            while (reader.TokenType == JsonToken.PropertyName)
            {
                string propertyName = reader.Value.ToString();

                var index = Array.IndexOf(PropNames, propertyName);
                if (index != -1)
                {
                    var name = PropNames[index];
                    ReadAndAssert(reader);
                    values[index] = serializer.Deserialize(reader, reflectionObject.GetType(name));
                }
                else
                {
                    reader.Skip();
                }

                ReadAndAssert(reader);
            }

            var matrix = (Matrix4x4)reflectionObject.Creator();
            matrix.m00 = (float)values[0];
            matrix.m01 = (float)values[1];
            matrix.m02 = (float)values[2];
            matrix.m03 = (float)values[3];
            matrix.m10 = (float)values[4];
            matrix.m11 = (float)values[5];
            matrix.m12 = (float)values[6];
            matrix.m13 = (float)values[7];
            matrix.m20 = (float)values[8];
            matrix.m21 = (float)values[9];
            matrix.m22 = (float)values[10];
            matrix.m23 = (float)values[11];
            matrix.m30 = (float)values[12];
            matrix.m31 = (float)values[13];
            matrix.m32 = (float)values[14];
            matrix.m33 = (float)values[15];
            return matrix;
        }
Beispiel #31
0
 protected override object ImportFromBoolean(ImportContext context, JsonReader reader)
 {
     return(new byte[] { (byte)(reader.ReadBoolean() ? 1 : 0) });
 }
Beispiel #32
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var notifications = new List <NotificationItem>();
            var jArr          = serializer.Deserialize <JArray>(reader);

            foreach (var jObj in jArr.OfType <JObject>())
            {
                var type = (string)jObj["type"];

                switch (type)
                {
                case "follow":
                    notifications.Add(jObj.ToObject <FollowNotification>());
                    break;

                case "friend_accepted":
                    notifications.Add(jObj.ToObject <FriendAcceptedNotification>());
                    break;

                case "mention":
                    notifications.Add(jObj.ToObject <MentionNotification>());
                    break;

                case "mention_comments":
                    notifications.Add(jObj.ToObject <MentionCommentsNotification>());
                    break;

                case "wall":
                    notifications.Add(jObj.ToObject <WallNotification>());
                    break;

                case "wall_publish":
                    notifications.Add(jObj.ToObject <WallPublishNotification>());
                    break;

                case "comment_post":
                    notifications.Add(jObj.ToObject <CommentPostNotification>());
                    break;

                case "comment_photo":
                    notifications.Add(jObj.ToObject <CommentPhotoNotification>());
                    break;

                case "comment_video":
                    notifications.Add(jObj.ToObject <CommentVideoNotification>());
                    break;

                case "reply_comment":
                    notifications.Add(jObj.ToObject <ReplyCommentNotification>());
                    break;

                case "reply_comment_photo":
                    notifications.Add(jObj.ToObject <ReplyCommentPhotoNotification>());
                    break;

                case "reply_comment_video":
                    notifications.Add(jObj.ToObject <ReplyCommentVideoNotification>());
                    break;

                case "reply_comment_market":
                    notifications.Add(jObj.ToObject <ReplyCommentMarketNotification>());
                    break;

                case "reply_topic":
                    notifications.Add(jObj.ToObject <ReplyTopicNotification>());
                    break;

                case "like_post":
                    notifications.Add(jObj.ToObject <LikePostNotification>());
                    break;

                case "like_comment":
                    notifications.Add(jObj.ToObject <LikeCommentNotification>());
                    break;

                case "like_photo":
                    notifications.Add(jObj.ToObject <LikePhotoNotification>());
                    break;

                case "like_video":
                    notifications.Add(jObj.ToObject <LikeVideoNotification>());
                    break;

                case "like_comment_photo":
                    notifications.Add(jObj.ToObject <LikeCommentPhotoNotification>());
                    break;

                case "like_comment_video":
                    notifications.Add(jObj.ToObject <LikeCommentVideoNotification>());
                    break;

                case "like_comment_topic":
                    notifications.Add(jObj.ToObject <LikeCommentTopicNotification>());
                    break;

                case "copy_post":
                    notifications.Add(jObj.ToObject <CopyPostNotification>());
                    break;

                case "copy_photo":
                    notifications.Add(jObj.ToObject <CopyPhotoNotification>());
                    break;

                case "copy_video":
                    notifications.Add(jObj.ToObject <CopyVideoNotification>());
                    break;

                case "mention_comment_photo":
                    notifications.Add(jObj.ToObject <MentionCommentPhotoNotification>());
                    break;

                case "mention_comment_video":
                    notifications.Add(jObj.ToObject <MentionCommentVideoNotification>());
                    break;
                }
            }

            return(notifications);
        }
Beispiel #33
0
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     return(reader.Value + "!");
 }
Beispiel #34
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
                                        JsonSerializer serializer)
        {
            var token = JToken.Load(reader);

            if (token.Value <string>() == null)
            {
                return(null);
            }
            var str = token.Value <string>();

            switch (str)
            {
            case "CUSTOM":
                return(QueueType.Custom);

            case "NORMAL_5x5_BLIND":
                return(QueueType.Normal5x5Blind);

            case "RANKED_SOLO_5x5":
                return(QueueType.RankedSolo5x5);

            case "RANKED_PREMADE_5x5":
                return(QueueType.RankedPremade5x5);

            case "BOT_5x5":
                return(QueueType.Bot5x5);

            case "NORMAL_3x3":
                return(QueueType.Normal3x3);

            case "RANKED_PREMADE_3x3":
                return(QueueType.RankedPremade3x3);

            case "NORMAL_5x5_DRAFT":
                return(QueueType.Normal5x5Draft);

            case "ODIN_5x5_BLIND":
                return(QueueType.Odin5x5Blind);

            case "ODIN_5x5_DRAFT":
                return(QueueType.Odin5x5Draft);

            case "BOT_ODIN_5x5":
                return(QueueType.BotOdin5x5);

            case "BOT_5x5_INTRO":
                return(QueueType.Bot5x5Intro);

            case "BOT_5x5_BEGINNER":
                return(QueueType.Bot5x5Beginner);

            case "BOT_5x5_INTERMEDIATE":
                return(QueueType.Bot5x5Intermediate);

            case "RANKED_TEAM_3x3":
                return(QueueType.RankedTeam3x3);

            case "RANKED_TEAM_5x5":
                return(QueueType.RankedTeam5x5);

            case "BOT_TT_3x3":
                return(QueueType.BotTt3x3);

            case "GROUP_FINDER_5x5":
                return(QueueType.GroupFinder5x5);

            case "ARAM_5x5":
                return(QueueType.Aram5x5);

            case "ONEFORALL_5x5":
                return(QueueType.OneForAll5x5);

            case "FIRSTBLOOD_1x1":
                return(QueueType.FirstBlood1x1);

            case "FIRSTBLOOD_2x2":
                return(QueueType.FirstBlood2x2);

            case "SR_6x6":
                return(QueueType.Sr6x6);

            case "URF_5x5":
                return(QueueType.Urf5x5);

            case "BOT_URF_5x5":
                return(QueueType.BotUrf5x5);

            case "BILGEWATER_5x5":
                return(QueueType.Bilgewater5x5);

            case "BILGEWATER_ARAM_5x5":
                return(QueueType.BilgewaterAram5x5);

            case "NIGHTMARE_BOT_5x5_RANK1":
                return(QueueType.NightmareBot5x5Rank1);

            case "NIGHTMARE_BOT_5x5_RANK2":
                return(QueueType.NightmareBot5x5Rank2);

            case "NIGHTMARE_BOT_5x5_RANK5":
                return(QueueType.NightmareBot5x5Rank5);

            case "TEAM_BUILDER_DRAFT_UNRANKED_5x5":
                return(QueueType.TeamBuilderDraftUnranked5x5);

            case "TEAM_BUILDER_DRAFT_RANKED_5x5":
                return(QueueType.TeamBuilderDraftRanked5x5);

            case "RANKED_FLEX_SR":
                return(QueueType.RankedFlexSR);

            case "RANKED_FLEX_TT":
                return(QueueType.RankedFlexTT);

            case "TEAM_BUILDER_RANKED_SOLO":
                return(QueueType.TeamBuilderRankedSolo);

            default:
                return(null);
            }
        }
 public override INode ReadJson(JsonReader reader, Type objectType, INode existingValue, bool hasExistingValue, JsonSerializer serializer)
 {
     throw new NotImplementedException();
 }
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     throw new NotSupportedException();
 }
Beispiel #37
0
 protected override object ImportFromNumber(ImportContext context, JsonReader reader)
 {
     return(new byte[] { reader.ReadNumber().ToByte() });
 }
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     return(new MessageB {
         Value = "Monster"
     });
 }
        public override object ReadJson(JsonReader reader, Type objectType, object?existingValue, JsonSerializer serializer)
        {
            var stringValue = (string)reader.Value !;

            return(Resistance.Parse(stringValue, serializer.Culture));
        }
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     return(values.Single(v => v.Value == (string)reader.Value).Key);
 }
Beispiel #41
0
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     throw new Exception("IPage Not supposed to be deserialized with PageConverter");
 }
Beispiel #42
0
 public override Version ReadJson(JsonReader reader, Type objectType, Version existingValue, bool hasExistingValue, JsonSerializer serializer)
 {
     return(new Version((string)reader.Value));
 }
Beispiel #43
0
        /// <summary>
        /// Gets the object from Json properties.
        /// </summary>
        /// <param name="reader">The <see cref="T: Newtonsoft.Json.JsonReader" /> to read from, reader must be placed at first property.</param>
        /// <returns>The object Value.</returns>
        internal static ApplicationUpgradeRollbackStartEvent GetFromJsonProperties(JsonReader reader)
        {
            var eventInstanceId               = default(Guid?);
            var timeStamp                     = default(DateTime?);
            var hasCorrelatedEvents           = default(bool?);
            var applicationId                 = default(string);
            var applicationTypeName           = default(string);
            var currentApplicationTypeVersion = default(string);
            var applicationTypeVersion        = default(string);
            var failureReason                 = default(string);
            var overallUpgradeElapsedTimeInMs = default(double?);

            do
            {
                var propName = reader.ReadPropertyName();
                if (string.Compare("EventInstanceId", propName, StringComparison.Ordinal) == 0)
                {
                    eventInstanceId = reader.ReadValueAsGuid();
                }
                else if (string.Compare("TimeStamp", propName, StringComparison.Ordinal) == 0)
                {
                    timeStamp = reader.ReadValueAsDateTime();
                }
                else if (string.Compare("HasCorrelatedEvents", propName, StringComparison.Ordinal) == 0)
                {
                    hasCorrelatedEvents = reader.ReadValueAsBool();
                }
                else if (string.Compare("ApplicationId", propName, StringComparison.Ordinal) == 0)
                {
                    applicationId = reader.ReadValueAsString();
                }
                else if (string.Compare("ApplicationTypeName", propName, StringComparison.Ordinal) == 0)
                {
                    applicationTypeName = reader.ReadValueAsString();
                }
                else if (string.Compare("CurrentApplicationTypeVersion", propName, StringComparison.Ordinal) == 0)
                {
                    currentApplicationTypeVersion = reader.ReadValueAsString();
                }
                else if (string.Compare("ApplicationTypeVersion", propName, StringComparison.Ordinal) == 0)
                {
                    applicationTypeVersion = reader.ReadValueAsString();
                }
                else if (string.Compare("FailureReason", propName, StringComparison.Ordinal) == 0)
                {
                    failureReason = reader.ReadValueAsString();
                }
                else if (string.Compare("OverallUpgradeElapsedTimeInMs", propName, StringComparison.Ordinal) == 0)
                {
                    overallUpgradeElapsedTimeInMs = reader.ReadValueAsDouble();
                }
                else
                {
                    reader.SkipPropertyValue();
                }
            }while (reader.TokenType != JsonToken.EndObject);

            return(new ApplicationUpgradeRollbackStartEvent(
                       eventInstanceId: eventInstanceId,
                       timeStamp: timeStamp,
                       hasCorrelatedEvents: hasCorrelatedEvents,
                       applicationId: applicationId,
                       applicationTypeName: applicationTypeName,
                       currentApplicationTypeVersion: currentApplicationTypeVersion,
                       applicationTypeVersion: applicationTypeVersion,
                       failureReason: failureReason,
                       overallUpgradeElapsedTimeInMs: overallUpgradeElapsedTimeInMs));
        }
 /// <inheritdoc/>
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     return(EventSourceVersion.FromCombined((double)reader.Value));
 }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var obj = JObject.Load(reader);

            var isCustomNode = obj["IsCustomNode"].Value <bool>();
            var description  = obj["Description"].Value <string>();
            var guidStr      = obj["Uuid"].Value <string>();
            var guid         = Guid.Parse(guidStr);
            var name         = obj["Name"].Value <string>();

            var elementResolver = obj["ElementResolver"].ToObject <ElementResolver>(serializer);
            var nmc             = (NodeReadConverter)serializer.Converters.First(c => c is NodeReadConverter);

            nmc.ElementResolver = elementResolver;

            var nodes = obj["Nodes"].ToObject <IEnumerable <NodeModel> >(serializer);

            // Setting Inputs
            // Required in headless mode by Dynamo Player that NodeModel.Name and NodeModel.IsSetAsInput are set
            var inputsToken = obj["Inputs"];

            if (inputsToken != null)
            {
                var inputs = inputsToken.ToArray().Select(x => x.ToObject <NodeInputData>()).ToList();
                // Use the inputs to set the correct properties on the nodes.
                foreach (var inputData in inputs)
                {
                    var matchingNode = nodes.Where(x => x.GUID == inputData.Id).FirstOrDefault();
                    if (matchingNode != null)
                    {
                        matchingNode.IsSetAsInput = true;
                        matchingNode.Name         = inputData.Name;
                    }
                }
            }

            // Setting Outputs
            var outputsToken = obj["Outputs"];

            if (outputsToken != null)
            {
                var outputs = outputsToken.ToArray().Select(x => x.ToObject <NodeOutputData>()).ToList();
                // Use the outputs to set the correct properties on the nodes.
                foreach (var outputData in outputs)
                {
                    var matchingNode = nodes.Where(x => x.GUID == outputData.Id).FirstOrDefault();
                    if (matchingNode != null)
                    {
                        matchingNode.IsSetAsOutput = true;
                        matchingNode.Name          = outputData.Name;
                    }
                }
            }

            #region Setting Inputs based on view layer info
            // TODO: It is currently duplicating the effort with Input Block parsing which should be cleaned up once
            // Dynamo supports both selection and drop down nodes in Inputs block
            var view = obj["View"];
            if (view != null)
            {
                var nodesView = view["NodeViews"];
                if (nodesView != null)
                {
                    var inputsView = nodesView.ToArray().Select(x => x.ToObject <Dictionary <string, string> >()).ToList();
                    foreach (var inputViewData in inputsView)
                    {
                        string isSetAsInput = "";
                        if (!inputViewData.TryGetValue("IsSetAsInput", out isSetAsInput) || isSetAsInput == bool.FalseString)
                        {
                            continue;
                        }

                        string inputId = "";
                        if (inputViewData.TryGetValue("Id", out inputId))
                        {
                            Guid inputGuid;
                            try
                            {
                                inputGuid = Guid.Parse(inputId);
                            }
                            catch
                            {
                                continue;
                            }

                            var matchingNode = nodes.Where(x => x.GUID == inputGuid).FirstOrDefault();
                            if (matchingNode != null)
                            {
                                matchingNode.IsSetAsInput = true;
                                string inputName = "";
                                if (inputViewData.TryGetValue("Name", out inputName))
                                {
                                    matchingNode.Name = inputName;
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            // notes
            //TODO: Check this when implementing ReadJSON in ViewModel.
            //var notes = obj["Notes"].ToObject<IEnumerable<NoteModel>>(serializer);
            //if (notes.Any())
            //{
            //    foreach(var n in notes)
            //    {
            //        serializer.ReferenceResolver.AddReference(serializer.Context, n.GUID.ToString(), n);
            //    }
            //}

            // connectors
            // Although connectors are not used in the construction of the workspace
            // we need to deserialize this collection, so that they connect to their
            // relevant ports.
            var connectors = obj["Connectors"].ToObject <IEnumerable <ConnectorModel> >(serializer);

            IEnumerable <PackageDependencyInfo> packageDependencies;
            if (obj["PackageDependencies"] != null)
            {
                packageDependencies = obj["PackageDependencies"].ToObject <IEnumerable <PackageDependencyInfo> >(serializer);
            }
            else
            {
                packageDependencies = new List <PackageDependencyInfo>();
            }

            var info = new WorkspaceInfo(guid.ToString(), name, description, Dynamo.Models.RunType.Automatic);

            // IsVisibleInDynamoLibrary and Category should be set explicitly for custom node workspace
            if (obj["View"] != null && obj["View"]["Dynamo"] != null && obj["View"]["Dynamo"]["IsVisibleInDynamoLibrary"] != null)
            {
                info.IsVisibleInDynamoLibrary = obj["View"]["Dynamo"]["IsVisibleInDynamoLibrary"].Value <bool>();
            }
            if (obj["Category"] != null)
            {
                info.Category = obj["Category"].Value <string>();
            }

            // Build an empty annotations. Annotations are defined in the view block. If the file has View block
            // serialize view block first and build the annotations.
            var annotations = new List <AnnotationModel>();

            // Build an empty notes. Notes are defined in the view block. If the file has View block
            // serialize view block first and build the notes.
            var notes = new List <NoteModel>();

            #region Restore trace data
            // Trace Data
            Dictionary <Guid, List <CallSite.RawTraceData> > loadedTraceData = new Dictionary <Guid, List <CallSite.RawTraceData> >();
            // Restore trace data if bindings are present in json
            if (obj["Bindings"] != null && obj["Bindings"].Children().Count() > 0)
            {
                JEnumerable <JToken> bindings = obj["Bindings"].Children();

                // Iterate through bindings to extract nodeID's and bindingData (callsiteId & traceData)
                foreach (JToken entity in bindings)
                {
                    Guid   nodeId        = Guid.Parse(entity["NodeId"].ToString());
                    string bindingString = entity["Binding"].ToString();

                    // Key(callsiteId) : Value(traceData)
                    Dictionary <string, string>  bindingData       = JsonConvert.DeserializeObject <Dictionary <string, string> >(bindingString);
                    List <CallSite.RawTraceData> callsiteTraceData = new List <CallSite.RawTraceData>();

                    foreach (KeyValuePair <string, string> pair in bindingData)
                    {
                        callsiteTraceData.Add(new CallSite.RawTraceData(pair.Key, pair.Value));
                    }

                    loadedTraceData.Add(nodeId, callsiteTraceData);
                }
            }
            #endregion

            WorkspaceModel ws;
            if (isCustomNode)
            {
                ws = new CustomNodeWorkspaceModel(factory, nodes, notes, annotations,
                                                  Enumerable.Empty <PresetModel>(), elementResolver, info);
            }
            else
            {
                ws = new HomeWorkspaceModel(guid, engine, scheduler, factory,
                                            loadedTraceData, nodes, notes, annotations,
                                            Enumerable.Empty <PresetModel>(), elementResolver,
                                            info, verboseLogging, isTestMode);
            }

            ws.PackageDependencies = packageDependencies.ToList();

            return(ws);
        }
Beispiel #46
0
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     throw new NotImplementedException();    // TODO:
 }
Beispiel #47
0
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     serializer.Converters.Clear();
     serializer.Converters.Add(Converter);
     return(serializer.Deserialize(reader, objectType));
 }
Beispiel #48
0
 /// <summary>
 /// Deserializes the JSON representation of the object.
 /// </summary>
 /// <param name="reader">The <see cref="T: Newtonsoft.Json.JsonReader" /> to read from.</param>
 /// <returns>The object Value.</returns>
 internal static ApplicationUpgradeRollbackStartEvent Deserialize(JsonReader reader)
 {
     return(reader.Deserialize(GetFromJsonProperties));
 }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
                                        JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                return(null);
            }

            JObject jObject = JObject.Load(reader);
            string  kind    = jObject[nameof(Ust.Kind)]?.ToString() ?? "";

            if (!ReflectionCache.TryGetClassType(kind, out Type type))
            {
                JsonUtils.LogError(Logger, JsonFile, jObject, $"Unknown UST {nameof(Ust.Kind)} {kind}");
                return(null);
            }

            RootUst rootUst = null;
            Ust     ust;

            if (type == typeof(RootUst))
            {
                string   languageString = (string)jObject?[nameof(RootUst.Language)] ?? "";
                Language language       = !string.IsNullOrEmpty(languageString)
                    ? languageString.ParseLanguages().FirstOrDefault()
                    : Uncertain.Language;

                rootUst = (RootUst)Activator.CreateInstance(type, null, language);
                ProcessRootUst(rootUst);

                ust = rootUst;
            }
            else
            {
                ust = (Ust)Activator.CreateInstance(type);
            }

            if (rootAncestors.Count > 0)
            {
                ust.Root = rootAncestors.Peek();
            }
            if (ancestors.Count > 0)
            {
                ust.Parent = ancestors.Peek();
            }

            if (rootUst != null)
            {
                rootAncestors.Push(rootUst);
            }
            ancestors.Push(ust);

            List <TextSpan> textSpans =
                jObject[nameof(Ust.TextSpan)]?.ToTextSpans(serializer).ToList() ?? null;

            if (textSpans != null && textSpans.Count > 0)
            {
                if (textSpans.Count == 1)
                {
                    ust.TextSpan = textSpans[0];
                }
                else
                {
                    ust.InitialTextSpans = textSpans;
                    ust.TextSpan         = textSpans.First();
                }
            }

            try
            {
                serializer.Populate(jObject.CreateReader(), ust);
            }
            catch (Exception ex)
            {
                Logger.LogError(JsonFile, jObject, ex);
            }

            if (!IgnoreExtraProcess)
            {
                ExtraProcess(ust, jObject);
            }

            if (rootUst != null)
            {
                rootAncestors.Pop();
            }
            ancestors.Pop();

            return(ust);
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            NodeModel node = null;

            var obj  = JObject.Load(reader);
            var type = Type.GetType(obj["$type"].Value <string>());

            // If we can't find this type - try to look in our load from assemblies,
            // but only during testing - this is required during testing because some dlls are loaded
            // using Assembly.LoadFrom using the assemblyHelper - which loads dlls into loadFrom context -
            // dlls loaded with LoadFrom context cannot be found using Type.GetType() - this should
            // not be an issue during normal dynamo use but if it is we can enable this code.
            if (type == null && this.isTestMode == true)
            {
                List <Assembly> resultList;

                var typeName = obj["$type"].Value <string>().Split(',').FirstOrDefault();
                // This assemblyName does not usually contain version information...
                var assemblyName = obj["$type"].Value <string>().Split(',').Skip(1).FirstOrDefault().Trim();
                if (assemblyName != null)
                {
                    if (this.loadedAssemblies.TryGetValue(assemblyName, out resultList))
                    {
                        var matchingTypes = resultList.Select(x => x.GetType(typeName)).ToList();
                        type = matchingTypes.FirstOrDefault();
                    }
                }
            }

            // Check for and attempt to resolve an unknown type before proceeding
            if (type == null)
            {
                // Attempt to resolve the type using `AlsoKnownAs`
                var  unresolvedName = obj["$type"].Value <string>().Split(',').FirstOrDefault();
                Type newType;
                nodeFactory.ResolveType(unresolvedName, out newType);

                // If resolved update the type
                if (newType != null)
                {
                    type = newType;
                }
            }

            // If the id is not a guid, makes a guid based on the id of the node
            var guid = GuidUtility.tryParseOrCreateGuid(obj["Id"].Value <string>());

            var replication = obj["Replication"].Value <string>();

            var inPorts  = obj["Inputs"].ToArray().Select(t => t.ToObject <PortModel>()).ToArray();
            var outPorts = obj["Outputs"].ToArray().Select(t => t.ToObject <PortModel>()).ToArray();

            var    resolver         = (IdReferenceResolver)serializer.ReferenceResolver;
            string assemblyLocation = objectType.Assembly.Location;

            bool remapPorts = true;

            // If type is still null at this point return a dummy node
            if (type == null)
            {
                node = CreateDummyNode(obj, assemblyLocation, inPorts, outPorts);
            }
            // Attempt to create a valid node using the type
            else if (type == typeof(Function))
            {
                var functionId = Guid.Parse(obj["FunctionSignature"].Value <string>());

                CustomNodeDefinition def  = null;
                CustomNodeInfo       info = null;
                bool     isUnresolved     = !manager.TryGetCustomNodeData(functionId, null, false, out def, out info);
                Function function         = manager.CreateCustomNodeInstance(functionId, null, false, def, info);
                node = function;

                if (isUnresolved)
                {
                    function.UpdatePortsForUnresolved(inPorts, outPorts);
                }
            }

            else if (type == typeof(CodeBlockNodeModel))
            {
                var code = obj["Code"].Value <string>();
                CodeBlockNodeModel codeBlockNode = new CodeBlockNodeModel(code, guid, 0.0, 0.0, libraryServices, ElementResolver);
                node = codeBlockNode;

                // If the code block node is in an error state read the extra port data
                // and initialize the input and output ports
                if (node.IsInErrorState)
                {
                    List <string> inPortNames = new List <string>();
                    var           inputs      = obj["Inputs"];
                    foreach (var input in inputs)
                    {
                        inPortNames.Add(input["Name"].ToString());
                    }

                    // NOTE: This could be done in a simpler way, but is being implemented
                    //       in this manner to allow for possible future port line number
                    //       information being available in the file
                    List <int> outPortLineIndexes = new List <int>();
                    var        outputs            = obj["Outputs"];
                    int        outputLineIndex    = 0;
                    foreach (var output in outputs)
                    {
                        outPortLineIndexes.Add(outputLineIndex++);
                    }

                    codeBlockNode.SetErrorStatePortData(inPortNames, outPortLineIndexes);
                }
            }
            else if (typeof(DSFunctionBase).IsAssignableFrom(type))
            {
                var    mangledName        = obj["FunctionSignature"].Value <string>();
                var    priorNames         = libraryServices.GetPriorNames();
                var    functionDescriptor = libraryServices.GetFunctionDescriptor(mangledName);
                string newName;

                // Update the function descriptor if a newer migrated version of the node exists
                if (priorNames.TryGetValue(mangledName, out newName))
                {
                    functionDescriptor = libraryServices.GetFunctionDescriptor(newName);
                }

                // Use the functionDescriptor to try and restore the proper node if possible
                if (functionDescriptor == null)
                {
                    node = CreateDummyNode(obj, assemblyLocation, inPorts, outPorts);
                }
                else
                {
                    if (type == typeof(DSVarArgFunction))
                    {
                        node = new DSVarArgFunction(functionDescriptor);
                        // The node syncs with the function definition.
                        // Then we need to make the inport count correct
                        var varg = (DSVarArgFunction)node;
                        varg.VarInputController.SetNumInputs(inPorts.Count());
                    }
                    else if (type == typeof(DSFunction))
                    {
                        node = new DSFunction(functionDescriptor);
                    }
                }
            }
            else if (type == typeof(DSVarArgFunction))
            {
                var functionId = Guid.Parse(obj["FunctionSignature"].Value <string>());
                node = manager.CreateCustomNodeInstance(functionId);
            }
            else if (type.ToString() == "CoreNodeModels.Formula")
            {
                node = (NodeModel)obj.ToObject(type);
            }
            else
            {
                node = (NodeModel)obj.ToObject(type);

                // if node is an customNode input symbol - assign the element resolver.
                if (node is Nodes.CustomNodes.Symbol)
                {
                    (node as Nodes.CustomNodes.Symbol).ElementResolver = ElementResolver;
                }
                // We don't need to remap ports for any nodes with json constructors which pass ports
                remapPorts = false;
            }

            if (remapPorts)
            {
                RemapPorts(node, inPorts, outPorts, resolver, manager.AsLogger());
            }


            // Cannot set Lacing directly as property is protected
            node.UpdateValue(new UpdateValueParams("ArgumentLacing", replication));
            node.GUID = guid;

            // Add references to the node and the ports to the reference resolver,
            // so that they are available for entities which are deserialized later.
            serializer.ReferenceResolver.AddReference(serializer.Context, node.GUID.ToString(), node);

            foreach (var p in node.InPorts)
            {
                serializer.ReferenceResolver.AddReference(serializer.Context, p.GUID.ToString(), p);
            }

            foreach (var p in node.OutPorts)
            {
                serializer.ReferenceResolver.AddReference(serializer.Context, p.GUID.ToString(), p);
            }

            return(node);
        }
Beispiel #51
0
 /// <summary>
 /// Deserializes the JSON representation of the object.
 /// </summary>
 /// <param name="reader">The <see cref="T: Newtonsoft.Json.JsonReader" /> to read from.</param>
 /// <returns>The object Value.</returns>
 internal static HttpRouteMatchRule Deserialize(JsonReader reader)
 {
     return(reader.Deserialize(GetFromJsonProperties));
 }
Beispiel #52
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            OrderDetail order = new OrderDetail();

            while (reader.Read())
            {
                if (reader.Value != null)
                {
                    int testInt;
                    switch (reader.Value.ToString())
                    {
                    case "AccountAlias":
                        if (reader.Read() && reader.Value != null)
                        {
                            order.AccountAlias = reader.Value.ToString();
                        }
                        break;

                    case "AccountID":
                        if (reader.Read() && reader.Value != null)
                        {
                            order.AccountKey = reader.Value.ToString();
                        }
                        break;

                    case "AdvancedOptions":
                        if (reader.Read() && reader.Value != null)
                        {
                            order.AdvancedOptions = reader.Value.ToString();
                        }
                        break;

                    case "AssetType":
                        AssetType assetType;
                        if (reader.Read() && reader.Value != null && Enum.TryParse(reader.Value.ToString(), out assetType))
                        {
                            order.AssetType = assetType;
                        }
                        break;

                    case "CommissionFee":
                        if (reader.Read() && reader.Value != null)
                        {
                            order.CommissionFee = decimal.Parse(reader.Value.ToString());
                        }
                        break;

                    case "ContractExpireDate":
                        if (reader.Read() && reader.Value != null)
                        {
                            order.ContractExpireDate = reader.Value.ToString();
                        }
                        break;

                    case "ConversionRate":
                        decimal testDecimal;
                        if (reader.Read() && reader.Value != null && decimal.TryParse(reader.Value.ToString(), out testDecimal))
                        {
                            order.ConversionRate = testDecimal;
                        }
                        break;

                    case "Country":
                        if (reader.Read() && reader.Value != null && !string.IsNullOrEmpty(reader.Value.ToString()))
                        {
                            order.Country = reader.Value.ToString();
                        }
                        break;

                    case "Denomination":
                        Currency denomination;
                        if (reader.Read() && reader.Value != null && Enum.TryParse(reader.Value.ToString(), out denomination))
                        {
                            order.Denomination = denomination;
                        }
                        break;

                    case "Duration":
                        if (reader.Read() && reader.Value != null && !string.IsNullOrEmpty(reader.Value.ToString()))
                        {
                            order.Duration = new OrderDuration(reader.Value.ToString());
                        }
                        break;

                    case "ExecuteQuantity":
                        if (reader.Read() && reader.Value != null && int.TryParse(reader.Value.ToString(), out testInt))
                        {
                            order.ExecuteQuantity = testInt;
                        }
                        break;

                    case "FilledCanceled":
                        if (reader.Read() && reader.Value != null)
                        {
                            order.FilledCanceled = reader.Value.ToString();
                        }
                        break;

                    case "FilledPriceText":
                        if (reader.Read() && reader.Value != null)
                        {
                            order.FilledPriceText = reader.Value.ToString();
                        }
                        break;

                    case "GroupName":
                        if (reader.Read() && reader.Value != null)
                        {
                            order.GroupName = reader.Value.ToString();
                        }
                        break;

                    case "Legs":

                        if (reader.Read() && reader.TokenType == JsonToken.StartArray)
                        {
                            //	order.Legs.AddRange((List<Leg>)JsonConvert.DeserializeObject<List<Leg>>(reader.Value.ToString()));
                            StringWriter sw = new StringWriter();

                            JsonTextWriter jw = new JsonTextWriter(sw);
                            jw.WriteStartArray();

                            do
                            {
                                reader.Read();
                                jw.WriteToken(reader);
                            } while (reader.TokenType != JsonToken.EndArray);
                            order.Legs.AddRange(JsonConvert.DeserializeObject <List <Leg> >(sw.ToString()));
                        }
                        break;

                    case "LimitPriceText":
                        if (reader.Read() && reader.Value != null)
                        {
                            order.LimitPriceText = reader.Value.ToString();
                        }
                        break;

                    case "OrderID":
                        if (reader.Read() && reader.Value != null && int.TryParse(reader.Value.ToString(), out testInt))
                        {
                            order.OrderId = testInt;
                        }
                        break;

                    case "Originator":
                        if (reader.Read() && reader.Value != null && int.TryParse(reader.Value.ToString(), out testInt))
                        {
                            order.Originator = testInt;
                        }
                        break;

                    case "Quantity":
                        if (reader.Read() && reader.Value != null && int.TryParse(reader.Value.ToString(), out testInt))
                        {
                            order.Quantity = testInt;
                        }
                        break;

                    case "QuantityLeft":
                        if (reader.Read() && reader.Value != null && int.TryParse(reader.Value.ToString(), out testInt))
                        {
                            order.QuantityLeft = testInt;
                        }
                        break;

                    case "RejectReason":
                        if (reader.Read() && reader.Value != null)
                        {
                            order.RejectReason = reader.Value.ToString();
                        }
                        break;

                    case "Routing":
                        Route route;
                        if (reader.Read() && reader.Value != null && Enum.TryParse(reader.Value.ToString(), out route))
                        {
                            order.Route = route;
                        }
                        break;

                    case "Spread":
                        if (reader.Read() && reader.Value != null)
                        {
                            order.Spread = reader.Value.ToString();
                        }
                        break;

                    case "Status":
                        if (reader.Read() && reader.Value != null)
                        {
                            order.Status = (OrderState)Enum.Parse(typeof(OrderState), reader.Value.ToString());
                        }
                        break;

                    case "StatusDescription":
                        if (reader.Read() && reader.Value != null)
                        {
                            order.StatusDescription = reader.Value.ToString();
                        }
                        break;

                    case "StopPriceText":
                        if (reader.Read() && reader.Value != null)
                        {
                            order.StopPriceText = reader.Value.ToString();
                        }
                        break;

                    case "Symbol":
                        if (reader.Read() && reader.Value != null)
                        {
                            order.Symbol = reader.Value.ToString();
                        }
                        break;

                    case "TimeStamp":
                        if (reader.Read() && reader.Value != null)
                        {
                            order.TimeStamp = DateTime.Parse(reader.Value.ToString());
                        }
                        break;

                    case "TriggeredBy":
                        if (reader.Read() && reader.Value != null)
                        {
                            order.TriggeredBy = reader.Value.ToString();
                        }
                        break;

                    case "Type":
                        if (reader.Read() && reader.Value != null)
                        {
                            StringBuilder action = new StringBuilder(255);
                            string[]      fields = reader.Value.ToString().Split(' ');
                            foreach (string field in fields)
                            {
                                if (!string.IsNullOrEmpty(field))
                                {
                                    action.Append(Char.ToUpper(field[0]) + field.Substring(1).ToLower());
                                }
                            }
                            order.TradeAction = (TradeAction)Enum.Parse(typeof(TradeAction), action.ToString());
                        }

                        break;

                    default:
                        reader.Read();
                        break;
                    }
                }
                else
                {
                    break;
                }
            }

            return(order);
        }
Beispiel #53
0
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) =>
 serializer.Deserialize <PoseModel>(reader)?.ToPose();
Beispiel #54
0
 /// <summary>
 /// Reads in JSON written by this converter. Currently not implemented.
 /// </summary>
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     throw new NotImplementedException("Stack de-serialization is not implemented.");
 }
Beispiel #55
0
        public IProperty Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
        {
            var arraySegment = reader.ReadNextBlockSegment();

            var    segmentReader = new JsonReader(arraySegment.Array, arraySegment.Offset);
            var    count         = 0;
            string typeString    = null;
            var    type          = FieldType.None;

            while (segmentReader.ReadIsInObject(ref count))
            {
                var propertyName = segmentReader.ReadPropertyNameSegmentRaw();
                if (AutomataDictionary.TryGetValue(propertyName, out var value))
                {
                    switch (value)
                    {
                    case 0:
                        typeString = segmentReader.ReadString();
                        type       = typeString.ToEnum <FieldType>().GetValueOrDefault(type);
                        break;

                    case 1:
                        if (type == FieldType.None)
                        {
                            type = FieldType.Object;
                        }

                        segmentReader.ReadNextBlock();
                        break;
                    }

                    // explicit type has been set
                    if (value == 0)
                    {
                        break;
                    }
                }
                else
                {
                    segmentReader.ReadNextBlock();
                }
            }

            segmentReader = new JsonReader(arraySegment.Array, arraySegment.Offset);

            switch (type)
            {
            case FieldType.Text: return(Deserialize <TextProperty>(ref segmentReader, formatterResolver));

            case FieldType.Keyword: return(Deserialize <KeywordProperty>(ref segmentReader, formatterResolver));

            case FieldType.Float:
            case FieldType.Double:
            case FieldType.Byte:
            case FieldType.Short:
            case FieldType.Integer:
            case FieldType.Long:
            case FieldType.ScaledFloat:
            case FieldType.HalfFloat:
                var numberProperty = Deserialize <NumberProperty>(ref segmentReader, formatterResolver);
                ((IProperty)numberProperty).Type = typeString;
                return(numberProperty);

            case FieldType.Date: return(Deserialize <DateProperty>(ref segmentReader, formatterResolver));

            case FieldType.Boolean: return(Deserialize <BooleanProperty>(ref segmentReader, formatterResolver));

            case FieldType.Binary: return(Deserialize <BinaryProperty>(ref segmentReader, formatterResolver));

            case FieldType.Object: return(Deserialize <ObjectProperty>(ref segmentReader, formatterResolver));

            case FieldType.Nested: return(Deserialize <NestedProperty>(ref segmentReader, formatterResolver));

            case FieldType.Ip: return(Deserialize <IpProperty>(ref segmentReader, formatterResolver));

            case FieldType.GeoPoint: return(Deserialize <GeoPointProperty>(ref segmentReader, formatterResolver));

            case FieldType.GeoShape: return(Deserialize <GeoShapeProperty>(ref segmentReader, formatterResolver));

            case FieldType.Completion: return(Deserialize <CompletionProperty>(ref segmentReader, formatterResolver));

            case FieldType.TokenCount: return(Deserialize <TokenCountProperty>(ref segmentReader, formatterResolver));

            case FieldType.Murmur3Hash: return(Deserialize <Murmur3HashProperty>(ref segmentReader, formatterResolver));

            case FieldType.Percolator: return(Deserialize <PercolatorProperty>(ref segmentReader, formatterResolver));

            case FieldType.DateRange: return(Deserialize <DateRangeProperty>(ref segmentReader, formatterResolver));

            case FieldType.DoubleRange: return(Deserialize <DoubleRangeProperty>(ref segmentReader, formatterResolver));

            case FieldType.FloatRange: return(Deserialize <FloatRangeProperty>(ref segmentReader, formatterResolver));

            case FieldType.IntegerRange: return(Deserialize <IntegerRangeProperty>(ref segmentReader, formatterResolver));

            case FieldType.LongRange: return(Deserialize <LongRangeProperty>(ref segmentReader, formatterResolver));

            case FieldType.IpRange: return(Deserialize <IpRangeProperty>(ref segmentReader, formatterResolver));

            case FieldType.Join: return(Deserialize <JoinProperty>(ref segmentReader, formatterResolver));

            case FieldType.Alias: return(Deserialize <FieldAliasProperty>(ref segmentReader, formatterResolver));

            case FieldType.RankFeature: return(Deserialize <RankFeatureProperty>(ref segmentReader, formatterResolver));

            case FieldType.RankFeatures: return(Deserialize <RankFeaturesProperty>(ref segmentReader, formatterResolver));

            case FieldType.None:
                // no "type" field in the property mapping
                return(Deserialize <ObjectProperty>(ref segmentReader, formatterResolver));

            default:
                throw new ArgumentOutOfRangeException(nameof(type), type, "mapping property converter does not know this value");
            }
        }
 public JsonTag(JsonReader reader)
 {
     TokenType = reader.TokenType;
     Value     = reader.Value;
     ValueType = reader.ValueType;
 }
Beispiel #57
0
        public override Address ReadJson(JsonReader reader, Type objectType, Address existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            string s = (string)reader.Value;

            return(string.IsNullOrEmpty(s) ? null : new Address(s));
        }
Beispiel #58
0
        internal void ReadContentFrom(JsonReader r)
        {
            ValidationUtils.ArgumentNotNull(r, "r");
            IJsonLineInfo lineInfo = r as IJsonLineInfo;

            JContainer parent = this;

            do
            {
                if (parent is JProperty && ((JProperty)parent).Value != null)
                {
                    if (parent == this)
                    {
                        return;
                    }

                    parent = parent.Parent;
                }

                switch (r.TokenType)
                {
                case JsonToken.None:
                    // new reader. move to actual content
                    break;

                case JsonToken.StartArray:
                    JArray a = new JArray();
                    a.SetLineInfo(lineInfo);
                    parent.Add(a);
                    parent = a;
                    break;

                case JsonToken.EndArray:
                    if (parent == this)
                    {
                        return;
                    }

                    parent = parent.Parent;
                    break;

                case JsonToken.StartObject:
                    JObject o = new JObject();
                    o.SetLineInfo(lineInfo);
                    parent.Add(o);
                    parent = o;
                    break;

                case JsonToken.EndObject:
                    if (parent == this)
                    {
                        return;
                    }

                    parent = parent.Parent;
                    break;

                case JsonToken.StartConstructor:
                    JConstructor constructor = new JConstructor(r.Value.ToString());
                    constructor.SetLineInfo(lineInfo);
                    parent.Add(constructor);
                    parent = constructor;
                    break;

                case JsonToken.EndConstructor:
                    if (parent == this)
                    {
                        return;
                    }

                    parent = parent.Parent;
                    break;

                case JsonToken.String:
                case JsonToken.Integer:
                case JsonToken.Float:
                case JsonToken.Date:
                case JsonToken.Boolean:
                case JsonToken.Bytes:
                    JValue v = new JValue(r.Value);
                    v.SetLineInfo(lineInfo);
                    parent.Add(v);
                    break;

                case JsonToken.Comment:
                    v = JValue.CreateComment(r.Value.ToString());
                    v.SetLineInfo(lineInfo);
                    parent.Add(v);
                    break;

                case JsonToken.Null:
                    v = new JValue(null, JTokenType.Null);
                    v.SetLineInfo(lineInfo);
                    parent.Add(v);
                    break;

                case JsonToken.Undefined:
                    v = new JValue(null, JTokenType.Undefined);
                    v.SetLineInfo(lineInfo);
                    parent.Add(v);
                    break;

                case JsonToken.PropertyName:
                    string    propertyName = r.Value.ToString();
                    JProperty property     = new JProperty(propertyName);
                    property.SetLineInfo(lineInfo);
                    JObject parentObject = (JObject)parent;
                    // handle multiple properties with the same name in JSON
                    JProperty existingPropertyWithName = parentObject.Property(propertyName);
                    if (existingPropertyWithName == null)
                    {
                        parent.Add(property);
                    }
                    else
                    {
                        existingPropertyWithName.Replace(property);
                    }
                    parent = property;
                    break;

                default:
                    throw new InvalidOperationException("The JsonReader should not be on a token of type {0}.".FormatWith(CultureInfo.InvariantCulture, r.TokenType));
                }
            } while (r.Read());
        }
        /// <summary>
        /// Gets the object from Json properties.
        /// </summary>
        /// <param name="reader">The <see cref="T: Newtonsoft.Json.JsonReader" /> to read from, reader must be placed at first property.</param>
        /// <returns>The object Value.</returns>
        internal static ContainerCodePackageProperties GetFromJsonProperties(JsonReader reader)
        {
            var name  = default(string);
            var image = default(string);
            var imageRegistryCredential = default(ImageRegistryCredential);
            var entrypoint           = default(string);
            var commands             = default(IEnumerable <string>);
            var environmentVariables = default(IEnumerable <EnvironmentVariable>);
            var settings             = default(IEnumerable <Setting>);
            var labels                  = default(IEnumerable <ContainerLabel>);
            var endpoints               = default(IEnumerable <EndpointProperties>);
            var resources               = default(ResourceRequirements);
            var volumeRefs              = default(IEnumerable <VolumeReference>);
            var volumes                 = default(IEnumerable <ApplicationScopedVolume>);
            var diagnostics             = default(DiagnosticsRef);
            var reliableCollectionsRefs = default(IEnumerable <ReliableCollectionsRef>);
            var instanceView            = default(ContainerInstanceView);

            do
            {
                var propName = reader.ReadPropertyName();
                if (string.Compare("name", propName, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    name = reader.ReadValueAsString();
                }
                else if (string.Compare("image", propName, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    image = reader.ReadValueAsString();
                }
                else if (string.Compare("imageRegistryCredential", propName, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    imageRegistryCredential = ImageRegistryCredentialConverter.Deserialize(reader);
                }
                else if (string.Compare("entrypoint", propName, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    entrypoint = reader.ReadValueAsString();
                }
                else if (string.Compare("commands", propName, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    commands = reader.ReadList(JsonReaderExtensions.ReadValueAsString);
                }
                else if (string.Compare("environmentVariables", propName, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    environmentVariables = reader.ReadList(EnvironmentVariableConverter.Deserialize);
                }
                else if (string.Compare("settings", propName, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    settings = reader.ReadList(SettingConverter.Deserialize);
                }
                else if (string.Compare("labels", propName, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    labels = reader.ReadList(ContainerLabelConverter.Deserialize);
                }
                else if (string.Compare("endpoints", propName, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    endpoints = reader.ReadList(EndpointPropertiesConverter.Deserialize);
                }
                else if (string.Compare("resources", propName, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    resources = ResourceRequirementsConverter.Deserialize(reader);
                }
                else if (string.Compare("volumeRefs", propName, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    volumeRefs = reader.ReadList(VolumeReferenceConverter.Deserialize);
                }
                else if (string.Compare("volumes", propName, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    volumes = reader.ReadList(ApplicationScopedVolumeConverter.Deserialize);
                }
                else if (string.Compare("diagnostics", propName, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    diagnostics = DiagnosticsRefConverter.Deserialize(reader);
                }
                else if (string.Compare("reliableCollectionsRefs", propName, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    reliableCollectionsRefs = reader.ReadList(ReliableCollectionsRefConverter.Deserialize);
                }
                else if (string.Compare("instanceView", propName, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    instanceView = ContainerInstanceViewConverter.Deserialize(reader);
                }
                else
                {
                    reader.SkipPropertyValue();
                }
            }while (reader.TokenType != JsonToken.EndObject);

            var containerCodePackageProperties = new ContainerCodePackageProperties(
                name: name,
                image: image,
                imageRegistryCredential: imageRegistryCredential,
                entrypoint: entrypoint,
                commands: commands,
                environmentVariables: environmentVariables,
                settings: settings,
                labels: labels,
                endpoints: endpoints,
                resources: resources,
                volumeRefs: volumeRefs,
                volumes: volumes,
                diagnostics: diagnostics,
                reliableCollectionsRefs: reliableCollectionsRefs);

            containerCodePackageProperties.InstanceView = instanceView;
            return(containerCodePackageProperties);
        }
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     return(Enum.Parse(objectType, reader.Value.ToString()));
 }