Code Not Preventing Duplicate E-mail Addresses in Database - c#

The code I have is allowing duplicate e-mails to be added to the database. I added a line of code before allowing entry into the database to prevent duplicate e-mail addresses to be added, however with this code I am still getting duplicate e-mails. I have provided both the form code in asp.net & the c# code. Please help.
Originally I was getting an error & I debugged the code in VS & realized that I actually had the wrong specification for the email entry, that has been corrected. In the VS debugger I see values for TextBox1.Text & TextBox2.Text, i also see the e-mail address passing through the string query = the issue however is that even if the e-mail is already in the database, it still gets added again. Any improvements to fix this issue with my code? Is my logic wrong perhaps?
c# code:
protected void Button1_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["northwind"].ToString();
con.Open();
string query = "SELECT COUNT(ID) FROM Table1 WHERE pEmail= '" + TextBox2.Text +"'";
OleDbCommand cmd = new OleDbCommand(query, con);
var count = cmd.ExecuteNonQuery();
if (count > 0)
{
Label1.Text = "email is already in use";
}
else {
cmd.CommandText = "insert into[Table1](pName, pEmail)values(#nm,#em)";
cmd.Parameters.AddWithValue("#nm", TextBox1.Text);
cmd.Parameters.AddWithValue("#em", TextBox2.Text);
cmd.Connection = con;
int a = cmd.ExecuteNonQuery();
if (a>0)
{
Label1.Text = "Inserted Sucessfully!";
}
}
}
}
Form Code:
<form id="form1" runat="server">
<div style="height: 138px">
Enter Name:<asp:TextBox ID="TextBox1" runat="server" style="margin-left: 12px"></asp:TextBox>
<asp:RequiredFieldValidator
id="reqName"
ControlToValidate="TextBox1"
Style="color:Red"
ErrorMessage="Please enter your name!"
runat="server" />
<br />
Enter Email:
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator
id="ValidEmail"
ControlToValidate="TextBox2"
Style="color:Red"
ValidationExpression="^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"
ErrorMessage="Invalid Email Entry"
runat="server" />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</form>

You should use ExecuteScalar instead of ExecuteNonQuery to get the row count
Original:
var count = cmd.ExecuteNonQuery();
Suggest to change:
var count = cmd.ExecuteScalar();
Refer to https://stackoverflow.com/a/4269651/1050927
The ExecuteNonQuery Method returns the number of row(s) affected by either an INSERT, an UPDATE or a DELETE. This method is to be used to perform DML (data manipulation language) statements as stated previously.
The ExecuteScalar Method will return a single value in the first row, first column from a SELECT statement. This method is to be used when you expect only one value from the query to be returned.

Use ExecuteScalar and Convert the result to int. I also recommend you to change the sql query concatenation to parameters, and if you are using ASP.NET Validators, you must check the property IsValid of the page as it will tell you if the controls has passed validation (remember that users can disable javascript and post the form).
protected void Button1_Click(object sender, EventArgs e)
{
if (IsValid)
{
using (var con = new OleDbConnection())
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["northwind"].ToString();
con.Open();
using (var cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT COUNT(ID) FROM Table1 WHERE pEmail= #em";
cmd.Parameters.AddWithValue("#em", TextBox2.Text);
int count = Convert.ToInt32(cmd.ExecutScalar());
if (count > 0)
{
Label1.Text = "email is already in use";
}
else
{
cmd.CommandText = "insert into[Table1](pName, pEmail)values(#nm, #em)";
cmd.Parameters.AddWithValue("#nm", TextBox1.Text);
// not need to add #em parameter, it was added previously
int insertedRows = cmd.ExecuteNonQuery();
if (insertedRows > 0)
{
Label1.Text = "Inserted Sucessfully!";
}
}
}
}
}
}

Related

Searching between 2 column numbers

