Visual Studio .NET - Problem with Insert not always saving data to SQL Express

Asked By Martin Howell
29-Aug-10 12:35 PM
Hi,
I'm pretty new to .net so this may be completely obvious but I just can't see whats going wrong.

I have made a form that on completion submits the data into a table and sends and email, however it only works about 60% of the time and I don't understand why.

Onclick should save data, send email and redirect to a completion page, but what is happening is that sometimes the page does not redirect, instead it remains on the original page but still sends the email even though the data has not been saved to the database.

Any ideas?


CreatRequest.aspx
01.<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CreateRequest.aspx.cs" Inherits="CreateTicket" %>
02.  
03.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
04.  
05.<html xmlns="http://www.w3.org/1999/xhtml">
06.<head runat="server">
07.  <title></title>
08.</head>
09.<body>
10.  <form id="form1" runat="server">
11.  <div>
12.    
13.  <h1>Create Support Request</h1>
14.  <p>Please complete the form below to submit your IT problem to the ISD Team.</p>
15.  
16.  <p>Email Address:<br />
17.    <asp:TextBox ID="emailTextBox" runat="server"></asp:TextBox>
18.   *
19.    <asp:RequiredFieldValidator ID="emailRequired" runat="server" 
20.      ControlToValidate="emailTextBox" Display="Dynamic" 
21.      ErrorMessage="Please enter your Email Address."></asp:RequiredFieldValidator>
22. <asp:RegularExpressionValidator ID="emailValid" runat="server" 
23.      ControlToValidate="emailTextBox" Display="Dynamic" 
24.      ErrorMessage="Please enter a valid Email Address." 
25.      ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
26.  </p>
27.  <p>Extension:<br />
28.    <asp:TextBox ID="extensionTextBox" runat="server"></asp:TextBox>
29.   *
30.    <asp:RequiredFieldValidator ID="extensionRequired" runat="server" 
31.      ErrorMessage="Please enter your Extension Number." 
32.      ControlToValidate="extensionTextBox" Display="Dynamic"></asp:RequiredFieldValidator>
33.   <asp:CompareValidator ID="extensionValid" runat="server" 
34.      ControlToValidate="extensionTextBox" Display="Dynamic" 
35.      ErrorMessage="Please enter a valid Extension Number i.e. 001." Operator="DataTypeCheck" Type="Integer"></asp:CompareValidator>
36.  </p>
37.    
38.  <p>Department:<br />
39.    <asp:DropDownList ID="departmentList" runat="server">
40.    </asp:DropDownList>
41.  </p>
42.    
43.  <p>Priority:<br />
44.    <asp:DropDownList ID="priorityList" runat="server"></asp:DropDownList>
45.  </p>
46.    
47.  <p>Category:<br />
48.    <asp:DropDownList ID="categoryList" runat="server"></asp:DropDownList>
49.  </p>
50.    
51.  <p>Subject:<br />
52.    <asp:TextBox ID="subjectTextBox" runat="server"></asp:TextBox>
53.   *
54.    <asp:RequiredFieldValidator ID="subjectRequired" runat="server" 
55.      ErrorMessage="Please enter a Subject." ControlToValidate="subjectTextBox" 
56.      Display="Dynamic"></asp:RequiredFieldValidator>
57.  </p>
58.    
59.  <p>Problem: *
60.    <asp:RequiredFieldValidator ID="problemRequired" runat="server" 
61.      ErrorMessage="Please provide details of the problem." 
62.      ControlToValidate="problemTextBox" Display="Dynamic"></asp:RequiredFieldValidator>
63.    <br />
64.    <asp:TextBox ID="problemTextBox" runat="server" TextMode="MultiLine" Width="400" Height="200"></asp:TextBox>
65.   </p>
66.    
67.    <asp:Button ID="submitButton" runat="server" Text="Submit Request" OnClick="CreateRequest" />
68.    
69.    <br />
70.    <br />
71.    <asp:Label ID="dbErrorMessage" runat="server"></asp:Label>
72.    
73.  </div>
74.  </form>
75.</body>
76.</html>

Code Behind
001.using System;
002.using System.Collections.Generic;
003.using System.Linq;
004.using System.Web;
005.using System.Web.UI;
006.using System.Web.UI.WebControls;
007.using System.Data.SqlClient;
008.using System.Configuration;
009.using System.Net.Mail;
010.  
 
