Filter out duplicate Users Asp.Net - sql

So I made a Registration page and a SQL table(Students Table) in the back end. In the code behind of my registration page.aspx I've got a sql query to count the number of StudentName in the db and if the count is equal to 1 then inform the user attempting to register that the student already exist in the database. However every time I test it the count is always 0, even when I register using a student name that is already in the db.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkUser = "select count(*) from Students where StudentName='" + txtStudentName.Text + "'";
SqlCommand com = new SqlCommand(checkUser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("Student already exist");
}
conn.Close();
}
}

Related

ADO.net Performing Multiple queries (ExecuteQuery & ExecuteScalar) and displaying the result in a web form control

Hey wish you all to have a happy holiday,
I am trying to display multiple query results from a SQL database table to a grid view control and a label. I have no problem with the grid view result, but the result from the ExecuteScalar command is not displaying inside my lable control with an ID="myCount". I could not figure out what went wrong with my code. I need your help.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MBSDB"].ConnectionString);
try {
conn.Open();
string query="SELECT * FROM tblBook";
using (SqlCommand mycmd = new SqlCommand(query, conn)) {
myGrid.DataSource = mycmd.ExecuteReader();
myGrid.DataBind();
}
string query2 = "SELECT count(title) FROM tblBook";
using (SqlCommand mycmd2 = new SqlCommand(query2, conn)) {
int count = (int)mycmd2.ExecuteScalar();
myCount.Text = count.ToString();
}
}
catch {
Exception(e);
}
finally { conn.Close(); }
}
Are you sure about there is no error. I think, the error occured and handling in the catch block and you are unaware of it.
You should change it;
(int)mycmd2.ExecuteScalar();
to
Convert.ToInt32(mycmd2.ExecuteScalar());
You can't unboxing an object like this; (int)mycmd2.ExecuteScalar()

Login form in ASP.net does not work

I'm new to ASP.net and currently failing to create a simple functioning login form. After establishing the connection to my database, I wanted the function to check whether a given combination of username and password exists in the database. Due to the fact that I have not created the "member zone" page yet, It's supposed to do nothing if the data is valid and return "Login failed" in the opposite case. For some reason, it doesn't work. I would be glad if someone could help me trace the problem.
protected void Login_Click(object sender, EventArgs e)
{
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ToString());
string query = "SELECT * FROM users WHERE username='" + UserName.Text +
"' AND password='" + Password.Text + "' ";
SqlCommand cmd = new SqlCommand(query, con);
string output = cmd.ExecuteScalar().ToString();
if (output == "1")
{
//Creating a session for the user
Session["user"] = UserName.Text;
Response.Redirect("");
}
else
Response.Write("Login failed.");
}
You have SELECT * FROM in the query and you are using ExecuteScalar method to check if anything is returned.
You should use SELECT COUNT(*) FROM to get the number of rows exist in the table for given username and password.
Another thing which is not right in your code is the generation of query. Using parameterized query is the most recommended approach.
protected void Login_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ToString());
string query = "SELECT COUNT(*) FROM users WHERE username=#userName AND password=#password";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add(new SqlParameter("#userName", UserName.Text));
cmd.Parameters.Add(new SqlParameter("#password", Password.Text));
con.Open();
string output = cmd.ExecuteScalar().ToString();
if (output == "1")
{
//Creating a session for the user
Session["user"] = UserName.Text;
Response.Redirect("");
}
else
{
Response.Write("Login failed.");
}
This should resolve your issue.
You forgot to open connection before executing ExecuteScalar()
protected void Login_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ToString());
string query = "SELECT COUNT(*) FROM users WHERE username=#userName AND password=#password";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add(new SqlParameter("#userName", UserName.Text));
cmd.Parameters.Add(new SqlParameter("#password", Password.Text));
//Add Below line and test your code.
con.Open();
string output = cmd.ExecuteScalar().ToString();
if (output == "1")
{
//Creating a session for the user
Session["user"] = UserName.Text;
Response.Redirect("");
}
else
{
Response.Write("Login failed.");
}

Manually Sorting Data in Gridview in asp.Net Webforms

