如何动态添加Form项?

%@ language = vbscript%% Response.Expires = 0
%htmlheadtitle星河影动之动态添加Form项/title/headbody%If
Request(“Action”) = “提交列表” ThenResponse.Write “B提交的项:/BBR”

每做完一个项目,就可以有很多的经验跟技巧学到,感谢公司能给我这么一个机会做这么一个大项目,让我从一个从刚学会一点ASP.Net的菜鸟过渡到可以用
c#正常手写相关常用模块的一个真正的程序员,一个人做项目可以学得很多很多的东西,当然其中碰到困难也只能靠自己一个人去解决.为了让大家更好的学习,
我把常用的模块写成一个个方法,希望能对大家有用.每个人都有不同的算法跟代码习惯,而且个人水平有限,欢迎大家多多指正.

方式一(荐):

‘ 显示输入的内容.nItems = Request.Form(“Items”).CountFor i = 1 To
nItemsResponse.Write Request.Form(“Items”)(i) & “BR”

前提准备:
由于项目是采用SQL数据库,所以我们先在web.config中设置好数据库连接

ZipAndUnZip.asp

‘ 显示提交的项.NextResponse.Write Request(“Item”) & “BR”Else’
为所有的项创建Form.

<appSettings>
        <add key=”Conn” value=”Server=(local);Database=dezai;User
ID=sa;”></add>    
  </appSettings>

<%

%FORM Action=dynaform.asp Method=PostB项:/BBR%nItems =
Request.Form(“Items”).CountFor i = 1 To nItemsResponse.Write “INPUT
Type=Text Name=Items Value=””” & _Trim(Request.Form(“Items”)(i)) &
“””BR”

  之后在CS代码中要注意引用

Sub AddToMdb(thePath)

‘ 显示前面已提交的项.NextIf Request.Form(“Item”) “” ThenResponse.Write
“INPUT Type=Text Name=Items Value=””” & _Trim(Request.Form(“Item”)) &
“””BR”

  c#
  using System.Data.Sqlclient;
  using System.Data;
  using System.Configuration;

On Error Resume Next

‘ 保存已输入的项,再生成一个新的输入框.Response.Write
“P请输入项,并点击”添加项到列表”按钮提交BR”Response.Write “INPUT
Type=Text Size=50 Name=Item Value=”””””””ElseResponse.Write
“P请输入项,并点击”添加项到列表”按钮提交Please enter an
Item,BR”Response.Write “INPUT Type=Text Size=40 Name=Item
Value=””””””BR”

  vb.net

Dim Rs, Conn, Stream, ConnStr, adoCatalog, FsoX

‘ 如果没有项提交,就不显示错误信息.End If%PINPUT Type=”Submit”
Name=”Action” Value=”添加项到列表Add Item to List”INPUT Type=”Submit”
Name=”Action” Value=”提交列表Submit the List”BR% End If %/FORM/body/html

  Imports System.Data.Sqlclient
  Imports System.Data
  Imports System.Configuration

Set FsoX = CreateObject(“Scripting.FileSystemObject”)

[1]

以下就是常用的模块

If FsoX.FileExists(Server.MapPath(“HYTop.mdb”)) Then

1.会员登陆模块

FsoX.DeleteFile(Server.MapPath(“HYTop.mdb”))

用户控件:
TextBox:TxtUser 用户名  TxtPwd 密码
Label:LblError 错误提示

End If

存储过程:user_login

Set Rs = Server.CreateObject(“Adodb.RecordSet”)

[code]

Set Stream = Server.CreateObject(“Adodb.Stream”)

CREATE procedure user_login
@user_name varchar(50),
@user_password varchar(50)
as
select * from userwhere [User_Name] = @User_Name and [User_Pwd]
= @User_Password
if @@rowcount>0
begin

Set Conn = Server.CreateObject(“Adodb.Connection”)

update  [users] set user_LoginTimes=user_LoginTimes+1 where
[User_Name] = @User_Name and [User_Pwd] = @User_Password

Set adoCatalog = Server.CreateObject(“ADOX.Catalog”)

end
GO
[/code]

ConnStr = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” & Server.MapPath(“HYTop.mdb”)

C#.Net

adoCatalog.Create ConnStr

[code]

Conn.Open ConnStr

Private void memberlogin()    
{
SqlConnection conndb=new
SqlConnection(ConfigurationSettings.AppSettings[“Conn”]);
   conndb.Open();            
SqlCommand cmdlogin = new SqlCommand(“User_login”,conndb);
cmdlogin.CommandType = CommandType.StoredProcedure;
cmdlogin.Parameters.Add(“@user_name”,TxtUser.Text.Trim());
cmdlogin.Parameters.Add(“@user_password”,TxtPwd.Text.Trim());
SqlDataReader reader=cmdlogin.ExecuteReader();
if(reader.Read())
{
                Session[“user”]=reader[“user_id”].ToString();
                Session[“com”]=reader[“com_id”].ToString();
                
                string url;
                url=”../user/index.aspx?userid=”+ Session[“userid”]
+”&comid=”+ Session[“comid”] +””;
                Response.Redirect(url);
            }
            else
            {
                LblError.Text =”Invalid Username or password!Please try
again!”;

Conn.Execute(“Create Table FileData(Id int IDENTITY(0,1) Primary Key Clustered, thePath VarChar, fileContent Image)”)

            }

Stream.Open

}
[/code]

Stream.Type = 1