I want to validate in my webform i have 1 textbox and i want to search number and if the number i search is between the range of 2 numbers in my 2 column i want to show the data in the row of my table.
select * from SSPRequest where StartingSeries = '" + TxtSearch.Text + "' BETWEEN EndingSeries= '"+TxtSearch2.Text+"'"
Well, drop a grid view, and then say have this code:
protected void cmdSearch_Click(object sender, EventArgs e)
{
string strSQL = "select * from SSPRequest where StartingSeries >= #Start " +
" AND EndingSeries <= #End";
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST3))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Parameters.Add("#Start", SqlDbType.Int).Value = txtSearch.Text;
cmdSQL.Parameters.Add("#End", SqlDbType.Int).Value = txtSearch2.Text;
conn.Open();
GridView1.DataSource = cmdSQL.ExecuteReader();
GridView1.DataBind();
}
}
}
So whatever the sql matches, the grid will display. Your markup could be say this:
Enter Start Number:
<asp:TextBox ID="txtSearch" runat="server" Style="width:25px;padding-right:25px"></asp:TextBox>
Enter End Number:
<asp:TextBox ID="txtSearch2" runat="server" Style="width:25px;padding-right:25px"></asp:TextBox>
<asp:Button ID="cmdSearch" runat="server" Text="Search" style="padding-left:25px;" CssClass="btn" OnClick="cmdSearch_Click" />
<br />
<br />
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
Looking at your sql posted, it seems a bit wonkey, and does not make sense. I would fire up sql studio, and hand code the sql with two range values and get the sql working, THEN AND ONLY THEN would I attempt the above code.
So FIRST get a working sql statement BEFORE YOU WRITE ONE line of code.

ASP.NET - Unable to insert data into database

I know that the connection string is not the problem because I can read data from the database fine but I cannot figure out why I cannot insert data into the database.
.aspx file
<div class="column one-second">
<asp:TextBox placeholder="Your name" type="text" name="name" id="namelbl" size="40" aria-required="true" aria-invalid="false" runat="server"></asp:TextBox>
</div>
<div class="column one-second">
<asp:TextBox placeholder="location" type="text" name="location" id="LocationLbl" size="40" aria-required="true" aria-invalid="false" runat="server"></asp:TextBox>
</div>
<div class="column one">
<asp:TextBox placeholder="Body" type="text" name="text" id="TextLBL" size="40" aria-required="true" aria-invalid="false" runat="server"></asp:TextBox>
</div>
<div class="column one">
<asp:FileUpload id="FileUpload1" runat="server"> </asp:FileUpload>
<asp:Label ID="lblmessage" runat="server" />
</div>
<div class="column one">
<asp:Button id="submit" Text="Submit" runat="server" OnClick="submit_Click"> </asp:Button>
</div>
C# function
protected void submit_Click(object sender, EventArgs e)
{
Console.WriteLine("BUTTON CLICKED");
string constr = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "INSERT INTO blo(Title, post, location) VALUES (#Title, #post, #location)";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
string title = namelbl.Text;
Console.WriteLine(title);
cmd.Parameters.AddWithValue("Title", title);
string post = TextLBL.Text;
cmd.Parameters.AddWithValue("post", post);
string location = LocationLbl.Text;
cmd.Parameters.AddWithValue("location", location);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Your query was not able to work as you mistype the parameter name in your .AddWithValue().
cmd.Parameters.AddWithValue("Title", title);
cmd.Parameters.AddWithValue("post", post);
cmd.Parameters.AddWithValue("location", location);
The correct way should be:
cmd.Parameters.AddWithValue("#Title", title);
cmd.Parameters.AddWithValue("#post", post);
cmd.Parameters.AddWithValue("#location", location);
RECOMMENDATIONS
1. It is recommended not to use `.AddWithValue()` as the concern mentioned in this [article](https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/). Please ensure that you need to pass the value with **exact datatype and length** that matches the respective table column in the `SqlParameter`.
cmd.Parameters.Add("#Param", <<MySqlDbType>>, <<Length>>).Value = value;
As you apply using block for MySqlConnection, MySqlCommand, you don't have to manually call con.Close() as these IDisposable objects will dispose the resources & connection automatically as mentioned in this article.
(Optional) Add try catch block and get value from ExecuteNonQuery() for verifying the record is inserted into the database and exception handling.
Exception handling will be useful in debugging and handling the exception hit during the execution. At the same time, you can provide a meaningful error message to notify the users.
ExecuteNonQuery() able to return the value indicate
The number of rows affected.
Hence, this will also be useful to return a useful message to notify whether the record is successfully inserted/updated into the database or not.
In the end, your code should be:
try
{
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "INSERT INTO blo(Title, post, location) VALUES (#Title, #Post, #Location)";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
string title = namelbl.Text;
Console.WriteLine(title);
cmd.Parameters.AddWithValue("#Title", title);
string post = TextLBL.Text;
cmd.Parameters.AddWithValue("#Post", post);
string location = LocationLbl.Text;
cmd.Parameters.AddWithValue("#Location", location);
con.Open();
var recordAffected = (int)cmd.ExecuteNonQuery();
if (recordAffected > 0)
{
// Record successfully inserted case
}
else
{
// Record fail inserted case
}
}
}
}
catch (Exception ex)
{
// Handling exception
}
Edited:
Much appreciated and credited to the comment provided by #BradleyGrainger, I had 'strikethrough' recommendation 1 as the concerns mentioned in Can We Stop Using .AddWithValue() are handled by MySql.
Start Using AddWithValue
The primary reason that AddWithValue is OK to use is that MySQL’s text protocol is not typed in a way that matters for client-side type inference.

