コード例 #1
0
        public static void Dispatch(MessageBuffer message)
        {
            if (message == null)
            {
                return;
            }
            int id = message.id();

            Type type = GetType((MessageID)id);

            if (type == null)
            {
                return;
            }

            //string jsonStr = Convert.ToBase64String(message.body());
            object data = JsonSerializerUtil.FromJsonByte(message.body(), type);

            //object data = ProtoTransfer.DeserializeProtoBuf(message.body(), type);
            if (data == null)
            {
                return;
            }

            mDispatcher.Dispatch(id, data, type);
        }
コード例 #2
0
        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));
        }
コード例 #3
0
        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();
        }
コード例 #4
0
    public T Get <T>() where T : class, ProtoBuf.IExtensible
    {
        T t = JsonSerializerUtil.FromJsonByte <T>(mData);

        //ProtoTransfer.DeserializeProtoBuf<T>(mData);
        return(t);
    }
コード例 #5
0
ファイル: User.cs プロジェクト: xuewenjie/LockStepLearingDemo
 public void SendTcp <T>(MessageID messageId, T t)
 {
     if (mClient != null)
     {
         byte[] data = JsonSerializerUtil.ToJsonByte <T>(t);
         //ProtoTransfer.SerializeProtoBuf<T>(t);
         MessageBuffer message = new MessageBuffer((int)messageId, data, mClient.id);
         mClient.SendTcp(message);
     }
 }
コード例 #6
0
        public async Task IncreaseInvisibilityAsync(ProvisioningQueueParentDto message, int invisibleForInSeconds)
        {
            _logger.LogInformation($"Queue: Increasing message invisibility for {message.MessageId} with description \"{message.Description}\" by {invisibleForInSeconds} seconds.");
            var messageAsJson = JsonSerializerUtil.Serialize(message);
            var updateReceipt = await _queueService.UpdateMessageAsync(message.MessageId, message.PopReceipt, messageAsJson, invisibleForInSeconds);
            message.PopReceipt = updateReceipt.PopReceipt;
            message.NextVisibleOn = updateReceipt.NextVisibleOn;
            _logger.LogInformation($"Queue: Message {message.MessageId} will be visible again at {updateReceipt.NextVisibleOn} (UTC)");

        }
コード例 #7
0
        private void OnMessage(Session client, MessageBuffer msg)
        {
            MessageID messageId = (MessageID)msg.id();

            switch (messageId)
            {
            case MessageID.GM_ACCEPT_CS:
            {
                GM_Accept recvData = JsonSerializerUtil.FromJsonByte <GM_Accept>(msg.body());
                //ProtoTransfer.DeserializeProtoBuf<GM_Accept>(msg);
                if (recvData.conv == client.id)
                {
                    OnConnect(client, recvData.roleId);
                }
            }
            break;

            case MessageID.GM_READY_CS:
            {
                GM_Ready recvData = JsonSerializerUtil.FromJsonByte <GM_Ready>(msg.body());
                //ProtoTransfer.DeserializeProtoBuf<GM_Ready>(msg);
                OnReceiveReady(client, recvData);
            }
            break;

            case MessageID.GM_FRAME_CS:
            {
                GM_Frame recvData = JsonSerializerUtil.FromJsonByte <GM_Frame>(msg.body());
                //ProtoTransfer.DeserializeProtoBuf<GM_Frame>(msg);
                if (mMode == Mode.LockStep)
                {
                    OnLockStepFrame(client, recvData);
                }
                else
                {
                    OnOptimisticFrame(client, recvData);
                }
            }
            break;

            case MessageID.GM_PING_CS:
            {
                GM_Request recvData = JsonSerializerUtil.FromJsonByte <GM_Request>(msg.body());
                //ProtoTransfer.DeserializeProtoBuf<GM_Request>(msg);
                User u = GetUser(recvData.id);
                if (u != null)
                {
                    GM_Return sendData = new GM_Return();
                    sendData.id = recvData.id;
                    u.SendTcp(MessageID.GM_PING_SC, sendData);
                }
            }
            break;
            }
        }
