Insert GUID into SQL Table - c#

I'm using ASP.Net/C# and I have a form that allows people to add information into a table and along with it I want to collect the Current Users GUID and insert it.
I have a field setup (UserID) as a unique identifier and I have the following code:
protected void Page_Load(object sender, EventArgs e)
{
MembershipUser currentUser = Membership.GetUser();
Guid temp = (Guid)(Membership.GetUser(User.Identity.Name).ProviderUserKey);
Guid #currentUserID = temp;
}
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\ASPNETDB.MDF;Integrated Security=True;User Instance=True");
SqlCommand cmd;
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("insert into Accom (UserID) values('" + #currentUserID + "')", con);
cmd.ExecuteNonQuery();
}
I basically want to link the variable to the Database any idea how as the above gives errors.

You should never insert values directly into a SQL statement like that, no matter what type they are, as that opens you up to a SQL Injection attack. Instead, you should use parameters in your query, through which System.Guid values will be automatically translated to the SQL Server uniqueidentifier type. This is how I would do it:
Guid currentUserId = (Guid)(Membership.GetUser(User.Identity.Name).ProviderUserKey);
using (var connection = new SqlConnection("..."))
using (var command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO Accom (UserID) VALUES (#UserID)";
var param = command.Parameters.Add("#UserID", SqlDbType.UniqueIdentifier);
param.Value = currentuserId;
connection.Open();
command.ExecuteNonQuery();
}

Guid #currentUserID = temp;
You are defining a variable currentUserID in local scope - you must save this variable in the Session so you can access it in the Button1_Click method:
Session["UserId"] = currentUserID;
Now you can retrieve it in Button1_Click:
Guid currentUserID = (Guid)Session["UserId"];
Also the # is not needed nor should it be there, you only should need it if you want to define variables with a name that matches a C# keyword - this is bad style anyway. Also you want to put the SqlConnection specific code all within the button click handler - otherwise this variable is instantiated evertime the page loads, not just when the button click handler is used. Finally you also want to use SqlParameters instead of strings in your SQL insert statement.
Edit:
As #pst pointed out, the more "ASP.NET way" would be to just use an instance variable
Guid currentUserID;
that you declare as part of the class, not within a method - then you can use this variable throughout the page. This means however, the user id will not be available on other pages (with a session it could be retrieved through the life time of the session on any page).

I dont know if SQL server supports GUID as a datatype, in MysQL I would go with a char, but that is not important, just a comment. The important part is that in the method:
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("insert into Accom (UserID) values('" + #currentUserID + "')", con);
cmd.ExecuteNonQuery();
}
You don't specify the actual value for #currentUserID
you must rewrite it to something like:
protected void Button1_Click(object sender, EventArgs e)
{
SqlParameter param = new SqlParameter();
con.Open();
cmd = new SqlCommand("insert into Accom (UserID) values(#currentUserID)", con);
//this are the important lines that I'm talking about
param.ParameterName = "#currentUserID";
param.Value = valueOfUserId;
cmd.Parameters.Add(param);
cmd.ExecuteNonQuery();
}
Hope that helps.

In the original code above the currentUser variable is unused. Also if the user is not logged on the call to Membership.GetUser(User.Identity.Name) will return a null reference and trying to retrieve ProviderUserKey code will throw a NullReferenceException. It would be better to have something along these lines;
public partial class Default : System.Web.UI.Page
{
MembershipUser currentUser;
protected void Page_Load(object sender, EventArgs e)
{
currentUser = Membership.GetUser();
}
protected void Button1_Click(object sender, EventArgs e)
{
if (null != currentUser)
{
Guid currentUserID = currentUser.ProviderUserKey;
// database code here
}
}
}

Related

Forms app wont accept my SQL table column with usernames, but it will accept the password

I'm creating a forms application which needs a login function. I have set up the MySqL connection and have applied it to my form. It does answer to my to responses, giving me a respons with a pass or no pass, BUT this is only when I ask for it to only match the input with passwords in the database. I cannot get it to match both the usernames and the passwords, even though I seem to have configurated my table as it should be. I've got 3 columns with ID, username(brugernavn) and password.
I can get it to accept both credentials if I match the ID's with the right password, fx SELECT * FROM bruger WHERE password =#pass AND id=#usn
I'm still very new to programming so if I'm confused please let me know.
Is anyone able to help?
I've tried to change my parameters to something else, but that didnt do the trick. There didnt seem to be a problem with the actual table, as it could acces my information about the passwords and the ID's, so I tried changing some values and stuff from the username column, but it did no good. I have both the username and password using varchar(100) and the ID is using INT(11) as a primary.
MySqlConnection connection = new MySqlConnection("server=localhost;port=3306;username=root;password=;database=bruger");
public void openConnection()
{
if (connection.State == System.Data.ConnectionState.Closed)
{
connection.Open();
}
}
public void closeConnection()
{
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
}
}
public MySqlConnection GetConnection()
{
return connection;
}
private void Loginbutton_Click(object sender, EventArgs e)
{
DB db = new DB();
string username = textBoxBrugernavn.Text;
string password = textBoxPassword.Text;
DataTable table = new DataTable();
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand command = new MySqlCommand("SELECT * FROM bruger WHERE password =#pass AND brugernavn =#usn", db.GetConnection());
command.Parameters.Add("#usn", MySqlDbType.VarChar).Value = username;
command.Parameters.Add("#pass", MySqlDbType.VarChar).Value = password;
adapter.SelectCommand = command;
adapter.Fill(table);
if (table.Rows.Count > 0)
{
MessageBox.Show("YES");
}
else
{
MessageBox.Show("NO");
}
I was hoping this would let me run my forms apps and then let me login with already created users in my database. This however is not the case, as I am unable to match these two informations in the application.
Keep you data objects local. Then you can be sure they are closed and disposed. The using blocks take care of that even if there is an error. Since we only need one piece of data (the count) we can use ExecuteScalar which returns the first column of the first row in the result set. Of course, in a real application, you would never store passwords as plain text. They would be salted and hashed.
private void Loginbutton_Click(object sender, EventArgs e)
{
Int64 RecordCount = 0;
using (MySqlConnection cn = new MySqlConnection("server=localhost;port=3306;username=root;password=;database=bruger"))
{
using (MySqlCommand command = new MySqlCommand("SELECT Count(*) FROM bruger WHERE password =#pass AND brugernavn =#usn", cn))
{
command.Parameters.Add("#usn", MySqlDbType.VarChar).Value = textBoxBrugernavn.Text;
command.Parameters.Add("#pass", MySqlDbType.VarChar).Value = textBoxPassword.Text;
cn.Open();
RecordCount = (Int64)command.ExecuteScalar();
}
}
if (RecordCount > 0)
{
MessageBox.Show("YES");
//Add code to proceed to your next form
}
else
{
MessageBox.Show("NO");
}
}

c# mysql query to If statement

So I'm trying to create simple button that decides if you are admin or user.
But I cant get it to work properly. I'm connected to MySQL db but when I click button with either admin/user account (stored in db) I get:
"you are an admin"
So I guess I have mistake somewhere but cant see where:
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection cn = new MySqlConnection("Server=;Database=;Uid=;Pwd=;");
MySqlCommand cmd = new MySqlCommand("SELECT usertype FROM table1 ", cn);
cmd.Parameters.AddWithValue("usertype", usertype.Text);
cn.Open();
string usertype123 = cmd.ExecuteScalar()?.ToString();
if (usertype123 == "admin")
{
MessageBox.Show("you are an admin");
}
else
{
MessageBox.Show("You are an user ");
}
cn.Close();
}
If you don't add a WHERE statement to your sql command you will always retrieve the value from the first column of the first row returned by the database engine. You should change your code to something like this
private void button1_Click(object sender, EventArgs e)
{
// I assume you have a field named UserID as the primary key of your table1
string sqlCmd = #"SELECT usertype FROM table1 WHERE UserID=#id";
using(MySqlConnection cn = new MySqlConnection("....."))
using(MySqlCommand cmd = new MySqlCommand(sqlCmd, cn))
{
cmd.Parameters.Add("#id", MySqlDbType.Int32).Value = currentUserid;
cn.Open();
string usertype123 = cmd.ExecuteScalar()?.ToString();
if (usertype123 == "admin")
{
MessageBox.Show("you are an admin");
}
else
{
MessageBox.Show("You are an user ");
}
}
}
Now the problem is how to define the variable currentUserId This is something that you need to retrieve when the user logs in and conserve at the class level to reuse when needed. Notice also that connections are disposable objects and as such your need to dispose them as soon as you have finished to use them. The using statement helps to do this