Save the data in database

Here I am trying to save the data in data base. Whatever data user enters it has to save in database and it has to save in page it self also. when user opens page that data has to display.
Code for aspx page
<asp:Label runat="server" ID="lblCnct" Text="Contact Number" AssociatedControlID="txtCnct" CssClass="control-label" />
<asp:TextBox runat="server" ID="txtCnct" CssClass="form-control" />
<asp:Label runat="server" ID="lblAltCnct" Text="Alternative Contact Number" AssociatedControlID="txtAltCnct" CssClass="control-label" />
<asp:TextBox runat="server" ID="txtAltCnct" CssClass="form-control" />
<asp:Label runat="server" ID="lblEmcnct" Text="Emergency Contact Number" AssociatedControlID="txtEmrCnct" CssClass="control-label" />
<asp:TextBox runat="server" ID="txtEmrCnct" CssClass="form-control" />
Button code saving the data in database
<button type="button" class="btn btn-primary" aria-label="Left Align" runat="server" onserverclick="btnContactInfoSave_click">
code for aspx.cs page
btnContactInfoSave_click code for saving the data in database.
protected void btnContactInfoSave_click(object sender, EventArgs e)
{
string[] ContactInfoData = new string[4];
ContactInfoData[0] = GlobalVars.UserEmail;
ContactInfoData[1] = txtCnct.Text;
ContactInfoData[2] = txtAltCnct.Text;
ContactInfoData[3] = txtEmrCnct.Text;
Utilities.sqlUploadContactInfoData(ContactInfoData);
}
}
public static void sqlUploadContactInfoData(string[] Userdata)
{
using (SqlConnection sqlConn = jPortalDBConnection())
{
try
{
sqlConn.Open();
string spName = "spUploadContactInfoData";
SqlCommand cmd = new SqlCommand(spName, sqlConn);
cmd.Parameters.AddWithValue("#txtCnct", Userdata[0].ToString());
cmd.Parameters.AddWithValue("#txtAltCnct", Userdata[1].ToString());
cmd.Parameters.AddWithValue("#txtEmrCnct", Userdata[2].ToString());
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConn;
cmd.ExecuteNonQuery();
}
catch (SqlException)
{
ErrorMsg("Server Error", "Server Error ! Please try again Later.");
}
}
}
After entering the data when I am trying to save the data it is not saving the data. button is not triggering. Any wrong in this code..???
Try with This. This is the way to Insert data into DB
SQL connection code for connecting database...
public static void sqlUploadContactInfoData(string[] Userdata)
{
using (SqlConnection sqlConn = jPortalDBConnection())
{
try
{
sqlConn.Open();
string spName = "spUploadContactInfoData";
SqlCommand cmd = new SqlCommand(spName, sqlConn);
cmd.Parameters.AddWithValue("#txtCnct", txtCnct.Text);
cmd.Parameters.AddWithValue("#txtAltCnct", txtAltCnct.Text);
cmd.Parameters.AddWithValue("#txtEmrCnct", txtEmrCnct.Text);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConn;
cmd.ExecuteNonQuery();
}
catch (SqlException)
{
ErrorMsg("Server Error", "Server Error ! Please try again Later.");
}
}
}
From your web from designer double click on the button check weather it pointing to the Button event you expected to be invoked.else this will create a event handler for you.
If you are assigning the click handler in code behind, make sure that it is not inside an IsPostBack == false check :
make sure CausesValidation = "false" attribute of button like:
runat="server" and OnClick="btnContactInfoSave_click" check these attribute exist in your asp button
Try button in this way:
<asp:Button ID="AddMore_Button" class="btn btn-primary" runat="server" Text="" OnClick="btnContactInfoSave_click" />

