Thursday, November 27, 2008

怎样把COOKIE放到公共类里再调用

一个关于怎样把COOKIE放到公共类里再调用的问题

Default.aspx code

<body>
<form id="form1" runat="server">
<div>
<center>
<table>
<tr>
<td>UserName : </td>
<td>
<asp:TextBox ID="txtUser" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Password</td>
<td>
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan=2>
<asp:Button ID="btnSubmit" runat="server" Text="Submit to Target"
onclick="btnSubmit_Click" />
</td>
</tr>
</table>
</center>
</div>
</form>
</body>

Default.aspx.cs code

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnSubmit_Click(object sender, EventArgs e)
{
HttpCookie objCookUser = new HttpCookie("UserName",txtUser.Text.Trim().ToString());
HttpCookie objCookPwd = new HttpCookie("Password",txtPassword.Text.ToString().Trim());
Response.Cookies.Add(objCookUser);
Response.Cookies.Add(objCookPwd);
Server.Transfer("TargetPage.aspx");
}
}

TargetPage.aspx.cs code

public partial class TargetPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (System.Web.HttpContext.Current.Request.Cookies["UserName"] != null && System.Web.HttpContext.Current.Request.Cookies["Password"] != null)
{
Response.Write(System.Web.HttpContext.Current.Request.Cookies["UserName"].Value.ToString() + "<br/>" + System.Web.HttpContext.Current.Request.Cookies["Password"].Value.ToString());
}
}
}
}

Monday, November 24, 2008

Session State Sample

this is a session state practise:

Default.aspx Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Session State</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<center>
<h1>Session State</h1>
<h3>Select a book category</h3>

<asp:RadioButtonList ID="rdl" runat="server" CellPadding="20" RepeatColumns="3" RepeatDirection="Horizontal" OnSelectedIndexChanged="rdl_SelectedIndexChanged">
<asp:ListItem Value="n">.NET</asp:ListItem>
<asp:ListItem Value="d">DataBase</asp:ListItem>
<asp:ListItem Value="h">HardWare</asp:ListItem>
</asp:RadioButtonList>
<asp:Button ID="btn" runat="server" Text="Submit" onclick="btn_Click" />
<br /><br />
<asp:Label ID="lblMessage" runat="server"></asp:Label>
<br /><br />
<asp:DropDownList ID="ddl" runat="server" Visible="false"></asp:DropDownList>
</center>
</div>
</form>
</body>
</html>

Default.aspx.cs Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Text;//necessary for StringBuilder

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void rdl_SelectedIndexChanged(object sender, EventArgs e)
{
if (rdl.SelectedIndex != -1)
{
string[] Books = new string[3];
Session["cattext"] = rdl.SelectedItem.Text;
Session["catcode"] = rdl.SelectedItem.Value;

switch (rdl.SelectedItem.Value)
{
case "n":
Books[0] = "Programming C#";
Books[1] = "Programming ASP.NET";
Books[2] = "Programming Essentials";
break;
case "d":
Books[0] = "Oracle & Open Source";
Books[1] = "SQL in a NutShell";
Books[2] = "Transact-SQL Programming";
break;
case "h":
Books[0] = "PC Hardware in a Nutshell";
Books[1] = "Dictionary of PC Hardware and Data Communications Terms";
Books[2] = "Linux Device Drivers";
break;
}

Session["books"] = Books;
}
}
protected void btn_Click(object sender, EventArgs e)
{
if (rdl.SelectedIndex == -1)
{
lblMessage.Text = "You must select a book category.";
}
else
{
StringBuilder sb = new StringBuilder();
sb.Append("You have selected the category ");
sb.Append((string)Session["cattext"]);
sb.Append(" with code \"");
sb.Append((string)Session["catcode"]);
sb.Append("\".");
lblMessage.Text = sb.ToString();

ddl.Visible = true;
string[] CatBooks = (string[]) Session["books"];

//populate the DropDownList
ddl.Items.Clear();
for (int i = 0; i < CatBooks.GetLength(0); i++)
{
ddl.Items.Add(new ListItem(CatBooks[i]));
}
}
}
}

Sunday, November 23, 2008

Cross page is post back with different method

this is a page redirect sample (Server.Transfer, Response.Redirect, Cross-Page):

Default.aspx Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Cross-Page Posting</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<center>
<h1>Cross-Page Posting</h1>
Select your favorite activity: 
<asp:DropDownList ID="ddlFavoriteActivity" runat="server" AutoPostBack="true">
<asp:ListItem Text="Eating" />
<asp:ListItem Text="Sleeping" />
<asp:ListItem Text="Programming" />
<asp:ListItem Text="Watching TV" />
<asp:ListItem Text="Sex" />
<asp:ListItem Text="Skiing" />
<asp:ListItem Text="Bicycling" />
</asp:DropDownList>
<br /><br /><br />
<asp:Button ID="btnServerTransfer" runat="server" Text="Server.Transfer"
onclick="btnServerTransfer_Click" /> 
<asp:Button ID="btnRedirect" runat="server" Text="Response.Redirect"
onclick="btnRedirect_Click" /> 
<asp:Button ID="btnCrossPage" runat="server" Text="Cross-Page Post" PostBackUrl="~/TargetPage.aspx" />
<br /><br />
IsPostBack:
<asp:Label ID="lblIsPostBack" runat="server" Text="not defined"></asp:Label>
<br />
IsCrossPagePoatBack:
<asp:Label ID="lblIsCrossPagePostBack" runat="server" Text="not defined"></asp:Label>
<br />
PreviousPage:
<asp:Label ID="lblPreviousPage" runat="server" Text="not defined"></asp:Label>
</center>
</div>
</form>
</body>
</html>

Default.aspx.cs Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Threading;//necessary for ThreadAbortException

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblIsPostBack.Text = IsPostBack.ToString();
lblIsCrossPagePostBack.Text = IsCrossPagePostBack.ToString();
if (Page.PreviousPage != null)
{
lblPreviousPage.Text = Page.PreviousPage.Title;
}
}
protected void btnServerTransfer_Click(object sender, EventArgs e)
{
Server.Transfer("TargetPage.aspx");
}
protected void btnRedirect_Click(object sender, EventArgs e)
{
Response.Redirect("TargetPage.aspx");
}
}

TargetPage.aspx Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Target page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<center>
<h1>Target Page</h1>
<br />
Your favorite activity is :
<asp:Label ID="lblAcyivity" runat="server" Text="unknow"></asp:Label>
<br /><br />
IsPostBack:
<asp:Label ID="lblIsPostBack" runat="server" Text="not defined"></asp:Label>
<br />
IsCrossPagePoatBack:
<asp:Label ID="lblIsCrossPagePostBack" runat="server" Text="not defined"></asp:Label>
<br />
PreviousPage:
<asp:Label ID="lblPreviousPage" runat="server" Text="not defined"></asp:Label>
<br />
Previous Page IsPostBack :
<asp:Label ID="lblPreviousPageIsPostBack" runat="server" Text="not defined"></asp:Label>
<br />
Previous Page IsCrossPagePostBack :
<asp:Label ID="lblPreviousPageCrossPagePostBack" runat="server" Text="not defined"></asp:Label>
</center>
</div>
</form>
</body>
</html>

