Finishing an Online E-Mail System in ASP.NET 2.0

Yesterday we began designing the interface for an online e-mail system in ASP.NET 2.0. Today, in the conclusion to this four-part series, we pick up where we left off. As you'll recall, the last thing we did was learn how to create folders; in this article, we'll learn how to rename and delete folders, and read and move e-mail.

Contributed by
Rating: 4 stars4 stars4 stars4 stars4 stars / 4
June 13, 2007
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

A downloadable .rar file is available for this article.

Renaming Folders

In this sample, renaming the folder is achieved through the RenameFolder.aspx, page. Figure 10 shows the relevant design-time snapshot.

Figure 10-the design-time view of the RenameFolder.aspx page

Since there are few controls on the page and their functions can be easily doped out, we choose not to waste time on the controls but to dive right into the associated code.

 

int nFolderID = -1;

protected void Page_Load(object sender,EventArgs e)

{

  ///get the value of parameter nFolderID

  if(Request.Params["FolderID"] != null)

  {

    if(Int32.TryParse(Request.Params["FolderID"].ToString(),out nFolderID) == false)

    {return;}

  }

  if(!Page.IsPostBack)

  { ///show name of the folder

    if(nFolderID > -1) { BindFolderData(nFolderID); }

  }

}

private void BindFolderData(int nFolderID)

{

  IFolder folder = new Folder();

  SqlDataReader dr = folder.GetSingleFolder(nFolderID);

  if(dr.Read())

  {

    Name.Text = dr["Name"].ToString();

  }

  dr.Close();

}

 

Here, when the RenameFolder.aspx page is initialized, we first obtain the value of the nFolderID parameter out of the address bar (of the browser), then call a helper function named BindFolderData which bears the responsibility of grabbing the information of the folder out of the database using the nFolderID parameter, and then displays the folder name in the text box called Name. Next, when you click the OK button (with the id of RenameBtn), renaming is started:

 

protected void NewBtn_Click(object sender,EventArgs e)

{

  try

  { ///define the object

    IFolder folder = new Folder();

    ///execute

    folder.RenameFolder(nFolderID,Name.Text.Trim());

    Response.Write("<script>alert('" + "Renaming succeeded, safekeep you data!" + "');</script>");

  }

  catch(Exception ex)

  { ///jump to the page dealing with exception handling

    Response.Redirect("ErrorPage.aspx?ErrorMsg=" + ex.Message.Replace("<br>","").Replace("n","")

      + "&ErrorUrl=" + Request.Url.ToString().Replace("<br>","").Replace("n",""));

  }

}

 

Here, when you click the OK button, the NewBtn_Click event is triggered to call the helper function named RenameFolder to rename the folder and persist the new name into the database. Finally, clicking the Return button will navigate you back to the MailDesktop.aspx page.

Deleting Folders

Deleting folders is accomplished inside the MailDesktop.aspx page. To do so, you can just click the X button on the web page, and then the selected folders will be deleted.

When we use Windows Explorer.exe to delete something, a dialog always appears to remind us of the possible danger. To achieve such an effect ourselves, we add the related code into the RowDataBound event of the FolderView control.

 

protected void FolderView_RowDataBound(object sender,GridViewRowEventArgs e)

{

  ImageButton deleteBtn = (ImageButton)e.Row.FindControl("DeleteBtn");

  if(deleteBtn != null)

  {

    deleteBtn.Attributes.Add("onclick", "return confirm('Are you sure to delete the selected item?');");

  }

}

 

Here, we first search for the button named DeleteBtn. If DeleteBtn is not null (i.e. exists or is found), then we bind a confirming dialog to it.

The main task of making the deletion is done within the GridView's RowCommand event.

 

protected void FolderView_RowCommand(object sender,GridViewCommandEventArgs e)

{

  if(e.CommandName == "delete")

  {

    try

    { ///delete data

        IFolder folder = new Folder();

        folder.DeleteFolder(Int32.Parse(e.CommandArgument.ToString()));

 

      ///rebind the controls' data

        BindFolderData();

      Response.Write("<script>alert('" + "Deleting successfully,safekeep your data!" + "');</script>");

      }

      catch(Exception ex)

      { ///jump to the page dealing with exception handling

        Response.Redirect("ErrorPage.aspx?ErrorMsg=" + ex.Message.Replace("<br>","").Replace("n","")

          + "&ErrorUrl=" + Request.Url.ToString().Replace("<br>","").Replace("n",""));

      }

  }

}

 

