Esempio n. 1
0
 public bool Equals(IJsonValue other)
 {
     if (other is JsonNumber) {
         return (double)(((JsonNumber)other).Value) == val;
     }
     return false;
 }
Esempio n. 2
0
 public bool Equals(IJsonValue other)
 {
     if (other is JsonBoolean) {
         return val == (bool)other.Value;
     }
     return false;
 }
Esempio n. 3
0
        /// <summary>
        /// Resolves a parameter value based on the provided object.
        /// </summary>
        /// <param name="descriptor">Parameter descriptor.</param>
        /// <param name="value">Value to resolve the parameter value from.</param>
        /// <returns>The parameter value.</returns>
        public virtual object ResolveParameter(ParameterDescriptor descriptor, IJsonValue value)
        {
            if (descriptor == null)
            {
                throw new ArgumentNullException("descriptor");
            }

            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            //if(descriptor.ParameterType == typeof(HubRequestMessageBase))
            //{
            //    NodeRegistration reg = new NodeRegistration();
            //    return value.ConvertTo(reg.GetType());
            //}

            //return value;

            if (value.GetType() == descriptor.ParameterType)
            {
                return value;
            }

            return value.ConvertTo(descriptor.ParameterType);
        }
        public object ConvertFromJson(IJsonValue value)
        {
            List<Location> result = null;

            if (value != null && value.ValueType == JsonValueType.String)
            {
                string valueInStr = value.GetString();
                var locationPairs = valueInStr.Split(';');
                if (locationPairs != null)
                {
                    result = new List<Location>();

                    foreach (var locationPair in locationPairs)
                    {
                        if (locationPair.Length > 0)
                        {
                            var latLong = locationPair.Split(',');

                            result.Add(new Location()
                                {
                                    Latitude = Convert.ToDouble(latLong[0]),
                                    Longitude = Convert.ToDouble(latLong[1]),
                                });
                        }
                    }
                }
            }

            return result;
        }
Esempio n. 5
0
 dynamic Convert(IJsonValue json)
 {
     dynamic obj = null;
     switch (json.ValueType)
     {
         case JsonValueType.Array:
             obj = ConvertArray(json.GetArray());
             break;
         case JsonValueType.Boolean:
             obj = json.GetBoolean();
             break;
         case JsonValueType.Null:
             obj = null;
             break;
         case JsonValueType.Number:
             obj = json.GetNumber();
             break;
         case JsonValueType.Object:
             obj = new JsonToDynamic(json.GetObject());
             break;
         case JsonValueType.String:
             obj = json.GetString();
             break;
     }
     return obj;
 }
 public object ConvertFromJson(IJsonValue value)
 {
     string text = value.AsString();
     return text != null ?
         new Uri(text) :
         null;
 }
 private void WriteJsonValue(JsonWriter writer, IJsonValue value)
 {
     switch (value.ValueType)
     {
         case JsonValueType.Array:
         {
             JsonArray a = value.GetArray();
             writer.WriteStartArray();
             for (int i = 0; i < a.Count; i++)
             {
                 WriteJsonValue(writer, a[i]);
             }
             writer.WriteEndArray();
         }
             break;
         case JsonValueType.Boolean:
         {
             writer.WriteValue(value.GetBoolean());
         }
             break;
         case JsonValueType.Null:
         {
             writer.WriteNull();
         }
             break;
         case JsonValueType.Number:
         {
             // JsonValue doesn't support integers
             // serialize whole numbers without a decimal point
             double d = value.GetNumber();
             bool isInteger = (d % 1 == 0);
             if (isInteger && d <= long.MaxValue && d >= long.MinValue)
                 writer.WriteValue(Convert.ToInt64(d));
             else
                 writer.WriteValue(d);
         }
             break;
         case JsonValueType.Object:
         {
             JsonObject o = value.GetObject();
             writer.WriteStartObject();
             foreach (KeyValuePair<string, IJsonValue> v in o)
             {
                 writer.WritePropertyName(v.Key);
                 WriteJsonValue(writer, v.Value);
             }
             writer.WriteEndObject();
         }
             break;
         case JsonValueType.String:
         {
             writer.WriteValue(value.GetString());
         }
             break;
         default:
             throw new ArgumentOutOfRangeException("ValueType");
     }
 }
 public ServiceCommand(IServiceCommandProcessor service, string uri, IJsonValue payload, ResponseListener listener)
 {
     Service = service;
     Target = uri;
     Payload = payload;
     RequestId = -1;
     HttpMethod = "request";
     responseListener = listener;
 }
Esempio n. 9
0
        /// <summary>
        /// Resolves a parameter value based on the provided object.
        /// </summary>
        /// <param name="descriptor">Parameter descriptor.</param>
        /// <param name="value">Value to resolve the parameter value from.</param>
        /// <returns>The parameter value.</returns>
        public virtual object ResolveParameter(ParameterDescriptor descriptor, IJsonValue value)
        {
            if (value.GetType() == descriptor.Type)
            {
                return value;
            }

            return value.ConvertTo(descriptor.Type);
        }