TargetPage.aspx.cs Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class TargetPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.PreviousPage != null)
{
DropDownList ddl = (DropDownList)Page.PreviousPage.FindControl("ddlFavoriteActivity");
if (ddl != null)
{
lblAcyivity.Text = ddl.SelectedItem.ToString() + "(late-bound)";
}
}
lblIsPostBack.Text = IsPostBack.ToString();
lblIsCrossPagePostBack.Text = IsCrossPagePostBack.ToString();
if (Page.PreviousPage != null)
{
lblPreviousPage.Text = Page.PreviousPage.Title;
lblPreviousPageIsPostBack.Text = Page.PreviousPage.IsPostBack.ToString();
lblPreviousPageCrossPagePostBack.Text = Page.PreviousPage.IsCrossPagePostBack.ToString();
}
}
}

How to Use MultiView and View

sometime we need use multiview to show some many content, this is a demo for it. Let's go!

client code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>This is a practice for MultiView and View</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<center>
<h1>MultiView and View</h1><br />
<asp:RadioButtonList ID="rdlView" runat="server" AutoPostBack="true"
RepeatDirection="Horizontal"
onselectedindexchanged="rdlView_SelectedIndexChanged">
<asp:ListItem Value="-1">Nothing</asp:ListItem>
<asp:ListItem Selected=True Value="0">First View</asp:ListItem>
<asp:ListItem Value="1">Second View</asp:ListItem>
<asp:ListItem Value="2">Third View</asp:ListItem>
<asp:ListItem Value="3">Last View</asp:ListItem>
</asp:RadioButtonList><br />
Current Index:
<asp:Label ID="lblCurrentIndex" runat="server"></asp:Label>
<br />
<asp:MultiView ID="MultiView1" runat="server"
onactiveviewchanged="MultiView1_ActiveViewChanged" ActiveViewIndex=0>
<asp:View ID="vwFirst" runat="server" OnActivate="ActivateView"
ondeactivate="DeactivateView">
<h2>First View</h2>
<asp:TextBox ID="txtFirstView" runat="server" />
<asp:Button ID="btnNext1" runat="server" CommandName="NextView" Text="Go to Next" />
<asp:Button ID = "btnLast" runat="server" CommandName="SwitchViewByID" CommandArgument="vwLast" Text = "Go to Last" />
</asp:View>
<asp:View ID="vwSecond" runat="server" OnActivate="ActivateView" OnDeactivate="DeactivateView">
<h2>Second View</h2>
<asp:TextBox ID="txtSecondView" runat="server"></asp:TextBox>
<asp:Button ID="btnNext2" runat="server" CommandName="NextView" Text="Go to Next" />
<asp:Button ID="btnPrevious2" runat="server" CommandName="PrevView" Text="Go to Previous" />
</asp:View>
<asp:View ID="vwThird" runat="server" OnActivate="ActivateView" OnDeactivate="DeactivateView">
<h2>Third View</h2>
<br />
<asp:Button ID="btnNext3" runat="server" CommandName="NextView" Text="Go to Next" />
<asp:Button ID="btnPrev3" runat="server" CommandName="PrevView" Text="Go to Previous" />
</asp:View>
<asp:View ID="vwLast" runat="server" OnActivate="ActivateView" OnDeactivate="DeactivateView">
<h2>Last View</h2>
<br />
<asp:Button ID="btnPrev4" runat="server" CommandName="PrevView" Text="Go to Previous" />
<asp:Button ID="btnFirst" runat="server" CommandName="SwitchViewByIndex" CommandArgument="0" Text="Go to First" />
</asp:View>
</asp:MultiView>
<br /><br />
First TextBox:
<asp:Label ID="lblFirstTextBox" runat="server"></asp:Label>
<br />
Second TextBox:
<asp:Label ID="lblSecondTextBox" runat="server"></asp:Label>
<br /><br />
<strong>
<span style="text-decoration:underline">
View Activation History:
</span>
</strong>
<br />
<asp:Label ID="lblViewActivation" runat="server"></asp:Label>
</center>
</div>
</form>
</body>
</html>

code behind:

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Page_PreRender(object sender, EventArgs e)
{
lblCurrentIndex.Text = MultiView1.ActiveViewIndex.ToString();
}
protected void rdlView_SelectedIndexChanged(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = Convert.ToInt32(rdlView.SelectedValue);
}
protected void ActivateView(object sender, EventArgs e)
{
string str = lblViewActivation.Text;
View v = (View)sender;
str += "View " + v.ID + " activated
";
lblViewActivation.Text = str;
}
protected void DeactivateView(object sender, EventArgs e)
{
string str = lblViewActivation.Text;
View v = (View)sender;
str += "View " + v.ID + " deactivated
";
lblViewActivation.Text = str;
}
protected void MultiView1_ActiveViewChanged(object sender, EventArgs e)
{
lblFirstTextBox.Text = txtFirstView.Text;
lblSecondTextBox.Text = txtSecondView.Text;
rdlView.SelectedIndex = MultiView1.ActiveViewIndex + 1;
}
}

comments:


1. in order to save you work, you can create a event group--ActivateView,DeactivateView, these group implement the same code for you.

2. please don't write the lblCurrentIndex.Text in the Page_Load() statement, because the page will be loaded before the label updated.
Just put the lblCurrentIndex.Text code in the Page_PreRender, this is a page event handler.

such as:


protected void Page_PreRender(object sender, EventArgs e)
{
lblCurrentIndex.Text = MultiView1.ActiveViewIndex.ToString();
}

Thursday, November 20, 2008

vs2008在编译时显示“无法显示该页面”

今天刚刚安装了vs2008和sql server2008,而且是在vista home 版本下边,运行了一个程序想体验一把vs2008,sql2008和vista的结合如何,结果按下F5后发现有错误,显示“该网页无法显示”,直接就晕了,vista home版本下是没有iis的,但是自从vs2005开始,编译运行时应该不再需要iis了(当然是在单机调试),我开始怀疑是不是安全权限设置有问题,因为vista的一个突出特点就是加入了许多的权限设置,于是大半夜的到网上搜啊,折腾了半天,才找到解决方案,不过这个方案应该不仅仅是适用于vista,其他的操作系统也有可能会遇见这样的问题,好了,看看我是怎么解决的吧。

开始-->运行-->输入c:\windows\system32\drivers\etc\hosts
这是会出现一个选框,你选择“记事本”,于是会有一个记事本文档,最下面有这样两行字:

127.0.0.1 localhost
::1 localhost

你只要将::1后面的localhost删除并保存即可以,修改后:

127.0.0.1 localhost
::1

保存后,再去运行vs2008里面的项目就可以了。简单吧?!!

其实问题的答案有时候真的很简单,不过要你不懈努力的去寻找才可以,这也许就是人们常说的会者不难难者不会。哈啊

Thursday, November 13, 2008

Tuesday, November 11, 2008

How to Create a dynamic web service

this is a sample about how to create webservice dynamicly. But at first, you must create a webservice on your local machine,
such as:http://localhost:2704/TestWebService/Service.asmx
OK, let's go !


code for default.aspx


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Dynamic Web Service Sample</title>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>WebService URL</td>
<td><asp:TextBox ID="wurl" runat="server">http://localhost:2704/TestWebService/Service.asmx</asp:TextBox></td>
</tr>
<tr>
<td>WebService Name</td>
<td><asp:TextBox ID="wname" runat="server">Service</asp:TextBox></td>
</tr>
<tr>
<td>Method Name</td>
<td><asp:TextBox ID="wmname" runat="server">RevSMS</asp:TextBox></td>
</tr>
<tr>
<td>Method Param0</td>
<td><asp:TextBox ID="wmparam0" runat="server">SYS06*</asp:TextBox></td>
</tr>
<tr>
<td>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /></td>
</tr>
<tr>
<td colspan="4"><asp:TextBox ID="result" runat="server" TextMode="MultiLine" Width="100%" Height="100px"></asp:TextBox></td>
</tr>
</table>

