Error connecting to database ASP.NET C# - c#

I keep getting this error:
Format of the initialization string does not conform to specification starting at index 0.
This line of code:
using (OleDbConnection conn = new OleDbConnection("PayrollSystem_DBConnectionString"))
I think I need sql statements instead of Ole, I'm not sure.
Here is my form html code:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:PayrollSystem_DBConnectionString %>"
ProviderName="<%$ ConnectionStrings:PayrollSystem_DBConnectionString.ProviderName %>"
Here is my frmManageUsers code:
public partial class frmManageUsers : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAddUser_Click1(object sender, EventArgs e)
{
//string userName, userPassword;
if (txtUserName.Text == "" || txtUserName.Text == null)
{
lblError.Text = ("User Name may not be empty");
lblError.ForeColor = System.Drawing.Color.Red;
return;
}
// else
// userName = (txtUserName.Text);
if (txtPassword.Text == "" || txtPassword.Text == null)
{
lblError.Text = ("Password may not be empty");
lblError.ForeColor = System.Drawing.Color.Red;
return;
}
//else
// userPassword = (txtPassword.Text);
using (OleDbConnection conn = new OleDbConnection("PayrollSystem_DBConnectionString"))
{
string insert = "Insert INTO tblUserLogin (UserName, UserPassword, SecurityLevel) Values (#UserName, #UserPassword, #SecurityLevel)";
OleDbCommand cmd = new OleDbCommand(insert, conn);
cmd.Parameters.Add("#UserName", txtUserName.Text);
cmd.Parameters.Add("#UserPassword", txtPassword.Text);
cmd.Parameters.Add("#SecurityLevel", drpdwnlstSecurityLevel.SelectedValue);
cmd.ExecuteNonQuery();
}
Session["UserName"] = txtUserName.Text;
Session["Password"] = txtPassword.Text;
Session["SecurityLevel"] = drpdwnlstSecurityLevel.SelectedValue;
Server.Transfer("frmManageUsers.aspx");
//Server.Transfer("grdUserLogin");
}
protected void drpdwnlstSecurityLevel_SelectedIndexChanged(object sender, EventArgs e)
{
}
}

OleDbConnection takes the actual connection string, not the NAME of the connection string. You have to get the connection string from the Configuration using ConfigurationManager.ConnectionStrings["PayrollSystem_DBConnectionString"].ConnectionString and pass that to OleDbConnection

Also, if you're using a 64-bit system, you need to change the connection string to use the new provider, Microsoft.ACE.OLEDB.14.0
You can download it here:
Microsoft.ACE.OLEDB.14.0 .NET Database Provider

Related

Upload documents to Access DB using c#

I am working in Visual Studio 2010 and I am trying to upload documents via a webpage to an access database. I am not getting any errors when I run my code, but nothing is writing to the database. Here is my on click code to show what I think it is supposed to do.
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileExtension = Path.GetExtension(FileUpload1.FileName);
if (fileExtension.ToLower() != ".doc" || fileExtension.ToLower() != ".docx" || fileExtension.ToLower() != ".pdf")
{
lblInfo.Text = "Only .doc, .docx, or .pdf files are allowed.";
lblInfo.ForeColor = System.Drawing.Color.Red;
}
else
{
int fileSize = FileUpload1.PostedFile.ContentLength;
if (fileSize > 2097152)
{
lblInfo.Text = "Maximum file size of 2 MB exceeded.";
lblInfo.ForeColor = System.Drawing.Color.Red;
}
else
{
OleDbCommand update = new OleDbCommand("Update STAFF SET Resume = #Resume WHERE StaffID=#StaffID", DBConnection);
update.Parameters.Add("#Resume", OleDbType.LongVarBinary).Value = FileUpload1.FileContent;
update.Parameters.Add("#StaffID", OleDbType.Integer).Value = txtStaffID.Text;
lblInfo.Text = "File Uploaded";
lblInfo.ForeColor = System.Drawing.Color.Green;
}
}
}
else
{
lblInfo.Text = "Please select a file to upload";
lblInfo.ForeColor = System.Drawing.Color.Red;
}
}
If you could provide any advice or suggestions that would be great. Thanks. I will show the entirety of the code also, just in case it's an issue with the DB connection.
public partial class Staff : System.Web.UI.Page
{
OleDbConnection DBConnection = new OleDbConnection();
OleDbDataAdapter DataAdapter;
DataTable LocalDataTable = new DataTable();
private void ConnectToDatabase()
{
DBConnection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\CIS470_TPS_System\CIS470_TPS_System\CIS470_TPS_System\App_Data\TpsSystem_DB.mdb";
DBConnection.Open();
DataAdapter = new OleDbDataAdapter("Select * From STAFF", DBConnection);
DataAdapter.Fill(LocalDataTable);
}
private void Page_Load(object sender, EventArgs e)
{
ConnectToDatabase();
}
protected void AccessDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string requestId = GridView1.SelectedRow.Cells[1].Text;
txtSelectedStaff.Text = requestId; //this control holds the selected value
}
protected void DetailsView1_PageIndexChanging(object sender, DetailsViewPageEventArgs e)
{
}
As suggested in the comments to the question, we can use the FileUpload control's .FileBytes property to supply the value of the query parameter, as in this (simplified) example:
protected void btnUpload_Click(object sender, EventArgs e)
{
using (var con = new OleDbConnection())
{
con.ConnectionString =
#"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=C:\__tmp\staffDb.accdb;";
con.Open();
using (var cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText =
"UPDATE STAFF SET Resume=? " +
"WHERE StaffID=?";
cmd.Parameters.AddWithValue("?", FileUpload1.FileBytes);
cmd.Parameters.AddWithValue("?", 1);
cmd.ExecuteNonQuery();
}
con.Close();
}
}

