public async Task <Stream> GetItemImage(string type, string no, int colorId)
        {
            var response = await _requestFactory.GetResponse($"items/{type}/{no}/images/{colorId}", _userOption.Value);

            JObject json = null;

            using (var stream = await response.Content.ReadAsStreamAsync())
            {
                var    reader     = new StreamReader(stream, Encoding.UTF8);
                string jsonString = reader.ReadToEnd();
                json = !string.IsNullOrEmpty(jsonString) ? JObject.Parse(jsonString) : null;
            }

            var meta = json?.SelectToken("meta");

            if (meta?.Value <int>("code") == 200)
            {
                var url = json?.SelectToken("data")?.Value <string>("thumbnail_url");
                if (!string.IsNullOrEmpty(url))
                {
                    var client = new HttpClient();
                    return(await client.GetStreamAsync($"http:{url}"));
                }
            }
            return(null);
        }
 /// <summary>
 /// Gets a string from the primary or backup language file
 /// </summary>
 /// <param name="path">The path to the node</param>
 /// <returns></returns>
 public static string GetString(string path)
 {
     if (primary == null && backup == null)
     {
         plugin.Verbose("Tried to send Discord message before loading languages.");
         return(null);
     }
     try
     {
         return(primary?.SelectToken(path).Value <string>());
     }
     catch (Exception primaryException)
     {
         // This exception means the node does not exist in the language file, the plugin attempts to find it in the backup file
         if (primaryException is NullReferenceException || primaryException is ArgumentNullException || primaryException is InvalidCastException || primaryException is JsonException)
         {
             plugin.Warn("Error reading string '" + path + "' from primary language file, switching to backup...");
             try
             {
                 return(backup.SelectToken(path).Value <string>());
             }
             // The node also does not exist in the backup file
             catch (NullReferenceException e)
             {
                 plugin.Error("Error: Language language string '" + path + "' does not exist. Message can not be sent." + e);
                 return(null);
             }
             catch (ArgumentNullException e)
             {
                 plugin.Error("Error: Language language string '" + path + "' does not exist. Message can not be sent." + e);
                 return(null);
             }
             catch (InvalidCastException e)
             {
                 plugin.Error(e.ToString());
                 throw;
             }
             catch (JsonException e)
             {
                 plugin.Error(e.ToString());
                 throw;
             }
         }
         else
         {
             plugin.Error(primaryException.ToString());
             throw;
         }
     }
 }
Example #3
0
        public async Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext.HttpContext.Request.Method.Equals(HttpMethod.Get.ToString(), StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }

            if (TryModelBindFromHttpContextItems(bindingContext))
            {
                return;
            }

            var strJson = await bindingContext.HttpContext.Request.GetRawBodyStringAsync();


            if (string.IsNullOrWhiteSpace(strJson))
            {
                return;
            }

            JObject?json = JsonConvert.DeserializeObject <JObject>(strJson);

            //if no explicit json path then use the model name
            JToken?match = json?.SelectToken(bindingContext.FieldName ?? bindingContext.ModelName);

            if (match == null)
            {
                return;
            }

            var model = match.ToObject(bindingContext.ModelType);

            bindingContext.Result = ModelBindingResult.Success(model);
        }
        /// <summary>
        /// Gets an array of <see cref="Guid"/> from the token matching the specified <paramref name="path"/>.
        /// </summary>
        /// <param name="obj">The instance of <see cref="JObject"/>.</param>
        /// <param name="path">A <see cref="string"/> that contains a JPath expression.</param>
        /// <returns>The token value as an array of <see cref="Guid"/>.</returns>
        public static Guid[] GetGuidArray(this JObject obj, string path)
        {
            JToken token = obj?.SelectToken(path);

            switch (token)
            {
            case null:
                return(new Guid[0]);

            case JArray array:

                List <Guid> temp = new List <Guid>();

                foreach (JToken t in array)
                {
                    // Attempt to parse the individual tokens in the array, ensuring invalid values doesn't trigger an exception
                    if (t != null && Guid.TryParse(t.ToString(), out Guid guid))
                    {
                        temp.Add(guid);
                    }
                }

                return(temp.ToArray());

            default:

                // Be friendly to other formats
                return(token.Type switch {
                    JTokenType.String => StringUtils.ParseGuidArray(token.Value <string>()),
                    JTokenType.Guid => new[] { token.Value <Guid>() },
                    _ => new Guid[0]
                });
            }
        }