Esempio n. 10
0
 public IEnumerable<IJsonValue> Evaluate(IJsonValue obj)
 {
     if (obj == null)
     {
         return null;
     }
     IEnumerable<IJsonValue> values = new[] {obj};
     return _evaluators.Aggregate(values,
                                  (current, evaluator) => evaluator.Evaluate(current).Where(v => v != null));
 }
Esempio n. 11
0
        private bool Matches(IJsonValue filter, IJsonValue value)
        {
            if ((filter == null) || (value == null))
            {
                return filter == value;
            }

            var comparer = filter.Visit(new CreateFilterComparerVisitor());
            return value.Visit(comparer);
        }
Esempio n. 12
0
 public static JsonArray GetJsonArrayFromJsonObj(IJsonValue obj,string propertyName)
 {
     try
     {
         return obj.GetObject()[propertyName].GetArray();
     }
     catch(Exception)
     {
         return null;
     }
 }
Esempio n. 13
0
 public static double? GetNullableNumberFromJsonObj(IJsonValue obj, string propertyName, double? defaultValue = null)
 {
     try
     {
         return obj.GetObject()[propertyName].GetNumber();
     }
     catch (Exception)
     {
         return defaultValue;
     }
 }
Esempio n. 14
0
 public static bool GetBooleanFromJsonObj(IJsonValue obj, string propertyName,bool defaultValue = false)
 {
     try
     {
         return obj.GetObject()[propertyName].GetBoolean();
     }
     catch (Exception)
     {
         return defaultValue;
     }
 }
Esempio n. 15
0
 public HttpJsonContent(IJsonValue jsonValue)
 {
     if (jsonValue == null)
     {
         throw new ArgumentException("jsonValue cannot be null.");
     }
     this.jsonValue = jsonValue;
     headers = new HttpContentHeaderCollection();
     headers.ContentType = new HttpMediaTypeHeaderValue("application/json");
     headers.ContentType.CharSet = "UTF-8";
 }
 private void WriteJsonValue(JsonWriter writer, IJsonValue value)
 {
   switch (value.ValueType)
   {
     case JsonValueType.Array:
       {
         JsonArray a = value.GetArray();
         writer.WriteStartArray();
         for (int i = 0; i < a.Count; i++)
         {
           WriteJsonValue(writer, a[i]);
         }
         writer.WriteEndArray();
       }
       break;
     case JsonValueType.Boolean:
       {
         writer.WriteValue(value.GetBoolean());
       }
       break;
     case JsonValueType.Null:
       {
         writer.WriteNull();
       }
       break;
     case JsonValueType.Number:
       {
         writer.WriteValue(value.GetNumber());
       }
       break;
     case JsonValueType.Object:
       {
         JsonObject o = value.GetObject();
         writer.WriteStartObject();
         foreach (KeyValuePair<string, IJsonValue> v in o)
         {
           writer.WritePropertyName(v.Key);
           WriteJsonValue(writer, v.Value);
         }
         writer.WriteEndObject();
       }
       break;
     case JsonValueType.String:
       {
         writer.WriteValue(value.GetString());
       }
       break;
     default:
       throw new ArgumentOutOfRangeException("ValueType");
   }
 }
        public void Deserialize(IJsonValue value)
        {
            // Get the ID and Age properties
            MobileServiceTableSerializer.Deserialize(value, this, true);

            if (Title != null)
            {
                string[] parts = Title.Split(':');
                if (parts.Length == 2)
                {
                    Tag = parts[0];
                    Title = parts[1].Trim();
                }
            }
        }
        private static object _jsonDeserialize_convert(IJsonValue json)
        {
            object obj = null;
            switch (json.ValueType)
            {
                case JsonValueType.Array:
                    JsonArray jsonArray = json.GetArray();
                    object[] objArray = new object[jsonArray.Count];
                    for (int i1 = 0; i1 < jsonArray.Count; i1++)
                    {
                        objArray[i1] = _jsonDeserialize_convert(jsonArray[i1]);
                    }
                    obj = objArray;
                    break;
                case JsonValueType.Boolean:
                    obj = json.GetBoolean();
                    break;
                case JsonValueType.Null:
                    obj = null;
                    break;
                case JsonValueType.Number:
                    obj = json.GetNumber();
                    break;
                case JsonValueType.Object:
                    JsonObject jsonObject = json.GetObject();

                    Dictionary<string, object> d = new Dictionary<string, object>();

                    List<string> keys = new List<string>();
                    foreach (var key in jsonObject.Keys)
                    {
                        keys.Add(key);
                    }

                    int i2 = 0;
                    foreach (var item in jsonObject.Values)
                    {
                        d.Add(keys[i2], _jsonDeserialize_convert(item));
                        i2++;
                    }
                    obj = d;
                    break;
                case JsonValueType.String:
                    obj = json.GetString();
                    break;
            }
            return obj;
        }