Drop-down list property [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I was wondering if somebody could point me in the right direction.My program has 1 dropdown list, 2 text boxes and 2 buttons.
namespace passwordReset
{
public partial class Form1 : Form
{
//variables to mess with the password
public string password1;
public string password2;
public string username;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(xxxxxxx);
connection.Open();
string query = "select Login, Password from Employees order by Login desc";
SqlDataAdapter da = new SqlDataAdapter(query, connection);
DataSet ds = new DataSet();
da.Fill(ds, "Credentials");
ddlLogin.DisplayMember = "Login";
ddlLogin.ValueMember = "Password";
ddlLogin.DataSource = ds.Tables["Credentials"];
connection.Close();
}
private void ddlLogin_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlLogin.SelectedItem != null)
{
DataRowView drv = ddlLogin.SelectedItem as DataRowView;
//MessageBox.Show("The username you selected is: " + drv.Row["Login"].ToString());
//MessageBox.Show("The password you selected is: " + drv.Row["Password"].ToString());
//MessageBox.Show("username selected is: " + ddlLogin.Text.ToString());
//MessageBox.Show("password is: " + ddlLogin.SelectedValue.ToString());
}
}
private void txtPassword1_TextChanged(object sender, EventArgs e)
{
password1 = txtPassword1.Text;
}
private void txtPassword2_TextChanged(object sender, EventArgs e)
{
password2 = txtPassword2.Text;
}
private void btnReset_Click(object sender, EventArgs e)
{
if (ddlLogin.Text == "rruales" || ddlLogin.Text == "xxxxx" || ddlLogin.Text == "xxxxxx")
{
MessageBox.Show("Cannot change this user's password");
}
if (password1 == password2 && ddlLogin.Text != "rruales" && ddlLogin.Text != "xxxxx" && ddlLogin.Text != "xxxxx")
{
string newPassword = txtPassword2.Text;
username = ddlLogin.Text.ToString();
string currentPassword = ddlLogin.SelectedValue.ToString();
currentPassword = newPassword;
SqlConnection connection = new SqlConnection(xxxxxxxx);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Employees SET [Password] = #password WHERE [Login] = #login";
cmd.Parameters.AddWithValue("#password", currentPassword);
cmd.Parameters.AddWithValue("#login", username);
cmd.Connection = connection;
connection.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Password successfully updated");
connection.Close();
}
else
{
MessageBox.Show("You either choose usernames rruales or xxxxx or xxxx, or the passwords don't match, try again");
}
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
The code does what it needs to do, when a user selects a user name from the dropdown menu, they can reset the user's password.But if the user types the username they want to reset, I get an error here:
string currentPassword = ddlLogin.SelectedValue.ToString();
the error says Object reference not set to an instance of an object.use the "new" keyword to create an object instance.I understand the error is coming from the fact that the user is inputting the username instead of selecting it. my question is and I don't need code, I want to understand how I can go ahead and handle that, where the user wants to just type the username or pick it from the dropdown?any advise to rewrite the code is welcome, I am an entry level developer.
update, I can't answer my own question, but it works now thanks all
All,
thank you for your help.
what you all said worked, and I also had to do 1 change to my code, I realized I was doing something very dumb:
private void txtPassword1_TextChanged(object sender, EventArgs e)
{
password1 = txtPassword1.Text;
}
private void txtPassword2_TextChanged(object sender, EventArgs e)
{
password2 = txtPassword2.Text;
}
private void btnReset_Click(object sender, EventArgs e)
{
if (ddlLogin.SelectedValue == null)
{
username = ddlLogin.Text.ToString();
}
else
{
username = ddlLogin.Text.ToString();
}
if (ddlLogin.Text == "rruales" || ddlLogin.Text == "xxxxx" || ddlLogin.Text == "xxxxxx")
{
MessageBox.Show("Cannot change this user's password");
}
if (password1 == password2 && ddlLogin.Text != "rruales" && ddlLogin.Text != "xxxxxx" && ddlLogin.Text != "xxxxxx")
{
string newPassword = txtPassword2.Text;
//username = ddlLogin.Text.ToString();
// string currentPassword = ddlLogin.SelectedValue.ToString();
currentPassword = newPassword;
SqlConnection connection = new SqlConnection(xxxxxx);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Employees SET [Password] = #password WHERE [Login] = #login";
cmd.Parameters.AddWithValue("#password", currentPassword);
cmd.Parameters.AddWithValue("#login", username);
cmd.Connection = connection;
connection.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Password successfully updated");
connection.Close();
}
else
{
MessageBox.Show("You either choose usernames rruales or xxxxx or xxxx, or the passwords don't match, try again");
}
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
I don't know why I did this:
string currentPassword = ddlLogin.SelectedValue.ToString();
If you don't select an item from the DropDown, it's SelectedValue will be null. You should check if it's null. If it is null then get the value from the textbox.
string userName;
if (ddlLogin.SelectedValue == null) {
userName = theTextBox.Text;
} else {
username = theDropDownList.SelectedValue.Text;
}
I'm not sure if it's the username you're trying to get. You mention the exception throws when you type the username but you grab a password from ddlLogin? Whatever you're trying to assign, just check if the dropdown is null like above and assign to the correct variable.

The password in the database still stored as a text

I want to store a password in the database, but when I click Submit button, it added successfully to the database, but it does not stored the password in the database as random text, but as the original text. How could I fix this?
Here is the code that I am using:
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\db1.accdb";
string myPassword;
string strHashedPassword;
string strStoredPassword;
int mySalt;
bool checking = false;
public Registration()
{
InitializeComponent();
}
private void Registration_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
if (this.textBox1.Text == "")
{
MessageBox.Show("Cannot be empty", "Warning", MessageBoxButtons.OK);
}
else
{
Checking _checking = new Checking();
_checking.ShowDialog();
checking = true;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (this.textBox1.Text == "" || this.textBox2.Text == "" || this.textBox3.Text == "" || this.textBox4.Text == "")
{
MessageBox.Show("Cannot be empty", "Warning", MessageBoxButtons.OK);
}
else
{
AddDatabase(sender, e);
}
}
private void AddDatabase(object sender, EventArgs e)
{
if (checking.Equals(false))
{
MessageBox.Show("You have to check first", "Warning", MessageBoxButtons.OK);
}
else
{
string query = "INSERT INTO [Member] ([Username], [Password], [UserType], [UserStore]) VALUES (#Username, #Password, #UserType, #UserStore)";
OleDbConnection _conn = new OleDbConnection(connectionString);
_conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, _conn))
{
cmd.Parameters.Add("#Username", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Username"].Value = this.textBox1.Text;
cmd.Parameters.Add("#Password", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Password"].Value = this.textBox2.Text;
cmd.Parameters.Add("#UserType", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#UserType"].Value = this.textBox3.Text;
cmd.Parameters.Add("#UserStore", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#UserStore"].Value = this.textBox4.Text;
cmd.ExecuteNonQuery();
DialogResult _dialogResult = MessageBox.Show("Added Successfully", "Success", MessageBoxButtons.OK);
if (_dialogResult == DialogResult.OK)
{
this.Hide();
CreateRandomPassword();
this.Close();
}
}
}
}
private void CreateRandomPassword()
{
// Generate a new random password string
myPassword = this.textBox2.Text;
// Generate a new random salt
mySalt = Password.CreateRandomSalt();
// Initialize the Password class with the password and salt
Password pwd = new Password(myPassword, mySalt);
// Compute the salted hash
// NOTE: you store the salt and the salted hash in the database
strHashedPassword = pwd.ComputeSaltedHash();
strStoredPassword = strHashedPassword;
}
Thank you!
Your answer much appreciated!
You're using this.textBox2.Text for the #Password portion of the query, but your CreateRandomPassword() method only changes strStoredPassword and strHashedPassword (As an aside, I don't really see why you have 2 variables to hold the same value, it's redundant).
You should change
cmd.Parameters.Add("#Password", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Password"].Value = this.textBox2.Text;
to
cmd.Parameters.Add("#Password", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Password"].Value = strStoredPassword;
and move the call to CreateRandomPassword() up above the query execute.
In your "AddDatabase" function, change textbox value to "strStoredPassword"
like below
cmd.Parameters.Add("#Password", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Password"].Value = strStoredPassword;

can't display "wrong pw"

I have this simple login page below ,
if I enter correct ID + pw -> success (which I want)
if I enter wrong ID -> wrong login (which I want)
But if I enter correct ID + wrong ID , I Want it to say wrong password.
How can I do it?
Thank you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["X"] != null)
{
Response.Redirect("MemberPage.aspx");
}
}
SqlConnection cnn = new SqlConnection("Initial Catalog=Northwind;Data Source=localhost;Integrated Security=SSPI;");
protected void Button1_Click(object sender, EventArgs e)
{
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT FirstName,LastName FROM Employees", cnn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
if (TextBox1.Text == dr.GetString(0) || TextBox2.Text == dr.GetString(1))
{
Session["x"] = TextBox1.Text;
Response.Redirect("MemberPage.aspx");
}
else
{
Label2.Text = "wrong login";
}
}
}
cnn.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("Register.aspx");
}
}
while this doesn't answer your question, I see a MAJOR security flaw with your logic. I think no matter what failure your users encounter, invalid username or invalid password, you should always display the same "invalid login" message.
If you have someone who is attempting to break into the system, once you validate that a user account exists (invalid password) they can then begin to crack that specific account's password using brute force.
Just something to think about.
You are putting your logic wrongly here. the logic will be
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["X"] != null)
{
Response.Redirect("MemberPage.aspx");
}
}
SqlConnection cnn = new SqlConnection("Initial Catalog=Northwind;Data Source=localhost;Integrated Security=SSPI;");
protected void Button1_Click(object sender, EventArgs e)
{
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT FirstName,LastName FROM Employees", cnn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
if (TextBox1.Text.Trim() == dr.GetString(0) || TextBox2.Text.Trim()== dr.GetString(1))
{
if (TextBox2.Text.Trim()== dr.GetString(1))
{
Session["x"] = TextBox1.Text.Trim();
Response.Redirect("MemberPage.aspx");
}
else
{
Label2.Text = "wrong password";
}
}
else
{
Label2.Text = "wrong login";
}
}
cnn.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("Register.aspx");
}
}
You read the firstname and the lastname from the database, but then check for the password against the lastname. I doubt that this field contains a valid password
A part from this logic error, you should use a WHERE clause in your statement to check if the user is present or not in the database.
protected void Button1_Click(object sender, EventArgs e)
{
// Command with parameters that check if a user with the supplied credentials exists
// If the user exists then just one record is returned from the datatable....
string cmdText = "SELECT FirstName,LastName " +
"FROM Employees " +
"WHERE username=#uname and pass=#pwd";
using(SqlConnection cnn = new SqlConnection(.....))
using(SqlCommand cmd = new SqlCommand(cmdText, cnn))
{
cnn.Open();
cmd.Parameters.AddWithValue("#uname", TextBox1.Text);
cmd.Parameters.AddWithValue("#pwd", TextBox2.Text);
using(SqlDataReader reader = cmd.ExecuteReader())
{
// If the Read returns true then a user with the supplied credentials exists
// Only one record is returned, not the whole table and you don't need to
// compare every record against the text in the input boxes
if(reader.Read())
{
Session["x"] = reader.GetString(0);
Response.Redirect("MemberPage.aspx");
}
else
{
Label2.Text = "Invalid credentials";
}
}
}
}
Another point to keep in mind is the following. In the database you should not have a password in clear text. The correct way to store password is to store an hashed string corresponding to the password and then applying the hashing function to the user input and check for same hashed string in the database