Example #5
0
        /// <summary>
        /// Deploys the custom activities.
        /// </summary>
        /// <param name="packages">The packages.</param>
        /// <param name="allFiles">All files.</param>
        /// <param name="outputFolder">The output folder.</param>
        private async Task <bool> DeployCustomActivities(List <CustomActivityPackageInfo> packages, List <AdfFileInfo> allFiles, string outputFolder)
        {
            logger.Write(string.Empty);
            logger.Write("Deploying custom activity packages to blob storage", "Black");

            var tasks = new List <Task <bool> >();

            foreach (CustomActivityPackageInfo package in packages)
            {
                // Get connection string for blob account to upload to
                JObject jObject = allFiles.FirstOrDefault(x => x.Name == package.PackageLinkedService)?.JObject;

                var parts = package.PackageFile.Split('/');

                if (parts.Length != 2)
                {
                    throw new Exception("packageFile should have only one '/' in it. Current packageFile value: " + package.PackageFile);
                }

                string connectionString = jObject?.SelectToken("$.properties.typeProperties.connectionString").ToObject <string>();
                string localFilePath    = Path.Combine(outputFolder, parts[1]);
                string blobFolder       = parts[0];

                tasks.Add(blob.UploadFile(localFilePath, connectionString, blobFolder));
            }

            var packageUploadResults = await Task.WhenAll(tasks);

            return(packageUploadResults.All(x => x));
        }
Example #6
0
        public Dictionary <int, int> GetGroupOrderOverride(JObject homeRegion)
        {
            var result     = new Dictionary <int, int>();
            var usagesRoot = homeRegion?.SelectToken("ParameterGroupUsages");

            if (usagesRoot != null)
            {
                foreach (var usage in usagesRoot)
                {
                    var idToken    = usage.SelectToken("Group.Id");
                    var orderToken = usage.SelectToken("SortOrder");
                    if (idToken != null && orderToken != null)
                    {
                        var key   = (int)idToken;
                        var value = (int)orderToken;
                        if (!result.ContainsKey(key))
                        {
                            result.Add(key, value);
                        }
                    }
                }
            }

            return(result);
        }
Example #7
0
        private void BindData(JObject obj)
        {
            var     words = obj?.SelectToken("words_result").ToString();
            dynamic json  = JToken.Parse(words) as dynamic;

            string text = string.Empty;

            int imageRowCount = json.Count;

            if (imageRowCount == 0)
            {
                return;
            }

            if (imageRowCount >= 5)
            {
                text = json[0].words + json[1].words;
            }

            label1.Text = json.Count >= 1 ? json[0].words : "";

            label2.Text = json.Count >= 2 ? json[1].words : "";

            label3.Text = json.Count >= 3 ? json[2].words : "";

            label4.Text = json.Count >= 4 ? json[3].words : "";

            label5.Text = json.Count >= 5 ? json[4].words : "";

            chromeBrowser.Load(string.Format("http://www.baidu.com/s?wd={0}", text));
        }
        internal static string ExtractFieldValuefromNode(JObject requestJson, string fieldName)
        {
            string  fieldVal;
            JObject accountData = JsonUtils.ExtractField(requestJson, new string[] { AccountLinkNodeName });

            if (accountData.HasValues == true)
            {
                fieldVal = accountData?.SelectToken($"{AccountLinkNodeName}.{fieldName}")?.Value <string>();
            }
            else
            {
                accountData = JsonUtils.ExtractField(requestJson, new string[] { AccountNodeName });
                fieldVal    = accountData?.SelectToken($"{AccountNodeName}.{fieldName}")?.Value <string>();
            }

            return(fieldVal);
        }
        public async Task <IEnumerable <ColorDto> > GetColors()
        {
            var response = await _requestFactory.GetResponse("colors", _userOption.Value);

            JObject json = null;

            using (var stream = await response.Content.ReadAsStreamAsync())
            {
                var    reader     = new StreamReader(stream, Encoding.UTF8);
                string jsonString = reader.ReadToEnd();
                json = !string.IsNullOrEmpty(jsonString) ? JObject.Parse(jsonString) : null;
            }

            var meta = json?.SelectToken("meta");

            return(meta?.Value <int>("code") == 200 ? json?.SelectToken("data")?.Select(token => token.ToObject <ColorDto>()) : null);
        }
        public void Test_RemoveField_ShouldRemoveWithJsonPath()
        {
            #region Arrange
            string   jsonPayload    = "{\"EmpId\":\"123456\", \"Name\":\"Hello World\", \"Grade\":\"A\",\"City\":\"Pune\", \"Address\": {\"City\":\"Bangalore\", \"State\":\"Karnataka\", \"Country\":\"IN\"}}";
            JObject  inObj          = JObject.Parse(jsonPayload);
            string[] fieldsToRemove = new string[] { "Grade", "Address.State" };
            #endregion Arrange

            #region Act
            JObject objWithoutFields = JsonUtils.RemoveField(inObj, fieldsToRemove);
            #endregion Act

            #region Assert
            Assert.AreEqual(objWithoutFields?.SelectToken("Address.City")?.Value <string>(), "Bangalore");
            Assert.AreEqual(objWithoutFields?.SelectToken("Address.State")?.Value <string>(), null);
            #endregion Assert
        }