012.  
013.public partial class CreateTicket : System.Web.UI.Page
014.{
015.  protected void Page_Load(object sender, EventArgs e)
016.  {
017.  
018.    if (!IsPostBack)
019.    {
020.      SqlConnection conn;
021.      SqlCommand departmentComm;
022.      SqlCommand priorityComm;
023.      SqlCommand categoryComm;
024.  
025.      SqlDataReader reader;
026.  
027.      string connectionString = ConfigurationManager.ConnectionStrings["ISDSupport"].ConnectionString;
028.      conn = new SqlConnection(connectionString);
029.  
030.      departmentComm = new SqlCommand("SELECT * FROM supportDepartments", conn);
031.      priorityComm = new SqlCommand("SELECT * FROM supportPriority", conn);
032.      categoryComm = new SqlCommand("SELECT * FROM supportCategory", conn);
033.  
034.      try
035.      {
036.        conn.Open();
037.  
038.        reader = departmentComm.ExecuteReader();
039.        departmentList.DataSource = reader;
040.        departmentList.DataValueField = "DepartmentID";
041.        departmentList.DataTextField = "Department";
042.        departmentList.DataBind();
043.        reader.Close();
044.  
045.        reader = priorityComm.ExecuteReader();
046.        priorityList.DataSource = reader;
047.        priorityList.DataValueField = "PriorityID";
048.        priorityList.DataTextField = "Priority";
049.        priorityList.DataBind();
050.        reader.Close();
051.  
052.        reader = categoryComm.ExecuteReader();
053.        categoryList.DataSource = reader;
054.        categoryList.DataValueField = "CategoryID";
055.        categoryList.DataTextField = "Category";
056.        categoryList.DataBind();
057.        reader.Close();
058.      }
059.      finally
060.      {
061.        conn.Close();
062.      }
063.    }
064.  }
065.  protected void CreateRequest(object sender, EventArgs e)
066.  {
067.    if (Page.IsValid)
068.    {
069.      SqlConnection conn;
070.      SqlCommand comm;
071.  
072.      string connectionString = ConfigurationManager.ConnectionStrings["ISDSupport"].ConnectionString;
073.      conn = new SqlConnection(connectionString);
074.  
075.      comm = new SqlCommand("INSERT INTO supportRequest (EmailAddress, Extension, DepartmentID, PriorityID, CategoryID, Subject, Problem)" +
076.      "Values(@EmailAddress, @Extension, @DepartmentID, @PriorityID, @CategoryID, @Subject, @Problem)", conn);
077.  
078.      comm.Parameters.Add("@EmailAddress", System.Data.SqlDbType.NVarChar, 50);
079.      comm.Parameters["@EmailAddress"].Value = emailTextBox.Text;
080.  
081.      comm.Parameters.Add("@Extension", System.Data.SqlDbType.Int);
082.      comm.Parameters["@Extension"].Value = extensionTextBox.Text;
083.  
084.      comm.Parameters.Add("@DepartmentID", System.Data.SqlDbType.Int);
085.      comm.Parameters["@DepartmentID"].Value = departmentList.SelectedItem.Value;
086.  
087.      comm.Parameters.Add("@PriorityID", System.Data.SqlDbType.Int);
088.      comm.Parameters["@PriorityID"].Value = priorityList.SelectedItem.Value;
089.  
090.      comm.Parameters.Add("@CategoryID", System.Data.SqlDbType.Int);
091.      comm.Parameters["@CategoryID"].Value = categoryList.SelectedItem.Value;
092.  
093.      comm.Parameters.Add("@Subject", System.Data.SqlDbType.Int);
094.      comm.Parameters["@Subject"].Value = subjectTextBox.Text;
095.  
096.      comm.Parameters.Add("@Problem", System.Data.SqlDbType.Int);
097.      comm.Parameters["@Problem"].Value = problemTextBox.Text;
098.  
099.      SendEmail();
100.  
101.      try
102.      {
103.        conn.Open();
104.        comm.ExecuteNonQuery();
105.        Response.Redirect("RequestSubmitted.aspx");
106.        SendEmail();
107.      }
108.      catch
109.      {
110.        dbErrorMessage.Text = "Error creating request, please try again later or call ";
111.      }
112.      finally
113.      {
114.        conn.Close();
115.      }
116.    }
117.  }
118.  private void SendEmail()
119.  {
120.    Trace.Write("email sent");
121.  
122.    SmtpClient smtpClient = new SmtpClient();
123.    MailMessage message = new MailMessage();
124.    // Try to send the message
125.    try
126.    {
127.      // Prepare two email addresses 
128.      MailAddress fromAddress = new MailAddress(from@example.com, "Support Dept");
129.      MailAddress toAddress = new MailAddress("to@example.com");
130.      MailAddress BccAddress = new MailAddress(emailTextBox.Text, "Support Request Submitted");
131.  
132.      // Prepare the mail message
133.      message.From = fromAddress;
134.      message.To.Add(toAddress);
135.      message.Bcc.Add(BccAddress);
136.      message.Priority = MailPriority.High;
137.      message.Subject = subjectTextBox.Text;
138.      message.IsBodyHtml = true;
139.  
140.      //HttpUtility is needed to ensure, &, <, > etc are converted into their HTML equivalents i.e. <, & etc
141.      message.Body = "<html><head><title>" + "Support Request Submitted" + "</title></head><body>" + 
142.        "<p>Your support request has been logged, we will contact you shortly.</p>" +
143.        "<b>Email Address: </b>" + HttpUtility.HtmlEncode(emailTextBox.Text) + "<br />" +
144.        "<b>Extension No: </b>" + HttpUtility.HtmlEncode(extensionTextBox.Text) + "<br />" +
145.        "<b>Department: </b>" + HttpUtility.HtmlEncode(departmentList.SelectedItem.Text) + "<br />" +
146.        "<b>Priority: </b>" + HttpUtility.HtmlEncode(priorityList.SelectedItem.Text) + "<br />" +
147.        "<b>Category: </b>" + HttpUtility.HtmlEncode(categoryList.SelectedItem.Text) + "<br /><br />" +
148.        "<b>Subject: </b>" + HttpUtility.HtmlEncode(subjectTextBox.Text) + "<br />" +
149.        "<b>Problem Details: </b><br />" + HttpUtility.HtmlEncode(problemTextBox.Text) + "<br /><br />" +
150.        "<p>Best regards, </p>" + "<p>ISD Support</p>" + 
151.        "</body></html>";
152.  
153.      // Set server details
154.      smtpClient.Host = "xxxxxxxxxx";
155.  
156.      // For SMTP servers that require authentication
157.      smtpClient.Credentials = new System.Net.NetworkCredential("xxxxxxxxxx", "xxxxxxxxxx");
158.  
159.      // Send the email
160.      smtpClient.Send(message);
161.  
162.      // Inform the user
163.      //resultLabel.Text = "Email sent!<br />";
164.    }
165.    catch
166.    {
167.      dbErrorMessage.Text = "email failed";
168.    }
169.  }
170.}


  Ken Fitzpatrick replied to Martin Howell