I am having some difficult manually sorting data on a gridview. I used a dataset and when set the AllowSort to true and also wrote the code to handle the sort based on the guide given on https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx . However, when I run my code, the data displays but when I click the header of each column, nothing happens.
here is my code
protected void Page_Load(object sender, EventArgs e)
{
string connstring = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
SqlConnection conn = new SqlConnection(connstring);
conn.Open();
SqlCommand comm = conn.CreateCommand();
comm.CommandText = "SELECT Count(Student.StudentID) AS StdCount, Schools.Name, Schools.StartDate, School.SchoolFees FROM Schools INNER JOIN Students ON Schools.SchoolID = Student.SchoolID WHERE School.Active = 1 GROUP BY Schools.Name, Schools.StartDate, Schools.SchoolFess ORDER BY Schools.Name ASC";
SqlDataAdapter da = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables.Count > 0)
{
DataTable dt = ds.Tables[0];
ViewState["datable"] = dt;
}
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = (DataTable)ViewState["datable"];
if (dt != null)
{
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
GridView1.DataSource = ViewState["datable"];
GridView1.DataBind();
}
}
private string GetSortDirection(string column)
{
// By default, set the sort direction to ascending.
string sortDirection = "ASC";
// Retrieve the last column that was sorted.
string sortExpression = ViewState["SortExpression"] as string;
if (sortExpression != null)
{
// Check if the same column is being sorted.
// Otherwise, the default value can be returned.
if (sortExpression == column)
{
string lastDirection = ViewState["SortDirection"] as string;
if ((lastDirection != null) && (lastDirection == "ASC"))
{
sortDirection = "DESC";
}
}
}
// Save new values in ViewState.
ViewState["SortDirection"] = sortDirection;
ViewState["SortExpression"] = column;
return sortDirection;
}
Any help will be appreciated. Thanks
You need to bind the DefaultView of the DataTable, which is this orderly, not ViewState variable.
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = (DataTable)ViewState["datable"];
if (dt != null)
{
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
GridView1.DataSource = dt.DefaultView;
GridView1.DataBind();
}
}
This looks to be a Page LifeCycle issue.
Every time you post back the entire Page LifeCycle runs
In your case you are retrieving and overwriting ViewState["datable"] on every postback, assuming of course that if (ds.Tables.Count > 0) evaluates to true.
And then you do this in Page Load:
GridView1.DataSource = ds;
but in your sorting routine you access:
DataTable dt = (DataTable)ViewState["datable"];
...
GridView1.DataSource = ViewState["datable"];
You just replaced GridView.DataSource, which initially was a DataSet, with a DataTable
Wrap your initial data Retrieval in PageLoad like this
if( !Page.IsPostback )
{
// This retrieves Data once, and you persist it
// in the ViewState no need to Keep retrieving it
// unless the data has changed
}
// Rebind outside the if
GridView1.DataSource = (DataTable) ViewState["datable"];
GridView1.DataBind();
Addendum
Per Andrei he is correct. ViewState is a hidden field on your rendered ASPX. View the page source in your browser and search for
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="" />
It's Ok to use as a learning aid as long as the dataset is small and doesn't contain any confidential information.
But as it's transmitted to and from your page on every postback you incur a lot of overhead. Imagine if your DataSet contained several thousand rows.
Session State is a better option, but the Application Cache is better still. Server Data Controls like SqlDataSource make use of this cache and so can you. Access it just like ViewState:
ViewState["datable"] = dt;
Cache["datable"] = dt;
But don't go crazy with it. ViewState, SessionState, Cookies, LocalStorage, etc all have their place, learn them.

Is there any replacement of Top in Sql dependency in signalr?

Can you please let me know how can i use Top or other sql statement in sql dependency to get Top 5 records, whenever i use this Top its always shows Sql NotificationType Subscribe.
Please help me out to get top records using query in SignalR
When i tried this its is working fine
public void SendStocksNotifications(string symbol="")
{
string conStr = ConfigurationManager.AppSettings["myConnectionString"].ToString();
using (var connection = new System.Data.SqlClient.SqlConnection(conStr))//"data source="";initial catalog="";persist security info=True;user id="";password="";multipleactiveresultsets=True;application name=EntityFramework""))
{
string newdate = DateTime.Now.ToString( "MM/dd/yyyy" );
string query = "SELECT TOP 1 [Close],Pre_Close, Volume, Pre_Volume, PercentageChange, Pre_PercentageChange, NetChange, Pre_NetChange, High, Low, Pre_High, Pre_Low,Previous, Pre_Previous, [52WH], [52WL] FROM [dbo].[History] WHERE Symbol='" + symbol + "' ORDER BY UpdatyedDate DESC";
connection.Open();
using ( SqlCommand command = new SqlCommand( query, connection ) )
{
}
}
}
But this code
private void dependency_OnChange1(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
string symbol = Vsymbol;
NotificationStocks nHub = new NotificationStocks();
nHub.SendStocksNotifications( symbol );
}
}
shows e.Type=SqlNotificationType.Subscribe.

Values not updates after update query