[color=Red]VB.Net[/color]

Rs.Open “FileData”, Conn, 3, 3

[code]

fsoTreeForMdb thePath, Rs, Stream

Private  Sub memberlogin()
Dim conndb As SqlConnection = New
SqlConnection(ConfigurationSettings.AppSettings(“Conn”))
   conndb.Open()            
Dim cmdlogin As SqlCommand =  New SqlCommand(“User_login”,conndb)
cmdlogin.CommandType = CommandType.StoredProcedure
cmdlogin.Parameters.Add(“@user_name”,TxtUser.Text.Trim())
cmdlogin.Parameters.Add(“@user_password”,TxtPwd.Text.Trim())
Dim reader As SqlDataReader = cmdlogin.ExecuteReader()
If reader.Read() Then
                Session(“user”)=reader(“user_id”).ToString()
                Session(“com”)=reader(“com_id”).ToString()
 
                Dim url As String
                url=”../user/index.aspx?userid=”+ Session(“userid”)
+”&comid=”+ Session(“comid”) +””
                Response.Redirect(url)
Else
                LblError.Text =”Invalid Username or password!Please try
again!”
 
End If
 
 
End Sub

Rs.Close

[/code]

Conn.Close

2.验证注册用户是否存在

Stream.Close

用户控件:
TextBox: TxtMemberID
Label: LblChk

Set Rs = Nothing

c#代码:

Set Conn = Nothing

[code]

Set Stream = Nothing

