The Edit Files Page

The code in Listing 22.6 is behind the EditFile.aspx page. This page allows users to edit information about the files that they have uploaded, as shown in Figure 22.4. Some of the fields are read-only and are there to display relevant information.

Figure 22.4. This Page Allows Users to Edit Information and View other Relevant Information.

graphics/22fig04.jpg

There are five methods in the code in Listing 22.6: Page_Load(), Main_Click(), Cancel_Click(), Delete_Click(), and Save_Click(). The Page_Load() method retrieves information about the file that's to be edited and puts the information into the user interface objects. The Main_Click() method simply goes to the main menu (Default.aspx). The Cancel_Click() method simply goes back to the Manage Files page (MngFiles.aspx). The Delete_Click() method deletes a file from disk and removes any references to it in the database. And the Save_Click() method saves all of the edited information to disk before going back to the Manage Files page.

Listing 22.6 This Code Is behind the EditFile.aspx Page.
 // This method is called when the page first loads. private void Page_Load(object sender, System.EventArgs e) {   if( !IsPostBack )   {   // Create a connection object.   SqlConnection objConnection =   new SqlConnection(ConfigurationSettings.AppSettings["ConnectString"]);     try     {       // Open the connection.       objConnection.Open();       string strSql = "Select Name,ID from FileGroup where OwnerID"] ) + " order by name";       // Create a command object.       SqlCommand objCommand = new SqlCommand( strSql, objConnection );       SqlDataReader objReader = objCommand.ExecuteReader();       GroupList.DataTextField = "Name";       GroupList.DataValueField = "ID";       GroupList.DataSource = objReader;       GroupList.DataBind();       objReader.Close();       strSql = "select * from FileInfo where ID"];       // Create a command object.       objCommand = new SqlCommand( strSql, objConnection );       objReader = objCommand.ExecuteReader();       if( objReader.Read() )       {         Title.Text = Convert.ToString( objReader["Title"] );         Version.Text =           Convert.ToDouble( objReader["Version"] ).ToString( "0.00" );         Description.Text = Convert.ToString( objReader["Description"] );         Filename.Text = Convert.ToString( objReader["Filename"] );         FileSize.Text = Convert.ToString( objReader["Filesize"] );         Directory.Text = Convert.ToString( objReader["Directory"] );         Downloads.Text = Convert.ToString( objReader["Downloads"] );         for( int i=0; i<GroupList.Items.Count; i++ )         {           if( Convert.ToInt32( GroupList.Items[i].Value ) ==             Convert.ToInt32( objReader["GroupID"] ) )           {             GroupList.SelectedIndex = i;             break;           }         }       }       objReader.Close();     }     catch( Exception ex )     {       // Alert the user to the error.       ErrorMessage.Text = ex.Message.ToString();     }     finally     {       // Close the connection.       if( objConnection.State == ConnectionState.Open )       {         objConnection.Close();       }     }   } } private void Main_Click(object sender, System.EventArgs e) {   Response.Redirect( "Default.aspx" ); } private void Cancel_Click(object sender, System.EventArgs e) {   Response.Redirect( "MngFiles.aspx" ); } private void Delete_Click(object sender, System.EventArgs e) {   bool bOperationSucceeded = true;   // Create a connection object.  SqlConnection objConnection =   new SqlConnection(ConfigurationSettings.AppSettings["ConnectString"]);   try   {     // Open the connection.     objConnection.Open();     string strSql = "Delete from FileInfo where ID"];     // Create a command object.     SqlCommand objCommand = new SqlCommand( strSql, objConnection );     objCommand.ExecuteNonQuery();     string strFilePath = Request.MapPath( "." ) + "\\" +         ConfigurationSettings.AppSettings["DirectoryName"] + "\\" +         Directory.Text + "\\" + Filename.Text;     File.Delete( strFilePath );   }   catch( Exception ex )   {     // Alert the user to the error.     ErrorMessage.Text = ex.Message.ToString();     bOperationSucceeded = false;   }   finally   {     // Close the connection.     if( objConnection.State == ConnectionState.Open )     {       objConnection.Close();     }   }   if( bOperationSucceeded )   {     Response.Redirect( "MngFiles.aspx" );   } } private void Save_Click(object sender, System.EventArgs e) {   bool bOperationSucceeded = true;   // Create a connection object.  SqlConnection objConnection =   new SqlConnection(ConfigurationSettings.AppSettings["ConnectString"]);   try   {     // Open the connection.     objConnection.Open();     string strSql = "Update FileInfo Set Title='" + Title.Text +        "',Version=" + Version.Text + ",Description='" +        Description.Text + "',Group where ID"];     // Create a command object.     SqlCommand objCommand = new SqlCommand( strSql, objConnection );     objCommand.ExecuteNonQuery();   }   catch( Exception ex )   {     // Alert the user to the error.     ErrorMessage.Text = ex.Message.ToString();     bOperationSucceeded = false;   }   finally   {     // Close the connection.     if( objConnection.State == ConnectionState.Open )     {       objConnection.Close();     }   }   if( bOperationSucceeded )   {     Response.Redirect( "MngFiles.aspx" );   } } 

