Example #1
0
        /// <summary>
        /// 获取商品特性
        /// </summary>
        /// <param name="elements"></param>
        /// <returns></returns>
        Dictionary <string, Dictionary <int, string> > GetFeatures(JsonElement.ArrayEnumerator elements)
        {
            var dic = new Dictionary <string, Dictionary <int, string> >();

            try
            {
                foreach (var item in elements)
                {
                    if (item.TryGetProperty("Values", out var valuesElement) && valuesElement.ValueKind == JsonValueKind.Array)
                    {
                        var values = new Dictionary <int, string>();
                        foreach (var value in valuesElement.EnumerateArray())
                        {
                            values.Add(value.GetProperty("Id").GetInt32(), value.GetProperty("Name").GetString());
                        }
                        dic.Add(item.GetProperty("Name").GetString(), values);
                    }
                }
            }
            catch (Exception ex)
            {
                this.Logger.Error("解析商品特性异常", ex);
            }
            return(dic);
        }
Example #2
0
        /// <summary>
        /// 获取商品规格参数
        /// </summary>
        /// <param name="elements"></param>
        /// <returns></returns>
        string GetSpecifications(JsonElement.ArrayEnumerator elements)
        {
            var dic = new Dictionary <string, string>();

            try
            {
                foreach (var item in elements)
                {
                    if (item.TryGetProperty("Paras", out var parasElement) && parasElement.ValueKind == JsonValueKind.Array)
                    {
                        foreach (var para in parasElement.EnumerateArray())
                        {
                            string value = para.GetProperty("ParameterValue").GetString();
                            if (!string.IsNullOrEmpty(value))
                            {
                                dic.Add(para.GetProperty("Name").GetString(), value);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.Logger.Error("解析商品规格异常", ex);
            }
            return(Newtonsoft.Json.JsonConvert.SerializeObject(dic));
        }
Example #3
0
        private static async Task <bool> ValidateResponse(HttpResponseMessage response, System.Net.IPAddress newIPAddress)
        {
            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"Failed - HTTP status {response.StatusCode}");
                Console.WriteLine("Response content: ");
                Console.WriteLine(await response.Content.ReadAsStringAsync());
                Console.WriteLine();
                return(false);
            }

            try
            {
                JsonDocument?doc = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());

                if (doc == null)
                {
                    throw new Exception("Response content missing");
                }

                var  root    = doc.RootElement;
                bool success = root.GetProperty("success").GetBoolean();

                if (!success)
                {
                    Console.WriteLine($"Failed - Errors:");

                    JsonElement.ArrayEnumerator errors = root.GetProperty("errors").EnumerateArray();
                    foreach (JsonElement error in errors)
                    {
                        int    errorCode    = error.GetProperty("code").GetInt32();
                        string?errorMessage = error.GetProperty("message").GetString();

                        Console.WriteLine($"{errorCode}: {errorMessage ?? ""}");
                    }
                    Console.WriteLine();
                    return(false);
                }

                string?resultContent = root.GetProperty("result").GetProperty("content").GetString();

                if (!System.Net.IPAddress.TryParse(resultContent, out System.Net.IPAddress? responseIP))
                {
                    throw new Exception("IP result contains invalid IP address.");
                }

                if (!newIPAddress.Equals(responseIP))
                {
                    throw new Exception("Incorrect IP returned");
                }

                Console.WriteLine("Done");
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Failed - {e.Message}");
                return(false);
            }
        }
Example #4
0
        private List <Teacher> ToListTeacher(HttpResponseMessage httpResponseMessage, out bool hasNext)
        {
            var jsonElement = JsonDocument.Parse(httpResponseMessage.Content.ReadAsStream()).RootElement;

            JsonElement.ArrayEnumerator data = jsonElement.GetProperty("data").EnumerateArray();

            var result = new List <Teacher>();

            foreach (var item in data)
            {
                var teacher = new Teacher
                {
                    UserId          = item.GetProperty("user_info").GetProperty("user_id").GetInt32(),
                    Nickname        = item.GetProperty("user_info").GetProperty("nickname").GetString(),
                    OriginCountryId = item.GetProperty("user_info").GetProperty("origin_country_id").GetString(),
                    SessionCount    = item.GetProperty("teacher_info").GetProperty("session_count").GetInt32(),
                    MinPrice        = item.GetProperty("course_info").GetProperty("min_price").GetInt32()
                };


                result.Add(teacher);
            }

            hasNext = jsonElement.GetProperty("paging").GetProperty("has_next").GetInt32() == 0;


            return(result);
        }
 private IEnumerable <Project> GetProjects(JsonElement.ArrayEnumerator arrayEnumerator)
 {
     foreach (var element in arrayEnumerator)
     {
         yield return(GetProject(element.GetString()));
     }
 }
Example #6
0
        public List <Starship> Parse()
        {
            List <Starship> result = new List <Starship> ();

            logger.Log(LogLevel.Information, "JSON parsing started");
            try
            {
                using (JsonDocument jsonDocument = JsonDocument.Parse(jsonString))
                {
                    JsonElement rootElementJson = jsonDocument.RootElement;
                    JsonElement.ArrayEnumerator starshipsArrayJson = rootElementJson.GetProperty("results").EnumerateArray();
                    result = starshipsArrayJson.AsParallel()
                             .Select(starshipObjectJson => {
                        return(ParseStarshipObject(starshipObjectJson));
                    })
                             .Where(starship => starship.MegalightsPerHour != 0 && starship.Consumables != 0)
                             .ToList();
                }
            }
            catch (Exception error)
            {
                logger.Log(LogLevel.Warning, $"exception has been occurred while trying to parse data: {error.Message}");
                throw error;
            }

            logger.Log(LogLevel.Information, "JSON parsing finished");

            return(result);
        }
        public static SimpleGatewayInterface[] GetInterfaces(JsonElement jsonInterfaces)
        {
            var gatewayInterfaces = new List <SimpleGatewayInterface>();

            JsonElement.ArrayEnumerator interfacesArrayEnumerator = jsonInterfaces.EnumerateArray();

            while (interfacesArrayEnumerator.MoveNext())
            {
                JsonElement currInterface = interfacesArrayEnumerator.Current;

                SimpleGatewayInterface @interface = new SimpleGatewayInterface();

                @interface.SvgIcon  = GetIcon(currInterface);
                @interface.Name     = GetName(currInterface);
                @interface.Topology = GetTopology(currInterface);
                @interface.IP       = GetIp(currInterface);
                @interface.Comments = GetComments(currInterface);

                gatewayInterfaces.Add(@interface);
            }

            // sort interfaces by name (ASC order)
            gatewayInterfaces.Sort((a, b) => string.CompareOrdinal(a.Name.ToLower(), b.Name.ToLower()));

            return(gatewayInterfaces.ToArray());
        }
Example #8
0
        private float ProcessLineString(List <Segment> segments, JsonElement.ArrayEnumerator coordinates, bool oneway)
        {
            float   maxCoordinate = 0;
            Vector3?lastOrNull    = null;

            foreach (var coordinate in coordinates)
            {
                Trace.Assert(coordinate.GetArrayLength() == 2);
                var(lon, lat) = (coordinate[0].GetDouble(), coordinate[1].GetDouble());  // beware the order!!
                // also see https://macwright.org/lonlat/
                var vec = _coordinateSpace.To(lat, lon);

                maxCoordinate = Math.Max(maxCoordinate, Math.Max(Math.Abs(vec.X), Math.Abs(vec.Y)));

                if (lastOrNull is Vector3 last)
                {
                    var segmentId = 1 + segments.Count;
                    var seg       = new Segment(segmentId, SegmentType.Rail, last, vec, oneway: oneway);
                    segments.Add(seg);
                }

                lastOrNull = vec;
            }

            return(maxCoordinate);
        }
Example #9
0
        /// <summary>
        /// Parse the json array of submission, return the biggest id number
        /// </summary>
        private async Task <long> ParseSubmissions(
            JsonElement.ArrayEnumerator array,
            ITargetBlock <Submission> target,
            ITargetBlock <CrawlerError> errors)
        {
            long maxId = 0;

            foreach (var submission in array)
            {
                if (submission.GetProperty("problemType").GetString() != "PROGRAMMING")
                {
                    await errors.SendAsync(new CrawlerError
                    {
                        Crawler = nameof(ZojSubmissionCrawler),
                        Message = "problemType is not PROGRAMMING",
                        Time    = DateTime.Now,
                        Data    = submission.GetRawText(),
                    });

                    continue;
                }

                var idStr = submission.GetProperty("id").GetString();
                var id    = long.Parse(idStr);
                maxId = Math.Max(id, maxId);

                try
                {
                    await target.SendAsync(new Submission
                    {
                        OnlineJudgeId = OnlineJudge,
                        SubmissionId  = id,
                        UserName      = submission.GetProperty("user")
                                        .GetProperty("user")
                                        .GetProperty("nickname")
                                        .GetString(),
                        Status       = ParseStatus(submission.GetProperty("status").GetString()),
                        ProblemLabel = submission.GetProperty("problemSetProblem")
                                       .GetProperty("label")
                                       .GetString(),
                        Time = DateTime.Parse(submission.GetProperty("submitAt").GetString()),
                    });
                }
                catch (KeyNotFoundException e)
                {
                    await errors.SendAsync(new CrawlerError
                    {
                        Crawler = nameof(ZojSubmissionCrawler),
                        Message = e.Message,
                        Time    = DateTime.Now,
                        Data    = submission.GetRawText(),
                    });
                }
            }

            return(maxId);
        }
Example #10
0
        public async Task TestCrowdactionList()
        {
            var         newCrowdaction     = new NewCrowdactionInternal("test" + Guid.NewGuid(), 100, "test", "test", "test", null, DateTime.UtcNow, DateTime.UtcNow.AddDays(1), null, null, null, null, new[] { Category.Community }, Array.Empty <string>(), CrowdactionDisplayPriority.Bottom, CrowdactionStatus.Running, 0, null);
            Crowdaction createdCrowdaction = await crowdactionService.CreateCrowdactionInternal(newCrowdaction, CancellationToken.None);

            Assert.NotNull(createdCrowdaction);

            const string QueryCrowdactions = @"
                query {
                    crowdactions {
                        id
                        name
                        categories {
                          category
                        }
                        descriptiveImage {
                            filepath
                        }
                    }
                }";

            HttpResponseMessage response = await PerformGraphQlQuery(QueryCrowdactions, null);

            string content = await response.Content.ReadAsStringAsync();

            Assert.True(response.IsSuccessStatusCode, content);
            JsonDocument result = JsonDocument.Parse(content);

            Assert.Throws <KeyNotFoundException>(() => result.RootElement.GetProperty("errors"));
            JsonElement.ArrayEnumerator crowdactions = result.RootElement.GetProperty("data").GetProperty("crowdactions").EnumerateArray();
            Assert.True(crowdactions.Any(), content);

            string       crowdactionId    = crowdactions.First().GetProperty("id").GetString();
            const string QueryCrowdaction = @"
                query($crowdactionId : ID!) {
                    crowdaction(id: $crowdactionId) {
                        id
                        name
                        descriptiveImage {
                            filepath
                        }
                    }
                }";
            dynamic      variables        = new { crowdactionId };

            response = await PerformGraphQlQuery(QueryCrowdaction, variables);

            content = await response.Content.ReadAsStringAsync();

            Assert.True(response.IsSuccessStatusCode, content);
            result = JsonDocument.Parse(content);
            Assert.Throws <KeyNotFoundException>(() => result.RootElement.GetProperty("errors"));
            JsonElement crowdaction = result.RootElement.GetProperty("data").GetProperty("crowdaction");

            Assert.Equal(crowdactionId.ToString(CultureInfo.InvariantCulture), crowdaction.GetProperty("id").GetString());
        }
Example #11
0
        /// <summary>
        /// Gets the overall stats of a country.
        /// </summary>
        /// <param name="inputCountry">The name of the searched country.</param>
        /// <returns>Returns the stats of the country which includes a 24 hour overview, and total stats.</returns>
        public Tracking getOverallStats(string inputCountry)
        {
            // Creating the new JsonElement, which includes a list of all the countries.
            JsonElement resultCountry = new JsonElement();
            // Creating the result tracking object.
            Tracking returnResult = new Tracking();

            // Downloading the result from the api.
            string apiCall = this.webClient.DownloadString("https://api.covid19api.com/summary");

            // Parsing the data into a JsonDocument.
            JsonDocument doc  = JsonDocument.Parse(apiCall);
            JsonElement  root = doc.RootElement;

            // Making the JsonDocument into a array which we can loop through.
            JsonElement.ArrayEnumerator countries = root.GetProperty("Countries").EnumerateArray();

            // Loop through every country in the list of countries.
            foreach (var country in countries)
            {
                // Checkes if the name of the search country matches the the looped country's name.
                if (country.GetProperty("Slug").GetString() == inputCountry.ToLower().Replace(" ", "-"))
                {
                    // If it does, then setting the result country to the looped country.
                    resultCountry = country;
                    break;
                    // Else continue the loop.
                }
                else
                {
                    continue;
                }
            }

            // Check if country was found
            if (resultCountry.ValueKind.ToString() == "Undefined")
            {
                return(returnResult);
            }

            // Binding the stats to the result object, then returing the result object.
            returnResult.countryName    = inputCountry;
            returnResult.dateTracked    = resultCountry.GetProperty("Date").GetString();
            returnResult.totalConfirmed = resultCountry.GetProperty("TotalConfirmed").GetInt32();
            returnResult.newConfirmed   = resultCountry.GetProperty("NewConfirmed").GetInt32();
            returnResult.totalDeaths    = resultCountry.GetProperty("TotalDeaths").GetInt32();
            returnResult.newDeaths      = resultCountry.GetProperty("NewDeaths").GetInt32();
            returnResult.totalRecovered = resultCountry.GetProperty("TotalRecovered").GetInt32();
            returnResult.newRecovered   = resultCountry.GetProperty("NewRecovered").GetInt32();

            return(returnResult);
        }
Example #12
0
        /// <summary>
        /// Parse the json array of submission, return the biggest id number
        /// </summary>
        private async Task <long> ParseSubmissions(
            JsonElement.ArrayEnumerator array,
            ITargetBlock <CrawlerMessage> pipeline)
        {
            long maxId = 0;

            foreach (var submission in array)
            {
                if (submission.GetProperty("problemType").GetString() != "PROGRAMMING")
                {
                    await pipeline.SendAsync(ErrorMessage(
                                                 "problemType is not PROGRAMMING",
                                                 submission.GetRawText()));

                    continue;
                }

                var idStr = submission.GetProperty("id").GetString();
                var id    = long.Parse(idStr);
                maxId = Math.Max(id, maxId);

                try
                {
                    await pipeline.SendAsync(new CrawlerMessage
                    {
                        Submission = new Submission
                        {
                            OnlineJudgeId = OnlineJudge,
                            SubmissionId  = id,
                            UserName      = submission.GetProperty("user")
                                            .GetProperty("user")
                                            .GetProperty("nickname")
                                            .GetString(),
                            Status       = ParseStatus(submission.GetProperty("status").GetString()),
                            ProblemLabel = submission.GetProperty("problemSetProblem")
                                           .GetProperty("label")
                                           .GetString(),
                            Time = DateTime.Parse(submission.GetProperty("submitAt").GetString()),
                        },
                        Checkpoint = true,
                    });
                }
                catch (KeyNotFoundException e)
                {
                    await pipeline.SendAsync(ErrorMessage(
                                                 e.Message, submission.GetRawText()));
                }
            }

            return(maxId);
        }
Example #13
0
        private async Task <string[]> GetTenRandomIso2Codes()
        {
            // Download a hundred Iso2Codes from worldbank.org.
            JsonElement.ArrayEnumerator array = await IoTDataSource.FetchJsonFromUrl("http://api.worldbank.org/v2/country?format=json&per_page=100");

            // Remove array wrapper from the Json.
            JsonElement.ArrayEnumerator countries = array.Current.EnumerateArray();
            // Select iso2Codes from array of countries.
            string[] iso2Codes = countries.Select(c => c.GetProperty("iso2Code").GetString()).ToArray();
            // Take 10 sequential codes from the hundred of country data.
            var random = new System.Random();

            return(Enumerable.Range(0, 10).Select(i => random.Next(i * 10, i * 10 + 10)).Select(i => iso2Codes[i]).ToArray());
        }
Example #14
0
        // This method is suitable only for Json in the style pf api.worlbank.org/v2.
        // Specifically the returned Json array mustcontain the first element for header.
        public static async Task <JsonElement.ArrayEnumerator> FetchJsonFromUrl(string url)
        {
            var webClient = new WebClient();
            var response  = await webClient.DownloadStringTaskAsync(url);

            JsonDocument responseJson = JsonDocument.Parse(response);

            JsonElement.ArrayEnumerator array = responseJson.RootElement.EnumerateArray();
            // Enumerate to the header.
            array.MoveNext();
            // Skip the header to the array of countries.
            array.MoveNext();
            return(array);
        }
Example #15
0
        private static async Task <JsonElement> DownloadCountryAsync(int semaphoreNumber, string iso2Code)
        {
            // Proceed only when the semaphore is not zero.
            await semaphores[semaphoreNumber].WaitAsync();

            JsonElement.ArrayEnumerator countryJson = await FetchJsonFromUrl($"http://api.worldbank.org/v2/country/{iso2Code}?format=json");

            // "country" variable represens a single country Json wrapped into array.
            JsonElement country = countryJson.Current;

            if (country.ValueKind != JsonValueKind.Array)
            {
                throw new System.FormatException("Invalid Json Format");
            }
            return(country[0]);
        }
Example #16
0
        private static void GenericObjectOrJsonElementConverterTestHelper <T>(string converterName, object objectValue, string stringValue, bool throws)
        {
            var options = new JsonSerializerOptions();

            JsonConverter <T> converter = (JsonConverter <T>)options.GetConverter(typeof(T));

            Assert.Equal(converterName, converter.GetType().Name);

            ReadOnlySpan <byte> data   = Encoding.UTF8.GetBytes(stringValue);
            Utf8JsonReader      reader = new Utf8JsonReader(data);

            reader.Read();
            T readValue = converter.Read(ref reader, typeof(T), null);

            if (readValue is JsonElement element)
            {
                Assert.Equal(JsonValueKind.Array, element.ValueKind);
                JsonElement.ArrayEnumerator iterator = element.EnumerateArray();
                Assert.True(iterator.MoveNext());
                Assert.Equal(3, iterator.Current.GetInt32());
            }
            else
            {
                Assert.True(false, "Must be JsonElement");
            }

            using (var stream = new MemoryStream())
                using (var writer = new Utf8JsonWriter(stream))
                {
                    if (throws)
                    {
                        Assert.Throws <InvalidOperationException>(() => converter.Write(writer, (T)objectValue, options));
                        Assert.Throws <InvalidOperationException>(() => converter.Write(writer, (T)objectValue, null));
                    }
                    else
                    {
                        converter.Write(writer, (T)objectValue, options);
                        writer.Flush();
                        Assert.Equal(stringValue, Encoding.UTF8.GetString(stream.ToArray()));

                        writer.Reset(stream);
                        converter.Write(writer, (T)objectValue, null); // Test with null option
                        writer.Flush();
                        Assert.Equal(stringValue + stringValue, Encoding.UTF8.GetString(stream.ToArray()));
                    }
                }
        }
Example #17
0
        static void EnumerateEle(JsonElement ele, string indentation)
        {
            switch (ele.ValueKind)
            {
            case JsonValueKind.Object:
                JsonElement.ObjectEnumerator objEnum = ele.EnumerateObject();
                while (objEnum.MoveNext())
                {
                    JsonProperty prop      = objEnum.Current;
                    string       propName  = prop.Name;
                    JsonElement  propValue = prop.Value;
                    switch (propValue.ValueKind)
                    {
                    case JsonValueKind.Object:
                        EnumerateEle(propValue, indentation + "  ");
                        break;

                    case JsonValueKind.Array:
                        Console.WriteLine(indentation + $"{propName} is an array of length {propValue.GetArrayLength()}");
                        EnumerateEle(propValue, indentation + "      ");
                        break;

                    default:
                        Console.WriteLine(indentation + $"{propName}: {propValue}");
                        break;
                    }
                }
                break;

            case JsonValueKind.Array:
                JsonElement.ArrayEnumerator arrEnum = ele.EnumerateArray();
                int i = 1;
                while (arrEnum.MoveNext())
                {
                    Console.WriteLine(indentation + $"Item {i} of {ele.GetArrayLength()}");
                    EnumerateEle(arrEnum.Current, indentation + "  ");
                    Console.WriteLine();
                    i++;
                }
                break;

            default:
                Console.WriteLine(indentation + ele);
                break;
            }
        }
Example #18
0
        public async Task <IActionResult> StartPayment([FromHeader] string id, [FromHeader] string name,
                                                       [FromHeader] string email, [FromHeader] string address, [FromBody] JsonElement data)
        {
            // data should have an array of orders
            if (data.ValueKind != JsonValueKind.Array)
            {
                return(BadRequest());
            }

            JsonElement.ArrayEnumerator enumerator = data.EnumerateArray();
            if (enumerator.Count() < 1)
            {
                return(BadRequest());
            }

            Order _order = new Order
            {
                TransactionId = id,
                Name          = name,
                Email         = email,
                Address       = address
            };

            // Loop through each order
            foreach (JsonElement product in enumerator)
            {
                if (product.ValueKind != JsonValueKind.String)
                {
                    return(BadRequest());
                }

                _order.ProductsIds.Add(product.GetString());
            }

            // Add to DB
            await _context.Order.AddAsync(_order);

            await _context.SaveChangesAsync();

            // Add to payment manager waiting for the payment processor's webhook
            _system.StartPayment(_order);
            // Returns id of order so that it can be used to track the order when a webhook is recieved
            return(Ok(_order.Id));
        }
        // this method should ideally be implemented using a proper JSON library,
        // but for the purpose of demonstrating which infos are needed from
        // the file header the built in scripting solution should be sufficient
        public void parseBCKeyFile(string keyFilePath)
        {
            Console.WriteLine("Parsing .bckey file: '" + keyFilePath + "'");

            if (!keyFilePath.Substring(keyFilePath.Length - 6).Equals(".bckey"))
            {
                throw new SystemException("Given filepath does not have the right extension ('.bckey'), please specify a Boxcryptor key file");
            }

            // Check if file is a regular file
            // Note: Possibly more FileAttributes other than 'Normal' and 'Archive' should be allowed
            FileAttributes attributes = File.GetAttributes(keyFilePath);

            if (attributes != FileAttributes.Normal && attributes != FileAttributes.Archive)
            {
                throw new SystemException("Encrypted file (" + keyFilePath + ") can't be opened (make sure the provided path "
                                          + "is correct, the file exists and you have the right to open the file)");
            }

            this.bcKeyFilePath = keyFilePath;

            try
            {
                byte[] keyFileDate = File.ReadAllBytes(Path.GetFullPath(keyFilePath));

                // parse the json data in .bckey-file
                string       keyFileContents = File.ReadAllText(keyFilePath, UTF8Encoding.UTF8);
                JsonDocument doc             = JsonDocument.Parse(keyFileContents);
                JsonElement  root            = doc.RootElement;
                JsonElement  userInfo        = root.GetProperty("users");
                JsonElement.ArrayEnumerator userInfoArray = userInfo.EnumerateArray();
                List <JsonElement>          userInfoList  = userInfoArray.ToList <JsonElement>();
                this.encryptedPrivateKey = userInfoList[0].GetProperty("privateKey").GetString();
                this.pbkdf2Salt          = userInfoList[0].GetProperty("salt").GetString();
                this.pbkdf2Iterations    = userInfoList[0].GetProperty("kdfIterations").GetInt32();
            }
            catch (IOException e)
            {
                throw new SystemException("BCKey file could not be parsed", e);
            }

            Console.WriteLine("Parsing finished");
        }
Example #20
0
        private static void Display(JsonElement.ArrayEnumerator results)
        {
            Console.WriteLine("Web Api result: \n");

            foreach (JsonElement element in results)
            {
                var id   = -1;
                var name = string.Empty;

                if (element.TryGetProperty("id", out JsonElement idElement))
                {
                    id = idElement.GetInt32();
                }
                if (element.TryGetProperty("name", out JsonElement nameElement))
                {
                    name = nameElement.GetString();
                }
                Console.WriteLine($"ID: {id} - {name}");
            }
        }
        /// <summary>
        /// Dynamically identifies the registration endpoint.
        /// </summary>
        /// <returns>NuGet registration endpoint</returns>
        private async Task <string> GetRegistrationEndpointAsync()
        {
            if (RegistrationEndpoint != null)
            {
                return(RegistrationEndpoint);
            }

            try
            {
                HttpClient   httpClient = CreateHttpClient();
                JsonDocument doc        = await GetJsonCache(httpClient, $"{ENV_NUGET_ENDPOINT_API}/v3/index.json");

                JsonElement.ArrayEnumerator resources = doc.RootElement.GetProperty("resources").EnumerateArray();
                foreach (JsonElement resource in resources)
                {
                    try
                    {
                        string?_type = resource.GetProperty("@type").GetString();
                        if (_type != null && _type.Equals("RegistrationsBaseUrl/Versioned", StringComparison.InvariantCultureIgnoreCase))
                        {
                            string?_id = resource.GetProperty("@id").GetString();
                            if (!string.IsNullOrWhiteSpace(_id))
                            {
                                RegistrationEndpoint = _id;
                                return(_id);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Debug(ex, "Error parsing NuGet API endpoint: {0}", ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Debug(ex, "Error parsing NuGet API endpoint: {0}", ex.Message);
            }
            RegistrationEndpoint = NUGET_DEFAULT_REGISTRATION_ENDPOINT;
            return(RegistrationEndpoint);
        }
Example #22
0
        public override AnalyzerContext Read(ref Utf8JsonReader reader, Type typeToConvert,
                                             JsonSerializerOptions options)
        {
            JsonDocument.TryParseValue(ref reader, out JsonDocument document);
            JsonElement.ArrayEnumerator metricMap =
                document.RootElement.GetProperty(SerdeExt.METRIC_MAP_FIELD).EnumerateArray();

            IEnumerable <KeyValuePair <IAnalyzer <IMetric>, IMetric> > result = metricMap.Select(element =>
            {
                JsonElement serializedAnalyzer = element.GetProperty(SerdeExt.ANALYZER_FIELD);
                IAnalyzer <IMetric> analyzer   =
                    JsonSerializer.Deserialize <IAnalyzer <IMetric> >(serializedAnalyzer.GetRawText(), options);

                JsonElement serializedMetric = element.GetProperty(SerdeExt.METRIC_FIELD);
                IMetric metric = JsonSerializer.Deserialize <IMetric>(serializedMetric.GetRawText(), options);

                return(new KeyValuePair <IAnalyzer <IMetric>, IMetric>(analyzer, metric));
            });

            return(new AnalyzerContext(new Dictionary <IAnalyzer <IMetric>, IMetric>(result)));
        }
Example #23
0
        public void ParseBCKeyFile(string keyFilePath)
        {
            Console.WriteLine($"Parsing .bckey file: '{keyFilePath}'");

            if (!keyFilePath.EndsWith(".bckey"))
            {
                throw new Exception("Given filepath does not have the right extension ('.bckey'), please specify a Boxcryptor key file");
            }

            try
            {
                byte[] keyFileDate = File.ReadAllBytes(Path.GetFullPath(keyFilePath));

                // parse the json data in .bckey-file
                string       keyFileContents = File.ReadAllText(keyFilePath, UTF8Encoding.UTF8);
                JsonDocument doc             = JsonDocument.Parse(keyFileContents);
                JsonElement  root            = doc.RootElement;
                JsonElement  userInfo        = root.GetProperty("users");
                JsonElement.ArrayEnumerator userInfoArray = userInfo.EnumerateArray();
                List <JsonElement>          userInfoList  = userInfoArray.ToList <JsonElement>();
                this.EncryptedPrivateKey = userInfoList[0].GetProperty("privateKey").GetString();
                this.PBKDF2Salt          = userInfoList[0].GetProperty("salt").GetString();
                this.PBKDF2Iterations    = userInfoList[0].GetProperty("kdfIterations").GetInt32();
            }
            catch (Exception e)
            {
                if (e is IOException)
                {
                    throw new Exception("BCKey file ({keyFilePath}) could not be parsed", e);
                }
                else
                {
                    throw new Exception("BCKey file ({keyFilePath}) could not be opened (make sure the provided path "
                                        + "is correct, the file exists and you have the right to open the file)", e);
                }
                throw;
            }

            Console.WriteLine("Parsing finished");
        }
Example #24
0
        List <int> GetAllProducts(JsonElement.ArrayEnumerator elements, Dictionary <string, Dictionary <int, string> > features, ProductModel product)
        {
            var list = new List <int>();

            foreach (var item in elements)
            {
                int productId = item.GetProperty("ProductId").GetInt32();
                try
                {
                    if (productId == product.Id)
                    {
                        var featureDic = new Dictionary <string, string>();
                        if (item.TryGetProperty("SpecificationValueIds", out var svIdElement) && svIdElement.ValueKind == JsonValueKind.Array)
                        {
                            foreach (var value in svIdElement.EnumerateArray())
                            {
                                int id      = value.GetInt32();
                                var feature = features.FirstOrDefault(f => f.Value.Keys.Any(k => k == id));
                                if (featureDic.Keys.Any(k => k == feature.Key))
                                {
                                    continue;
                                }
                                featureDic.Add(feature.Key, feature.Value[id]);
                            }
                        }
                        product.Thumbnails  = item.TryGetProperty("Thumbnails", out var thumbnailsElement) ? thumbnailsElement.GetString() : product.MainImgs;
                        product.Features    = Newtonsoft.Json.JsonConvert.SerializeObject(featureDic);
                        product.CostPrice   = item.GetProperty("Price1").GetDecimal();
                        product.CustomPrice = item.GetProperty("Price2").GetDecimal();
                    }
                    list.Add(productId);
                }
                catch (Exception ex)
                {
                    this.Logger.Error($"解析商品{productId}规格异常", ex);
                }
            }
            return(list);
        }
Example #25
0
        /// <summary>
        /// 解析每一个商品
        /// </summary>
        /// <param name="elements"></param>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        List <ProductModel> ParseItem(JsonElement.ArrayEnumerator elements, int categoryId)
        {
            var list = new List <ProductModel>();

            foreach (var item in elements)//一页数据
            {
                //需要加载每个商品详情(每一种规格都需要加载)
                try
                {
                    var products = GetAllProductDetail(item.GetProperty("ID").GetInt32(), categoryId);
                    list.AddRange(products);
                    // this.Context.ProductModels.AddRangeAsync(list);
                    // this.Context.SaveChangesAsync();
                }
                catch (Exception ex)
                {
                    this.Logger.Error("解析商品详情异常", ex);
                    System.Threading.Thread.Sleep(1000);
                }
            }
            return(list);
        }
Example #26
0
        public static void TestArrayEnumerator()
        {
            var jsonArray = new JsonArray()
            {
                1, 2, 3
            };
            JsonElement jsonArrayElement = jsonArray.AsJsonElement();

            JsonElement.ArrayEnumerator arrayEnumerator = jsonArrayElement.EnumerateArray();

            for (int i = 1; i <= 3; i++)
            {
                Assert.True(arrayEnumerator.MoveNext());
                Assert.Equal(i, arrayEnumerator.Current.GetInt32());
            }

            Assert.False(arrayEnumerator.MoveNext());
            Assert.False(arrayEnumerator.MoveNext());

            JsonElement notArray = new JsonObject().AsJsonElement();

            Assert.Throws <InvalidOperationException>(() => notArray.EnumerateArray());
        }
Example #27
0
        public async Task <List <WikiSearch> > SearchAsync(string query, int limit = 5)
        {
            using HttpClient http = _http.CreateClient();
            string result = await http.GetStringAsync($"{ApiUrl}&list=search&srsearch={query}&srlimit={limit}&format=json").ConfigureAwait(false);

            using JsonDocument json = JsonDocument.Parse(result);
            JsonElement queryElement = json.RootElement.GetProperty("query");

            JsonElement searchInfo = queryElement.GetProperty("searchinfo");
            int         hits       = searchInfo.GetProperty("totalhits").GetInt32();

            var results = new List <WikiSearch>();

            if (hits != 0)
            {
                JsonElement.ArrayEnumerator enumerator = queryElement.GetProperty("search").EnumerateArray();

                foreach (JsonElement page in enumerator)
                {
                    string snippet = page.GetProperty("snippet").GetString() !.Replace(@"<span class=""searchmatch"">", "**").Replace("</span>", "**");
                    results.Add(new WikiSearch
                    {
                        Title   = page.GetProperty("title").GetString(),
                        Snippet = HttpUtility.HtmlDecode(snippet)
                    });
                }
            }
            else if (searchInfo.TryGetProperty("suggestion", out JsonElement suggestion))
            {
                results.Add(new WikiSearch
                {
                    Title = suggestion.GetString()
                });
            }

            return(results);
        }
Example #28
0
        protected void AssertJsonObject(JsonElement.ArrayEnumerator expected, object actual)
        {
            var actualList = (actual as IEnumerable)?.Cast <object>().ToList();

            if (actualList is null && actual.GetType().GetGenericTypeDefinition() == typeof(KeyValuePair <,>))
            {
                // Cast KeyValuePair to a list
                dynamic kvp = actual;
                actualList = new List <object> {
                    kvp.Key, kvp.Value
                };
            }
            if (actualList is null)
            {
                throw new InvalidOperationException($"Expected an object that's castable to an enumerable for {expected}");
            }

            var expectedList = expected.ToList();

            for (int i = 0; i < expectedList.Count; i++)
            {
                this.AssertJsonObject(expectedList[i], actualList[i]);
            }
        }
Example #29
0
        // Loads all the custom Layouts from tmp file passed by FancyZonesLib
        public static ObservableCollection <LayoutModel> LoadCustomModels()
        {
            _customModels = new ObservableCollection <LayoutModel>();

            try
            {
                FileStream   inputStream = File.Open(Settings.FancyZonesSettingsFile, FileMode.Open);
                JsonDocument jsonObject  = JsonDocument.Parse(inputStream, options: default);
                JsonElement.ArrayEnumerator customZoneSetsEnumerator = jsonObject.RootElement.GetProperty(CustomZoneSetsJsonTag).EnumerateArray();

                while (customZoneSetsEnumerator.MoveNext())
                {
                    var    current = customZoneSetsEnumerator.Current;
                    string name    = current.GetProperty(NameStr).GetString();
                    string type    = current.GetProperty(TypeJsonTag).GetString();
                    string uuid    = current.GetProperty(UuidJsonTag).GetString();
                    var    info    = current.GetProperty(InfoJsonTag);

                    if (type.Equals(GridJsonTag))
                    {
                        bool error = false;

                        int rows    = info.GetProperty(RowsJsonTag).GetInt32();
                        int columns = info.GetProperty(ColumnsJsonTag).GetInt32();

                        List <int> rowsPercentage = new List <int>(rows);
                        JsonElement.ArrayEnumerator rowsPercentageEnumerator = info.GetProperty(RowsPercentageJsonTag).EnumerateArray();

                        List <int> columnsPercentage = new List <int>(columns);
                        JsonElement.ArrayEnumerator columnsPercentageEnumerator = info.GetProperty(ColumnsPercentageJsonTag).EnumerateArray();

                        if (rows <= 0 || columns <= 0 || rowsPercentageEnumerator.Count() != rows || columnsPercentageEnumerator.Count() != columns)
                        {
                            error = true;
                        }

                        while (!error && rowsPercentageEnumerator.MoveNext())
                        {
                            int percentage = rowsPercentageEnumerator.Current.GetInt32();
                            if (percentage <= 0)
                            {
                                error = true;
                                break;
                            }

                            rowsPercentage.Add(percentage);
                        }

                        while (!error && columnsPercentageEnumerator.MoveNext())
                        {
                            int percentage = columnsPercentageEnumerator.Current.GetInt32();
                            if (percentage <= 0)
                            {
                                error = true;
                                break;
                            }

                            columnsPercentage.Add(percentage);
                        }

                        int i = 0;
                        JsonElement.ArrayEnumerator cellChildMapRows = info.GetProperty(CellChildMapJsonTag).EnumerateArray();
                        int[,] cellChildMap = new int[rows, columns];

                        if (cellChildMapRows.Count() != rows)
                        {
                            error = true;
                        }

                        while (!error && cellChildMapRows.MoveNext())
                        {
                            int j = 0;
                            JsonElement.ArrayEnumerator cellChildMapRowElems = cellChildMapRows.Current.EnumerateArray();
                            if (cellChildMapRowElems.Count() != columns)
                            {
                                error = true;
                                break;
                            }

                            while (cellChildMapRowElems.MoveNext())
                            {
                                cellChildMap[i, j++] = cellChildMapRowElems.Current.GetInt32();
                            }

                            i++;
                        }

                        if (error)
                        {
                            ShowExceptionMessageBox(string.Format(ErrorLayoutMalformedData, name));
                            continue;
                        }

                        _customModels.Add(new GridLayoutModel(uuid, name, LayoutType.Custom, rows, columns, rowsPercentage, columnsPercentage, cellChildMap));
                    }
                    else if (type.Equals(CanvasJsonTag))
                    {
                        int lastWorkAreaWidth  = info.GetProperty(RefWidthJsonTag).GetInt32();
                        int lastWorkAreaHeight = info.GetProperty(RefHeightJsonTag).GetInt32();

                        JsonElement.ArrayEnumerator zonesEnumerator = info.GetProperty(ZonesJsonTag).EnumerateArray();
                        IList <Int32Rect>           zones           = new List <Int32Rect>();

                        bool error = false;

                        if (lastWorkAreaWidth <= 0 || lastWorkAreaHeight <= 0)
                        {
                            error = true;
                        }

                        while (!error && zonesEnumerator.MoveNext())
                        {
                            int x      = zonesEnumerator.Current.GetProperty(XJsonTag).GetInt32();
                            int y      = zonesEnumerator.Current.GetProperty(YJsonTag).GetInt32();
                            int width  = zonesEnumerator.Current.GetProperty(WidthJsonTag).GetInt32();
                            int height = zonesEnumerator.Current.GetProperty(HeightJsonTag).GetInt32();

                            if (width <= 0 || height <= 0)
                            {
                                error = true;
                                break;
                            }

                            zones.Add(new Int32Rect(x, y, width, height));
                        }

                        if (error)
                        {
                            ShowExceptionMessageBox(string.Format(ErrorLayoutMalformedData, name));
                            continue;
                        }

                        _customModels.Add(new CanvasLayoutModel(uuid, name, LayoutType.Custom, zones, lastWorkAreaWidth, lastWorkAreaHeight));
                    }
                }

                inputStream.Close();
            }
            catch (Exception ex)
            {
                ShowExceptionMessageBox(ErrorLoadingCustomLayouts, ex);
                return(new ObservableCollection <LayoutModel>());
            }

            return(_customModels);
        }
Example #30
0
        public static void DynamicKeyword()
        {
            dynamic myDynamic = GetExpandoObject();

            // STJ serializes ExpandoObject as IDictionary<string, object>;
            // there is no custom converter for ExpandoObject.
            string json = JsonSerializer.Serialize <dynamic>(myDynamic);

            JsonTestHelper.AssertJsonEqual(Json, json);

            dynamic d = JsonSerializer.Deserialize <dynamic>(json);

            try
            {
                // We will get an exception here if we try to access a dynamic property since 'object' is deserialized
                // as a JsonElement and not an ExpandoObject.
                int c = d.MyInt;
                Assert.True(false, "Should have thrown Exception!");
            }
            catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) { }

            Assert.IsType <JsonElement>(d);
            JsonElement elem = (JsonElement)d;

            VerifyPrimitives();
            VerifyObject();
            VerifyArray();

            // Re-serialize
            json = JsonSerializer.Serialize <object>(elem);
            JsonTestHelper.AssertJsonEqual(Json, json);

            json = JsonSerializer.Serialize <dynamic>(elem);
            JsonTestHelper.AssertJsonEqual(Json, json);

            json = JsonSerializer.Serialize(elem);
            JsonTestHelper.AssertJsonEqual(Json, json);

            void VerifyPrimitives()
            {
                Assert.Equal("Hello", elem.GetProperty("MyString").GetString());
                Assert.True(elem.GetProperty("MyBoolean").GetBoolean());
                Assert.Equal(42, elem.GetProperty("MyInt").GetInt32());
                Assert.Equal(MyDateTime, elem.GetProperty("MyDateTime").GetDateTime());
                Assert.Equal(MyGuid, elem.GetProperty("MyGuid").GetGuid());
            }

            void VerifyObject()
            {
                Assert.Equal("World", elem.GetProperty("MyObject").GetProperty("MyString").GetString());
            }

            void VerifyArray()
            {
                JsonElement.ArrayEnumerator enumerator = elem.GetProperty("MyArray").EnumerateArray();
                Assert.Equal(2, enumerator.Count());
                enumerator.MoveNext();
                Assert.Equal(1, enumerator.Current.GetInt32());
                enumerator.MoveNext();
                Assert.Equal(2, enumerator.Current.GetInt32());
            }
        }