Sql connection security - c#

I use the code bellow to connect to my database on my website:
string tempstr = "Data Source=" + "72.55.---.---" + ";Initial Catalog=-------;Integrated Security=False;Persist Security Info=True;User ID=" + "MYUSER" + ";Password=" + "MYPASS";
SqlConnection con = new SqlConnection(tempstr);
con.Open();
Is it secure enough ? or someone who is not professional hacker can capture the username and the password which is sent from his/her computer to my database !?
thanks in advance.

Strings like the above will be stored in plain text in the executable.
If the "attacker" has access to the DLL, it is a simple thing to dump all the strings contained in it - including the connection string.
If you want to secure the connection string, a common practice is to store it in the connectionStrings section of the application .config file and encrypt it.

Related

Create Backup of attached database file

I have Database file .mdf which is installed with setup where application installed.
All database operation Insert,Update delete works fine but only problem arise in back up.
Now i want to make back up of attached mdf file to application installed path when i click on backup button.
Following is my connection string.
<add name="MyConstring" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Database=Database;Integrated Security=True;User Instance=True;Connect Timeout=30" providerName="System.Data.SqlClient" />
Code which create back up.
string serverName = "";
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.ConnectionString = ConfigurationManager.ConnectionStrings["MyConString"].ToString();
string server = builder.DataSource;
string attachDBFilename = builder.AttachDBFilename;
string DatabaseName = "[" + builder.InitialCatalog + "]";
string SQLBackUp = #"BACKUP DATABASE " + DatabaseName + " TO DISK = N'" + #"d:\Data\" + "Aa.bak" + #"'";
string svr = "Server=" + server + ";Database=master;Integrated Security=True";
SqlConnection cnBk = new SqlConnection(svr);
SqlCommand cmdBkUp = new SqlCommand(SQLBackUp, cnBk);
cnBk.Open();
cmdBkUp.ExecuteNonQuery();
Above code give following error only if i use database file attached.
But is gives error
"Database does not exist"
Your database service engine account must have access to that physical file. As error suggest it's a operating system error. So You need to give proper permission on that folder or file.
See following link.
http://dbamohsin.wordpress.com/2009/06/03/attaching-database-unable-to-open-physical-file-access-is-denied/
Write click on folder and goto security and give proper permission to the data folder so that your SQL server user can access that folder.

C# Winform Application

I am creating a winform application which connects to a ms-access database. The problem is with my connection string as i can access the database locally but if i run from my usb stick or from any other pc it would give me error. How can i modify my connection string so that i can run my application on other pc without any trouble.
string strConnect = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Aakash\Documents\Visual Studio 2013\Projects\Industrial Foundry\record.accdb";
using (OleDbConnection con = new OleDbConnection(strConnect))
{
con.Open();
using (OleDbCommand cmd = new OleDbCommand("select * from Industry ", con))
{
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
Perhaps this would be a good start:
http://msdn.microsoft.com/en-us/library/ms254494(v=vs.110).aspx
Since your title indicates you have a WinForms application, you may also want to consider adding a "Browse" button to locate the database and then using a connection string builder to build your connection.
I hope this can help you.
Create a winform where you can input parameters like "server", "password", etc., etc
After that, update your connection string with the parameters:
Friend Principal As New SqlClient.SqlConnection("data source=" & My.Settings.Server & ";INITIAL CATALOG=" & My.Settings.DB & ";UID=" & My.Settings.User & ";PWD=" & My.Settings.Password & ";workstation id=" & My.Settings.PC & ";packet size=4096")
Your connection string points directly to a path on your C: drive.
There are a number of ways that you could fix it; you could just prompt the user for the file location, and/or store it in a user configurable settings file.
I think simple way for you would be use App.Config file (Application Configuration File), you can add your database key in config file, when app launch you can check if key value is null than you should force user to choose database path, and you can set that database path to your config file. You can read your key value something using..
Code for Read Key
System.Configuration.ConfigurationSettings.AppSettings["DBKey"];
Code for Write Key
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection app = config.AppSettings;
app.Settings.Add("DBKey", "DBPath");
config.Save(ConfigurationSaveMode.Modified)
Thanks
Suresh

Cannot remotely connect to database

Im receiving a MySqlException was unhandled on a line: conn.Open();
MySqlConnection conn = new MySqlConnection("host=fdb5.freehostingeu.com;user=1477630_one;password=******;database=1477630_one;");
MySqlCommand cmd = new MySqlCommand("SELECT * FROM users WHERE name = '"+name+"'AND surname = '"+ surname +"';");
cmd.Connection = conn;
conn.Open();
I think the format of my connection string is wrong. and I've tried altering the values to see whether it's the problem but I'm still unable to connect.
what am I doing wrong?
According to their live support, they do not offer Remote Connection to MySQL on the free packages.
ConnectionStrings.com shows this as the correct standard format:
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
Adjusting yours accordingly:
Server=fdb5.freehostingeu.com;Uid=1477630_one;Pwd=******;database=1477630_one;
See this other answer if you need to allow remote connections to MySQL.
Shared web hosts almost never allow remote access to shared resources such as MySQL. What you will need to do is install a copy of MySQL in your local environment to do you development and testing. Then push your schema out through whatever tools they provide to you - these are usually web based. Then when you push your site to the shared host you the connection string you are using should work fine.
1) Be sure to add a reference to MySQL.Data
2) Include using MySql.Data.MySqlClient
3) Your connection string should be formatted as such:
connectionString = "SERVER=" + yourserver + ";" + "DATABASE=" + databasename + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
4) Do a try-catch statement to catch the errors