The Page_Load() method does database access and therefore has the things that all of our methods with database access have had: creation of a SqlConnection object, a try block for the working code, a catch block in which exceptions messages are displayed for users, and a finally block in which the database objects are cleaned up. Inside the try block, the SqlConnection is opened with the Open() method. Then, a SQL string is created using the logged-in user ID as the criteria. The recordsets will contain the Name and ID from the FileGroup table. The following code shows the creation of the SQL string:

C#
 string strSql = "Select Name,ID from FileGroup where OwnerID"] ) + " order by name"; 
VB
 Dim strSql As String = "Select Name,ID from FileGroup where " + _   "OwnerID= + Convert.ToString( Session("ID") ) + " order by name" 

If the logged-in user has an ID of 5, the following SQL will result:

 Select Name,ID from FileGroup where OwnerID=5 order by name 

A SqlCommand object is created using the SQL string and the SqlConnection object as arguments to its constructor. The SqlCommand object's ExecuteReader() method is then called, and this returns a SqlDataReader object containing the returned recordsets. There is a user interface object named GroupList of the type DropDownList. The SqlDataReader object is bound to this object so that the groups that belong to the logged-in user will be shown in the list. (The group ID is the data value, while the name is the display value.)

We'll then need to retrieve the actual file information. This process starts by creating a SQL string based on the file ID (which is contained in an HTML parameter). The following line shows how the SQL string is formed:

C#
 int nID = 0; try (   nID  = Convert.ToInt32( Request.QueryString["ID"] ); } catch { } strSql = "select * from FileInfo where docEmphStrong">VB
 Dim nID As Integer = 0 Try   NID = Convert.ToInt32( Request.QueryString("ID") ) Catch End Try strSql = "select * from FileInfo where docText">If the file ID is 16, the following SQL will result:

 select * from FileInfo where ID=16 

A SqlCommand object is created with the SQL string and the Sql Connection object. This object's ExecuteReader() method is called, and a recordset containing the matches files is returned in a SqlDataReader object.

To get the first recordset, the Read() method must be executed. (It's unlike the old ADO recordsets in classic ASP, in which there was always an initial recordset if one was found in the database.) The relevant information is placed into the user interface objects from the recordset. Included in the user interface objects are Title, Version, Description, Filename, FileSize, Directory, and Downloads. The corresponding group is also selected in the DropDownList object with the following code:

 for( int i=0; i<GroupList.Items.Count; i++ ) {   if( Convert.ToInt32( GroupList.Items[i].Value ) ==     Convert.ToInt32( objReader["GroupID"] ) )   {     GroupList.SelectedIndex = i;     break;   } } 

Before leaving the try block, the SqlDataReader object is closed.

The Main_Click() method simply goes to the main page (Default.aspx) by calling the Response.Redirect() method. The Cancel_Click() method redirects similarly to the Main_Click() method but it redirects to the Manage Files page (MngFiles.aspx).

The Delete_Click() method is intended to get rid of a file that is no longer needed. It removes the file from disk and deletes database records that reference it. It has the customary SqlConnection object creation, and the try/catch/finally construct. The SqlConnection object is opened with the Open() method. A SQL string is created that will delete the file's record in the FileInfo table. The following code shows how the SQL string is formed:

C#
 string strSql = "Delete from FileInfo where ID"]; 
VB
 Dim strSql As string = "Delete from FileInfo where ID") 

If the file ID is 19, the resulting SQL will be the following:

 Delete from FileInfo where ID=19 

A SqlCommand object is created with the SQL string and the Sql Connection object as parameters for its constructor. The SqlCommand object's ExecuteNonQuery() method is called, and this executes the SQL and deletes the record.

The last thing that has to be done is to delete the file from disk. The full path to the file is composed of several things: the path of the current application, the directory in which all files are stored, the file's additional directory, and the file name. The following shows how these strings are obtained:

The path of the current application:

 Request.MapPath( "." ) 

The directory into which all files will be placed:

 ConfigurationSettings.AppSettings["DirectoryName"] 

The specific subdirectory in which the file resides:

 Directory.Text 

The file name:

 Filename.Text 

The Directory and Filename objects are TextBox objects that are part of the user interface. They were initially populated in the Page_Load() method. They are read-only, and therefore the user can't edit them and prevent the file from being deleted.

With the full path name for the file developed, a call to the File.Delete() static method can be made to delete the file. Note that for C# you must include System.IO, and for VB you must import System.IO.

The last method in Listing 22.6 is the Save_Click() method, which has the expected SqlConnection object creation and the try/catch/ finally construct. In the try block, the SqlConnection object is opened, and a SQL string is created based on the items in the user interface objects (but only those items that can be edited). The following code shows how the SQL string is formed:

C#
 string strSql = "Update FileInfo Set Title='" + Title.Text +   "',Version=" + Version.Text + ",Description='" +   Description.Text + "',Group where ID"]; 
VB
 Dim strSql As String = "Update FileInfo Set Title='" + Title.Text + _   "',Version=" + Version.Text + ",Description='" + _   Description.Text + "',Group where ID") 

The following might be what the actual SQL would look like for a file with an ID of 32:

 Update FileInfo Set Title='My Title',Version=1.1,Description='My Description',GroupID=5   where ID=32 

The SQL is executed using the SqlCommand object's ExecuteNonQuery() method.



ASP. NET Solutions - 24 Case Studies. Best Practices for Developers
ASP. NET Solutions - 24 Case Studies. Best Practices for Developers
ISBN: 321159659
EAN: N/A
Year: 2003
Pages: 175

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net