How to check if Username exists in specific column of database

I'm using C# with an ASP.Net table. I'm trying to check when a user accesses my web app, that their User ID is listed in the column called UserID in a table that is displayed in the web app. If it is not, then I want to redirect them to an error page.
I need this to check when the page is loaded so obviously it needs to be in Page_Load. I just don't know how to call the column in my table and to have it check the User ID.
This is what I have so far:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string UserID = HttpContext.Current.Request.LogonUserIdentity.Name.Substring(4);
SQLUserID();
if (UserID != //'Whatever values are in the UserID column'//)
{
Server.Transfer("ErrorPage.aspx");
}
SQLCmd = SqlDataSource1.SelectCommand;
GridView1.DataBind();
}
}
The string UserID gives me the User ID of the user. SQLUserID() = SELECT UserId FROM Info. I know the way I called that isn't correct but I'm not sure how to do it.
It can help you:
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand check_User_Name ("SELECT COUNT(*) FROM tblUser WHERE (UserID=#UserID)",conn);
check_User_Name.Parameters.AddWithValue("#UserID,UserID);
int userExist=(int)check_User_Name.ExecuteScalar();
if(userExist>0)
{
//Login
}
else
{
Server.Transfer("ErrorPage.aspx");
}
just write your connection string and enjoy it.
So here is how I got it to work below Page_Load
{
string connectionString = "Data Source=###;Initial Catalog=###;Integrated Security=True";
if (!Page.IsPostBack)
{
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
using (SqlCommand sqlCommand = new SqlCommand("SELECT COUNT(UserID) from Info WHERE UserID like #UserID", sqlConnection))
{
string UserID = HttpContext.Current.Request.LogonUserIdentity.Name.Substring(4);
sqlCommand.Parameters.AddWithValue("#UserID", UserID);
int userCount = (int)sqlCommand.ExecuteScalar();
if (userCount == 0)
{
Server.Transfer("ErrorPage.aspx");
}
SQLCmd = SqlDataSource1.SelectCommand;
GridView1.DataBind();
}
}
}

SQL delete command advice using c#

On click button presents the following code,
For some reason it wont delete data from database, (the dropdownlist is valid) any advice or changes needed?
protected void deleteback_Click(object sender, EventArgs e)
{
// declare variables
String EditNewID = DropDownList3.SelectedItem.Value;
// set connection string to database
String connectionString = WebConfigurationManager.ConnectionStrings["ScrumString"].ConnectionString;
SqlConnection myConnection2 = new SqlConnection(connectionString);
// delete values to product backlog
myConnection2.Open();
String query = "DELETE * FROM product_backlog WHERE product_backlog.id = #id ";
SqlCommand commanddelete = new SqlCommand(query, myConnection2);
commanddelete.Parameters.AddWithValue("#id", EditNewID);
// refresh page
Page.Response.Redirect(Page.Request.Url.ToString(), true);
commanddelete.ExecuteNonQuery();
myConnection2.Close();
}
maybe you are creating one string ID instead an integer
Try something like
commanddelete.Parameters.Add("#id", SqlDbType.Int);
commanddelete.Parameters["#id"].Value = Int32.Parse(customerID);

Update Statement into Textboxes c# data type mismatched in criteria

Attempting to use the update Statement but when I execute the program it claims:
user type mismatch in data criteria
When I click the updatebutton, I want for the database to update where ID =
private void Update_Click(object sender, EventArgs e)
{
//OPENING CONNECTION
db.Open();
int idd = int.Parse( InstructorIDText.Text);
OleDbCommand df = new OleDbCommand("UPDATE Instructors SET FirstName='"+FNText.Text+"',LastName='"+Lntext.Text+"',Street='"+StreetText.Text+"',City='"+CityText.Text+"',State='"+StateText.Text+"',Zip='"+ZipText.Text+"',Office='"+OfficeText.Text+"',EMail='"+EmailText.Text+"' WHERE ID = " + idd +"", db);
//creating parameters
df.Parameters.AddWithValue("#ID", InstructorIDText.Text);
df.Parameters.AddWithValue("#FirstName", FNText.Text);
df.Parameters.AddWithValue("#LastName", Lntext.Text);
df.Parameters.AddWithValue("#Street", StreetText.Text);
df.Parameters.AddWithValue("#City", CityText.Text);
df.Parameters.AddWithValue("#State", StateText.Text);
df.Parameters.AddWithValue("#Zip", ZipText.Text);
df.Parameters.AddWithValue("#Office", OfficeText.Text);
df.Parameters.AddWithValue("#EMail", EmailText.Text);
df.ExecuteNonQuery();
db.Close();
}
Use #parameter in query instead of concatenating exact values
For MS-SQL
//OPENING CONNECTION
db.Open();
int idd = int.Parse(InstructorIDText.Text);
OleDbCommand df = new OleDbCommand("UPDATE Instructors SET FirstName=#FirstName,LastName=#LastName,Street=#Street,City=#City,State=#State,Zip=#Zip,Office=#Office,EMail=#EMail WHERE ID = #ID", db);
//creating parameters
df.Parameters.AddWithValue("#ID", InstructorIDText.Text);
df.Parameters.AddWithValue("#FirstName", FNText.Text);
df.Parameters.AddWithValue("#LastName", Lntext.Text);
df.Parameters.AddWithValue("#Street", StreetText.Text);
df.Parameters.AddWithValue("#City", CityText.Text);
df.Parameters.AddWithValue("#State", StateText.Text);
df.Parameters.AddWithValue("#Zip", ZipText.Text);
df.Parameters.AddWithValue("#Office", OfficeText.Text);
df.Parameters.AddWithValue("#EMail", EmailText.Text);
df.ExecuteNonQuery();
db.Close();
When using add with value use the variable idd instead of the .Text property. The query is expecting an int for your #id parameter but you are supplying a string.
See if that helps

Categories