I have this code to Backup My database using C#.
But I get Backup Failed for Server ADMIN-PC error message.
I can run Backup from SQL Server Management Studio but from here for some reason it gives me this error.
How can I make this work?
private void btnBackup_Click(object sender, EventArgs e)
{
progressBar1.Value = 0;
try
{
Server dbServer = new Server(new ServerConnection(txtServer.Text, txtUserName.Text, txtPassword.Text));
Backup dbBackup = new Backup() {Action = BackupActionType.Database, Database = txtDatabase.Text};
dbBackup.Devices.AddDevice(#"C:\PDM.bak", DeviceType.File);
dbBackup.Initialize = true;
dbBackup.PercentComplete += DbBackup_PercentComplete;
dbBackup.PercentComplete += DbBackup_Complete;
dbBackup.SqlBackupAsync(dbServer);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message ", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void DbBackup_Complete(object sender, ServerMessageEventArgs e)
{
if (e.Error != null)
{
label5.Invoke((MethodInvoker)delegate
{
lblStatus.Text = e.Error.Message;
});
}
}
private void DbBackup_PercentComplete(object sender, PercentCompleteEventArgs e)
{
progressBar1.Invoke((MethodInvoker)delegate
{
progressBar1.Value = e.Percent;
progressBar1.Update();
});
label5.Text = $"{e.Percent}%";
}
}
Is that the all exception message? Try only the backup work without progressbar and see what exception is thrown. Without full picture, people here cannot help you enough.
Do you only have to use that way for backup ?
This is my code to backup database for your reference.
using (SqlConnection masterdbConn = new SqlConnection())
{
masterdbConn.ConnectionString = localmasterConnectionString;
masterdbConn.Open();
using (SqlCommand rollback_dbcomm = new SqlCommand())
{
rollback_dbcomm.Connection = masterdbConn;
rollback_dbcomm.CommandText = "ALTER DATABASE mydbname SET MULTI_USER WITH ROLLBACK IMMEDIATE";
rollback_dbcomm.ExecuteNonQuery();
}
masterdbConn.Close();
}
SqlConnection.ClearAllPools();
using (SqlConnection backupConn = new SqlConnection())
{
backupConn.ConnectionString = localConnectionString;
backupConn.Open();
using (SqlCommand backupcomm = backupConn.CreateCommand())
{
backupcomm.CommandText = #"BACKUP DATABASE mydbname TO DISK='c:\mydbname.bak'";
backupcomm.ExecuteNonQuery();
}
backupConn.Close();
}
Alter DATABASE ROLL BACK IMMEDIATE command finishes all the unfinished transactions with the database and let's say 'hands off from the database to be ready for Backup.
And you need to check roles and permissions in the connectionstring..
Can you show the SQL syntax to backup in SQL Server Management Studio? and the connectionstring without the credentials(like password)?
And can you describe you problem in more detail?
Backup work needs deep understanding how Sever works..
Related
So I am using c# windows form with visual studio to query an access database.
When I run with debugger and stop the application from within visual studio there is no problem, however when I run WITHOUT debugger, query the database and then close using X, the process which appears under "Apps" in Task manager becomes a background process. I can have multiple instances of this process if I run the application numerous times.
I would appreciate any information on this, Thanks!
Here is the code I am using.
private void BtnSendQuery_Click(object sender, EventArgs e)
{
ReadDatabase();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
var x = MessageBox.Show("Are you sure you want to exit? ", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (x == DialogResult.No)
{
e.Cancel = true;
}
else
{
e.Cancel = false;
}
}
private void ReadDatabase()
{
string CONNECTION_STR = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source = C:\\Users\\***\\Documents\\db_folder\\access_db.accdb;
Persist Security Info = False";
string query = ""; // query string
OleDbConnection DB_CONNECTION = null;
try
{
DB_CONNECTION = new OleDbConnection(CONNECTION_STR);
DB_CONNECTION.Open();
query = TbInputQuery.Text;
var command = new OleDbCommand(query, DB_CONNECTION);
var str = new StringBuilder();
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
str.AppendLine(reader["ID"].ToString());
}
TbOutputTable.Text = str.ToString();
}
DB_CONNECTION.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (DB_CONNECTION != null)
{
DB_CONNECTION.Close();
}
}
}
}
As general rule, both your connection and cmdSQL or reader should be in a using block.
While your reader is in a using block, the ALL important connection object is not.
In fact, once beyond the using block for connection? You could get away not even having using blocks for the command and reader object.
And even if a trapped error, or UN-trapped error occurs? The using block WILL ALWAYS clean up the connection.
So, for command and reader - not end of world for using block.
But, for connection? yes, always do that.
Project->settings - I would use the connection builder for the connection string - not put in code.
eg this one:
Then use advanced, and make sure you choose ACE (for accdb) or JET (for mdb)
So this:
So, with above setting, then we have ONE spot in the system - never typing connecting string by hand or having to place in the code (makes change of connection very hard).
Also, don't use "any cpu" force the project to x86 for using Access x32
(or if using x64, then force project to that).
So, code say like this:
private void ReadDatabase()
{
string CONNECTION_STR = Properties.Settings.Default.AccessDB;
string query = ""; // query string
try
{
using (OleDbConnection DB_CONNECTION = new OleDbConnection(CONNECTION_STR))
{
using (OleDbCommand command = new OleDbCommand(query, DB_CONNECTION))
{
DB_CONNECTION.Open();
var str = new StringBuilder();
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
str.AppendLine(reader["ID"].ToString());
}
TbOutputTable.Text = str.ToString();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
}
}
Note in above - don't really care about the catch block - as long as the using block for the connection is built - it gets cleaned up no matter what - and even if no try/catch, or if in fact you have one!!
And if a error trigger - still again, note how we do NOT have to clean up, or close the connection.
I need register the user access on my webpage aspx in MySQL remote Database.
But this MySQL remote Database it could be unavailable.
I have tried this code, but how to execute the RegisterUSer() method in the bool IsServerConnected() method ?
public bool IsServerConnected()
{
using (var l_oConnection =
new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString))
{
try
{
l_oConnection.Open();
return true;
}
catch (OdbcException)
{
return false;
}
}
}
private void RegisterUSer()
{
using (OdbcConnection myConnectionString =
new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString))
{
string sql = #String.Format(" INSERT IGNORE INTO tbl_user ");
sql += String.Format(" ... ");
using (OdbcCommand command =
new OdbcCommand(sql, myConnectionString))
{
try
{
command.Connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
command.Connection.Close();
}
}
#Edit 01
Error :
The type or namespace name 'resultType' could not be found (are you
missing a using directive or an assembly reference?)
You could just do a "wrapper" method that calls first to IsServerConnected() and depending on the returned boolean then calls RegisterUSer() or throws an error if the database is not availiable.
Quick and dirty pseudocode
private resultType ChickenWrapMethod()
{
if (!IsServerConnected())
{
//Throw some error here and exit
}
RegisterUSer()
}
BTW...in my opinion you should consider opening the sql connection out of the methods so it can be shared by both operations
Try this in c#. I hope I was helpful.
using System.Net.NetworkInformation;
var ping = new Ping();
var reply = ping.Send("XX.XX.XX.XXX", 60 * 1000); // 1 minute time out (in ms)
if (reply.Status == IPStatus.Success)
{
Response.Write("Server XX.XX.XX.XXX is up");
RegisterUSer();
}
else
{
Response.Write("Server XX.XX.XX.XXX is down");
}
I can't get connected to MySql database via SSH on remote desktop. I use C# and SshNet library. Actually, I have no problem to connect to the database with the help of popular tools, such as SQL Manager Lite, but when I do the same thing with the same settings with my tool - always get
Mysql 1042 Error (Unable to connect to any of the specified MySQL hosts)
Also, the part in my.cnf is edited to
bind-address = 0.0.0.0 and
# skip-networking. (Yes I tried with localhost and server ip on bind-address - same problem)
And I also granted all permissions to the user. Double-checked that.
Please, look at the code, maybe I missed something.
And sorry, I'm using forms, I just will need GUI :{
Many thanks in advance, everybody.
PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo("serverip", "sshlogin", "sshpass");
connectionInfo.Timeout = TimeSpan.FromSeconds(30);
using (var client = new SshClient(connectionInfo))
{
try
{
client.Connect();
if (client.IsConnected)
{
label1.Text = "ssh ok";
}
else
{
label1.Text = "ssh shit";
}
var port = new ForwardedPortRemote(3306, "serverip", 3306);
client.AddForwardedPort(port);
port.Start();
if (port.IsStarted)
{
label5.Text = "port open";
}
else
{
label5.Text = "port shit";
}
var conn_info = "Server=serverip;Port=3306;Database=database;Uid=remoteuser;Pwd=password;";
bool isConn = false;
MySqlConnection conn = null;
try
{
conn = new MySqlConnection(conn_info);
conn.Open();
isConn = true;
}
catch (ArgumentException a_ex)
{
label3.Text = "Check the Connection String.";
label4.Text = a_ex.Message;
label5.Text = a_ex.ToString();
}
catch (MySqlException ex)
{
string sqlErrorMessage = "Message: " + ex.Message + "\n" +
"Source: " + ex.Source + "\n" +
"Number: " + ex.Number;
label3.Text = sqlErrorMessage;
isConn = false;
switch (ex.Number)
{
case 1042: // Unable to connect to any of the specified MySQL hosts (Check Server,Port)
break;
case 0: // Access denied
break;
default:
break;
}
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
client.Disconnect();
label2.Text = isConn.ToString();
}
catch (SocketException exd)
{
label5.Text = exd.Message;
}
}
In your code, you are using var port = new ForwardedPortRemote(3306, "serverip", 3306); which will forward connections to port 3306 on the remote machine to 3306 on the local machine. Is this what you're trying to do? It seems like you want ForwardPortLocal or whatever the function would be called to forward connections the other direction.
I was facing the same issue. The MySql database was running on ubuntu and required SSH connection to connect. I downloaded the sshnet .NET 4.0 library from here. Then, importing the library into the project, the following steps were followed:
Establishing the ssh connection
var client = new SshClient("ip address of linux server", "username", "password"); client.Connect();
Check if the client got connected. If yes, then the port forwarding was done from Linux server to local server. This was a kind of magical line.
var portForwardedL = new ForwardedPortLocal(3306, "127.0.0.3", 3306);
client.AddForwardedPort(portForwardedL);
portForwardedL.Start();
Now just connect with the MySql Database using the forwarded serverip and port
using (MySqlConnection con = new MySqlConnection("SERVER=127.0.0.3;PORT=3306;UID=username;PWD=password;DATABASE=database_name"))
{
using (MySqlCommand com = new MySqlCommand("SELECT * FROM cities", con))
{
DataSet ds = new DataSet();
MySqlDataAdapter da = new MySqlDataAdapter(com);
da.Fill(ds);
foreach (DataRow drow in ds.Tables[0].Rows)
{
Console.WriteLine("From MySql: " + drow[1].ToString());
}
}
}
That's it! It worked like a magic!!! Please be sure to close the ssh connection.
I have written the following code to implement common connection string so that all the forms use the connection string provided in Login Form of my application.The application works fine on my machine but when I run my application on any other machine I get the error "Connection to the server could not be established" ie it enters the catch block. even when the UDL file is available on the machine.Can anyone help me to rectify this.
Thanks
public void FrmLogin_Load(object sender, EventArgs e)
{
btncancel.CausesValidation = false;
try
{
string FileName = "Intellect_LeadMt.udl";
if (!File.Exists(FileName))
{
MessageBox.Show(FileName + " File is not available in current folder!");
//return;
this.Close();
}
string[] str = File.ReadAllLines(FileName);
con = new OleDbConnection(str[2]);
con.Open();
add = new AddModify_Lead(this);
foll = new Follow_Lead(this);
rem = new Reminder_Lead(this);
ContctAdd = new AddContact(this);
UtilityMaster = new UtilityMasters(this);
LeadManagerForm = new LeadManager(this);
Register = new FrmRegistration(this);
Mainform = new Form1(this);
Ld = new LoginDetails(this);
Ul = new UserLog(this);
Mc = new Modify_Client(this);
}
catch
{
MessageBox.Show("Connection to Database currently is unavailable!\n Please Check udl and start application once again.\n Sorry For the inconvenience", "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
Application.Exit();
}
}
I have a VS2013 (written in C# x32) desktop application accessing a hosted SQL Server 2012. It has a report that has 4 subreports. After I installed it onto a few PCs, One of the PC has the above issue but the other PCs display the report correctly. The strange thing is the problem PC display this error half-way through subreport4. All PCs are running on Windows 7 (x32/64). I am really at a lost as to how to find out why it happened only to 1 PC which is basically similar to the rest.
The coding of the report is reproduced below:-
public partial class ReportProject : Form
{
cl_Class1 mySettings = new cl_Class1();
SqlConnection conReport = new SqlConnection();
public ReportProject()
{
InitializeComponent();
this.Text = "Test Report";
// Add a handler for SubreportProcessing
reportViewer1.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(LocalReport_SubreportProcessing);
}
// data set at the class level to access by all methods
DataSet dsReport = new dsTestReport();
private void ReportProject_Load(object sender, EventArgs e)
{
// connection to database
conReport.ConnectionString = mySettings.myConnString;
SqlCommand cmdReport = new SqlCommand();
SqlDataReader drReport;
try
{
// open connection
conReport.Open();
cmdReport.CommandType = CommandType.Text;
cmdReport.Connection = conReport;
// get query string from builder
string strMain = "aaaaa";
string strSub1 = "bbbbb";
string strSub2 = "ccccc";
string strSub3 = "ddddd";
cmdReport.CommandText = strMain + strSub1 + strSub2 + strSub3;
// execute query and load result to dataset
drReport = cmdReport.ExecuteReader();
dsReport.Load(drReport, LoadOption.OverwriteChanges, dsReport.Tables[0], dsReport.Tables[1], dsReport.Tables[2], dsReport.Tables[3]);
// close connection
drReport.Close();
conReport.Close();
// prepare report for view
reportViewer1.LocalReport.ReportEmbeddedResource = "myProgram.rptMain.rdlc";
ReportDataSource rds = new ReportDataSource();
rds.Name = "DataSet1";
rds.Value = dsReport.Tables[0];
reportViewer1.LocalReport.DataSources.Add(rds);
// preview the report
reportViewer1.RefreshReport();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (conReport.State == ConnectionState.Open)
{
conReport.Close();
}
}
}
void LocalReport_SubreportProcessing(object sender, SubreportProcessingEventArgs e)
{
string myReportName = e.ReportPath;
if (myReportName == "rptSubReport1")
{
e.DataSources.Add(new ReportDataSource("DataSet1", dsReport.Tables[1]));
}
if (myReportName == "rptSubReport2")
{
e.DataSources.Add(new ReportDataSource("DataSet1", dsReport.Tables[2]));
}
if (myReportName == "rptSubReport3")
{
e.DataSources.Add(new ReportDataSource("DataSet1", dsReport.Tables[3]));
}
if (myReportName == "rptSubReport4")
{
e.DataSources.Add(new ReportDataSource("DataSet1", dsReport.Tables[3]));
}
}
}
NOTE: SubReport3 and SubReport4 uses the same dataset (dsReport.Tables[3])
Would apprecate advise/help to resolve this.
Thank you in advance!
As a last resort, I uninstalled the reportviewer runtime from this PC (this is the only PC with a copy of the reportviewer). After the uninstall, the report now runs correctly! although this seemed to resolve the issue, I am still puzzled why this is the case - maybe there is something in the reportviewer runtime that conflict with the compiled software.