Example #11
0
        /// <summary>
        /// Gets an instance of <see cref="DateTime"/> from the value of the token matching the specified
        /// <paramref name="path"/>.
        /// </summary>
        /// <param name="obj">The instance of <see cref="JObject"/>.</param>
        /// <param name="path">A <see cref="String"/> that contains a JPath expression.</param>
        /// <returns>An instance of <see cref="DateTime"/> representing the value of the property.</returns>
        public static DateTime GetDateTime(this JObject obj, string path)
        {
            JToken token = obj?.SelectToken(path);

            if (token == null || token.Type == JTokenType.Null)
            {
                return(default(DateTime));
            }
            return(token.Type == JTokenType.Date ? token.Value <DateTime>() : DateTime.Parse(token.Value <string>()));
        }
Example #12
0
        public UserDTO GetUser(WebhookRequest request)
        {
            UserDTO result = new UserDTO();

            try
            {
                var device = request.OriginalDetectIntentRequest.Payload.Fields.Where(x => x.Key.ToLower() == "user").FirstOrDefault();

                JObject userAsJSONObject = JObject.Parse(device.Value.ToString());

                result.FirstName = (string)userAsJSONObject?.SelectToken("profile.givenName");
                result.LastName  = (string)userAsJSONObject?.SelectToken("profile.familyName");
                result.UserID    = (string)userAsJSONObject?.SelectToken("userId");
            }
            catch
            {
            }

            return(result);
        }
Example #13
0
        /// <summary>
        /// Gets the items of the <see cref="JArray"/> from the token matching the specfied <paramref name="path"/>.
        /// </summary>
        /// <param name="obj">The instance of <see cref="JObject"/>.</param>
        /// <param name="path">A <see cref="String"/> that contains a JPath expression.</param>
        /// <param name="callback">A callback function used for parsing or converting the token value.</param>
        /// <returns>An array of <typeparamref name="TValue"/>. If the a matching token isn't found, an empty
        /// array will still be returned.</returns>
        public static TValue[] GetArrayItems <TKey, TValue>(this JObject obj, string path, Func <TKey, TValue> callback) where TKey : JToken
        {
            if (!(obj?.SelectToken(path) is JArray token))
            {
                return(new TValue[0]);
            }

            return((
                       from TKey child in token
                       select callback(child)
                       ).ToArray());
        }
