static void Main(string[] args)
        {
            string jsonString  = "{\"data\":[{\"key\":\"Audio\",\"it.e][\\\"ms\":[{\"key\":\"Bluetooth Headphones\",\"items\":null,\"count\":13482,\"summary\":[12099500.9899]}]}],\"totalCount\":1000000,\"summary\":[3638256074.5103]}";
            string jsonString2 = "[[{\"key\":\"Bluetooth Headphones\",\"items\":null,\"count\":13482,\"summary\":[12099500.9899]}],[\"value\"]]";
            string jsonString1 = "{\"ABC\": [\"a\", \"b\"]}";
            var    obj         = JsonSerializerUtil.Deserialize(jsonString);

            Console.WriteLine("Enter conversion option (0: Default, 1: JToken): ");
            var convertOption = Console.ReadLine();

            Console.Clear();
            if (convertOption == "1")
            {
                Console.WriteLine("Converting JSON to Object Initializer using Token types");
                string objectIniOutput = new JTokenConverter().ConstructObjectInitializerFormat(obj);
                Console.WriteLine(objectIniOutput);
            }
            else if (convertOption == "0")
            {
                Console.WriteLine("Converting JSON to Object Initializer using Property names");
                string objectIniOutput = new DefaultConverter().ConstructObjectInitializerFormat(obj);
                Console.WriteLine(objectIniOutput);
            }
            else
            {
                Console.WriteLine("Invalid option provided.");
            }

            Console.ReadLine();
        }
        public async Task <string> GetIp(string curIpUrl, CancellationToken cancellation = default)
        {
            using (var client = new HttpClient())
            {
                HttpResponseMessage responseMessage = null;

                try
                {
                    responseMessage = await client.GetAsync(curIpUrl, cancellation);

                    if (responseMessage.IsSuccessStatusCode)
                    {
                        var responseString = await responseMessage.Content.ReadAsStringAsync();

                        var deserializedResponse = JsonSerializerUtil.Deserialize <IpAddressResponse>(await responseMessage.Content.ReadAsStringAsync());

                        return(deserializedResponse.ip);
                    }
                    else
                    {
                        throw new Exception(await CreateErrorMessage(curIpUrl, responseMessage: responseMessage));
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(await CreateErrorMessage(curIpUrl, responseMessage: responseMessage, exception: ex), ex);
                }
            }

            throw new Exception(await CreateErrorMessage(curIpUrl));
        }
        public async Task <List <AzureResourceSku> > GetSKUsForRegion(string region, string resourceType = null, bool filterBasedOnResponseRestrictions = true, CancellationToken cancellationToken = default)
        {
            using (var client = new Microsoft.Azure.Management.Compute.ComputeManagementClient(_credentials))
            {
                client.SubscriptionId = _subscriptionId;

                var skus = await client.ResourceSkus.ListWithHttpMessagesAsync($"location eq '{region}'", cancellationToken : cancellationToken);

                var responseText = await skus.Response.Content.ReadAsStringAsync();

                var responseDeserialized = JsonSerializerUtil.Deserialize <AzureSkuResponse>(responseText);

                return(ApplyRelevantFilters(region, responseDeserialized.value, resourceType, filterBasedOnResponseRestrictions));
            }
        }
        public List <MetricSerie> PerformQuery(string db, string query)
        {
            List <MetricSerie> metricSeries;

            ParamterUtil.CheckEmptyString("db", db);
            ParamterUtil.CheckEmptyString("query", query);
            List <MetricSerie> metricSeries1 = new List <MetricSerie>();

            try
            {
                DebugUtil.Log(string.Format("MeasurementHost: performing query '{0}' on db '{1}'.", query, db));
                string appUri = LocationHelper.Instance.GetAppUri(AppNameEnum.MeasurementApi);
                if (string.IsNullOrEmpty(appUri))
                {
                    DebugUtil.Log("MeasurementHost: failed to fetch measurementServerInfo.Uri from location.");
                }
                else
                {
                    string  str     = string.Format("{0}api/measurement/run", appUri);
                    Command command = new Command()
                    {
                        Type = CommandType.Read
                    };
                    command.Parameters.Add("dbname", db);
                    command.Parameters.Add("query", query);
                    FoundationResponse <string> result = ProxyBase.Call <FoundationResponse <string>, Command>(str, command, ApiHttpMethod.POST, 180000, null).Result;
                    if ((result == null ? true : string.IsNullOrEmpty(result.Data)))
                    {
                        DebugUtil.Log(string.Format("MeasurementHost: query '{0}' on db '{1}' return empty.", query, db));
                    }
                    else
                    {
                        metricSeries1 = JsonSerializerUtil.Deserialize <List <MetricSerie> >(result.Data);
                    }
                    metricSeries = metricSeries1;
                    return(metricSeries);
                }
            }
            catch (Exception exception)
            {
                DebugUtil.LogException(exception);
            }
            metricSeries = metricSeries1;
            return(metricSeries);
        }
        // Gets first message as QueueMessage without removing from queue, but makes it invisible for 30 seconds.
        public async Task<ProvisioningQueueParentDto> ReceiveMessageAsync()
        {
            _logger.LogInformation($"Queue: Receive message");
            var messageFromQueue = await _queueService.ReceiveMessageAsync();

            if (messageFromQueue != null)
            {
                var convertedMessage = JsonSerializerUtil.Deserialize<ProvisioningQueueParentDto>(messageFromQueue.MessageText);

                convertedMessage.MessageId = messageFromQueue.MessageId;
                convertedMessage.PopReceipt = messageFromQueue.PopReceipt;
                convertedMessage.NextVisibleOn = messageFromQueue.NextVisibleOn;

                return convertedMessage;
            }

            return null;
        }
示例#6
0
        private async Task <T> GetResponseObject <T>(HttpResponseMessage response)
        {
            if (response.StatusCode == System.Net.HttpStatusCode.NoContent)
            {
                return(default(T));
            }

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

            if (string.IsNullOrWhiteSpace(content))
            {
                return(default(T));
            }

            var deserializedObject = JsonSerializerUtil.Deserialize <T>(content);

            return(deserializedObject);
        }
示例#7
0
        public ICacheResult <T> Get <T>(string key)
        {
            CacheResult <T> cacheResult = new CacheResult <T>()
            {
                Success = false,
                Status  = Status.None
            };
            CacheResult <T> cacheResult1 = cacheResult;

            try
            {
                RedisValue redisValue = this.db.StringGet(KeyGen.AttachPrefixToKey(key), 0);
                cacheResult1.Value   = JsonSerializerUtil.Deserialize <T>(redisValue);
                cacheResult1.Success = true;
                cacheResult1.Status  = Status.Success;
            }
            catch (Exception exception)
            {
                cacheResult1.Exception = exception;
            }
            return(cacheResult1);
        }
示例#8
0
        protected async Task <T> PerformRequest <T>(string url, HttpMethod method, HttpContent content = null, bool needsAuth = true, Dictionary <string, string> additionalHeaders = null, CancellationToken cancellationToken = default)
        {
            if (needsAuth)
            {
                var token = _apiTokenType == ApiTokenType.App ? await _tokenAcquisition.GetAccessTokenForAppAsync(_scope) : await _tokenAcquisition.GetAccessTokenForUserAsync(scopes : new List <string>()
                {
                    _scope
                });

                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            }

            if (additionalHeaders != null)
            {
                foreach (var curHeader in additionalHeaders)
                {
                    _httpClient.DefaultRequestHeaders.Add(curHeader.Key, curHeader.Value);
                }
            }

            HttpResponseMessage responseMessage = null;

            if (method == HttpMethod.Get)
            {
                responseMessage = await _httpClient.GetAsync(url, cancellationToken);
            }
            else if (method == HttpMethod.Post)
            {
                responseMessage = await _httpClient.PostAsync(url, content, cancellationToken);
            }
            else if (method == HttpMethod.Put)
            {
                responseMessage = await _httpClient.PutAsync(url, content, cancellationToken);
            }
            else if (method == HttpMethod.Patch)
            {
                responseMessage = await _httpClient.PatchAsync(url, content, cancellationToken);
            }
            else if (method == HttpMethod.Delete)
            {
                responseMessage = await _httpClient.DeleteAsync(url, cancellationToken);
            }

            if (responseMessage.IsSuccessStatusCode)
            {
                var responseText = await responseMessage.Content.ReadAsStringAsync();

                var deserializedResponse = JsonSerializerUtil.Deserialize <T>(responseText);
                return(deserializedResponse);
            }
            else
            {
                var errorMessageBuilder = new StringBuilder();
                errorMessageBuilder.Append($"{this.GetType()}: Response for {method} against the url {url} failed with status code {responseMessage.StatusCode}");

                if (!String.IsNullOrWhiteSpace(responseMessage.ReasonPhrase))
                {
                    errorMessageBuilder.Append($", reason: {responseMessage.ReasonPhrase}");
                }

                var responseString = await responseMessage.Content.ReadAsStringAsync();

                if (!String.IsNullOrWhiteSpace(responseString))
                {
                    errorMessageBuilder.Append($", response content: {responseString}");
                }

                throw new Exception(errorMessageBuilder.ToString());
            }
        }
示例#9
0
 public static Dictionary <string, string> TagStringToDictionary(string tags)
 {
     return(JsonSerializerUtil.Deserialize <Dictionary <string, string> >(tags));
 }