async Task WriteCache(List <StakePool> allPools) { BlockChainCache = new BlockChainCache { StakePools = new ObservableCollection <StakePool>(allPools), CacheDate = DateTime.Now }; var options = new JsonSerializerOptions { WriteIndented = true }; byte[] jsonUtf8Bytes = JsonSerializer.SerializeToUtf8Bytes(BlockChainCache, options); if (BlockChainCache.StakePools.Any()) { BlockChainCache.StakePools.Clear(); } OnPropertyChanged("BlockChainCache"); if (!_stakePoolListDatabase.HasWritePermissionOnDir()) { throw new Exception(string.Format( "Failed caching to local system. Software can still be used but without caching it results in slower performance. {0}No write permission for: {1}", Environment.NewLine, _stakePoolListDatabase)); } await File.WriteAllBytesAsync(_stakePoolListDatabase, jsonUtf8Bytes); }
public byte[] MessageToBytes(Type messageType, object message) { return(JsonSerializer.SerializeToUtf8Bytes(message, messageType, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase })); }
public async Task Save(IList <StorageItem> items) { if (!(items?.Any() ?? false)) { return; } var bytes = storageCompressor.Compress(JsonSerializer.SerializeToUtf8Bytes(items, jsonSerializerOptions)); var multipartItems = bytes.ToMultipartItems(MaxPayloadSize).ToList(); var tries = Tries; var statusCode = HttpStatusCode.OK; string response = null; while (tries-- > 0) { (statusCode, response) = await TrySave(multipartItems); if (statusCode != PreconditionRequired) { break; } await Task.Delay(RetrySleepMilliseconds); } CheckResponse(statusCode, response); logger.LogInformation("Update {ads} successfully", string.Join(" ", items.Select(x => x.Id))); }
protected string Serialize <T>(T o) { return(Serializer switch { JsonSerializerType.NewtonsoftJson => Newtonsoft.Json.JsonConvert.SerializeObject(o, CreateJsonSerializerSettings()), JsonSerializerType.SystemTextJson => Encoding.UTF8.GetString(JsonSerializer.SerializeToUtf8Bytes(o, CreateJsonSerializerOptions())), _ => throw new NotSupportedException() });
private static void NetCore3JsonTest() { for (var i = 0; i < 50; i++) { var bytes = CoreJsonSerializer.SerializeToUtf8Bytes(Source, new JsonSerializerOptions { IgnoreNullValues = true }); var book = CoreJsonSerializer.Deserialize <Book>(bytes); Trace.Assert(book.Title != null); } }
async Task <bool> StartServerAsync() { try { var cardanoServerConsoleProcess = _cardanoServer.Start(_nodePort); var allWallets = await _walletClient.GetAllWalletsAsync(); AllWallets = new ObservableCollection <Wallet>(allWallets); var allPools = await _walletClient.GetAllPoolsAsync(); BlockChainCache = new BlockChainCache(); BlockChainCache.StakePools = new ObservableCollection <StakePool>(allPools); BlockChainCache.CacheDate = DateTime.Now; string jsonString = JsonConvert.SerializeObject(BlockChainCache); byte[] jsonUtf8Bytes; var options = new JsonSerializerOptions { WriteIndented = true }; jsonUtf8Bytes = JsonSerializer.SerializeToUtf8Bytes(BlockChainCache, options); await File.WriteAllBytesAsync(StakePoolListDatabase, jsonUtf8Bytes); //var allPoolsGrouped = allPools.GroupBy(g=>g.LifeTimeBlocks == 0).ToDictionary(x => x.Key, x => x.ToList()); var allStakePoolsGroups = new DataGridCollectionView(allPools); //allStakePoolsGroups.GroupDescriptions.Add(new DataGridPathGroupDescription("LifeTimeBlocks")); //allStakePoolsGroups.Filter = FilterProperty; AllStakePools = new ObservableCollection <StakePool>(allPools); if (BlockChainCache.StakePools.Any()) { BlockChainCache.StakePools.Clear(); } OnPropertyChanged("BlockChainCache"); return(true); } catch (Exception e) { Log.Logger.Fatal(e.Message); return(false); } }
/// <summary> /// serialize to utf8 json bytes, more performance than to json string /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static byte[] SerializeJsonBytes <T>(this T obj) { return(JsonSerializer.SerializeToUtf8Bytes(obj, SerializeOptions)); }
public async Task <ActionResult <CharacterAnalysis> > GetCharacters( [FromRoute(Name = "leagueName")] string _leagueName, [FromQuery] GetCharactersConfig config ) { config.Normalized(); string leagueName; if (_leagueName == DEFAULT_LEAGUE_NAME) { PoeLeagueModel defaultLeague = await leagueService .GetDefaultLeagueQuery() .Select(x => new PoeLeagueModel { LeagueId = x.LeagueId }) .SingleOrDefaultAsync(); if (defaultLeague != null) { leagueName = defaultLeague.LeagueId; } else { leagueName = _leagueName; } } else { leagueName = _leagueName; } var cacheKey = $"{CHARACTERS_CACHE_PREFIX}:{leagueName}:{config.GetCacheKey()}"; var encodedResult = await distributedCache.GetAsync(cacheKey); if (encodedResult != null) { var jsonStr = System.Text.Encoding.UTF8.GetString(encodedResult); var result = JsonSerializer.Deserialize <CharacterAnalysis>(jsonStr); Response.Headers.Add("Cache-Control", "public, max-age=60"); return(result); } else { var result = await leagueService.GetCharactersByAnalysis(leagueName, config); if (result.Total == 0) { return(NotFound()); } else { int expirMulti = (int)(result.Total / 1000); expirMulti = expirMulti < 1 ? 1 : expirMulti; expirMulti = expirMulti >= 2 ? 2 : expirMulti; var jsonBytes = JsonSerializer.SerializeToUtf8Bytes(result); var options = new DistributedCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromMinutes(3 * expirMulti)) .SetAbsoluteExpiration(DateTime.Now.AddHours(1 * expirMulti)); await distributedCache.SetAsync(cacheKey, jsonBytes, options); Response.Headers.Add("Cache-Control", "public, max-age=180"); return(result); } } }