コード例 #8
0
        private void OnAccept(Session c)
        {
            GM_Accept sendData = new GM_Accept();

            sendData.conv = c.id;

            byte[]        data    = JsonSerializerUtil.ToJsonByte(sendData);
            MessageBuffer message = new MessageBuffer((int)MessageID.GM_ACCEPT_SC, data, c.id);

            c.SendTcp(message);
        }
コード例 #9
0
        public static JsonResponse CreateErrorMessageResult(string requestId, string message, HttpStatusCode statusCode = HttpStatusCode.InternalServerError)
        {
            var content = JsonSerializerUtil.Serialize(new Common.Dto.ErrorResponse
            {
                Message   = message,
                RequestId = requestId
            });

            return(new JsonResponse {
                Content = content, StatusCode = statusCode
            });
        }
コード例 #10
0
        public async Task<ProvisioningQueueParentDto> SendMessageAsync(ProvisioningQueueParentDto message, TimeSpan? visibilityTimeout = null, CancellationToken cancellationToken = default)
        {
            _logger.LogInformation($"Queue: Adding message: {message.Description}, having {message.Children.Count} children");
            var serializedMessage = JsonSerializerUtil.Serialize(message);
            var sendtMessage = await _queueService.SendMessageAsync(serializedMessage, visibilityTimeout, cancellationToken);

            message.MessageId = sendtMessage.MessageId;
            message.PopReceipt = sendtMessage.PopReceipt;
            message.NextVisibleOn = sendtMessage.NextVisibleOn;

            return message;

        }
コード例 #11
0
        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));
            }
        }
コード例 #12
0
        private RedisCache()
        {
            string cacheConfigString = AppContext.CacheConfigString;
            string appUri            = LocationHelper.Instance.GetAppUri(AppNameEnum.RedisSvc);

            cacheConfigString = (string.IsNullOrEmpty(cacheConfigString) ? appUri.Replace("http://", string.Empty).Trim(new char[] { '/' }) : cacheConfigString);
            ConfigurationOptions configurationOption = ConfigurationOptions.Parse(cacheConfigString);

            if (configurationOption.EndPoints.Count == 0)
            {
                configurationOption.EndPoints.Add(appUri);
            }
            this.redis = ConnectionMultiplexer.Connect(configurationOption, null);
            this.db    = this.redis.GetDatabase(-1, null);
            DebugUtil.CollectDebugInfo(JsonSerializerUtil.Serialize <ConfigurationOptions>(configurationOption));
        }
コード例 #13
0
        ///// <summary>
        ///// 通过UDP发送
        ///// </summary>
        ///// <typeparam name="T"></typeparam>
        ///// <param name="messageId"></param>
        ///// <param name="data"></param>
        //public void SendUdp<T>(ClientID clientID, MessageID id, T data) where T : class, ProtoBuf.IExtensible
        //{
        //    var client = GetClient(clientID);

        //    if(client== null)
        //    {
        //        return;
        //    }

        //    byte[] bytes = ProtoTransfer.SerializeProtoBuf<T>(data);

        //    MessageBuffer buffer = new MessageBuffer((int)id, bytes, client.acceptSock);

        //    client.SendUdp(buffer);
        //}

        /// <summary>
        /// 通过TCP协议发送
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="messageId"></param>
        /// <param name="data"></param>
        public void SendTcp <T>(ClientID clientID, MessageID id, T data) where T : class, ProtoBuf.IExtensible
        {
            var client = GetClient(clientID);

            if (client == null)
            {
                return;
            }

            //byte[] bytes = ProtoTransfer.SerializeProtoBuf<T>(data);
            byte[] bytes = JsonSerializerUtil.ToJsonByte <T>(data);

            MessageBuffer buffer = new MessageBuffer((int)id, bytes, client.acceptSock);

            client.SendTcp(buffer);
        }
コード例 #14
0
        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);
        }
コード例 #15
0
ファイル: RestHelper.cs プロジェクト: equinor/sepes-api
        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);
        }
コード例 #16
0
        // 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;
        }