</form>
</body>
</html>

code for default.aspx.cs

public partial class _Default : System.Web.UI.Page
{
DynamicWebService we = new DynamicWebService("http://localhost:2704/TestWebService/Service.asmx", "Service");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
we = new DynamicWebService("http://localhost:2704/TestWebService/Service.asmx", "Service");
result.Text = we.InvokeMethod("HelloWorld", null).ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(wurl.Text)
&& !string.IsNullOrEmpty(wname.Text)
&& !string.IsNullOrEmpty(wmname.Text))
{
we = new DynamicWebService(wurl.Text, wname.Text);
result.Text = we.InvokeMethod(wmname.Text, string.IsNullOrEmpty(wmparam0.Text) ? null : new object[] { wmparam0.Text }).ToString();
}
}
}


code for DynamicWebService.cs

using System.Net;//for webclient
using System.Reflection;// for assembly
using System.IO;//for Stream
using System.Web.Services.Description;//for servicedescription
using System.CodeDom;//for CodeNameSpace
using System.CodeDom.Compiler;//for CodeDomProvider
/// <summary>
/// Summary description for DynamicWebService
/// </summary>
public class DynamicWebService
{
public DynamicWebService()
{
//
// TODO: Add constructor logic here
//
}

Assembly service = null;
string _url;
string _name;

public string ServiceURL
{
get
{
if (!_url.ToUpper().EndsWith("?WSDL"))
{
_url += "?WSDL";
}
return _url;
}
}

public string ServiceClassName
{
get { return _name; }
}

public DynamicWebService(string serviceURL,string serviceClassName)
{
_url = serviceURL;
_name = serviceClassName;
GetService();
}

public void GetService()
{
// 1. 使用 WebClient 下载 WSDL 信息。
WebClient web = new WebClient();
Stream stream = web.OpenRead(ServiceURL);

// 2. 创建和格式化 WSDL 文档。
ServiceDescription description = ServiceDescription.Read(stream);

// 3. 创建客户端代理代理类。
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = "Soap";// 指定访问协议。
importer.Style = ServiceDescriptionImportStyle.Client;// 生成客户端代理。
importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties | System.Xml.Serialization.CodeGenerationOptions.GenerateNewAsync;
importer.AddServiceDescription(description, null, null);// 添加 WSDL 文档。

// 4. 使用 CodeDom 编译客户端代理类。
CodeNamespace nmspace = new CodeNamespace();// 为代理类添加命名空间,缺省为全局空间。
CodeCompileUnit unit = new CodeCompileUnit();
unit.Namespaces.Add(nmspace);

ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

CompilerParameters parameter = new CompilerParameters();
parameter.GenerateExecutable = false;
parameter.GenerateInMemory = true;
parameter.ReferencedAssemblies.Add("System.dll");
parameter.ReferencedAssemblies.Add("System.XML.dll");
parameter.ReferencedAssemblies.Add("System.Web.Services.dll");
parameter.ReferencedAssemblies.Add("System.Data.dll");

CompilerResults result = provider.CompileAssemblyFromDom(parameter,unit);

if (!result.Errors.HasErrors)
{
service = result.CompiledAssembly;
}
else
{
throw new Exception("WebService have errors. ");
}
}

public object InvokeMethod(string MethodName,object[] parameters)
{
// 如果在前面为代理类添加了命名空间,此处需要将命名空间添加到类型前面。
System.Type t = service.GetType(ServiceClassName);

object o = Activator.CreateInstance(t);
MethodInfo method = t.GetMethod(MethodName);
return method.Invoke(o, parameters);
}
}

how to create a calendar in C#

I read a blog about how to create a calendar, it's simple, but i still want to past it on my blog. OK, Let's go !

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Response.Write(DateTime.Now.Year+" . "+ DateTime.Now.Month);
CreateCalendar(DateTime.Now.Year, DateTime.Now.Month);
}
}

private void CreateCalendar(int year, int month)
{
int days = DateTime.DaysInMonth(year, month);//retrieve the days of month
DateTime dt = new DateTime(year,month,1);
int weeke = Convert.ToInt32(dt.DayOfWeek.ToString("d")); //get the week day of the first day in month
string[,] cal = new string[7,6];//store the date
for (int day = 1; day <= days; day++)
{
int x = (day + weeke - 1) % 7;
int y = (day + weeke - 1) / 7;
for (int j = 0; j < 6; j++)
{
for (int i = 0; i < 7; i++)
{
cal[x, y] = day.ToString();
}
}
}

System.Text.StringBuilder st = new System.Text.StringBuilder();
st.Append("<table cellpadding=\"0\" cellspacing=\"0\" border=\"1\">");
st.Append("<thead><th>星期天</th><th>星期一</th><th>星期二</th><th>星期三</th><th>星期四</th><th>星期五</th><th>星期六</th></thead>");
for (int i = 0; i < 6; i++)
{
st.Append("<tr>");
for (int j = 0; j < 7; j++)
{
st.Append("<td>" + cal[j, i] + "</td>");
}
st.Append("</tr>");
}
st.Append("</table>");
Response.Write(st);
Response.End();
}

}

Thursday, November 6, 2008

几种ASP.Net常用的代码

1. 打开新的窗口并传送参数: 传送参数: response.write("<script>window.open(’*.aspx?

id="+this.DropDownList1.SelectIndex+"&id1="+...+"’)</script>") 接收参数: string a =

Request.QueryString("id"); string b = Request.QueryString("id1");

Demo:
default.aspx

<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
function RedirectToOtherPage()
{
// alert(document.getElementById("DropDownList1").value);
window.open("DestinationPage.aspx?value="+document.getElementById

("DropDownList1").value,"ref");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<center>
<h1>Redirect to another page and transfer value</h1>
<br /><br /><br />
<asp:DropDownList ID="DropDownList1" runat="server" Width="150">
<asp:ListItem>Kevin</asp:ListItem>
<asp:ListItem>Mary</asp:ListItem>
<asp:ListItem>Gary</asp:ListItem>
<asp:ListItem>Derek</asp:ListItem>
<asp:ListItem>John</asp:ListItem>
</asp:DropDownList> 
<asp:Button ID="Button1" runat="server" Text="TransferWithString"

OnClientClick="RedirectToOtherPage()" /> 
 
 
 
</center>
</div>
</form>
</body>
********************************
destination.aspx.cs

public partial class DestinationPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string msg = Request.QueryString["value"].ToString();
Response.Write(msg);
}
}
}

2.为按钮添加对话框 Button1.Attributes.Add("onclick","return confirm(’确认?’)");

button.attributes.add("onclick","if(confirm(’are you sure...?’)){return true;}else{return

false;}")

Demo:
default.aspx

<asp:Button ID="Button2" runat="server" Text="Button" onclick="Button2_Click" />
<asp:HiddenField ID="Text1" runat="server" />

************************
default.aspx.cs

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Button2.Attributes.Add("onclick", "if(confirm('are you sure?')){return true;}

else{return false;}");
Button2.Attributes.Add("onclick", "if(confirm('are you sure?'))

{document.getElementById('Text1').value='kevin';}else{document.getElementById

('Text1').value='false';}");

}
protected void Button2_Click(object sender, EventArgs e)
{
if (Text1.Value == "kevin")
{
Response.Write("this is true....");
}
else
{
Response.Write("this is false...");
}
}
}

