public static List <RealCurrencyCostModel> GetRealCurrencyProducts(this ShopModel shopModel) { List <RealCurrencyCostModel> realCurrencyProducts = shopModel.UiSections .SelectMany(container => container.UiItems) .SelectMany(test1 => test1) .Where(productModel => productModel.CostModel.CostTypeEnum == CostTypeEnum.RealCurrency) .Select(productModel => ZeroFormatterSerializer.Deserialize <RealCurrencyCostModel>(productModel.CostModel.SerializedCostModel)) .ToList(); return(realCurrencyProducts); }
protected IExceptionWrapper GetInnerException() { return(InnerException == null ? null : ZeroFormatterSerializer.Deserialize <IExceptionWrapper>(InnerException)); }
public T Deserialise <T>(byte[] packetBytes) { return(ZeroFormatterSerializer.Deserialize <T>(packetBytes)); }
public async Task WriteAsync(string playerServiceId, LootboxModel lootboxModel) { Account account = await dbContext.Accounts .Where(account1 => account1.ServiceId == playerServiceId) .SingleOrDefaultAsync(); List <Increment> increments = new List <Increment>(); foreach (ResourceModel prize in lootboxModel.Prizes) { Increment increment = new Increment(); switch (prize.ResourceTypeEnum) { case ResourceTypeEnum.SoftCurrency: { increment.IncrementTypeId = IncrementTypeEnum.SoftCurrency; int amount = ZeroFormatterSerializer .Deserialize <SoftCurrencyResourceModel>(prize.SerializedModel).Amount; increment.Amount = amount; break; } case ResourceTypeEnum.HardCurrency: { increment.IncrementTypeId = IncrementTypeEnum.HardCurrency; int amount = ZeroFormatterSerializer .Deserialize <HardCurrencyResourceModel>(prize.SerializedModel).Amount; increment.Amount = amount; break; } case ResourceTypeEnum.WarshipPowerPoints: { var model = ZeroFormatterSerializer .Deserialize <WarshipPowerPointsResourceModel>(prize.SerializedModel); if (model.WarshipId != null) { increment.IncrementTypeId = IncrementTypeEnum.WarshipPowerPoints; increment.Amount = model.FinishValue - model.StartValue; increment.WarshipId = model.WarshipId; } else { throw new NullReferenceException("warshipId"); } break; } default: throw new ArgumentOutOfRangeException(); } increments.Add(increment); } Transaction transaction = new Transaction { AccountId = account.Id, DateTime = DateTime.UtcNow, TransactionTypeId = TransactionTypeEnum.LootboxOpening, Decrements = new List <Decrement> { new Decrement { Amount = 100, DecrementTypeId = DecrementTypeEnum.LootboxPoints } }, Increments = increments, WasShown = false }; await dbContext.Transactions.AddAsync(transaction); await dbContext.SaveChangesAsync(); }
private void ReplayLoop() { if (!replayLoopInProgress) { replayLoopInProgress = true; if (replayModeActivated) { if (isReplayingFileSerieDefined) { //Si le nom de la série de fichier à traiter est défini if (!isReplayingFileOpened) { //Si aucun fichier n'est ouvert, on ouvre le courant if (subFileIndex == 0) { filePath = replayFileSerieName + "0_Init.rbt"; } else { filePath = replayFileSerieName + subFileIndex + ".rbt"; } if (File.Exists(filePath)) { sr = new StreamReader(filePath); isReplayingFileOpened = true; OnFileNameChange(filePath); initialDateTime = DateTime.Now; } else { //On n'a plus de fichier à traiter isReplayingFileOpened = false; isReplayingFileSerieDefined = false; replayModeActivated = false; } } if (isReplayingFileOpened) { //Si un fichier est déjà ouvert do { var s = sr.ReadLine(); if (s != null) { byte[] bytes = Convert.FromBase64String(s); var deserialization = ZeroFormatterSerializer.Deserialize <ZeroFormatterLogging>(bytes); switch (deserialization.Type) { case ZeroFormatterLoggingType.IMUDataEventArgs: IMUDataEventArgsLog ImuData = (IMUDataEventArgsLog)deserialization; newReplayInstant = ImuData.InstantInMs; var e = new IMUDataEventArgs(); e.accelX = ImuData.accelX; e.accelY = ImuData.accelY; e.accelZ = ImuData.accelZ; e.gyroX = ImuData.gyroX; e.gyroY = ImuData.gyroY; e.gyroZ = ImuData.gyroZ; e.magX = ImuData.magX; e.magY = ImuData.magY; e.magZ = ImuData.magZ; e.EmbeddedTimeStampInMs = ImuData.EmbeddedTimeStampInMs; OnIMU(e); break; case ZeroFormatterLoggingType.PolarSpeedEventArgs: PolarSpeedEventArgsLog robotSpeedData = (PolarSpeedEventArgsLog)deserialization; newReplayInstant = robotSpeedData.InstantInMs; var eSpeed = new PolarSpeedEventArgs(); eSpeed.RobotId = robotSpeedData.RobotId; eSpeed.Vtheta = robotSpeedData.Vtheta; eSpeed.Vx = robotSpeedData.Vx; eSpeed.Vy = robotSpeedData.Vy; eSpeed.timeStampMs = robotSpeedData.timeStampMs; OnSpeedData(eSpeed); break; case ZeroFormatterLoggingType.RawLidarArgs: RawLidarArgsLog currentLidarLog = (RawLidarArgsLog)deserialization; newReplayInstant = currentLidarLog.InstantInMs; OnLidar(currentLidarLog.RobotId, currentLidarLog.PtList); break; default: break; } if (LogDateTimeOffsetInMs == null) { LogDateTimeOffsetInMs = newReplayInstant; } } else { //Lecture échouée, on a une fin de fichier isReplayingFileOpened = false; sr.Close(); subFileIndex++; } } //On le fait tant que l'instant courant des data de Replay est inférieur à l'instant théorique de simulation, on traite les datas while (newReplayInstant / speedFactor < DateTime.Now.Subtract(initialDateTime).TotalMilliseconds + LogDateTimeOffsetInMs && isReplayingFileOpened); } } } replayLoopInProgress = false; } }
private static object ZFDeserialise(byte[] binary) { return(AfterDeserialiseObject(ZeroFormatterSerializer.Deserialize <object>(binary))); }
// Endless Start reading loop private async void StartReading(Socket client) { var endpoint = client.RemoteEndPoint as IPEndPoint; // Get remote endpoint // Loop theoretically infinetly while (true) { try { long size = await LeadingByteProcessor.ReadLeading(client).ConfigureAwait(false); // leading var bytes = new byte[size]; var segment = new ArraySegment <byte>(bytes); // TODO: Do something when receiving interrupts? Wait for client to come back? // read until all data is read int read = 0; while (read < size) { long receive = size - read; // current buffer size if (receive > ReceiveBufferSize) { receive = ReceiveBufferSize; // max size } var slice = segment.SliceEx(read, (int)receive); // get buffered portion of array read += await client.ReceiveAsync(slice, SocketFlags.None).ConfigureAwait(false); } if (read < 1) { throw new TransferException($"{read} bytes were read! " + "Null bytes could mean a connection shutdown."); } var message = ZeroFormatterSerializer.Deserialize <T>(segment.Array); ReceivedMessage?.Invoke(endpoint, message); // call event } catch (SocketException ex) { Console.WriteLine(ex.ErrorCode); bool success = DisconnectClient(endpoint); // try to disconnect if (success) { return; // Exit Reading loop once successfully disconnected } } catch (ObjectDisposedException) { // client object is disposed bool success = DisconnectClient(endpoint); // try to disconnect if (success) { return; // Exit Reading loop once successfully disconnected } } catch (TransferException) { // 0 read bytes = null byte bool success = DisconnectClient(endpoint); // try to disconnect if (success) { return; // Exit Reading loop once successfully disconnected } } } // Listen again after client connected }
private void LoadNextSnapshots() { lock (backtestingService.SyncRoot) { if (loadedSignalSnapshots == 0 && loadedTickerSnapshots == 0) { loggingService.Info($"<<<--- Backtesting started. Total signals snapshots: {totalSignalSnapshots}, Total tickers snapshots: {totalTickerSnapshots} --->>>"); backtestingTimer = Stopwatch.StartNew(); } if (allSignalSnapshotPaths.TryDequeue(out string currentSignalsSnapshotPath)) { try { byte[] currentSignalsSnapshotBytes = File.ReadAllBytes(currentSignalsSnapshotPath); IEnumerable <ISignal> data = ZeroFormatterSerializer.Deserialize <IEnumerable <SignalData> >(currentSignalsSnapshotBytes).Select(s => s.ToSignal()).ToList(); currentSignals = data.GroupBy(s => s.Pair).ToDictionary(s => s.Key, s => s.AsEnumerable()); loadedSignalSnapshots++; var currentSignalsSnapshotFile = currentSignalsSnapshotPath.Substring(currentSignalsSnapshotPath.Length - 27); currentSignalsSnapshotFile = currentSignalsSnapshotFile.Replace('\\', '-').Replace('/', '-'); if (backtestingService.Config.ReplayOutput && loadedSignalSnapshots % 100 == 0) { loggingService.Info($"<<<--- ({loadedSignalSnapshots}/{totalSignalSnapshots}) Load signals snapshot file: {currentSignalsSnapshotFile} --->>>"); } healthCheckService.UpdateHealthCheck(Constants.HealthChecks.BacktestingSignalsSnapshotLoaded, $"File: {currentSignalsSnapshotFile}"); } catch (Exception ex) { loggingService.Error($"<<<--- Unable to load signals snapshot file: {currentSignalsSnapshotPath} --->>>", ex); } } if (allTickerSnapshotPaths.TryDequeue(out string currentTickersSnapshotPath)) { try { byte[] currentTickersSnapshotBytes = File.ReadAllBytes(currentTickersSnapshotPath); IEnumerable <ITicker> data = ZeroFormatterSerializer.Deserialize <IEnumerable <TickerData> >(currentTickersSnapshotBytes).Select(t => t.ToTicker()).ToList(); currentTickers = data.ToDictionary(t => t.Pair, t => t); loadedTickerSnapshots++; var currentTickersSnapshotFile = currentTickersSnapshotPath.Substring(currentTickersSnapshotPath.Length - 27); currentTickersSnapshotFile = currentTickersSnapshotFile.Replace('\\', '-').Replace('/', '-'); if (backtestingService.Config.ReplayOutput && loadedTickerSnapshots % 100 == 0) { loggingService.Info($"<<<--- ({loadedTickerSnapshots}/{totalTickerSnapshots}) Load tickers snapshot file: {currentTickersSnapshotFile} --->>>"); } healthCheckService.UpdateHealthCheck(Constants.HealthChecks.BacktestingTickersSnapshotLoaded, $"File: {currentTickersSnapshotFile}"); } catch (Exception ex) { loggingService.Error($"<<<--- Unable to load tickers snapshot file: {currentTickersSnapshotPath} --->>>", ex); } } if (currentSignalsSnapshotPath == null && currentTickersSnapshotPath == null) { isCompleted = true; backtestingTimer.Stop(); loggingService.Info($"<<<--- Backtesting finished in {Math.Round(backtestingTimer.Elapsed.TotalSeconds)} seconds --->>>"); backtestingService.Complete(totalSignalSnapshots - loadedSignalSnapshots, totalTickerSnapshots - loadedTickerSnapshots); } } }
public async Task <TotalMeasurementResult> Measure(int sampleSize, int minNumberOfDataPoints, int maxNumberOfDataPoints, int stepSize, bool applyCompression, string compressionType) { double transferTime = 0; double deserializationTime = 0; string contentEncoding = ""; Stream responseStream = null; double fileSize = 0; TotalMeasurementResult totalMeasurementResult = new TotalMeasurementResult(); for (var i = minNumberOfDataPoints; i <= maxNumberOfDataPoints; i += stepSize) { MeasurementResult measurementResult = new MeasurementResult(); for (int j = 0; j < sampleSize; j++) { //Streaming System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Start(); HttpResponseMessage responseMessage = await base.MakeRequestAsync(i, applyCompression, compressionType); contentEncoding = responseMessage.Content.Headers.ContentEncoding.ToString(); if (responseMessage.IsSuccessStatusCode) { var packet = await responseMessage.Content.ReadAsStreamAsync(); stopwatch.Stop(); transferTime += stopwatch.ElapsedMilliseconds; stopwatch.Reset(); fileSize += packet.Length; stopwatch.Start(); //Decompression if compressed //Deserialization if (contentEncoding.ToLower().Contains("gzip")) { responseStream = new GZipStream(packet, CompressionMode.Decompress); } else if (contentEncoding.ToLower().Contains("deflate")) { responseStream = new DeflateStream(packet, CompressionMode.Decompress); } else if (contentEncoding.ToLower().Contains("br")) { responseStream = new BrotliStream(packet, CompressionMode.Decompress); } else { responseStream = packet; } MemoryStream ms = new MemoryStream(); responseStream.CopyTo(ms); TimeSeriesData[] timeSeries = ZeroFormatterSerializer.Deserialize <TimeSeriesData[]>(ms.ToArray()); stopwatch.Stop(); deserializationTime += stopwatch.ElapsedMilliseconds; stopwatch.Reset(); } } measurementResult.DataPoints = i; measurementResult.TransferAndSerializationTime = transferTime / sampleSize; measurementResult.DeserializationTime = deserializationTime / sampleSize; measurementResult.FileSize = fileSize / sampleSize; totalMeasurementResult.ResultList.Add(measurementResult); } return(totalMeasurementResult); }
private static void Benchmark <T>(T target) { const int Iteration = 10000; Console.WriteLine("Running {0} iterations...", Iteration); var jsonSerializer = new JsonSerializer(); MsgPack.Serialization.SerializationContext msgpack = MsgPack.Serialization.SerializationContext.Default; msgpack.GetSerializer <T>().PackSingleObject(target); MessagePackSerializer.Serialize(target); MessagePackSerializer.Serialize(target, MessagePackSerializerOptions.LZ4Standard); ZeroFormatter.ZeroFormatterSerializer.Serialize(target); ProtoBuf.Serializer.Serialize(new MemoryStream(), target); jsonSerializer.Serialize(new JsonTextWriter(new StringWriter()), target); Console.WriteLine(typeof(T).Name + " serialization test"); Console.WriteLine(); Console.WriteLine("Serialize::"); Deserializing = false; byte[] data = null; var data0 = new Nerdbank.Streams.Sequence <byte>(); byte[] data1 = null; byte[] data2 = null; byte[] data3 = null; byte[] dataJson = null; byte[] dataGzipJson = null; using (new Measure("MessagePack for C#")) { for (int i = 0; i < Iteration; i++) { data0.Reset(); MessagePackSerializer.Serialize(data0, target); } } using (new Measure("MessagePack for C# (LZ4)")) { for (int i = 0; i < Iteration; i++) { data3 = MessagePackSerializer.Serialize(target, MessagePackSerializerOptions.LZ4Standard); } } using (new Measure("MsgPack-Cli")) { for (int i = 0; i < Iteration; i++) { data = msgpack.GetSerializer <T>().PackSingleObject(target); } } using (new Measure("protobuf-net")) { for (int i = 0; i < Iteration; i++) { using (var ms = new MemoryStream()) { ProtoBuf.Serializer.Serialize(ms, target); } } } using (new Measure("ZeroFormatter")) { for (int i = 0; i < Iteration; i++) { data1 = ZeroFormatter.ZeroFormatterSerializer.Serialize(target); } } using (new Measure("Json.NET")) { for (int i = 0; i < Iteration; i++) { using (var ms = new MemoryStream()) using (var sw = new StreamWriter(ms, Encoding.UTF8, 1024, true)) using (var jw = new JsonTextWriter(sw)) { jsonSerializer.Serialize(jw, target); } } } using (new Measure("Json.NET(+GZip)")) { for (int i = 0; i < Iteration; i++) { using (var ms = new MemoryStream()) using (var gzip = new GZipStream(ms, CompressionLevel.Fastest)) using (var sw = new StreamWriter(gzip, Encoding.UTF8, 1024, true)) using (var jw = new JsonTextWriter(sw)) { jsonSerializer.Serialize(jw, target); } } } using (var ms = new MemoryStream()) { ProtoBuf.Serializer.Serialize(ms, target); data2 = ms.ToArray(); } using (var ms = new MemoryStream()) { using (var sw = new StreamWriter(ms, Encoding.UTF8, 1024, true)) using (var jw = new JsonTextWriter(sw)) { jsonSerializer.Serialize(jw, target); } dataJson = ms.ToArray(); } using (var ms = new MemoryStream()) { using (var gzip = new GZipStream(ms, CompressionLevel.Fastest)) using (var sw = new StreamWriter(gzip, Encoding.UTF8, 1024, true)) using (var jw = new JsonTextWriter(sw)) { jsonSerializer.Serialize(jw, target); } dataGzipJson = ms.ToArray(); } msgpack.GetSerializer <T>().UnpackSingleObject(data); MessagePackSerializer.Deserialize <T>(data0); ////ZeroFormatterSerializer.Deserialize<T>(data1); ProtoBuf.Serializer.Deserialize <T>(new MemoryStream(data2)); MessagePackSerializer.Deserialize <T>(data3, MessagePackSerializerOptions.LZ4Standard); jsonSerializer.Deserialize <T>(new JsonTextReader(new StreamReader(new MemoryStream(dataJson)))); Console.WriteLine(); Console.WriteLine("Deserialize::"); Deserializing = true; using (new Measure("MessagePack for C#")) { for (int i = 0; i < Iteration; i++) { MessagePackSerializer.Deserialize <T>(data0); } } using (new Measure("MessagePack for C# (LZ4)")) { for (int i = 0; i < Iteration; i++) { MessagePackSerializer.Deserialize <T>(data3, MessagePackSerializerOptions.LZ4Standard); } } using (new Measure("MsgPack-Cli")) { for (int i = 0; i < Iteration; i++) { msgpack.GetSerializer <T>().UnpackSingleObject(data); } } using (new Measure("protobuf-net")) { for (int i = 0; i < Iteration; i++) { using (var ms = new MemoryStream(data2)) { ProtoBuf.Serializer.Deserialize <T>(ms); } } } using (new Measure("ZeroFormatter")) { for (int i = 0; i < Iteration; i++) { ZeroFormatterSerializer.Deserialize <T>(data1); } } using (new Measure("Json.NET")) { for (int i = 0; i < Iteration; i++) { using (var ms = new MemoryStream(dataJson)) using (var sr = new StreamReader(ms, Encoding.UTF8)) using (var jr = new JsonTextReader(sr)) { jsonSerializer.Deserialize <T>(jr); } } } using (new Measure("Json.NET(+GZip)")) { for (int i = 0; i < Iteration; i++) { using (var ms = new MemoryStream(dataGzipJson)) using (var gzip = new GZipStream(ms, CompressionMode.Decompress)) using (var sr = new StreamReader(gzip, Encoding.UTF8)) using (var jr = new JsonTextReader(sr)) { jsonSerializer.Deserialize <T>(jr); } } } Console.WriteLine(); Console.WriteLine("FileSize::"); var label = string.Empty; label = "MessagePack for C#"; Console.WriteLine($"{label,-25} {data0.Length,14} byte"); label = "MessagePack for C# (LZ4)"; Console.WriteLine($"{label,-25} {data3.Length,14} byte"); label = "MsgPack-Cli"; Console.WriteLine($"{label,-25} {data.Length,14} byte"); label = "protobuf-net"; Console.WriteLine($"{label,-25} {data2.Length,14} byte"); label = "ZeroFormatter"; Console.WriteLine($"{label,-25} {data1.Length,14} byte"); label = "Json.NET"; Console.WriteLine($"{label,-25} {dataJson.Length,14} byte"); label = "Json.NET(+GZip)"; Console.WriteLine($"{label,-25} {dataGzipJson.Length,14} byte"); Console.WriteLine(); Console.WriteLine(); }
protected override void HandleBytes(byte[] data, IPEndPoint endPoint) { MessageWrapper messageWrapper = ZeroFormatterSerializer.Deserialize <MessageWrapper>(data); messageProcessor.Handle(messageWrapper, endPoint); }
protected override T Deserialize(Stream stream) { return(ZeroFormatterSerializer.Deserialize <T>(stream)); }
private void ReplayLoop() { if (!replayLoopInProgress) { replayLoopInProgress = true; if (replayModeActivated) { if (isReplayingFileSerieDefined) { //Si le nom de la série de fichier à traiter est défini if (!isReplayingFileOpened) { //Si aucun fichier n'est ouvert, on ouvre le courant if (subFileIndex == 0) { filePath = replayFileSerieName + "0_Init.rbt"; } else { filePath = replayFileSerieName + subFileIndex + ".rbt"; } if (File.Exists(filePath)) { sr = new StreamReader(filePath); isReplayingFileOpened = true; OnFileNameChange(filePath); if (subFileIndex == 0) { initialDateTime = DateTime.Now; lastDataTimestamp = 0; } } else { //On n'a plus de fichier à traiter isReplayingFileOpened = false; isReplayingFileSerieDefined = false; replayModeActivated = false; } } if (isReplayingFileOpened) { int successiveDataCounter = 0; //Récupère l'instant courant de la dernière data du replay currentTimestamp = DateTime.Now.Subtract(initialDateTime).TotalMilliseconds + LogDateTimeOffsetInMs; if (currentTimestamp == null) { currentTimestamp = 0; } //On le fait tant que l'instant courant des data de Replay est inférieur à l'instant théorique de simulation, on traite les datas while (lastDataTimestamp <= currentTimestamp * speedFactor && isReplayingFileOpened && successiveDataCounter < 10) { var s = sr.ReadLine(); if (s != null) { byte[] bytes = Convert.FromBase64String(s); var deserialization = ZeroFormatterSerializer.Deserialize <ZeroFormatterLogging>(bytes); switch (deserialization.Type) { case ZeroFormatterLoggingType.PolarSpeedEventArgs: PolarSpeedEventArgsLog robotSpeedData = (PolarSpeedEventArgsLog)deserialization; lastDataTimestamp = robotSpeedData.InstantInMs; var eSpeed = new PolarSpeedEventArgs(); eSpeed.RobotId = robotSpeedData.RobotId; eSpeed.Vtheta = robotSpeedData.Vtheta; eSpeed.Vx = robotSpeedData.Vx; eSpeed.Vy = robotSpeedData.Vy; eSpeed.timeStampMs = robotSpeedData.timeStampMs; OnSpeedData(eSpeed); break; case ZeroFormatterLoggingType.RawLidarArgs: RawLidarArgsLog currentLidarLog = (RawLidarArgsLog)deserialization; lastDataTimestamp = currentLidarLog.InstantInMs; OnLidar(currentLidarLog.RobotId, currentLidarLog.PtList); break; default: break; } if (LogDateTimeOffsetInMs == null) { LogDateTimeOffsetInMs = lastDataTimestamp; } successiveDataCounter++; } else { //Lecture échouée, on a une fin de fichier isReplayingFileOpened = false; sr.Close(); subFileIndex++; } //Récupère l'instant courant de la dernière data du replay currentTimestamp = (double)(DateTime.Now.Subtract(initialDateTime).TotalMilliseconds + LogDateTimeOffsetInMs); } } } } replayLoopInProgress = false; } }
public T Deserialise <T>(byte[] packetBytes, int offset, int length) { var res = ZeroFormatterSerializer.Deserialize <T>(packetBytes, offset); return(res); }
public async Task <LobbyModel> Load(CancellationToken cts) { log.Info("Старт скачивания модели аккаунта"); using (HttpClient httpClient = new HttpClient()) { int attemptNumber = 0; while (true) { if (attemptNumber != 0) { await Task.Delay(3000, cts); } log.Info("Номер попытки " + attemptNumber++); try { if (!PlayerIdStorage.TryGetServiceId(out string playerServiceId)) { log.Error("Не удалось получить id игрока"); continue; } else { log.Error("id игрока получен"); } if (!PlayerIdStorage.TryGetUsername(out string username)) { log.Error("Не удалось получить username игрока"); continue; } HttpResponseMessage response; using (MultipartFormDataContent formData = new MultipartFormDataContent()) { formData.Add(new StringContent(playerServiceId), nameof(playerServiceId)); formData.Add(new StringContent(username), nameof(username)); response = await httpClient.PostAsync(NetworkGlobals.InitializeLobbyUrl, formData, cts); } if (!response.IsSuccessStatusCode) { log.Error("Статус ответа " + response.StatusCode); continue; } string base64String = await response.Content.ReadAsStringAsync(); if (base64String.Length == 0) { log.Error("Ответ пуст "); continue; } byte[] data = Convert.FromBase64String(base64String); log.Info("Длина ответа в байтах " + data.Length); LobbyModel result = ZeroFormatterSerializer.Deserialize <LobbyModel>(data); log.Info("Десериализация прошла нормально"); return(result); } catch (TaskCanceledException e) { log.Error("Task был отменён"); } catch (Exception e) { UiSoundsManager.Instance().PlayError(); log.Error("Упало при скачивании модели " + e.Message + " " + e.StackTrace); } } } }
public void EnumFormatTest() { { var r = ZeroFormatterSerializer.Serialize <IntEnum>(IntEnum.Apple); ZeroFormatterSerializer.Deserialize <IntEnum>(r).Is(IntEnum.Apple); ZeroFormatterSerializer.Serialize <IntEnum>(IntEnum.Orange); } { var r = ZeroFormatterSerializer.Serialize <IntEnum?>(null); ZeroFormatterSerializer.Deserialize <IntEnum?>(r).IsNull(); } { var r = ZeroFormatterSerializer.Serialize <IntEnum?>(IntEnum.Apple); ZeroFormatterSerializer.Deserialize <IntEnum?>(r).Is(IntEnum.Apple); } { var r = ZeroFormatterSerializer.Serialize <UIntEnum>(UIntEnum.Apple); ZeroFormatterSerializer.Deserialize <UIntEnum>(r).Is(UIntEnum.Apple); } { var r = ZeroFormatterSerializer.Serialize <UIntEnum?>(null); ZeroFormatterSerializer.Deserialize <UIntEnum?>(r).IsNull(); } { var r = ZeroFormatterSerializer.Serialize <UIntEnum?>(UIntEnum.Apple); ZeroFormatterSerializer.Deserialize <UIntEnum?>(r).Is(UIntEnum.Apple); } { var r = ZeroFormatterSerializer.Serialize <UShortEnum>(UShortEnum.Apple); ZeroFormatterSerializer.Deserialize <UShortEnum>(r).Is(UShortEnum.Apple); } { var r = ZeroFormatterSerializer.Serialize <UShortEnum?>(null); ZeroFormatterSerializer.Deserialize <UShortEnum?>(r).IsNull(); } { var r = ZeroFormatterSerializer.Serialize <UShortEnum?>(UShortEnum.Apple); ZeroFormatterSerializer.Deserialize <UShortEnum?>(r).Is(UShortEnum.Apple); } { var r = ZeroFormatterSerializer.Serialize <ByteEnum>(ByteEnum.Apple); ZeroFormatterSerializer.Deserialize <ByteEnum>(r).Is(ByteEnum.Apple); } { var r = ZeroFormatterSerializer.Serialize <ByteEnum?>(null); ZeroFormatterSerializer.Deserialize <ByteEnum?>(r).IsNull(); } { var r = ZeroFormatterSerializer.Serialize <ByteEnum?>(ByteEnum.Apple); ZeroFormatterSerializer.Deserialize <ByteEnum?>(r).Is(ByteEnum.Apple); } { var r = ZeroFormatterSerializer.Serialize <SByteEnum>(SByteEnum.Apple); ZeroFormatterSerializer.Deserialize <SByteEnum>(r).Is(SByteEnum.Apple); } { var r = ZeroFormatterSerializer.Serialize <SByteEnum?>(null); ZeroFormatterSerializer.Deserialize <SByteEnum?>(r).IsNull(); } { var r = ZeroFormatterSerializer.Serialize <SByteEnum?>(SByteEnum.Apple); ZeroFormatterSerializer.Deserialize <SByteEnum?>(r).Is(SByteEnum.Apple); } { var r = ZeroFormatterSerializer.Serialize <LongEnum>(LongEnum.Apple); ZeroFormatterSerializer.Deserialize <LongEnum>(r).Is(LongEnum.Apple); } { var r = ZeroFormatterSerializer.Serialize <LongEnum?>(null); ZeroFormatterSerializer.Deserialize <LongEnum?>(r).IsNull(); } { var r = ZeroFormatterSerializer.Serialize <LongEnum?>(LongEnum.Apple); ZeroFormatterSerializer.Deserialize <LongEnum?>(r).Is(LongEnum.Apple); } { var r = ZeroFormatterSerializer.Serialize <ULongEnum>(ULongEnum.Apple); ZeroFormatterSerializer.Deserialize <ULongEnum>(r).Is(ULongEnum.Apple); } { var r = ZeroFormatterSerializer.Serialize <ULongEnum?>(null); ZeroFormatterSerializer.Deserialize <ULongEnum?>(r).IsNull(); } { var r = ZeroFormatterSerializer.Serialize <ULongEnum?>(ULongEnum.Apple); ZeroFormatterSerializer.Deserialize <ULongEnum?>(r).Is(ULongEnum.Apple); } }
public void Handle(INetworkerConnection clientConnection, NetworkerPacketBase packet, byte[] bytes) { this.Handle(clientConnection, ZeroFormatterSerializer.Deserialize <T>(bytes)); }
public int ZeroFormatter() { return(SumResult(ZeroFormatterSerializer.Deserialize <IntStruct>(ZeroFormatterInput))); }
private static T ZFDeserialise <T>(byte[] binary) { return((T)AfterDeserialiseObject(ZeroFormatterSerializer.Deserialize <T>(binary))); }
private void asyncReceive(object state) { while (true) { byte[] readBuffer; lock (_readBuffers) { if (_readBuffers.Count == 0) { lock (_readingPacketsLock) { _readingPackets = false; } return; } readBuffer = _readBuffers.Dequeue(); } _readableDataLen += readBuffer.Length; bool process = true; while (process) { switch (_receiveState) { case ReceiveType.Header: // PayloadLength { if (_readableDataLen >= HEADER_SIZE) { int headerLength = (_appendHeader) ? HEADER_SIZE - _tempHeaderOffset : HEADER_SIZE; try { if (_appendHeader) { try { Array.Copy(readBuffer, _readOffset, _tempHeader, _tempHeaderOffset, headerLength); } catch (Exception) { process = false; disconnect(); break; } _payloadLen = BitConverter.ToInt32(_tempHeader, 0); _tempHeaderOffset = 0; _appendHeader = false; } else { _payloadLen = BitConverter.ToInt32(readBuffer, _readOffset); } if (_payloadLen <= 0 || _payloadLen > MAX_PACKET_SIZE) { throw new Exception("invalid header"); } } catch (Exception) { process = false; disconnect(); break; } _readableDataLen -= headerLength; _readOffset += headerLength; _receiveState = ReceiveType.Payload; } else // _readableDataLen < HEADER_SIZE { try { Array.Copy(readBuffer, _readOffset, _tempHeader, _tempHeaderOffset, _readableDataLen); } catch (Exception) { process = false; disconnect(); break; } _tempHeaderOffset += _readableDataLen; _appendHeader = true; process = false; } break; } case ReceiveType.Payload: //Deserialize Payload { if (_payloadBuffer == null || _payloadBuffer.Length != _payloadLen) { _payloadBuffer = new byte[_payloadLen]; } int length = (_writeOffset + _readableDataLen >= _payloadLen) ? _payloadLen - _writeOffset : _readableDataLen; try { Array.Copy(readBuffer, _readOffset, _payloadBuffer, _writeOffset, length); } catch (Exception) { process = false; disconnect(); break; } _writeOffset += length; _readOffset += length; _readableDataLen -= length; if (_writeOffset == _payloadLen) { bool isError = _payloadBuffer.Length == 0; if (isError) { process = false; disconnect(); break; } try { IPackets packet = ZeroFormatterSerializer.Deserialize <IPackets>(_payloadBuffer); packetReader(packet); } catch (Exception) { process = false; disconnect(); break; } _receiveState = ReceiveType.Header; _payloadBuffer = null; _payloadLen = 0; _writeOffset = 0; } if (_readableDataLen == 0) { process = false; } break; } } } if (_receiveState == ReceiveType.Header) { _writeOffset = 0; } _readOffset = 0; _readableDataLen = 0; } }
/// <summary> /// Deserialize an object that is ZeroFormattable. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="input"></param> /// <exception cref="System.InvalidOperationException">Thrown when object T is not ZeroFormattable.</exception> /// <returns>An object of type T</returns> public static async Task <T> DeserializeAsZeroFormatAsync <T>(byte[] input) { return(await Task.Run(() => ZeroFormatterSerializer.Deserialize <T>(input))); }
public async Task BuyProduct(string playerServiceId, int productId, string base64ProductModelFromClient, int shopModelId) { //Аккаунт существует? AccountDbDto accountDbDto = await dbReaderService.ReadAccountAsync(playerServiceId); if (accountDbDto == null) { throw new Exception($"Такого аккаунта не существует {nameof(playerServiceId)} {playerServiceId}"); } //Модель магазина существует? ShopModelDb shopModelDb = await dbContext .ShopModels .Where(shopModelDb1 => shopModelDb1.Id == shopModelId) .SingleOrDefaultAsync(); if (shopModelDb == null) { throw new Exception($"Такой модели магазина не существует {nameof(shopModelId)} {shopModelId}"); } //Эта модель создана для этого аккаунта? if (accountDbDto.Id != shopModelDb.AccountId) { throw new Exception("Модель магазина не относится к этому аккаунту"); } //Эта модель не просрочена? if (DateTime.UtcNow - shopModelDb.CreationDateTime > TimeSpan.FromDays(3)) { throw new Exception("Модель магазина просрочена"); } //В модели магазина из БД есть продукт с таким же id? NetworkLibrary.NetworkLibrary.Http.ShopModel shopModel; try { shopModel = ZeroFormatterSerializer .Deserialize <NetworkLibrary.NetworkLibrary.Http.ShopModel>(shopModelDb.SerializedModel); } catch { throw new Exception("Не удалось десериализовать модель продукта при чтении из БД"); } if (shopModel == null) { throw new Exception("Не удалось достать модель магазина для игрока"); } ProductModel productModelFromDb = shopModel.UiSections .SelectMany(uiSection => uiSection.UiItems) .SelectMany(arr => arr) .SingleOrDefault(productModel1 => productModel1.Id == productId); if (productModelFromDb == null) { throw new Exception("В модели магазина такого продукта нет."); } //Продукт из БД совпадает с присланным с клиента? byte[] serializedProductModelFromClient = Convert.FromBase64String(base64ProductModelFromClient); byte[] serializedProductModelFromDb = ZeroFormatterSerializer.Serialize(productModelFromDb); var productModelFromClient = ZeroFormatterSerializer .Deserialize <ProductModel>(serializedProductModelFromClient); bool isEqual = new ProductChecker().IsEqual(productModelFromClient, productModelFromDb); if (!isEqual) { Console.WriteLine(serializedProductModelFromClient.Length.ToString()); Console.WriteLine(serializedProductModelFromDb.Length.ToString()); throw new Exception("Модели продуктов не совпадают"); } bool isResourcesEnough = costCheckerService .IsResourcesEnough(productModelFromClient, accountDbDto.SoftCurrency, accountDbDto.HardCurrency); if (!isResourcesEnough) { throw new Exception("Не хватает ресурсов."); } //создать транзакцию по модели продукта Transaction transaction = shopTransactionFactory.Create(productModelFromDb, accountDbDto.Id); //todo проверить транзакцию на адекватность //записать транзакцию await dbContext.Transactions.AddAsync(transaction); //перезаписать модель продукта if (productModelFromDb.ResourceTypeEnum == ResourceTypeEnum.WarshipPowerPoints) { productModelFromDb.IsDisabled = true; shopModelDb.SerializedModel = ZeroFormatterSerializer.Serialize(shopModel); } await dbContext.SaveChangesAsync(); }
public T DeserializeInternal <T>(byte[] data) { return(ZeroFormatterSerializer.Deserialize <T>(data)); }
public Root ZeroFormatter_Deserialize() { return(ZeroFormatterSerializer.Deserialize <Root>(System.Text.Encoding.UTF8.GetBytes(JsonSampleString))); }
public bool IsEqual(ProductModel productModel1, ProductModel productModel2) { if (productModel1.Id != productModel2.Id) { // Console.WriteLine("Id"); return(false); } // Console.WriteLine(productModel1.Id+" "+productModel2.Id); if (productModel1.ResourceTypeEnum != productModel2.ResourceTypeEnum) { // Console.WriteLine("ResourceTypeEnum"); return(false); } // Console.WriteLine(productModel1.ResourceTypeEnum+" "+productModel2.ResourceTypeEnum); // Console.WriteLine(productModel1.SerializedModel.Length+" "+productModel2.SerializedModel.Length); switch (productModel1.ResourceTypeEnum) { case ResourceTypeEnum.WarshipPowerPoints: { var model1 = ZeroFormatterSerializer.Deserialize <WarshipPowerPointsProductModel>(productModel1.SerializedModel); var model2 = ZeroFormatterSerializer.Deserialize <WarshipPowerPointsProductModel>(productModel2.SerializedModel); if (model1.Increment != model2.Increment) { // Console.WriteLine("FinishValue "); return(false); } if (model1.WarshipId != model2.WarshipId) { // Console.WriteLine("WarshipId"); return(false); } break; } case ResourceTypeEnum.SoftCurrency: { var model1 = ZeroFormatterSerializer.Deserialize <SoftCurrencyProductModel>(productModel1.SerializedModel); var model2 = ZeroFormatterSerializer.Deserialize <SoftCurrencyProductModel>(productModel2.SerializedModel); if (model1.Amount != model2.Amount) { return(false); } break; } default: throw new ArgumentOutOfRangeException(); } if (productModel1.CostModel.CostTypeEnum != productModel2.CostModel.CostTypeEnum) { // Console.WriteLine("CostTypeEnum"); return(false); } // Console.WriteLine(productModel1.SerializedModel.Length+" "+productModel2.SerializedModel.Length); if (productModel1.CostModel.SerializedCostModel.Length != productModel2.CostModel.SerializedCostModel.Length) { // Console.WriteLine("CostModel.SerializedCostModel.Length"); return(false); } // Console.WriteLine(productModel1.CostModel.SerializedCostModel.Length+" "+productModel2.CostModel.SerializedCostModel.Length); if (productModel1.ProductSizeEnum != productModel2.ProductSizeEnum) { // Console.WriteLine("ProductSizeEnum"); return(false); } // Console.WriteLine(productModel1.ProductSizeEnum+" "+productModel2.ProductSizeEnum); if (productModel1.IsDisabled != productModel2.IsDisabled) { // Console.WriteLine("IsDisabled"); return(false); } // Console.WriteLine(productModel1.IsDisabled+" "+productModel2.IsDisabled); if (productModel1.ProductMark != productModel2.ProductMark) { // Console.WriteLine("ProductMark"); return(false); } // Console.WriteLine(productModel1.SerializedModel.Length+" "+productModel2.SerializedModel.Length); if (productModel1.ProductMark?.ProductMarkTypeEnum != productModel2.ProductMark?.ProductMarkTypeEnum) { // Console.WriteLine("ProductMark.ProductMarkTypeEnum"); return(false); } // Console.WriteLine(productModel1.ProductMark?.ProductMarkTypeEnum+" "+productModel2.ProductMark?.ProductMarkTypeEnum); if (productModel1.ProductMark?.SerializedProductMark.Length != productModel2.ProductMark?.SerializedProductMark.Length) { // Console.WriteLine("ProductMark.SerializedProductMark.Length"); return(false); } // Console.WriteLine(productModel1.ProductMark?.SerializedProductMark.Length+" "+productModel2.ProductMark?.SerializedProductMark.Length); if (productModel1.PreviewImagePath != productModel2.PreviewImagePath) { // Console.WriteLine("PreviewImagePath"); return(false); } // Console.WriteLine(productModel1.PreviewImagePath+" "+productModel2.PreviewImagePath); // Console.WriteLine("Проверка прошла успешно"); return(true); }
public async Task <IActionResult> Index(string id) { Logger.LogInformation("Hello from the External SPA Home Index Controller"); var spa = _externalSpaStore.GetRecord(id); if (spa == null) { return(new NotFoundResult()); } var loadedSpas = SessionCacheManager <Dictionary <string, ExternalSPARecord> > .Grab(_httpContextAccessor.HttpContext, _loadedSpasKey) ?? new Dictionary <string, ExternalSPARecord>(); var result = HttpContext.User.Claims.Select( c => new ClaimType { Type = c.Type, Value = c.Value }); var cacheKey = $".extSpaViewBagRecord.{id}"; ViewBagRecord viewBagRecord = null; var value = await _cache.GetAsync(cacheKey); if (value != null) { viewBagRecord = ZeroFormatterSerializer.Deserialize <ViewBagRecord>(value); } else { var doc = await _discoveryCache.GetAsync(); var request = new AuthorizeRequest(doc.AuthorizeEndpoint); var url = request.CreateAuthorizeUrl( clientId: spa.ClientId, responseType: OidcConstants.ResponseTypes.Code, prompt: OidcConstants.PromptModes.None, redirectUri: spa.RedirectUri, scope: "openid profile email"); var mySpaRecord = new MySpaRecord() { ClientId = spa.ClientId, Key = spa.Key, RedirectUri = spa.RedirectUri, CacheBustHash = spa.CacheBustHash }; viewBagRecord = new ViewBagRecord { AuthorizeEndpoint = doc.AuthorizeEndpoint, AuthorizeUrl = url, SpaRecord = mySpaRecord }; var val = ZeroFormatterSerializer.Serialize(viewBagRecord); var cacheEntryOptions = new DistributedCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromMinutes(5)); _cache.Set(cacheKey, val, cacheEntryOptions); } ViewBag.ViewBagRecord = viewBagRecord; if (!loadedSpas.ContainsKey(id)) { loadedSpas.Add(id, spa); SessionCacheManager <Dictionary <string, ExternalSPARecord> > .Insert(_httpContextAccessor.HttpContext, _loadedSpasKey, loadedSpas); } var key = $".extSpa.Session.{viewBagRecord.SpaRecord.Key}"; var customData = SessionCacheManager <string> .Grab(_httpContextAccessor.HttpContext, key); ViewBag.CacheBustHash = viewBagRecord.SpaRecord.CacheBustHash; ViewBag.CustomData = customData; return(View(spa.View, result)); }
public Summary ZeroFormatterBinaryDeserializer() { return(ZeroFormatterSerializer.Deserialize <Summary>(_summaryZeroFormatterBytes)); }
public virtual void ReadFromBinaryFile <T>(string filePath) where T : struct, IEquatable <T>, IFormattable { byte[] bytes = File.ReadAllBytes(filePath); T[] data = ZeroFormatterSerializer.Deserialize <T[]>(bytes); ReadFrom(data, data.Length); }