Esempio n. 19
0
        // JsonArray extensions.
        public static bool ContainsStringValue(this JsonArray jsonArray, string value, out IJsonValue selectedValue)
        {
            selectedValue = null;

            foreach (IJsonValue jsonValue in jsonArray)
            {
                if (jsonValue.ValueType == JsonValueType.String)
                {
                    string currentValue = jsonValue.GetString();
                    if (String.Compare(value, currentValue, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        selectedValue = jsonValue;
                        return true;
                    }
                }
            }

            return false;
        }
        /// <summary>
        /// Resolves a parameter value based on the provided object.
        /// </summary>
        /// <param name="descriptor">Parameter descriptor.</param>
        /// <param name="value">Value to resolve the parameter value from.</param>
        /// <returns>The parameter value.</returns>
        public virtual object ResolveParameter(ParameterDescriptor descriptor, IJsonValue value)
        {
            if (descriptor == null)
            {
                throw new ArgumentNullException("descriptor");
            }

            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            if (value.GetType() == descriptor.ParameterType)
            {
                return value;
            }

            return value.ConvertTo(descriptor.ParameterType);
        }
        private static string BuildHubExecutableMethodCacheKey(HubDescriptor hub, string method, IJsonValue[] parameters)
        {
            string normalizedParameterCountKeyPart;

            if (parameters != null)
            {
                normalizedParameterCountKeyPart = parameters.Length.ToString(CultureInfo.InvariantCulture);
            }
            else
            {
                // NOTE: we normailize a null parameter array to be the same as an empty (i.e. Length == 0) parameter array
                normalizedParameterCountKeyPart = "0";
            }

            // NOTE: we always normalize to all uppercase since method names are case insensitive and could theoretically come in diff. variations per call
            string normalizedMethodName = method.ToUpperInvariant();

            string methodKey = hub.Name + "::" + normalizedMethodName + "(" + normalizedParameterCountKeyPart + ")";

            return methodKey;
        }
        /// <summary>
        /// Resolves a parameter value based on the provided object.
        /// </summary>
        /// <param name="descriptor">Parameter descriptor.</param>
        /// <param name="value">Value to resolve the parameter value from.</param>
        /// <returns>The parameter value.</returns>
        public virtual object ResolveParameter(ParameterDescriptor descriptor, IJsonValue value)
        {
            if (descriptor == null)
            {
                throw new ArgumentNullException("descriptor");
            }

            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            if (_provider.HasPayload(descriptor.ParameterType))
            {
                return _decompressor.Decompress(value.ConvertTo(typeof(object[])), descriptor.ParameterType);
            }
            else
            {
                return value.ConvertTo(descriptor.ParameterType);
            }
        }
        public object ConvertFromJson(IJsonValue value)
        {
            List<DateTime> result = null;

            if (value != null && value.ValueType == JsonValueType.String)
            {
                string valueInStr = value.GetString();
                var checkIns = valueInStr.Split(';');
                if (checkIns != null)
                {
                    result = new List<DateTime>();

                    foreach (var checkIn in checkIns)
                    {
                        result.Add(Convert.ToDateTime(checkIn));
                    }
                }
            }

            return result;
        }
Esempio n. 24
0
 /// <summary>
 /// Usage : 
 /// like    var token = JsonParser.GetStringFromJsonObj(json, "token");
 /// </summary>
 /// <param name="obj"></param>
 /// <param name="propertyName"></param>
 /// <returns></returns>
 public static string GetStringFromJsonObj(IJsonValue obj,string propertyName,string defaultValue=null)
 {
     try
     {
         if (obj.GetObject()[propertyName].ValueType == JsonValueType.String)
         {
             return obj.GetObject()[propertyName].GetString();
         }
         else if (obj.GetObject()[propertyName].ValueType == JsonValueType.Number)
         {
             return obj.GetObject()[propertyName].GetNumber().ToString();
         }
         else if (obj.GetObject()[propertyName].ValueType == JsonValueType.Boolean)
         {
             return obj.GetObject()[propertyName].GetBoolean() ? "true" : "false";
         }
         else throw new Exception();
     }
     catch(Exception)
     {
         return defaultValue;
     }
 }
 public virtual float?ValueFromObject(IJsonValue @object, float scale)
 {
     return(JsonUtils.ValueFromObject(@object) * scale);
 }
Esempio n. 26
0
 private static bool ShouldApplyDefaultValue(IField field, IJsonValue value)
 {
     return(value.Type == JsonValueType.Null || (field is IField <StringFieldProperties> && value is JsonScalar <string> s && string.IsNullOrEmpty(s.Value)));
 }
Esempio n. 27
0
        private void WriteJsonValue(JsonWriter writer, IJsonValue value)
        {
            switch (value.ValueType)
            {
            case JsonValueType.Array:
            {
                JsonArray a = value.GetArray();
                writer.WriteStartArray();
                for (int i = 0; i < a.Count; i++)
                {
                    WriteJsonValue(writer, a[i]);
                }
                writer.WriteEndArray();
            }
            break;

            case JsonValueType.Boolean:
            {
                writer.WriteValue(value.GetBoolean());
            }
            break;

            case JsonValueType.Null:
            {
                writer.WriteNull();
            }
            break;

            case JsonValueType.Number:
            {
                // JsonValue doesn't support integers
                // serialize whole numbers without a decimal point
                double d         = value.GetNumber();
                bool   isInteger = (d % 1 == 0);
                if (isInteger && d <= long.MaxValue && d >= long.MinValue)
                {
                    writer.WriteValue(Convert.ToInt64(d));
                }
                else
                {
                    writer.WriteValue(d);
                }
            }
            break;

            case JsonValueType.Object:
            {
                JsonObject o = value.GetObject();
                writer.WriteStartObject();
                foreach (KeyValuePair <string, IJsonValue> v in o)
                {
                    writer.WritePropertyName(v.Key);
                    WriteJsonValue(writer, v.Value);
                }
                writer.WriteEndObject();
            }
            break;

            case JsonValueType.String:
            {
                writer.WriteValue(value.GetString());
            }
            break;

            default:
                throw new ArgumentOutOfRangeException("ValueType");
            }
        }
Esempio n. 28
0
 public JsonArray Add(IJsonValue value)
 {
     this.Values.Add(value);
     return(this);
 }
Esempio n. 29
0
        public TopicViewModel(IJsonValue t) : base(t)
        {
            JsonObject token = t.GetObject();

            commentnum = token["commentnum"].ToString().Replace("\"", string.Empty);
        }
Esempio n. 30
0
        public async Task <IReadOnlyList <IEnrichedAssetEntity> > GetReferencedAssetsAsync(IJsonValue value)
        {
            var ids = ParseIds(value);

            if (ids == null)
            {
                return(EmptyAssets);
            }

            var dataLoader = GetAssetsLoader();

            return(await dataLoader.LoadManyAsync(ids));
        }
        /// <summary>
        /// Throw an exception for an invalid response to a web request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="response">The response.</param>
        /// <param name="body">The body of the response as JSON.</param>
        private static void ThrowInvalidResponse(IServiceFilterRequest request, IServiceFilterResponse response, IJsonValue body)
        {
            Debug.Assert(request != null, "request cannot be null!");
            Debug.Assert(response != null, "response cannot be null!");
            Debug.Assert(
                response.ResponseStatus != ServiceFilterResponseStatus.Success ||
                response.StatusCode >= 400,
                "response should be failing!");

            // Create either an invalid response or connection failed message
            // (check the status code first because some status codes will
            // set a protocol ErrorStatus).
            string message = null;

            if (response.StatusCode >= 400)
            {
                // Get the error message, but default to the status message
                // if there's no error message present.
                string error =
                    body.Get("error").AsString() ??
                    body.Get("description").AsString() ??
                    response.StatusDescription;

                // Get the status code, text
                int code = body.Get("code").AsInteger() ?? response.StatusCode;

                // Combine the pieces and throw the exception
                message =
                    string.Format(CultureInfo.InvariantCulture,
                                  Resources.MobileServiceClient_ThrowInvalidResponse_ErrorMessage,
                                  code,
                                  (HttpStatusCode)code,
                                  error,
                                  response.Content);
            }
            else
            {
                message = string.Format(
                    CultureInfo.InvariantCulture,
                    Resources.MobileServiceClient_ThrowConnectionFailure_ErrorMessage,
                    response.ResponseStatus);
            }

            // Combine the pieces and throw the exception
            throw CreateMobileServiceException(message, request, response);
        }
Esempio n. 32
0
 public bool Equals(IJsonValue other)
 {
     // Going by JavaScript rules here. We don't know if they want
     // deep or shallow compare, so do neither
     return false;
 }
Esempio n. 33
0
 public Args(IJsonValue value)
 {
     Value = value;
 }
Esempio n. 34
0
 public void TestIJsonNodeConstructorDoesNotThrowExceptionOnValidValue()
 {
     IJsonValue jsonValue = this.GetJsonValueInstance(this.JsonNodeA);
 }
Esempio n. 35
0
 public void TestStringConstructorDoesNotThrowExceptionOnValidValue()
 {
     IJsonValue jsonValue = this.GetJsonValueInstance(this.StringValueA);
 }
Esempio n. 36
0
        public void TestIsNodeMethodReturnsFalseStringValue()
        {
            IJsonValue jsonValue = this.GetJsonValueInstance(this.StringValueA);

            Assert.IsFalse(jsonValue.IsNode());
        }
Esempio n. 37
0
        public void TestIsStringMethodReturnsFalseNodeValue()
        {
            IJsonValue jsonValue = this.GetJsonValueInstance(this.JsonNodeA);

            Assert.IsFalse(jsonValue.IsString());
        }
Esempio n. 38
0
 public void Emit(string eventName, IJsonValue args, AckCallback ackCallback)
 {
     rootNamespace.Emit(eventName, args, ackCallback);
 }
Esempio n. 39
0
        private static bool TryParseDateTime(List <string> errors, PropertyPath path, IJsonValue value, out Instant result)
        {
            result = default;

            if (value is JsonString jsonString)
            {
                foreach (var pattern in InstantPatterns)
                {
                    var parsed = pattern.Parse(jsonString.Value);

                    if (parsed.Success)
                    {
                        result = parsed.Value;

                        return(true);
                    }
                }

                errors.Add($"Expected ISO8601 DateTime String for path '{path}', but got invalid String.");
            }
            else
            {
                errors.Add($"Expected ISO8601 DateTime String for path '{path}', but got {value.Type}.");
            }

            return(false);
        }
Esempio n. 40
0
 public Task SetAsync(Guid appId, string?userId, string path, IJsonValue value)
 {
     return(GetGrain(appId, userId).SetAsync(path, value.AsJ()));
 }
Esempio n. 41
0
 public static bool TryGetByPath(this IJsonValue value, string?path, [MaybeNullWhen(false)] out IJsonValue result)
 {
     return(TryGetByPath(value, path?.Split(PathSeparators, StringSplitOptions.RemoveEmptyEntries), out result !));
 }
Esempio n. 42
0
        public static bool TryGetByPath(this IJsonValue?value, IEnumerable <string>?path, [MaybeNullWhen(false)] out IJsonValue result)
        {
            result = value !;

            if (path != null)
            {
                foreach (var pathSegment in path)
                {
                    if (result == null || !result.TryGet(pathSegment, out result !))
                    {
                        break;
                    }
                }
            }

            return(result != null && !ReferenceEquals(result, value));
        }
Esempio n. 43
0
        public async Task <IReadOnlyList <IContentEntity> > GetReferencedContentsAsync(Guid schemaId, IJsonValue value)
        {
            var ids = ParseIds(value);

            if (ids == null)
            {
                return(EmptyContents);
            }

            var dataLoader = GetContentsLoader(schemaId);

            return(await dataLoader.LoadManyAsync(ids));
        }
        void ICustomMobileServiceTableSerialization.Deserialize(IJsonValue value)
        {
            int? id = value.Get("id").AsInteger();
            if (id != null)
            {
                Id = id.Value;
            }

            Name = value.Get("name").AsString();

            JsonArray children = value.Get("children").AsArray();
            if (children != null)
            {
                Children.AddRange(children.Select(MobileServiceTableSerializer.Deserialize<SimpleTree>));
            }
        }
Esempio n. 45
0
            public Args(IJsonValue value, HashSet <DomainId> validIds)
            {
                Value = value;

                ValidIds = validIds;
            }
Esempio n. 46
0
        public FeedViewModelBase(IJsonValue t) : base(t)
        {
            JsonObject token = t.GetObject();

            if (token.TryGetValue("info", out IJsonValue value1))
            {
                info = value1.GetString();
            }
            likenum   = token["likenum"].ToString().Replace("\"", string.Empty);
            replynum  = token["replynum"].ToString().Replace("\"", string.Empty);
            share_num = token["forwardnum"].ToString().Replace("\"", string.Empty);
            if (token["entityType"].GetString() != "article")
            {
                showSourceFeedGrid = !string.IsNullOrEmpty(token["source_id"]?.GetString());
                if (showSourceFeedGrid)
                {
                    showSourceFeed = token.TryGetValue("forwardSourceFeed", out IJsonValue jsonValue) &&
                                     jsonValue != null &&
                                     jsonValue.ToString() != "null";
                    if (showSourceFeed)
                    {
                        sourceFeed = new SourceFeedViewModel(jsonValue.GetObject());
                    }
                }
                if (token["feedType"].GetString() == "question")
                {
                    isQuestionFeed      = true;
                    question_answer_num = token["question_answer_num"].ToString().Replace("\"", string.Empty);
                    question_follow_num = token["question_follow_num"].ToString().Replace("\"", string.Empty);
                }
                showUser = true;
                if (!string.IsNullOrEmpty(token["userInfo"].GetObject()["userSmallAvatar"].GetString()))
                {
                    userSmallAvatar = new BitmapImage(new Uri(token["userInfo"].GetObject()["userSmallAvatar"].GetString()));
                }
                showExtra_url = token.TryGetValue("extra_title", out IJsonValue valueextra_title) && !string.IsNullOrEmpty(valueextra_title.GetString());
                if (showExtra_url)
                {
                    extra_title = valueextra_title.GetString();
                    extra_url   = token["extra_url"].GetString();
                    if (!string.IsNullOrEmpty(extra_url))
                    {
                        if (extra_url.IndexOf("http") == 0)
                        {
                            extra_url2 = new Uri(extra_url).Host;
                        }
                        else
                        {
                            extra_url2 = string.Empty;
                        }
                    }
                    else
                    {
                        extra_url2 = string.Empty;
                    }
                    if (!string.IsNullOrEmpty(token["extra_pic"].GetString()))
                    {
                        extra_pic = new BitmapImage(new Uri(token["extra_pic"].GetString()));
                    }
                }
                device_title = token["device_title"].GetString();
            }
        }
Esempio n. 47
0
        private IJsonValue CreateJsonValue(JsonReader reader)
        {
            while (reader.TokenType == JsonToken.Comment)
            {
                if (!reader.Read())
                {
                    throw JsonSerializationException.Create(reader, "Unexpected end.");
                }
            }

            switch (reader.TokenType)
            {
            case JsonToken.StartObject:
            {
                return(CreateJsonObject(reader));
            }

            case JsonToken.StartArray:
            {
                JsonArray a = new JsonArray();

                while (reader.Read())
                {
                    switch (reader.TokenType)
                    {
                    case JsonToken.EndArray:
                        return(a);

                    default:
                        IJsonValue value = CreateJsonValue(reader);
                        a.Add(value);
                        break;
                    }
                }
            }
            break;

            case JsonToken.Integer:
            case JsonToken.Float:
                return(JsonValue.CreateNumberValue(Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture)));

            case JsonToken.String:
                return(JsonValue.CreateStringValue(reader.Value.ToString()));

            case JsonToken.Boolean:
                return(JsonValue.CreateBooleanValue(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture)));

            case JsonToken.Null:
                // surely there is a better way to create a null value than this?
                return(JsonValue.Parse("null"));

            case JsonToken.Date:
                return(JsonValue.CreateStringValue(reader.Value.ToString()));

            case JsonToken.Bytes:
                return(JsonValue.CreateStringValue(reader.Value.ToString()));

            default:
                throw JsonSerializationException.Create(reader, "Unexpected or unsupported token: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
            }

            throw JsonSerializationException.Create(reader, "Unexpected end.");
        }
