string connectionString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
SQLiteConnection connString = new SQLiteConnection(connectionString);
using (var command = connString.CreateCommand())
{
try
{
connString.SetPassword(ConfigurationManager.AppSettings["password1"]);
connString.Open();
connString.ChangePassword((String)null);
connString.ChangePassword(ConfigurationManager.AppSettings["password2"]);
connString.Close();
connString.Dispose();
}
catch (Exception e)
{
Console.Write(e.Message + "\n" + e.StackTrace);
}
}
I'm trying to test SQLite by having a simple console application. I'm using an app.config file to read passwords and connection string from. The code is able to set the password the very first time it runs but if I open the connection and try to change password by calling ChangePassWord() method, the password is not changed. I also try to set password to null and then reset it to some new password, but that doesn't work either.
The error is
File Opened that is not a database file. File is encrypted or is not a database
Some other people have the same problem: ChangePassword method problem.
I'm not 100% sure. But for some reason reading the connection string from the app.config could have some bearing on it. I took out the connection string and decided to hardcode it like so
SQLiteConnection connString = new SQLiteConnection("data source=\".\\SomeDatabase\"");
before was like so:
<connectionStrings>
<add name="connection"
connectionString="data source=".\SomeDatabase""
providerName="System.Data.SQLite" />
</connectionStrings>
Hope this helps somebody
Related
I'm attempting to insert some data into my local SQL database. The command seems to run successfully and I'm not getting any errors, but for some reason the data is not being inserted into the database. Have I forgotten something?
public void RegisterUser(string fName, string lName, string email, string password)
{
string conStr = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
using (SqlConnection openCon = new SqlConnection(conStr))
{
string saveUser = "INSERT into Users (firstName,lastName,email,password,isAdmin) VALUES (#firstName,#lastName,#email,#password,#isAdmin)";
using (SqlCommand querySaveUser = new SqlCommand(saveUser))
{
querySaveUser.Connection = openCon;
querySaveUser.Parameters.AddWithValue("#firstName", fName);
querySaveUser.Parameters.AddWithValue("#lastName", lName);
querySaveUser.Parameters.AddWithValue("#email", email);
querySaveUser.Parameters.AddWithValue("#password", password);
querySaveUser.Parameters.AddWithValue("#isAdmin", 1);
openCon.Open();
querySaveUser.ExecuteNonQuery();
}
}
}
Connection String:
<connectionStrings>
<add name="DatabaseConnectionString" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\App_Data\Database.mdf;Integrated Security=True;"
providerName="System.Data.SqlClient" />
update:
SOLVED! I was trying to output to another directory for some reason. Ended up recreating the database which solved the issue.
Do
int affected = querySaveUser.ExecuteNonQuery();
and set a debug point and watch affected value.
According to MSDN "If a rollback occurs, the return value is also -1."
In case you are debugging a copy of your DB is created in bin/Debug folder, thus you might be checking different DB. Check this - https://visualstudiomagazine.com/blogs/tool-tracker/2012/05/dealing-with-local-databases-or-why-your-updates-dont-stick.aspx
I check your code and its working fine in my system but i have changed your connection string so please modified your connection string as mine then check i hope your problem solved
public void RegisterUser(string fName, string lName, string email, string password)
{
string conStr = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
using (SqlConnection openCon = new SqlConnection(conStr))
{
string saveUser = "INSERT into Users (firstName,lastName,email,password,isAdmin) VALUES (#firstName,#lastName,#email,#password,#isAdmin)";
using (SqlCommand querySaveUser = new SqlCommand(saveUser))
{
querySaveUser.Connection = openCon;
querySaveUser.Parameters.AddWithValue("#firstName", fName);
querySaveUser.Parameters.AddWithValue("#lastName", lName);
querySaveUser.Parameters.AddWithValue("#email", email);
querySaveUser.Parameters.AddWithValue("#password", password);
querySaveUser.Parameters.AddWithValue("#isAdmin", 1);
openCon.Open();
querySaveUser.ExecuteNonQuery();
}
}
}
Connection String: web.config
<connectionStrings>
<add name="DatabaseConnectionString" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database.mdf; Initial Catalog=Database.mdf; Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
It might help someone looking for Entity Framework Core or ASP.NET Zero related solution.
In my case I was using ASP.NET Zero boiler plate templates for ASP.NET Core and it was not inserting into the database. After a few minutes exploration, I found out that ASP.NET Zero does not immediately execute the ef queries on db rather it inserts rows at end of the unit of work.
Usually, it fails to insert if there is an exception it will log that to Logs table, you can see the latest logs with exceptions if they were failed.
If you want to execute the queries immediately, you can force it to save changes by calling the SaveChanges() method like this:
await CurrentUnitOfWork.SaveChangesAsync();
I am trying to have a personalized database connection string for the machines i install the C# application into. I have created a database using Visual Studio but that only points the location of the database to my personal directory and that is not something general.
Now when i try to publish the application and try to install it in some other computer, the database gives me an error that it wasnt found, which makes sense because the connection string is pointing to my personal computers directory.
Here is part of my code:
private void button13_Click_1(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Program Files\\Hydrolec Inc\\PanelProgressLogger\\PanelProgress.mdf;Integrated Security=True;User Instance=True;");
sda = new SqlDataAdapter(#"SELECT [Panel Progress].*
FROM [Panel Progress]", con);
fill_grid();
}
catch (Exception error)
{
label6.Text = error.Message;
}
}
Can anyone please guide me towards the right path to solve this issue and to generate a personalized connection string for every computer the database gets installed to?
In your app.config or web.config file (Whichever is relevant to you) add the following connection string under configuration tag.
<connectionStrings>
<add name="DbConnection" connectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Program Files\\Hydrolec Inc\\PanelProgressLogger\\PanelProgress.mdf;Integrated Security=True;User Instance=True;" />
</connectionStrings>
If you already have a connection strings section then add only the
<add name="DbConnection" connectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Program Files\\Hydrolec Inc\\PanelProgressLogger\\PanelProgress.mdf;Integrated Security=True;User Instance=True;" />
Then in your C# code instead of hard coding the connection string you can use the config value.
string connectionString = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;
private void button13_Click_1(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(connectionString);
sda = new SqlDataAdapter(#"SELECT [Panel Progress].*
FROM [Panel Progress]", con);
fill_grid();
}
catch (Exception error)
{
label6.Text = error.Message;
}
}
Build it. Then when you deploy the application in to another machine all you have to do is change your connection string in the app.config or web.config(whichever is relevant for you) to the new file location without changing hard coded values and rebuilding the application again.
Hey I'm new to programming and have never made an actual program that needs to work on another pc. The program is connected with a databank. When I'm on another pc i change program.exe.config file so that i can apply the right location of the databank but its still doesn't work. here is the code i have, maybe something is wrong here.
app.config:
<connectionStrings>
<add name="Program.Properties.Settings.InventoryDBConnectionString"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\School\Stage\Program testen\Program\bin\Debug\InventoryDB.accdb"
providerName="System.Data.OleDb" />
</connectionStrings>
in standard code:
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\School\Stage\Program testen\Program\bin\Debug\InventoryDB.accdb");
The first thing is that you are specifying a connection string in your application configuration file:
<connectionStrings>
<add name="Program.Properties.Settings.InventoryDBConnectionString"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\School\Stage\Program testen\Program\bin\Debug\InventoryDB.accdb"
providerName="System.Data.OleDb" />
</connectionStrings>
You aren't using the connection string from your Program.exe.config, instead you are copying-and-pasting the connection string.
If you change your code slightly, perhaps you can see what i mean:
//Get the connection string to use
String connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\School\Stage\Program testen\Program\bin\Debug\InventoryDB.accdb";
//Open a connection to the database
OleDbConnection con = new OleDbConnection(connectionString);
What you should be doing is pulling the connection string from your application's configuration:
//Get our connection string setting, and the connectionString it contains
ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings["Program.Properties.Settings.InventoryDBConnectionString"];
String connectionString = cs.ConnectionString;
//Open a connection to the database
OleDbConnection con = new OleDbConnection(connectionString);
There is one more change that you can make. Your connection string entry itself specifies which provider you want to use:
providerName="System.Data.OleDb"
But then you go ahead and use that provider yourself:
OleDbConnection con = new OleDbConnection(...);
If you changed your connection string to use a different provider:
providerName="System.Data.SqlClient"
your code would still be using the OleDbConnection, rather than the provider given in the application configuration.
Fortunately, the .NET framework has a handy little helper function, where it can create the correct provider for you:
public static DbConnection GetConnection()
{
//Get the connection string info from our application config
ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings["Program.Properties.Settings.InventoryDBConnectionString"];
if (cs == null)
throw new Exception("Could not find connection string settings");
//Get the factory for the given provider (e.g. "System.Data.OleDbClient")
DbProviderFactory factory = DbProviderFactories.GetFactory(cs.ProviderName);
if (factory == null)
throw new Exception("Could not obtain factory for provider \"" + cs.ProviderName + "\"");
//Have the factory give us the right connection object
DbConnection conn = factory.CreateConnection();
if (conn == null)
throw new Exception("Could not obtain connection from factory");
//Knowing the connection string, open the connection
conn.ConnectionString = cs.ConnectionString;
conn.Open();
return conn;
}
I want to get the user id and the password of oracle db instance from the connection string that i have stored in my App.config file.
Here is the connection string stored in App.Config File
<add name="MyConnection" connectionString="Data Source=xe;User ID=UsmanDBA;Password=root;" providerName="System.Data.SqlClient" />
I have tried OracleConnectionString Builder but it does not return the password of connection string Here is the code:
public string ConPass()
{
OracleConnectionStringBuilder builder = new OracleConnectionStringBuilder();
builder.ConnectionString = con.ConnectionString;
return builder.Password;
}
this method does return the user id but not the password
Is there something i am missing? or is there any other way to do this?
Kindly help me to sort this out..
ConnectionString property never contains password. That is the security measure. In your code, password has been lost in this line:
builder.ConnectionString = con.ConnectionString;
You have to devise a different approach. For example, to read the connection string from config and then to feed it to the connection string builder. This might not be generally applicable if you only have the connection and no information from which config entry it was constructed...
On a related note, SQL Server connection (SqlConnection) exposes the Credential property which could be used to read password (I haven't actually tried this). I don't know of similar property in Oracle connection implementation.
You can make use of the SqlConnectionStringBuilder
string conString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
OracleConnectionStringBuilder builder = new OracleConnectionStringBuilder(conString);
string user = builder.UserID;
string pass = builder.Password;
My code works well but after trying to host it. Its database always response with the null value . I failed to host it. and now when i try to debug in my PC its also have the same problem of null response.
my class file and its scalar query code.
public Object ExecuteScalarQuery(String sp)
{
String _ConnString = System.Configuration.ConfigurationManager.ConnectionStrings["rfid"].ConnectionString;
// string _ConnString = ConfigurationManager.ConnectionStrings["rfid"].ConnectionString;
SqlConnection myConnection = new SqlConnection(_ConnString);
SqlCommand cmd = new SqlCommand(sp, myConnection);
Object result = 0;
try
{
myConnection.Open();
result = cmd.ExecuteScalar();
}
catch (Exception ex)
{
//if (myConnection.State == ConnectionState.Open)
// myConnection.Close();
}
finally
{
//if (myConnection.State == ConnectionState.Open)
// myConnection.Close();
}
return result;
}
And web.config file having connectionstring
<connectionStrings>
<add name="rfid" connectionString="Data Source=CHINTAN-PC\SQLEXPRESS;Initial Catalog=msdb;Integrated Security=True " providerName="System.Data.SqlClient"/>
while doing step by step debugging its connectionstring look like this which is not being working.
"Data Source=CHINTAN-PC\\SQLEXPRESS;Initial Catalog=msdb;Integrated Security=True "
One thing to check is that results are being returned by your stored procedure. I copied your code, made a table and a stored procedure to query all records from it, and it returned null when the table was empty and the value of the first column of the first row when I added a couple records.
add the property 'pooling'.
<add name="rfid" connectionString="Data Source=CHINTAN-PC\SQLEXPRESS;Initial Catalog=msdb;Integrated Security=True; pooling=false;" providerName="System.Data.SqlClient"/>
go to server explorer, select you data base. in the right pane(Properties) copy connection string and paste it. if that doesn't work. go to sql management studio. its your windows authentication and sql authentication problem. make a new sql authentication login and give userid="" and password="" like "sa" and "sa123" in the connection string.
Use toString to retrieve the string value
String _ConnString = System.Configuration.ConfigurationManager.ConnectionStrings["rfid"].ConnectionString.toString();