Connecting multiple sql users to one database with entity framework - c#

Hello i am a beginner in C# winform,
I have to connect multiple users (400 different users) through a login form ( textbox : name - password) to a single sql database with Winform C#, all users are sql users created in the database and have roles like users or admin.
I have been looking for an easy way of doing this with entity framework but couldn't find anyhting.. anyone has an idea how this can be done ?
Thanks for your help.

Does every user need their own login to the database?
If this is true you would need to write a special connection string, something like below:
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"User id=" + UserName + ";"
"Password=" + Password + ";";
conn.Open();
Put this in a class that accepts the username and password.
Full example:
class myConnection
{
public static SqlConnection GetConnection(string UserName, string Password)
{
string str = "Data Source=ServerName;Initial Catalog=DataBaseName;User id=" + UserName + ";Password=" + Password + ";";
SQlConnection con = new SqlConnection(str);
con.Open();
return con;
}
}

User credentials are specified in the connection string, so you need to build a connection string with the data provided by the user in the login form.
var sqlBuilder = new SqlConnectionStringBuilder();
// Set the properties for the data source.
sqlBuilder.DataSource = "ServerName";
sqlBuilder.InitialCatalog = "DatabaseName";
sqlBuilder.UserID = "USERNAME";
sqlBuilder.Password = "PASSWORD";
sqlBuilder.IntegratedSecurity = true;
// Build the SqlConnection connection string.
string providerString = sqlBuilder.ToString();
// Initialize the EntityConnectionStringBuilder.
var entityBuilder = new EntityConnectionStringBuilder();
//Set the provider name.
entityBuilder.Provider = "System.Data.SqlClient";
// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = providerString;
And then use this connection string to initialize your DbContext
var context = new DbContext(entityBuilder.ConnectionString);

Related

SQL Bulk DestinationTableName

I use a .csv file to bulk insert into my SQL Server database. The problem is DestinationTableName because when I use a string for DestinationTableName, I get error exception
System.InvalidOperationException: Cannot access destination table
as you can see in the screenshot.
If a use "test" like copy.DestinationTableName = "test"; it works fine
string symbolName = dt.Rows[1][0].ToString();
string strConnection = #"Data Source =.\SQLEXPRESS; AttachDbFilename = C:\USERS\JEF\DOCUMENTS\DATABASE1.MDF; Integrated Security = True; Connect Timeout = 30; User Instance = True";
SqlConnection condb2 = new SqlConnection(strConnection);
string createTablerow ="create table ['"+symbolName+"'] (code1 VARCHAR(100) COLLATE Arabic_CI_AI_KS_WS,date1 varchar(50),open1 varchar(50),high1 varchar(50),low1 varchar(50),close1 varchar(50),vol1 varchar(50))";
using (SqlConnection connection = new SqlConnection(strConnection))
{
SqlCommand command1 = new SqlCommand(createTablerow, connection);
connection.Open();
command1.ExecuteNonQuery();
}
using (SqlConnection cn = new SqlConnection(strConnection))
{
cn.Open();
using (SqlBulkCopy copy = new SqlBulkCopy(cn))
{
copy.ColumnMappings.Add(0, "code1");
copy.ColumnMappings.Add(1, "date1");
copy.ColumnMappings.Add(2, "open1");
copy.ColumnMappings.Add(3, "high1");
copy.ColumnMappings.Add(4, "low1");
copy.ColumnMappings.Add(5, "close1");
copy.ColumnMappings.Add(6, "vol1");
copy.DestinationTableName = symbolName;
copy.WriteToServer(dt);
}
}
Just like you did when you created the table:
"create table ['"+symbolName+"']
the trick here is probably to escape the table name to compensate for the hyphen in it, so:
copy.DestinationTableName = "[" + symbolName + "]";
Note: if possible, it is usually preferable to stick to names that don't need escaping. But... if it works.

Retrieve data from database using C#