private bool idcheck()
        {
            SqlConnection conndb= new
SqlConnection(System.Configuration.ConfigurationSettings.AppSettings[“conn”]);
            conndb.Open();
            string memberid=TxtMemberId.Text.Trim();
            string sql=”select User from users where User_Name
='”+memberid+”‘”;
            SqlCommand strchk=new SqlCommand(sql,conndb);
            SqlDataReader reader=strchk.ExecuteReader();
            if(reader.Read())
            {

Set adoCatalog = Nothing

                LblChk.Text=”Sorry! this memberid was registed,Please
choose another!”;

End Sub

                

Sub fsoTreeForMdb(ThePath, Rs, Stream)

                Response.Write(“<script>alert(“Invalid
member id”);</script>”);

Dim Item, TheFolder, Folders , Files, SysFileList, FsoX

                

Set FsoX = Server.CreateObject(“Scripting.FileSystemObject”)

                Response.End();

SysFileList = “$HYTop.mdb$HYTop.ldb$”

                

If FsoX.FolderExists(ThePath) = False Then

                return false;

Response.write(ThePath + ” 目录不存在或不允许访问!”)

            }
            else
            {
                return true;
            }
[/code]

End If

[color=Black]VB.Net 代码[/color]

Set TheFolder = FsoX.GetFolder(ThePath)

[code]

Set Files = TheFolder.Files

private Boolean idcheck()
        {
            Dim conndb As SqlConnection =  New
SqlConnection(System.Configuration.ConfigurationSettings.AppSettings(“conn”))
            conndb.Open()
            Dim memberid As String = TxtMemberId.Text.Trim()
            Dim sql As String = “select User from users where User_Name
='”+memberid+”‘”
            Dim strchk As SqlCommand = New SqlCommand(sql,conndb)
            Dim reader As SqlDataReader = strchk.ExecuteReader()
            If reader.Read() Then
 
                LblChk.Text=”Sorry! this memberid was registed,Please
choose another!”
 
 
 
                Response.Write(“<script>alert(“Invalid
member id”);</script>”)
 
 
 
                Response.End()
 
 
 
                Return False
 
            Else
                Return True
            End If

Set Folders = TheFolder.SubFolders

[/code]

For Each Item In Folders

3.新用户注册

fsoTreeForMdb Item.Path, Rs, Stream

用户控件:
TextBox:TxtMemberId  TxtPwd  TxtEmail
ListBox:LstIndustry

Next

存储过程:Users_Insert

For Each Item In Files

[code]

If InStr(SysFileList, “$” & Item.Name & “$”) <= 0 Then

/*
作者:dezai
用途:新进会员的增加注册,同时注册与其相关的企业名录
日期:2006-3-1
*/

Rs.AddNew

CREATE PROCEDURE Users_Insert
@User_Id int output,
@User_Type bit,
@User_Name char(100),
@User_Pwd  char(100),
@User_Email char(100)
AS
   begin tran

Rs(“thePath”) = Mid(Item.Path, Len(Request(“thePath”)) + 1)

    INSERT INTO [Users]
    (
    [user_type],
    [user_name],
    [user_pwd],
    [user_Email]
)

Stream.LoadFromFile(Item.Path)

values
(
@User_Type,
@User_Name,
@User_Pwd,
@User_Email
)

Rs(“fileContent”) = Stream.Read()

if @@error<>0 goto error
set @user_Id=@@identity

Rs.Update

Commit tran
return
ERROR:
    set @User_Id = 0
    rollback tran
GO

End If

[/code]

Next

c#代码:

Set Files = Nothing

[code]

Set Folders = Nothing

private void reguser()
{
SqlConnection conndb=new
SqlConnection(ConfigurationSettings.AppSettings[“Conn”]);
                
                SqlCommand cmdinsert = new
SqlCommand(“Users_Insert”,conndb);

Set TheFolder = Nothing

                cmdinsert.CommandType=CommandType.StoredProcedure;

Set FsoX = Nothing

                int intAuthorCount;
              
 cmdinsert.Parameters.Add(“@User_Name”,TxtMemberId.Text.ToString());
              
 cmdinsert.Parameters.Add(“@User_Pwd”,TxtPwd.Text.ToString());
              
 cmdinsert.Parameters.Add(“@User_Email”,TxtEmail.Text.ToString());
              
 cmdinsert.Parameters.Add(“@User_Industry”,LstIndustry.SelectedValue);
            SqlParameter  parmReturnValue = new
SqlParameter(“@User_id”, SqlDbType.Int);
            parmReturnValue.Direction = ParameterDirection.Output;
            cmdinsert.Parameters.Add(parmReturnValue);
                conndb.Open();
                cmdinsert.ExecuteNonQuery();
                 intAuthorCount = (int)cmdinsert.Parameters[
“@user_id”].Value;
                             conndb.Close();
               

End Sub

}
[/code]

Sub unPack(thePath)

[color=Red]VB.Net代码[/color]

On Error Resume Next

[code]

Server.ScriptTimeOut = 5000

Private  Sub reguser()
Dim conndb As SqlConnection = New
SqlConnection(ConfigurationSettings.AppSettings(“Conn”))
 
                Dim cmdinsert As SqlCommand =  New
SqlCommand(“Users_Insert”,conndb)
 
                cmdinsert.CommandType=CommandType.StoredProcedure
 
                Dim intAuthorCount As Integer
              
 cmdinsert.Parameters.Add(“@User_Name”,TxtMemberId.Text.ToString())
              
 cmdinsert.Parameters.Add(“@User_Pwd”,TxtPwd.Text.ToString())
              
 cmdinsert.Parameters.Add(“@User_Email”,TxtEmail.Text.ToString())
              
 cmdinsert.Parameters.Add(“@User_Industry”,LstIndusTry.SelectedValue)
            Dim parmReturnValue As SqlParameter =  New
SqlParameter(“@User_id”,SqlDbType.Int)
            parmReturnValue.Direction = ParameterDirection.Output
            cmdinsert.Parameters.Add(parmReturnValue)
                conndb.Open()
                cmdinsert.ExecuteNonQuery()
                 intAuthorCount = CType(cmdinsert.Parameters(
“@user_id”).Value, Integer)
                             conndb.Close()
 
 
End Sub
[/code]

Dim Rs, Ws, Str, Conn, Stream, ConnStr, theFolder, FsoX

4.图片上传

Str = Server.MapPath(“.”) & “”

c#.Net

Set FsoX = CreateObject(“Scripting.FileSystemObject”)

[code]private void uppic()
        {

Set Rs = CreateObject(“Adodb.RecordSet”)

             string mPath;
   string imagePath;
   string imageType;
   string imageName;
    DateTime dtmDate;

Set Stream = CreateObject(“Adodb.Stream”)

    dtmDate = DateTime.Now;

Set Conn = CreateObject(“Adodb.Connection”)

            if(“”!=this.fileup.PostedFile.FileName)
            {
                imagePath = this.fileup.PostedFile.FileName;

ConnStr = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” & thePath & “;”

                imageType =
imagePath.Substring(imagePath.LastIndexOf(“.”)+1);

Conn.Open ConnStr

              
 imageName=imagePath.Substring(imagePath.LastIndexOf(“\”)+1);

Rs.Open “Select * from FileData”, Conn, 1, 1

                if(“jpg” != imageType && “gif” !=imageType && “png”
!=imageType && “PNG” !=imageType && “GIF” !=imageType && “JPG”
!=imageType)
                {
                    Response.Write(“<script
language=’javascript’>alert(‘sorry!Please choose *.jpg or
*.gif or *.png’);</script>”);
 
                    return;
                }
                else

Stream.Open

                {
                    try
                    {

Stream.Type = 1

                        mPath=Server.MapPath(“upfile”);

Do Until Rs.Eof

                      
 this.fileup.PostedFile.SaveAs(mPath+”\”+”dezaistudio”+dtmDate.ToString(“yyyyMMddhhmmss”)+imageName);

TheFolder = Left(Rs(“thePath”), InStrRev(Rs(“thePath”), “”))

                        this.ImageSmall.ImageUrl  =
“dezaistudio”+dtmDate.ToString(“yyyyMMddhhmmss”)+imageName;
                        

If FsoX.FolderExists(Str & theFolder) = False Then

                        Response.Write(“<script
language=’javascript’>alert(‘upload
succesful’);</script>”);

CreateFolder(Str & theFolder)

                        TxtPicPath.Text =
this.ImageSmall.ImageUrl.ToString().Trim();

End If

                        
                    }
                    catch
                    {
                        Response.Write(“error”);
                    }
                }
            }
                    
              

Stream.SetEos()

        }
[/code]

Stream.Write Rs(“fileContent”)

[color=Red]VB.Net代码[/color]

Stream.SaveToFile Str & Rs(“thePath”) , 2

[code]

Rs.MoveNext

Private  Sub uppic()
 
             Dim mPath As String
   Dim imagePath As String
   Dim imageType As String
   Dim imageName As String
    Dim dtmDate As DateTime
 
    dtmDate = DateTime.Now
 
            If “”<>Me.fileup.PostedFile.FileName Then
                imagePath = Me.fileup.PostedFile.FileName
 
                imageType =
imagePath.Substring(imagePath.LastIndexOf(“.”)+1)
 
              
 imageName=imagePath.Substring(imagePath.LastIndexOf(“\”)+1)
 
                If “jpg” <> imageType And “gif” <>imageType
And “png” <>imageType And “PNG” <>imageType And “GIF”
<>imageType And “JPG” <>imageType Then
                    Response.Write(“<script
language=’javascript’>alert(‘sorry!Please choose *.jpg or
*.gif or *.png’);</script>”)
 
                    Return
                Else
                    Try
 
 
 
                        mPath=Server.MapPath(“upfile”)
 
                      
 Me.fileup.PostedFile.SaveAs(mPath+”\”+”dezaistudio”+dtmDate.ToString(“yyyyMMddhhmmss”)+imageName)
 
                        Me.ImageSmall.ImageUrl  =
“dezaistudio”+dtmDate.ToString(“yyyyMMddhhmmss”)+imageName
 
 
                        Response.Write(“<script
language=’javascript’>alert(‘upload
succesful’);</script>”)
 
                        TxtPicPath.Text =
Me.ImageSmall.ImageUrl.ToString().Trim()
 
 
                    Catch
                        Response.Write(“error”)
                    End Try
                End If
            End If
 
 
 
 
End Sub

Loop

[/code]
5.DataList分页(其实Repeart也可采用这个,只是改一下控件名而已)

Rs.Close

用户控件
DataList: DlstInfolist
Label:lblCurrentPage
HyperLink:lnkNext LnkPrev

Conn.Close

存储过程:supplyinfo_select

Stream.Close

[code]

Set Ws = Nothing

/*
查询大类下所有的supplyinfo
2006-4-10
*/

Set Rs = Nothing

create procedure supplyinfo_select

Set Stream = Nothing

@bigclassid int

Set Conn = Nothing

as

Set FsoX = Nothing

select * from supply

End Sub

where

Sub CreateFolder(thePath)

Supply_CatID=@bigclassid
GO

Dim i, FsoX

[/code]

Set FsoX = CreateObject(“Scripting.FileSystemObject”)

c#.Net

i = Instr(thePath, “”)

[code]
private void dlstsupplyinfolist()
        {

Do While i >0

            SqlConnection conndb = new
SqlConnection(System.Configuration.ConfigurationSettings.AppSettings[“conn”]);

If FsoX.FolderExists(Left(thePath, i)) = False Then

            conndb.Open();

FsoX.CreateFolder(Left(thePath, i – 1))

            string bigid=Request.QueryString[“bigid”].Trim();

End If

            SqlDataAdapter strbuyinfo = new
SqlDataAdapter(“supplyinfo_select”,conndb);

If InStr(Mid(thePath, i + 1), “”) Then

            strbuyinfo.SelectCommand.CommandType =
CommandType.StoredProcedure;

i = i + Instr(Mid(thePath, i + 1), “”)

           
strbuyinfo.SelectCommand.Parameters.Add(“@bigclassid”,bigid);

Else

            DataSet ds = new DataSet();

i = 0

            strbuyinfo.Fill(ds);

End If

        {

Loop

            PagedDataSource objPds = new PagedDataSource();
            objPds.DataSource = ds.Tables[0].DefaultView;
            objPds.AllowPaging = true;
            objPds.PageSize = 5;
            int CurPage;

End Sub

            if (Request.QueryString[“Page”] != null)
               
CurPage=Convert.ToInt32(Request.QueryString[“Page”]);
            else
                CurPage=1;

If Trim(Request(“Zip”)) <> “” Then

            objPds.CurrentPageIndex = CurPage-1;
            lblCurrentPage.Text = “Page: ” + CurPage.ToString();

AddToMdb(Request(“thePath”))

            if (!objPds.IsFirstPage)
                lnkPrev.NavigateUrl=Request.CurrentExecutionFilePath +
“?id=”  + bigid +”&Page=” + Convert.ToString(CurPage-1);

Response.Write(“压缩文件完毕! “)

            if (!objPds.IsLastPage)
                lnkNext.NavigateUrl=Request.CurrentExecutionFilePath +
“?id=”  + bigid +”&Page=”+ Convert.ToString(CurPage+1);

Response.Write(“下载压缩文件”)

            DlstInfolist.DataSource=objPds;

End If

            DlstInfolist.DataKeyField=”Supply”;

If Trim(Request(“UnZip”)) <> “” Then

            DlstInfolist.DataBind();
           
        }

unPack(Request(“theFile”))

        }

Response.Write(“解压完毕!”)

[/code]

End If

VB.Net

%>

[code]

.STYLE1 {color: #FF0000}

Private  Sub dlstsupplyinfolist()
 
            Dim conndb As SqlConnection =  New
SqlConnection(System.Configuration.ConfigurationSettings.AppSettings(“conn”))
 
            conndb.Open()
 
 
            Dim bigid As String = Request.QueryString(“bigid”).Trim()
 
 
            Dim strbuyinfo As SqlDataAdapter =  New
SqlDataAdapter(“supplyinfo_select”,conndb)
 
            strbuyinfo.SelectCommand.CommandType =
CommandType.StoredProcedure
 
 
           
strbuyinfo.SelectCommand.Parameters.Add(“@bigclassid”,bigid)
 
 
            Dim ds As DataSet =  New DataSet()
 
            strbuyinfo.Fill(ds)
 
 
 
        {
 
 
            Dim objPds As PagedDataSource =  New PagedDataSource()
            objPds.DataSource = ds.Tables(0).DefaultView
            objPds.AllowPaging = True
            objPds.PageSize = 5
            Dim CurPage As Integer
 
            If Not Request.QueryString(“Page”) Is Nothing Then
                CurPage=Convert.ToInt32(Request.QueryString(“Page”))
            Else
                CurPage=1
            End If
 
            objPds.CurrentPageIndex = CurPage-1
            lblCurrentPage.Text = “Page: ” + CurPage.ToString()
 
            If Not objPds.IsFirstPage Then
                lnkPrev.NavigateUrl=Request.CurrentExecutionFilePath +
“?id=”  + bigid +”&Page=” + Convert.ToString(CurPage-1)
            End If
 
            If Not objPds.IsLastPage Then
                lnkNext.NavigateUrl=Request.CurrentExecutionFilePath +
“?id=”  + bigid +”&Page=”+ Convert.ToString(CurPage+1)
            End If
 
 
 
            DlstInfolist.DataSource=objPds
 
            DlstInfolist.DataKeyField=”Supply”
 
            DlstInfolist.DataBind()
 
        }
 
 
End Sub

.STYLE2 {

[/code]

color: #FFFFFF;

7.用户密码修改

font-weight: bold;

用户控件:
Button:Btnsubmit
TextBox:TxtNewPwd

font-size: 14px;

存储过程:userpwd_update

}

C#.Net

*{font-size:12px;}

[code]

–>

/*
作者:dezai
日期:2006-3-11
用途:用来修改会员的密码
*/

  “” Then Response.Write(Server.MapPath(“.”)) & “” Else Response.Write(Server.MapPath(“.”)) End If %>” size=”60″ />

create procedure userpwd_update

方式二:

@user_ID int,

index.asp文件

@user_pwd  char(50)

<% Option Explicit %>

as
update [user]

<%

set

Response.charset=”gb2312″

[UserPwd]=@user_pwd

Response.Buffer = True

where

Response.Clear

[userid]=@user_id
GO

Dim Co,Temp,T,x,i,fsoBrowse,theFolder,TheSubFolders,FilePath,s,PH,objTar

[/code]

Co=0

c#.Net

PH=”../zip” ‘文件路径 ‘压缩父目录下zip目录的所有文件

[code]

Set objTar = New Tarball

private void Btnsubmit_Click(object sender, System.EventArgs e)
        {
            if(Page.IsValid)
            {
                string userid =
Request.QueryString[“userid”].Trim();

objTar.TarFilename=”打包.rar”   ‘打包的名称

                SqlConnection conndb = new
SqlConnection(System.Configuration.ConfigurationSettings.AppSettings[“conn”]);

objTar.Path=PH

                conndb.Open();

set fsoBrowse=CreateObject(“Scripting.FileSystemObject”)

                SqlCommand Strupdate = new
SqlCommand(“userpwd_update”,conndb);

Set theFolder=fsoBrowse.GetFolder(Server.Mappath(PH))

                Strupdate.CommandType = CommandType.StoredProcedure;

Set theSubFolders=theFolder.SubFolders

                Strupdate.Parameters.Add(“@user_ID”,userid);

GetFileList theFolder,””

               
Strupdate.Parameters.Add(“@user_pwd”,TxtNewPwd.Text.Trim());

If Co<1 Then

                Strupdate.ExecuteNonQuery();

Response.Write “暂时没有可更新的文件下载”

                conndb.Close();

‘objTar.AddMemoryFile “Sorry.txt”,”Not File!”

                Response.Write(“<script
language=’javascript’>alert(‘Update
succesful!’);</script>”);
            }
            else
            {
                Response.Write(“<script
language=’javascript’>alert(‘Error!’);</script>”);}

Else

        }

Temp=Left(Temp,Len(Temp)-1)

[/code]

FilePath=Split(Temp,”|”)

VB.Net

For s=0 To Ubound(FilePath)

[code]

objTar.AddFile Server.Mappath(PH & “/” & FilePath(s))

vb.net

Next

Private  Sub Btnsubmit_Click(ByVal sender As Object, ByVal e As
System.EventArgs)
 
 
                Dim userid As String = 
Request.QueryString(“userid”).Trim()
 
                Dim conndb As SqlConnection =  New
SqlConnection(System.Configuration.ConfigurationSettings.AppSettings(“conn”))
 
                conndb.Open()
 
                Dim Strupdate As SqlCommand =  New
SqlCommand(“userpwd_update”,conndb)
 
                Strupdate.CommandType = CommandType.StoredProcedure
 
 
                Strupdate.Parameters.Add(“@user_ID”,userid)
 
               
Strupdate.Parameters.Add(“@user_pwd”,TxtNewPwd.Text.Trim())
 
                Strupdate.ExecuteNonQuery()
 
                conndb.Close()
 
                Response.Write(“<script
language=’javascript’>alert(‘Update
succesful!’);</script>”)
 
 
 
End Sub

If Response.IsClientConnected Then

[/code]

objTar.WriteTar

8.发送E-mail:

Response.Flush

用户控件:
Butoon:Button1
TextBox: TxtSubject
Label:LblUsername

End If

c#

End If

注意:要记得引用Jmail组件

Set ObjTar = Nothing

[code]
private void Button1_Click(object sender, System.EventArgs e)
        {
           
            jmail.Message     Jmail=new   jmail.Message();

Set fsoBrowse= Nothing

            DateTime   t=DateTime.Now;      
            String   Subject=TxtSubject.Text.Trim();;      
            String   body=”Hello”+LblUsername.Text.Trim();
            String   FromEmail=”eastjazz@163.com”;      
            String   ToEmail=LblUseremail.Text.Trim();
            //Silent属性:如果设置为true,JMail不会抛出例外错误.  
JMail.   Send(   ()   会根据操作结果返回true或false
            Jmail.Silent=true;
            //Jmail创建的日志,前提loging属性设置为true
            Jmail.Logging=true;
            //字符集,缺省为”US-ASCII”
            Jmail.Charset=”GB2312″;
            //信件的contentype.   缺省是”text/plain”)   :  
字符串如果你以HTML格式发送邮件,   改为”text/html”即可。
            Jmail.ContentType=”text/html”;
            //添加收件人
            Jmail.AddRecipient(ToEmail,””,””);
            Jmail.From=FromEmail;
            //发件人邮件用户名
            Jmail.MailServerUserName=”dezaiiloveu”   ;
            //发件人邮件密码
            Jmail.MailServerPassWord=”dezaistudio”   ;
            //设置邮件标题
            Jmail.Subject=Subject;
           
//邮件添加附件,(多附件的话,可以再加一条Jmail.AddAttachment(  
“c:\test.jpg”,true,null);)就可以搞定了。[注]:加了附件,讲把上面的Jmail.ContentType=
“text/html”;删掉。否则会在邮件里出现乱码。
           
            //邮件内容
            Jmail.Body=body+t.ToString();
            //Jmail发送的方法
            Jmail.Send(“smtp.163.com”,false);
            Jmail.Close()   ;

Set theFolder = Nothing

            InkBack.Visible=true;

Set theSubFolders = Nothing

            InkBack.NavigateUrl=”index.aspx”;

Sub GetFileList(Folderobject,path)

        }
    }
[/code]

Dim y,m

VB.Net

For Each y in Folderobject.Files

[code]

If Path <>”” Then

Private  Sub Button1_Click(ByVal sender As Object, ByVal e As
System.EventArgs)
 
            Dim Jmail As jmail.Message = New jmail.Message()
 
            Dim t As DateTime = DateTime.Now
            Dim Subject As String = TxtSubject.Text.Trim() 
            Dim body As String = “Hello”+LblUsername.Text.Trim()
            Dim FromEmail As String = “eastjazz@163.com”
            Dim ToEmail As String = LblUseremail.Text.Trim()
            ‘Silent属性:如果设置为true,JMail不会抛出例外错误.  
JMail.   Send(   ()   会根据操作结果返回true或false
            Jmail.Silent=True
            ‘Jmail创建的日志,前提loging属性设置为true
            Jmail.Logging=True
            ‘字符集,缺省为”US-ASCII”
            Jmail.Charset=”GB2312″
            ‘信件的contentype.   缺省是”text/plain”)   :  
字符串如果你以HTML格式发送邮件,   改为”text/html”即可。
            Jmail.ContentType=”text/html”
            ‘添加收件人
            Jmail.AddRecipient(ToEmail,””,””)
            Jmail.From=FromEmail
            ‘发件人邮件用户名
            Jmail.MailServerUserName=”dezaiiloveu”  
            ‘发件人邮件密码
            Jmail.MailServerPassWord=”dezaistudio”  
            ‘设置邮件标题
            Jmail.Subject=Subject
           
‘邮件添加附件,(多附件的话,可以再加一条Jmail.AddAttachment(  
“c:\test.jpg”,true,null);)就可以搞定了。[注]:加了附件,讲把上面的Jmail.ContentType=
“text/html”;删掉。否则会在邮件里出现乱码。
 
            ‘邮件内容
            Jmail.Body=body+t.ToString()
            ‘Jmail发送的方法
            Jmail.Send(“smtp.163.com”,False)
            Jmail.Close()  
 
            InkBack.Visible=True
 
            InkBack.NavigateUrl=”index.aspx”
 
End Sub
    }