Here, in the RowCommand event, we obtain the value of the CommandName property of the X button and save it in the CommandName parameter. Next, we get the value of the CommandArgument property and convert it into an integer which is stored in the nFolderID parameter. If all the requirements are satisfied, then we start to delete the selected folder, which is fulfilled by calling the  DeleteFolder (int nFolderID) function of the IDisk interface, removing the item (whose value of FolderID is nFolderID) from the database. And finally, an appropriate dialog appears to indicate whether or not the operation is successful.

Reading Your Email

1. The user interface design

Now we'll examine how to read e-mail, which is done through the Reader.aspx page. Figure 11 gives its design-time snapshot.

Figure 11-the design-time snapshot of the Reader.aspx page

Here we use a table to exhibit the controls and their functions.

Id

Control Type

Function

To

TextBox

The receiver's address (may be more than one)

CC

TextBox

The email address(es) to whom the email is copied

Title

TextBox

Title of the email

Body

TextBox

Body of the email

AttachView

GridView

Used to show the attachment(s) with the email

ReceiverBtn

Button

Reply to the receiver(s) (including those to be copied to)

ReturnBtn

Button

Return to the ViewMail.aspx page

HtmlCB

HTML checkbox Button

Set the format of the email

2. Initialization

When initialized, the Reader.aspx page first obtains the parameters named FolderID and MailID from the Request object (which is passed when you click the corresponding hyperlink address of the email in the ViewMail.aspx page):

 

if(Request.Params["FolderID"] != null)

{

  if(Int32.TryParse(Request.Params["FolderID"].ToString(),out nFolderID) == false)

  { return;}

}

if(Request.Params["MailID"] != null)

{

  if(Int32.TryParse(Request.Params["MailID"].ToString(),out nMailID) == false)

  { return;}

}

 

Next, we will display the content of the specified e-mail.

 

if(!Page.IsPostBack)

{ ///show the content of the mail

  if(nMailID > -1)

  {

    BindMailData(nMailID);

  }

}

private void BindMailData(int nMailID)

{

  IMail mail = new Mail();

  SqlDataReader dr = mail.GetSingleMail(nMailID);

  if(dr.Read())

  {

    Title.Text = dr["Title"].ToString();

    CC.Text = dr["CCAddress"].ToString();

    To.Text = dr["ToAddress"].ToString();

    Body.Text = dr["Body"].ToString();

    HtmlCB.Checked = bool.Parse(dr["HTMLFormat"].ToString().ToLower());

 

    SqlDataReader drAttach = mail.GetAttachmentsByMail(nMailID);

    AttachView.DataSource = drAttach;

    AttachView.DataBind();

    drAttach.Close();

  }

  dr.Close();

}

 

You can see here that we define a helper function named BindMailData which picks out the detailed information about the email from the underlying database according to the nMailID parameter identifying the email. And also, the corresponding attachment is shown from inside the BindMailData function, with a GridView control (AttachView) to display the content of the attachment. Additionally, when you click the 'New Mail' link from inside the draft box, you can view the email in it, too.

3. Reply and Return

When you click the Reply button on the page, the control is directed to the  Sender.aspx page:

 

protected void RecieverBtn_Click(object sender,EventArgs e)

{ ///reply

  Response.Redirect("~/Sender.aspx?MailID=" + nMailID.ToString());

}

 

And when you click the Return button, you are navigated back to the ViewMail.aspx page.

Deleting Your Email

It's comparatively easy to delete email, which is accomplished in the DeleteBtn_Click event on the ViewMail.aspx page.

 

