private void ReadCompleted(IAsyncResult result) { var stream = (NetworkStream)result.AsyncState; try { var x = stream.EndRead(result); if (x == 0) { Reconnect(0); } for (var i = 0; i < x; i++) { if (_buffer[i] == 0) { var data = _readBuffer.ToArray(); var base64 = Encoding.UTF8.GetString(data, 0, data.Length); var actual = Convert.FromBase64String(base64); var o = _formatter.Deserialize(new MemoryStream(actual)); ThreadPool.QueueUserWorkItem(HandleMessage, o); _readBuffer.SetLength(0); } else { _readBuffer.WriteByte(_buffer[i]); } } stream.BeginRead(_buffer, 0, _buffer.Length, ReadCompleted, stream); } catch //(Exception ex) { //WriteError(ex); Reconnect(0); } }
private void SerializeCustom() { var s = new CustomBinaryFormatter(); var message = new CustomTypicalMessage() { StringProp = "hello", GuidProp = Guid.NewGuid(), IntProp = 123, DateProp = DateTime.UtcNow, }; s.Register <CustomTypicalMessage>(0); var stream = new MemoryStream(); s.Serialize(stream, message); var bytes = stream.ToArray(); RunTest("Greg Young Custom Serializer", () => { var stream2 = new MemoryStream(); s.Serialize(stream2, message); }, () => { stream.Position = 0; s.Deserialize(stream); }, bytes.Length); }
private T serializeDeserialize <T>(T message) { using (var memStream = new MemoryStream()) { _formatter.Serialize(memStream, message); memStream.Seek(0, SeekOrigin.Begin); return((T)_formatter.Deserialize(memStream)); } }
public static void Deserialize(byte[] data, Action <SactaMsg> deliver, Action <string> deliverError) { try { MemoryStream ms = new MemoryStream(data); CustomBinaryFormatter bf = new CustomBinaryFormatter(); SactaMsg msg = bf.Deserialize <SactaMsg>(ms); deliver(msg); } catch (Exception x) { Logger.Exception <SactaMsg>(x); deliverError(x.Message); } }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="dg"></param> void OnNewData(object sender, DataGram dg) { try { MemoryStream ms = new MemoryStream(dg.Data); CustomBinaryFormatter bf = new CustomBinaryFormatter(); SactaMsg msg = bf.Deserialize <SactaMsg>(ms); if (IsValid(msg)) { int net = (sender == _Comm[0] ? 0 : 1); _LastScvReceived[net] = DateTime.Now; switch (msg.Type) { case SactaMsg.MsgType.Presence: _ActivityTimeOut = (uint)(((SactaMsg.PresenceInfo)(msg.Info)).ActivityTimeOutSg * 1000); if (_ActivityTimeOut < 5) { _ActivityTimeOut = Settings.Default.ActivityTimeOut; } break; case SactaMsg.MsgType.SectAsk: SendSectorization(net, _SectorUcs, msg.UserOrg); MainForm.LogMethod("INFO", net == 0 ? "SACTA1" : "SACTA2", "Recibida Peticion de Sectorizacion"); break; case SactaMsg.MsgType.SectAnwer: SactaMsg.SectAnswerInfo info = (SactaMsg.SectAnswerInfo)(msg.Info); MainForm.LogMethod("INFO", net == 0 ? "SACTA1" : "SACTA2", String.Format("Sectorizacion V-{0}: {1}", info.Version, (info.Result == 1 ? "Implantada" : "Rechazada"))); break; case SactaMsg.MsgType.Init: MainForm.LogMethod("INFO", net == 0 ? "SACTA1" : "SACTA2", "Recibido MSG INIT"); _SeqNum = 0; break; } } } catch (Exception ex) { if (!_Disposed) { MainForm.LogMethod("ERROR", "OnNewData", String.Format("Excepción al Procesar Datos Recibidos: {0}", ex.Message)); } } }
private void ReadCompleted(IAsyncResult result) { var client = (ConnectedClient)result.AsyncState; try { var x = client.Stream.EndRead(result); if (x == 0) { RemoveClient(client.Stream); } for (int i = 0; i < x; i++) { if (client.Buffer[i] == 0) { byte[] data = client.ReadBuffer.ToArray(); var base64 = Encoding.UTF8.GetString(data, 0, data.Length); var actual = Convert.FromBase64String(base64); object o; lock (_clients) { o = _formatter.Deserialize(new MemoryStream(actual)); } if (o.GetType().Equals(typeof(DiagnosticInstanceMessage))) { MoveToDiagnostic(client.Stream); } ThreadPool.QueueUserWorkItem(HandleMessage, o); client.ReadBuffer.SetLength(0); } else { client.ReadBuffer.WriteByte(client.Buffer[i]); } } client.Stream.BeginRead(client.Buffer, 0, client.Buffer.Length, ReadCompleted, client); } catch (Exception ex) { RemoveClient(client.Stream); notifyProviderAboutDisconnect(string.Format("ReadCompleted failed ({0})", ex)); } }
public void ChatRoomInfosSerializationTest() { var original = new[] { new ChatRoomInfo { IsPasswordProtected = true, Name = "r1" }, new ChatRoomInfo { IsPasswordProtected = false, Name = "r2" } }; // Serializing var serializedData = CustomBinaryFormatter.Serialize(original); Assert.NotNull(serializedData); Assert.True(serializedData.Length > 0); // Deserializing var reconstructed = CustomBinaryFormatter.Deserialize(serializedData, 0, serializedData.Length); CollectionAssert.AreEqual(original, reconstructed, new ChatRoomInfoComparer()); }
internal static List<HistoryRecord> GetRecords(ServerInfo server, bool isServer, DateTypes dateType, DateTime startDate) { var records = new List<HistoryRecord>(); var key = GetKey(server, isServer); using (var dateIndexStream = new FileStream(GetFile(false, true), FileMode.OpenOrCreate)) { using (var dateContentStream = new FileStream(GetFile(false, false), FileMode.OpenOrCreate)) { var dateFormatter = new CustomBinaryFormatter(dateIndexStream, dateContentStream); dateFormatter.Register<HistoryDate>(1); var endDate = DateTime.Now.Date; var samplingSpan = 1; switch (dateType) { case DateTypes.Hour: endDate = startDate.AddDays(1); samplingSpan = 1; break; case DateTypes.Day: endDate = startDate.AddDays(1); samplingSpan = 24; break; case DateTypes.Week: endDate = startDate.AddDays(7); samplingSpan = 7 * 24; break; case DateTypes.Month: endDate = startDate.AddMonths(1); samplingSpan = 31 * 24; break; case DateTypes.Year: endDate = startDate.AddYears(1); samplingSpan = 365 * 24; break; default: break; } var count = dateFormatter.Count; Debug.WriteLine("all date count:" + count); Debug.WriteLine("start date:" + startDate); var dates = new List<HistoryDate>(); for (long i = 0; i < count; i++) { var date = dateFormatter.Deserialize<HistoryDate>(false); var dateTime = DateTime.Parse(date.Date); Debug.WriteLine("current date:" + dateTime); if (startDate.Date <= dateTime && dateTime <= endDate) dates.Add(date); } Debug.WriteLine("valid date count:" + dates.Count); if (dates.Count > 0) { var start = dates.Aggregate((d1, d2) => DateTime.Parse(d1.Date) < DateTime.Parse(d2.Date) ? d1 : d2); var end = dates.Aggregate((d1, d2) => DateTime.Parse(d1.Date) > DateTime.Parse(d2.Date) ? d1 : d2); using (var dataIndexStream = new FileStream(GetFile(true, true), FileMode.OpenOrCreate)) { using (var dataContentStream = new FileStream(GetFile(true, false), FileMode.OpenOrCreate)) { var historyFormatter = new CustomBinaryFormatter(dataIndexStream, dataContentStream); historyFormatter.Register<HistoryRecord>(1); for (var i = start.Index; i < end.Index; i += samplingSpan) { historyFormatter.MoveTo(i); var record = historyFormatter.Deserialize<HistoryRecord>(false); if (record.Key == key) records.Add(record); } historyFormatter.Close(); dataContentStream.Close(); } dataIndexStream.Close(); } } dateFormatter.Close(); dateContentStream.Close(); } dateIndexStream.Close(); } return records; }
internal static void AddRecords(List<HistoryRecord> records) { lock (SyncRoot) { using (var dataIndexStream = new FileStream(GetFile(true, true), FileMode.OpenOrCreate)) { using (var dataContentStream = new FileStream(GetFile(true, false), FileMode.OpenOrCreate)) { var historyFormatter = new CustomBinaryFormatter(dataIndexStream, dataContentStream); historyFormatter.Register<HistoryRecord>(1); historyFormatter.MoveToEnd(); var historyCount = historyFormatter.Count; records.ForEach(r => { historyFormatter.Serialize<HistoryRecord>(r); }); historyFormatter.Flush(); using (var dateIndexStream = new FileStream(GetFile(false, true), FileMode.OpenOrCreate)) { using (var dateContentStream = new FileStream(GetFile(false, false), FileMode.OpenOrCreate)) { var dateFormatter = new CustomBinaryFormatter(dateIndexStream, dateContentStream); dateFormatter.Register<HistoryDate>(1); var dateCount = dateFormatter.Count; var today = DateTime.Now.Date.AddDays(1); var yesterday = DateTime.Now.Date; long todayIndex = -1; var foundYesterday = false; for (long i = 0; i < dateCount; i++) { var date = dateFormatter.Deserialize<HistoryDate>(false); if (DateTime.Parse(date.Date) == today) todayIndex = i; if (DateTime.Parse(date.Date) == yesterday) foundYesterday = true; } if (!foundYesterday) { dateFormatter.MoveToEnd(); dateFormatter.Serialize<HistoryDate>(new HistoryDate { Date = yesterday.ToString(), Index = historyCount }); } if (todayIndex != -1) { dateFormatter.MoveTo(todayIndex); dateFormatter.Serialize<HistoryDate>(new HistoryDate { Date = today.ToString(), Index = historyFormatter.Count }, true); } else { dateFormatter.MoveToEnd(); dateFormatter.Serialize<HistoryDate>(new HistoryDate { Date = today.ToString(), Index = historyFormatter.Count }); } dateFormatter.Flush(); } } } } } }
internal static List <HistoryRecord> GetRecords(ServerInfo Server, bool IsServer, DateTypes DateType, DateTime StartDate) { var records = new List <HistoryRecord>(); var key = GetKey(Server, IsServer); using (FileStream dateIndexStream = new FileStream(GetFile(false, true), FileMode.OpenOrCreate)) { using (FileStream dateContentStream = new FileStream(GetFile(false, false), FileMode.OpenOrCreate)) { var dateFormatter = new CustomBinaryFormatter(dateIndexStream, dateContentStream); dateFormatter.Register <HistoryDate>(1); var endDate = DateTime.Now.Date; var samplingSpan = 1; switch (DateType) { case DateTypes.Hour: endDate = StartDate.AddDays(1); samplingSpan = 1; break; case DateTypes.Day: endDate = StartDate.AddDays(1); samplingSpan = 24; break; case DateTypes.Week: endDate = StartDate.AddDays(7); samplingSpan = 7 * 24; break; case DateTypes.Month: endDate = StartDate.AddMonths(1); samplingSpan = 31 * 24; break; case DateTypes.Year: endDate = StartDate.AddYears(1); samplingSpan = 365 * 24; break; default: break; } var count = dateFormatter.Count; System.Diagnostics.Debug.WriteLine("all date count:" + count); System.Diagnostics.Debug.WriteLine("start date:" + StartDate); var dates = new List <HistoryDate>(); for (long i = 0; i < count; i++) { var date = dateFormatter.Deserialize <HistoryDate>(false); var dateTime = DateTime.Parse(date.Date); System.Diagnostics.Debug.WriteLine("current date:" + dateTime); if (StartDate.Date <= dateTime && dateTime <= endDate) { dates.Add(date); } } System.Diagnostics.Debug.WriteLine("valid date count:" + dates.Count); if (dates.Count > 0) { var start = dates.Aggregate((d1, d2) => DateTime.Parse(d1.Date) < DateTime.Parse(d2.Date) ? d1 : d2); var end = dates.Aggregate((d1, d2) => DateTime.Parse(d1.Date) > DateTime.Parse(d2.Date) ? d1 : d2); using (FileStream dataIndexStream = new FileStream(GetFile(true, true), FileMode.OpenOrCreate)) { using (FileStream dataContentStream = new FileStream(GetFile(true, false), FileMode.OpenOrCreate)) { var historyFormatter = new CustomBinaryFormatter(dataIndexStream, dataContentStream); historyFormatter.Register <HistoryRecord>(1); for (long i = start.Index; i < end.Index; i += samplingSpan) { historyFormatter.MoveTo(i); var record = historyFormatter.Deserialize <HistoryRecord>(false); if (record.Key == key) { records.Add(record); } } historyFormatter.Close(); dataContentStream.Close(); } dataIndexStream.Close(); } } dateFormatter.Close(); dateContentStream.Close(); } dateIndexStream.Close(); } return(records); }
internal static void AddRecords(List <HistoryRecord> Records) { lock (_syncRoot) { using (FileStream dataIndexStream = new FileStream(GetFile(true, true), FileMode.OpenOrCreate)) { using (FileStream dataContentStream = new FileStream(GetFile(true, false), FileMode.OpenOrCreate)) { var historyFormatter = new CustomBinaryFormatter(dataIndexStream, dataContentStream); historyFormatter.Register <HistoryRecord>(1); historyFormatter.MoveToEnd(); var historyCount = historyFormatter.Count; Records.ForEach(r => { historyFormatter.Serialize <HistoryRecord>(r); }); historyFormatter.Flush(); using (FileStream dateIndexStream = new FileStream(GetFile(false, true), FileMode.OpenOrCreate)) { using (FileStream dateContentStream = new FileStream(GetFile(false, false), FileMode.OpenOrCreate)) { var dateFormatter = new CustomBinaryFormatter(dateIndexStream, dateContentStream); dateFormatter.Register <HistoryDate>(1); var dateCount = dateFormatter.Count; var today = DateTime.Now.Date.AddDays(1); var yesterday = DateTime.Now.Date; long todayIndex = -1; var foundYesterday = false; for (long i = 0; i < dateCount; i++) { var date = dateFormatter.Deserialize <HistoryDate>(false); if (DateTime.Parse(date.Date) == today) { todayIndex = i; } if (DateTime.Parse(date.Date) == yesterday) { foundYesterday = true; } } if (!foundYesterday) { dateFormatter.MoveToEnd(); dateFormatter.Serialize <HistoryDate>(new HistoryDate { Date = yesterday.ToString(), Index = historyCount }); } if (todayIndex != -1) { dateFormatter.MoveTo(todayIndex); dateFormatter.Serialize <HistoryDate>(new HistoryDate { Date = today.ToString(), Index = historyFormatter.Count }, true); } else { dateFormatter.MoveToEnd(); dateFormatter.Serialize <HistoryDate>(new HistoryDate { Date = today.ToString(), Index = historyFormatter.Count }); } dateFormatter.Flush(); } } } } } }