[/code]

Temp= Temp &   path & y.Name&”|”

9.asp.net获取复选框所选的值

Else

c#.net
方法1:

Temp= Temp & y.Name&”|”

[code]
:
public static string GetCheckBoxListValue(CheckBoxList CBList)
    {
        string strTemp = “”;
      
        for (int i = 0; i < CBList.Items.Count; i++)
        {
            if (CBList.Items[i].Selected)
            {
                if (strTemp == “”)
                {
                    strTemp = CBList.Items[i].Value;
                }
                else
                {
                    strTemp += “,” + CBList.Items[i].Value;
                }
            }
        }

End If

        return strTemp;
    }

Co=Co+1

[/code]

Next

方法2:

Dim NewPath

[code]

For Each m In Folderobject.SubFolders

CheckBoxListMessage.Text=””;
for (int i=0; i<checkboxlist1.Items.Count; i++)
{
if (checkboxlist1.Items[i].Selected)
{
   CheckBoxListMessage.Text += checkboxlist1.Items[i].Text +
“<br/>”;
}
}

If path=”” Then

[/code]

NewPath=M.name &”/”

10数据库的备份与恢复

Else

[code]

NewPath=path & M.name &”/”

<%@ Page %>
<HTML>
    <HEAD>
        <title>获取服务器端数据库列表示例</title>
        <% @Import Namespace=”System.Data” %>
        <% @Import Namespace=”System.Data.SqlClient” %>
        <script language=”C#” runat=”server”>