Example #14
0
        /// <summary>
        /// Gets the items of the <see cref="JArray"/> from the token matching the specfied <paramref name="path"/>.
        /// </summary>
        /// <param name="obj">The instance of <see cref="JObject"/>.</param>
        /// <param name="path">A <see cref="String"/> that contains a JPath expression.</param>
        /// <param name="callback">A callback function used for parsing or converting the token value.</param>
        /// <returns>An array of <typeparamref name="T"/>. If the a matching token isn't found, an empty array will
        /// still be returned.</returns>
        public static T[] GetArrayItems <T>(this JObject obj, string path, Func <JObject, T> callback)
        {
            if (!(obj?.SelectToken(path) is JArray token))
            {
                return(new T[0]);
            }

            return((
                       from JObject child in token
                       select callback(child)
                       ).ToArray());
        }
Example #15
0
        /// <summary>
        /// Gets the items of the <see cref="JArray"/> from the token matching the specfied <paramref name="path"/>.
        /// </summary>
        /// <param name="obj">The instance of <see cref="JObject"/>.</param>
        /// <param name="path">A <see cref="String"/> that contains a JPath expression.</param>
        /// <returns>An array of <typeparamref name="T"/>. If the a matching token isn't found, an empty array will
        /// still be returned.</returns>
        public static T[] GetArrayItems <T>(this JObject obj, string path)
        {
            if (!(obj?.SelectToken(path) is JArray token))
            {
                return(new T[0]);
            }

            return((
                       from JToken child in token
                       select child.Value <T>()
                       ).ToArray());
        }
        private void ParseImpressionGuid(JObject jsonObject)
        {
            var pingUri = jsonObject?.SelectToken("$.instrumentation.pingUrlBase")?.ToString();

            if (string.IsNullOrEmpty(pingUri))
            {
                return;
            }
            // IG is the unique id of the ping that's made
            this.ImpressionGuid = pingUri.Substring(
                pingUri.IndexOf("IG=", StringComparison.OrdinalIgnoreCase) + 3,
                32);
        }
Example #17
0
        /// <summary>
        /// Gets an array of <typeparamref name="T"/> from the token matching the specified <paramref name="path"/>,
        /// using the specified delegate <paramref name="callback"/> for parsing each item in the array.
        /// </summary>
        /// <param name="obj">The instance of <see cref="JObject"/>.</param>
        /// <param name="path">A <see cref="String"/> that contains a JPath expression.</param>
        /// <param name="callback">A callback function used for parsing or converting the token value.</param>
        public static T[] GetArray <T>(this JObject obj, string path, Func <JObject, T> callback)
        {
            if (!(obj?.SelectToken(path) is JArray token))
            {
                return(null);
            }

            return((
                       from child in token
                       where child is JObject
                       select callback((JObject)child)
                       ).ToArray());
        }
        public static T[] GetArray <T>(JObject obj, string path, Func <JObject, T> callback)
        {
            JArray token = obj?.SelectToken(path) as JArray;

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

            return((
                       from JObject child in token
                       select callback(child)
                       ).ToArray());
        }
Example #19
0
        /// <summary>
        /// Gets whether a token matching the specified <paramref name="path"/> exists and isn't <c>null</c> (or
        /// an empty string).
        /// </summary>
        /// <param name="obj">The parent object.</param>
        /// <param name="path">A <see cref="String"/> that contains a JPath expression.</param>
        /// <returns><c>true</c> if the property exists and the value isn't <c>null</c>, otherwise
        /// <c>false</c>.</returns>
        public static bool HasValue(this JObject obj, string path)
        {
            JToken token = obj?.SelectToken(path);

            return(!(
                       token == null
                       ||
                       (token.Type == JTokenType.Array && !token.HasValues)
                       ||
                       (token.Type == JTokenType.Object && !token.HasValues)
                       ||
                       (token.Type == JTokenType.String && token.ToString() == string.Empty)
                       ||
                       token.Type == JTokenType.Null
                       ));
        }
Example #20
0
        private static AzureDeploymentState GetState(JObject deploymentJson)
        {
            var jsonState = deploymentJson?.SelectToken("$..provisioningState")?.ToString();

            if (string.IsNullOrEmpty(jsonState))
            {
                return(AzureDeploymentState.Unknown);
            }
            else if (Enum.TryParse <AzureDeploymentState>(jsonState, out AzureDeploymentState state))
            {
                return(state);
            }
            else
            {
                throw new NotSupportedException($"The deployment status '{jsonState}' is not supported.");
            }
        }
