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 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 }
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; } } }); }
public static object Deserialize(TextReader text) { JsonDecoder jsonDecoder = new JsonDecoder(); jsonDecoder.parseNumbersAsFloat = true; return(jsonDecoder.Decode(text.ReadToEnd())); }
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> /// 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> /// 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> /// 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); }
/// <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); }
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 string GetUserLocale() { var getLocaleCall = new ApiCallList.General.GetPlayer(); getLocaleCall.ContextFilter = new List <string>() { "player.locale" }; var request = new ApiRequest(); request.EnqueueApiCall(getLocaleCall); string response; HttpStatusCode statusCode = ApiManagerInstance.SendRequest(request, out response); if (statusCode != HttpStatusCode.OK) { throw new Exception("GetUserLocale returned: " + statusCode.ToString()); } dynamic decoded = JsonDecoder.Decode(response); return(decoded[getLocaleCall.Call]["context"]["player"]["locale"].ToString()); }
private static void UpdateCardInstanceDefinitions_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = (BackgroundWorker)sender; UpdateCardInstanceDefinitionsArgument managers = (UpdateCardInstanceDefinitionsArgument)e.Argument; worker.ReportProgress(0); var getCardsFromCollectionPageCall = new ApiCallList.Collections.GetCollectionPage { nbPerPage = 52, // Maximum allowed by the API ItemsFilter = new List <string>() { "id", "id_player_character", "level", "xp" }, ContextFilter = new List <string>() { "totalPages" } }; var request = new ApiRequest(); request.EnqueueApiCall(getCardsFromCollectionPageCall); int page = 0; int totalPages = 1; // First valid page = 0. Last valid page = totalPages - 1 bool firstIteration = true; var instances = new List <CardInstance>(); while (page < totalPages) { if (worker.CancellationPending == true) { e.Cancel = true; return; } getCardsFromCollectionPageCall.page = page; string response; HttpStatusCode statusCode = managers.ApiManager.SendRequest(request, out response); if (statusCode != HttpStatusCode.OK) { throw new Exception("GetCardInstancesFromSummary returned: " + statusCode.ToString()); } dynamic decoded = JsonDecoder.Decode(response); if (firstIteration) { dynamic context = decoded[getCardsFromCollectionPageCall.Call]["context"]; totalPages = int.Parse(context["totalPages"].ToString()); getCardsFromCollectionPageCall.ContextFilter.Remove("totalPages"); firstIteration = false; } worker.ReportProgress(100 * page / totalPages); // totalPages can't be zero, a player can't sell cards on their current deck dynamic items = decoded[getCardsFromCollectionPageCall.Call]["items"]; foreach (dynamic item in items) { int cardBaseId = int.Parse(item["id"].ToString()); int cardInstanceId = int.Parse(item["id_player_character"].ToString()); int level = int.Parse(item["level"].ToString()); int experience = int.Parse(item["xp"].ToString()); instances.Add(new CardInstance(managers.InMemoryManager.GetCardBase(cardBaseId), cardInstanceId, level, experience)); } page++; } managers.InMemoryManager.ReloadToMemoryCardInstances(instances); worker.ReportProgress(100); }
private static void UpdateCardBaseDefinitions_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = (BackgroundWorker)sender; Debug.Assert(e.Argument != null); UpdateCardBaseDefinitionsArgument managers = (UpdateCardBaseDefinitionsArgument)e.Argument; worker.ReportProgress(0, "Connecting to server..."); // This process will set the locale to English. Here we take the previous value to restore it at the end. string userLocale = managers.ServerQueriesManager.GetUserLocale(); var existingIds = managers.ServerQueriesManager.GetAllCardBaseIds(); var storedIds = managers.DatabaseManager.GetAllCardBaseIds(); var idsToAnalyze = existingIds.Except(storedIds).ToList(); idsToAnalyze.Sort(); /* There are 3 API calls to get characters details: * - characters.getCharacters (labeled "oldGetCharacters") * - characters.getCharacterLevels * - urc.getCharacters (labeled "newGetCharacters") * Some details can be obtained from various of those calls, some only from one of them. * "newGetCharacters" is the fastest one, so we will get most of the details from that one, and the rest from "oldGetCharacters". * "getCharacterLevels" will not be used, all the details that we can obtain from it we can get it from the "new" one too. */ var request = new ApiRequest(); var setLocaleToEnglishCall = new ApiCallList.Players.SetLanguages(new List <string> { ServerQueriesManager.EnglishLocale }); request.EnqueueApiCall(setLocaleToEnglishCall); var oldGetCharactersCall = new ApiCallList.Characters.GetCharacters { // This call is painfully slow, so we optimize it as much as we can, asking only for the info we need charactersIDs = new List <int>(idsToAnalyze), maxLevels = true, ItemsFilter = new List <string>() { "id", "level_min", "level_max", "ability", "ability_unlock_level", "release_date" } }; request.EnqueueApiCall(oldGetCharactersCall); var newGetCharactersCall = new ApiCallList.Urc.GetCharacters(); request.EnqueueApiCall(newGetCharactersCall); string response; HttpStatusCode statusCode = managers.GlobalManager.ApiManagerInstance.SendRequest(request, out response); if (statusCode != HttpStatusCode.OK) { throw new Exception("GetCardBase SendRequest returned: " + statusCode.ToString()); // TODO: Manage timeouts gracefully (GatewayTimeout) } dynamic decoded = JsonDecoder.Decode(response); int progress = 0; var oldData = SortServerCharacterDataIntoDictionary(oldGetCharactersCall.Call, decoded); var newData = SortServerCharacterDataIntoDictionary(newGetCharactersCall.Call, decoded); foreach (int id in idsToAnalyze) { if (worker.CancellationPending == true) { e.Cancel = true; break; } int minLevel = int.Parse(oldData[id]["level_min"].ToString()); int maxLevel = int.Parse(oldData[id]["level_max"].ToString()); string abilityText = oldData[id]["ability"].ToString(); int abilityUnlockLevel = int.Parse(oldData[id]["ability_unlock_level"].ToString()); int timeSinceRelease = int.Parse(oldData[id]["release_date"].ToString()); string name = newData[id]["name"].ToString(); int clanId = int.Parse(newData[id]["clanID"].ToString()); string rarityText = newData[id]["rarity"].ToString(); var cardLevels = new List <CardLevel>(); foreach (dynamic levelItem in newData[id]["levels"]) { int level = int.Parse(levelItem["level"].ToString()); int power = int.Parse(levelItem["power"].ToString()); int damage = int.Parse(levelItem["damage"].ToString()); cardLevels.Add(new CardLevel(level, power, damage)); } worker.ReportProgress((int)(100 * progress / idsToAnalyze.Count()), $"[{id}] {name}"); progress++; var card = ApiToCardBaseAdapter.ToCardBase(id, name, clanId, minLevel, maxLevel, rarityText, abilityText, abilityUnlockLevel, timeSinceRelease, cardLevels); if (card == null) { continue; // TODO: Remove this line if day/night is implemented, or after 11/2018, whatever happens first } managers.DatabaseManager.StoreCardBase(card); managers.InMemoryManager.LoadToMemoryCardBase(card); managers.ImageDownloader.AddCardBaseToDownloadQueue(card, CharacterImageFormat.Color800x640); } managers.ServerQueriesManager.SetUserLocale(userLocale); worker.ReportProgress(100); }
/// <summary> /// Try to deserialize the json into a json dictionary /// </summary> /// <returns><c>true</c>, if deserialize object was successfull, <c>false</c> if the process failed.</returns> /// <param name="json">Json.</param> /// <param name="obj">Object.</param> public static bool TryDeserialize(string json, out object obj) { obj = (!string.IsNullOrEmpty(json)) ? JsonDecoder.Decode(json) : null; return(obj != null); }
/// <summary> /// /// </summary> /// <param name="id">Must be a valid ID</param> /// <exception cref="ArgumentException"></exception> /// <returns></returns> public CardBase GetCardBase(int id) { if (id <= 0) { throw new ArgumentOutOfRangeException(nameof(id), id, "Must be greater than 0"); } var setEnglishLocaleCall = new ApiCallList.Players.SetLanguages(new List <string>() { EnglishLocale }); var getCardBaseInfoCall = new ApiCallList.Characters.GetCharacters(); getCardBaseInfoCall.charactersIDs = new List <int>() { id }; getCardBaseInfoCall.maxLevels = true; getCardBaseInfoCall.ItemsFilter = new List <string>() { "name", "clan_id", "level_min", "level_max", "rarity", "ability", "ability_unlock_level", "release_date" }; var getCardLevelsCall = new ApiCallList.Characters.GetCharacterLevels(id); getCardLevelsCall.levelMax = -1; // Get all the levels getCardLevelsCall.ItemsFilter = new List <string>() { "level", "power", "damage" }; var request = new ApiRequest(); request.EnqueueApiCall(setEnglishLocaleCall); request.EnqueueApiCall(getCardBaseInfoCall); request.EnqueueApiCall(getCardLevelsCall); string response; HttpStatusCode statusCode = ApiManagerInstance.SendRequest(request, out response); if (statusCode != HttpStatusCode.OK) { throw new Exception("GetCardBase SendRequest returned: " + statusCode.ToString()); } dynamic decoded = JsonDecoder.Decode(response); dynamic dynBaseCard; try { dynBaseCard = decoded[getCardBaseInfoCall.Call]["items"][0]; } catch { // TODO: Log attempt to download invalid ID throw new ArgumentException("The id doesn't exist", nameof(id)); } string name = dynBaseCard["name"].ToString(); int clan_id = int.Parse(dynBaseCard["clan_id"].ToString()); int level_min = int.Parse(dynBaseCard["level_min"].ToString()); int level_max = int.Parse(dynBaseCard["level_max"].ToString()); string rarity = dynBaseCard["rarity"].ToString(); string ability = dynBaseCard["ability"].ToString(); int ability_unlock_level = int.Parse(dynBaseCard["ability_unlock_level"].ToString()); int release_date = int.Parse(dynBaseCard["release_date"].ToString()); var levels = new List <CardLevel>(); foreach (dynamic item in decoded[getCardLevelsCall.Call]["items"]) { int level = int.Parse(item["level"].ToString()); int power = int.Parse(item["power"].ToString()); int damage = int.Parse(item["damage"].ToString()); levels.Add(new CardLevel(level, power, damage)); } return(ApiToCardBaseAdapter.ToCardBase(id, name, clan_id, level_min, level_max, rarity, ability, ability_unlock_level, release_date, levels)); }
public void TestJsonDecoder_ParseSuccess() { /* PRECONDITION */ Debug.Assert(decoder != null); Debug.Assert(fileSystem != null); Debug.Assert(config != null); Debug.Assert(container != null); config.RelativeFilePath = new FilePath(fileLocation, true); container.ComposeExportedValue(config); container.ComposeParts(decoder); /* GIVEN */ var random = new Random(); var eventList = new List <TestEvent> { new TestEvent(random.Next()), new TestEvent(random.Next()) }; var serializedString = JsonManualSerialization.GenerateSerializedEvents(eventList); var mockFileData = new MockFileData(serializedString, Encoding.UTF8); fileSystem.AddFile(recordingFolderLocation + fileLocation, mockFileData); using var awaitThreadEvent = new ManualResetEvent(false); using var openEvent = new ManualResetEvent(false); using var didDecodeAllEvents = new ManualResetEvent(false); /* WHEN */ var thread = new Thread(async() => { await foreach (var @event in Awaitable.Await(decoder.GetEvents(), awaitThreadEvent)) { var deserialized = JsonSerializer.Deserialize(@event.Data, @event.Type); if ((!(deserialized is TestEvent receivedEvent))) { continue; } var index = eventList.FindIndex((compareEvent) => compareEvent.Identifier == receivedEvent.Identifier); if (index == -1) { continue; } eventList.RemoveAt(index); if (eventList.Count == 0) { didDecodeAllEvents.Set(); } } }); decoder.Open(); thread.Start(); Assert.IsTrue(awaitThreadEvent.WaitOne(maxWaitTime), "Thread did not start in time!"); decoder.Decode(new DirectoryPath(recordingFolderLocation, true)); /* THEN */ Assert.IsTrue(decoder.DecodeFinished.WaitOne(maxWaitTime), "Decoder did not finish in time!"); Assert.IsTrue(didDecodeAllEvents.WaitOne(maxWaitTime), "Could not find all encoded events."); }
public static T Decode <T>(string value) { return(JsonDecoder.Decode <T>(value)); }
public static Dictionary <string, object> Decode(string value, IEnumerable <KeyValuePair <string, Type> > valueTypes) { return(JsonDecoder.Decode(value, valueTypes)); }
public static object Decode(string value, Type type) { return(JsonDecoder.Decode(value, type)); }