Can't connect to SQL Server DB

I'm trying to connect to a DB and I followed the connection string suggestions. However, I'm not a DB-guy so some things are, hrmp... less than obvious.
For instance, the DB server is within the network and the connection to it goes from another server, also in the same network. I've used the server name and port to connect to it using Management Studio so it's up and running.
This is my connection string.
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
conn.ConnectionString =
"integrated security=SSPI;"+
"server=server.name.as.in.management.studio,4340" +
"persist security info=False;database=NameOfTheDb";
The authentication is done using AD and the error message is 40 - can't find the server. Besides the obvious - the server can't be found - what can I do to trouble-shoot this, obtain more information etc.?
I'm at a customer and their system is not as well documented as one'd like. I get very little information and the coverage is questionable. The person who set up the attrocity is gone since a long time.
Suggestions are welcome.
EDIT
Following the corrections provided, I'm getting error code 0 - The requested name is valid but no data of the requested type was found.
What do I do with this?! :)
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
conn.ConnectionString =
"integrated security=SSPI;"+
"Data Source=myServerAddress;" +
"persist security info=False;" +
"Initial Catalog=NameOfTheDb";
Hope this helps.
Sure servce in Managmnet Sql Server is Start.
You can do that by go to ---> Control Panel-->All Control Panel Items-->Administrative Tools--Services --> SQL Server(MSSQLSERVER) and click Start.
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlDbConnection();
conn.ConnectionString =
"Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"User id=UserName;" +
"Password=Secret;";
conn.Open();

ConnectionString Database c#

I am create a database utility and I seem to not be able to get my connectionstring correct.
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|ConfigurationData.mdf;";
I believe this is in the correct format. As for the data source, my sql server is SQLExpress which runs sql server 2008 R2. My database is named ConfigurationData. Am I missing something?
When I run it, it opens the database - I assume it does since it does not through exception - but when I try inserting into a table, it does not actually insert it yet it executes the command.
conn.Open();
try
{
SqlCommand comm = new SqlCommand("INSERT INTO Test " + "(id,number) " + " VALUES(" + 10 + " , " + 12 + ")", conn);
comm.ExecuteNonQuery();
Console.WriteLine("Database is created successfully", "MyProgram");
}
catch (Exception ex)
{
}
finally
{
if ((conn.State == ConnectionState.Open))
{
conn.Close();
}
}
EDIT
Just remembered that I had answered a similar question a while back. Check it out:
Why can't I insert data into local database (SQL Compact Edition) with C#?
I don't think it is the connection string issue. But for your reference, a good site to refer to is http://www.connectionstrings.com/sql-server-2008/
You would need one of these:
Attach a database file, located in the data directory, on connect to a local SQL Server Express instance
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf;Database=dbname;
Trusted_Connection=Yes;
Attach a database file on connect to a local SQL Server Express instance
Server=.\SQLExpress;AttachDbFilename=C:\MyFolder\MyDataFile.mdf;Database=dbname;
Trusted_Connection=Yes;
Using an User Instance on a local SQL Server Express instance
The User Instance functionality creates a new SQL Server instance on the fly during connect. This works only on a local SQL Server instance and only when connecting using windows authentication over local named pipes. The purpose is to be able to create a full rights SQL
Server instance to a user with limited administrative rights on the computer.
Data Source=.\SQLExpress;Integrated Security=true;
AttachDbFilename=C:\MyFolder\MyDataFile.mdf;User Instance=true;
To use the User Instance functionality you need to enable it on the SQL Server. This is done by executing the following command: sp_configure 'user instances enabled', '1'. To disable the functionality execute sp_configure 'user instances enabled', '0'.
try (local) instead of dot, dot is not recognized in Win XP
conn.ConnectionString =
"Data Source=(local)\\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|ConfigurationData.mdf;";
You're SQL Statement isn't right also, and you should use parameters, but here is what you should have
SqlCommand comm = new SqlCommand("INSERT INTO Test (id, number) VALUES('" + 10 + " ', '" + 12 + "')", conn);
Why not just use the SqlConnectionStringBuilder class?:
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = #"(local)\SQLExpress";
builder.UserInstance = true;
builder.IntegratedSecurity = true;
builder.AttachDBFilename = "|DataDirectory|ConfigurationData.mdf";
SqlConnection conn = new SqlConnection(builder.ConnectionString());
The output:
"Data Source=(local)\\SQLExpress;AttachDbFilename=|DataDirectory|ConfigurationData.mdf;Integrated Security=True;User Instance=True"
One of the way to do this is to add your connection string in web.config file as shown below:
Jus click on the properties of database on the database explorer. There you will find connectionstring in its properties. Jus add it in connectionstring below.
<configuration>
<connectionStrings>
<add name="ConnectionName" connectionString="your connection string" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
Then in the page you can store it in string or directly refer to your connection as shown below:
Connection con=new SqlConnection();
con.ConnectionString=ConfigurationManager.ConnectionStrings["connString"].ToString();
and I suspect your insert statement is not properly declared.
Just try this:
SqlCommand comm = new SqlCommand("INSERT INTO Test (id,number) VALUES('10' ,'12')", con);
That's all from my part... Hope it helped you..

Categories