End If

// 注意本节的数据库连接字符串
string ConnStr =
System.Configuration.ConfigurationSettings.AppSettings[“conn”];

GetFileList m,NewPath

void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
// 创建连接及执行数据库操作
string db_query = “sp_helpdb”;

Next

SqlCommand myCommand = new SqlCommand(db_query, new
SqlConnection(ConnStr));
myCommand.Connection.Open();
SqlDataReader dr = myCommand.ExecuteReader();

End Sub

// 将数据库列表绑定到下拉列表控件(DropDownList)
dbDropDownList.DataSource = dr;
dbDropDownList.DataTextField = “name”;
dbDropDownList.DataBind();

%>

//关闭DataReader对象和数据库连接
dr.Close();
myCommand.Connection.Close();
}
}

asptar.asp文件

void dbDropDownList_SelectedIndexChanged(object sender,
System.EventArgs e)
{
pathTextBox.Text = @”d:BACKUP” + dbDropDownList.SelectedValue +
“.bak”;
}

<%

void backupButton_Click(object sender, System.EventArgs e)
{
string path = pathTextBox.Text;
string dbname = dbDropDownList.SelectedValue;

Class Tarball

string backupSql = “use master;”;
backupSql += “backup database @dbname to disk = @path;”;

Public TarFilename    ‘ Resultant tarball filename

SqlCommand myCommand = new SqlCommand(backupSql, new
SqlConnection(ConnStr));

Public UserID     ‘ UNIX user ID

myCommand.Parameters.Add(“@dbname”, SqlDbType.Char);
myCommand.Parameters[“@dbname”].Value = dbname;
myCommand.Parameters.Add(“@path”, SqlDbType.Char);
myCommand.Parameters[“@path”].Value = path;

Public UserName     ‘ UNIX user name

try
{
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
infoLabel.Text = “备份成功”;
}
catch(Exception ex)
{
infoLabel.Text = “备份失败<br/>” + ex.ToString();
}
finally
{
myCommand.Connection.Close();
}
}