Example #21
0
        public static string GetValue(Stream stream, string key)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }
            if (string.IsNullOrEmpty(key))
            {
                return(null);
            }

            using (var streamReader = new StreamReader(stream))
                using (var reader = new JsonTextReader(streamReader))
                {
                    JObject document = JObject.Load(reader);
                    JToken  value    = document?.SelectToken(key.Replace(':', '.'));
                    return(value?.ToString());
                }
        }
Example #22
0
        internal static TransactionPhasing ParseJson(JObject jObject)
        {
            if (jObject?.SelectToken(Parameters.PhasingFinishHeight) == null)
            {
                return(null);
            }

            var phasing = new TransactionPhasing
            {
                FinishHeight    = GetAttachmentValue <int>(jObject, Parameters.PhasingFinishHeight),
                HoldingId       = ulong.Parse(GetAttachmentValue <string>(jObject, Parameters.PhasingHolding)),
                MinBalance      = long.Parse(GetAttachmentValue <string>(jObject, Parameters.PhasingMinBalance)),
                MinBalanceModel = (MinBalanceModel)GetAttachmentValue <int>(jObject, Parameters.PhasingMinBalanceModel),
                Quorum          = GetAttachmentValue <long>(jObject, Parameters.PhasingQuorum),
                VotingModel     = (VotingModel)GetAttachmentValue <int>(jObject, Parameters.PhasingVotingModel)
            };

            if (jObject.SelectToken(Parameters.PhasingWhitelist) != null)
            {
                phasing.WhiteList = ParseWhitelist(jObject.SelectToken(Parameters.PhasingWhitelist))
                                    .Select(w => new Account(ulong.Parse(w)))
                                    .ToList();
            }
            if (jObject.SelectToken(Parameters.PhasingHashedSecret) != null)
            {
                phasing.HashedSecret          = new BinaryHexString(GetAttachmentValue <string>(jObject, Parameters.PhasingHashedSecret));
                phasing.HashedSecretAlgorithm = (HashAlgorithm)GetAttachmentValue <int>(jObject, Parameters.PhasingHashedSecretAlgorithm);
            }
            if (jObject.SelectToken(Parameters.PhasingLinkedFullHashes) != null)
            {
                phasing.LinkedFullHashes =
                    ParseWhitelist(jObject.SelectToken(Parameters.PhasingLinkedFullHashes))
                    .Select(s => new BinaryHexString(s))
                    .ToList();
            }

            return(phasing);
        }
        /// <summary>
        /// Adds tasks to the passed in Job using the FQR's from the Database
        /// </summary>
        /// <param name="job">Job to add Tasks to</param>
        public void CreateTasks(JobEntity job)
        {
            var fqrGuids = (new FqrRepository()).GetAllAsync().Result;

            foreach (var fqrGuid in fqrGuids)
            {
                var    response = ApiRequest.RunEndpointCallAsync($"{ApiRequest.UrlBase}/objects/{fqrGuid.Guid}/attributes", acceptHeader).Result;
                JArray items;

                try
                {
                    JObject jsonObject = JObject.Parse(response);
                    items = JArray.Parse(jsonObject?.SelectToken("items").ToString());
                }
                catch (Exception)
                {
                    items = new JArray();
                }

                foreach (var item in items)
                {
                    var url = item.SelectToken("samples")?.ToString();

                    if (!string.IsNullOrWhiteSpace(url))
                    {
                        job.Tasks.Add(new TaskQueueEntity
                        {
                            JobId       = job.Id,
                            Parent      = job,
                            TaskType    = this.TaskType,
                            TaskUrl     = ConvertAttributeLink(url, job),
                            IsCompleted = false
                        });
                    }
                }
            }
        }