Using a SQL Server Stored Procedure in Visual Studio

My Experience & What I'm Using
So I'm just starting off with a very basic web application in ASP.NET to gain a little more familiarity with SQL Server Management Studios and Visual Studios 2010. Normally, I use MySQL, PHP, and Sublime Text Editor 2. I'm not very experienced with C# and implementing a database in Visual Studios. So I'm trying to use a stored procedure from SQL Server Management Studios and implement it in Visual Studios 2010.
The Issue
So here's my problem: I'm trying to create a basic webpage that links to a SQL Server and be able to add, delete, search and display all records from the database. Now I've written my own code based on what I thought was correct for add/delete and nothing happens when I click the buttons. So I'm sure you can see where my frustration derives from. I'm not sure if the issue is in my C# coding or in my SQL coding.
I'd like to focus on just getting my add/delete buttons to work and then to figure out the logic to display all files. I'd like to be able to click a button and then have it show all files instead of just displaying a grid. My database is called FirstApp.
Here's what's in my web.config file:
<add name="FirstApp" connectionString="Data Source=PCNAME\SQLEXPRESS;Initial Catalog=FirstApp;Integrated Security=True"
providerName="System.Data.SqlClient" />
Now this is what's in my Default.aspx.cs file:
*CORRECT CODE NOW!*
namespace FirstApp
{
public partial class _Default : System.Web.UI.Page
{
public string CommandArgument { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
}
private void MessageBox(string msg)
{
Label lbl = new Label();
lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('" + msg + "')</script>";
Page.Controls.Add(lbl);
}
//Add a new company to the database
protected void add_Click(object sender, EventArgs e)
{
SqlDataReader rdr = null;
string connectionString = null;
SqlConnection cnn;
connectionString = "Data Source=ITXDK29M91\\SQLEXPRESS;Initial Catalog=FirstApp;Integrated Security=True";
cnn = new SqlConnection(connectionString);
try
{
cnn.Open();
SqlCommand cmd = new SqlCommand("dbo.Add_Company", cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#companyname", companyname.Text);
cmd.Parameters.AddWithValue("#companyphone", companyphone.Text);
cmd.Parameters.AddWithValue("#companyid", companyid.Text);
cmd.Parameters.AddWithValue("#companytype", companytype.Text);
rdr = cmd.ExecuteReader();
}
finally
{
//Close the connections
if (cnn != null)
{
cnn.Close();
}
if (rdr != null)
{
rdr.Close();
}
}
}
//Delete a company from the database
protected void delete_Click(object sender, EventArgs e)
{
SqlDataReader rdr = null;
SqlConnection cnn;
string connectionString = null;
connectionString = "Data Source=ITXDK29M91\\SQLEXPRESS;Initial Catalog=FirstApp;Integrated Security=True";
cnn = new SqlConnection(connectionString);
try
{
cnn.Open();
SqlCommand cmd = new SqlCommand("dbo.deleteCo", cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ID", SqlDbType.Int);
rdr = cmd.ExecuteReader();
}
finally
{
//Close the connections
if (cnn != null)
{
cnn.Close();
}
if (rdr != null)
{
rdr.Close();
}
}
}
protected void Search_Click(object sender, EventArgs e)
{
}
protected void Getall_Click(object sender, EventArgs e)
{
}
}
}
This is what's in my Source Code in Default.aspx
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <h2>Ready for an Adventure? Let's get started!
</h2> <hr />This is where you can enter information about your company.
<br />
<form method="post" action="">
Company Name:<br />
<asp:TextBox ID="companyname" runat="server"></asp:TextBox>
<br />
Company Phone Number:<br />
<asp:TextBox ID="companyphone" runat="server"></asp:TextBox>
<br />
Company Tax ID Number:
<br />
<asp:TextBox ID="companyid" runat="server"></asp:TextBox>
<br />
Type of business: <br />
<asp:TextBox ID="companytype" runat="server"></asp:TextBox>
<br />
<asp:Button ID="add" runat="server" BackColor="DeepSkyBlue"
BorderColor="Black" BorderStyle="Solid" BorderWidth="1px"
CssClass="submitButton" Font-Names="Palatino Linotype" ForeColor="White"
onclick="add_Click" Text="Submit" Width="128px" />
</form> <hr />
Want to delete your company information?<br />
Enter in the Company ID Number:
<br />
<asp:TextBox ID="PrimaryKey" runat="server" Width="120px"></asp:TextBox>
<br />
<asp:Button ID="delete" runat="server" BackColor="DeepSkyBlue"
BorderColor="Black" BorderStyle="Solid" BorderWidth="1px"
CssClass="submitButton" Font-Names="Palatino Linotype" ForeColor="White"
onclick="delete_Click" Text="Delete Info" Width="119px" />
<br />
<hr />
Looking for similar companies?
<br />
(Ex: Retail, Designer, Restaurant, etc.)
<br />
Enter the type of company:
<br />
<asp:TextBox ID="scompanyid" runat="server" Width="120px"></asp:TextBox>
<br />
<asp:Button ID="Search" runat="server" BackColor="DeepSkyBlue"
BorderColor="Black" BorderStyle="Solid" BorderWidth="1px"
CssClass="submitButton" Font-Names="Palatino Linotype" ForeColor="White"
onclick="Search_Click" Text="Start Searching!" Width="119px" />
<br />
<hr />
Want to see all the companies that we work with? <br />
Click the button below!
<br />
<asp:Button ID="Getall" runat="server" BackColor="DeepSkyBlue"
BorderColor="Black" BorderStyle="Solid" BorderWidth="1px"
CssClass="submitButton" Font-Names="Palatino Linotype" ForeColor="White"
onclick="Getall_Click" Text="Get all records!" Width="119px" />
<br />
<br />
</asp:Content>
UPDATE: I've updated the code to display the correct code. The add button works but my delete button is not. I'm still trying to figure that one out.
You're not actually opening a connection or executing your SQL commands. Generally, the way you execute a simple command is:
using (var conn = new SqlConnection(connectionString))
{
using (var comm = conn.CreateCommand())
{
conn.Open();
comm.CommandText = "SOME SQL HERE";
// command type, parameters, etc.
//pick one of the following
comm.ExecuteNonQuery();
int value = (int)comm.ExecuteScalar();
SqlDataReader reader = comm.ExecuteReader();
}
}
You need to actually execute the command. There are four types of execution (depending on the type of results you'll be expecting from your query statement)
ExecuteReader - Rows and columns returned (e.g. Normal select queries)
ExecuteNonquery - No results expected. (e.g. Deleting a record)
ExecuteScalar - Single value (e.g. Count, Max, etc..)
ExecuteXMLReader - For XML stuff
Something like this for the add
cmd.ExecuteNonquery();
Even before worrying about executing the command though, you always need an open connection through which you execute commands and you need to link your command to it:
SqlConnection cn = new SqlConnection(connStr);
cn.Command = cmd;
cn.Open();
<your command/parameter code here>
cmd.ExecuteNonquery();
And don't forget to put stuff back the way you found it:
cmd.Close();
cn.Close();
There are other suggestions I'd make--like making the phone number varchar since you're not going to do arithmetic on it as a number--but this is not your real question here and now.
Best wishes!
FYI: Side topic: Whenever you begin to use commands to return results, you will not need a "new" for your SqlDataReaders because commands executed with ExecuteReader create and return an SqlDataReader object. This means you can just do this
//This next line not needed
//dr = new SqlDataReader()
SqlDataReader dr = cmd.ExecuteReader();
It looks like you aren't executing your SQL statements. Try creating a method that does the below then call that method from your delete button click event.
public static void DeleteSomething()
{
using (var conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("usp_proc_delete", conn.CreateCommand()))
{
conn.Open()
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#PrimaryKey", SqlDbType.Int);
cmd.ExecuteNonQuery();
}
}
}

How to insert the selected type of the suggestion into the database?

I am developing a simple suggestion web-based application using ASP.NET with C#. It works well except one thing. I have the following database design:
Table SafetySuggestionsLog
ID, Title, Description, Username, DateSubmitted, TypeID, OtherTypes
Table SafetySuggestionsType
ID, Type
The user will be able to fill the form and submit it. I could be able to insert the username, title, description and datesubmitted to the database. But I have to insert the type either it is one of the types in the database or a new one. I am struggling with this part and I don't know who resolve it. So could you please help me in this? How I can insert the value of type into the database?
ASP.NET Code:
<div ID="contactform">
<ol>
<li>
<label for="subject">Type</label>
<asp:DropDownList ID="DropDownList" runat="server"
DataSourceID="SqlDataSource1" Width="155px" Font-Bold="True"
ForeColor="#006666" AppendDataBoundItems="false" DataTextField="Type"
DataValueField="ID" AutoPostBack="true"
OnDataBound="DropDownList_DataBound"/>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT * FROM [SafetySuggestionsType]"/>
<asp:TextBox ID="TextBox1" runat="server" CssClass="text"/><br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
ControlToValidate="dropdownlist"
ErrorMessage="Please select a type ... or choose Others"/>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server"
ControlToValidate="TextBox1"
ErrorMessage="Please enter a type for your suggestion"/>
</li>
<li>
<label for="subject">Subject</label>
<asp:TextBox ID="txtSubject" runat="server" CssClass="text"/><br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="txtSubject"
ErrorMessage="Please enter a subject/title for your suggestion"/>
</li>
<%--The following hidden field is for inserting the date--%>
<li>
<asp:TextBox ID="dateSubmitted" runat="server" CssClass="text"
Visible="false"/><br />
</li>
<li>
<label for="message">Your Suggestion</label>
<asp:TextBox ID="txtSuggestion" runat="server" cols="50"
CssClass="textarea" rows="6" TextMode="MultiLine"/><br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="txtSuggestion"
ErrorMessage="Please enter your suggestion"/>
</li>
<li class="buttons">
<asp:ImageButton ID="imageField" runat="server"
ImageURL="images/Send.gif" OnClick="btnSubmit_Click" />
<%--<input type="image" name="imageField" id="imageField"
src="images/Send.gif" />--%>
</li>
</ol>
</div>
Code-Behind:
protected void btnSubmit_Click(object sender, ImageClickEventArgs e)
{
SmtpClient sc = new SmtpClient("MAIL.Aramco.com");
StringBuilder sb = new StringBuilder();
MailMessage msg = null;
sb.Append("Message from: " + Service.User.Name + "\n");
sb.Append("Email: " + Service.User.GetProperty("EMP_BINTERMAIL") + "\n");
sb.Append("Type: ");
sb.Append((DropDownList.SelectedItem.Text.Equals("Others")
? TextBox1.Text : DropDownList.SelectedItem.Text) + "\n");
sb.Append("Title: " + txtSubject.Text + "\n");
sb.Append("Suggestion : " + txtSuggestion.Text + "\n");
try
{
msg = new MailMessage(Service.User.GetProperty("EMP_BINTERMAIL"),
"JOHN.ARNESON#ARAMCO.COM", "PSSP: New Safety Suggestion Box",
sb.ToString());
sc.Send(msg);
MultiView1.SetActiveView(ViewConfirm);
}
catch (Exception ex)
{
throw ex;
//Response.Write("Something bad happened!");
}
finally
{
if (msg != null)
{
msg.Dispose();
}
}
//For storing the suggestions in the database
string connString = "Data Source=localhost\\sqlexpress;"
+ "Initial Catalog=psspdbTest;Integrated Security=True";
string insertCommand = "INSERT INTO SafetySuggestionsLog "
+ "(Title, DateSubmitted, Description, Username) values "
+ "(#Title, #DateSubmitted, #Description, #Username)";
string username = Service.User.ID;
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(insertCommand, conn))
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Title", txtSubject.Text);
cmd.Parameters.AddWithValue("#DateSubmitted",
DateTime.Now.ToString());
cmd.Parameters.AddWithValue("#Description", txtSuggestion.Text);
cmd.Parameters.AddWithValue("#Username", username);
cmd.ExecuteNonQuery();
}
}
}
UPDATE:
I modified my code for storing the suggestion information:
//For stroing the suggestions in the database
string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=psspdbTest;Integrated Security=True";
//string insertCommand = "INSERT INTO SafetySuggestionsLog (Title, DateSubmitted, Description, Username) values(#Title, #DateSubmitted, #Description, #Username)";
string insertCommand = #"insert into SafetySuggestionsLog
( Title, Description, Username, DateSubmitted, TypeID, OtherTypes ) values
( #Title, #Description, #Username, #DateSubmitted,
( select ID from SafetySuggestionsType where Type = #Type ), '?' )";
string username = Service.User.ID;
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(insertCommand, conn))
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Title", txtSubject.Text);
cmd.Parameters.AddWithValue("#DateSubmitted", DateTime.Now.ToString());
cmd.Parameters.AddWithValue("#Description", txtSuggestion.Text);
cmd.Parameters.AddWithValue("#Username", username);
cmd.Parameters.AddWithValue("#Type", DropDownList.SelectedValue);
cmd.ExecuteNonQuery();
}
}
And still I could not be able to store the selected type from the dropdownlist. I got (?) under othertype column in the databast and NULL under the Type column even when I selected one of the predefined types. WHY?
A stored procedure can gracefully handle the steps involved.
if not exists ( select 42 from SafetySuggestionsType where Type = #Type )
insert into SafetySuggestionsType ( Type ) values ( #Type )
insert into SafetySuggestionsLog
( Title, Description, Username, DateSubmitted, TypeID, OtherTypes ) values
( #Title, #Description, #Username, #DateSubmitted,
( select TypeId from SafetySuggestionsType where Type = #Type ), '?' )
you can specify parameter type with SqlDbType like this:
cmd.Parameters.Add("#Title",SqlDbType.VarChar, 20);
cmd.Parameters["#Title"].Value = txtSubject.Text;
You can make the type column primary key and when you insert a new type in the database which is already in there an exception will be thrown. So, insert the record inside the try block.
try{
//Do your insertion, if a duplicate item was found, the insertion will not take place
}
catch{
//Do something is an value was inserted which already existed
}

Categories