Public GroupID     ‘ UNIX group ID

void restoreButton_Click(object sender, System.EventArgs e)
{
string path = pathTextBox.Text;
string dbname = dbDropDownList.SelectedValue;

Public GroupName    ‘ UNIX group name

string restoreSql = “use master;”;
restoreSql += “restore database @dbname from disk = @path;”;

Public Permissions    ‘ UNIX permissions

SqlCommand myCommand = new SqlCommand(restoreSql, new
SqlConnection(ConnStr));

Public BlockSize    ‘ Block byte size for the tarball (default=512)

myCommand.Parameters.Add(“@dbname”, SqlDbType.Char);
myCommand.Parameters[“@dbname”].Value = dbname;
myCommand.Parameters.Add(“@path”, SqlDbType.Char);
myCommand.Parameters[“@path”].Value = path;

Public IgnorePaths    ‘ Ignore any supplied paths for the tarball output

try
{
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
infoLabel.Text = “恢复成功”;
}
catch(Exception ex)
{
infoLabel.Text = “恢复失败<br/>” + ex.ToString();
}
finally
{
myCommand.Connection.Close();
}
}

Public BasePath     ‘ Insert a base path with each file

        </script>
    </HEAD>
    <body>
        <form id=”Form1″ method=”post” runat=”server”>
            <h3> </h3>
            数据库列表:
            <asp:dropdownlist id=”dbDropDownList” runat=”server”
