using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace yinLouSys.code
{
	/// <summary>
	/// 基础类：提供一些常用并通用的方法
	/// </summary>
	public class Base
	{
		public Base()
		{
			//
			// TODO: 在此处添加构造函数逻辑
			//
		}

		//对正文部分进行过滤
		public static string ComputeContent(string val)
		{
			string result = "";
			for (int i = 0; i < val.Length; i++)
			{
				switch (val[i])
				{
					case '<':
						result += "&lt;";
						break;
					case '>':
						result += "&gt;";
						break;
					case '\'':
						result += "&rsquo;";
						break;
					case '\n':
						result += "<p>";
						break;
					case ' ':
						result += "&nbsp;";
						break;
					default:
						result += val[i];
						break;
				}
			}
			return result;
		}


        /// <summary>
        /// 字符串解密
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="my">密钥</param>
        /// <returns></returns>
        public static string Decrypt(string str, string my)
        {
            DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();

            byte[] key = Encoding.Unicode.GetBytes(my);

            byte[] data = Convert.FromBase64String(str);

            MemoryStream MStream = new MemoryStream();

            CryptoStream CStream = new CryptoStream(MStream, descsp.CreateDecryptor(key, key), CryptoStreamMode.Write);

            CStream.Write(data, 0, data.Length);

            CStream.FlushFinalBlock();

            return Encoding.Unicode.GetString(MStream.ToArray());
        }

		/// <summary>
		/// 去除HTML字符 
		/// </summary>
		/// <param name="val"></param>
		/// <returns></returns>
		public static string RemoteHtmlStr(string val)
		{
			string result=val;
			string [] htmlStrs={"&lt;","&gt;","&rsquo;","<p>","&nbsp;"};
			for(int i=0;i<htmlStrs.Length;i++)
			{
				result=result.Replace(htmlStrs[i],"");
			}
			return result;
		}

		/// <summary>
		/// 获取加密后的字符串
		/// </summary>
		/// <param name="input">要加密的字符串</param>
		/// <returns></returns>
		public static string StringToMD5Hash(string inpuString)
		{
			MD5CryptoServiceProvider md5=new MD5CryptoServiceProvider();
			byte[] encryptedBytes=md5.ComputeHash(Encoding.ASCII.GetBytes(inpuString));
			StringBuilder sb=new StringBuilder();
			for(int i=0;i<encryptedBytes.Length;i++)
			{
				sb.AppendFormat("{0:x2}",encryptedBytes[i]);
			}

			return sb.ToString();
		}

        /// <summary>全角转半角    
        /// 半角空格32,全角空格12288    
        /// 其他字符半角33~126,其他字符全角65281~65374,相差65248    
        /// </summary>    
        /// <param name="input"></param>    
        /// <returns></returns>    
        public static string SBCToDBC(string input)
        {
            char[] cc = input.ToCharArray();
            for (int i = 0; i < cc.Length; i++)
            {
                if (cc[i] == 12288)
                {
                    // 表示空格    
                    cc[i] = (char)32;
                    continue;
                }
                if (cc[i] > 65280 && cc[i] < 65375)
                {
                    cc[i] = (char)(cc[i] - 65248);
                }

            }
            return new string(cc);
        }

		/// <summary>
		/// 获取验证码
		/// </summary>
		/// <param name="digit">要生成的位数</param>
		/// <returns>返回生成好的验证码(string)</returns>
		public static string getValidateCode(int digit)
		{
			string result="";
			try
			{
				string []element={"0","1","2","3","4","5","6","7","8","9",
									 "a","b","c","d","e","f","g","h","i","j","k","l",
									 "m","n","o","p","q","r","s","t","u","v","w","x","y","z",
									 "A","B","C","D","E","F","G","H","I","J","K","L","M","N",
									 "O","P","Q","R","S","T","U","V","W","X","Y","Z"};
				int count=element.Length;
				Random aa=new Random(System.DateTime.Now.Millisecond);
				for(int i=1;i<=digit;i++)
				{
					int n=(int)Math.Floor(aa.NextDouble()*count);
					result+=element[n];
				}
			}
			catch(Exception e)
			{
				throw e;
			}
			return result;

		}

		/// <summary>
		/// 格式化日期 yyyy=>年  MM=>月  dd=>日
		/// hh=>小时  mm=>分钟  ss=>秒
		/// </summary>
		/// <param name="time">时间字段</param>
		/// <param name="formartStr">格式化字符串</param>
		/// <returns></returns>
		public static string formartDate(DateTime time,string formartStr)
		{
			System.Collections.Hashtable vals=new System.Collections.Hashtable();

			//年
			vals.Add("yyyy",time.Year); 
			//月
			vals.Add("MM",time.Month>9?time.Month.ToString():("0"+time.Month.ToString()));
			//日
			vals.Add("dd",time.Day>9?time.Day.ToString():("0"+time.Day.ToString()));
			//时
			vals.Add("hh",time.Hour>9?time.Hour.ToString():("0"+time.Hour.ToString()));
			//分
			vals.Add("mm",time.Minute>9?time.Minute.ToString():("0"+time.Minute.ToString()));
			//秒
			vals.Add("ss",time.Second>9?time.Second.ToString():("0"+time.Second.ToString()));
			//毫秒
			vals.Add("MS",time.Millisecond<10?"00"+time.Millisecond.ToString():time.Millisecond<100?"0"+time.Millisecond.ToString():time.Millisecond.ToString());


			string[]type={"yyyy","MM","dd","hh","mm","ss","MS"};

			string replaceStr=formartStr;
			for(int i=0;i<type.Length;i++)
			{
				string aa1=vals[type[i]].ToString();
				int bbb=replaceStr.IndexOf(type[i]);
				if(replaceStr.IndexOf(type[i])>-1)
				{
					replaceStr=replaceStr.Replace(type[i].ToString(),vals[type[i]].ToString());
				}

			}

			return replaceStr;			
		} 

		//对日期进行格式化  转换为8为的日期格式
		public static string GetFormatDate(DateTime date)
		{
			string month=(date.Month<10)?"0"+date.Month.ToString():date.Month.ToString();
			string day=(date.Day<10)?"0"+date.Day.ToString():date.Day.ToString();

			return date.Year.ToString()+month.ToString()+day.ToString();
		}

		/// <summary>
		/// 把标准日期字符串转换为日期类型 例：20070203
		/// </summary>	
		public static DateTime String2Date(string dateStr)
		{
			try
			{
				string temp=dateStr.Substring(0,4)+"-"+dateStr.Substring(4,2)+"-"+dateStr.Substring(6,2);
				return Convert.ToDateTime(temp);
			}
			catch(Exception ex)
			{
				throw ex;
			}
		}

		public static string getChineseValidateCode(int digit)
		{
			//获取GB2312编码页（表） 
			Encoding gb=Encoding.GetEncoding("gb2312"); 
     
			//调用函数产生4个随机中文汉字编码 
			object[] bytes=CreateRegionCode(digit); 
     
			//根据汉字编码的字节数组解码出中文汉字 			
			string result="";
			for(int i=0;i<bytes.Length;i++)
			{
				result+=gb.GetString((byte[])Convert.ChangeType(bytes[i], typeof(byte[]))); 
			}

            return result;			
		}

		//用户生成汉字验证码
		private static object[] CreateRegionCode(int strlength) 
		{ 
			//定义一个字符串数组储存汉字编码的组成元素 
			string[] rBase=new String [16]{"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"}; 
     
			Random rnd=new Random(); 
     
			//定义一个object数组用来 
			object[] bytes=new object[strlength]; 
     
			/**//*每循环一次产生一个含两个元素的十六进制字节数组，并将其放入bject数组中 
			每个汉字有四个区位码组成 
			区位码第1位和区位码第2位作为字节数组第一个元素 
			区位码第3位和区位码第4位作为字节数组第二个元素 
			*/ 
			for(int i=0;i<strlength;i++) 
			{ 
				//区位码第1位 
				int r1=rnd.Next(11,14); 
				string str_r1=rBase[r1].Trim(); 
      
				//区位码第2位 
				rnd=new Random(r1*unchecked((int)DateTime.Now.Ticks)+i);//更换随机数发生器的 
      
				//	种子避免产生重复值 
				int r2; 
				if (r1==13) 
				{ 
					r2=rnd.Next(0,7); 
				} 
				else 
				{ 
					r2=rnd.Next(0,16); 
				} 
				string str_r2=rBase[r2].Trim(); 
      
				//区位码第3位 
				rnd=new Random(r2*unchecked((int)DateTime.Now.Ticks)+i); 
				int r3=rnd.Next(10,16); 
				string str_r3=rBase[r3].Trim(); 
    
				//区位码第4位 
				rnd=new Random(r3*unchecked((int)DateTime.Now.Ticks)+i); 
				int r4; 
				if (r3==10) 
				{ 
					r4=rnd.Next(1,16); 
				} 
				else if (r3==15) 
				{ 
					r4=rnd.Next(0,15); 
				} 
				else 
				{ 
					r4=rnd.Next(0,16); 
				} 
				string str_r4=rBase[r4].Trim(); 
    
				//定义两个字节变量存储产生的随机汉字区位码 
				byte byte1=Convert.ToByte(str_r1 + str_r2,16); 
				byte byte2=Convert.ToByte(str_r3 + str_r4,16); 
				//将两个字节变量存储在字节数组中 
				byte[] str_r=new byte[]{byte1,byte2}; 
      
				//将产生的一个汉字的字节数组放入object数组中 
				bytes.SetValue(str_r,i);       
			}    
			return bytes;    
		} 



	}    
    

}