Esempio n. 48
0
 public static TObject ToObject <TObject>(this IJsonValue value)
 {
     return((TObject)value.ToObject(typeof(TObject)));
 }
Esempio n. 49
0
 public object ConvertFromJson(IJsonValue value)
 {
     // unused
     return null;
 }
        /// <summary>
        /// Throw an exception for an invalid response to a web request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="response">The response.</param>
        /// <param name="body">The body of the response as JSON.</param>
        private static void ThrowInvalidResponse(IServiceFilterRequest request, IServiceFilterResponse response, IJsonValue body)
        {
            Debug.Assert(request != null, "request cannot be null!");
            Debug.Assert(response != null, "response cannot be null!");
            Debug.Assert(
                response.ResponseStatus != ServiceFilterResponseStatus.Success ||
                    response.StatusCode >= 400,
                "response should be failing!");

            // Create either an invalid response or connection failed message
            // (check the status code first because some status codes will
            // set a protocol ErrorStatus).
            string message = null;
            if (response.StatusCode >= 400)
            {
                if (body != null)
                {
                    if (body.ValueType == JsonValueType.String)
                    {
                        // User scripts might return errors with just a plain string message as the
                        // body content, so use it as the exception message
                        message = body.GetString();
                    }
                    else if (body.ValueType == JsonValueType.Object)
                    {
                        // Get the error message, but default to the status description
                        // below if there's no error message present.
                        message = body.Get("error").AsString() ??
                                  body.Get("description").AsString();
                    }
                }
                
                if (string.IsNullOrWhiteSpace(message))
                {
                    message = string.Format(
                        CultureInfo.InvariantCulture,
                        Resources.MobileServiceClient_ErrorMessage,
                        response.StatusDescription);
                }
            }
            else
            {
                message = string.Format(
                    CultureInfo.InvariantCulture,
                    Resources.MobileServiceClient_ErrorMessage,
                    response.ResponseStatus);
            }

            // Combine the pieces and throw the exception
            throw CreateMobileServiceException(message, request, response);
        }