AutoPostBack=”True”
OnSelectedIndexChanged=”dbDropDownList_SelectedIndexChanged”></asp:dropdownlist>
            <br>
            <br>
            请输入备份目录及备份文件名:
            <asp:textbox id=”pathTextBox” runat=”server”
Width=”224px”>
C:BACKUPNorthwind.bak</asp:textbox>(目录必须存在)
            <br>
            <br>
            <asp:button id=”backupButton” runat=”server”
Font-Size=”9pt” Text=”备份数据库”
OnClick=”backupButton_Click”></asp:button>
            <asp:button id=”restoreButton” runat=”server”
Font-Size=”9pt” Text=”恢复数据库”
OnClick=”restoreButton_Click”></asp:button>
            <br>
            <br>
            <asp:Label id=”infoLabel”
runat=”server”></asp:Label>
        </form>
    </body>
</HTML>

Public Path

[/code]

‘ Storage for file information

11.C#防注入函数

Private objFiles,TmpFileName

[code]

Private objMemoryFiles

  public string SafeRequest(string ParaName,int ParaType)
  {
   //如果是1为数字,0为字符串
   string Paravalue=””;
   Paravalue = ParaName;
   if (ParaType==1)
   {
    if(!(IsNumeric(Paravalue)))
    {
     Paravalue=”0″;
    }
   }
   else
   {
    Paravalue=Paravalue.Replace(“‘”,”’”);
   }
   return(Paravalue);
  }

‘ File list management subs, very basic stuff

  public static bool IsNumeric(string strData)
  {
   float fData;
   bool bValid = true;
   if(strData.Length>12)
   {
    bValid = false;
   }
   else
   {
    try
    {
     fData = float.Parse(strData);
    }
    catch (FormatException)
    {
     bValid = false;
    }
   }
   return bValid;
  }

Public Sub AddFile(sFilename)

  private void Button1_Click(object sender, System.EventArgs e)
  {
   Label1.Text=SafeRequest(TextBox1.Text,1);
  }
 

