I'm new to Asp.net, and creating a online telephone bill payment form. A new user has to register to get a valid id,
In the SQL Server I created a table which has only two columns as Phone_number and User_name. I have set the Phone_number column as unique. Just to avoid re-registration of a user.
I have checked the form during runtime using asp.net web page but, i get some error in the code.
Also I have to display a message that "the phone number already exists."
my code is as follows. Is there a better way??
try
{
string s = " insert into new_user values(#Phone_number,#name)";
cmd = new SqlCommand(s, con);
cmd.Parameters.AddWithValue(#"Phone_number", TextBox1.Text);
cmd.Parameters.AddWithValue(#"Name", TextBox2.Text);
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
Console.WriteLine(ex);
MessageBox.Show("Phone Number already exist, Enter a different phone number");
}
TextBox1.Text = TextBox2.Text = null;
Session["a"] = TextBox1.Text;
Response.Redirect("registration.aspx");
}
in the above code if I don't user the Console.Writeline(); I get an error in the ExecuteNonQuerry() part.
I suggest that First you check, Is there same phone no available in database?
Just use select query , If you get any record you can display a message and if not exist any record then use insert query.
If(select * from table where phone=#Phone)
insert command
else
message
Related
Greeting,
I created my own database and used this method by Ankush Agnihotri (Create And Install ASP.NET Membership Database)to create users asnd membership and roles in my web application projects. See link below which method I used:
https://www.c-sharpcorner.com/blogs/create-install-asp-net-membership-database
I designed form to admin site to create an employee account in three steps :
First step :create employee account by (Registration tool) to create user account which will store employee account in Users Table.
Second Step: redirect admin to next page to complete an employee form information.
Until this moment a last two steps working correctly.
Third step: an confirmation appears to admin to catch a ROLE ID and USER ID which represented as (UniqueIdentifier) value to store its in USERSINROLE table as figures below:
A last two steps (one and two) working correctly, but a confirmation catch this problem:
My C# code behind to insert a two parameters in table, I tried in many ways from 1 to 5 but no ways to store a UniqueIdentifier value.
protected void Button1_Command(object sender, CommandEventArgs e)
{
using (SqlConnection sqlcon = new SqlConnection(connString))
{
sqlcon.Open();
string query = "INSERT INTO UsersInRoles(UserId,RoleId) VALUES (#UserId,#RoleId)";
SqlCommand sqlcmd = new SqlCommand(query, sqlcon);
//Try NO.1
//sqlcmd.Parameters.AddWithValue("#UserId",(FormView1.FindControl("l1") as Label).Text);
//sqlcmd.Parameters.AddWithValue("#RoleId", (FormView1.FindControl("L2") as Label).Text);
//Try NO.2
//sqlcmd.Parameters.Add("#UserId", SqlDbType.UniqueIdentifier).Value=(FormView1.FindControl("l1") as Label).Text;
// sqlcmd.Parameters.Add("#RoleId", SqlDbType.UniqueIdentifier).Value=(FormView1.FindControl("L2") as Label).Text;
//Try NO.3
//sqlcmd.Parameters.Add("#UserId", SqlDbType.UniqueIdentifier).Value = new System.Data.SqlTypes.SqlGuid((FormView1.FindControl("l1") as Label).Text);
//sqlcmd.Parameters.Add("#RoleId", SqlDbType.UniqueIdentifier).Value = new System.Data.SqlTypes.SqlGuid((FormView1.FindControl("L2") as Label).Text);
//Try NO.4
//sqlcmd.Parameters.AddWithValue("#UserId",new Guid(Convert.ToString((FormView1.FindControl("l1") as Label).Text)));
//sqlcmd.Parameters.AddWithValue("#RoleId", new Guid(Convert.ToString((FormView1.FindControl("L2") as Label).Text)));
//Try NO.5
//sqlcmd.Parameters.Add("#UserId", SqlDbType.UniqueIdentifier).Value = new Guid(Convert.ToString((FormView1.FindControl("l1") as Label).Text));
//sqlcmd.Parameters.Add("#RoleId", SqlDbType.UniqueIdentifier).Value = new Guid(Convert.ToString((FormView1.FindControl("L2") as Label).Text));
//Try NO.6
sqlcmd.Parameters.Add("#UserId", SqlDbType.UniqueIdentifier,32).Value =(FormView1.FindControl("l1") as Label).Text;
sqlcmd.Parameters.Add("#RoleId", SqlDbType.UniqueIdentifier, 32).Value = ((FormView1.FindControl("L2") as Label).Text);
sqlcmd.ExecuteNonQuery();
FormView1.DataBind();
sqlcmd.Connection.Close();
}
So anyone able to help me. Thanks
I have following tables in my MS Access database.
Personal, Partner, ContactDetails, NativeAddress bla bla bal. I created a Wizard in Visual Studio 2012 for above tables. A screenshot is given below. Now I want to submit all data at once in all tables when user presses the submit button. So what syntax should I use now. Please guide.
My code is something like this. Its incomplete and just beginning of my script. So please don't get me wrong.
protected void dataWizard_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\micronets\jobwork-2013\arunthathiyar-sangham\arunthathiyar-web-application\App_Data\arunthathiyar-db.accdb";
string personalDetails = "INSERT INTO PersonalDetails(FirstName, MiddleName, LastName, Sex, Age, DateOfBirth, PlaceOfBirth, EducationalQualification, EmploymentStatus, Profession, PhysicalStatus, BloodGroup) VALUES (#fnPD, #mmPD, #lnPD, #sexPD, #agePD, #dobPD, #pobPD, #eqPD, #esPD, #profPD, #phyicPD, #bgPD)";
string familyDetails = "INSERT INTO FamilyDetails(Relationship, FullName, Status, BloodGroup, EducationalQualification, Profession, EmploymentStatus) VALUES(#relFD, #fnFD, #statusFD, #bgFD, #eqFD, #profFD, #esFD)";
string contactDetails = "INSERT INTO ContactDetails(FlatBuildingStreet, Landmark, Area, City, Pincode, State, Country, Mobile, Telephone, Email) VALUES(#fbsCD, #landCD, #areaCD, #cityCD, #pinCD, #stateCD, #countryCD, #mobCD, #telCD, #emailCD)";
try
{
con.Open();
txtMemAmountReceived.Text = txtPDFirstName.Text;
}
catch
{
txtMemAmountReceived.Text = "Sorry";
}
You're heading in the right direction. Here's what you need to do next:
Create an OleDbCommand object
You have a connection, now you need to create and Command object that can store the SQL text and execute commands against the database. Something like this:
OleDbCommand cmd = new OleDbCommand(personalDetails, con);
Open, execute, close
Then, inside your try block, you want to open the connection, execute the query, and close the connection:
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
Rinse and repeat
You can take it from there as far as executing all three queries. You just need to update the cmd.CommandText property with the text for the other queries you want to execute, and call ExecuteNonQuery again.
you could possibly concatenate all of your query strings into one separated by semicolons(;) So the one large string would be sent to the server and each query would be processed and you would then only have to make one connection to the database.
string myQuery = personalDetails+ "; " + familyDetails + "; " + contactDetails
However i would just make 3 separate connections just so it will be easier to manage all of your parameters. If you ever have to go back and change the query or a parameter it will be a mess.
I wrote a stored procedure to update PAID column in tblUser, and that stored proceudre works perfectly,
Code:
#buyer_email varchar(50),
#payment bit
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
update tblUser set paid=#payment where email = #buyer_email
END
but when I call it from my asp.net app then it doesn't update the Paid column, even if I try simple update statement in my asp.net code but that also doesn't update the column.
String userEmail_send = (Convert.ToString(Request.QueryString["emailAdmin"]));
String conString = "Data Source=COSANOSTRA; MultipleActiveResultSets=true; Initial Catalog=Waleed_orsfinal;Integrated Security=True";
try
{
con.Open();
if (userEmail_get.Replace("'", string.Empty) == userEmail_send.Replace("''", string.Empty))
{
//String query1 = "update tblUser Set paid=1 where email='" + userEmail_send + "' ";
SqlCommand sqlcom1 = new SqlCommand("submitPaypalPayment", con);
sqlcom1.CommandType = CommandType.StoredProcedure;
sqlcom1.Parameters.Add("#buyer_email", SqlDbType.VarChar).Value = userEmail_send;
sqlcom1.Parameters.Add("#payment", SqlDbType.Bit).Value= 1 ;
sqlcom1.ExecuteScalar();
hdr_msg_success.InnerText = "Congrats, You have paid successfully. Wait for an approval by an admin ";
Response.Write("<br/>"+" "+ "Matched=" +userEmail_send.Replace("''","'"));
}
else
{
hdr_msg_success.InnerText = "Something went wrong in matching Emails , Please confirm your Email";
}
}
catch (Exception exc)
{
Response.Write(exc.Message);
}
finally
{
con.Close();
}
The failure is likely due to your connectionstring security context.
Assuming you're running under IIS impersonation of the current web user is not the default behavior.
By specifying Integrated Security=True in your connectionstring you're telling SQL Server to accept the current Windows context as the user attempting to gain access to the database. This will be the IIS Application Pool account, not your own account, when running under IIS.
Try creating a SQL Server user name and password and specifying them in the connectionstring instead of using integrated security with a web application. You could alternatively set the Application Pool Windows Identity but that's something that's usually more cumbersome to maintain and migrate... There's also the option of allowing web user impersonation but that's even more unwieldy.
By the way, here are some other things to consider...
Store your connectionstring in a config file, not hardcoded (I understand that this may just be test code, but if not...)
Consider interacting with your stored procedure from ADO.net with something more like this in your use case.
using (SqlCommand sqlcom1 = new SqlCommand("dbo.submitPaypalPayment", con))
{
sqlcom1.CommandType = CommandType.StoredProcedure;
sqlcom1.Parameters.Add("#buyer_email", SqlDbType.VarChar) { Value = userEmail_send };
sqlcom1.Parameters.Add("#payment", SqlDbType.Bit) { Value= 1 };
sqlcom1.ExecuteNonQuery();
}
Based on what I read here, I seems like the values are not set correctly to the variables from the Request object.
Have you tried setting the break point and check what value is set to your userEmail_send variable from this statement
[String userEmail_send = (Convert.ToString(Request.QueryString["emailAdmin"]));]?
May be its not setting the right value for that variable.
Set the break point at this line sqlcom1.ExecuteScalar(); and check the parameter values.
You can do that by the ordinal position or by the name of the parameter as shown below:
By ordinal position sqlcom1.Parameters[0].Value or by name sqlcom1.Parameters["#buyer_email"].Value
do the same thing for your #payment parameter as well. Remember its ordinal position would be 1.
Hope, this helps... and good luck...
I just create Membership management program, this program can create user one by one and it can import data from text file as well. When I import data from text file, it can create around 30 user before timeout, after I debug it take nearly 1 sec for each CreateUser call.
I want to know, how can I improve performance when I create large number of aspnet user.
Solution1:
Get all data from user table into dataset ds in table "User"
Get all data from member table into table "Member" in the same dataset ds
Create a relationship between the two tables on field userid
Run a loop on each row of table User
For each user call Membership.CreateUser with UserName and Password as parameters
Get all child rows for the current user DataRow.GetChildRows
For each childrow returned, call Roles.AddUserToRole with username and rolename as parameters (add only if the role is active)
Taken from here.
Solution 2:
Download Peter Keller's Membership Editor
Create a SpreadSheet with these columns: UserName,password, and email.
Import this excel file to this database as table: yourUsers$
Create a Winforms application, Add a button to form and paste this code in its click event:
protected void batchInsertButton_Click(object sender, EventArgs e)
{
string strConn = ConfigurationManager.ConnectionStrings["1ConnectionString"].ConnectionString;
string strSQL = "SELECT * FROM yourUsers$";
SqlConnection myConnection = new SqlConnection(strConn);
myConnection.Open();
SqlCommand myCommand = new SqlCommand(strSQL,myConnection);
SqlDataReader myReader;
myReader = myCommand.ExecuteReader();
while (myReader.Read()) {
ObjectDataSourceMembershipUser.InsertParameters["UserName"].DefaultValue = myReader["UserName"].ToString();//TextBoxUserName.Text; ;
ObjectDataSourceMembershipUser.InsertParameters["password"].DefaultValue = myReader["password"].ToString();//TextBoxPassword.Text;
ObjectDataSourceMembershipUser.InsertParameters["passwordQuestion"].DefaultValue ="your qestion";//TextBoxPasswordQuestion.Text;
ObjectDataSourceMembershipUser.InsertParameters["passwordAnswer"].DefaultValue = "your answer";//TextBoxPasswordAnswer.Text;
ObjectDataSourceMembershipUser.InsertParameters["email"].DefaultValue = myReader["email"].ToString();//TextBoxEmail.Text;
ObjectDataSourceMembershipUser.InsertParameters["isApproved"].DefaultValue = "true";//CheckboxApproval.Checked == true ? "true" : "false";
ObjectDataSourceMembershipUser.Insert();
//hard code this user role
Roles.AddUserToRole(myReader["UserName"].ToString(), "NormalUser");
}
myConnection.Close();
GridViewMemberUser.DataBind();
GridViewRole.DataBind();
}
Taken from here.
I have the following code snippet.
SqlCommand cmd = new SqlCommand("SELECT FName,LName FROM EMPLOYEE_TABLE WHERE EmployeeID = '" +TextBox1.Text + "' AND Password = '"+ TextBox2.Text +"'", con);
SqlDataReader x = cmd.ExecuteReader();
try
{
if (x.Read())
{
name = (string)x["FName"] +' '+ (string)x["LName"];
Session["NAME"] = name;
Session["ID"] = TextBox1.Text;
Response.Redirect("sample.aspx?action=On_Click");
}
else
{
errormsg.Text = "login failed.Please enter Valid UserID and Password";
errormsg.ForeColor = System.Drawing.Color.Red;
}
}
catch (Exception exp)
{
errormsg.Text = "Sorry,You dont have access to this portal.";
}
finally
{
x.Close();
con.Close();
}
Now, when i use a valid id (that exists) and password as abc' or 'x'='x then it logs in into the first account of the table in the database. Till this it's fine.
However when I try to debug the code, it throws an error Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack..
Also if it is throwing an error then why is it logging into this 1st account of the database. Note: the first account of the database has a different userid than that which i m providing.
Note: I am the developed of this application. So I'm not doing anything illegal. :)
Look at this part of your SQL:
"' AND Password = '"+ TextBox2.Text +"'"
With your password, it's
"' AND Password = ''x'='x'"
which is not the SQL you want.
Even if you are trying to do SQL injection, you have to result in valid SQL. Usually, it's by ending the statement with a semi-colon after closing the quote. See this:
http://xkcd.com/327/
OK, to provide an answer based on the primary issue you've got (as you've stated, you're new to the SQL Injection issue).
SQL Injection is caused by dynamically building a SQL query using user input as part of the construction. The simplest solution to this in .Net is to create a parameterized query.
I think Jeff Atwood has the most complete yet concise article providing an explanation and complete example here
Quoted from above link:
SqlConnection conn = new SqlConnection(_connectionString);
conn.Open();
string s = "SELECT email, passwd, login_id, full_name " +
"FROM members WHERE email = #email";
SqlCommand cmd = new SqlCommand(s);
cmd.Parameters.Add("#email", email);
SqlDataReader reader = cmd.ExecuteReader();
The issue at hand:
The reason it's still logging into the account is because the query is still "valid".
The statement will still be executed, and the relevant record will still be returned from the database, no exception will be thrown.
The only way you will stop the login process when invalid data is provided is to validate the input before executing the query. You should always validate user input before sending it off to the database. If the user were to provide:
username'; drop table users;--
as the username, you would be in a LOT of trouble.
The error you're encountering is a debugging error, not an actual program exception. That's why it works when you run it normally.
To remedy the error, I'd first make sure that everything is running with a Debug build. Also, make sure you're currently debugging in the function of the variable you want to inspect. Try stepping (F10) a few times past your breakpoint to refresh the context. There are a slew of other suggestions on the internet for that particular error, so if you're still having problems you might have to do some googling.