Esempio n. 51
0
 public Args(IJsonValue value, HashSet <DomainId> result, int take)
 {
     Value       = value;
     Result      = result;
     ResultLimit = take;
 }
Esempio n. 52
0
            public Args(IJsonValue value, IJsonSerializer jsonSerializer)
            {
                Value = value;

                JsonSerializer = jsonSerializer;
            }
        /// <summary>
        /// Perform a web request and include the standard Mobile Services
        /// headers.
        /// </summary>
        /// <param name="method">
        /// The HTTP method used to request the resource.
        /// </param>
        /// <param name="uriFragment">
        /// URI of the resource to request (relative to the Mobile Services
        /// runtime).
        /// </param>
        /// <param name="content">
        /// Optional content to send to the resource.
        /// </param>
        /// <returns>The JSON value of the response.</returns>
        internal async Task<IJsonValue> RequestAsync(string method, string uriFragment, IJsonValue content)
        {
            Debug.Assert(!string.IsNullOrEmpty(method), "method cannot be null or empty!");
            Debug.Assert(!string.IsNullOrEmpty(uriFragment), "uriFragment cannot be null or empty!");

            // Create the web request
            IServiceFilterRequest request = new ServiceFilterRequest();
            request.Uri = new Uri(this.ApplicationUri, uriFragment);
            request.Method = method.ToUpper();
            request.Accept = RequestJsonContentType;

            // Set Mobile Services authentication, application, and telemetry
            // headers
            request.Headers[RequestInstallationIdHeader] = applicationInstallationId;
            if (!string.IsNullOrEmpty(this.ApplicationKey))
            {
                request.Headers[RequestApplicationKeyHeader] = this.ApplicationKey;
            }
            if (!string.IsNullOrEmpty(this.currentUserAuthenticationToken))
            {
                request.Headers[RequestAuthenticationHeader] = this.currentUserAuthenticationToken;
            }

            // Add any request as JSON
            if (content != null)
            {
                request.ContentType = RequestJsonContentType;
                request.Content = content.Stringify();
            }

            // Send the request and get the response back as JSON
            IServiceFilterResponse response = await ServiceFilter.ApplyAsync(request, this.filter);
            IJsonValue body = GetResponseJsonAsync(response);

            // Throw errors for any failing responses
            if (response.ResponseStatus != ServiceFilterResponseStatus.Success || response.StatusCode >= 400)
            {
                ThrowInvalidResponse(request, response, body);
            }

            return body;
        }
