Problem with Insert not always saving data to SQL Express

Asked By Martin Howell
29-Aug-10 12:35 PM
Earn up to 0 extra points for answering this tough question.
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.}


  re: Problem with Insert not always saving data to SQL Express

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

  re: Problem with Insert not always saving data to SQL Express

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




  re: Problem with Insert not always saving data to SQL Express

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
SQL Server 2005 (SQLEXPRESS)- BETA 1: Hosting CLR Code Sql Server 2005 CLR Native Methods By Peter A. Bromberg, Ph not have a chance to read them at all. . " - - Thoreau Sql Server 2005 BETA 1 "SQLEXPRESS" was released to the MSDN and UDTs (User-Defined Types) written in C# or VB.NET, right inside SQL Server. Once you get the various syntax issues out of opens up to you as a developer. Have some cool .NET code you've written that you'd like to make into a user - defined function callable from T-SQL? No problem - now you can, and that's just the over the web from Yahoo Finance, compile it into a .NET Class library, and demonstrate how the function can be called with normal SQL Code - right from out of SQL Server 2005. But first, let's go over a few
visual web developer 2005 I have just installed visual web developer 2005 along with sql server express 2005 beta version. When i try to view my website file auto-creation error: The connection string specifies a local SQL Server Express instance using a database location within the applications App_Data directory the web server account will attempt to verify that the SQL Server Express database already exists within the applications App_Data directory. Note that account will prevent the provider from correctly determining if the SQL Server Express database already exists. This will cause an error when SQL
running in visualstudio.This project is a developed with Asp.Net with C# code and my problem is when ever iam while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider SQL Network Interfaces, error: 26 - Error Locating Server / Instance Specified) Why the . \ sqlexpress hi. . Networking protocols are disabled by default in SQL Server Express. If someone simply installs Express and chooses all the defaults, SQL Server Express will only be able to have connections originating on the local machine where SQL Server is installed. You need to expressly enable networking protocols
this msdn website it gives you total info regarding embedding sql server express into custom application http: / / msdn.microsoft.com / en-us / library If you need an embedded database, you should consider the SQL Server 2005 Compact Edition because it might be the better choice over the SQL Server 2005 Express Edition. The Compact Edition is not a released product yet using MSDE, then you might want to start seriously considering SQL Server 2005 Express Edition or Compact Editions Hi, Someone with administrator privileges on the machine, would need to sign in the SQL Server Express and add you as a member of the sysadmin server role. You would then be a "SQL Administrator" and perfrom below tasks. 1. If you don't
How to add SQL SERVER Database to a Windows Desktop project ? Hi all. . . . . . . . . I to develop a Windows Application. How to compact it with SQL Server database . . ( Steps for adding database ) And How to connect with the database ? ( Code for connectivity ). . . . . . I use VS 2008 (SQL Server 2005) Regards. . . . . . . . . . . . . . . hi For ASP.NET 2.0 applications, you should store connection strings in the your Web pages, use the ConnectionStrings: qualifier in an ASP.NET expression to use a connection string stored in your application microsoft.com / en-us / library / ff647396.aspx http: / / www.asp.net / mvc / tutorials / authenticating-users-with-forms-authentication-cs First I suggest you to learn ADO.Net You connect to database using SQLCONNECTION The sequence of operations SqlConnection. • Open the connection. • Pass the connection to other ADO.NET objects. • Perform database operations with the other ADO.NET objects. • Close the connection. Use these namespaces using System; using SqlConnection( "Data Source = (local);Initial Catalog = Northwind;Integrated Security = SSPI"); SqlDataReader rdr = null; try { / / 2. Open the connection conn.Open(); / / 3
ASP.NET Forms Authentication Hello I just uploaded my MVC 3 site the following error: Failed to generate a user instance of SQL Server due to failure in retrieving the user's local Data.SqlClient.SqlException: Failed to generate a user instance of SQL Server due to failure in retrieving the user's local Trace: [SqlException (0x80131904): Failed to generate a user instance of SQL Server due to failure in retrieving the user's local 234 System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2275 System.Data.SqlClient.SqlInternalConnectionTds userName, String password, String email) in C: \ Users \ Ismael \ Documents \ Visual Studio 2010 \ Projects \ MVCPRACTICE \ MVCPRACTICE \ Models \ AccountModels.cs:127 MVCPRACTICE.Controllers AccountController.Register(RegisterModel model) in C: \ Users \ Ismael \ Documents \ Visual Studio 2010 \ Projects \ MVCPRACTICE \ MVCPRACTICE \ Controllers \ AccountController.cs:91 lambda_method(Closure HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184 Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0
it contains a great set of documentation on using ADO.Net data services in Silverlight. I found one more good article Calling a WCF service from your Silverlight application • Consuming ADO.NET Data Service (Astoria) from Silverlight refer the links also http: / / michaelsync.net / 2008 / 03 / 10 / silverlight-2-beta1-database-operations-with-aspnet LastName FROM Person" ; cmd . CommandType = CommandType . Text ; cn . Open (); using ( SqlDataReader dr = cmd . ExecuteReader ()) { while ( dr . Read ()) { list . Add ( dr . GetString wcf / Hi, Try this • Created Silverlight 4 web application in Visual Studio 2010 (Windows 7) • Added a SQL database to the "App_Data" folder on the ASP.NET side of the website called "aspnetdb.mdf". I'm running SQL Server Express on my machine. • Wrote a simple WCF webservice that returns