public void Offset() { var ot = new OffsetType() { Dummy1 = 100, Dummy2 = "hogehogehugahuga", VariableSizeList = new[] { "a", "bvcde", "fwadfaze" }, Dictionary = new Dictionary<string, int> { { "a", 3232 }, { "fdaaz", 9999 } }, ObjectProp = new Offset2 { Prop1 = 10, Prop2 = "abc" } }; var ms = new MemoryStream(); ms.Position = 99; // skip to... ZeroFormatterSerializer.Serialize(ms, ot); var originalBytes = ms.ToArray(); // var originalBytes = ZeroFormatterSerializer.Serialize(ot); var newBytes = new byte[originalBytes.Length + 13]; Array.Copy(originalBytes, 0, newBytes, 13, originalBytes.Length); int size; var newT = Formatter<DefaultResolver, OffsetType>.Default.Deserialize(ref newBytes, 13 + 99, new DirtyTracker(), out size); size.Is(originalBytes.Length - 99); newT.Dummy1.Is(ot.Dummy1); newT.Dummy2.Is(ot.Dummy2); newT.VariableSizeList.Is(ot.VariableSizeList); newT.Dictionary["a"].Is(3232); newT.Dictionary["fdaaz"].Is(9999); newT.ObjectProp.Prop1.Is(ot.ObjectProp.Prop1); newT.ObjectProp.Prop2.Is(ot.ObjectProp.Prop2); var bytes = ZeroFormatterSerializer.Serialize(newT); var newT2 = ZeroFormatterSerializer.Deserialize<OffsetType>(bytes); newT2.Dummy1.Is(ot.Dummy1); newT2.Dummy2.Is(ot.Dummy2); newT2.VariableSizeList.Is(ot.VariableSizeList); newT2.Dictionary["a"].Is(3232); newT2.Dictionary["fdaaz"].Is(9999); newT2.ObjectProp.Prop1.Is(ot.ObjectProp.Prop1); newT2.ObjectProp.Prop2.Is(ot.ObjectProp.Prop2); }
public override void ReadFromBinaryFile <T>(string filePath) { byte[] bytes = File.ReadAllBytes(filePath); if (bytes.Length > ZeroFormatterSerializer.MaximumLengthOfDeserialize) { ZeroFormatterSerializer.MaximumLengthOfDeserialize = bytes.Length; } T[] dataWithSizeInfo = ZeroFormatterSerializer.Deserialize <T[]>(bytes); _buffer.nRows = (uint)Convert.ChangeType(dataWithSizeInfo[dataWithSizeInfo.Length - 2], typeof(uint)); _buffer.nCols = (uint)Convert.ChangeType(dataWithSizeInfo[dataWithSizeInfo.Length - 1], typeof(uint)); T[] data = new T[dataWithSizeInfo.Length - 2]; Array.Copy(dataWithSizeInfo, data, data.Length); SetColumnsPointers(); ReadFrom(data, data.Length); }
public async Task Send(T message, IPEndPoint to) { if (message == null) { throw new ArgumentNullException(nameof(message)); } // Build a byte array of the serialized data byte[] bytes = ZeroFormatterSerializer.Serialize(message); ArraySegment <byte> segment = new ArraySegment <byte>(bytes); // Find socket var socket = Clients.FirstOrDefault(c => c.Key.Equals(to)).Value; if (socket == null) { throw new Exception($"The IP Address {to} could not be found!"); } int size = bytes.Length; await SendLeading(size, socket); // send leading size // Write buffered int written = 0; while (written < size) { int send = size - written; // current buffer size if (send > ReceiveBufferSize) { send = ReceiveBufferSize; // max size } ArraySegment <byte> slice = segment.SliceEx(written, send); // buffered portion of array written = await socket.SendAsync(slice, SocketFlags.None); } if (written < 1) { throw new TransferException($"{written} bytes were sent! " + "Null bytes could mean a connection shutdown."); } }
public ProductModel Create(int cost, string previewImagePath, int increment, int warshipId, WarshipTypeEnum warshipTypeEnum) { if (warshipId == 0) { throw new Exception("warshipId is empty"); } Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Создание очков силы для корабля:"); Console.WriteLine($"{nameof(warshipId)} {warshipId} " + $"{nameof(increment)} {increment} " + $"{nameof(warshipTypeEnum)} {warshipTypeEnum}"); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); return(new ProductModel { ResourceTypeEnum = ResourceTypeEnum.WarshipPowerPoints, CostModel = new CostModel() { CostTypeEnum = CostTypeEnum.SoftCurrency, SerializedCostModel = ZeroFormatterSerializer.Serialize( new InGameCurrencyCostModel() { Cost = cost }) }, PreviewImagePath = previewImagePath, SerializedModel = ZeroFormatterSerializer.Serialize(new WarshipPowerPointsProductModel { WarshipId = warshipId, Increment = increment, WarshipTypeEnum = warshipTypeEnum, SupportClientModel = null }), ProductSizeEnum = ProductSizeEnum.Small }); }
public async Task <NetworkLibrary.NetworkLibrary.Http.ShopModel> Write(NetworkLibrary.NetworkLibrary.Http.ShopModel shopModel, int accountId) { ShopModelDb shopModelDb = new ShopModelDb { CreationDateTime = DateTime.UtcNow, AccountId = accountId }; await dbContext.ShopModels.AddAsync(shopModelDb); await dbContext.SaveChangesAsync(); //Эта хрень нужна для того, чтобы id у модели магазина всегда был уникальным shopModel.Id = shopModelDb.Id; shopModelDb.SerializedModel = ZeroFormatterSerializer.Serialize(shopModel); await dbContext.SaveChangesAsync(); return(shopModel); }
public void SendNetMessage <T>(ClientPacketID id, T message, bool compress = false) where T : BaseMessage { var body = ZeroFormatterSerializer.Serialize(message); var header = new PacketHeader((byte)id, compress, (ushort)body.Length); uint size = 0; if (compress) { var compressedBody = CLZF2.Compress(body); header.ContentLength = (ushort)compressedBody.Length; _client.Send(NetworkUtils.CreateMessageBytes(header, compressedBody, out size)); } else { _client.Send(NetworkUtils.CreateMessageBytes(header, body, out size)); } _bytesSent += size; _packetsSent++; }
public void Bool() { { var r = ZeroFormatterSerializer.Serialize(true); ZeroFormatterSerializer.Deserialize <bool>(r).IsTrue(); } { var r = ZeroFormatterSerializer.Serialize(false); ZeroFormatterSerializer.Deserialize <bool>(r).IsFalse(); } { var r = ZeroFormatterSerializer.Serialize <bool?>(null); ZeroFormatterSerializer.Deserialize <bool?>(r).IsNull(); } { var r = ZeroFormatterSerializer.Serialize <bool?>(true); ZeroFormatterSerializer.Deserialize <bool?>(r).Value.IsTrue(); } }
public void OnIMURawDataReceived(object sender, IMUDataEventArgs e) { IMUDataEventArgsLog data = new IMUDataEventArgsLog(); data.accelX = e.accelX; data.accelY = e.accelY; data.accelZ = e.accelZ; data.gyroX = e.gyroX; data.gyroY = e.gyroY; data.gyroZ = e.gyroZ; data.magX = e.magX; data.magY = e.magY; data.magZ = e.magZ; data.EmbeddedTimeStampInMs = e.EmbeddedTimeStampInMs; data.InstantInMs = DateTime.Now.Subtract(initialDateTime).TotalMilliseconds; var msg = ZeroFormatterSerializer.Serialize <ZeroFormatterLogging>(data); Log(msg); }
public async Task Send(T message, IPEndPoint to) { if (message.Equals(default(T))) { throw new ArgumentNullException(nameof(message)); } // Build a byte array of the serialized data var bytes = ZeroFormatterSerializer.Serialize(message); var segment = new ArraySegment <byte>(bytes); // Find socket var socket = Sockets.FirstOrDefault(c => c.Key.Equals(to)).Value; if (socket == null) { throw new NetworkInterfaceException($"The IP Address {to} could not be found!"); } int size = bytes.Length; await LeadingByteProcessor.SendLeading(socket, size).ConfigureAwait(false); // send leading size //TODO: Do something when sending interrupts? Wait for client to come back? // Write buffered int written = 0; while (written < size) { int send = size - written; // current buffer size if (send > SendBufferSize) { send = SendBufferSize; // max size } var slice = segment.SliceEx(written, send); // buffered portion of array written = await socket.SendAsync(slice, SocketFlags.None).ConfigureAwait(false); } if (written < 1) { throw new TransferException($"{written} bytes were sent! " + "Null bytes could mean a connection shutdown."); } }
public void HandleBytes(byte[] datagram) { //Для отладки на компьютере специально пропуская пакеты #if UNITY_EDITOR if (packetLossEvent.IsEventHappened()) { return; } #endif MessagesPack messagesContainer = ZeroFormatterSerializer.Deserialize <MessagesPack>(datagram); NetworkStatisticsStorage.Instance.RegisterDatagram(datagram.Length, messagesContainer.Id); foreach (byte[] data in messagesContainer.Messages) { MessageWrapper message = ZeroFormatterSerializer.Deserialize <MessageWrapper>(data); NetworkStatisticsStorage.Instance.RegisterMessage(data.Length, message.MessageType); messageProcessor.Handle(message); } }
public void OnPerceptionReceived(object sender, EventArgsLibrary.PerceptionArgs e) { //PerceptionMonitor.PerceptionReceived(); if (localWorldMap == null) { return; } if (localWorldMap.RobotId == e.RobotId) { //On ajoute les infos à la Local World Map localWorldMap.robotLocation = e.Perception.robotKalmanLocation; localWorldMap.obstaclesLocationList = e.Perception.obstaclesLocationList; localWorldMap.ballLocationList = e.Perception.ballLocationList; //On recopie les infos de la local World Map dans la structure de transfert (sans ce qui coute cher : heatmaps, lidarpoints...) LocalWorldMap transferLocalWorldMap = new LocalWorldMap(); transferLocalWorldMap.RobotId = localWorldMap.RobotId; transferLocalWorldMap.TeamId = localWorldMap.TeamId; transferLocalWorldMap.robotLocation = localWorldMap.robotLocation; transferLocalWorldMap.destinationLocation = localWorldMap.destinationLocation; transferLocalWorldMap.waypointLocation = localWorldMap.waypointLocation; transferLocalWorldMap.robotGhostLocation = localWorldMap.robotGhostLocation; transferLocalWorldMap.robotRole = localWorldMap.robotRole; transferLocalWorldMap.ballHandlingState = localWorldMap.ballHandlingState; transferLocalWorldMap.messageDisplay = localWorldMap.messageDisplay; transferLocalWorldMap.playingSide = localWorldMap.playingSide; transferLocalWorldMap.obstaclesLocationList = localWorldMap.obstaclesLocationList; transferLocalWorldMap.ballLocationList = localWorldMap.ballLocationList; if (transferLocalWorldMap.robotLocation != null) { var s = ZeroFormatterSerializer.Serialize <WorldMap.ZeroFormatterMsg>(transferLocalWorldMap); OnMulticastSendLocalWorldMapCommand(s); //Envoi à destination des autres robots en multicast OnLocalWorldMapToGlobalWorldMapGenerator(transferLocalWorldMap); //Envoi à destination du robot lui même en direct OnLocalWorldMapForDisplayOnly(localWorldMap); //Pour affichage uniquement, sinon transmission radio en, multicast //LWMEmiseMonitoring.LWMEmiseMonitor(s.Length); } } }
public static (KlineArrayInfo info, IList) Deserialize(string path) { var(info, stream) = DeserializeStream(path); Stream?decompressionStream = null; if (info.Compression == "LZ4") { decompressionStream = stream = LZ4Stream.Decode(stream); } //Console.WriteLine($"stream position: {stream.Position}"); IList list; try { switch (info.FieldSet) { case FieldSet.Native: list = ZeroFormatterSerializer.Deserialize <List <BinanceFuturesKlineItem> >(stream); break; case FieldSet.Ohlcv: list = ZeroFormatterSerializer.Deserialize <List <OhlcvItem> >(stream); break; case FieldSet.Ohlc: list = ZeroFormatterSerializer.Deserialize <List <OhlcDecimalItem> >(stream); break; default: throw new NotImplementedException($"{nameof(info.FieldSet)} info.FieldSet.ToString()"); } } finally { decompressionStream?.Dispose(); stream.Dispose(); } Trace.WriteLine($"Deserialized {list.Count} bars"); return(info, list); }
public void Spawn(PurchaseModel purchaseModel, GameObject sectionGameObject, ProductClickHandlerScript productClickHandlerScript) { var costModel = ZeroFormatterSerializer.Deserialize <RealCurrencyCostModel>(purchaseModel.productModel.CostModel.SerializedCostModel); HardCurrencyProductModel hardCurrencyProductModel = purchaseModel.productModel; //Создать объект на сцене GameObject premiumCurrencyItemPrefab = Resources .Load <GameObject>("Prefabs/LobbyShop/Image_PremiumCurrencyItem"); GameObject premiumCurrencyItemGameObject = Object.Instantiate(premiumCurrencyItemPrefab, sectionGameObject.transform, false); //Заполнить картинку Image itemPreview = premiumCurrencyItemGameObject.transform.Find("Image_ItemPreview") .GetComponentInChildren <Image>(); itemPreview.sprite = Resources.Load <Sprite>(purchaseModel.productModel.PreviewImagePath); //Заполнить цену Text itemCost = premiumCurrencyItemGameObject.transform.Find("Image_Cost/Text_Amount").GetComponent <Text>(); if (costModel.CostString != null) { itemCost.text = costModel.CostString.ToString(CultureInfo.InvariantCulture); } else { itemCost.text = "undefined"; } //Заполнить название Text itemName = premiumCurrencyItemGameObject.transform.Find("Image_ItemPreview/Text_ItemName").GetComponent <Text>(); itemName.text = hardCurrencyProductModel.Amount.ToString(); //Установить обработчик нажатия Button itemButton = premiumCurrencyItemGameObject.GetComponent <Button>(); itemButton.onClick.RemoveAllListeners(); itemButton.onClick.AddListener(() => { productClickHandlerScript.Product_OnClick(purchaseModel); }); }
public void TestMethod1() { var refreshToken = new RefreshToken() { AccessToken = new Token(OidcConstants.TokenTypes.AccessToken) { CreationTime = DateTime.UtcNow, Audiences = { "test-audience" }, Issuer = "the-issuer", Lifetime = 3600, Claims = new List <Claim>() { new Claim("a", "b") }, ClientId = "client-id", AccessTokenType = AccessTokenType.Jwt }, CreationTime = DateTime.UtcNow, Lifetime = 3600 * 10, }; var zeroRefreshToken = refreshToken.ToZeroRefreshToken(); var data = ZeroFormatterSerializer.Serialize <ZeroRefreshToken>(zeroRefreshToken); var zeroRefreshToken2 = ZeroFormatterSerializer.Deserialize <ZeroRefreshToken>(data); zeroRefreshToken2.ShouldBe(zeroRefreshToken); var refreshToken2 = zeroRefreshToken2.ToRefreshToken(); refreshToken2.ClientId.ShouldBe(refreshToken.ClientId); refreshToken2.CreationTime.ShouldBe(refreshToken.CreationTime); refreshToken2.Lifetime.ShouldBe(refreshToken.Lifetime); refreshToken2.Version.ShouldBe(refreshToken.Version); refreshToken2.AccessToken.CreationTime.ShouldBe(refreshToken.AccessToken.CreationTime); refreshToken2.AccessToken.Audiences.ShouldBe(refreshToken.AccessToken.Audiences); refreshToken2.AccessToken.Issuer.ShouldBe(refreshToken.AccessToken.Issuer); refreshToken2.AccessToken.Lifetime.ShouldBe(refreshToken.AccessToken.Lifetime); refreshToken2.AccessToken.Claims.ShouldBe(refreshToken.AccessToken.Claims); refreshToken2.AccessToken.ClientId.ShouldBe(refreshToken.AccessToken.ClientId); refreshToken2.AccessToken.AccessTokenType.ShouldBe(refreshToken.AccessToken.AccessTokenType); }
// Endless Start reading loop private void StartReceiving() { // Loop theoretically infinetly while (true) { try { // Read the leading "byte" long size = LeadingByteProcessor.ReadLeading(Socket).GetAwaiter().GetResult(); byte[] bytes = new byte[size]; ArraySegment <byte> segment = new ArraySegment <byte>(bytes); //TODO: Decide whether to catch errors in buffer-loop and continue once fixed or cancel whole receive? // 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 } ArraySegment <byte> slice = segment.SliceEx(read, (int)receive); // get buffered portion of array read += Socket.ReceiveAsync(slice, SocketFlags.None).GetAwaiter().GetResult(); } var message = ZeroFormatterSerializer.Deserialize <T>(segment.Array); ReceivedMessage?.Invoke(EndPoint, message); // call event } catch (ObjectDisposedException) { return; // Socket was closed & disposed -> exit } catch (SocketException) { ConnectionLost?.Invoke(EndPoint); if (!AutoReconnect) { Reconnect().GetAwaiter().GetResult(); // Try reconnecting on an error, then continue receiving } } // Listen again after client connected } }
private void SendDatagram(IPEndPoint ipEndPoint, List <byte[]> messages, int startMessageIndex, int messagesCount, int packId) { if (messagesCount == 0) { throw new Exception("Нельзя отправлять пустые контейнеры"); } //Положить сообщения в контейнер MessagesPack messagesPack = new MessagesPack(); messagesPack.Messages = new byte[messagesCount][]; messages.CopyTo(startMessageIndex, messagesPack.Messages, 0, messagesCount); //Установить номер контейнера для игрока messagesPack.Id = packId; //Сериализовать контейнер byte[] serializedDatagram = ZeroFormatterSerializer.Serialize(messagesPack); //Отправить контейнер udpSender.Send(serializedDatagram, ipEndPoint); }
private async Task writeDataAsync(List <T> samples, string dim, long index) { // Debug.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + " 序列化payload"); //var ms = new MemoryStream(); //Serializer.Serialize(ms, samples); //byte[] result = ms.ToArray(); byte[] result = ZeroFormatterSerializer.Serialize(samples); // Debug.WriteLine("size: "+result.Count()); // Debug.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + " 结束序列化payload"); SEPayload newPayload = new SEPayload(); newPayload.parentid = signalId; newPayload.indexes = index; newPayload.samples = result; newPayload.dimensions = dim; // Debug.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + " 插入payload"); await mapper.InsertAsync <SEPayload>(newPayload); // Debug.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + " 结束插入payload"); }
public void Char() { { var r = ZeroFormatterSerializer.Serialize('あ'); ZeroFormatterSerializer.Deserialize <char>(r).Is('あ'); } { var r = ZeroFormatterSerializer.Serialize('z'); ZeroFormatterSerializer.Deserialize <char>(r).Is('z'); } { var r = ZeroFormatterSerializer.Serialize <char?>(null); ZeroFormatterSerializer.Deserialize <char?>(r).IsNull(); } { var r = ZeroFormatterSerializer.Serialize <char?>('花'); ZeroFormatterSerializer.Deserialize <char?>(r).Value.Is('花'); } }
public bool Set(IElementsHolder t) { FormattableModifierList formmatable = new FormattableModifierList(); formmatable.Set(t.permanentModifierList.ToList()); var core = new ElementsHolderCore { statusList = t.elementDictionary.Select(ele => { FormattableStatusHolder status = new FormattableStatusHolder(); status.Set(ele.Value); return(status); }).ToList(), modifierList = formmatable //.ToDictionary(ele=>ele.Item1,ele=>ele.status) }; Data = ZeroFormatterSerializer.Serialize(core); DataType = TypeUtils.TypeToString(t.GetType()); return(true); }
public async Task <byte[]> GetAsync(string key, CancellationToken token = default(CancellationToken)) { switch (key) { case "USD": return(ZeroFormatterSerializer.Serialize(new CacheExchangeInfo(1000) { BaseType = ExchangeType.USD, Published = DateTimeOffset.Now, Rates = new List <ExchangeRateInfo> { new ExchangeRateInfo { Rate = 1, Type = ExchangeType.EUR }, new ExchangeRateInfo { Rate = 1, Type = ExchangeType.RUB }, new ExchangeRateInfo { Rate = 1, Type = ExchangeType.USD } } })); case "NONE": return(ZeroFormatterSerializer.Serialize(new CacheExchangeInfo(1000) { BaseType = ExchangeType.USD, Published = DateTimeOffset.Now, Rates = new List <ExchangeRateInfo>() })); default: throw new ArgumentNullException(); } }
public DataBlockNode LoadDataBlock(int offset) { if (offset == 0) { return(null); } _fileStream.Seek(offset, SeekOrigin.Begin); var buffer = new byte[metaInfDataStorage.DataBlockSize]; _fileStream.Read(buffer, 0, metaInfDataStorage.DataBlockSize); using var memStream = new MemoryStream(); memStream.Write(buffer, 0, buffer.Length); memStream.Seek(0, SeekOrigin.Begin); readCount++; var block = ZeroFormatterSerializer.Deserialize <DataBlockNode>(memStream); block.FilePtr = offset; return(block); }
public void GenericClass() { var ofString = new MyGenericClass <string>("xyz", int.MinValue); var ofString2 = ZeroFormatterSerializer.Convert(ofString); ofString2.x.Is("xyz"); ofString2.y.Is(int.MinValue); var ofMGS = new MyGenericClass <MyGenericStruct <double> >( new MyGenericStruct <double>(0, 2, 3), int.MinValue); var ofMGS2 = ZeroFormatterSerializer.Convert(ofMGS); ofMGS2.x.x.Is(0d); ofMGS2.x.y.Is(2); ofMGS2.x.z.Is(3d); ofMGS2.y.Is(int.MinValue); }
public static void Main(string[] args) { var mc = new WhatC { MyReadOnlyListOne = new List <int> { 1, 10, 100, 1000 }, MyReadOnlyListTwo = new string[] { "a", "bcde", "fghijklmnop" }, MyReadOnlyDictOne = new Dictionary <int, string> { { 0, "a" }, { 100, "bcd" } }, MyReadOnlyDictTwo = new Dictionary <KeyTuple <int, string>, string> { { KeyTuple.Create(10, "aiueo"), "AAA" }, { KeyTuple.Create(999, "nano"), "sa" } } }; var converted = ZeroFormatterSerializer.Convert(mc); var huga = converted.MyReadOnlyListOne; Console.WriteLine(huga[0]); }
public void ModeLazyAllReadOnly() { ILazyReadOnlyDictionary <int, string> dict = new Dictionary <int, string> { { 1, "a" }, { 2, "b" }, { 3, "c" } }.AsLazyReadOnlyDictionary(); var immediateLazySegment = ZeroFormatterSerializer.Convert(dict); var segment = immediateLazySegment as IZeroFormatterSegment; immediateLazySegment[1].Is("a"); immediateLazySegment[2].Is("b"); immediateLazySegment[3].Is("c"); segment.CanDirectCopy().IsTrue(); var moreSerialize = ZeroFormatterSerializer.Convert(immediateLazySegment, true); (moreSerialize as IZeroFormatterSegment).CanDirectCopy().IsTrue(); }
public static void Call(string[] args) { if (args.Length != 2) { return; } string token = args[0]; string libraryName = args[1]; // Create new named pipe with token from client using (var pipe = new NamedPipeServerStream(token, PipeDirection.InOut, 1, PipeTransmissionMode.Message)) { pipe.WaitForConnection(); try { //CallData data = (CallData)formatter.Deserialize(pipe); CallData data = ZeroFormatterSerializer.Deserialize <CallData>(getMessage(pipe)); // Load requested library using (NativeLibrary library = NativeLibrary.Load(libraryName, NativeLibraryLoadOptions.SearchAll)) { // Receive CallData from client while (data.Status != KeepAliveStatus.Close) { InvokeFunction(data, pipe, library); //data = (CallData)formatter.Deserialize(pipe); data = ZeroFormatterSerializer.Deserialize <CallData>(getMessage(pipe)); } } } catch (Exception e) { WriteExceptionToClient(pipe, e); } } }
public async Task <UsernameValidationResultEnum> ChangesUsernameAsync(string username) { if (!PlayerIdStorage.TryGetServiceId(out string playerServiceId)) { log.Warn("Не удалось получить id игрока"); return(UsernameValidationResultEnum.OtherError); } HttpClient httpClient = new HttpClient(); 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.ChangeUsernameUrl, formData); } if (!response.IsSuccessStatusCode) { log.Warn("Статус ответа " + response.StatusCode); } UsernameValidationResultEnum result = UsernameValidationResultEnum.OtherError; try { string base64String = await response.Content.ReadAsStringAsync(); byte[] data = Convert.FromBase64String(base64String); result = ZeroFormatterSerializer.Deserialize <UsernameValidationResult>(data).UsernameValidationResultEnum; } catch (Exception e) { log.Error(e.Message + " " + e.StackTrace); } return(result); }
static T SerializeZeroFormatter <T>(T original) { Console.WriteLine("ZeroFormatter"); T copy = default(T); byte[] bytes = null; using (new Measure("Serialize")) { for (int i = 0; i < Iteration; i++) { bytes = ZeroFormatterSerializer.Serialize(original); } } using (new Measure("Deserialize")) { for (int i = 0; i < Iteration; i++) { copy = ZeroFormatterSerializer.Deserialize <T>(bytes); } } using (new Measure("ReSerialize")) { for (int i = 0; i < Iteration; i++) { bytes = ZeroFormatterSerializer.Serialize(copy); } } if (!dryRun) { Console.WriteLine(string.Format("{0,15} {1}", "Binary Size", ToHumanReadableSize(bytes.Length))); } return(copy); }
private void Fun_JsonTest() { byte[] c = null; for (int i = 0; i < Constant.LOOP_MAX; i++) { c = ZeroFormatterSerializer.Serialize(new StringZ { name = "a", health = 100, fff = 1.124f, position1 = new Vector3 { x = 1.123f, y = 2.123f, z = 3.123f }, position2 = new Vector3 { x = 1.123f, y = 2.123f, z = 3.123f } }); //c.name += "b"; } //Console.WriteLine(c); //var re = ZeroFormatterSerializer.Convert(c); }
private void FillData(GameObject powerPointsContent, ProductModel productModel) { WarshipPowerPointsProductModel model = productModel; int increment = model.Increment; var costModel = ZeroFormatterSerializer.Deserialize <InGameCurrencyCostModel>(productModel.CostModel .SerializedCostModel); //установить картинку корабля Image image = powerPointsContent.transform.Find("Image_WarshipPowerPointsItem/Image_WarshipPreview") .GetComponent <Image>(); image.sprite = Resources.Load <Sprite>(productModel.PreviewImagePath); //установить текущее кол-во очков силы корабля Text text = powerPointsContent.transform.Find("Image_WarshipPowerPointsItem/Empty_PowerValueRoot/Text") .GetComponent <Text>(); string text1 = $"{model.SupportClientModel.StartValue}/{model.SupportClientModel.MaxValueForLevel}"; // log.Debug("текущее кол-во очков силы корабля "+text1); text.text = text1; //установить значение слайдера Slider slider = powerPointsContent.transform .Find("Image_WarshipPowerPointsItem/Empty_PowerValueRoot/Slider").GetComponent <Slider>(); slider.value = 1f * model.SupportClientModel.StartValue / model.SupportClientModel.MaxValueForLevel; // log.Debug($"slider.value = {slider.value}"); //установить прибавляемое кол-во очков силы Text wppIncrementText = powerPointsContent.transform .Find("Image_WarshipPowerPointsItem/Text_Increment").GetComponent <Text>(); wppIncrementText.text = "+" + (increment); //установить описание Text description = powerPointsContent.transform.Find("Text_WarshipDescription").GetComponent <Text>(); description.text = $"Power points: {increment}. Collect power points to activate improvements for the spacecraft."; //установить цену Text cost = powerPointsContent.transform.Find("Button_Buy/Text_Cost").GetComponent <Text>(); cost.text = costModel.Cost.ToString(CultureInfo.InvariantCulture); //TODO сделать установку типа валюты }
public void SetData <T>(string id, T data) { var path = GetPath(id); var uncompressedBytes = ZeroFormatterSerializer.Serialize(data); var compressedBytes = LZ4Codec.Wrap(uncompressedBytes, 0, uncompressedBytes.Length); if (lck.ContainsKey(id)) { lock (lck[id]) { File.WriteAllBytes(path, compressedBytes); } } else { lock (lck) { lck[id] = new object(); File.WriteAllBytes(path, compressedBytes); } } }