/// <summary> /// 保存用户信息 /// </summary> /// <param name="user"></param> public void SaveUserInfo(Models.UserInfo user) { if (user == null) { return; } BinarySerializeHelper.Serialize(Paths.UserInfoFile, user); }
/// <summary> /// 从hash表获取Model /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="dataKey"></param> /// <returns></returns> public T HashGet <T>(string key, string dataKey) where T : class { var redisValue = _redisDb.HashGet(key, dataKey); var bytes = Convert.FromBase64String(redisValue); var model = BinarySerializeHelper.DeserializeObject2(bytes) as T; return(model); }
public static NetPacket GetPacket(byte[] buffer) { if (buffer.Length < NetPacketHead.HEAD_SIZE) { throw (new Exception("数据包长度过短,无法转换")); } if (buffer.Length < (NetPacketHead.HEAD_SIZE + BitConverter.ToInt32(buffer, 8))) { throw (new Exception("数据包长度过短,无法转换")); } Int32 version = BitConverter.ToInt32(buffer, 0);//协议号 if (version != NetPacketHead.Version) { throw (new Exception("数据协议版本号不符!")); } NetPacket packet = new NetPacket(); NetPacketHead packetHead = new NetPacketHead(); packetHead.PType = (NetPacketType)BitConverter.ToInt32(buffer, sizeof(Int32));//封包类型 packetHead.Len = BitConverter.ToInt32(buffer, sizeof(Int32) + sizeof(Int32)); packet._packetHead = packetHead; Byte[] packetBuffer = new Byte[packetHead.Len]; Array.Copy(buffer, NetPacketHead.HEAD_SIZE, packetBuffer, 0, packetHead.Len); switch (packetHead.PType) { case NetPacketType.STRING: packet.Data = encoding.GetString(packetBuffer); break; case NetPacketType.BINARY: NetFile f = new NetFile(); int filenamelen = BitConverter.ToInt32(packetBuffer, 0);//文件名长度 f.FileName = encoding.GetString(packetBuffer, sizeof(Int32), filenamelen); f.Content = new Byte[packetBuffer.Length - sizeof(Int32) - filenamelen]; Array.Copy(packetBuffer, sizeof(Int32) + filenamelen, f.Content, 0, f.Content.Length); packet.Data = f; break; case NetPacketType.COMPLEX: NetObject no = new NetObject(); int typenamelen = BitConverter.ToInt32(packetBuffer, 0);//文件名长度 no.TypeName = NetPacket.encoding.GetString(packetBuffer, sizeof(Int32), typenamelen); byte[] Content = new Byte[packetBuffer.Length - sizeof(Int32) - typenamelen]; Array.Copy(packetBuffer, sizeof(Int32) + typenamelen, Content, 0, Content.Length); MemoryStream mStream = new MemoryStream(); mStream.Write(Content, 0, Content.Length); mStream.Position = 0; no.gragh = BinarySerializeHelper.DeSerialize(mStream); mStream.Close(); packet.Data = no; break; } return(packet); }
/// <summary> /// 从本地文件得到用户信息 /// </summary> /// <returns></returns> public Models.UserInfo GetUserInfo() { try { return(BinarySerializeHelper.Deserialize <Models.UserInfo>(Paths.UserInfoFile)); } catch { return(null); } }
// TODO 序列化的文件是Json文件, static void Main(string[] args) { BaseClass ba = new BaseClass(); SerTest st2 = new SerTest(1000, 5000f, 1000f, 1000f); string path = "D:\\Desktop\\1.bin"; BinarySerializeHelper.InstanceDataToFile(st2, path); SerTest mc = BinarySerializeHelper.FileToInstanceData <SerTest>(path); mc.Print(); MemoryStream stram = BinarySerializeHelper.InstanceDataToMemory(st2); SerTest m0 = BinarySerializeHelper.MemoryToInstanceData <SerTest>(stram, 0); m0.Print(); SoapSerializeHelper.InstanceDataToFile(st2, path); SerTest mc1 = BinarySerializeHelper.FileToInstanceData <SerTest>(path); mc1.Print(); MemoryStream stram1 = BinarySerializeHelper.InstanceDataToMemory(st2); SerTest m01 = BinarySerializeHelper.MemoryToInstanceData <SerTest>(stram1, 0); m01.Print(); /* 测试结果:两种都正常使用*/ /* 测试 集合 */ ClassCollection cc1 = new ClassCollection(); // 第一种 字段全为null MemoryStream temp = BinarySerializeHelper.InstanceDataToMemory(cc1); Console.WriteLine(temp.Length); ClassCollection cc2 = BinarySerializeHelper.MemoryToInstanceData <ClassCollection>(temp, 0); cc2.Print(); Console.WriteLine("---------------------"); // 第二种 正常 List <SerTest> list = new List <SerTest>(); Dictionary <string, SerTest> dict = new Dictionary <string, SerTest>(); Stack <SerTest> stack = new Stack <SerTest>(); Queue <SerTest> queue = new Queue <SerTest>(); list.Add(st2); dict.Add("1", st2); stack.Push(st2); queue.Enqueue(st2); ClassCollection cc3 = new ClassCollection(list, dict, stack, queue); cc3.Myfloat = 0.9f; MemoryStream temp2 = BinarySerializeHelper.InstanceDataToMemory(cc3); Console.WriteLine("**"); Console.WriteLine(temp2.Length); ClassCollection cc4 = BinarySerializeHelper.MemoryToInstanceData <ClassCollection>(temp2, 0); cc4.PrintDetail(); Console.WriteLine(cc4.x); Console.WriteLine(cc4.Myfloat); Console.ReadLine(); }
private static void SaveShortcut() { string path = Path.Combine(Application.StartupPath, STATIC_Shortcuts_Folder, STATIC_Shortcuts_FileName); if (File.Exists(path)) { File.Delete(path); } using (FileStream fileStream = new FileStream(path, FileMode.Create)) { ISerializeHelper se = new BinarySerializeHelper(); se.Serialize <Dictionary <BoxGroup, List <BoxFile> > >(fileStream, STATIC_Shortcuts); } }
public static T Hash_GetBase64 <T>(string key, string dataKey) { using (IRedisClient redis = _prcm.GetClient()) { var value = redis.GetValueFromHash(key, dataKey); if (string.IsNullOrWhiteSpace(value)) { return(default(T)); } var b = Convert.FromBase64String(value); var obj = BinarySerializeHelper.DeserializeObject2(b); return((T)obj); } }
//测试方法 // public Task Execute(IJobExecutionContext context) // { // Console.WriteLine("微信推送"); // // #region 测试 // var stockSignalSingles = MongoService.GetAllStockSignalSingle(); // var model1 = stockSignalSingles.FirstOrDefault(); // var model2 = stockSignalSingles.Last(); // List<stock_signal_single> list = new List<stock_signal_single> // { // model1,model2 // }; // DirectExchangeSendMsg(list); // #endregion // // // return Task.FromResult(0); // } public static void DirectExchangeSendMsg(List <stock_signal_single> signalNowList) { using (IConnection conn = RabbitMqFactory.CreateConnection()) { using (IModel channel = conn.CreateModel()) { channel.ExchangeDeclare(ExchangeName, "direct", durable: true, autoDelete: false, arguments: null); channel.QueueDeclare(QueueName, durable: true, autoDelete: false, exclusive: false, arguments: null); channel.QueueBind(QueueName, ExchangeName, routingKey: "signalList"); var props = channel.CreateBasicProperties(); props.Persistent = true; var listToJson = JsonConvert.SerializeObject(signalNowList); var msgBody = BinarySerializeHelper.SerializeObject(listToJson); channel.BasicPublish(exchange: ExchangeName, routingKey: "signalList", basicProperties: props, body: msgBody); } } }
private static void LoadLikeShortcut() { if (STATIC_LikeShortcuts.Count == 0) { string path = Path.Combine(Application.StartupPath, STATIC_Shortcuts_Folder, STATIC_LikeShortcuts_FileName); if (File.Exists(path)) { using (Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { ISerializeHelper se = new BinarySerializeHelper(); STATIC_LikeShortcuts = se.DeSerialize <List <BoxFile> >(stream); } } if (STATIC_LikeShortcuts == null || STATIC_LikeShortcuts.Count == 0) { STATIC_LikeShortcuts = new List <BoxFile>(); } } }
public static void DirectExchangeSendMsg() { using (IConnection conn = RabbitMqFactory.CreateConnection()) { using (IModel channel = conn.CreateModel()) { channel.ExchangeDeclare(ExchangeName, "direct", durable: true, autoDelete: false, arguments: null); channel.QueueDeclare(QueueName, durable: true, autoDelete: false, exclusive: false, arguments: null); channel.QueueBind(QueueName, ExchangeName, routingKey: "key1"); // channel.QueueDeclare(QueueName2, durable: true, autoDelete: false, exclusive: false, arguments: null); // channel.QueueBind(QueueName2, ExchangeName, routingKey: "key2"); var props = channel.CreateBasicProperties(); props.Persistent = true; var chgModel = Service.GetChgData(); var msgBody = BinarySerializeHelper.SerializeObject(chgModel); // var msgBody = Encoding.UTF8.GetBytes(bytes); channel.BasicPublish(exchange: ExchangeName, routingKey: "key1", basicProperties: props, body: msgBody); } } }
public static byte[] MakeObjectPacket(string type, object graph) { if (graph == null) { throw (new Exception("NetPacket打包的对象不存在!")); } if (!graph.GetType().IsSerializable) { throw (new Exception("NetPacket打包的对象不可序列化!")); } Byte[] typename = encoding.GetBytes(type); MemoryStream m = new MemoryStream(); BinarySerializeHelper.Serialize(m, graph); m.Position = 0; Byte[] content = new byte[m.Length + sizeof(Int32) + typename.Length]; Array.Copy(BitConverter.GetBytes(typename.Length), 0, content, 0, sizeof(Int32)); //把"文件名长度(4字节)"放入数组 Array.Copy(typename, 0, content, sizeof(Int32), typename.Length); //把"文件名字节数组"放入数组 m.Read(content, sizeof(Int32) + typename.Length, (Int32)m.Length); return(MakePacket(NetPacketType.COMPLEX, content)); }
private static void LoadShortcut() { if (STATIC_Shortcuts.Count == 0) { string path = Path.Combine(Application.StartupPath, STATIC_Shortcuts_Folder, STATIC_Shortcuts_FileName); if (File.Exists(path)) { using (Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { ISerializeHelper se = new BinarySerializeHelper(); STATIC_Shortcuts = se.DeSerialize <Dictionary <BoxGroup, List <BoxFile> > >(stream); } } if (STATIC_Shortcuts == null || STATIC_Shortcuts.Count == 0) { STATIC_Shortcuts = new Dictionary <BoxGroup, List <BoxFile> >(); STATIC_Shortcuts.Add(new BoxGroup() { Key = getUniqueKey(STATIC_GroupName), Name = STATIC_GroupName }, null); } } }
/// <summary> /// 请求处理最后的内容 /// </summary> protected override void ProcessFinalResponse() { OnPreContentProcessed(); base.ProcessFinalResponse(); //查找开始标记 var index = CheckUtf8Bom() ? 3 : 0; while ((index < Result.Length && (Result[index] == ' ' || Result[index] == '\t' || Result[index] == '\r' || Result[index] == '\n'))) { index++; } if (index >= Result.Length) { Object = default(T); return; } var isJobject = typeof(T) == typeof(JObject) || typeof(T) == typeof(object); try { if (Result[index] == '<') { //XML反序列化 Object = (T)typeof(T).XmlDeserialize(Utils.RemoveXmlDeclaration(Utils.NormalizeString(StringResult))); ContentType = ResponseContentType.Xml; } else if (Result[index] == '{' || Result[index] == '[') { ContentType = ResponseContentType.Json; if (isJobject) { Object = (T)(object)JObject.Parse(StringResult); } else { //JSON反序列化 Object = Context.JsonDeserialize <T>(StringResult, Object); } } else { //根据目标结果的类型判断 var jsonp = string.Empty; if (!IsBinaryContent() && !string.IsNullOrEmpty(jsonp = GetJsonPContent(StringResult))) { //尝试找到JSONP ContentType = ResponseContentType.JsonP; if (isJobject) { Object = (T)(object)JObject.Parse(jsonp); } else { //JSON反序列化 Object = Context.JsonDeserialize <T>(jsonp, Object); } } else { //二进制序列化 Object = (T)BinarySerializeHelper.DeserialzieFromBytes(Result); ContentType = ResponseContentType.Binary; } } } catch (Exception ex) { if (ex is InvalidOperationException) { ex = new ObjectSerializationNotSupportException(typeof(T), ex); } Exception = ex; Object = default(T); if (AsyncData == null) { throw; } AsyncData.Exception = ex; } OnPostContentProcessed(); }