I'm trying to retrieve data from database in Microsoft visual studio 2013 . I am totally lost whether I am already able to connect to the database or not and I am not sure how to retrieve data using c# as I am totally new to c#.
I am also not sure where I should put the static void main method statement before or after connectDB() method.
private void connectDB()
{
// server = "172.20.129.159";
database = "eyetracker";
server = "localhost";
// uid = "ogamaaccess";
// password = "ogama";
uid = "root";
password = "root";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
c = new MySqlConnection(connectionString);
Console.WriteLine("Connected to database");
}
private bool OpenConnection()
{
try
{
c.Open();
Console.WriteLine("Connection Opened.");
return true;
}
catch (MySqlException)
{
return false;
}
You need to install the MySql NET Connector that provides the appropriate bits to connect to MySQL database.
After installing the provider you need to add a reference to MySql.Data.Dll and add the appropriate using statement to your code
using MySql.Data.MySqlClient;
You also need to change your connection string which could be found in here.
Connection code should look something close to this:
private void Login() // login method
{
string connectString = #"uid=<UserID>;password=<Password>;
server=<IPorDomainNameOfDatabase>;
database=<DatabaseNameOnServer>;";;
using(MySqlConnection cnn = new MySqlConnection(connectString))
{
try
{
cnn.Open();
}
catch (Exception e)
{
.....
}
}
}
Full code could look something like this (command should be edited according to data you want to retrieve):
MySqlConnection connect = new MySqlConnection(connectString);
MySqlCommand command = connect.CreateCommand();
command.CommandText = "Select <VALUE> from <TABLE> order by <ID> desc limit <0,1>;";
//Command to get query needed value from DataBase
connect.Open();
MySqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
var result = reader.GetString(0);
}
Note: I strongly suggest you to put connect.Open(); into TryCatch statment, since there are many things that can do wrong and your program will crash.

ServerConnection doesn't work with a connection string

I use below code to create backup from my database in c#.net. but when I run Code I getting this error :
Failed to connect to server Data Source=.;Initial Catalog=AngularJs;Integrated Security=True.
my code to do this is :
ServerConnection con = new ServerConnection("Data Source=" + txtServerName.Text + ";Initial Catalog=" + drpDatabases.SelectedItem.ToString() + ";Integrated Security=True");
Server server = new Server(con);
Backup source = new Backup();
source.Action = BackupActionType.Database;
source.Database = drpDatabases.SelectedItem.ToString();
BackupDeviceItem destination = new BackupDeviceItem(Path, DeviceType.File);
source.Devices.Add(destination);
source.SqlBackup(server);
con.Disconnect();
Where is Problem ? Why this is not work ?
I tested connections string with sqlconnection its work fine and open very well .
Try this:
ServerConnection con= new ServerConnection(new SqlConnectionStringBuilder(cnstring).DataSource);
Your code is wrong, use:
ServerConnection con = new ServerConnection(
new SqlConnection(
"Data Source=" + txtServerName.Text + ";Initial Catalog="
+ drpDatabases.SelectedItem.ToString()
+ ";Integrated Security=True"));
The ServerConnection(string) overload expects an instance name, not a connection string. You can simply write new ServerConnection(".") or :
var con = new ServerConnection(txtServerName.Text);
The error message tells you that ServerConnection tried to connect to a server having a name the same as the entire connection string and failed.
A ServerConnection represents a connection to a specific server, not a database, so it doesn't need a SqlConnection object. If you supply one, it's used only to extract the relevant information.
Try This:
SqlConnection con = new SqlConnection("Data Source=" + txtServerName.Text + ";Initial Catalog=" + drpDatabases.SelectedItem.ToString() + ";Integrated Security=True");
SeverConnection scon = new ServerConnection(con);
Server svr = new Server(scon);
because I think you're passing an incorrect parameter for the ServerConnection.

C# Sqlite connection does not fail on wrong password

