I have looked for multiple Solutions for my Problem.
I have a program, that needs to insert/update/select data from a Database nearly all the time. And the program itself works, but the problem is, it should also work in a production system with our staff and this needs to be secure.
One of the main thing is:
How do I manage, that the program can connect to the DataBase from our Staff PC's, without mentioning in the Connection String the Username and Password.
Some People said, I should use Windows Authentication.
But where do I mention the user/password that will be used to connect to the database? I need it to work in a way, people cant see the Login-Data to manipulate the DB-Server, but the programm itself should still be able to connect to it.
How can I do it?
Here are 2 connection strings my Visual Studio generated for me:
"Data Source=domain,Port;Initial Catalog=Zeiterfassung;Persist Security Info=True;User ID=sa;Password=PW"
"Data Source=domain;Initial Catalog=Zeiterfassung;Integrated Security=True"
First one works fine, but the password is visible there. That shouldn't be. Even if I store it somewhere in the program, a decompiler will still make it visible.
Will the second string really work on ANY PC out there, that has internet connection and the program? So no one can see the Information need to Manipulate the program outside of the program or the Admin itself? Right now I can test on authorized PC's, that have a user which is manually added as authorized on the DB-Server, but what is with other users? The should only be able to connect to the DB with the Program, not manually with their Windows Account in MSSMS. Last thing should really be forbidden.
A Simple Code Snippet to clarify how the Connection looks for Example:
class Utility {
private static SqlConnection con;
static Utility() {
con = new SqlConnection();
con.ConnectionString = Properties.Settings.Default.DBPath1;
}
public static DataTableReader getSelectDataTableReader(string selectCommand, SqlParameter[] parameter) {
SqlDataAdapter adapter = new SqlDataAdapter(selectCommand, con);
if (parameter.Length > 0) {
adapter.SelectCommand.Parameters.AddRange(parameter);
}
DataSet ds = new DataSet();
try {
adapter.Fill(ds, "Table");
} catch (Exception ex) {
writeToLog(ex.Message);
return null;
}
return ds.Tables["Table"].CreateDataReader();
}
Related
I don't get it why my (very simple) code is working properly on my local machine from Visual Studio 2022 and on the local IIS 10 to connect to a sql server express (15) and on my webserver it's not. I'm sure that's a really simple quesion for you.
What I'm tryin' to do is a simple login page. My code in the Login.aspx is:
using System.Data;
using System.Data.SqlClient;
try
{
SqlConnection con = new SqlConnection(#"Data Source=BERLIN\SQLEXPRESS;Initial Catalog=membersarea; User ID=sa;Password=Test2022!");
SqlCommand sqlCmd = new SqlCommand("select * from useraccount where username=#userName and passWord=#Password", con);
sqlCmd.Parameters.AddWithValue("#userName", tbxUsername.Text.ToString());
sqlCmd.Parameters.AddWithValue("#passWord", tbxPassword.Text.ToString());
SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlCmd);
DataTable datatable = new DataTable();
sqlAdapter.Fill(datatable);
con.Open();
int i = sqlCmd.ExecuteNonQuery();
con.Close();
if (datatable.Rows.Count > 0)
{
Session["userName"] = tbxUsername.Text.ToString();
datatable.Dispose();
Response.Redirect("Content.aspx");
}
else
{
lblMessage.Text = "Benutzername oder Passwort falsch.";
lblMessage.ForeColor = System.Drawing.Color.DarkOrange;
lblMessage.Visible = true;
}
}
catch(Exception ex)
{
}
(I know that I'm not supposed to do this with the sa account, just to keep it simple... The only thing I do on the web server is to change the name of the sql server instance. Management Studio works fine with this User Id and Password on my web server. I installed the sql server using Plesk and I don't think it is working properly within plesk. Using the Management Studio I can restore backups, queries, create new accounts, etc.)
My Content.asps says Hi (including my name) and shows the Logout-Button. If you enter credentials that are not correct it says so and if you try to go to the content-Page without loggin' in you're redirected to the Login-page. That is what I want. Trouble is, it's not workin' on my webserver. It is simply doin' nothing. No error message, or something else. It takes a while, password is cleared again and username is still there. (Doesn't matter which credentials are used.)
I don't think that it comes to the first line of my code, and I don't know why. Are there DLLs that are needed, or what else did I forget? I'm pretty sure this is a absolute beginner problem but I can't figure it out.
Tried to fill in some code to alter the lblMessage, to find out where the problem starts, but nothing of it is displayed.
I think the trouble started when I checked the pattern web forms while creating the project. In the bin folder there is a "name-of-my-project".dll and a "name-of-my-project".pdb file. Those two are generated if you recreate your project. I'm pretty sure you guys know that - I did not. Or better I do know that they were generated, but not that they are necessary. (As I wrote before, I'm at the very beginning.)
In guess that in this *.pdb and/or *.dll the connection string is stored, too. When I recreate my project with the valid connection string for the web server and upload them, too - everything works as expected. Thank you, guys for your ideas.
Just learning how to create an Windows Forms application via Tom Owsiak C# Windows Forms video tutorials and I'm stuck at the database project (contacts management system) which requires to store data to a database.
I've been following his every single step yet somehow manage to mess up the application writing process. The error happen at the line
SqlConnection conn = new SqlConnection(connString);
Have been searching stackExchange for a while now and try possible solution but still couldn't work it out.
// error occurs here, stated key word not supported, connection timeout
using (SqlConnection connectforfucksake = new SqlConnection(connString))
{
try
{
connectforfucksake.Open(); // open the connection
// create the new SqlCommand object
command = new SqlCommand(insert, connectforfucksake);
command.Parameters.AddWithValue(#"Data_Added", dateTimePicker1.Value.Date);
command.Parameters.AddWithValue(#"Company", txtCompany.Text);
command.Parameters.AddWithValue(#"Website", txtWebsite.Text);
command.Parameters.AddWithValue(#"Title", txtTitle.Text);
command.Parameters.AddWithValue(#"First_Name", txtFName.Text);
command.Parameters.AddWithValue(#"Last_Name", txtLName.Text);
command.Parameters.AddWithValue(#"Address", txtAddress.Text);
command.Parameters.AddWithValue(#"City", txtCity.Text);
command.Parameters.AddWithValue(#"State", txtState.Text);
command.Parameters.AddWithValue(#"Postal_Code", txtPostalCode.Text);
command.Parameters.AddWithValue(#"Mobile", txtMobile.Text);
command.Parameters.AddWithValue(#"Note", txtNote.Text);
command.ExecuteNonQuery(); // pushing whatever in the form into table
}
catch (Exception ex)
{
MessageBox.Show(ex.Message); // show the unforeseen error
}
}
Expected application to take result and then store them into database but it seem like the SqlConnection object instantiate is causing the error.
It sounds like your connection string is simply wrong; most likely, you meant "Connect Timeout" rather than "connection timeout". A basic connection string that includes a connect timeout might be something like:
Data Source=.;Initial Catalog=master;Integrated Security=True;Connect Timeout=42
I am having problems connecting to a SQL Server database from C#.
The exception that returns is the login has failed for the specified user, which is clear enough. However, I am not sure why it fails as the username and password are definitely correct. Are there any settings I need to enable on the SQL Server to allow this to happen, as it is a default express install,
Thanks,
Below is my connection code if I'm missing anything obvious.
static void Main(string[] args) {
try
{
SqlConnection con = new SqlConnection(#"Data Source = .\SQLEXPRESS;Initial Catalog=furniture_display;User ID=login;Password=login");
con.Open();
Console.WriteLine("all ok");
con.Close();
}
catch (SqlException err)
{
Console.WriteLine(err);
}
}
According to your code Data Source = .\SQLEXPRESS, you'r trying to connect to a local server. If so you don't need any ID and Password. And be aware of using Catalog, it's somehow tricky and I hate it. To know how it's working, check this out.
Actually I'm using this code and it works like a charm:
SqlConnection con = new SqlConnection(#"Server = localhost; Database = furniture_display; Integrated Security=True;");
Hello there I hope you're having a great time.
I have a question And I will break it down into 3 points:
1: create a class to connect to sql server the connection should be made using sql server authentication.
This class should contain several variables for connection parameters.
2: create a user form that shows the current connection parameters. And allow the user to update those parameters. In this form there should be a button to test the connect and another button to save the user changes to the connection parameters.
3: how to share the connection, created by the class we made in point 1, between different forms in the application. Without keeping too many open connections ideally only one connection should be open.
I will add the code that can solve this problem I hope that you can help me refine it.
I am new to all of this.
Thank you all for help.
already exists; SqlConnection and maybe SqlConnectionStringBuilder
that kinda already exists, via the IDE, but last time I checked this was not a redistributable dll. You could, however, simply hook a SqlConnectionStringBuilder to a PropertyGrid - or just write the UI from scratch
even "only one connection should be open" is wrong, IMO - let the inbuilt connection pooling deal with that; all you need is some configuration class with the connection string - and just deal with the connections as you need them, very locally - i.e.
using(var conn = new SqlConnection(Config.ConnectionString))
{
conn.Open();
// NOT SHOWN: do a couple of related operations
} // <== and here, it dies
1 : go to MSDN website you'll find what you need :
http://msdn.microsoft.com/fr-fr/library/system.data.sqlclient.sqlcommand.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
private static void ReadOrderData(string connectionString)
{
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(
queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
}
2: look at your connection properties (http://msdn.microsoft.com/en-us/library/System.Data.SqlClient.SqlConnection_properties.aspx) and fill a listView or equivalent with it
3: Use previous SqlConnection.Open() to deal with it
Right, I have been tasked with developing a new application in MVC3 that unfortunately has to integrate very slightly with a classic asp web site. This won't be forever as the old site will get an update at some point, but not yet. In the mean time however the new MVC3 application will need a little bit of access to the database for the old site, which is a old MS Access .mdb whereas the new app will be using sql server 2008.
I would greatly appreciate it if someone could give me some examples of how to connect to the access db, aswell as how to execute sql queries (i am fine writing the sql, just got no idea how to execute against the database from my mvc3 app).
thanks in advance
EDIT: I've not got much experience with the old site, but it appears to use the JET adaptor if that helps! ;-)
Your question requires an answer too extensive to be given in detail
I will give you a check list of things and class to research
Define the connection string used to reach your database [see
here]
Create and open the OleDbConnection
Define your OleDbCommand and the command text to be executed
Create and use an OleDbDataReader to read your data line by line
Create and use an OleDbDataAdapter to read your data and load a
DataSet or DataTable
Now don't forget to close your connection and use parametrized query
string connectionString = Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;Jet OLEDB:Database Password=MyDbPassword;
public void InsertRow(string connectionString, string insertSQL)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
// The insertSQL string contains a SQL statement that
// inserts a new row in the source table.
OleDbCommand command = new OleDbCommand(insertSQL);
// Set the Connection to the new OleDbConnection.
command.Connection = connection;
// Open the connection and execute the insert command.
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
}