protected void DeleteBtn_Click(object sender,EventArgs e){

  ///create a new instance of class Mail

    IMail mail = new Mail();

    try {

      foreach(GridViewRow row in MailView.Rows)

    { ///find your control

      CheckBox checkMail = (CheckBox)row.FindControl("CheckMail");

      if(checkMail != null)

      {

        if(checkMail.Checked == true)

        {

      ///execute the requested operation on the database

    mail.DeleteMail(Int32.Parse(MailView.DataKeys[row.RowIndex].Value.ToString()));

        }

      }

    }

  ///rebind the data to the control

    BindMailData(nFolderID);

  }

  catch(Exception ex)

  { ///jump to the page responsible for dealing exception

    Response.Redirect("ErrorPage.aspx?ErrorMsg=" + ex.Message.Replace("<br>","").Replace("n","")

      + "&ErrorUrl=" + Request.Url.ToString().Replace("<br>","").Replace("n",""));

  }

}

 

As is seen from above, we first find the ID value matching each e-mail to be deleted in the mail list control named MailView, and then invoke the DeleteMail method of the Mail object, which is finished through a typical for loop sentence. Here, remember that after deleting the selected e-mail, you have to rebind the data to MailView (i.e. refresh).

Moving Your Email

Finally we come to the last piece -- moving selected e-mails, which is also accomplished through the ViewMail.aspx page. When clicking the Move To button, you can move the selected e-mails to another folder or mailbox. To do so, we'll follow the steps listed below:

1. Select the e-mails to move;

2. Select the destination folder or mailbox;

3. Click the Move To button to finish the task.

All the moving functions are fulfilled inside the MoveBtn_Click(object sender, EventArgs e) event, whose complete code is shown below.

 

protected void MoveBtn_Click(object sender,EventArgs e)

{

  ///define object

  IMail mail = new Mail();

  try

  {

    foreach(GridViewRow row in MailView.Rows)

    { ///find your control

      CheckBox checkMail = (CheckBox)row.FindControl("CheckMail");

      if(checkMail != null)

      {

        if(checkMail.Checked == true)

        {

          ///execute the requested operation on the database

          mail.MoveMail(Int32.Parse(MailView.DataKeys[row.RowIndex].Value.ToString()),

            Int32.Parse(FolderList.SelectedValue));

        }

      }

    }

    ///rebind the data to the control

    BindMailData(nFolderID);

  }

  catch(Exception ex)

  { ///jump to the page responsible for dealing exception

    Response.Redirect("ErrorPage.aspx?ErrorMsg=" + ex.Message.Replace("<br>","").Replace("n","")

      + "&ErrorUrl=" + Request.Url.ToString().Replace("<br>","").Replace("n",""));

    }

}

 

To begin, we iterate through the mail list control named MailView to obtain the ID(s) of the e-mail to move, and then get the FolderID of the destination folder/mailbox, and finally call the MoveMail function to perform the movement. Similarly, after moving all the selected e-mails, you must remember to rebind data to the MailView control.

Conclusion

Whew, it has been a long a journey! However, this four-part tutorial has only presented you with a general framework for constructing an online e-mail system under ASP.NET 2.0/SQL Server 2005/.NET 2.0 environments, and you are sure to agree that there is nothing incredibly complex in it. Moreover, there are still a great many items that can be modified or enhanced, such as providing the function of strict user info authentication, using the popular AJAX technique to improve the users' real time experience, supplying the users with the ability to customize the system, and so on. Okay, there is no sense in piling up more words, just roll up your sleeves and give it a test run!

blog comments powered by Disqus
ASP.NET ARTICLES

- Implementing ASP.NET 4.0 Page.MetaDescriptio...
- ASP.Net Development Tips
- Intro to Sessions in ASP.Net
- Google Maps API Introduction in ASP.NET usin...
- Creating an ASP.NET 3.5 Gridview Image Galle...
- Encrypt QueryString in ASP.NET 3.5 using VB....
- ASP.NET 3.5 Drop Down List Controls
- Connect to Access Database with ASP.Net
- Secure Audio Streaming with ASP.Net and Flash
- Dynamic Sitemap and Navigation in ASP.Net
- Implement Gzip and Deflate Compression in AS...
- Run ASP.Net in Ubuntu with Apache
- ASP.Net Mono Website Contact Forms
- ASP.Net URL Rewriting Methods
- Murach`s ASP.NET 4 Web Programming with C# 2...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 3 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials