public IEnumerable <Deck> GetDeckList() { var getPresetsCall = new ApiCallList.Collections.GetPresets(); string response; HttpStatusCode statusCode = ApiManagerInstance.SendRequest(getPresetsCall, out response); if (statusCode != HttpStatusCode.OK) { throw new Exception("GetDeckList SendRequest returned: " + statusCode.ToString()); } dynamic decoded = JsonDecoder.Decode(response); dynamic items = decoded[getPresetsCall.Call]["items"]; foreach (var item in items) { int deckId = int.Parse(item["id"].ToString()); string name = item["name"].ToString(); string deckValue = item["deckValue"].ToString(); IEnumerable <CardInstance> cards = DecodeDeckValue(deckValue); yield return(new Deck(deckId, name, cards)); } // Server response example: //"id" : 14648770, //"name" : "Duel+LD+Missions", //"deckValue" : "289388796#422299407#424125543#424584307#443996560#444106871#449630678#453161946#", //"nbCards" : 8, //"isCurrentDeck" : true }
public static object Deserialize(TextReader text) { JsonDecoder jsonDecoder = new JsonDecoder(); jsonDecoder.parseNumbersAsFloat = true; return(jsonDecoder.Decode(text.ReadToEnd())); }
/// <summary> /// Encode Network Message Header /// </summary> /// <param name="jsonDecoder"></param> private void DecodeNetworkMessageHeader(JsonDecoder jsonDecoder) { object token = null; if (jsonDecoder.ReadField(nameof(MessageId), out token)) { MessageId = jsonDecoder.ReadString(nameof(MessageId)); NetworkMessageContentMask = JsonNetworkMessageContentMask.NetworkMessageHeader; } if (jsonDecoder.ReadField(nameof(MessageType), out token)) { MessageType = jsonDecoder.ReadString(nameof(MessageType)); } if (jsonDecoder.ReadField(nameof(PublisherId), out token)) { PublisherId = jsonDecoder.ReadString(nameof(PublisherId)); NetworkMessageContentMask |= JsonNetworkMessageContentMask.PublisherId; } if (jsonDecoder.ReadField(nameof(DataSetClassId), out token)) { DataSetClassId = jsonDecoder.ReadString(nameof(DataSetClassId)); NetworkMessageContentMask |= JsonNetworkMessageContentMask.DataSetClassId; } }
public void BeforeTest() { fileSystem = new MockFileSystem(); decoder = new JsonDecoder(fileSystem); config = new JsonDecoderConfiguration(); container = new CompositionContainer(); }
private void StartBackgroundReceiver() { Running = true; Task.Factory.StartNew(async() => { while (Running) { dynamic msg = await MessageUtil.ReadMessage(Client); IPacket message = JsonDecoder.Decode(msg); switch (message.Type) { case PacketType.BidMessage: HandleBidMessage((BidMessage)message); break; case PacketType.CarMessage: HandleCarMessage((CarMessage)message); break; case PacketType.OkMessage: HandleOkMessage((OkMessage)message); break; } } }); }
/// <summary> /// Decode RawData type /// </summary> /// <returns></returns> private object DecodeRawData(JsonDecoder jsonDecoder, FieldMetaData fieldMetaData, string fieldName) { if (fieldMetaData.BuiltInType != 0) { try { if (fieldMetaData.ValueRank == ValueRanks.Scalar) { return(DecodeRawScalar(jsonDecoder, fieldMetaData.BuiltInType, fieldName)); } if (fieldMetaData.ValueRank >= ValueRanks.OneDimension) { return(jsonDecoder.ReadArray(fieldName, fieldMetaData.ValueRank, (BuiltInType)fieldMetaData.BuiltInType)); } else { Utils.Trace("JsonDataSetMessage - Decoding ValueRank = {0} not supported yet !!!", fieldMetaData.ValueRank); } } catch (Exception ex) { Utils.Trace(ex, "JsonDataSetMessage - Error reading element for RawData."); return(StatusCodes.BadDecodingError); } } return(null); }
public IEnumerable <int> GetAllCardBaseIds() { var getExistingCardBaseIdsCall = new ApiCallList.Urc.GetCharacters(); getExistingCardBaseIdsCall.ItemsFilter = new List <string>() { "id" }; var request = new ApiRequest(); request.EnqueueApiCall(getExistingCardBaseIdsCall); string response; HttpStatusCode statusCode = ApiManagerInstance.SendRequest(request, out response); if (statusCode != HttpStatusCode.OK) { throw new Exception("GetAllCardBaseIds SendRequest returned: " + statusCode.ToString()); } dynamic decoded = JsonDecoder.Decode(response); dynamic items = decoded[getExistingCardBaseIdsCall.Call]["items"]; foreach (var item in items) { yield return(int.Parse(item["id"].ToString())); } }
public void JsonSerializing_LoginMessageEmpty_String() { string message = "{\"Login\":null,\"Password\":null}"; string reqMessage = new JsonDecoder().Serialize(new AuthMessage()); Assert.AreEqual(message, reqMessage); }
/// <summary> /// Atempt to decode dataset from the Keyvalue pairs /// </summary> private void DecodePossibleDataSetReader(JsonDecoder jsonDecoder, DataSetReaderDataType dataSetReader) { // check if there shall be a dataset header and decode it if (HasDataSetMessageHeader) { DecodeDataSetMessageHeader(jsonDecoder); } if (dataSetReader.DataSetWriterId != 0 && DataSetWriterId != dataSetReader.DataSetWriterId) { return; } object token = null; string payloadStructureName = kFieldPayload; // try to read "Payload" structure if (!jsonDecoder.ReadField(kFieldPayload, out token)) { // Decode the Messages element in case there is no "Payload" structure jsonDecoder.ReadField(null, out token); payloadStructureName = null; } Dictionary <string, object> payload = token as Dictionary <string, object>; if (payload != null) { if (payload.Count > dataSetReader.DataSetMetaData.Fields.Count) { // filter out payload that has more fields than the searched datasetMetadata return; } // check also the field names from reader, if any extra field names then the payload is not matching foreach (string key in payload.Keys) { var field = dataSetReader.DataSetMetaData.Fields.FirstOrDefault(f => f.Name == key); if (field == null) { // the field from payload was not found in dataSetReader therefore the payload is not suitable to be decoded return; } } } try { // try decoding Payload Structure bool wasPush = jsonDecoder.PushStructure(payloadStructureName); if (wasPush) { DataSet = DecodePayloadContent(jsonDecoder, dataSetReader); } } finally { // redo decode stack jsonDecoder.Pop(); } }
//private string websocketUrl; public NetworkManager(JsonDecoder jsonDecoder) { this.JsonDecoder = jsonDecoder; HttpNetworkService = new HttpNetworkService(); baseLobbyUrl = string.Concat(NetworkConfig.LobbyProtocol, NetworkConfig.MasterAdress, NetworkConfig.ServerPort); }
public void AfterTest() { container.Dispose(); container = null; config = null; fileSystem = null; decoder = null; }
public Managers() { JsonDecoder = new JsonDecoder(); NetworkManager = new NetworkManager(JsonDecoder); Session = new Session(); FileManager = new FileManager(); MessagesManager = new MessagesManager(FileManager, JsonDecoder); LogWriter = new LogWriter("Creating log writer"); }
public async Task <RegisterResponse> Register(RegisterMessage authorizeMessage) { var result = await HttpNetworkService.Post( JsonDecoder.Serialize(authorizeMessage), string.Concat(baseLobbyUrl, NetworkConfig.RegisterUrl) ); return(new RegisterResponse()); }
public void JsonSerializing_LoginMessage_String() { string message = "{\"Login\":\"vasya\",\"Password\":\"ivanov\"}"; string reqMessage = new JsonDecoder().Serialize(new AuthMessage { Login = "******", Password = "******" }); Assert.AreEqual(message, reqMessage); }
public void FromJson(string json) { var decoder = new JsonDecoder(json, ServiceMessageContext.GlobalContext); AuthorityUrl = decoder.ReadString("authority"); GrantType = decoder.ReadString("grantType"); TokenEndpoint = decoder.ReadString("tokenEndpoint"); ResourceId = decoder.ReadString("resource"); Scopes = decoder.ReadStringArray("scopes"); }
/// <summary> /// Decode the jsonDecoder content as a MetaData message /// </summary> /// <param name="jsonDecoder"></param> private void DecodeMetaDataMessage(JsonDecoder jsonDecoder) { try { m_metadata = jsonDecoder.ReadEncodeable(kFieldMetaData, typeof(DataSetMetaDataType)) as DataSetMetaDataType; } catch (Exception ex) { // Unexpected exception in DecodeMetaDataMessage Utils.Trace(ex, "JsonNetworkMessage.DecodeMetaDataMessage"); } }
private static GenericRecord Parse(Schema schema, string json) { var jsonEntity = (JToken)JsonConvert.DeserializeObject(json); var avroEntity = JsonDecoder.DecodeAny(schema, jsonEntity); if (avroEntity is GenericRecord) { return((GenericRecord)avroEntity); } throw new ArgumentException("schema was not a record"); }
public void EncodeDecodeCallbacks() { TestCallbacks tc = new TestCallbacks("Black", 23); string json = JsonEncoder.Encode(tc); Assert.IsTrue(tc.PreEncodedMethodCalled); Assert.IsTrue(tc.EncodedMethodCalled); var decoded = JsonDecoder.Decode <TestCallbacks>(json); Assert.IsTrue(decoded.DecodedMethodCalled); }
/// <summary> /// Decodes the message /// </summary> /// <param name="context"></param> /// <param name="message"></param> /// <param name="dataSetReaders"></param> public override void Decode(IServiceMessageContext context, byte[] message, IList <DataSetReaderDataType> dataSetReaders) { if (dataSetReaders == null || dataSetReaders.Count == 0) { return; } string json = System.Text.Encoding.ASCII.GetString(message); using (JsonDecoder decoder = new JsonDecoder(json, context)) { //decode bytes using dataset reader information DecodeSubscribedDataSets(decoder, dataSetReaders); } }
/// <summary> /// Sends the upload request asynchronously. /// </summary> /// <typeparam name="TRequest">The type of the request.</typeparam> /// <typeparam name="TResponse">The type of the response.</typeparam> /// <typeparam name="TError">The type of the error.</typeparam> /// <param name="request">The request.</param> /// <param name="body">The document to upload.</param> /// <param name="host">The server host to send the request to.</param> /// <param name="route">The route name.</param> /// <returns> /// An asynchronous task for the response. /// </returns> /// <exception cref="ApiException{TError}"> /// This exception is thrown when there is an error reported by the server. /// </exception> async Task <TResponse> ITransport.SendUploadRequestAsync <TRequest, TResponse, TError>( TRequest request, Stream body, string host, string route) { var serializedArg = JsonEncoder.Encode(request); var res = await this.RequestJsonStringWithRetry(host, route, RouteStyle.Upload, serializedArg, body); if (res.IsError) { throw JsonDecoder.Decode <ApiException <TError> >(res.ObjectResult); } return(JsonDecoder.Decode <TResponse>(res.ObjectResult)); }
/// <summary> /// Starts a background listener that waits for any message from the client /// </summary> private void StartBackgroundListener() { Task.Factory.StartNew(async() => { while (Running) { Console.WriteLine("Receiving..."); dynamic msg = await MessagingUtil.ReceiveMessage(_stream); if (msg == null) { CloseConnection(); return; } IMessage message = JsonDecoder.Decode(msg); Console.WriteLine(message.Type); switch (message.Type) { case MessageType.OK_MESSAGE: HandleOkMessage((OkMessage)message); break; case MessageType.ERROR_MESSAGE: HandleErrorMessage((ErrorMessage)message); break; case MessageType.LOGIN_MESSAGE: HandleLoginMessage((LoginMessage)message); break; case MessageType.CHAT_MESSAGE: HandleChatMessage((ChatMessage)message); break; case MessageType.PATCH_MESSAGE: HandlePatchMessage((PatchMessage)message); break; case MessageType.OUT_OF_SYNC_MESSAGE: HandleOutOfSyncMessage((OutOfSyncMessage)message); break; } } }, TaskCreationOptions.LongRunning); }
/// <inheritdoc/> public static DataSetMetadata Decode(ServiceMessageContext context, StreamReader reader) { var json = reader.ReadToEnd(); var output = new DataSetMetadata(); using (var decoder = new JsonDecoder(json, context)) { output.MessageId = decoder.ReadString("MessageId"); output.MessageType = decoder.ReadString("MessageType"); output.PublisherId = decoder.ReadString("PublisherId"); output.DataSetClassId = decoder.ReadString("DataSetClassId"); output.MetaData = (DataSetMetaDataType)decoder.ReadEncodeable("MetaData", typeof(DataSetMetaDataType)); decoder.Close(); } return(output); }
/// <summary> /// Sends the download request asynchronously. /// </summary> /// <typeparam name="TRequest">The type of the request.</typeparam> /// <typeparam name="TResponse">The type of the response.</typeparam> /// <typeparam name="TError">The type of the error.</typeparam> /// <param name="request">The request.</param> /// <param name="host">The server host to send the request to.</param> /// <param name="route">The route name.</param> /// <returns> /// An asynchronous task for the response. /// </returns> /// <exception cref="ApiException{TError}"> /// This exception is thrown when there is an error reported by the server. /// </exception> async Task <IDownloadResponse <TResponse> > ITransport.SendDownloadRequestAsync <TRequest, TResponse, TError>( TRequest request, string host, string route) { var serializedArg = JsonEncoder.Encode(request); var res = await this.RequestJsonStringWithRetry(host, route, RouteStyle.Download, serializedArg); if (res.IsError) { throw JsonDecoder.Decode <ApiException <TError> >(res.ObjectResult); } var response = JsonDecoder.Decode <TResponse>(res.ObjectResult); return(new DownloadResponse <TResponse>(response, res.HttpResponse)); }
/// <summary> /// The StartBackgroundListener is listening for new Messages that come in. /// These messages will come in from the stream the sender is always the server. /// The messages that will come forward from the stream are messages with certain types so the switch cases can recongnize it. /// </summary> private void StartBackgroundListener() { Console.WriteLine("Connected!"); Task.Factory.StartNew(async() => { while (Running) { dynamic msg = await MessagingUtil.ReceiveMessage(_stream); Console.WriteLine($"In Client BackgroundListener: {msg}"); IMessage message = JsonDecoder.Decode(msg); Console.WriteLine($"In Client BackgroundListener: {message.Type}"); switch (message.Type) { case MessageType.OK_MESSAGE: HandleOkMessage((OkMessage)message); break; case MessageType.OK_LOGIN_MESSAGE: HandleOkLoginMessage((OkLoginMessage)message); break; case MessageType.ERROR_MESSAGE: HandleErrorMessage((ErrorMessage)message); break; case MessageType.CHAT_MESSAGE: HandleChatMessage((ChatMessage)message); break; case MessageType.PATCH_MESSAGE: HandlePatchMessage((PatchMessage)message); break; case MessageType.PATCH_ERROR_MESSAGE: HandlePatchErrorMessage((PatchErrorMessage)message); break; case MessageType.OUT_OF_SYNC_RESPONSE: HandleOutOfSyncResponse((OutOfSyncResponse)message); break; } } }, TaskCreationOptions.LongRunning); }
/// <summary> /// Decodes the DataSetMessageHeader /// </summary> private void DecodeDataSetMessageHeader(JsonDecoder jsonDecoder) { object token = null; if ((DataSetMessageContentMask & JsonDataSetMessageContentMask.DataSetWriterId) != 0) { if (jsonDecoder.ReadField(nameof(DataSetWriterId), out token)) { DataSetWriterId = Convert.ToUInt16(jsonDecoder.ReadString(nameof(DataSetWriterId))); } } if ((DataSetMessageContentMask & JsonDataSetMessageContentMask.SequenceNumber) != 0) { if (jsonDecoder.ReadField(nameof(SequenceNumber), out token)) { SequenceNumber = jsonDecoder.ReadUInt32(nameof(SequenceNumber)); } } if ((DataSetMessageContentMask & JsonDataSetMessageContentMask.MetaDataVersion) != 0) { if (jsonDecoder.ReadField(nameof(MetaDataVersion), out token)) { MetaDataVersion = jsonDecoder.ReadEncodeable(nameof(MetaDataVersion), typeof(ConfigurationVersionDataType)) as ConfigurationVersionDataType; } } if ((DataSetMessageContentMask & JsonDataSetMessageContentMask.Timestamp) != 0) { if (jsonDecoder.ReadField(nameof(Timestamp), out token)) { Timestamp = jsonDecoder.ReadDateTime(nameof(Timestamp)); } } if ((DataSetMessageContentMask & JsonDataSetMessageContentMask.Status) != 0) { if (jsonDecoder.ReadField(nameof(Status), out token)) { Status = jsonDecoder.ReadStatusCode(nameof(Status)); } } }
/// <summary> /// Decode dataset from the provided json decoder using the provided <see cref="DataSetReaderDataType"/>. /// </summary> /// <param name="jsonDecoder">The json decoder that contains the json stream.</param> /// <param name="messagesCount">Number of Messages found in current jsonDecoder. If 0 then there is SingleDataSetMessage</param> /// <param name="messagesListName">The name of the Messages list</param> /// <param name="dataSetReader">The <see cref="DataSetReaderDataType"/> used to decode the data set.</param> public void DecodePossibleDataSetReader(JsonDecoder jsonDecoder, int messagesCount, string messagesListName, DataSetReaderDataType dataSetReader) { if (messagesCount == 0) { // check if there shall be a dataset header and decode it if (HasDataSetMessageHeader) { DecodeDataSetMessageHeader(jsonDecoder); // push into PayloadStructure if there was a dataset header jsonDecoder.PushStructure(kFieldPayload); } DecodeErrorReason = ValidateMetadataVersion(dataSetReader?.DataSetMetaData?.ConfigurationVersion); if (IsMetadataMajorVersionChange) { return; } // handle single dataset with no network message header & no dataset message header (the content of the payload) DataSet = DecodePayloadContent(jsonDecoder, dataSetReader); } else { for (int index = 0; index < messagesCount; index++) { bool wasPush = jsonDecoder.PushArray(messagesListName, index); if (wasPush) { // atempt decoding the DataSet fields DecodePossibleDataSetReader(jsonDecoder, dataSetReader); // redo jsonDecoder stack jsonDecoder.Pop(); if (DataSet != null) { // the dataset was decoded return; } } } } }
public override void Write(byte[] data) { base.Write(data); JsonDecoder decoder = new JsonDecoder(); ResonanceDecodingInformation info = new ResonanceDecodingInformation(); decoder.Decode(data, info); if (info.Type == ResonanceTranscodingInformationType.ContinuousRequest || info.Type == ResonanceTranscodingInformationType.Message || info.Type == ResonanceTranscodingInformationType.MessageSync || info.Type == ResonanceTranscodingInformationType.Request || info.Type == ResonanceTranscodingInformationType.Response) { Logger.LogInformation($"Write: {_loggedInClients[GetConnectionId()].Credentials.Name} => {_loggedInClients[GetOtherSideConnectionId()].Credentials.Name} => {{@Message}}", info.Message); } }
public async Task <AuthResponse> Login(AuthMessage authorizeMessage) { var result = await HttpNetworkService.Post( JsonDecoder.Serialize(authorizeMessage), string.Concat(baseLobbyUrl, NetworkConfig.LoginUrl) ); var response = new AuthResponse(); if (result.Status == 200) { response = JsonDecoder.Deserialize <AuthResponse>(result.Message, MessagesTypes.LoginResponse); response.IsSuccesful = true; } else { //todo } return(response); }
/// <summary> /// Decodes the message /// </summary> /// <param name="context"></param> /// <param name="message"></param> /// <param name="dataSetReaders"></param> public override void Decode(IServiceMessageContext context, byte[] message, IList <DataSetReaderDataType> dataSetReaders) { string json = System.Text.Encoding.UTF8.GetString(message); using (JsonDecoder jsonDecoder = new JsonDecoder(json, context)) { // 1. decode network message header (PublisherId & DataSetClassId) DecodeNetworkMessageHeader(jsonDecoder); if (m_jsonNetworkMessageType == JSONNetworkMessageType.DataSetMetaData) { DecodeMetaDataMessage(jsonDecoder); } else if (m_jsonNetworkMessageType == JSONNetworkMessageType.DataSetMessage) { //decode bytes using dataset reader information DecodeSubscribedDataSets(jsonDecoder, dataSetReaders); } } }
/// <summary> /// Decodes the message /// </summary> /// <param name="message"></param> /// <param name="dataSetReaders"></param> public override void Decode(byte[] message, IList <DataSetReaderDataType> dataSetReaders) { if (dataSetReaders == null || dataSetReaders.Count == 0) { return; } ServiceMessageContext messageContext = new ServiceMessageContext(); messageContext.NamespaceUris = ServiceMessageContext.GlobalContext.NamespaceUris; messageContext.ServerUris = ServiceMessageContext.GlobalContext.ServerUris; string json = System.Text.Encoding.ASCII.GetString(message); using (JsonDecoder decoder = new JsonDecoder(json, messageContext)) { //decode bytes using dataset reader information DecodeSubscribedDataSets(decoder, dataSetReaders); } }