Esempio n. 54
0
 public void Emit(string eventName, IJsonValue args)
 {
     rootNamespace.Emit(eventName, args);
 }
Esempio n. 55
0
        public static object ToObject(this IJsonValue value, Type targetType)
        {
            if (value.GetType() == targetType)
            {
                return(value);
            }

            if (value.ValueType == JsonValueType.Null)
            {
                return(null);
            }

            if (targetType == typeof(JsonObject))
            {
                return(JsonObject.Parse(value.Stringify()));
            }

            if (typeof(IJsonValue).IsAssignableFrom(targetType))
            {
                return(value);
            }

            if (targetType == typeof(string))
            {
                return(value.GetString());
            }

            if (targetType == typeof(int) || targetType == typeof(int?))
            {
                return((int)value.GetNumber());
            }

            if (targetType == typeof(long) || targetType == typeof(long?))
            {
                return((long)value.GetNumber());
            }

            if (targetType == typeof(bool) || targetType == typeof(bool?))
            {
                return(value.GetBoolean());
            }

            if (targetType == typeof(float) || targetType == typeof(float?))
            {
                return((float)value.GetNumber());
            }

            if (targetType == typeof(double) || targetType == typeof(double?))
            {
                return(value.GetNumber());
            }

            if (targetType == typeof(decimal) || targetType == typeof(decimal?))
            {
                return((decimal)value.GetNumber());
            }

            if (targetType == typeof(DateTime) || targetType == typeof(DateTime?))
            {
                return(DateTime.Parse(value.GetString()));
            }

            if (targetType == typeof(TimeSpan) || targetType == typeof(TimeSpan?))
            {
                return(TimeSpan.Parse(value.GetString()));
            }

            throw new NotSupportedException($"Type {targetType} is not supported.");
        }
