建网工具:vs.net sql2005
建网用途:为学校做一个能让教师发布作业题,查看学生作业并打分;学生能下载作业题,上传作业答案;
建网用到技术:首先会用.net的C#语言编程;利用模板建立网站界面;文件的上传,下载;文件夹的创建,查找,删除;会用 Login,Creatuserwizard 控件做用户登陆;数据库连接,创建数据,查找数据;
网站实现过程中的重要代码:
一. 在利用模板时,可将asp的代码直接拷来用,但你会发现不能用asp.net的控件了.其实它需要:
<
form
id
="form1"
runat
="server"
>
这样就能在asp中使用.net控件了.
二. 文件的上传,要用到FileUpload控件,它的代码为:
protected
void
Button1_Click(
object
sender, EventArgs e)
... {
try
...{
if (FileUpload1.PostedFile != null)
...{
string filename = FileUpload1.PostedFile.FileName;
int filelength = FileUpload1.PostedFile.ContentLength;
string sMsg = null;
if (filelength > (10 * 1024 * 1024))
...{
sMsg = filename + "文件的大小超过了10兆了!";
}
else
...{
filename = filename.Substring(filename.LastIndexOf(@""));
string spath = Server.MapPath(@".ServerData");
spath += Profile.Rname + @"TeaUpFile";
if (Directory.Exists(spath) == false)
...{
Directory.CreateDirectory(spath);
}
FileUpload1.PostedFile.SaveAs(spath + filename);
sMsg = "成功上传文件:" + filename + "文件大小:" + filelength + "字节" + "文件类型:" + FileUpload1.PostedFile.ContentType;
}
Response.Write("<script language='JavaScript'>window.alert('" + sMsg + "');</script>");
}
}
catch ...{ }
}
... {
try
...{
if (FileUpload1.PostedFile != null)
...{
string filename = FileUpload1.PostedFile.FileName;
int filelength = FileUpload1.PostedFile.ContentLength;
string sMsg = null;
if (filelength > (10 * 1024 * 1024))
...{
sMsg = filename + "文件的大小超过了10兆了!";
}
else
...{
filename = filename.Substring(filename.LastIndexOf(@""));
string spath = Server.MapPath(@".ServerData");
spath += Profile.Rname + @"TeaUpFile";
if (Directory.Exists(spath) == false)
...{
Directory.CreateDirectory(spath);
}
FileUpload1.PostedFile.SaveAs(spath + filename);
sMsg = "成功上传文件:" + filename + "文件大小:" + filelength + "字节" + "文件类型:" + FileUpload1.PostedFile.ContentType;
}
Response.Write("<script language='JavaScript'>window.alert('" + sMsg + "');</script>");
}
}
catch ...{ }
}
当保存文件时 用win系统带的保存控件的代码:
protected
void
Savefile(
string
filename)
... {
//string filename = "a.txt";
if (filename != "")
...{
//string path = Server.MapPath(filename);
string path = Server.MapPath(@".ServerData");
path += this.DropDownList1.SelectedValue+@" eaupfile"+filename;
System.IO.FileInfo file = new System.IO.FileInfo(path);
if (file.Exists)
...{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.Filter.Close();
Response.WriteFile(file.FullName);
Response.End();
}
else
...{
Response.Write("This file does not exist.");
}
}
}
... {
//string filename = "a.txt";
if (filename != "")
...{
//string path = Server.MapPath(filename);
string path = Server.MapPath(@".ServerData");
path += this.DropDownList1.SelectedValue+@" eaupfile"+filename;
System.IO.FileInfo file = new System.IO.FileInfo(path);
if (file.Exists)
...{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.Filter.Close();
Response.WriteFile(file.FullName);
Response.End();
}
else
...{
Response.Write("This file does not exist.");
}
}
}
三. 用.net2005自带的用户创建控件用户登陆控件
创建自定义的项时
protected
void
CreateUserWizard1_CreatedUser(
object
sender, EventArgs e)
... {
ProfileCommon p = (ProfileCommon)ProfileCommon.Create(CreateUserWizard1.UserName, true);
// Populate some Profile properties off of the create user wizard
p.Rname = ((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Rname")).Text;
p.Gender = ((DropDownList)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Gender")).SelectedValue;
p.age = Int32.Parse(((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Rname")).Text);
// Save the profile - must be done since we explicitly created this profile instance
p.Save();
}
... {
ProfileCommon p = (ProfileCommon)ProfileCommon.Create(CreateUserWizard1.UserName, true);
// Populate some Profile properties off of the create user wizard
p.Rname = ((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Rname")).Text;
p.Gender = ((DropDownList)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Gender")).SelectedValue;
p.age = Int32.Parse(((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Rname")).Text);
// Save the profile - must be done since we explicitly created this profile instance
p.Save();
}
调用时为:
Profile.Rname;
注意的是 要想用ProfileCommon类 还要改个值在web.config中 <profile enabled="true">
<
properties
>
< add name ="Rname" type ="string" />
<!-- <add name="Gender" type="string"/>
<add name="Age" type="Int32"/> -->
</ properties >
</ profile >
< add name ="Rname" type ="string" />
<!-- <add name="Gender" type="string"/>
<add name="Age" type="Int32"/> -->
</ properties >
</ profile >
想这个时 头都大了 才想出来的 ^_^
四.当给用户添加权限时 它的代码为:
protected
void
AddUserToRole(
string
newUserName,
string
roleInformation)
... {
switch (roleInformation)
...{
case ("0"):
Roles.AddUserToRole(newUserName, "Administrator");
Roles.AddUserToRole(newUserName, "Teacher");
break;
case ("1"):
Roles.AddUserToRole(newUserName, "Teacher");
break;
default:
Roles.AddUserToRole(CreateUserWizard1.UserName, "Teacher");
break;
}
}
protected void CreateUserWizard1_FinishButtonClick( object sender, WizardNavigationEventArgs e)
... {
//if (Page.User.IsInRole("Administrator"))
//{
AddUserToRole(CreateUserWizard1.UserName, GroupName.SelectedValue);
//}
//Panel1.Visible = true;
}
private string GetDefaultRoleForNewUser()
... {
if (ConfigurationManager.AppSettings["DefaultRoleForNewUser"] == null)
...{
throw (new Exception("DefaultRoleForNewUser was not been defined in the appsettings section of config"));
}
else
...{
string defaultRole = ConfigurationManager.AppSettings["DefaultRoleForNewUser"];
if (string.IsNullOrEmpty(defaultRole))
...{
throw (new Exception("DefaultRoleForNewUser does not contain a default value"));
}
else
...{
if (string.Compare(defaultRole, "3") < 0 && string.Compare(defaultRole, "0") >= 0)
...{
return (ConfigurationManager.AppSettings["DefaultRoleForNewUser"]);
}
else
...{
throw (new ArgumentException("DefaultRoleForNewUser defined in the appsettings has to be between 0 and 2"));
}
}
}
}
... {
switch (roleInformation)
...{
case ("0"):
Roles.AddUserToRole(newUserName, "Administrator");
Roles.AddUserToRole(newUserName, "Teacher");
break;
case ("1"):
Roles.AddUserToRole(newUserName, "Teacher");
break;
default:
Roles.AddUserToRole(CreateUserWizard1.UserName, "Teacher");
break;
}
}
protected void CreateUserWizard1_FinishButtonClick( object sender, WizardNavigationEventArgs e)
... {
//if (Page.User.IsInRole("Administrator"))
//{
AddUserToRole(CreateUserWizard1.UserName, GroupName.SelectedValue);
//}
//Panel1.Visible = true;
}
private string GetDefaultRoleForNewUser()
... {
if (ConfigurationManager.AppSettings["DefaultRoleForNewUser"] == null)
...{
throw (new Exception("DefaultRoleForNewUser was not been defined in the appsettings section of config"));
}
else
...{
string defaultRole = ConfigurationManager.AppSettings["DefaultRoleForNewUser"];
if (string.IsNullOrEmpty(defaultRole))
...{
throw (new Exception("DefaultRoleForNewUser does not contain a default value"));
}
else
...{
if (string.Compare(defaultRole, "3") < 0 && string.Compare(defaultRole, "0") >= 0)
...{
return (ConfigurationManager.AppSettings["DefaultRoleForNewUser"]);
}
else
...{
throw (new ArgumentException("DefaultRoleForNewUser defined in the appsettings has to be between 0 and 2"));
}
}
}
}
就是实例拿来用的,看看你就明白了.
当用到创建控件时 要配置它的属性 即web.config:
<
system
.web
>
< processModel autoConfig ="true" />
< httpHandlers />
< membership >
< providers >
< add name ="AspNetSqlMembershipProvider"
type ="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName ="LocalSqlServer"
enablePasswordRetrieval ="false"
enablePasswordReset ="true"
requiresQuestionAndAnswer ="true"
applicationName ="/"
requiresUniqueEmail ="false"
passwordFormat ="Hashed"
maxInvalidPasswordAttempts ="5"
minRequiredPasswordLength ="6"
minRequiredNonalphanumericCharacters ="0"
passwordAttemptWindow ="10"
passwordStrengthRegularExpression ="" />
</ providers >
</ membership >
< profile >
< providers >
< add name ="AspNetSqlProfileProvider" connectionStringName ="LocalSqlServer" applicationName ="/"
type ="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</ providers >
</ profile >
< roleManager >
< providers >
< add name ="AspNetSqlRoleProvider" connectionStringName ="LocalSqlServer" applicationName ="/"
type ="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
< add name ="AspNetWindowsTokenRoleProvider" applicationName ="/"
type ="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</ providers >
</ roleManager >
</ system.web >
< processModel autoConfig ="true" />
< httpHandlers />
< membership >
< providers >
< add name ="AspNetSqlMembershipProvider"
type ="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName ="LocalSqlServer"
enablePasswordRetrieval ="false"
enablePasswordReset ="true"
requiresQuestionAndAnswer ="true"
applicationName ="/"
requiresUniqueEmail ="false"
passwordFormat ="Hashed"
maxInvalidPasswordAttempts ="5"
minRequiredPasswordLength ="6"
minRequiredNonalphanumericCharacters ="0"
passwordAttemptWindow ="10"
passwordStrengthRegularExpression ="" />
</ providers >
</ membership >
< profile >
< providers >
< add name ="AspNetSqlProfileProvider" connectionStringName ="LocalSqlServer" applicationName ="/"
type ="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</ providers >
</ profile >
< roleManager >
< providers >
< add name ="AspNetSqlRoleProvider" connectionStringName ="LocalSqlServer" applicationName ="/"
type ="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
< add name ="AspNetWindowsTokenRoleProvider" applicationName ="/"
type ="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</ providers >
</ roleManager >
</ system.web >
其他的:
为Checkboxlist添加节点:
private
void
UpItem()
... {
string mpath = Server.MapPath(@".ServerData");
mpath += Profile.Rname+@"TeaUpFile";
string[] file = Directory.GetFiles(mpath, "*.*");
foreach (string dir in file)
...{
this.CheckBoxList1.Items.Add(new ListItem(dir.Substring(mpath.Length)));
}
}
... {
string mpath = Server.MapPath(@".ServerData");
mpath += Profile.Rname+@"TeaUpFile";
string[] file = Directory.GetFiles(mpath, "*.*");
foreach (string dir in file)
...{
this.CheckBoxList1.Items.Add(new ListItem(dir.Substring(mpath.Length)));
}
}
限制登陆用户的权限问题用代码:
<
location
path
="teachuse.aspx"
>
< system .web >
< authorization >
< deny users ="?" />
< allow users ="*" />
</ authorization >
</ system.web >
</ location > //在web.config中
< system .web >
< authorization >
< deny users ="?" />
< allow users ="*" />
</ authorization >
</ system.web >
</ location > //在web.config中
for
(
int
i
=
0
; i
<
CheckBoxList1.Items.Count; i
++
)
... {
if (CheckBoxList1.Items[i].Selected)
...{
this.TextBox1.Text += CheckBoxList1.Items[i].Value + " ";
}
}
... {
if (CheckBoxList1.Items[i].Selected)
...{
this.TextBox1.Text += CheckBoxList1.Items[i].Value + " ";
}
}
try
...
{
if (Directory.Exists(spath) == false)
Directory.CreateDirectory(spath);
if (!Directory.Exists(spath + @" emp.txt"))
...{
File.Delete(spath + @" emp.txt");
}
StreamWriter stmw = new StreamWriter(spath + @" emp.txt", true, System.Text.Encoding.Default);
stmw.Write(this.TextBox1.Text);
stmw.Close();
}
catch
... {
}
if (Directory.Exists(spath) == false)
Directory.CreateDirectory(spath);
if (!Directory.Exists(spath + @" emp.txt"))
...{
File.Delete(spath + @" emp.txt");
}
StreamWriter stmw = new StreamWriter(spath + @" emp.txt", true, System.Text.Encoding.Default);
stmw.Write(this.TextBox1.Text);
stmw.Close();
}
catch
... {
}
if
(
this
.IsPostBack
==
false
)
... {
this.DropDownList1.DataBind();
this.DropDownList1.Items.Insert(0, new ListItem("", ""));
}
... {
this.DropDownList1.DataBind();
this.DropDownList1.Items.Insert(0, new ListItem("", ""));
}
private
bool
Updata_name()
... {
bool mb = true;
string rlname = ((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Rname")).Text;
try
...{
DataSet dataset1 = new DataSet();
string connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ Server.MapPath(@".dbRealnameDB.mdb")
+ ";Mode=Share Deny None;Persist Security Info=False";
OleDbConnection conn = new OleDbConnection(connstr);
conn.Open();
string sql = "select * from [MycreatDB] ";
OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);
OleDbCommandBuilder builder = new OleDbCommandBuilder(da);
da.Fill(dataset1, "MycreatDB");
DataRow newRow = dataset1.Tables["MycreatDB"].NewRow();
newRow["realname"] = rlname;
dataset1.Tables["MycreatDB"].Rows.Add(newRow);
da.Update(dataset1, "MycreatDB");//
conn.Close();
return mb;
}
catch
...{
//this.Response.Write("<script language='javascript'>alert('数据库连接异常!!')</script>");
return mb = false;
}
}
... {
bool mb = true;
string rlname = ((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Rname")).Text;
try
...{
DataSet dataset1 = new DataSet();
string connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ Server.MapPath(@".dbRealnameDB.mdb")
+ ";Mode=Share Deny None;Persist Security Info=False";
OleDbConnection conn = new OleDbConnection(connstr);
conn.Open();
string sql = "select * from [MycreatDB] ";
OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);
OleDbCommandBuilder builder = new OleDbCommandBuilder(da);
da.Fill(dataset1, "MycreatDB");
DataRow newRow = dataset1.Tables["MycreatDB"].NewRow();
newRow["realname"] = rlname;
dataset1.Tables["MycreatDB"].Rows.Add(newRow);
da.Update(dataset1, "MycreatDB");//
conn.Close();
return mb;
}
catch
...{
//this.Response.Write("<script language='javascript'>alert('数据库连接异常!!')</script>");
return mb = false;
}
}