1设置虚拟路径
<!--#include virtual="/index/include/head.htm"-->
2加页面缓存
<%@ OutputCache Duration="7200" VaryByParam="*" %>
<%@ OutputCache Duration="7200" VaryByParam="*" %>
3数据绑定之datarowview
<%# import NameSpace="System.Data"%>
<%#((datarowview)container.dataitem)["newsline"]%><%#((DataRowView)Container.DataItem)["newsline"]%>
4好用的图片加文字绑定格式(注意datalist本身就是一个table所以一般把width放在datalist上,里面不用再加width这样可以保证可是不变形)
1
<
asp:DataList id
=
"
dtlist
"
runat
=
"
server
"
RepeatColumns
=
"
3
"
width
=
"
360
"
>
2
<
ItemTemplate
>
3
<
table height
=
"
87
"
border
=
"
0
"
cellpadding
=
"
1
"
cellspacing
=
"
1
"
bgcolor
=
"
#C7CDD9
"
>
4
<
tr
>
5
<
td width
=
"
32%
"
height
=
"
85
"
align
=
"
center
"
bgcolor
=
"
#FFFFFF
"
><
a href
=
'
<%#((DataRowView)Container.DataItem)["newsurl"]%>
'
target
=
"
_blank
"
><
img src
=
'
<%#((DataRowView)Container.DataItem)["imgPath"]%>
'
width
=
"
110
"
height
=
"
83
"
border
=
"
0
"
/></
a
></
td
>
6
</
tr
>
7
<
tr
>
8
<
td
>
9
<
a href
=
'
<%#((DataRowView)Container.DataItem)["newsurl"]%>
'
target
=
"
_blank
"
>
'
<%#((DataRowView)Container.DataItem)["newsline"]%>
'
</
a
>
10
</
td
>
11
</
tr
>
12
</
table
>
13
</
ItemTemplate
>
14
</
asp:DataList
>
5,cs里对绑定数据加颜色
dt.Rows[i]["newsline"] = "<font color=\"red\">"+dt.Rows[i]["newsline"]+"</font>";
6获取文件名绑定到地址栏
Code
public string getfilename()
{
string filename="";
filename=System.IO.Path.GetFileName(Request.Path);
return filename;
}
Wuc_page1.page_url ="../"+ getfilename()+"?page=" + ChannelNewsList1.M_page;
7zai web.config配置编码解码的文字格式
Code
<!-- 全球化
此节设置应用程序的全球化设置。
-->
<globalization
requestEncoding="utf-8"
responseEncoding="gb2312"
/>
8 属性的初始化
Code
private string year;
public string Year
{
set{year=value;}
get{return year;}
}
9数据库节日期函数
datepart(year,newsday)
@SelectedTime.IndexOf("-")+1;
10右对齐日期
day.Month.ToString ().PadLeft(2,'0');
11好用的显示绑定数据的条数,数据种类,与截取字符数据的长度
Code
/// <summary>
/// 根据新闻栏目ID来获取新闻列表
/// </summary>
/// <param name="topnum">新闻条数</param>
/// <param name="typeid">新闻栏目ID</param>
/// <param name="len">新闻标题的最大长度</param>
public static DataTable GetNewsListByTypeID(string topnum ,string typeid,int len,string wherePart,string orderPart,string domain,bool isPic)
{
string sql="";
if(wherePart != "")
{
wherePart = " and " + wherePart;
}
if( orderPart == "")
{
orderPart =" news_sort DESC, index_id DESC ";
}
if(isPic)
{
sql ="select top "+topnum+" newsid,newsline,newsday,imgpath,url,news_color,combinedTitle,newsSummary,Quarry,quarryUrl from dbo.VIEW_NEWS_TITLE_INDEX where type_id='"+typeid+"' and imgpath<>''" +wherePart+" ORDER BY news_sort DESC, index_id DESC";
}
else
{
sql ="select top "+topnum+" newsid,newsline,newsday,imgpath,url,news_color,combinedTitle,newsSummary,Quarry,quarryUrl from dbo.VIEW_NEWS_TITLE_INDEX where type_id='"+typeid+"'"+wherePart+" ORDER BY news_sort DESC, index_id DESC";
}
DataTable dt = new DataTable();
dt =Soufun.SqlHelper.ExecuteDataset(connStr, CommandType.Text, sql).Tables[0];
dt.Columns.Add ("newsurl");
dt.Columns.Add ("newstitle");
for(int i=0;i<dt.Rows.Count;i++)
{
//设置跳转
if(dt.Rows[i]["url"].ToString()!="")
{
dt.Rows[i]["newsurl"]=dt.Rows[i]["url"];
}
else
{
string newsurl = "";
string newsid = dt.Rows[i]["newsid"].ToString ();
DateTime day = Convert.ToDateTime(dt.Rows[i]["newsday"]);
newsurl = domain+"news/"+day.Year+"-"+day.Month.ToString ().PadLeft(2,'0')+"-"+day.Day.ToString ().PadLeft(2,'0')+"/"+typeid+"/"+newsid+".htm";
dt.Rows[i]["newsurl"] = newsurl;
}
dt.Rows[i]["newstitle"]=dt.Rows[i]["newsline"];
//设置标题长度
if(dt.Rows[i]["newsline"].ToString().Length>len)
{
dt.Rows[i]["newsline"] = dt.Rows[i]["newsline"].ToString ().Substring (0,len);
}
//设置标题标红
if(dt.Rows[i]["news_color"].ToString()=="1")
{
dt.Rows[i]["newsline"] = "<font color=\"red\">"+dt.Rows[i]["newsline"]+"</font>";
}
}
return dt;
}
12企业库中中设置缓存过期时间
Code
Microsoft.Practices.EnterpriseLibrary.Caching.Expirations.AbsoluteTime expireTime = DataLayer.CacheMan.GetAbsoluteTime(60);
public static AbsoluteTime GetAbsoluteTime(int t)
{
TimeSpan ts = new TimeSpan(0, t, 0);
AbsoluteTime at = new AbsoluteTime(ts);
return at;
}
13抛出异常
Exception ex_c = new Exception(message);throw ex_c;
14标准函数注释写法
Code
/// <summary>
/// 根据新闻分别编号获得指定条数的新闻列表
/// </summary>
/// <param name="topnum">前多少条</param>
/// <param name="parentid">新闻分类编号</param>
/// <param name="len">新闻截断长度</param>
/// <returns>新闻列表</returns>
15获得远端ip地址
clientip = Request.ServerVariables["REMOTE_ADDR"]
16在查询分析器里显示物理读和逻辑读
SET STATISTICS IO on
17去页面缓存
Code
CS里
Response.AddHeader("Cache-Control", "no-cache");
Response.AddHeader("Expires", "0");
html里
<meta http-equiv=Pragma content=no-cache>
<meta http-equiv=expires content=0>
<meta http-equiv="cache-control" content="no-store">
19读文件
Code
public static string getFileContent(string file_path)
{
FileStream reader = File.OpenRead(file_path);
int leng = (int)reader.Length;
Byte[] buffer = new byte[leng];
reader.Read(buffer,0,leng);
Encoding temp = Encoding.GetEncoding("gb2312");
string content = temp.GetString(buffer);
reader.Close();
return content.Trim();
}
21所有页面打开新窗口
<base target="_blank"/>
22前台绑定日期
Code
<%# DateTime.Parse(DataBinder.Eval(Container.DataItem, "uptime").ToString()).Year.ToString() + "-" + DateTime.Parse(DataBinder.Eval(Container.DataItem, "uptime").ToString()).Month.ToString() + "-" + DateTime.Parse(DataBinder.Eval(Container.DataItem, "uptime").ToString()).Day.ToString()%>
23去超链接下划线
Code
<style TYPE="text/css">
<!--
A:link{text-decoration:none}
A:visited{text-decoration:none}
A:hover {color: #ff00ff;text-decoration:underline}
-->
</style>
24动态添加脚本
Code
string strjavascript = "<script language='javascript'>alert('You cant delete the node which have childnode!')</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "onclick", strjavascript);
26常用错误记录方式
Code
string message = "信息:"+ex.Message+((char)13).ToString()+((char)10).ToString();
message += "堆栈:"+ex.StackTrace+((char)13).ToString()+((char)10).ToString();
message += "发生错误对象:"+ex.Source+((char)13).ToString()+((char)10).ToString();
message += "发生错误方法:"+ex.TargetSite+((char)13).ToString()+((char)10).ToString();
message += "数据库语句:"+sqlstring+((char)13).ToString()+((char)10).ToString();
message += "数据库链接:"+connstring+((char)13).ToString()+((char)10).ToString();
27sql日期转换(只留年月日)
convert(char(10),datetime,101)
28后台绑定option
Code
if(dts.Rows[i][0].ToString() == id)
{
selectStr += "<option selected value=\"" + dts.Rows[i][0].ToString() + "\">" + (i+1) + "</option>";
}
else
{
selectStr += "<option value=\"" + dts.Rows[i][0].ToString() + "\">" + (i+1) + "</option>";
}
29动态页转静态页基类
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
string name = Request.Url.AbsolutePath.Substring(1, Request.Url.AbsolutePath.Length - 1).Replace("aspx", "htm");
string newurl = "";
if (name.IndexOf("/") > 0)
{
newurl = Server.MapPath("../") + name;
}
else
{
newurl = Server.MapPath("./") + name;
}
MemoryStream ms = new MemoryStream();
StreamWriter sww = new StreamWriter(ms);
StreamWriter swr = new StreamWriter(newurl);
System.Web.UI.HtmlTextWriter htmlw = new HtmlTextWriter(swr);
base.Render(htmlw);
htmlw.Flush();
htmlw.Close();
string strLL = System.Text.Encoding.UTF8.GetString(ms.ToArray());
Response.Write(strLL);
Response.Redirect(Request.Url.AbsoluteUri.Replace("aspx", "htm"), true);
}
30数据库输出xml
for xml auto,elements
31截取字符串
按位截取字符串
/**//// <summary>
/// 按位截取字符串
/// </summary>
/// <returns></returns>
public static string CutByteString(string str,int len)
{
str = str.Trim();
byte[] myByte = System.Text.Encoding.Default.GetBytes(str);
if(myByte.Length>len)
{
string result = "";
for(int i=0;i<str.Length;i++)
{
byte[] tempByte=System.Text.Encoding.Default.GetBytes(result);
if(tempByte.Length<len)
{
result += str.Substring(i,1);
}
else
{
break;
}
}
if(result.Length == str.Length)
{
result = result;
}
else
{
result = result+"";
}
return result;
}
else
{
return str;
}
}
/**//// <summary>
/// 获取位数
/// </summary>
/// <param name="str"></param>
/// <param name="len"></param>
/// <returns></returns>
public static int StringLen(string str )
{
str = str.Trim();
byte[] myByte = System.Text.Encoding.Default.GetBytes(str);
return myByte.Length;
}
32写文件
写文件
FileStream fs = new FileStream(filepaths, FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.GetEncoding("gb2312"));
sw.Flush();
sw.BaseStream.Seek(0, SeekOrigin.Begin);
sw.Write(ex.Message.ToString());
sw.Close();
//flag = true;
newsidflag = false;
33检查添加缓存
//检查、添加缓存
DataTable dt = new DataTable ();
string CacheName = "@3$%"+newsid;
object u = Cache.Get(CacheName);
if(u == null)
{
dt = GetNewsContentByNewsID(newsid);
Cache.Insert (CacheName,dt.Copy(),null,DateTime.Now.AddMinutes(60),TimeSpan.Zero);
}
else
{
dt = (DataTable)u;
}
34自定义customErrors
<customErrors defaultRedirect="http://localhost/sitemap.html" mode="RemoteOnly" />
35通过地址栏得到参数并过滤的通用方法。
request
public static string GetRequestStr(string keystr)
{
System.Web.HttpRequest Request = System.Web.HttpContext.Current.Request;
if(Request.Form[keystr] == null && Request.QueryString[keystr] == null){ return "";}
string returnstr = "";
if(Request.Form[keystr] != null)
{
if(Request.Form[keystr].ToString().Trim().Length > 0)
{
returnstr = Request.Form[keystr].ToString().Trim().Replace("'","''");
}
}
else if(Request.QueryString[keystr] != null)
{
if(Request.QueryString[keystr].ToString().Trim().Length > 0)
{
returnstr = Request.QueryString[keystr].ToString().Trim().Replace("'","''");
}
}
//屏蔽16进制编码,将2700替换成2个2700
if(returnstr.ToLower().IndexOf("cast(0x")>=0)
{
returnstr=returnstr.ToLower().Replace("cast(0x","");
returnstr=returnstr.Replace("2700","27002700");
}
return returnstr;
}