我们继续讲解LINQ to SQL语句,这篇我们来讨论Group By/Having操作符和Exists/In/Any/All/Contains操作符。 Group By/Having操作符 适用场景:分组数据,为我们查找数据缩小范围。 说明:分配并返回对传入参数进行分组操作后的可枚举对象。分组;延迟 1.简单形式:
1 2 3 4 |
var q = from p in db.Products group p by p.CategoryID into g select g; |
语句描述:使用Group By按CategoryID划分产品。 说明:from p in db.Products 表示从表中将产品对象取出来。group p by p.CategoryID into g表示对p按CategoryID字段归类。其结果命名为g,一旦重新命名,p的作用域就结束了,所以,最后select时,只能select g。当然,也不必重新命名可以这样写:
1 2 3 |
var q = from p in db.Products group p by p.CategoryID; |
我们用示意图表示: 如果想遍历某类别中所有记录,这样:
1 2 3 4 5 6 7 8 9 10 |
foreach (var gp in q) { if (gp.Key == 2) { foreach (var item in gp) { //do something } } } |
2.Select匿名类:
1 2 3 4 |
var q = from p in db.Products group p by p.CategoryID into g select new { CategoryID = g.Key, g }; |
说明:在这句LINQ语句中,有2个property:CategoryID和g。这个匿名类,其实质是对返回结果集重新进行了包装。把g的property封装成一个完整的分组。如下图所示: 如果想遍历某匿名类中所有记录,要这么做:
1 2 3 4 5 6 7 8 9 10 |
foreach (var gp in q) { if (gp.CategoryID == 2) { foreach (var item in gp.g) { //do something } } } |
3.最大值
1 2 3 4 5 6 7 |
var q = from p in db.Products group p by p.CategoryID into g select new { g.Key, MaxPrice = g.Max(p => p.UnitPrice) }; |
语句描述:使用Group By和Max查找每个CategoryID的最高单价。 说明:先按CategoryID归类,判断各个分类产品中单价最大的Products。取出CategoryID值,并把UnitPrice值赋给MaxPrice。 4.最小值
1 2 3 4 5 6 7 |
var q = from p in db.Products group p by p.CategoryID into g select new { g.Key, MinPrice = g.Min(p => p.UnitPrice) }; |
语句描述:使用Group By和Min查找每个CategoryID的最低单价。 说明:先按CategoryID归类,判断各个分类产品中单价最小的Products。取出CategoryID值,并把UnitPrice值赋给MinPrice。 5.平均值
1 2 3 4 5 6 7 |
var q = from p in db.Products group p by p.CategoryID into g select new { g.Key, AveragePrice = g.Average(p => p.UnitPrice) }; |
语句描述:使用Group By和Average得到每个CategoryID的平均单价。 说明:先按CategoryID归类,取出CategoryID值和各个分类产品中单价的平均值。 6.求和
1 2 3 4 5 6 7 |
var q = from p in db.Products group p by p.CategoryID into g select new { g.Key, TotalPrice = g.Sum(p => p.UnitPrice) }; |
语句描述:使用Group By和Sum得到每个CategoryID 的单价总计。 说明:先按CategoryID归类,取出CategoryID值和各个分类产品中单价的总和。 7.计数
1 2 3 4 5 6 7 |
var q = from p in db.Products group p by p.CategoryID into g select new { g.Key, NumProducts = g.Count() }; |
语句描述:使用Group By和Count得到每个CategoryID中产品的数量。 说明:先按CategoryID归类,取出CategoryID值和各个分类产品的数量。 8.带条件计数
1 2 3 4 5 6 7 |
var q = from p in db.Products group p by p.CategoryID into g select new { g.Key, NumProducts = g.Count(p => p.Discontinued) }; |
语句描述:使用Group By和Count得到每个CategoryID中断货产品的数量。 说明:先按CategoryID归类,取出CategoryID值和各个分类产品的断货数量。 Count函数里,使用了Lambda表达式,Lambda表达式中的p,代表这个组里的一个元素或对象,即某一个产品。 9.Where限制
1 2 3 4 5 6 7 8 |
var q = from p in db.Products group p by p.CategoryID into g where g.Count() >= 10 select new { g.Key, ProductCount = g.Count() }; |
语句描述:根据产品的―ID分组,查询产品数量大于10的ID和产品数量。这个示例在Group By子句后使用Where子句查找所有至少有10种产品的类别。 说明:在翻译成SQL语句时,在最外层嵌套了Where条件。 10.多列(Multiple Columns)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var categories = from p in db.Products group p by new { p.CategoryID, p.SupplierID } into g select new { g.Key, g }; |
语句描述:使用Group By按CategoryID和SupplierID将产品分组。 说明: 既按产品的分类,又按供应商分类。在by后面,new出来一个匿名类。这里,Key其实质是一个类的对象,Key包含两个Property:CategoryID、SupplierID。用g.Key.CategoryID可以遍历CategoryID的值。 11.表达式(Expression)
1 2 3 4 |
var categories = from p in db.Products group p by new { Criterion = p.UnitPrice > 10 } into g select g; |
语句描述:使用Group By返回两个产品序列。第一个序列包含单价大于10的产品。第二个序列包含单价小于或等于10的产品。 说明:按产品单价是否大于10分类。其结果分为两类,大于的是一类,小于及等于为另一类。 Exists/In/Any/All/Contains操作符 适用场景:用于判断集合中元素,进一步缩小范围。 Any 说明:用于判断集合中是否有元素满足某一条件;不延迟。(若条件为空,则集合只要不为空就返回True,否则为False)。有2种形式,分别为简单形式和带条件形式。 1.简单形式: 仅返回没有订单的客户:
1 2 3 4 |
var q = from c in db.Customers where !c.Orders.Any() select c; |
[…]
View DetailsWhat are attributes and why do we need it? How can we create custom Attributes? Is it possible to restrict a custom attribute to a method only? Other than information what more can we do? Do attributes get inherited ? What if we want some attributes to be prevented from inheriting? If I want an attribute to be used only once in a program? What are attributes and why do we need it? “Attribute is nothing but a piece of information”. This information can be attached to your […]
View Details如何在ASP.NET中用C#将XML转换成JSON 本文旨在介绍如果通过C#将获取到的XML文档转换成对应的JSON格式字符串,然后将其输出到页面前端,以供JavaScript代码解析使用。或许你可以直接利用JavaScript代码通过Ajax的方式来读取XML,然后直接对其中的内容进行解析,这样或许更直接一些。但本文中给出的代码旨在说明如何通过原生的C#代码来完成这一转换。除此之外,你仍然可以借用一些第三方类库或者更高级一些的.NET库对象来实施转换。我们来看看这里介绍的一些较为简单的方法,但前提是你必须拥有可支持的类库和对象以备使用。 使用Json.NET类库 前提是需要首先下载和安装Json.NET类库,在这里可以找到http://json.codeplex.com/ 下面是一个例子: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using Newtonsoft.Json; namespace JSonConverter
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<span style="line-height:1.5 !important;">{ </span><span style="color:#0000FF;line-height:1.5 !important;">class</span><span style="line-height:1.5 !important;"> Program { </span><span style="color:#0000FF;line-height:1.5 !important;">static</span> <span style="color:#0000FF;line-height:1.5 !important;">void</span> Main(<span style="color:#0000FF;line-height:1.5 !important;">string</span><span style="line-height:1.5 !important;">[] args) { </span><span style="color:#0000FF;line-height:1.5 !important;">string</span> xml = <span style="color:#800000;line-height:1.5 !important;">"</span><span style="color:#800000;line-height:1.5 !important;"><Test><Name>Test class</Name><X>100</X><Y>200</Y></Test></span><span style="color:#800000;line-height:1.5 !important;">"</span><span style="line-height:1.5 !important;">; XmlDocument doc </span>= <span style="color:#0000FF;line-height:1.5 !important;">new</span><span style="line-height:1.5 !important;"> XmlDocument(); doc.LoadXml(xml); </span><span style="color:#0000FF;line-height:1.5 !important;">string</span> json =<span style="line-height:1.5 !important;"> Newtonsoft.Json.JsonConvert.SerializeXmlNode(doc); Console.WriteLine(</span><span style="color:#800000;line-height:1.5 !important;">"</span><span style="color:#800000;line-height:1.5 !important;">XML -> JSON: {0}</span><span style="color:#800000;line-height:1.5 !important;">"</span><span style="line-height:1.5 !important;">, json); Console.ReadLine(); } } }</span> |
使用.NET Framework中的JavaScriptSerializer类 首先需要确保你的工程或服务器支持.NET 4.0或以上版本的Framework,否则无法找到该类。 下面是一个例子: using System; using System.Linq; using System.Web.Script.Serialization; using System.Xml.Linq; class Program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<span style="line-height:1.5 !important;">{ </span><span style="color:#0000FF;line-height:1.5 !important;">static</span> <span style="color:#0000FF;line-height:1.5 !important;">void</span><span style="line-height:1.5 !important;"> Main() { </span><span style="color:#0000FF;line-height:1.5 !important;">var</span> xml = <span style="color:#800000;line-height:1.5 !important;">@"</span><span style="color:#800000;line-height:1.5 !important;"><Columns> <Column Name=""key1"" DataType=""Boolean"">True</Column> <Column Name=""key2"" DataType=""String"">Hello World</Column> <Column Name=""key3"" DataType=""Integer"">999</Column> </Columns></span><span style="color:#800000;line-height:1.5 !important;">"</span><span style="line-height:1.5 !important;">; </span><span style="color:#0000FF;line-height:1.5 !important;">var</span> dic =<span style="line-height:1.5 !important;"> XDocument .Parse(xml) .Descendants(</span><span style="color:#800000;line-height:1.5 !important;">"</span><span style="color:#800000;line-height:1.5 !important;">Column</span><span style="color:#800000;line-height:1.5 !important;">"</span><span style="line-height:1.5 !important;">) .ToDictionary( c </span>=> c.Attribute(<span style="color:#800000;line-height:1.5 !important;">"</span><span style="color:#800000;line-height:1.5 !important;">Name</span><span style="color:#800000;line-height:1.5 !important;">"</span><span style="line-height:1.5 !important;">).Value, c </span>=><span style="line-height:1.5 !important;"> c.Value ); </span><span style="color:#0000FF;line-height:1.5 !important;">var</span> json = <span style="color:#0000FF;line-height:1.5 !important;">new</span><span style="line-height:1.5 !important;"> JavaScriptSerializer().Serialize(dic); Console.WriteLine(json); } }</span> |
其输出结果为:{"key1":"True","key2":"Hello World","key3":"999"} 可能还会有更多的方法,这里不一一列出了。那么如何使用原生的C#代码将XML转换成JSON格式字符串呢?或者说该C#代码在较低版本的.NET Framework中也可以运行呢?来看看下面的介绍吧。 Introduction JSON是一个轻量级的数据交换格式,它可以非常容易地被页面的JavaScript编码为对象的形式,从而方便数据操作。 基于AJAX的页面使用XmlHttpRequest对象从服务端接收数据来响应用户的请求,当返回的数据是XML格式时,它可以被转换为JSON格式的字符串从而通过JavaScript更加容易地对数据进行处理。 许多应用程序都将数据存储为XML的格式,而且会将数据以JSON的格式发送到客户端以做进一步处理。要实现这一点,它们必须将XML格式转换为JSON格式。下面的ASP.NET C#代码实现了这一过程。 Code Description 代码中提供了一个方法XmlToJSON,可以用来将XmlDocument对象转换为JSON字符串。代码通过迭代每一个XML节点、属性以及子节点,来创建对应的JSON对象。 代码不会生成数字和布尔类型的值 Xml DocumentElement对象始终会被转换为JSON对象的member:object,它遵循下面这些规则。 节点的属性会被对应地转换为JSON对象的成员"attr_name":"attr_value"。如: XML JSON <xx yy=’nn'></xx> { "xx" : { "yy" : "nn" } } <xx yy="></xx> { "xx" : { "yy" : "" } } 没有子节点、属性和内容的节点被转换为成员"child_name":null XML JSON <xx/> { "xx" : null } 没有子节点和属性,但是有内容的节点被转换为成员"child_name":"child_text" XML JSON […]
View Details一、XML和JSON字符串的对应表格 1、节点的属性会被对应地转换为JSON对象的成员"attr_name":"attr_value"。如: XML JSON <xx yy=’nn'></xx> { "xx" : { "yy" : "nn" } } <xx yy="></xx> { "xx" : { "yy" : "" } } 2、没有子节点、属性和内容的节点被转换为成员"child_name":null XML JSON <xx/> { "xx" : null } 3、没有子节点和属性,但是有内容的节点被转换为成员"child_name":"child_text" XML JSON <xx>yyy</xx> { "xx" : "yyy" } 4、其它节点和属性会被适当地转换为"child_name":对象或者"child_name":[elements]对象数组,节点的值会被转换为对象成员的"value",如: XML JSON <xx yy=’nn'><mm>zzz</mm></xx> { "xx" : { "yy" : "nn", "mm" : "zzz" } } <xx yy=’nn'><mm>zzz</mm><mm>aaa</mm></xx> { "xx" : { "yy" : "nn", "mm" : [ "zzz", "aaa" ] } } <xx><mm>zzz</mm>some text</xx> […]
View Details
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 |
//------------------------------------------------------------------------------ // <copyright file="CryptoUtil.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.Security.Cryptography { using System; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; using System.Web.Util; // Contains helper methods for dealing with cryptographic operations. internal static class CryptoUtil { /// <summary> /// Similar to Encoding.UTF8, but throws on invalid bytes. Useful for security routines where we need /// strong guarantees that we're always producing valid UTF8 streams. /// </summary> public static readonly UTF8Encoding SecureUTF8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); /// <summary> /// Converts a byte array into its hexadecimal representation. /// </summary> /// <param name="data">The binary byte array.</param> /// <returns>The hexadecimal (uppercase) equivalent of the byte array.</returns> public static string BinaryToHex(byte[] data) { if (data == null) { return null; } char[] hex = new char[checked(data.Length * 2)]; for (int i = 0; i < data.Length; i++) { byte thisByte = data[i]; hex[2 * i] = NibbleToHex((byte)(thisByte >> 4)); // high nibble hex[2 * i + 1] = NibbleToHex((byte)(thisByte & 0xf)); // low nibble } return new string(hex); } // Determines if two buffer instances are equal, e.g. whether they contain the same payload. This method // is written in such a manner that it should take the same amount of time to execute regardless of // whether the result is success or failure. The modulus operation is intended to make the check take the // same amount of time, even if the buffers are of different lengths. // // !! DO NOT CHANGE THIS METHOD WITHOUT SECURITY [MethodImpl(MethodImplOptions.NoOptimization)] public static bool BuffersAreEqual(byte[] buffer1, int buffer1Offset, int buffer1Count, byte[] buffer2, int buffer2Offset, int buffer2Count) { Debug.ValidateArrayBounds(buffer1, buffer1Offset, buffer1Count); Debug.ValidateArrayBounds(buffer2, buffer2Offset, buffer2Count); bool success = (buffer1Count == buffer2Count); // can't possibly be successful if the buffers are of different lengths for (int i = 0; i < buffer1Count; i++) { success &= (buffer1[buffer1Offset + i] == buffer2[buffer2Offset + (i % buffer2Count)]); } return success; } /// <summary> /// Computes the SHA256 hash of a given input. /// </summary> /// <param name="input">The input over which to compute the hash.</param> /// <returns>The binary hash (32 bytes) of the input.</returns> public static byte[] ComputeSHA256Hash(byte[] input) { return ComputeSHA256Hash(input, 0, input.Length); } /// <summary> /// Computes the SHA256 hash of a given segment in a buffer. /// </summary> /// <param name="buffer">The buffer over which to compute the hash.</param> /// <param name="offset">The offset at which to begin computing the hash.</param> /// <param name="count">The number of bytes in the buffer to include in the hash.</param> /// <returns>The binary hash (32 bytes) of the buffer segment.</returns> public static byte[] ComputeSHA256Hash(byte[] buffer, int offset, int count) { Debug.ValidateArrayBounds(buffer, offset, count); using (SHA256 sha256 = CryptoAlgorithms.CreateSHA256()) { return sha256.ComputeHash(buffer, offset, count); } } /// <summary> /// Returns an IV that's based solely on the contents of a buffer; useful for generating /// predictable IVs for ciphertexts that need to be cached. The output value is only /// appropriate for use as an IV and must not be used for any other purpose. /// </summary> /// <remarks>This method uses an iterated unkeyed SHA256 to calculate the IV.</remarks> /// <param name="buffer">The input buffer over which to calculate the IV.</param> /// <param name="ivBitLength">The requested length (in bits) of the IV to generate.</param> /// <returns>The calculated IV.</returns> public static byte[] CreatePredictableIV(byte[] buffer, int ivBitLength) { // Algorithm: // T_0 = SHA256(buffer) // T_n = SHA256(T_{n-1}) // output = T_0 || T_1 || ... || T_n (as many blocks as necessary to reach ivBitLength) byte[] output = new byte[ivBitLength / 8]; int bytesCopied = 0; int bytesRemaining = output.Length; using (SHA256 sha256 = CryptoAlgorithms.CreateSHA256()) { while (bytesRemaining > 0) { byte[] hashed = sha256.ComputeHash(buffer); int bytesToCopy = Math.Min(bytesRemaining, hashed.Length); Buffer.BlockCopy(hashed, 0, output, bytesCopied, bytesToCopy); bytesCopied += bytesToCopy; bytesRemaining -= bytesToCopy; buffer = hashed; // next iteration (if it occurs) will operate over the block just hashed } } return output; } /// <summary> /// Converts a hexadecimal string into its binary representation. /// </summary> /// <param name="data">The hex string.</param> /// <returns>The byte array corresponding to the contents of the hex string, /// or null if the input string is not a valid hex string.</returns> public static byte[] HexToBinary(string data) { if (data == null || data.Length % 2 != 0) { // input string length is not evenly divisible by 2 return null; } byte[] binary = new byte[data.Length / 2]; for (int i = 0; i < binary.Length; i++) { int highNibble = HttpEncoderUtility.HexToInt(data[2 * i]); int lowNibble = HttpEncoderUtility.HexToInt(data[2 * i + 1]); if (highNibble == -1 || lowNibble == -1) { return null; // bad hex data } binary[i] = (byte)((highNibble << 4) | lowNibble); } return binary; } // converts a nibble (4 bits) to its uppercase hexadecimal character representation [0-9, A-F] private static char NibbleToHex(byte nibble) { return (char)((nibble < 10) ? (nibble + '0') : (nibble - 10 + 'A')); } } } |
前两天在VS2008下做个项目,用到了excel组件没有问题,但当把该项目在IIS下配置后,用浏览器浏览结果则不正确,网上说用dcom组件配置下,可是我按照要求配了,结果还是不对。 后来找到一个方法好用了。 Web.config中加了一句话:“<identity impersonate="true" userName="操作系统用户" password="用户密码"/>”,浏览…,结果正确,后来我就在网上查了下这句话的作用,MSDN是这样说的: 1、模拟 IIS 验证的帐户或用户 若要在收到 ASP.NET 应用程序中每个页的每个请求时模拟 Microsoft Internet 信息服务 (IIS) 身份验证用户,必须在此应用程序的 Web.config 文件中包含 <identity> 标记,并将 impersonate 属性设置为 true 2、为 ASP.NET 应用程序的所有请求模拟特定用户 若要为 ASP.NET 应用程序的所有页面上的所有请求模拟特定用户,可以在该应用程序的 Web.config 文件的 <identity> 标记中指定 userName 和 password 属性。例如: <identity impersonate="true" userName="accountname" password="password" /> from:http://blog.csdn.net/lazyleland/article/details/7726528
View Details
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 |
#region 排序方法 #region 冒泡排序法 /// <summary> /// 冒泡排序法 /// </summary> /// <param name="list">数据列表</param> /// <param name="SortType">排序类型,选择是升序还是降序</param> public static void BubbleSort(int[] list, string SortType) { int j, temp; j = 1; while ((j < list.Length)) { for (int i = 0; i < list.Length - j; i++) { bool Bl; if (SortType == "asc") { Bl = list[i] > list[i + 1]; } else if (SortType == "desc") { Bl = list[i] < list[i + 1]; } else { Bl = false; } if (Bl) { temp = list[i]; list[i] = list[i + 1]; list[i + 1] = temp; } } j++; } } #endregion 冒泡排序法 #region 选择排序法 /// <summary> /// 选择排序法 /// </summary> /// <param name="list">数据列表</param> public static void ChoiceSort(int[] list) { int min; for (int i = 0; i < list.Length - 1; i++) { min = i; for (int j = i + 1; j < list.Length; j++) { if (list[j] < list[min]) min = j; } int t = list[min]; list[min] = list[i]; list[i] = t; } } #endregion 选择排序法 #region 插入排序法 /// <summary> /// 插入排序法 /// </summary> /// <param name="list">数据列表</param> public static void InsertSort(int[] list) { for (int i = 1; i < list.Length; i++) { int t = list[i]; int j = i; while ((j > 0) && (list[j - 1] < t)) { list[j] = list[j - 1]; --j; } list[j] = t; } } #endregion 插入排序法 #region 希尔排序法 /// <summary> /// 希尔排序法 /// </summary> /// <param name="list">数据列表</param> public static void ShellSort(int[] list) { int inc; for (inc = 1; inc <= list.Length / 9; inc = 3 * inc + 1) ; for (; inc > 0; inc /= 3) { for (int i = inc + 1; i <= list.Length; i += inc) { int t = list[i - 1]; int j = i; while ((j > inc) && (list[j - inc - 1] > t)) { list[j - 1] = list[j - inc - 1]; j -= inc; } list[j - 1] = t; } } } #endregion 希尔排序法 #endregion 排序方法 |
移动端越来越火了,我们在开发过程中,总会碰到要和移动端打交道的场景,比如.NET和android或者iOS的打交道。为了让数据交互更安全,我们需要对数据进行加密传输。今天研究了一下,把几种语言的加密都实践了一遍,实现了.NET,java(android),iOS都同一套的加密算法,下面就分享给大家。 AES加密有多种算法模式,下面提供两套模式的可用源码。 加密方式: 先将文本AES加密 返回Base64转码 解密方式: 将数据进行Base64解码 进行AES解密 一、CBC(Cipher Block Chaining,加密块链)模式 是一种循环模式,前一个分组的密文和当前分组的明文异或操作后再加密,这样做的目的是增强破解难度. 密钥 密钥偏移量 java/adroid加密AESOperator类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 |
package com.bci.wx.base.util; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; /** * AES 是一种可逆加密算法,对用户的敏感信息加密处理 对原始数据进行AES加密后,在进行Base64编码转化; */ public class AESOperator { /* * 加密用的Key 可以用26个字母和数字组成 此处使用AES-128-CBC加密模式,key需要为16位。 */ private String sKey = "smkldospdosldaaa";//key,可自行修改 private String ivParameter = "0392039203920300";//偏移量,可自行修改 private static AESOperator instance = null; private AESOperator() { } public static AESOperator getInstance() { if (instance == null) instance = new AESOperator(); return instance; } public static String Encrypt(String encData ,String secretKey,String vector) throws Exception { if(secretKey == null) { return null; } if(secretKey.length() != 16) { return null; } Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); byte[] raw = secretKey.getBytes(); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); IvParameterSpec iv = new IvParameterSpec(vector.getBytes());// 使用CBC模式,需要一个向量iv,可增加加密算法的强度 cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encrypted = cipher.doFinal(encData.getBytes("utf-8")); return new BASE64Encoder().encode(encrypted);// 此处使用BASE64做转码。 } // 加密 public String encrypt(String sSrc) throws Exception { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); byte[] raw = sKey.getBytes(); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());// 使用CBC模式,需要一个向量iv,可增加加密算法的强度 cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8")); return new BASE64Encoder().encode(encrypted);// 此处使用BASE64做转码。 } // 解密 public String decrypt(String sSrc) throws Exception { try { byte[] raw = sKey.getBytes("ASCII"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes()); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);// 先用base64解密 byte[] original = cipher.doFinal(encrypted1); String originalString = new String(original, "utf-8"); return originalString; } catch (Exception ex) { return null; } } public String decrypt(String sSrc,String key,String ivs) throws Exception { try { byte[] raw = key.getBytes("ASCII"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec iv = new IvParameterSpec(ivs.getBytes()); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);// 先用base64解密 byte[] original = cipher.doFinal(encrypted1); String originalString = new String(original, "utf-8"); return originalString; } catch (Exception ex) { return null; } } public static String encodeBytes(byte[] bytes) { StringBuffer strBuf = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a'))); strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a'))); } return strBuf.toString(); } public static void main(String[] args) throws Exception { // 需要加密的字串 String cSrc = "[{\"request_no\":\"1001\",\"service_code\":\"FS0001\",\"contract_id\":\"100002\",\"order_id\":\"0\",\"phone_id\":\"13913996922\",\"plat_offer_id\":\"100094\",\"channel_id\":\"1\",\"activity_id\":\"100045\"}]"; // 加密 long lStart = System.currentTimeMillis(); String enString = AESOperator.getInstance().encrypt(cSrc); System.out.println("加密后的字串是:" + enString); long lUseTime = System.currentTimeMillis() - lStart; System.out.println("加密耗时:" + lUseTime + "毫秒"); // 解密 lStart = System.currentTimeMillis(); String DeString = AESOperator.getInstance().decrypt(enString); System.out.println("解密后的字串是:" + DeString); lUseTime = System.currentTimeMillis() - lStart; System.out.println("解密耗时:" + lUseTime + "毫秒"); } } |
.NET AES加密解密:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
using System; using System.Security.Cryptography; using System.Text; namespace AESDome { class Program { private static string key = "smkldospdosldaaa"; //key,可自行修改 private static string iv = "0392039203920300"; //偏移量,可自行修改 static void Main(string[] args) { string encrytpData = Encrypt("abc", key, iv); Console.WriteLine(encrytpData); string decryptData = Decrypt("5z9WEequVr7qtd+WoxV+Kw==", key, iv); Console.WriteLine(decryptData); Console.ReadLine(); } public static string Encrypt(string toEncrypt, string key, string iv) { byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv); byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt); RijndaelManaged rDel = new RijndaelManaged(); rDel.BlockSize = 128; rDel.KeySize = 256; rDel.FeedbackSize = 128; rDel.Padding = PaddingMode.PKCS7; rDel.Key = keyArray; rDel.IV = ivArray; rDel.Mode = CipherMode.CBC; ICryptoTransform cTransform = rDel.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Convert.ToBase64String(resultArray, 0, resultArray.Length); } public static string Decrypt(string toDecrypt, string key, string iv) { byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv); byte[] toEncryptArray = Convert.FromBase64String(toDecrypt); // 这里的模式,请保持和上面加密的一样。但源代码里,这个地方并没有修正,虽然也能正确解密。看到博客的朋友,请自行修改。 // 这是个人疏忽的地址,感谢@jojoka 的提醒。 RijndaelManaged rDel = new RijndaelManaged(); rDel.Key = keyArray; rDel.IV = ivArray; rDel.Mode = CipherMode.CBC; rDel.Padding = PaddingMode.Zeros; rDel.BlockSize = 128; rDel.KeySize = 256; rDel.FeedbackSize = 128; rDel.Padding = PaddingMode.PKCS7; rDel.Key = keyArray; rDel.IV = ivArray; rDel.Mode = CipherMode.CBC; ICryptoTransform cTransform = rDel.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return UTF8Encoding.UTF8.GetString(resultArray); } } } |
iOS源码,请下载源码,源码里有包含。 java,.net,iOS,android通用AES加密解密源码:AES_CBC_ECB_android_java_ios_net通用模式 二、ECB(Electronic Code Book,电子密码本)模式 是一种基础的加密方式,密文被分割成分组长度相等的块(不足补齐),然后单独一个个加密,一个个输出组成密文。 只需要提供密码即可。 iOS,android,java已调通源码:AES_CBC_ECB_android_java_ios_net通用模式 AES在线加解密验证工具: http://www.seacha.com/tools/aes.html from:http://www.cnblogs.com/jys509/p/4768120.html
View Details本文目录 1.窗口的外观 2.窗口的位置 3.窗口的大小 4.窗口的可见性和状态 5.窗口的生命周期 1.窗口的外观 WPF中默认窗口框架的外观,主要取决于Icon、Title、WindowsStyle、ResizeMode等属性。 Icon 指定窗口的图标; Title 指定窗口的标题; WindowStyle 指定窗口样式,有4个取值: None,无边框;(当ResizeMode属性为NoResize时,仅剩下窗口核心。) SingleBorderWindow,单边框【默认】; ThreeDBorderWindow,3D边框; ToolBorderWindow,工具箱窗口; ResizeMode 是指定大小调节样式,有4个取值: NoResize,不可调节,同时没有最大最小按钮; CanMinimize,不可调节。但可以最小化;(此时最大化按钮不可用) CanResize,可调节【默认】; CanResizeWithGrid,可根据网格调节;(窗口右下脚显示可调节网格) 2.窗口的位置 WindowStartLocation 指定窗口初始位置,有3个取值: Manual,手工指定位置,表示可以通过设置其Top、Left属性值来决定窗口的初始位置; CenterScreen,屏幕中央; CenterOwner,父窗体中央; TopMost 调节窗口的前后顺序,属性值为true时,窗口位于最前。 TopMost值为true的窗口,位于TopMost值为false的窗口之前(如下图记事本与示例窗口); TopMost值都为true的窗口,获得焦点的窗口位于前(如下图QQ与示例窗口)。 3.窗口的大小 Width、Height,分别表示窗口的宽度和高度,称为“尺寸属性”。 MaxWidth、MinWidth、MaxHeight、MinHeight,分别表示窗口最大宽度、最小宽度、最大高度、最小高度。可以通过得到和更改这些属性值,来获取和改变窗口的大小和长宽范围。 ActualWidth、ActualHeight,分别表示窗口的实际宽度和实际高度,称为“实际尺寸属性”。 实际尺寸属性是根据当前窗口大小、最小化时窗口大小和最大化时窗口大小来计算得到的,其值是只读的,也就是说,不能通过改变ActualWidth、ActualHeight的值来更改窗口大小。 SizeToContent,表示窗口大小由内容决定,有4个取值: Manual,手工【默认】; Width,窗体宽度由内容决定; Height,窗体高度由内容决定; WidthAndHeight,窗体大小由内容决定; 如果内容尺寸超过了窗口的最大或最小范围,还是以最大/最小范围为主。如果手工指定了窗口的Width、Height 属性,那么SizeToContent将被忽略。 ReSize,窗口大小的可调整性(第1部分已提到)。 4.窗口的可见性和状态 Visibility,窗口可见性,有4个枚举值: Visiable,可见; Hidden,隐藏; Collapsed,折叠。 虽然窗口类认为Collapsed与Hidden一样,但二者区别在于,Hidden仅仅将元素设为不可见,但是元素在画面上依然占有空间;而Collapsed,在不可视的基础上,能将元素在画面上的占位符清除,元素彻底不影响画面。 Show、Hide,显示窗口和隐藏窗口的两个方法。如果窗口的ShowInTaskbar属性值为true,Hide不但隐藏窗口本身,同时隐藏其在任务栏上的图标。 WindowState,窗口状态属性,有3个枚举值: Normal,正常; Maximized,最大化; Minimized,最小化; RestoreBounds,获取窗口在最小化或最大化之前的大小和位置,有4个枚举值,Top、Left、Width、Height。
1 2 3 4 |
<span style="color:#008000;line-height:1.5 !important;">//</span><span style="color:#008000;line-height:1.5 !important;">输出当前窗口的RestoreBounds值</span><span style="color:#008000;line-height:1.5 !important;"> </span><span style="color:#0000FF;line-height:1.5 !important;">private</span> <span style="color:#0000FF;line-height:1.5 !important;">void</span> button1_Click(<span style="color:#0000FF;line-height:1.5 !important;">object</span> sender, RoutedEventArgs e) { MessageBox.Show(<span style="color:#0000FF;line-height:1.5 !important;">this</span>.RestoreBounds.ToString()); } |
该主窗口的Top:75,Left:75,Width:525,Height:350 只有窗口在Normal状态下移动或调整时,RestoreBounds的值才会改变。于是可以在窗口关闭时将RestoreBounds属性值保存到配置文件,下一次启动程序窗口时,读取上次保存的窗口大小、位置,来初始化窗口,以此实现保存用户配置等功能。MSDN上的例子:http://msdn.microsoft.com/zh-cn/library/system.windows.window.restorebounds.aspx 。但推荐使用config文件来保存配置,更方便。 应用程序窗口在上次关闭处启动 向资源中添加两个变量MainRestoreBounds和MainWindowState,对应类型如图所示,用于保存主窗口的RestoreBounds属性值。 XAML
1 |
<span style="color:#0000FF;line-height:1.5 !important;"><</span><span style="color:#800000;line-height:1.5 !important;">Window </span><span style="color:#FF0000;line-height:1.5 !important;">x:Class</span><span style="color:#0000FF;line-height:1.5 !important;">="WpfApplication1.MainWindow"</span><span style="color:#FF0000;line-height:1.5 !important;"> xmlns</span><span style="color:#0000FF;line-height:1.5 !important;">="http://schemas.microsoft.com/winfx/2006/xaml/presentation"</span><span style="color:#FF0000;line-height:1.5 !important;"> xmlns:x</span><span style="color:#0000FF;line-height:1.5 !important;">="http://schemas.microsoft.com/winfx/2006/xaml"</span><span style="color:#FF0000;line-height:1.5 !important;"> Width</span><span style="color:#0000FF;line-height:1.5 !important;">="360"</span><span style="color:#FF0000;line-height:1.5 !important;"> Height</span><span style="color:#0000FF;line-height:1.5 !important;">="240"</span><span style="color:#FF0000;line-height:1.5 !important;"> Closing</span><span style="color:#0000FF;line-height:1.5 !important;">="Window_Closing"</span><span style="color:#0000FF;line-height:1.5 !important;">></span> <span style="color:#0000FF;line-height:1.5 !important;"></</span><span style="color:#800000;line-height:1.5 !important;">Window</span><span style="color:#0000FF;line-height:1.5 !important;">></span> |
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<span style="color:#0000FF;line-height:1.5 !important;">using</span> System; <span style="color:#0000FF;line-height:1.5 !important;">using</span> System.Collections.Generic; <span style="color:#0000FF;line-height:1.5 !important;">using</span> System.Linq; <span style="color:#0000FF;line-height:1.5 !important;">using</span> System.Text; <span style="color:#0000FF;line-height:1.5 !important;">using</span> System.Windows; <span style="color:#0000FF;line-height:1.5 !important;">using</span> System.Windows.Controls; <span style="color:#0000FF;line-height:1.5 !important;">using</span> System.Windows.Data; <span style="color:#0000FF;line-height:1.5 !important;">using</span> System.Windows.Documents; <span style="color:#0000FF;line-height:1.5 !important;">using</span> System.Windows.Input; <span style="color:#0000FF;line-height:1.5 !important;">using</span> System.Windows.Media; <span style="color:#0000FF;line-height:1.5 !important;">using</span> System.Windows.Media.Imaging; <span style="color:#0000FF;line-height:1.5 !important;">using</span> System.Windows.Navigation; <span style="color:#0000FF;line-height:1.5 !important;">using</span> System.Windows.Shapes; <span style="color:#0000FF;line-height:1.5 !important;">namespace</span> WpfApplication1 { <span style="color:#0000FF;line-height:1.5 !important;">public</span> <span style="color:#0000FF;line-height:1.5 !important;">partial</span> <span style="color:#0000FF;line-height:1.5 !important;">class</span> MainWindow : Window { <span style="color:#0000FF;line-height:1.5 !important;">public</span> MainWindow() { InitializeComponent(); <span style="color:#008000;line-height:1.5 !important;">//</span><span style="color:#008000;line-height:1.5 !important;">读取配置文件</span><span style="color:#008000;line-height:1.5 !important;"> </span> <span style="color:#0000FF;line-height:1.5 !important;">try</span> { <span style="color:#008000;line-height:1.5 !important;">//</span><span style="color:#008000;line-height:1.5 !important;">设置位置、大小</span><span style="color:#008000;line-height:1.5 !important;"> </span> Rect restoreBounds = Properties.Settings.Default.MainRestoreBounds; <span style="color:#0000FF;line-height:1.5 !important;">this</span>.WindowState = WindowState.Normal; <span style="color:#0000FF;line-height:1.5 !important;">this</span>.Left = restoreBounds.Left; <span style="color:#0000FF;line-height:1.5 !important;">this</span>.Top = restoreBounds.Top; <span style="color:#0000FF;line-height:1.5 !important;">this</span>.Width = restoreBounds.Width; <span style="color:#0000FF;line-height:1.5 !important;">this</span>.Height = restoreBounds.Height; <span style="color:#008000;line-height:1.5 !important;">//</span><span style="color:#008000;line-height:1.5 !important;">设置窗口状态</span><span style="color:#008000;line-height:1.5 !important;"> </span> <span style="color:#0000FF;line-height:1.5 !important;">this</span>.WindowState = Properties.Settings.Default.MainWindowState; } <span style="color:#0000FF;line-height:1.5 !important;">catch</span> { } } <span style="color:#0000FF;line-height:1.5 !important;">private</span> <span style="color:#0000FF;line-height:1.5 !important;">void</span> Window_Closing(<span style="color:#0000FF;line-height:1.5 !important;">object</span> sender, System.ComponentModel.CancelEventArgs e) { <span style="color:#008000;line-height:1.5 !important;">//</span><span style="color:#008000;line-height:1.5 !important;">保存当前位置、大小和状态,到配置文件</span><span style="color:#008000;line-height:1.5 !important;"> </span> Properties.Settings.Default.MainRestoreBounds = <span style="color:#0000FF;line-height:1.5 !important;">this</span>.RestoreBounds; Properties.Settings.Default.MainWindowState = <span style="color:#0000FF;line-height:1.5 !important;">this</span>.WindowState; Properties.Settings.Default.Save(); } } } |
5.窗口的生命周期 关于各事件的描述: Initialized:当窗口的FrameworkElement底层初始化时触发,即InitializeComponent方法调用时触发。 LocationChanged:窗口被移动时触发。 Activated:窗口被激活时触发。 Deactivated:窗口处于非激活时(即其他窗口处于激活时)触发。 Loaded:显示窗口之前触发。 ContentRendered:当内容显示的时候触发。 Closing:尝试关闭窗口时触发,可以将参数CancelEventArgs的Cancel的属性设置为true,取消关闭操作。 Closed:在窗口关闭后触发该事件,无法取消。 Unloaded:当关闭窗口并且从可视化树移除后触发。 from:http://www.cnblogs.com/libaoheng/archive/2011/11/18/2253751.html
View Details