Example #24
0
        public virtual IEnumerable <JToken> FilterServicesOnProduct(JObject product, IEnumerable <int> excludeIds = null, JObject homeRegionData = null)
        {
            var root = product.SelectToken(LinkName);

            if (root == null)
            {
                yield break;
            }
            var homeRegion = homeRegionData?.SelectToken("Alias")?.ToString();

            foreach (var elem in (JArray)root)
            {
                var hasModifier =
                    elem.SelectTokens("Parent.Modifiers.[?(@.Alias)].Alias")
                    .Select(m => m.ToString())
                    .Contains(LinkModifierName);
                var isArchive = elem.SelectTokens("Service.Modifiers.[?(@.Alias)].Alias")
                                .Select(m => m.ToString())
                                .Contains("Archive");

                var serviceId = (int)elem.SelectToken("Service.Id");
                var toExclude = excludeIds?.Contains(serviceId) ?? false;

                if (hasModifier && !isArchive && !toExclude)
                {
                    var regionAliases = new HashSet <string>(elem.SelectTokens("Service.Regions.[?(@.Alias)].Alias").Select(m => m.ToString()));
                    var satisfyRegion = string.IsNullOrEmpty(homeRegion) ||
                                        !regionAliases.Any() ||
                                        regionAliases.Contains(homeRegion);

                    if (satisfyRegion)
                    {
                        yield return(elem);
                    }
                }
            }
        }
Example #25
0
    public void EvaluateSinglePropertyReturningArray()
    {
      JObject o = new JObject(
        new JProperty("Blah", new [] { 1, 2, 3 }));

      JToken t = o.SelectToken("Blah");
      Assert.IsNotNull(t);
      Assert.AreEqual(JTokenType.Array, t.Type);

      t = o.SelectToken("Blah[2]");
      Assert.AreEqual(JTokenType.Integer, t.Type);
      Assert.AreEqual(3, (int)t);
    }
Example #26
0
    public void EvaluateIndexerOnObjectWithError()
    {
      JObject o = new JObject(
        new JProperty("Blah", 1));

      o.SelectToken("[1]", true);
    }
Example #27
0
    public void EvaluateMissingProperty()
    {
      JObject o = new JObject(
        new JProperty("Blah", 1));

      JToken t = o.SelectToken("Missing[1]");
      Assert.IsNull(t);
    }
Example #28
0
        /// <summary>
        /// Gets the <see cref="JToken"/> at the specified <paramref name="path"/>. If the type of the token is either
        /// <see cref="JTokenType.Object"/> or <see cref="JTokenType.Array"/>, the method will return
        /// <c>null</c> instead.
        /// </summary>
        /// <param name="obj">The instance of <see cref="JObject"/>.</param>
        /// <param name="path">A <see cref="String"/> that contains a JPath expression.</param>
        /// <returns>An instance of <see cref="JToken"/>, or <c>null</c>.</returns>
        private static JToken GetSimpleTypeTokenFromPath(JObject obj, string path)
        {
            JToken token = obj?.SelectToken(path);

            return(token == null || token.Type == JTokenType.Object || token.Type == JTokenType.Array ? null : token);
        }
        public void EvaluateWhitespaceString()
        {
            JObject o = new JObject(
                new JProperty("Blah", 1));

            JToken t = o.SelectToken(" ");
            Assert.Equal(o, t);
        }
Example #30
0
 /// <summary>
 /// Gets an object from a token matching the specified <paramref name="path"/>.
 /// </summary>
 /// <param name="obj">The parent object.</param>
 /// <param name="path">A <see cref="String"/> that contains a JPath expression.</param>
 /// <returns>An instance of <typeparamref name="T"/>, or the default value of <typeparamref name="T"/> if not
 /// found.</returns>
 public static T GetObject <T>(this JObject obj, string path)
 {
     return(!(obj?.SelectToken(path) is JObject child) ? default(T) : child.ToObject <T>());
 }
Example #31
0
    public void EvaluateIndexerOnObjectWithError()
    {
      JObject o = new JObject(
        new JProperty("Blah", 1));

      ExceptionAssert.Throws<JsonException>(
        @"Index 1 not valid on JObject.",
        () =>
        {
          o.SelectToken("[1]", true);
        });
    }
