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.
Related
When I am trying to open a excel into one of my windows service using following code it is throwing "Value cannot be null. Parameter name: source" on objConn.Open(); Can any one please help me.
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
LogManager LogWrite = new LogManager();
try
{
string conn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Repository\RuleExcel\Rules_Repository_2018-06-28_03-41-29-133.xlsx;Extended Properties='Excel 12.0;HDR=YES;';";
LogWrite.WriteLog(conn);
// Create connection object by using the preceding connection string.
objConn = new OleDbConnection(conn);
LogWrite.WriteLog(objConn.DataSource);
// Open connection with the database.
objConn.Open();
try this below code, it works for me :
using (OleDbConnection objConn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + #";Extended Properties=""Excel 12.0;IMEX=1;HDR=YES;"""))
{
objConn.Open();
}
I am trying to insert data into Microsoft SQL Server DB using C# and the insert command works well and I get no errors or exceptions. But when I check my database in SQL Server there is no effect on the table and the records are not inserted into the table. This is the code that I try:
try
{
SqlConnection con1 = new SqlConnection();
con1.ConnectionString = "Server = (local); Database = My_DataBase; Integrated Security = true";
con1.Open();
SqlCommand cm1 = new SqlCommand();
cm1.Connection = con1;
cm1.CommandText = "insert into Users values('" + update.Message.Chat.Id.ToString() + "','" + update.Message.Chat.FirstName + "','" + update.Message.Chat.LastName + "','#" + update.Message.Chat.Username + "','" + req1.Status + "')";
con1.Close();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
continue;
}
I've seen similar questions here and here, but the answers did not fix my problem.
Also when I insert data to the DB manually and run select command like mentioned below, I get the correct answer but for the insert command I do not.
SqlConnection con2 = new SqlConnection();
con2.ConnectionString = "Server = (local); Database = My_DataBase; Integrated Security = true";
con2.Open();
SqlDataAdapter da1 = new SqlDataAdapter("select * from Users where ChatID='" + update.Message.Chat.Id.ToString() + "'", con2);
DataSet ds1 = new DataSet();
da1.Fill(ds1);
con1.Close();
Please help me fix this issue.
By the way I know that this kind of insertion is not safe and I'l like to let you know that this is just a demo and I will make it secure against sql injection.
You are not executing your command anywhere.
You need:
cm1.ExecuteNonQuery();
In your code, you are creating a SqlCommand object, then you associate a SqlConnection to it, but in no where you are actually executing the command. Your code should look like:
SqlConnection con1 = new SqlConnection();
con1.ConnectionString = "Server = (local); Database = My_DataBase; Integrated Security = true";
con1.Open();
SqlCommand cm1 = new SqlCommand();
cm1.Connection = con1;
cm1.CommandText = "insert into Users values('" + update.Message.Chat.Id.ToString() + "','" + update.Message.Chat.FirstName + "','" + update.Message.Chat.LastName + "','#" + update.Message.Chat.Username + "','" + req1.Status + "'";
cm1.ExecuteNonQuery();
con1.Close();
Apart from SQL Injection vulnerability, you should consider enclosing your SqlCommand and SqlConnection object in using statement, that will ensure proper disposal of un-managed resources.
hi guys I have this connection and I have to type it every time when I need my db is there any way to type it once and using it in every button by con.open(); and con.close();
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\db\\it.accdb");
Yes. Use a function.
private OleDbConnection GetConnection()
{
return new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\db\\it.accdb");
}
Then when you need a connection, call it:
var con = GetConnection();
Functions promote code re-use. This code can further be improved by moving the connection string into a configuration file.
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);
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