Esempio n. 56
0
        public static ClrValue?Convert(JsonSchema schema, IJsonValue value, PropertyPath path, List <string> errors)
        {
            ClrValue?result = null;

            switch (GetType(schema))
            {
            case JsonObjectType.Boolean:
            {
                if (value is JsonArray jsonArray)
                {
                    result = ParseArray <bool>(errors, path, jsonArray, TryParseBoolean);
                }
                else if (TryParseBoolean(errors, path, value, out var temp))
                {
                    result = temp;
                }

                break;
            }

            case JsonObjectType.Integer:
            case JsonObjectType.Number:
            {
                if (value is JsonArray jsonArray)
                {
                    result = ParseArray <double>(errors, path, jsonArray, TryParseNumber);
                }
                else if (TryParseNumber(errors, path, value, out var temp))
                {
                    result = temp;
                }

                break;
            }

            case JsonObjectType.String:
            {
                if (schema.Format == JsonFormatStrings.Guid)
                {
                    if (value is JsonArray jsonArray)
                    {
                        result = ParseArray <Guid>(errors, path, jsonArray, TryParseGuid);
                    }
                    else if (TryParseGuid(errors, path, value, out var temp))
                    {
                        result = temp;
                    }
                }
                else if (schema.Format == JsonFormatStrings.DateTime)
                {
                    if (value is JsonArray jsonArray)
                    {
                        result = ParseArray <Instant>(errors, path, jsonArray, TryParseDateTime);
                    }
                    else if (TryParseDateTime(errors, path, value, out var temp))
                    {
                        result = temp;
                    }
                }
                else
                {
                    if (value is JsonArray jsonArray)
                    {
                        result = ParseArray <string>(errors, path, jsonArray, TryParseString !);
                    }
                    else if (TryParseString(errors, path, value, out var temp))
                    {
                        result = temp;
                    }
                }

                break;
            }

            default:
            {
                errors.Add($"Unsupported type {schema.Type} for {path}.");
                break;
            }
            }

            return(result);
        }