Example #32
0
        public void Path()
        {
            JObject o =
                new JObject(
                    new JProperty("Test1", new JArray(1, 2, 3)),
                    new JProperty("Test2", "Test2Value"),
                    new JProperty("Test3", new JObject(new JProperty("Test1", new JArray(1, new JObject(new JProperty("Test1", 1)), 3)))),
                    new JProperty("Test4", new JConstructor("Date", new JArray(1, 2, 3)))
                    );

            JToken t = o.SelectToken("Test1[0]");
            Assert.Equal("Test1[0]", t.Path);

            t = o.SelectToken("Test2");
            Assert.Equal("Test2", t.Path);

            t = o.SelectToken("");
            Assert.Equal("", t.Path);

            t = o.SelectToken("Test4[0][0]");
            Assert.Equal("Test4[0][0]", t.Path);

            t = o.SelectToken("Test4[0]");
            Assert.Equal("Test4[0]", t.Path);

            t = t.DeepClone();
            Assert.Equal("", t.Path);

            t = o.SelectToken("Test3.Test1[1].Test1");
            Assert.Equal("Test3.Test1[1].Test1", t.Path);

            JArray a = new JArray(1);
            Assert.Equal("", a.Path);

            Assert.Equal("[0]", a[0].Path);
        }
Example #33
0
        /// <summary>
        /// Returns Json Token that matches <paramref name="jsonpath"/> expression.
        /// </summary>
        /// <param name="jsonpath">A string that contains json path expression</param>
        /// <returns>Token returned by <paramref name="jsonpath"/> expression</returns>

        public IToken <IMapper <string> > From(string jsonpath)
        {
            jObject = jObject ?? JObject.Parse(jsonString);
            token   = jObject?.SelectToken(jsonpath, false);
            return(new JsonToken(this, token));
        }
        public void EvaluateEmptyString()
        {
            JObject o = new JObject(
                new JProperty("Blah", 1));

            JToken t = o.SelectToken("");
            Assert.Equal(o, t);

            t = o.SelectToken("['']");
            Assert.Equal(null, t);
        }
        public void SelectTokenSimple()
        {
            JObject o = new JObject();

            #region SelectTokenSimple
            string name = (string)o.SelectToken("Manufacturers[0].Name");
            #endregion
        }
        public void QuoteName()
        {
            JObject o = new JObject(
                new JProperty("Blah", 1));

            JToken t = o.SelectToken("['Blah']");
            Assert.NotNull(t);
            Assert.Equal(JTokenType.Integer, t.Type);
            Assert.Equal(1, (int)t);
        }
Example #37
0
    public void EvaluateMissingPropertyWithError()
    {
      JObject o = new JObject(
        new JProperty("Blah", 1));

      ExceptionAssert.Throws<JsonException>(
        "Property 'Missing' does not exist on JObject.",
        () =>
        {
          o.SelectToken("Missing", true);
        });
    }
        public void EvaluateDollarTypeString()
        {
            JObject o = new JObject(
                new JProperty("$values", new JArray(1, 2, 3)));

            JToken t = o.SelectToken("$values[1]");
            Assert.Equal(2, (int)t);
        }
        public void EvaluateMissingPropertyIndexWithError()
        {
            JObject o = new JObject(
                new JProperty("Blah", 1));

            AssertException.Throws<JsonException>(() => { o.SelectToken("['Missing','Missing2']", true); }, "Property 'Missing' does not exist on JObject.");
        }
        public void EvaluateDollarString()
        {
            JObject o = new JObject(
                new JProperty("Blah", 1));

            JToken t = o.SelectToken("$");
            Assert.Equal(o, t);
        }
        public void EvaluatePropertyWithoutError()
        {
            JObject o = new JObject(
                new JProperty("Blah", 1));

            JValue v = (JValue)o.SelectToken("Blah", true);
            Assert.Equal(1, v.Value);
        }
        public void EvaluateEmptyStringWithMatchingEmptyProperty()
        {
            JObject o = new JObject(
                new JProperty(" ", 1));

            JToken t = o.SelectToken("[' ']");
            Assert.Equal(1, (int)t);
        }
Example #43
0
        private void EscapedPathAssert(string propertyName, string expectedPath)
        {
            int v1 = int.MaxValue;
            JValue value = new JValue(v1);

            JObject o = new JObject(new JProperty(propertyName, value));

            Assert.AreEqual(expectedPath, value.Path);

            JValue selectedValue = (JValue)o.SelectToken(value.Path);

            Assert.AreEqual(value, selectedValue);
        }