3.删除表格选定记录 int intEmpID = (int)MyDataGrid.DataKeys[e.Item.ItemIndex]; string

deleteCmd = "DELETE from Employee where emp_id = " + intEmpID.ToString()    4.删除表格记

录警告 private void DataGrid_ItemCreated(Object sender,DataGridItemEventArgs e) {  switch

(e.Item.ItemType)  {   case ListItemType.Item :   case ListItemType.AlternatingItem :

  case ListItemType.EditItem:    TableCell myTableCell;    myTableCell =

e.Item.Cells[14];    LinkButton myDeleteButton ;    myDeleteButton = (LinkButton)

myTableCell.Controls[0];    myDeleteButton.Attributes.Add("onclick","return confirm(’您

是否确定要删除这条信息’);");    break;   default:    break;  } }    5.点击表格行

链接另一页 private void grdCustomer_ItemDataBound(object sender,

System.Web.UI.WebControls.DataGridItemEventArgs e) {  //点击表格打开  if (e.Item.ItemType

== ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)   

e.Item.Attributes.Add("onclick","window.open(’Default.aspx?id=" + e.Item.Cells[0].Text + "’

);"); } 双击表格连接到另一页 在itemDataBind事件中 if(e.Item.ItemType == ListItemType.Item

|| e.Item.ItemType == ListItemType.AlternatingItem) {  string OrderItemID =e.item.cells

[1].Text;  ...  e.item.Attributes.Add("ondblclick", "location.href=’../ShippedGrid.aspx?

id=" + OrderItemID + "’"); }    双击表格打开新一页 if(e.Item.ItemType ==

ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {  string

OrderItemID =e.item.cells[1].Text;  ...  e.item.Attributes.Add("ondblclick", "open

(’../ShippedGrid.aspx?id=" + OrderItemID + "’)"); } 6.表格超连接列传递参数 <

asp:HyperLinkColumn Target="_blank" headertext="ID号" DataTextField="id"

NavigateUrl="aaa.aspx?id=’  <%# DataBinder.Eval(Container.DataItem, "数据字段1")%>’ &

name=’<%# DataBinder.Eval(Container.DataItem, "数据字段2")%>’ />    7.表格点击改变颜色

if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem)

{  e.Item.Attributes.Add("onclick","this.style.backgroundColor=’#99cc00’;    

this.style.color=’buttontext’;this.style.cursor=’default’;"); } 写在DataGrid的

_ItemDataBound里 if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType ==

ListItemType.AlternatingItem) { e.Item.Attributes.Add

("onmouseover","this.style.backgroundColor=’#99cc00’;    this.style.color=’

buttontext’;this.style.cursor=’default’;"); e.Item.Attributes.Add

("onmouseout","this.style.backgroundColor=’’;this.style.color=’’;"); }    8.关于日期格式

日期格式设定 DataFormatString="{0:yyyy-MM-dd}" 我觉得应该在itembound事件中 e.items.cell["你

的列"].text=DateTime.Parse(e.items.cell["你的列"].text.ToString("yyyy-MM-dd"))    9.获取

错误信息并到指定页面 不要使用Response.Redirect,而应该使用Server.Transfer   e.g // in

global.asax protected void Application_Error(Object sender, EventArgs e) { if

(Server.GetLastError() is HttpUnhandledException) Server.Transfer("MyErrorPage.aspx"); //其

余的非HttpUnhandledException异常交给ASP.NET自己处理就okay了 :) }   Redirect会导致post-

back的产生从而丢失了错误信息,所以页面导向应该直接在服务器端执行,这样就可以在错误处理页面

得到出错信息并进行相应的处理    10.清空Cookie Cookie.Expires=[DateTime];

Response.Cookies("UserName").Expires = 0    11.自定义异常处理 //自定义异常处理类 using

System; using System.Diagnostics; namespace MyAppException {  /// <summary>  /// 从系统

异常类ApplicationException继承的应用程序异常处理类。  /// 自动将异常内容记录到Windows

NT/2000的应用程序日志  /// </summary>  public class

AppException:System.ApplicationException  {   public AppException()   {    if

(ApplicationConfiguration.EventLogEnabled)LogEvent("出现一个未知错误。");   }  public

AppException(string message)  {   LogEvent(message);  }  public AppException(string

message,Exception innerException)  {   LogEvent(message);   if (innerException !=

null)   {    LogEvent(innerException.Message);   }  }  //日志记录类  using

System;  using System.Configuration;  using System.Diagnostics;  using System.IO;  

using System.Text;  using System.Threading;  namespace MyEventLog  {   /// <summary>

  /// 事件日志记录类,提供事件日志记录支持   /// <remarks>   /// 定义了4个日志记录

方法 (error, warning, info, trace)   /// </remarks>   /// </summary>   public

class ApplicationLog   {    /// <summary>    /// 将错误信息记录到Win2000/NT事件日

志中    /// <param name="message">需要记录的文本信息</param>    /// </summary>

   public static void WriteError(String message)    {     WriteLog

(TraceLevel.Error, message);    }    /// <summary>    /// 将警告信息记录到

Win2000/NT事件日志中    /// <param name="message">需要记录的文本信息</param>   

 /// </summary>    public static void WriteWarning(String message)    {     

WriteLog(TraceLevel.Warning, message);      }    /// <summary>    /// 将提示信

息记录到Win2000/NT事件日志中    /// <param name="message">需要记录的文本信息</param>

   /// </summary>    public static void WriteInfo(String message)    {     

WriteLog(TraceLevel.Info, message);    }    /// <summary>    /// 将跟踪信息记录

到Win2000/NT事件日志中    /// <param name="message">需要记录的文本信息</param>   

 /// </summary>    public static void WriteTrace(String message)    {     

WriteLog(TraceLevel.Verbose, message);    }    /// <summary>    /// 格式化记录到

事件日志的文本信息格式    /// <param name="ex">需要格式化的异常对象</param>   

 /// <param name="catchInfo">异常信息标题字符串.</param>    /// <retvalue>    

/// <para>格式后的异常信息字符串,包括异常内容和跟踪堆栈.</para>    /// </retvalue

>    /// </summary>    public static String FormatException(Exception ex, String

catchInfo)    {     StringBuilder strBuilder = new StringBuilder();     if

(catchInfo != String.Empty)     {      strBuilder.Append(catchInfo).Append

("\r\n");     }     strBuilder.Append(ex.Message).Append("\r\n").Append

(ex.StackTrace);     return strBuilder.ToString();    }    /// <summary>    

/// 实际事件日志写入方法    /// <param name="level">要记录信息的级别

(error,warning,info,trace).</param>    /// <param name="messageText">要记录的文本.

</param>    /// </summary>    private static void WriteLog(TraceLevel level,

String messageText)    {     try     {      EventLogEntryType LogEntryType;

     switch (level)      {       case TraceLevel.Error:        

LogEntryType = EventLogEntryType.Error;        break;       case

TraceLevel.Warning:        LogEntryType = EventLogEntryType.Warning;        

break;       case TraceLevel.Info:        LogEntryType =

EventLogEntryType.Information;        break;       case TraceLevel.Verbose:  

      LogEntryType = EventLogEntryType.SuccessAudit;        break;      

 default:        LogEntryType = EventLogEntryType.SuccessAudit;        

break;      }      EventLog eventLog = new EventLog("Application",

ApplicationConfiguration.EventLogMachineName, ApplicationConfiguration.EventLogSourceName

);      //写入事件日志      eventLog.WriteEntry(messageText, LogEntryType);   

  }    catch {} //忽略任何异常   }  } //class ApplicationLog } 12.Panel 横向滚动,

纵向自动扩展<asp:panel style="overflow-x:scroll;overflow-y:auto;"></asp:panel>    13.

回车转换成Tab <script language="javascript" for="document" event="onkeydown">  if

(event.keyCode==13 && event.srcElement.type!=’button’ && event.srcElement.type!=’submit’ &&

    event.srcElement.type!=’reset’ && event.srcElement.type!=’’&&

event.srcElement.type!=’textarea’);    event.keyCode=9; </script> onkeydown="if

(event.keyCode==13) event.keyCode=9"    14.DataGrid超级连接列 DataNavigateUrlField="字段

名" DataNavigateUrlFormatString="http://xx/inc/delete.aspx?ID={0}"    15.DataGrid行随鼠标

变色 private void DGzf_ItemDataBound(object sender,

System.Web.UI.WebControls.DataGridItemEventArgs e) {  if (e.Item.ItemType!

=ListItemType.Header)  {   e.Item.Attributes.Add(

"onmouseout","this.style.backgroundColor=\""+e.Item.Style["BACKGROUND-COLOR"]+"\"");   

e.Item.Attributes.Add( "onmouseover","this.style.backgroundColor=\""+ "#EFF3F7"+"\"");  }

}    16.模板列 <ASP:TEMPLATECOLUMN visible="False" sortexpression="demo" headertext="ID"

> <ITEMTEMPLATE> <ASP:LABEL text=’<%# DataBinder.Eval(Container.DataItem,

"ArticleID")%>’ runat="server" width="80%" id="lblColumn" /> </ITEMTEMPLATE>

</ASP:TEMPLATECOLUMN> <ASP:TEMPLATECOLUMN headertext="选中"> <HEADERSTYLE wrap="False"

horizontalalign="Center"></HEADERSTYLE> <ITEMTEMPLATE> <ASP:CHECKBOX id="chkExport"

runat="server" /> </ITEMTEMPLATE> <EDITITEMTEMPLATE> <ASP:CHECKBOX id="chkExportON"

runat="server" enabled="true" /> </EDITITEMTEMPLATE> </ASP:TEMPLATECOLUMN>    后台代

码 protected void CheckAll_CheckedChanged(object sender, System.EventArgs e) {  //改变列的

选定,实现全选或全不选。  CheckBox chkExport ;  if( CheckAll.Checked)  {   foreach

(DataGridItem oDataGridItem in MyDataGrid.Items)   {    chkExport = (CheckBox)

oDataGridItem.FindControl("chkExport");    chkExport.Checked = true;   }  }  else  

{   foreach(DataGridItem oDataGridItem in MyDataGrid.Items)   {    chkExport =

(CheckBox)oDataGridItem.FindControl("chkExport");    chkExport.Checked = false;   }  

} }    17.数字格式化   【<%#Container.DataItem("price")%>的结果是500.0000,怎样格式化

为500.00?】 <%#Container.DataItem("price","{0:¥#,##0.00}")%> int i=123456; string

s=i.ToString("###,###.00"); 18.日期格式化   【aspx页面内:<%# DataBinder.Eval

(Container.DataItem,"Company_Ureg_Date")%>   显示为: 2004-8-11 19:44:28   我只想要:

2004-8-11 】 <%# DataBinder.Eval(Container.DataItem,"Company_Ureg_Date","{0:yyyy-M-d}")%>

  应该如何改?   【格式化日期】   取出来,一般是object((DateTime)

objectFromDB).ToString("yyyy-MM-dd");   【日期的验证表达式】   A.以下正确的输入格式:

[2004-2-29], [2004-02-29 10:29:39 pm], [2004/12/31] ^((\d{2}(([02468][048])|([13579][26]))

[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|

(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|([1-2][0-9])))))|(\d

{2}(([02468][1235679])|([13579][01345789]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1

-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2

[\-\/\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\s(((0?[1-9])|(1[0-2]))\:([0-5][0-9])((\s)|(\:

([0-5][0-9])\s))([AM|PM|am|pm]{2,2})))?$   B.以下正确的输入格式:[0001-12-31], [9999 09

30], [2002/03/03] ^\d{4}[\-\/\s]?((((0[13578])|(1[02]))[\-\/\s]?(([0-2][0-9])|(3[01])))|

(((0[469])|(11))[\-\/\s]?(([0-2][0-9])|(30)))|(02[\-\/\s]?[0-2][0-9]))$   【大小写转换】

HttpUtility.HtmlEncode(string); HttpUtility.HtmlDecode(string)
19.如何设定全局变量   Global.asax中   Application_Start()事件中   添加Application[属

性名] = xxx;   就是你的全局变量    20.怎样作到HyperLinkColumn生成的连接后,点击连接,

打开新窗口?   HyperLinkColumn有个属性Target,将器值设置成"_blank"即可.(Target="_blank")

  【ASPNETMENU】点击菜单项弹出新窗口   在你的menuData.xml文件的菜单项中加入

URLTarget="_blank",如: <?xml version="1.0" encoding="GB2312"?> <MenuData

ImagesBaseURL="images/"> <MenuGroup> <MenuItem Label="内参信息" URL="Infomation.aspx"

> <MenuGroup ID="BBC"> <MenuItem Label="公告信息" URL="Infomation.aspx"

URLTarget="_blank" LeftIcon="file.gif"/> <MenuItem Label="编制信息简报"

URL="NewInfo.aspx" LeftIcon="file.gif" /> ...... 21.读取DataGrid控件TextBox值 foreach

(DataGrid dgi in yourDataGrid.Items) {  TextBox tb = (TextBox)dgi.FindControl

("yourTextBoxId");  tb.Text.... }    23.在DataGrid中有3个模板列包含Textbox分别为

DG_ShuLiang (数量) DG_DanJian(单价) DG_JinE(金额)分别在5.6.7列,要求在录入数量及单价的时候

自动算出金额即:数量*单价=金额还要求录入时限制为 数值型.我如何用客户端脚本实现这个功能?   

〖思归〗 <asp:TemplateColumn HeaderText="数量"> <ItemTemplate> <asp:TextBox

id="ShuLiang" runat=’server’ Text=’<%# DataBinder.Eval(Container.DataItem,"DG_ShuLiang")%

>’ onkeyup="javascript:DoCal()" /> <asp:RegularExpressionValidator id="revS"

runat="server" ControlToValidate="ShuLiang" ErrorMessage="must be integer"

ValidationExpression="^\d+$" /> </ItemTemplate> </asp:TemplateColumn> <

asp:TemplateColumn HeaderText="单价"> <ItemTemplate> <asp:TextBox id="DanJian" runat=’

server’ Text=’<%# DataBinder.Eval(Container.DataItem,"DG_DanJian")%>’

onkeyup="javascript:DoCal()" /> <asp:RegularExpressionValidator id="revS2" runat="server"

ControlToValidate="DanJian" ErrorMessage="must be numeric" ValidationExpression="^\d+

(\.\d*)?$" /> </ItemTemplate> </asp:TemplateColumn> <asp:TemplateColumn HeaderText="

金额"> <ItemTemplate> <asp:TextBox id="JinE" runat=’server’ Text=’<%# DataBinder.Eval

(Container.DataItem,"DG_JinE")%>’ /> </ItemTemplate> </asp:TemplateColumn><script

language="javascript"> function DoCal() {  var e = event.srcElement;  var row =

e.parentNode.parentNode;  var txts = row.all.tags("INPUT");  if (!txts.length ||

txts.length < 3)   return;  var q = txts[txts.length-3].value;  var p = txts

[txts.length-2].value;  if (isNaN(q) || isNaN(p))   return;  q = parseInt(q);  p =

parseFloat(p);  txts[txts.length-1].value = (q * p).toFixed(2); } </script> 24.datagrid

选定比较底下的行时,为什么总是刷新一下,然后就滚动到了最上面,刚才选定的行因屏幕的关系就看

不到了。page_load page.smartNavigation=true    25.在Datagrid中修改数据,当点击编辑键时,

数据出现在文本框中,怎么控制文本框的大小 ? private void DataGrid1_ItemDataBound(obj

sender,DataGridItemEventArgs e) {  for(int i=0;i<e.Item.Cells.Count-1;i++)   if

(e.Item.ItemType==ListItemType.EditType)   {    e.Item.Cells[i].Attributes.Add

("Width", "80px")   } }    26.对话框 private static string ScriptBegin = "<script

language=\"JavaScript\">"; private static string ScriptEnd = "</script>"; public static

void ConfirmMessageBox(string PageTarget,string Content) {  string ConfirmContent="var

retValue=window.confirm(’"+Content+"’);"+"if(retValue){window.location=’"+PageTarget+"’;}";

 ConfirmContent=ScriptBegin + ConfirmContent + ScriptEnd;  Page ParameterPage = (Page)

System.Web.HttpContext.Current.Handler;  ParameterPage.RegisterStartupScript

("confirm",ConfirmContent);  //Response.Write(strScript); }    27. 将时间格式化:string

aa=DateTime.Now.ToString("yyyy年MM月dd日"); 1.1 取当前年月日时分秒

currentTime=System.DateTime.Now; 1.2 取当前年 int 年= DateTime.Now.Year;    1.3 取当前月

int 月= DateTime.Now.Month;    1.4 取当前日 int 日= DateTime.Now.Day;    1.5 取当前时

int 时= DateTime.Now.Hour;    1.6 取当前分 int 分= DateTime.Now.Minute;    1.7 取当前秒

int 秒= DateTime.Now.Second;    1.8 取当前毫秒 int 毫秒= DateTime.Now.Millisecond;   

28.自定义分页代码: 先定义变量 : public static int pageCount; //总页面数 public static

int curPageIndex=1; //当前页面    下一页: if(DataGrid1.CurrentPageIndex <

(DataGrid1.PageCount - 1)) {  DataGrid1.CurrentPageIndex += 1;  curPageIndex+=1; } bind

(); // DataGrid1数据绑定函数    上一页: if(DataGrid1.CurrentPageIndex >0) {  

DataGrid1.CurrentPageIndex += 1;  curPageIndex-=1; } bind(); // DataGrid1数据绑定函数   

直接页面跳转: int a=int.Parse(JumpPage.Value.Trim());//JumpPage.Value.Trim()为跳转值 if(a

<DataGrid1.PageCount) {  this.DataGrid1.CurrentPageIndex=a; } bind(); 29.DataGrid使用:

添加删除确认: private void DataGrid1_ItemCreated(object sender,

System.Web.UI.WebControls.DataGridItemEventArgs e) {  foreach(DataGridItem di in

this.DataGrid1.Items)  {   if

(di.ItemType==ListItemType.Item||di.ItemType==ListItemType.AlternatingItem)   {    

((LinkButton)di.Cells[8].Controls[0]).Attributes.Add("onclick","return confirm(’确认删除此

项吗?’);");   }  } }    样式交替: ListItemType itemType = e.Item.ItemType; if

(itemType == ListItemType.Item ) {  e.Item.Attributes["onmouseout"] =

"javascript:this.style.backgroundColor=’#FFFFFF’;";  e.Item.Attributes["onmouseover"] =

"javascript:this.style.backgroundColor=’#d9ece1’;cursor=’hand’;" ; } else if( itemType ==

ListItemType.AlternatingItem) {  e.Item.Attributes["onmouseout"] =

"javascript:this.style.backgroundColor=’#a0d7c4’;";  e.Item.Attributes["onmouseover"] =

"javascript:this.style.backgroundColor=’#d9ece1’;cursor=’hand’;" ; }    添加一个编号列:

DataTable dt= c.ExecuteRtnTableForAccess(sqltxt); //执行sql返回的DataTable DataColumn

dc=dt.Columns.Add("number",System.Type.GetType("System.String")); for(int i=0;i<

dt.Rows.Count;i++) {  dt.Rows[i]["number"]=(i+1).ToString(); } DataGrid1.DataSource=dt;

DataGrid1.DataBind();   DataGrid1中添加一个CheckBox,页面中添加一个全选框 private void

CheckBox2_CheckedChanged(object sender, System.EventArgs e) {  foreach(DataGridItem

thisitem in DataGrid1.Items)  {   ((CheckBox)thisitem.Cells[0].Controls

[1]).Checked=CheckBox2.Checked;  } }    将当前页面中DataGrid1显示的数据全部删除 foreach

(DataGridItem thisitem in DataGrid1.Items) {  if(((CheckBox)thisitem.Cells[0].Controls

[1]).Checked)  {   string strloginid= DataGrid1.DataKeys[thisitem.ItemIndex].ToString();

  Del (strloginid); //删除函数  } }    30.当文件在不同目录下,需要获取数据库连接字符

串(如果连接字符串放在Web.config,然后在Global.asax中初始化) 在Application_Start中添加以下

代码: Application["ConnStr"]

=this.Context.Request.PhysicalApplicationPath+ConfigurationSettings.    AppSettings

["ConnStr"].ToString();    31. 变量.ToString() 字符型转换 转为字符串 12345.ToString

("n"); //生成 12,345.00 12345.ToString("C"); //生成 ¥12,345.00 12345.ToString("e"); //生成

1.234500e+004 12345.ToString("f4"); //生成 12345.0000 12345.ToString("x"); //生成 3039 (16

进制) 12345.ToString("p"); //生成 1,234,500.00%    32、变量.Substring(参数1,参数2); 截取

字串的一部分,参数1为左起始位数,参数2为截取几位。 如:string s1 = str.Substring(0,2); 33.

在自己的网站上登陆其他网站:(如果你的页面是通过嵌套方式的话,因为一个页面只能有一个FORM,这

时可以导向另外一个页面再提交登陆信息) <SCRIPT language="javascript"> <!--  function

gook(pws)  {   frm.submit();  } //--> </SCRIPT> <body leftMargin="0" topMargin="0"

onload="javascript:gook()" marginwidth="0" marginheight="0"> <form name="frm" action="

http://220.194.55.68:6080/login.php?retid=7259 " method="post"> <tr> <td> <input

id="f_user" type="hidden" size="1" name="f_user" runat="server"> <input id="f_domain"

type="hidden" size="1" name="f_domain" runat="server"> <input class="box" id="f_pass"

type="hidden" size="1" name="pwshow" runat="server"> <INPUT id="lng" type="hidden"

maxLength="20" size="1" value="5" name="lng"> <INPUT id="tem" type="hidden" size="1"

value="2" name="tem"> </td> </tr> </form>   文本框的名称必须是你要登陆的网页上的名

称,如果源码不行可以用vsniffer 看看。   下面是获取用户输入的登陆信息的代码: string name;

name=Request.QueryString["EmailName"]; try {  int a=name.IndexOf("@",0,name.Length);  

f_user.Value=name.Substring(0,a);  f_domain.Value=name.Substring(a+1,name.Length-(a+1));

 f_pass.Value=Request.QueryString["Psw"]; } catch {  Script.Alert("错误的邮箱!");  

Server.Transfer("index.aspx"); }

Wednesday, November 5, 2008

使用HttpContext的User属性来实现用户验证

HttpContext类包含了个别HTTP请求的所有特定HTTP信息。这个示例主要是讲如何使用HttpContext类中的User属性来实现用户验证!

用户验证是大部分ASP.NET WEB应用程序都要用到的,它在整个应用程序中占有很重要的地位,在.NET中,包含了很多种用户验证方式,如众所周知的PassPort认证,Windows认证,Form认证等等,可是这些都很难满足我们在实际应用中的需求,以致于很多朋友都是自己另外写代码来实现自己需要的功能,这让我们在安全性以及系统效率上要考虑很多。

实际上,ASP.NET中内置的用户验证机制功能非常强大,同时也具有非常好的的可扩展性,它能够在HttpContext对象中生成一个名为 User的属性,这个属性能让我们访问各种信息,包括用户是否已验证,用户的类型,用户名等等,我们还可以对该属性的功能进性扩展,以实现我们的要求。

分配给HttpContext.User的对象必须实现IPrincipal接口,而Iprincipal定义的属性之一是Identity,它必须实现Iidentity接口。因为,我们只要写了实现这两个接口的类,就可以在这些类中添加任何我们所需要的功能。

首先,我们创建一个项目,然后创建两个实现Iprincipal和Iidentity的类(分别放在相应的cs文件中),分另为MyIprincipal和MyIdentity

Code for MyIprincipal.cs

using System.Collections;//
///
/// Summary description for MyIprincipal
///

public class MyIprincipal : System.Security.Principal.IPrincipal
{
private System.Security.Principal.IIdentity identity;
private ArrayList roleList;

public MyIprincipal(string userID, string passwrod)
{
identity = new MyIdentity(userID, passwrod);
if (identity.IsAuthenticated)
{
roleList = new ArrayList();
roleList.Add("Admin");
}
}

public ArrayList RoleList
{
get
{
return roleList;
}
}

public System.Security.Principal.IIdentity Identity
{
get
{
return identity;
}

set
{
identity = value;
}
}

public bool IsInRole(string role)
{
return roleList.Contains(role);
}

public MyIprincipal()
{
//
// TODO: Add constructor logic here
//
}
}

*******************************

Code for MyIdentity.cs

///
/// Summary description for MyIdentity
///

public class MyIdentity : System.Security.Principal.IIdentity
{
private string userID;
private string password;

public MyIdentity( string currentUserID,string currentPassword)
{
userID = currentUserID;
password = currentPassword;
}

private bool CanPass()
{
if (userID == "kevin" && password == "kevin")
{
return true;
}
else
{
return false;
}
}

public string Name
{
get
{
return userID;
}
}

public string Password
{
get
{
return password;
}

set
{
password = value;
}
}

public bool IsAuthenticated
{
get
{
return CanPass();
}
}

public string AuthenticationType
{
get
{
return null;
}
}

public MyIdentity()
{
//
// TODO: Add constructor logic here
//
}
}

********************
Code for Default.aspx


<body>
<form id="form1" runat="server">
<div>
<center>
<table>
<tr>
<td>Name</td>
<td>
<asp:TextBox ID="txtName"

runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Password</td>
<td>
<asp:TextBox ID="txtPwd"

runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<asp:Button ID="btnSubmit" runat="server"

Text="Submit"
onclick="btnSubmit_Click" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="lblMsg" Text=""

runat="server"></asp:Label>
</td>
</tr>
</table>
</center>
</div>
</form>
</body>

*************************

Code for Default.aspx.cs

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnSubmit_Click(object sender, EventArgs e)
{
MyIprincipal pri = new MyIprincipal(txtName.Text.ToString(), txtPwd.Text.ToString());
if (pri.Identity.IsAuthenticated)
{
this.lblMsg.Text = "OK";
}
else
{
lblMsg.Text = "No";
}
}
}

Tuesday, November 4, 2008

Create a discretional string(C#)

Here is a interview exam, I write it with RanDom class. OK Let's go!!

namespace StringBuildTest
{
class StringBuildT
{
string[] str = new string[] { "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"};
StringBuilder SB = new StringBuilder();
Random rd = new Random();
string strOut = "";//length is 1000
public void DsiplayString()
{
for (int i = 0; i < 1000; i++)
{
SB.Append(str[(int)rd.Next(26)].ToString());
}
strOut = SB.ToString();
Console.WriteLine(strOut);
}
}

class Program
{
static void Main(string[] args)
{
StringBuildT sbt = new StringBuildT();
sbt.DsiplayString();
}
}
}

Post和Get的区别(兼谈页面间传值的方式)

I read a blog about transfer data between pages with post or get method, I think this is a good article, so past it on my blog. There's a very funny method maybe you want to focus--Context.Items
which is similar with Session.
OK,let's go!

从一个页面转向另一个页面的请求方式有两种,Post和Get.
如果从原理上来探究他们的区别,涉及到Http传输协议的细节,本文不加探究,只讨论一下表象。

所有的人都知道如下区别:
1.Post传输数据时,不需要在URL中显示出来,而Get方法要在URL中显示。
2.Post传输的数据量大,可以达到2M,而Get方法由于受到URL长度的限制,只能传递大约1024字节.
3.Post顾名思义,就是为了将数据传送到服务器段,Get就是为了从服务器段取得数据.而Get之所以也能传送数据,只是用来设计告诉服务器,你到底需要什么样的数据.Post的信息作为http请求的内容,而Get是在Http头部传输的。

我们的form表单的method方法,有两个,post,get.它在页面传值的时候的区别也就是上面提到的三点.

先来看一下post方法.
这个方法在asp时代应该跟程序员打交道很多的,因为那时候没有现在的ViewState,每个页面要恢复原来的状态,都要将页面Post给自身,然后挨个取值,重新赋值.现在这些琐碎的事情都让ViewState代劳了.所以将页面post给自身的动作,在某种程度上已经被Asp.net的程序员们忘却了,所以Post也就被大部分的忽视了,这就是技术进步的双刃剑,带来方便的同时,蒙上你的眼睛。

ViewState必须包含在<form runat="server">的窗体下,而只要包含了"runat="server""的标志,就甭想Post到其他页面中去,为什么?老盖说,我的ViewState是保存当前页面状态的,你要转到其他页面,他说,不行,**不认识的参数.如果想Post一个窗体,咋办?有四种方式可供选择.

1.在页面上新建一个form,不要加上runat="server"的标志,当然在这个窗体下的控件也就不用想用Viewstate来传值了.当在其他有runat="server"的窗体的中的按钮事件中,手动调用新建form的submit() 函数.

传送页面代码如下:

<!--html代码-->
<form id="Form1" method="post" runat="server">
<input id="btnTransfer" type="button" onclick="post();" runat="server">
<input type="text" runat="server" id="SourceData">
</form>
<form id="forPost" method="post">
<input type="text" runat="server" id="SourceData2">
</form>

<!--Script代码-->
<script language="javascript">
function post()
{
forPost.action="DestinationPage.aspx";
forPost.submit();
}
</script>


接收页面
string a=Request.Form["SourceData2"].ToString();


2.通过Session取值,在一个页面中赋值,在其他页面中共享,这个方式也被广泛应用,个人不倾向于用这种方式,我怕造成Session值的混乱无序,Session用来存一些公共的东西已经累得够呛了。

3.通过Context传值,在传送页面之前,将需要传递到其他页面的值存在Context中。示例代码如下:

传送页面

//点击某个button时触发
private void btnTransfer_ServerClick(object sender, EventArgs e)
{
Context.Items["SourceData"]=SourceData.Value;
Server.Transfer("DestinationPage.aspx");
}


接收页面

string a=Context.Items["SourceData"].ToString();


4.通过Server.Transfer的方式。
这个方式在方法三种已经用到了,不过可以在调用页面为要传递到被调用页面的值创建属性(当然可以直接将它设成public),这样就可以在其他页面访问了。

传送页面

//要传送的值
private
System.Web.UI.HtmlControls.HtmlInputText SourceData;

public string getSourceData
{
get
{
return SourceData.Value;
}
}

//传送页面
Server.Transfer("DestinationPage.aspx");


接收页面

private SourceClass sourcePage;

sourcePage=(SourceClass)Context.Handler;
string aa=sourcePage.getSourceData;


以上就是Post的在不同页面传递数据的方式了。
下面是get方法
我常用的是 传送页面

string aa=SourceData.Value;
string bb=SourceData.Value;

string url="DestinationPage.aspx?parameter1="+aa+"¶meter2="+bb;
Response.Redirect(url,false);


接收页面

string aa=Request.QueryString["parameter1"].ToString();
string bb=Request.QueryString["parameter2"].ToString();


至于 Response.Redirect(url,false)里的false都是Response.End()这个方法惹的祸,老盖说,写成false就好了,因为默认是true。我都转向其他页面了,还不让我终止原来页面的响应,BT!

方法继承

第一等的面向对象机制为C#的方法引入了virtual,override,sealed,abstract四种修饰符来提供不同的继承需求。类的虚方法是可以在该类的继承自类中改变其实现的方法,当然这种改变仅限于方法体的改变,而非方法头(方法声明)的改变。被子类改变的虚方法必须在方法头加上override来表示。当一个虚方法被调用时,该类的实例--亦即对象的运行时类型(run-time type)来决定哪个方法体被调用。我们看下面的例子:

using System;
class Parent
{
public void F() { Console.WriteLine("Parent.F"); }
public virtual void G() { Console.WriteLine("Parent.G"); }
}
class Child: Parent
{
new public void F() { Console.WriteLine("Child.F"); }
public override void G() { Console.WriteLine("Child.G"); }
}
class Test
{
static void Main()
{
Child b = new Child();
Parent a = b;
a.F();
b.F();
a.G();
b.G();
}
}

程序经编译后执行输出:

Parent.F
Child.F
Child.G
Child.G

我们可以看到class Child中F()方法的声明采取了重写(new)的办法来屏蔽class Parent中的非虚方法F()的声明。而G()方法就采用了覆盖(override)的办法来提供方法的多态机制。需要注意的是重写(new)方法和覆盖(override)方法的不同,从本质上讲重写方法是编译时绑定,而覆盖方法是运行时绑定。值得指出的是虚方法不可以是静态方法--也就是说不可以用static和virtual同时修饰一个方法,这由它的运行时类型辨析机制所决定。override必须和virtual配合使用,当然也不能和static同时使用。

那么我们如果在一个类的继承体系中不想再使一个虚方法被覆盖,我们该怎样做呢?答案是sealed override (密封覆盖),我们将sealed和override同时修饰一个虚方法便可以达到这种目的:sealed override public void F()。注意这里一定是sealed和override同时使用,也一定是密封覆盖一个虚方法,或者一个被覆盖(而不是密封覆盖)了的虚方法。密封一个非虚方法是没有意义的,也是错误的。看下面的例子:

//sealed.cs
// csc /t:library sealed.cs
using System;
class Parent
{
public virtual void F()
{
Console.WriteLine("Parent.F");
}
public virtual void G()
{
Console.WriteLine("Parent.G");
}
}
class Child: Parent
{
sealed override public void F()
{
Console.WriteLine("Child.F");
}
override public void G()
{
Console.WriteLine("Child.G");
}
}
class Grandson: Child
{
override public void G()
{
Console.WriteLine("Grandson.G");
}
}

抽象(abstract)方法在逻辑上类似于虚方法,只是不能像虚方法那样被调用,而只是一个接口的声明而非实现。抽象方法没有类似于{…}这样的方法实现,也不允许这样做。抽象方法同样不能是静态的。含有抽象方法的类一定是抽象类,也一定要加abstract类修饰符。但抽象类并不一定要含有抽象方法。继承含有抽象方法的抽象类的子类必须覆盖并实现(直接使用override)该方法,或者组合使用abstract override使之继续抽象,或者不提供任何覆盖和实现。后两者的行为是一样的。看下面的例子:

//abstract1.cs
// csc /t:library abstract1.cs
using System;
abstract class Parent
{
public abstract void F();
public abstract void G();
}
abstract class Child: Parent
{
public abstract override void F();
}
abstract class Grandson: Child
{
public override void F()
{
Console.WriteLine("Grandson.F");
}
public override void G()
{
Console.WriteLine("Grandson.G");
}
}

抽象方法可以抽象一个继承来的虚方法,我们看下面的例子:

//abstract2.cs
// csc /t:library abstract2.cs
using System;
class Parent
{
public virtual void Method()
{
Console.WriteLine("Parent.Method");
}
}
abstract class Child: Parent
{
public abstract override void Method();
}
abstract class Grandson: Child
{
public override void Method()
{
Console.WriteLine("Grandson.Method");
}
}

归根结底,我们抓住了运行时绑定和编译时绑定的基本机理,我们便能看透方法呈现出的种种overload,virtual,override,sealed,abstract等形态,我们才能运用好方法这一利器!

Use UpdatePanel to implement the ajax effect(C#)

this is a sample about how to use UpdatePanel and ScriptManager to implement ajax performance.
OK, let's go!

Client Code:
<body>
<form id="form1" runat="server">
<div>
<center>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering=true>
</asp:ScriptManager>
<asp:DropDownList ID="ddl1" runat="server" AutoPostBack="true" Width="170px" OnSelectedIndexChanged="ddl1_SelectedIndexChanged">
<asp:ListItem>One</asp:ListItem>
<asp:ListItem>Two</asp:ListItem>
<asp:ListItem>Three</asp:ListItem>
<asp:ListItem>Four</asp:ListItem>
<asp:ListItem>Five</asp:ListItem>
</asp:DropDownList>
<br /><br /><br />

</center>
<asp:updatepanel runat="server" ID="updatepanel1">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddl1" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<asp:Label ID="lbl1" runat=server Text="" ></asp:Label>
</ContentTemplate>
</asp:updatepanel>
</div>
</form>
</body>

Code Behind:

protected void ddl1_SelectedIndexChanged(object sender, EventArgs e)
{
this.lbl1.Text = "You selected :" + ddl1.SelectedValue.ToString();
}

Attention: You have to put ScriptManager in the front of the all controls when you use it, or you will get a error, and you can try it to put it at last code.