コード例 #17
0
        public ICacheResult <T> Set <T>(string key, T value, int expiredTime = 3600)
        {
            CacheResult <T> cacheResult = new CacheResult <T>()
            {
                Success = false,
                Status  = Status.None
            };
            CacheResult <T> cacheResult1 = cacheResult;

            expiredTime = (expiredTime <= 0 ? 3600 : expiredTime);
            try
            {
                string str = JsonSerializerUtil.Serialize <T>(value);
                cacheResult1.Success = this.db.StringSet(KeyGen.AttachPrefixToKey(key), str, new TimeSpan?(new TimeSpan(0, 0, expiredTime)), 0, 0);
                cacheResult1.Status  = Status.Success;
            }
            catch (Exception exception)
            {
                cacheResult1.Exception = exception;
            }
            return(cacheResult1);
        }
コード例 #18
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);
        }
コード例 #19
0
        public async Task <AzureRoleAssignment> AddRoleAssignment(string resourceId, string roleDefinitionId, string principalId, string roleAssignmentId = null, CancellationToken cancellationToken = default)
        {
            try
            {
                if (String.IsNullOrWhiteSpace(roleAssignmentId))
                {
                    roleAssignmentId = Guid.NewGuid().ToString();
                }

                var addRoleUrl = $"https://management.azure.com{resourceId}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentId}?api-version=2015-07-01";

                var body     = new AzureRoleAssignmentRequestDto(roleDefinitionId, principalId);
                var bodyJson = new StringContent(JsonSerializerUtil.Serialize(body), Encoding.UTF8, "application/json");

                var result = await PerformRequest <AzureRoleAssignment>(addRoleUrl, HttpMethod.Put, bodyJson, true, cancellationToken : cancellationToken);

                return(result);
            }
            catch (Exception ex)
            {
                throw new Exception($"Add role assignment with id {roleAssignmentId} failed for resource {resourceId}. Role definition: {roleDefinitionId}, principalId: {principalId}", ex);
            }
        }
コード例 #20
0
ファイル: TagUtils.cs プロジェクト: equinor/sepes-api
 public static string TagDictionaryToString(Dictionary <string, string> tags)
 {
     return(JsonSerializerUtil.Serialize(tags));
 }
コード例 #21
0
        public async Task Run([QueueTrigger(queueName: "sandbox-resource-operations-queue")] QueueMessage queueMessage)
        {
            //var queueMessage = JsonSerializer.Deserialize<QueueMessage>(messageText);
            _logger.LogInformation($"Processing message: {queueMessage.MessageId}, pop count: {queueMessage.DequeueCount}, exp: {queueMessage.ExpiresOn}, next visible: { queueMessage.NextVisibleOn}");

            var transformedQueueItem = JsonSerializer.Deserialize <ProvisioningQueueParentDto>(queueMessage.Body, JsonSerializerUtil.GetDefaultOptions());

            transformedQueueItem.MessageId    = queueMessage.MessageId;
            transformedQueueItem.PopReceipt   = queueMessage.PopReceipt;
            transformedQueueItem.DequeueCount = Convert.ToInt32(queueMessage.DequeueCount);

            await _provisioningService.HandleWork(transformedQueueItem);
        }
コード例 #22
0
ファイル: TagUtils.cs プロジェクト: equinor/sepes-api
 public static Dictionary <string, string> TagStringToDictionary(string tags)
 {
     return(JsonSerializerUtil.Deserialize <Dictionary <string, string> >(tags));
 }
コード例 #23
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());
            }
        }
コード例 #24
0
 public object Get(Type type)
 {
     return(JsonSerializerUtil.FromJsonByte(mData, type));
     //ProtoTransfer.DeserializeProtoBuf(mData, type);
 }
コード例 #25
0
 public void Set <T>(CommandID type, T t) where T : class, ProtoBuf.IExtensible
 {
     mType = (int)type;
     mData = JsonSerializerUtil.ToJsonByte <T>(t);
     //ProtoTransfer.SerializeProtoBuf<T>(t);
 }