Esempio n. 57
0
        /// <summary>
        /// Sends a message to a peer.
        /// </summary>
        /// <param name="peerId">ID of the peer to send a message to.</param>
        /// <param name="json">The json message.</param>
        /// <returns>True if the message is sent.</returns>
        public async Task <bool> SendToPeer(int peerId, IJsonValue json)
        {
            string message = json.Stringify();

            return(await SendToPeer(peerId, message));
        }
        /// <summary>
        /// Perform a web request and include the standard Mobile Services
        /// headers.
        /// </summary>
        /// <param name="method">
        /// The HTTP method used to request the resource.
        /// </param>
        /// <param name="uriFragment">
        /// URI of the resource to request (relative to the Mobile Services
        /// runtime).
        /// </param>
        /// <param name="content">
        /// Optional content to send to the resource.
        /// </param>
        /// <returns>The JSON value of the response.</returns>
        internal async Task <IJsonValue> RequestAsync(string method, string uriFragment, IJsonValue content)
        {
            Debug.Assert(!string.IsNullOrEmpty(method), "method cannot be null or empty!");
            Debug.Assert(!string.IsNullOrEmpty(uriFragment), "uriFragment cannot be null or empty!");

            // Create the web request
            IServiceFilterRequest request = new ServiceFilterRequest();

            request.Uri    = new Uri(this.ApplicationUri, uriFragment);
            request.Method = method.ToUpper();
            request.Accept = RequestJsonContentType;

            // Set Mobile Services authentication, application, and telemetry
            // headers
            request.Headers[RequestInstallationIdHeader] = applicationInstallationId;
            if (!string.IsNullOrEmpty(this.ApplicationKey))
            {
                request.Headers[RequestApplicationKeyHeader] = this.ApplicationKey;
            }
            if (!string.IsNullOrEmpty(this.currentUserAuthenticationToken))
            {
                request.Headers[RequestAuthenticationHeader] = this.currentUserAuthenticationToken;
            }

            // Add any request as JSON
            if (content != null)
            {
                request.ContentType = RequestJsonContentType;
                request.Content     = content.Stringify();
            }

            // Send the request and get the response back as JSON
            IServiceFilterResponse response = await ServiceFilter.ApplyAsync(request, this.filter);

            IJsonValue body = GetResponseJsonAsync(response);

            // Throw errors for any failing responses
            if (response.ResponseStatus != ServiceFilterResponseStatus.Success || response.StatusCode >= 400)
            {
                ThrowInvalidResponse(request, response, body);
            }

            return(body);
        }
Esempio n. 59
0
 private void RenderValue(IJsonValue json, double indent)
 {
     switch (json.ValueType)
     {
         case JsonValueType.Array:
             RenderArray(json.GetArray(), indent);
             break;
         case JsonValueType.Object:
             RenderObject(json.GetObject(), indent);
             break;
         case JsonValueType.Null:
             AddInlines(new Run() { Text = "null", FontStyle = Windows.UI.Text.FontStyle.Italic, Foreground = BooleanBrush });
             break;
         case JsonValueType.Number:
             AddInlines(new Run() { Text = json.GetNumber().ToString(), Foreground = NumberBrush });
             break;
         case JsonValueType.String:
             AddInlines(new Run() { Text = "\"" + json.GetString() + "\"", Foreground = StringBrush });
             break;
         case JsonValueType.Boolean:
             AddInlines(new Run() { Text = json.GetBoolean().ToString(), Foreground = BooleanBrush });
             break;
     }
 }
Esempio n. 60
0
        public async Task <IReadOnlyList <IEnrichedAssetEntity> > GetReferencedAssetsAsync(IJsonValue value, TimeSpan cacheDuration,
                                                                                           CancellationToken ct)
        {
            var ids = ParseIds(value);

            if (ids == null)
            {
                return(EmptyAssets);
            }

            async Task <IReadOnlyList <IEnrichedAssetEntity> > LoadAsync(IEnumerable <DomainId> ids)
            {
                var result = await GetAssetsLoader().LoadAsync(ids).GetResultAsync(ct);

                return(result?.NotNull().ToList() ?? EmptyAssets);
            }

            if (cacheDuration > TimeSpan.Zero)
            {
                var assets = await AssetCache.CacheOrQueryAsync(ids, async pendingIds =>
                {
                    return(await LoadAsync(pendingIds));
                }, cacheDuration);

                return(assets);
            }

            return(await LoadAsync(ids));
        }