29-Aug-10 03:00 PM
I would comment out the call to sendmail and the redirect and figure out why the insert isn't working first. When you get that working, go onto the next task. I would suggest you start using the debugger to trace through the CreateRequest method. Set a break point at the top of CreateRequest and run by hitting F5. When it hits your break point, start tracing line by examining your variables in the watch window. If there is an exception, the debugger will jump right to the catch statement.

I didn't see anything by looking at it. I think you will need to switch your sendmail and response.redirect around. When Response.Redirect is used, a ThreadAbort exception is thrown and your sendmail will never run. Not sure why your sendmail is running and not the redirect. I would just try to accomplish one task at a time. When that task is working, go onto the next one.

Good Luck,

Ken
  Martin Howell replied to Ken Fitzpatrick
29-Aug-10 04:24 PM
Thanks Ken, that really helped.

I spotted that I had two sendmails in my code, once disabled I stepped through and could see where the form was failing, such a silly mistake... Subject and Problem are nvarchar not int

093.    comm.Parameters.Add("@Subject", System.Data.SqlDbType.Int); 
094.    comm.Parameters["@Subject"].Value = subjectTextBox.Text; 
095.  
096.    comm.Parameters.Add("@Problem", System.Data.SqlDbType.Int); 
097.    comm.Parameters["@Problem"].Value = problemTextBox.Text;

Cheers for the help




  Ken Fitzpatrick replied to Martin Howell
29-Aug-10 04:36 PM
No problem, sometimes it is easier to take things one step at a time. Glad I could help!

Ken
Create New Account
help
Visual Studio .net .NET Framework Hi NG, ich habe vor längerer Zeit mit Visual Studio .Net 2003 gearbeitet und überlege momentan auf einen neueren Stand upzudaten. Ein Visual Studio .Net 2008 scheint es nicht zu geben. Habe zumindest mit googeln nichts gefunden. Was
Wise for Visual Studio.NET Wise for Visual Studio.NET By Peter A. Bromberg, Ph.D. To "Print This Page" Link Peter Bromberg Wise for Visual Studio .NET is a total and complete installation development system for creating and editing Windows® Installer
Visual Studio versioning . . . . how to tell? .NET Framework To my knowledge, Visual studio 6 was released in 1998, then Visual Studio .NET 2002 is VS 7, then Visual Studio .NET 2003 is VS 7.1, then Visual
visual studio.net 2003 and Access 2007 database .NET Framework Hi I am currently using Visual Studio.Net 2003 running on Windows Server 2000 operating system. I have used Visual Studio.net 2003 connecting to Access 2002 databases in the pass with great success. Now
Is Visual Studio self-hosting ? .NET Framework Does Microsoft use Visual Studio IDE, Visual Studio Debugger, Visual Studio Linker and Visual Studio compiler for developing Visual Studio ? Or is Visual Studio not