1.验证登录 18.图片上传
2.验证码 19.取消js中事件冒泡
3.事务
4.分页的存储过程 20:遍历一个枚举
5.Sqlserver中抛异常 21.序列化和反序列化
6.流水号生成 22.自动跳转页面<meta http-equiv="refresh" content="5;url=“”)
7.DALBase类 23.XML的读写
8.KeyAttribute类 24.
9.ModelBase类 25.
10.PageClass类(用于分页) 26.
11.SqlHelp类 27.
12.SqlManager类 28.
13.MD5编码类 29.
14.生成实体类 30.
15.XML操作 31.
16.JSON.js
(WebService 时调用) 32.
17.AJAX.js 33.
(WebService 通用部分)
18.mysql 连接
server=localhost;uid=root;pwd=root;database=test;CharSet=utf8;oldsyntax=true;
-------------------------
19. ado.net 访问数据库:
/// <summary>
/// The SqlHelper class is intended to encapsulate high performance,
/// scalable best practices for common uses of SqlClient.
/// </summary>
public sealed class SqlHelper
{
private SqlHelper(){}
//Database connection strings
public static readonly string CONN_STRING = ConfigurationManager.ConnectionStrings["SqlConnection"].ConnectionString;
/// <summary>
/// Execute a SqlCommand that returns a resultset against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="cmdType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="cmdText">the stored procedure name or T-SQL command</param>
/// <param name="cmdParms">an array of SqlParamters used to execute the command</param>
/// <returns>A SqlDataReader containing the results</returns>
public static SqlDataReader ExecuteReader(CommandType cmdType, string cmdText, params SqlParameter[] cmdParms)
{
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(CONN_STRING);
// we use a try/catch here because if the method throws an exception we want to
// close the connection throw code, because no datareader will exist, hence the
// commandBehaviour.CloseConnection will not work
try
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return rdr;
}
catch
{
conn.Close();
throw;
}
}
/// <summary>
/// Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="cmdType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="cmdText">the stored procedure name or T-SQL command</param>
/// <param name="cmdParms">an array of SqlParamters used to execute the command</param>
/// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
public static object ExecuteScalar(CommandType cmdType, string cmdText, params SqlParameter[] cmdParms)
{
SqlCommand cmd = new SqlCommand();
using (SqlConnection conn = new SqlConnection(CONN_STRING))
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
object val = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;
}
}
/// <summary>
/// Execute a SqlCommand that returns the first column of the first record against an existing database connection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="conn">an existing database connection</param>
/// <param name="cmdType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="cmdText">the stored procedure name or T-SQL command</param>
/// <param name="cmdParms">an array of SqlParamters used to execute the command</param>
/// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
public static object ExecuteScalar(SqlConnection conn, CommandType cmdType, string cmdText, params SqlParameter[] cmdParms)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
object val = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;
}
/// <summary>
/// Prepare a command for execution
/// </summary>
/// <param name="cmd">SqlCommand object</param>
/// <param name="conn">SqlConnection object</param>
/// <param name="trans">SqlTransaction object</param>
/// <param name="cmdType">Cmd type e.g. stored procedure or text</param>
/// <param name="cmdText">Command text, e.g. Select * from Products</param>
/// <param name="cmdParms">SqlParameters to use in the command</param>
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = cmdType;
if (cmdParms != null)
{
foreach (SqlParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
}
}
MVC部分:
在ASP.net中用MVC框架时专递参数时需要手动将参数转成JSON格式
通过一个下面的js脚本
(function($){$.toJSON=function(o)
{if(typeof(JSON)=='object'&&JSON.stringify)
return JSON.stringify(o);var type=typeof(o);if(o===null)
return"null";if(type=="undefined")
return undefined;if(type=="number"||type=="boolean")
return o+"";if(type=="string")
return $.quoteString(o);if(type=='object')
{if(typeof o.toJSON=="function")
return $.toJSON(o.toJSON());if(o.constructor===Date)
{var month=o.getUTCMonth()+1;if(month<10)month='0'+month;var day=o.getUTCDate();if(day<10)day='0'+day;var year=o.getUTCFullYear();var hours=o.getUTCHours();if(hours<10)hours='0'+hours;var minutes=o.getUTCMinutes();if(minutes<10)minutes='0'+minutes;var seconds=o.getUTCSeconds();if(seconds<10)seconds='0'+seconds;var milli=o.getUTCMilliseconds();if(milli<100)milli='0'+milli;if(milli<10)milli='0'+milli;return'"'+year+'-'+month+'-'+day+'T'+
hours+':'+minutes+':'+seconds+'.'+milli+'Z"';}
if(o.constructor===Array)
{var ret=[];for(var i=0;i<o.length;i++)
ret.push($.toJSON(o[i])||"null");return"["+ret.join(",")+"]";}
var pairs=[];for(var k in o){var name;var type=typeof k;if(type=="number")
name='"'+k+'"';else if(type=="string")
name=$.quoteString(k);else
continue;if(typeof o[k]=="function")
continue;var val=$.toJSON(o[k]);pairs.push(name+":"+val);}
return"{"+pairs.join(", ")+"}";}};$.evalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);return eval("("+src+")");};$.secureEvalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))
return eval("("+src+")");else
throw new SyntaxError("Error parsing JSON, source is not valid.");};$.quoteString=function(string)
{if(string.match(_escapeable))
{return'"'+string.replace(_escapeable,function(a)
{var c=_meta[a];if(typeof c==='string')return c;c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
return'"'+string+'"';};var _escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var _meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};})(jQuery);
-------------------------------------------------------------------------------------------
//验证登录:
1.设置拦截器进行验证
using System.Web;
/// <summary>
///PageModel 的摘要说明
/// </summary>
public class PageModel:IHttpModule
{
public PageModel()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
#region IHttpModule 成员
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.AcquireRequestState += new EventHandler(context_AcquireRequestState);
}
void context_AcquireRequestState(object sender, EventArgs e)
{
HttpApplication ha = sender as HttpApplication;
string fileName = System.IO.Path.GetFileName(ha.Request.PhysicalPath);
string ex = System.IO.Path.GetExtension(ha.Request.PhysicalPath);
if (ex.ToLower() == ".aspx" && fileName != "Login.aspx")
{
if (ha.Session["user"] == null)
{
ha.Response.Redirect("Login.aspx");
}
}
}
#endregion
}
2.通过Session验证:
用法:写一个页面类的父类,将所有需要验证的页面都继承这个类,但是这个类也是页面类继承(System.Web.UI.Page)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
///PageBase 的摘要说明
/// </summary>
public class PageBase:System.Web.UI.Page
{
public PageBase()
{
//
//TODO: 在此处添加构造函数逻辑
//
Load += new EventHandler(PageBase_Load);
}
void PageBase_Load(object sender, EventArgs e)
{
if (System.Configuration.ConfigurationManager.AppSettings["check"].ToString() == "true")
{
if (Session["user"] == null)
{
Response.Write("<script> window.location = 'Error.aspx';</script>");
}
}
}
}
/
//验证码
1.提供图片的验证码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
public partial class ShowImage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Drawing.Image images = System.Drawing.Image.FromFile(Server.MapPath("Image\\check.jpg"));
string code = GetCode();
using (Graphics g = Graphics.FromImage(images))
{
g.DrawString(code, new Font("宋体", 18), new SolidBrush(Color.Blue), 15, 4);
Response.ContentType = "image/jpeg";
images.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
Response.End();
}
}
public string GetCode()
{
string code="";
Random ran = new Random();
for (int i = 0; i < 4; i++)
{
int temp = ran.Next() % 2;
if (temp == 0)
{
code += ran.Next(0,9);
}
else
{
code +=((char)ran.Next('A', 'Z')).ToString();
}
}
return code;
}
}
2.全自动生成验证码:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Drawing;
namespace UI
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//调用自定义方法绘制验证码
CreateCheckCodeImage(GenerateCheckCode());
}
private string GenerateCheckCode()
{
//创建整型型变量
int number;
//创建字符型变量
char code;
//创建字符串变量并初始化为空
string checkCode = String.Empty;
//创建Random对象
Random random = new Random();
//使用For循环生成4个数字
for (int i = 0; i < 4; i++)
{
//生成一个随机数
number = random.Next();
//将数字转换成为字符型
code = (char)('0' + (char)(number % 10));
checkCode += code.ToString();
}
//将生成的随机数添加到Cookies中
Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));
//返回字符串
return checkCode;
}
private void CreateCheckCodeImage(string checkCode)
{