在项目中查询时,因数据量大,导致网络传输很慢,这就需要在服务器端查询出的数据进行压缩处理,后传输完了在客户端进行解压处理(此为在Silverlight中压缩与解压); 具体方法如下:
using Newtonsoft.Json; using Telerik.Windows.Zip; ////服务器端对查询出的数据进行压缩处理 public static string CompressString(string str) { string result = string.Empty; try { MemoryStream memoryStream = new MemoryStream(); ZipOutputStream zipOutputStream = new ZipOutputStream(memoryStream, ZipCompression.Default); StreamWriter writer = new StreamWriter(zipOutputStream); writer.Write(str); writer.Flush(); result = Convert.ToBase64String(memoryStream.ToArray()); } catch { } return result; }
如:Common.CompressString(JsonConvert.SerializeObject(b.ToList<Employees>()));服务器端查询出来的 b.ToList<Employees>()数据后,先序列化后通过上面方法CompressString()压缩;压缩后传输到客户端,此Employees为一个实体类。
////客户端进行解压处理 public string UnCompressString(string compressedBase64String) { string result = string.Empty; try { MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(compressedBase64String)); ZipInputStream input = new ZipInputStream(memoryStream); StreamReader reader = new StreamReader(input); result = reader.ReadToEnd(); } catch { } return result; }
如: result_Employees= new QueryableCollectionView(JsonConvert.DeserializeAnonymousType<List<Employees>>(UnCompressString(e.Result),new List<Employees>()));客户端接受数据 时先通过方法UnCompressString()解压数据后反序列化,得到相关实体类Employees的List表;
通过序列化、压缩、解压、反序列化,会发现在处理大批量数据查询时,客户端查询等待时间会缩短几十倍的关系;
值得注意的是,在用WebServices作为服务器查询数据时,当前台页面引用该WebServices时可能丢失实体类的定义说明,故在引用的Reference.cs中需加上该实体类的定义说明,否则客户端解压数据时出问题。