I am developing a project in ASP.NET with c# and SQL Server 2005 as back end. It includes a page profile.aspx which displays the information of a user from database. The session variable is used to keep track of the current logged in user.
The profiles table in the database contains a username column and 10 others columns like dept, address, contact, skills, interests etc etc.
I am displaying all these values on profile.aspx. Another page is edit_profile.aspx which comes up when the edit button on profile.aspx is clicked. Here the data is displayed in textboxes, with older entries already displayed, which can be edited, and click the Update button to confirm.
The update query runs fine, there is no error, but the values are not updates in the database tables. What is the possible reason? Solution?
Thank you
protected void Page_Load(object sender, EventArgs e)
{
string CNS = ConfigurationManager.ConnectionStrings["myconn"].ToString();
SqlConnection con = new SqlConnection(#CNS);
SqlDataAdapter sda = new SqlDataAdapter("select * from profiles where username='" + Session["currentusername"].ToString()+"'", con);
DataSet ds = new DataSet();
sda.Fill(ds, "profiles");
txt_name.Text = ds.Tables["profiles"].Rows[0][0].ToString();
txt_deptt.Text = ds.Tables["profiles"].Rows[0][1].ToString();
txt_qualificatns.Text = ds.Tables["profiles"].Rows[0][2].ToString();
txt_add.Text = ds.Tables["profiles"].Rows[0][3].ToString();
txt_contacts.Text = ds.Tables["profiles"].Rows[0][4].ToString();
txt_interests.Text = ds.Tables["profiles"].Rows[0][5].ToString();
txt_awards.Text = ds.Tables["profiles"].Rows[0][6].ToString();
txt_website.Text = ds.Tables["profiles"].Rows[0][7].ToString();
txt_skills.Text = ds.Tables["profiles"].Rows[0][8].ToString();
txt_mstatus.Text = ds.Tables["profiles"].Rows[0][9].ToString();
ds.Reset();
}
protected void Button1_Click(object sender, EventArgs e)
{
string CNS = ConfigurationManager.ConnectionStrings["myconn"].ToString();
SqlConnection con = new SqlConnection(#CNS);
SqlCommand sda = new SqlCommand("update profiles set department='"+txt_deptt.Text+"',qualifications='"+txt_qualificatns.Text+"', address='"+txt_add.Text+"', contacts='"+txt_contacts.Text+"', interests='"+txt_interests.Text+"', awards='"+txt_awards.Text+"', website='"+txt_website.Text+"', skills='"+txt_skills.Text+"', mstatus='"+txt_mstatus.Text+"' where username='" + Session["currentusername"].ToString() + "'", con);
DataSet ds = new DataSet();
try
{
con.Open();
int temp=sda.ExecuteNonQuery();
con.Close();
if (temp >= 1)
{
lbl_message.ForeColor = System.Drawing.Color.Green;
lbl_message.Text = "Profile Updated Successfully!";
}
else
{
lbl_message.ForeColor = System.Drawing.Color.Red;
lbl_message.Text = "Integer less than 1";
}
}
catch
{
lbl_message.ForeColor = System.Drawing.Color.Red;
lbl_message.Text = "Try Again Later, An Error Occured!";
}
//Response.Redirect("profile.aspx");
}
}
You are overwriting the contents of your textboxes every time the page loads so the user inputted conntet is never written to the database...
Look at the Page.IsPostBack method. Basically, wrap the commands to fill the textboxes with
if (!Page.IsPostBack) {}
To only load the values into the text box the first time the page loads (and so not overwrite the user entered values when you click the button you need to check that the page isn't a post back.
I think maybe a book on basic ASP.Net will help answer many questions you may have early on.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) {
string CNS = ConfigurationManager.ConnectionStrings["myconn"].ToString();
SqlConnection con = new SqlConnection(#CNS);
SqlDataAdapter sda = new SqlDataAdapter("select * from profiles where username='" + Session["currentusername"].ToString()+"'", con);
DataSet ds = new DataSet();
sda.Fill(ds, "profiles");
txt_name.Text = ds.Tables["profiles"].Rows[0][0].ToString();
txt_deptt.Text = ds.Tables["profiles"].Rows[0][1].ToString();
txt_qualificatns.Text = ds.Tables["profiles"].Rows[0][2].ToString();
txt_add.Text = ds.Tables["profiles"].Rows[0][3].ToString();
txt_contacts.Text = ds.Tables["profiles"].Rows[0][4].ToString();
txt_interests.Text = ds.Tables["profiles"].Rows[0][5].ToString();
txt_awards.Text = ds.Tables["profiles"].Rows[0][6].ToString();
txt_website.Text = ds.Tables["profiles"].Rows[0][7].ToString();
txt_skills.Text = ds.Tables["profiles"].Rows[0][8].ToString();
txt_mstatus.Text = ds.Tables["profiles"].Rows[0][9].ToString();
ds.Reset();
}
}