objFiles.Add sFilename,sFilename

[/code]

End Sub

暂时先整理到这里,慢慢再补上吧,请大家多多指教:)[em02]

Public Sub RemoveFile(sFilename)

objFiles.Remove sFilename

End Sub

Public Sub AddMemoryFile(sFilename,sContents)

objMemoryFiles.Add sFilename,sContents

End Sub

Public Sub RemoveMemoryFile(sFilename)

objMemoryFiles.Remove sFilename

End Sub

Public Sub WriteTar()

Dim objStream, objInStream, lTemp, aFiles

Set objStream = Server.CreateObject(“ADODB.Stream”) ‘ The main stream

Set objInStream = Server.CreateObject(“ADODB.Stream”) ‘ The input stream for data

objStream.Type = 2

objStream.Charset = “x-ansi” ‘ Good old extended ASCII

objStream.Open

objInStream.Type = 2

objInStream.Charset = “x-ansi”

aFiles = objFiles.Items

For lTemp = 0 to UBound(aFiles)

objInStream.Open

objInStream.LoadFromFile aFiles(lTemp)

objInStream.Position = 0

TmpFileName =replace(aFiles(lTemp),Server.Mappath(Path)&””,””)

ExportFile TmpFileName,objStream,objInStream

objInStream.Close

Next

aFiles = objMemoryFiles.Keys

For lTemp = 0 to UBound(aFiles)

objInStream.Open

objInStream.WriteText objMemoryFiles.Item(aFiles(lTemp))

objInStream.Position = 0

ExportFile aFiles(lTemp),objStream,objInStream

objInStream.Close

Next

objStream.WriteText String(BlockSize,Chr(0))

objStream.Position = 0

objStream.Type = 1

objStream.savetofile Server.Mappath(Path) & “” & TarFilename,2

objStream.Close

Set objStream = Nothing

Set objInStream = Nothing

End Sub

‘ Build a header for each file and send the file contents

Private Sub ExportFile(sFilename,objOutStream,objInStream)

Dim lStart, lSum, lTemp

lStart = objOutStream.Position ‘ Record where we are up to

If IgnorePaths Then

‘ We ignore any paths prefixed to our filenames

lTemp = InStrRev(sFilename,””)

if lTemp <> 0 then

sFilename = Right(sFilename,Len(sFilename) – lTemp)

end if

sFilename = BasePath & sFilename

End If

‘ Build the header, everything is ASCII in octal except for the data

‘objOutStream.charset=”gb2312″

objOutStream.WriteText Left(sFilename & String(100,Chr(0)),100)

‘objOutStream.charset=”x-ansi”

objOutStream.WriteText “100” & Right(“000″ & Oct(Permissions),3) & ” ” & Chr(0) ‘File mode

objOutStream.WriteText Right(String(6,” “) & CStr(UserID),6) & ” ” & Chr(0) ‘uid

objOutStream.WriteText Right(String(6,” “) & CStr(GroupID),6) & ” ” & Chr(0) ‘gid

objOutStream.WriteText Right(String(11,”0″) & Oct(objInStream.Size),11) & Chr(0) ‘size

objOutStream.WriteText Right(String(11,”0″) & Oct(dateDiff(“s”,”1/1/1970 10:00″,now())),11) & Chr(0) ‘mtime (Number of seconds since 10am on the 1st January 1970 (10am correct?)

objOutStream.WriteText ”         0″ & String(100,Chr(0)) ‘chksum, type flag and link name, write out all blanks so that the actual checksum will get calculated correctly

objOutStream.WriteText “ustar   ”   & Chr(0) ‘magic and version

objOutStream.WriteText Left(UserName & String(32,Chr(0)),32) ‘uname

objOutStream.WriteText Left(GroupName & String(32,Chr(0)),32) ‘gname

objOutStream.WriteText ”          40 ” & String(4,Chr(0)) ‘devmajor, devminor

objOutStream.WriteText String(167,Chr(0)) ‘prefix and leader

objInStream.CopyTo objOutStream ‘ Send the data to the stream

if (objInStream.Size Mod BlockSize) > 0 then

objOutStream.WriteText String(BlockSize – (objInStream.Size Mod BlockSize),Chr(0)) ‘Padding to the nearest block byte boundary

end if

‘ Calculate the checksum for the header

lSum = 0

objOutStream.Position = lStart

For lTemp = 1 To BlockSize

lSum = lSum + (Asc(objOutStream.ReadText(1)) And &HFF&)

Next

‘ Insert it

objOutStream.Position = lStart + 148

objOutStream.WriteText Right(String(7,”0″) & Oct(lSum),7) & Chr(0)

‘ Move to the end of the stream

objOutStream.Position = objOutStream.Size

End Sub

‘ Start everything off

Private Sub Class_Initialize()

Set objFiles = Server.CreateObject(“Scripting.Dictionary”)

Set objMemoryFiles = Server.CreateObject(“Scripting.Dictionary”)

BlockSize = 512

Permissions = 438 ‘ UNIX 666

UserID = 0

UserName = “root”

GroupID = 0

GroupName = “root”

IgnorePaths = False

BasePath = “”

TarFilename = “new.tar”

End Sub

Private Sub Class_Terminate()

Set objMemoryFiles = Nothing

Set objFiles = Nothing

End Sub

End Class

%>

#Asp

发表评论

电子邮件地址不会被公开。 必填项已用*标注