Example #44
0
    public void EvaluateSingleProperty()
    {
      JObject o = new JObject(
        new JProperty("Blah", 1));

      JToken t = o.SelectToken("Blah");
      Assert.IsNotNull(t);
      Assert.AreEqual(JTokenType.Integer, t.Type);
      Assert.AreEqual(1, (int)t);
    }
        public void EvaluateSliceOnObjectWithError()
        {
            JObject o = new JObject(
                new JProperty("Blah", 1));

            AssertException.Throws<JsonException>(() => { o.SelectToken("[:]", true); }, @"Array slice is not valid on JObject.");
        }
Example #46
0
    public void EvaluateIndexerOnObject()
    {
      JObject o = new JObject(
        new JProperty("Blah", 1));

      JToken t = o.SelectToken("[1]");
      Assert.IsNull(t);
    }
        public void EvaluateWildcardIndexOnObjectWithError()
        {
            JObject o = new JObject(
                new JProperty("Blah", 1));

            AssertException.Throws<JsonException>(() => { o.SelectToken("[*]", true); }, @"Index * not valid on JObject.");
        }
Example #48
0
    public void EvaluateMissingPropertyWithError()
    {
      JObject o = new JObject(
        new JProperty("Blah", 1));

      o.SelectToken("Missing", true);
    }
Example #49
0
 /// <summary>
 /// Gets an object from a token matching the specified <paramref name="path"/>.
 /// </summary>
 /// <param name="obj">The parent object.</param>
 /// <param name="path">A <see cref="String"/> that contains a JPath expression.</param>
 /// <returns>An instance of <see cref="JObject"/>, or <c>null</c> if not found.</returns>
 public static JObject GetObject(this JObject obj, string path)
 {
     return(obj?.SelectToken(path) as JObject);
 }
Example #50
0
 /// <summary>
 /// Gets the <see cref="bool"/> value of the token matching the specified <paramref name="path"/>, or
 /// <paramref name="fallback"/> if <paramref name="path"/> doesn't match a token.
 /// </summary>
 /// <param name="obj">The parent object.</param>
 /// <param name="path">A <see cref="string"/> that contains a JPath expression.</param>
 /// <param name="fallback">The fallback value.</param>
 /// <returns>An instance of <see cref="bool"/>.</returns>
 public static bool GetBoolean(this JObject obj, string path, bool fallback)
 {
     return(JsonTokenUtils.GetBoolean(obj?.SelectToken(path), fallback));
 }
        public void SelectTokenLinq()
        {
            JObject o = new JObject();

            #region SelectTokenLinq
            IList<string> storeNames = o.SelectToken("Stores").Select(s => (string)s).ToList();
            // Lambton Quay
            // Willis Street

            IList<string> firstProductNames = o["Manufacturers"].Select(m => (string)m.SelectToken("Products[1].Name")).ToList();
            // null
            // Headlight Fluid

            decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)m.SelectToken("Products[0].Price"));
            // 149.95
            #endregion
        }
Example #52
0
 /// <summary>
 /// Gets the <see cref="bool"/> value of the token matching the specified <paramref name="path"/> and parses
 /// it into an instance of <typeparamref name="T"/>, or the default value of <typeparamref name="T"/> if
 /// <paramref name="path"/> doesn't match a token.
 /// </summary>
 /// <param name="obj">The parent object.</param>
 /// <param name="path">A <see cref="string"/> that contains a JPath expression.</param>
 /// <param name="callback">A callback function used for parsing or converting the token value.</param>
 /// <returns>An instance of <see cref="bool"/>, or <c>false</c> if <paramref name="path"/>
 /// doesn't match a token.</returns>
 public static T GetBoolean <T>(this JObject obj, string path, Func <bool, T> callback)
 {
     return(JsonTokenUtils.TryGetBoolean(obj?.SelectToken(path), out bool result) ? callback(result) : default);
        public void EvaluateEmptyPropertyIndexer()
        {
            JObject o = new JObject(
                new JProperty("", 1));

            JToken t = o.SelectToken("['']");
            Assert.Equal(1, (int)t);
        }