SqlConnection Runtime error

Here i have write the coding for image upload control.but getting some RUNTIME error.error sows in SqlConnection place
first i have
1.Image name box - Textbox
2.Image Upload control - asp imageupload control
3.Upload button
ERROR :Object synchronization method was called from an unsynchronized block of code.
Code Below
public partial class ProfileDetails : System.Web.UI.Page
{
string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
//SqlConnection con = new SqlConnection("Data Source=CHATHU-LAPTOP;Initial Catalog=ProfilemgtDB;User ID=sa;Password=sa123");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void Upload_Click(object sender, EventArgs e)
{
string path = Server.MapPath("images/");
if (FileUpload1.HasFile)
{
string ext = Path.GetExtension(FileUpload1.FileName);
if (ext == ".jpg" || ext == ".png")
{
FileUpload1.SaveAs(path + FileUpload1.FileName);
string name = "~/images/" + FileUpload1.FileName;
string s = "Insert into Profile values('" + TextBox12.Text.Trim() + " '.'" + name + "' )";
SqlConnection con = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(s, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Write("File Uploaded");
}
else
{
Response.Write("You can upload only JPG & PNG");
}
}
else {
Response.Write("Please Select File");
}
}
}
ERROR :Object synchronization method was called from an unsynchronized block of code.
Nimesh,
I do not see anything wrong in the code. However, you may want to check if your web.config contains the same connectionStrings name as mentioned in your code (which is ConnectionString).
Also, refer the following links
http://www.ezzylearning.com/tutorial.aspx?tid=4287517
http://forums.asp.net/t/1757347.aspx/1
Hope this helps.

Categories

Resources