This is how i create a database and put a password:
SQLiteConnection.CreateFile(filePath + "/" + username + ".sqlite");
dbconnection = new SQLiteConnection("Data Source=" + filePath + "/" + username + ".sqlite;Version=3;");
dbconnection.Open();
dbconnection.ChangePassword(password);
sychroniseDb("Create");
This is how i check if i can connect to the database:
try{
dbconnection = new SQLiteConnection("Data Source=" + filePath + "\\" + username + ".sqlite;Version=3; Password=" + password + ";");
localDbConnected = true;
dbconnection.Open();
return true;
}
catch
{
MessageBox.Show("User or password incorrect");
localDbConnected = false;
return false;
}
The problem in this whole thing is that even if the password is wrong it's still passes the Try and doesn't go in the Catch and even opens the connection. The dll are the ones from Nuget Packages. I have Visual Studio Express 2013.
The real problem is that when i do a query it tells me is encrypted or its not a database but why it passes that try catch?
From the Sqlite website it tells that if its wrong it shouldn't connect.
I had the same problem. To be thrown exception must be made some commands. Try the following code:
try
{
var dbPath = Path.Combine(filePath, (username + ".sqlite"));
var csb = new SQLiteConnectionStringBuilder { DataSource = dbPath, Version = 3, Password = password };
dbconnection = new SQLiteConnection(csb.ConnectionString);
dbconnection.Open();
//COMMENT: Any command to check whether the database is encrypted
using (SQLiteCommand command = new SQLiteCommand("PRAGMA schema_version;", dbconnection))
{
var ret = command.ExecuteScalar();
}
localDbConnected = true;
return true;
}
catch(SQLiteException)
{
MessageBox.Show("User or password incorrect");
localDbConnected = false;
return false;
}
According to System.Data.SQLite documentation, SQLiteConnection implements System.Common.DbConnection.
SQLite implentation of DbConnection.
For a list of all members of this type, see SQLiteConnection Members .
System.Object    MarshalByRefObject
      Component
         DbConnection
            SQLiteConnection
public sealed class SQLiteConnection : DbConnection, ICloneable
The MSDN documentation states:
Notes to Inheritors When you inherit from DbConnection, you must
override the following members: Close, BeginDbTransaction,
ChangeDatabase, CreateDbCommand, Open, and StateChange. You must
also provide the following properties: ConnectionString, Database,
DataSource, ServerVersion, and State.
On DbConnection.Open the MSDN documentation states:
Opens a database connection with the settings specified by the
ConnectionString.
Thus, it makes sense for implementers to only check the password when you actually open a dbconnection. Not in the constructor.

C# unable to establish SQL Server connection

I have a basic form with an 'Add Recipe' button which is meant to write the following to me SQL Server Express database:
Recipe Name
Recipe Ingredients
Recipe Instructions
Recipe Image
The form is located at the bottom of the question and when I click the 'Add Recipe' button it makes a call to the updatedate() method, this method looks like so:
private void updatedata()
{
// filestream object to read the image
// full length of image to a byte array
try
{
// try to see if the image has a valid path
if (imagename != "")
{
FileStream fs;
fs = new FileStream(#imagename, FileMode.Open, FileAccess.Read);
// a byte array to read the image
byte[] picbyte = new byte[fs.Length];
fs.Read(picbyte, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
//open the database using odp.net and insert the lines
string connstr = #"Data Source=.;Initial Catalog=RecipeOrganiser;Persist Security Info=True;User ID=sa";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
string query;
query = "insert into Recipes(RecipeName,RecipeImage,RecipeIngredients,RecipeInstructions) values (" + textBox1.Text + "," + " #pic" + "," + textBox2.Text + "," + textBox3.Text + ")";
SqlParameter picparameter = new SqlParameter();
picparameter.SqlDbType = SqlDbType.Image;
picparameter.ParameterName = "pic";
picparameter.Value = picbyte;
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.Add(picparameter);
cmd.ExecuteNonQuery();
MessageBox.Show("Image successfully saved");
cmd.Dispose();
conn.Close();
conn.Dispose();
Connection();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
My problem is when ever I click the 'Add recipe' button with the information populated, it freezes for around 30 seconds and then displays the following error, I have checked that the SQL Server services are running which thy are. Can anyone offer ay advice what I am doing wrong here?
Image of Form
string connstr = #"Data Source=.;Initial Catalog=RecipeOrganiser;Persist Security Info=True;User ID=sa";
needs to be
string connstr = #"Server=localhost\{SERVER_NAME};Database=RecipeOrganiser;Trusted_Connection=True;";
you can get the SERVER_NAME from the property value "Name" user the SQL server properties
Use the following link
SqlConnection con = new SqlConnection("Data Source=servername\\SQLEXPRESS;Initial Catalog=databasename;User ID=sa;Password=yoursqlserverpassword");
Hope it will help you
your connection string doesn't look good to me ... try using .Net SqlConnectionStringBuilder class to create a valid connection string ... set DataSource, InitialCatalog and IntegratedSecurity or UserId and Password properties

Categories