ASP.NET(C#)

  一个生成不重复随机数的方法

  //生成不重复随机数算法

  private int GetRandomNum(int i,int length,int up,int down)

  {

  int iFirst=0;

  Random ro=new Random(i*length*unchecked((int)DateTime.Now.Ticks));

  iFirst=ro.Next(up,down);

  return iFirst;

  }

  发表于 @ 2005年12月30日 3:44 PM | 评论 (0)

  ASP.NET多文件上传方法

  前台代码

  <script language="Javascript">

  function addFile()

  {

  var str = '<INPUT type="file" size="30" NAME="File"><br>'

  document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",str)

  }

  </script>

  <form id="form1" method="post" runat="server" enctype="multipart/form-data">

  <div align="center">

  <h3>多文件上传</h3>

  <P id="MyFile"><INPUT type="file" size="30" NAME="File"><br></P>

  <P>

  <input type="button" value="增加(Add)" onclick="addFile()"> <input onclick="this.form.reset()" type="button" value="重置(ReSet)">

  <asp:Button Runat="server" Text="开始上传" ID="UploadButton">

  </asp:Button>

  </P>

  <P>

  <asp:Label id="strStatus" runat="server" Font-Names="宋体" Font-Bold="True" Font-Size="9pt" Width="500px"

  BorderStyle="None" BorderColor="White"></asp:Label>

  </P>

  </div>

  </form>

  后台代码

  protected System.Web.UI.WebControls.Button UploadButton;

  protected System.Web.UI.WebControls.Label strStatus;

  private void Page_Load(object sender, System.EventArgs e)

  {

  /// 在此处放置用户代码以初始化页面

  if (this.IsPostBack) this.SaveImages();

  }

  private Boolean SaveImages()

  {

  ///'遍历File表单元素

  HttpFileCollection files = HttpContext.Current.Request.Files;

  /// '状态信息

  System.Text.StringBuilder strMsg = new System.Text.StringBuilder();

  strMsg.Append("上传的文件分别是:<hr color=red>");

  try

  {

  for(int iFile = 0; iFile < files.Count; iFile++)

  {

  ///'检查文件扩展名字

  HttpPostedFile postedFile = files[iFile];

  string fileName,fileExtension,file_id;

  //取出精确到毫秒的时间做文件的名称

  int year = System.DateTime.Now.Year;

  int month = System.DateTime.Now.Month;

  int day = System.DateTime.Now.Day;

  int hour = System.DateTime.Now.Hour;

  int minute = System.DateTime.Now.Minute;

  int second = System.DateTime.Now.Second;

  int millisecond = System.DateTime.Now.Millisecond;

  string my_file_id = year.ToString() + month.ToString() + day.ToString() + hour.ToString() + minute.ToString() + second.ToString() + millisecond.ToString()+iFile.ToString();

  fileName = System.IO.Path.GetFileName(postedFile.FileName);

  fileExtension = System.IO.Path.GetExtension(fileName);

  file_id = my_file_id+fileExtension;

  if (fileName != "")

  {

  fileExtension = System.IO.Path.GetExtension(fileName);

  strMsg.Append("上传的文件类型:" + postedFile.ContentType.ToString() + "<br>");

  strMsg.Append("客户端文件地址:" + postedFile.FileName + "<br>");

  strMsg.Append("上传文件的文件名:" + file_id + "<br>");

  strMsg.Append("上传文件的扩展名:" + fileExtension + "<br><hr>");

  postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("images/") + file_id);

  }

  }

  strStatus.Text = strMsg.ToString();

  return true;

  }

  catch(System.Exception Ex)

  {

  strStatus.Text = Ex.Message;

  return false;

  }

  }

  发表于 @ 2005年12月30日 3:37 PM | 评论 (0)

  邮件系统使用的上传附件方法

  前台HTML代码

  <form id="mail" method="post" runat="server">

  <table border="0" cellpadding="0" cellspacing="0" style="BORDER-COLLAPSE: collapse" bordercolor="#111111"

  width="39%" id="AutoNumber1" height="75">

  <tr>

  <td width="100%" height="37"><INPUT id="myFile" style="WIDTH: 297px; HEIGHT: 22px" type="file" size="30" name="myFile"

  runat="server">

  <asp:button id="Upload" runat="server" Text="上传附件"></asp:button></td>

  </tr>

  <tr>

  <td width="100%" height="38">

  共计

  <asp:textbox id="P_size" runat="server" Width="65px"></asp:textbox>KB

  <asp:dropdownlist id="dlistBound" runat="server"></asp:dropdownlist>

  <asp:button id="btnDel" runat="server" Text="删除附件"></asp:button></td>

  </tr>

  </table>

  </form>

  后台CS代码

  public class Upload_Mail : System.Web.UI.Page

  {

  protected System.Web.UI.WebControls.Button Upload;

  protected System.Web.UI.WebControls.DropDownList dlistBound;

  protected System.Web.UI.WebControls.TextBox P_size;

  protected System.Web.UI.WebControls.Button btnDel;

  protected System.Web.UI.HtmlControls.HtmlInputFile myFile;

  private void Page_Load(object sender, System.EventArgs e)

  {

  if (!IsPostBack)

  {

  //没有附件的状态

  dlistBound.Items.Clear();

  ArrayList arr = new ArrayList();

  arr.Add("--没有附件--");

  dlistBound.DataSource = arr ;

  dlistBound.DataBind();

  P_size.Text = "0";

  }

  }

  private void Upload_Click(object sender, System.EventArgs e)

  {

  if(myFile.PostedFile !=null)

  {

  HttpFileCollection files  = HttpContext.Current.Request.Files;

  HttpPostedFile postedFile = files[0];

  string fileName = System.IO.Path.GetFileName(postedFile.FileName);

  string path = Request.PhysicalApplicationPath+@"UploadMail\"+ fileName;

  postedFile.SaveAs(path);

  //数组对上存附件进行实时绑定

  if((string)Session["udMail"]==null)

  {

  Session["udMail"] = fileName;

  }

  else

  {

  Session["udMail"] = (string)Session["udMail"]+"|"+fileName;

  }

  string[] udMail = Session["udMail"].ToString().Split('|');

  ArrayList list = new ArrayList(udMail);

  list.Reverse();

  udMail=(string[])list.ToArray(typeof(string));

  dlistBound.Items.Clear();

  long dirsize=0;

  for(int i = 0;i<udMail.Length;i++)

  {

  string  IndexItem =  udMail[i];

  string  VauleItem = Request.PhysicalApplicationPath+@"UploadMail\"+udMail[i];

  dlistBound.Items.Add(new ListItem(IndexItem,VauleItem));

  System.IO.FileInfo mysize = new System.IO.FileInfo(@VauleItem);

  dirsize += System.Convert.ToInt32(mysize.Length/1024)+1;

  }

  P_size.Text = dirsize.ToString();

  }

  }

  private void btnDel_Click(object sender, System.EventArgs e)

  {

  string trueDelfile = dlistBound.SelectedValue.ToString();

  string Delfile = dlistBound.SelectedItem.ToString();

  usageIO.DeletePath(trueDelfile);

  if(Session["udMail"] != null)

  {

  int index = Session["udMail"].ToString().IndexOf("|");

  if(index == -1)

  {

  Session["udMail"] = null;

  dlistBound.Items.Clear();

  dlistBound.Items.Add("--没有附件--");

  P_size.Text = "0";

  }

  else

  {

  string[] udMail = Session["udMail"].ToString().Split('|');

  ArrayList values = new ArrayList(udMail);

  values.Remove(Delfile);

  string s = null;

  for(int i=0;i<values.Count;i++)

  {

  if(values.Count!=0)

  {

  s += values[i].ToString()+"|";

  }

  }

  if(s!=""||s!=null)

  {

  s =  s.TrimEnd('|');

  }

  Session["udMail"] = s;

  string[] uMail = Session["udMail"].ToString().Split('|');

  ArrayList list = new ArrayList(uMail);

  list.Reverse();

  uMail=(string[])list.ToArray(typeof(string));

  dlistBound.Items.Clear();

  long dirsize=0;

  for(int i = 0;i<uMail.Length;i++)

  {

  string  IndexItem =  uMail[i];

  string  VauleItem = Request.PhysicalApplicationPath+@"UploadMail\"+uMail[i];

  dlistBound.Items.Add(new ListItem(IndexItem,VauleItem));

  System.IO.FileInfo mysize = new System.IO.FileInfo(@VauleItem);

  dirsize += System.Convert.ToInt32(mysize.Length/1024)+1;

  }

  P_size.Text = dirsize.ToString();

  }

  }

  }

  Web 窗体设计器生成的代码#region Web 窗体设计器生成的代码

  override protected void OnInit(EventArgs e)

  {

  //

  // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。

  //

  InitializeComponent();

  base.OnInit(e);

  }

  /**//// <summary>

  /// 设计器支持所需的方法 - 不要使用代码编辑器修改

  /// 此方法的内容。

  /// </summary>

  private void InitializeComponent()

  {

  this.Upload.Click += new System.EventHandler(this.Upload_Click);

  this.btnDel.Click += new System.EventHandler(this.btnDel_Click);

  this.Load += new System.EventHandler(this.Page_Load);

  }

  #endregion

  }

  发表于 @ 2005年12月30日 3:29 PM | 评论 (0)

  上传图片并且生成可以控制大小图片清晰度的方法

  private void Upload_Click(object sender, System.EventArgs e)

  {

  if(myFile.PostedFile !=null)

  {

  // 检查文件扩展名字

  HttpFileCollection files  = HttpContext.Current.Request.Files;

  HttpPostedFile postedFile = files[0];

  string fileName,fileExtension,file_id,file_path;

  //取出精确到毫秒的时间做文件的名称

  int year = System.DateTime.Now.Year;

  int month = System.DateTime.Now.Month;

  int day = System.DateTime.Now.Day;

  int hour = System.DateTime.Now.Hour;

  int minute = System.DateTime.Now.Minute;

  int second = System.DateTime.Now.Second;

  int millisecond = System.DateTime.Now.Millisecond;

  string my_file_id = year.ToString() + month.ToString() + day.ToString() + hour.ToString() + minute.ToString() + second.ToString() + millisecond.ToString();

  //获得文件类型

  fileName = System.IO.Path.GetFileName(postedFile.FileName);

  fileExtension = System.IO.Path.GetExtension(fileName);

  //重新命名文件,防止重复

  file_id = "topnews_"+my_file_id+fileExtension;

  file_path = "images/article_images/"+file_id;

  //文件上传到服务器的根目录

  postedFile.SaveAs(Request.PhysicalApplicationPath+@"images\article_images\"+ file_id);

  //处理图片大小

  int width,height,level;

  width=120;

  height=90;

  level=100;//从1-100

  GetThumbnailImage(width,height,level,file_id);

  }

  }

  //生成缩略图函数

  public void GetThumbnailImage(int width,int height,int level,string file_id)

  {

  string newfile= Request.PhysicalApplicationPath+"images/article_images/"+"top_"+ file_id;

  System.Drawing.Image oldimage = System.Drawing.Image.FromFile(Request.PhysicalApplicationPath+"images/article_images/"+ file_id);

  System.Drawing.Image thumbnailImage = oldimage.GetThumbnailImage(width, height,new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);

  Bitmap output=new Bitmap(thumbnailImage);

  //处理JPG质量的函数

  ImageCodecInfo[] codecs=ImageCodecInfo.GetImageEncoders();

  ImageCodecInfo ici=null;

  foreach(ImageCodecInfo codec in codecs){if(codec.MimeType=="image/jpeg")ici=codec;}

  EncoderParameters ep=new EncoderParameters();

  ep.Param[0]=new EncoderParameter(Encoder.Quality,(long)level);

  output.Save(newfile,ici,ep);

  //释放所有使用对象

  ep.Dispose();

  output.Dispose();

  oldimage.Dispose();

  thumbnailImage.Dispose();

  //删除源图片

  string file_path = "images/article_images/"+"top_"+file_id;

  usageIO.DeletePath(Request.PhysicalApplicationPath+"images/article_images/"+ file_id);

  Response.Write("<script >parent.Form1.A_Simg.value ='"+file_path+"';location.replace('Upload_Img.aspx')</script>");

  }

  bool ThumbnailCallback()

  {

  return false;

  }

  发表于 @ 2005年12月30日 3:25 PM | 评论 (0)

  生成高清晰度的缩略图[方法1]

  public void pic_zero(string sourcepath,string aimpath,int scale)

  {

  string originalFilename =sourcepath;

  //生成的高质量图片名称

  string strGoodFile =aimpath;

  //从文件取得图片对象

  System.Drawing.Image image = System.Drawing.Image.FromFile(originalFilename);

  int iImgWidth = image.Width;

  int iImgHeight = image.Height;

  int iScale = (iImgWidth / scale)>(iImgHeight/scale) ? (iImgWidth / scale) : (iImgHeight / scale);

  //取得图片大小

  System.Drawing.Size size = new Size(image.Width / iScale , image.Height / iScale);

  //新建一个bmp图片

  System.Drawing.Image bitmap = new System.Drawing.Bitmap(size.Width,size.Height);

  //新建一个画板

  System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

  //设置高质量插值法

  g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

  //设置高质量,低速度呈现平滑程度

  g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

  //清空一下画布

  g.Clear(Color.Blue);

  //在指定位置画图

  g.DrawImage(image, new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),

  new System.Drawing.Rectangle(0, 0, image.Width,image.Height),

  System.Drawing.GraphicsUnit.Pixel);

  //保存高清晰度的缩略图

  bitmap.Save(strGoodFile, System.Drawing.Imaging.ImageFormat.Jpeg);

  g.Dispose();

  }

  发表于 @ 2005年12月30日 3:23 PM | 评论 (0)

  比较完美的图片验证码

  需要引用的名字空间

  using System.IO;

  using System.Drawing.Imaging;

  using System.Drawing.Drawing2D;

  public class ValidationCodeImg : System.Web.UI.Page

  {

  private void Page_Load(object sender, System.EventArgs e)

  {

  this.CreateCheckCodeImage(GenerateCheckCode());

  }

  private string GenerateCheckCode()

  {

  int number;

  char code;

  string checkCode = String.Empty;

  System.Random random = new Random();

  for(int i=0; i<5; i++)

  {

  number = random.Next();

  if(number % 2 == 0)

  code = (char)('0' + (char)(number % 10));

  else

  code = (char)('0' + (char)(number % 10));

  checkCode += code.ToString();

  }

  Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));

  return checkCode;

  }

  private void CreateCheckCodeImage(string checkCode)

  {

  if(checkCode == null || checkCode.Trim() == String.Empty)

  return;

  System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 24);

  Graphics g = Graphics.FromImage(image);

  try

  {

  //生成随机生成器

  Random random = new Random();

  //清空图片背景色

  g.Clear(Color.White);

  //画图片的背景噪音线

  for(int i=0; i<2; i++)

  {

  int x1 = random.Next(image.Width);

  int x2 = random.Next(image.Width);

  int y1 = random.Next(image.Height);

  int y2 = random.Next(image.Height);

  g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);

  }

  Font font = new System.Drawing.Font("Tahoma", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));

  System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Black, Color.Black, 1.2f, true);

  g.DrawString(checkCode, font, brush, 2, 2);

  //画图片的前景噪音点

  for(int i=0; i<100; i++)

  {

  int x = random.Next(image.Width);

  int y = random.Next(image.Height);

  image.SetPixel(x, y, Color.FromArgb(random.Next()));

  }

  //画图片的边框线

  g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

  System.IO.MemoryStream ms = new System.IO.MemoryStream();

  image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);

  Response.ClearContent();

  Response.ContentType = "image/Gif";

  Response.BinaryWrite(ms.ToArray());

  }

  finally

  {

  g.Dispose();

  image.Dispose();

  }

  }

  发表于 @ 2005年12月30日 3:09 PM | 评论 (0)

  IE订单的打印处理办法

  在一个商城项目应用中我需要把客户在网上下的订单使用IE打印出来

  首先必须控制订单不能出现IE的页眉页脚(需要使用ScriptX)

  <OBJECT id="factory" style="DISPLAY: none" codeBase="http://www.meadroid.com/scriptx/ScriptX.cab#Version=5,60,0,360"

  classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814" viewastext>

  </OBJECT>

  <SCRIPT defer>

  function println() {

  factory.printing.header = ""

  factory.printing.footer = ""

  factory.printing.Print(true)

  factory.printing.leftMargin = 0.2

  factory.printing.topMargin = 0.5

  factory.printing.rightMargin = 0.2

  factory.printing.bottomMargin = 1.5

  window.print();

  }

  </SCRIPT>

  然后主要是控制订单数据输出用什么办法显示出来,为了灵活的控制输出效果,我这里使用的是循环读入数据(定购的商品)的办法(下面的代码是我使用的)

  public string myOrder(string B_No)

  {

  doData.conn.Open();

  string strFirstMenu =null;

  string    strSql = "select Items_Type,Items_Name,Items_Unit,Items_Count,Items_Price from [OrderItems] where Order_No = '"+B_No+"'  order by ID desc";

  SqlDataAdapter da = new SqlDataAdapter(strSql,doData.conn);

  DataSet ds = new DataSet();

  da.Fill(ds,"myOrder");

  int count = ds.Tables[0].Rows.Count;

  string Items_Type,Items_Name,Items_Price,Items_Count,Items_Unit,Items_TotalPrice;

  Double Items_AllTotalPrice = 0;

  int Items_TotalCount = 0;

  string begin = "<table id =\"inc\"style=\"BORDER-COLLAPSE: collapse\" borderColor=\"#111111\" height=\"35\" cellSpacing=\"0\" cellPadding=\"0\" width=\"95%\" border=\"1\"><tr><td align=\"center\" width=\"14%\" height=\"35\">商品编号</td><td align=\"center\" width=\"25%\" height=\"35\">商品名称</td><td align=\"center\" width=\"10%\" height=\"35\">单位</td><td align=\"center\" width=\"10%\" height=\"35\">数量</td><td align=\"center\" width=\"20%\" height=\"35\">单价(元)</td><td align=\"center\" width=\"21%\" height=\"35\">金额(元)</td></tr>";

  for(int rb = 0; rb < count;rb++)

  {

  Items_Type = ds.Tables[0].Rows[rb][0].ToString();

  Items_Name = ds.Tables[0].Rows[rb][1].ToString();

  Items_Unit = ds.Tables[0].Rows[rb][2].ToString();

  Items_Count = ds.Tables[0].Rows[rb][3].ToString();

  Items_Price = Double.Parse(ds.Tables[0].Rows[rb][4].ToString()).ToString("0.00");

  Items_TotalPrice = (Double.Parse(Items_Price)*Double.Parse(Items_Count)).ToString("0.00");

  Items_AllTotalPrice += Double.Parse(Items_TotalPrice);

  Items_TotalCount += Int32.Parse(Items_Count);

  strFirstMenu += "<tr><td width=\"14%\" height=\"20\"> "+Items_Type+"</td><td width=\"25%\" height=\"20\">"+Items_Name+"</td><td width=\"10%\" height=\"20\">"+Items_Unit+"</td><td width=\"10%\" height=\"20\">"+Items_Count+"</td><td width=\"20%\" height=\"20\">"+Items_Price+"</td><td width=\"21%\" height=\"20\">"+Items_TotalPrice+"</td></tr>";

  }

  string FirstMenu = begin+strFirstMenu+"</table>";

  doData.conn.Close();

  return FirstMenu;

  }

  发表于 @ 2005年12月30日 3:06 PM | 评论 (0)

  URL传输参数加密解密

  最近做一个论坛入口时要实现帐号和密码不在IE地址栏出现而做的

  index.aspx.cs (加密处理)

  Byte[] Iv64={11, 22, 33, 44, 55, 66, 77, 85};

  Byte[] byKey64={10, 20, 30, 40, 50, 60, 70, 80};

  public string Encrypt(string strText)

  {

  try

  {

  DESCryptoServiceProvider des = new DESCryptoServiceProvider();

  Byte[] inputByteArray  = Encoding.UTF8.GetBytes(strText);

  MemoryStream ms = new MemoryStream();

  CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey64, Iv64), CryptoStreamMode.Write);

  cs.Write(inputByteArray, 0, inputByteArray.Length);

  cs.FlushFinalBlock();

  return Convert.ToBase64String(ms.ToArray());

  }

  catch(Exception ex)

  {

  return ex.Message;

  }

  }

  private void btnLogin_Click(object sender, System.Web.UI.ImageClickEventArgs e)

  {

  DateTime nowTime = DateTime.Now;

  string postUser = txtUser.Text.ToString();

  string postPass = txtPassword.Text.ToString();

  Response.Redirect("Login.aspx?clubID="+Encrypt(postUser+","+postPass+","+nowTime.ToString()));

  }

  login.aspx.cs (解密处理)

  //随机选8个字节既为密钥也为初始向量

  Byte[] byKey64={10, 20, 30, 40, 50, 60, 70, 80};

  Byte[] Iv64={11, 22, 33, 44, 55, 66, 77, 85};

  public string Decrypt(string strText)

  {

  Byte[] inputByteArray = new byte[strText.Length];

  try

  {

  DESCryptoServiceProvider des = new DESCryptoServiceProvider();

  inputByteArray = Convert.FromBase64String(strText);

  MemoryStream  ms = new MemoryStream();

  CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey64, Iv64), CryptoStreamMode.Write);

  cs.Write(inputByteArray, 0, inputByteArray.Length);

  cs.FlushFinalBlock();

  System.Text.Encoding encoding = System.Text.Encoding.UTF8;

  return encoding.GetString(ms.ToArray());

  }

  catch(Exception ex)

  {

  return ex.Message;

  }

  }

  private void Page_Load(object sender, System.EventArgs e)

  {

  if(Request.Params["clubID"]!=null)

  {

  string originalValue = Request.Params["clubID"];

  originalValue = originalValue.Replace(" ","+");

  //+号通过url传递变成了空格。

  string decryptResult = Decrypt(originalValue);

  //DecryptString(string)解密字符串

  string delimStr = ",";

  char[] delimiterArray = delimStr.ToCharArray();

  string [] userInfoArray = null;

  userInfoArray = decryptResult.Split(delimiterArray);

  string userName = userInfoArray[0];

  User userToLogin = new User();

  userToLogin.Username = userInfoArray[0];

  userToLogin.Password = userInfoArray[1];

  ......

  }

  }