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();
}
}
Related
I want to send SMS from my Application that is under developing on Windows Forms Application, The trouble to achieving this task is getting Port Number, I'm suffering by this issue over a week, kindly guide me, I'm sending uploading my code, one thing more is that I'm using Android OS on my cell phone where I have installed SIM card, and device vendor is HUAWEI. thanks a lot in advance......
private void button1_Click(object sender, EventArgs e)
{
GsmCommMain comm;
int portn = 0;
System.IO.Ports.SerialPort _srp = new System.IO.Ports.SerialPort();
try
{
Cursor.Current = Cursors.Cross;
System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_SerialPort");
Cursor = Cursors.WaitCursor;
foreach (System.Management.ManagementObject queryObj in searcher.Get())
{
Cursor = Cursors.Hand;
StatusLabel.Text = "Just Enterd in foreach Block...";
if (queryObj != null)
{
Cursor = Cursors.UpArrow;
object captionObj = queryObj["DESCRIPTION"];//Model Name
object capdeviceid = queryObj["DEVICEID"];//Comm port
object MaxBaudRate = queryObj["MAXBAUDRATE"];
object connstatus = queryObj["STATUS"];
object ct = queryObj.ToString();
int timeoutsec = 300;
StatusLabel.Text = "USB Modem Condition Main Enter Na Ho Saki...";
if (captionObj.ToString().Contains("USB Modem"))
{
_srp.PortName = capdeviceid.ToString();
portn = Convert.ToInt32(capdeviceid.ToString().Substring(3));
label1.Text = _srp.PortName + " ,,, " + portn;
comm = new GsmComm.GsmCommunication.GsmCommMain(portn, Convert.ToInt32(MaxBaudRate), timeoutsec);
StatusLabel.Text = "USB Modem Condition Main Entry...";
comm.Open();
if (comm.IsOpen())
btnSMSConnect.BackColor = Color.Green;
MessageBox.Show("Not Opening..." );
StatusLabel.Text = "Not Opening...";
}
}
}
}
catch (Exception e15)
{
MessageBox.Show("An error occurred while querying for WMI data: " + e15.Message);
btnSMSConnect.BackColor = Color.Transparent;
//comm.Close();
_srp.Close();
}
}
}
}
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..
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.
I'm new at this world of developing a software. So this may sound silly.
I'm working on developing a simple Login System at college, and I want to speed things up a little bit, my professor can be a tad, disorganized and it jeopardize the little time we have to learn a million things about programming.
I could get the program running and only opening the Main Form if the username and password are valid.
Before I researched and made a register button that will write data in my database, the message box was working properly.
But now, I cannot seem to make the message box show up saying if it is either, a successful login or if it is not.
My code is as following for the Login button:
private void VLogin_Click(object sender, EventArgs e)
{
try
{
string ConnectionString = "User ID=*****;Password=*******;" +
"Database=C:\\Users\\marqu_000\\Documents\\WindowsFormsApplication13\\Sistema.GDB;" +
"DataSource=localhost";
FbConnection addDetailsConnection = new FbConnection(ConnectionString);
addDetailsConnection.Open();
string SQLCommandText = "select * from LOGIN where USERNAME=#username and PASSWORD=#password";
FbCommand addDetailsCommand = new FbCommand(SQLCommandText, addDetailsConnection);
addDetailsCommand.Parameters.Add("#username", FbDbType.VarChar, 15).Value = userName.Text;
addDetailsCommand.Parameters.Add("#password", FbDbType.VarChar, 15).Value = userPassword.Text;
FbDataReader reader = addDetailsCommand.ExecuteReader();
while (reader.Read())
{
this.Visible = false;
MainWin MWin = new MainWin();
MWin.ShowDialog();
Application.Exit();
}
MessageBox.Show("Login Successful");
}
catch (Exception x)
{
MessageBox.Show("Invalid username or password");
MessageBox.Show(x.Message);
}
}
And this is my code for the register button:
private void registerUser_Click(object sender, EventArgs e)
{
try
{
string ConnectionString = "User ID=****;Password=****;" +
"Database=C:\\Users\\marqu_000\\Documents\\WindowsFormsApplication13\\Sistema.GDB;" +
"DataSource=localhost";
FbConnection addDetailsConnection = new FbConnection(ConnectionString);
addDetailsConnection.Open();
FbCommand SQLCommandTextInsert = new FbCommand("INSERT INTO LOGIN(USERNAME, PASSWORD, LEVEL) VALUES (#username,#password,#level)", addDetailsConnection);
SQLCommandTextInsert.Parameters.AddWithValue("username", registerUsername.Text);
SQLCommandTextInsert.Parameters.AddWithValue("password", registerPassword.Text);
SQLCommandTextInsert.Parameters.AddWithValue("level", registerLevel.Text);
SQLCommandTextInsert.ExecuteNonQuery();
MessageBox.Show("Registration completed!");
}
catch (FbException fbex)
{
//throw fbex;
MessageBox.Show("Invalid information, please verify!");
MessageBox.Show(fbex.Message);
}
}
If there is any good-for-nothing lines in there, and easiest ways to make those things, I would like to know.
I thank you all in advance for the help.
Marco.
ShowDialog is a blocking call, that means no code will run until that call completes. Which in this case is when your MWin closes. You'll need to display the success message before calling ShowDialog or call it from MWin.
Your Login failed message will only show when an exception occurs. I think if i read your code correctly if the reader returns no results (failed login) then you'll display "Login Succesful" and then doing nothing else.
You can use an if to determine if the database returned results and login failed is your else condition.
I finally made it!
I searched how to validate with a IF and could do it. This is how my code is now:
try
{
string ConnectionString = "User ID=*****;Password=*******;" +
"Database=C:\\Users\\marqu_000\\Documents\\WindowsFormsApplication13\\Sistema.GDB;" +
"DataSource=localhost";
FbConnection addDetailsConnection = new FbConnection(ConnectionString);
addDetailsConnection.Open();
string SQLCommandText = "select * from LOGIN where USERNAME=#username and PASSWORD=#password";
FbCommand addDetailsCommand = new FbCommand(SQLCommandText, addDetailsConnection);
addDetailsCommand.Parameters.Add("#username", FbDbType.VarChar, 15).Value = userName.Text;
addDetailsCommand.Parameters.Add("#password", FbDbType.VarChar, 15).Value = userPassword.Text;
FbDataReader reader = addDetailsCommand.ExecuteReader();
if (reader.Read())
{
this.Visible = false;
MessageBox.Show("Login Successful!");
MainWin MWin = new MainWin();
MWin.ShowDialog();
}
else
{
MessageBox.Show("Invalid username or password!");
}
I have a c# program which does the following on form load:
Creates an OleDbConnection to a database in the same folder as the program
Gets the computer name
Gets the username
Fills in some textbox fields on the form with data obtained from the database
When I open the form using Windows explorer, shortcut, or debugging in visual studio express 2013, it does all of this without any issues. When trying to open it with a command prompt or with a hyperlink, the database connection is not established, but no error messages appear. The textbox fields are filled with "not found" as a result of my try-catch statements around the oledb commands. The same try-catch statement should print ex.message to a text file, but that does not happen either. As stated before, this all runs flawlessly when running from debug mode in vs or running the program by opening it in Windows explorer, so I'm not sure how to debug this.
2 questions - Is there a known problem with opening c# forms which try to establish OleDb connections with access databases on form load when launching the program from command prompt or a shortcut? If so, are there any workarounds? Given that it runs fine in debug mode in vs, and my catch statements seem to be terminating prematurely without error messages, is there any other way to debug and find out exactly where the problem occurs?
I left off some of the irrelevant lines of code to make this shorter.
private void Form1_Load(object sender, EventArgs e)
{
userData = onLoad.loadDb(out userNotFound);
ComputerName = onLoad.getComputer();
// Session Notification
WTSRegisterSessionNotification(this.Handle, NotifyForThisSession);
// Initialize Hooks
initialize_Hooks();
if (userData.Count < 4)
{
for(int i = 0; i<4; i++) { userData.Add("Not Found"); }
}
// globals:
FullID = userData[0];
ID = userData[2];
firstName = userData[1];
lastName = userData[0];
nanid = userData[3];
fullName = firstName + " " + lastName;
// Fill in Form
label1.Text = fullName;
label2.Text = ID;
label3.Text = nanid;
}
public class onLoad
{
public static string getUser() // returns Environment.UserName
public static string getComputer() // returns System.Environment.MachineName;
public static List<string> loadDb(out bool userNotFound)
{
List<string> rList = new List<string>();
string strAccessConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=db.mdb";
string strAccessSelect = "SELECT (//select statement which works fine when I open the program in explorer or vs debug)
DataSet myDataSet = new DataSet();
OleDbConnection myAccessConn = null;
try
{
myAccessConn = new OleDbConnection(strAccessConn);
}
catch(Exception ex)
{
for(int i = 0; i<4; i++) { rList.Add("Not Found"); }
error_handler.error_logger(ex.Message);
userNotFound = true;
return rList;
}
try
{
OleDbCommand myAccessCommand = new OleDbCommand(strAccessSelect, myAccessConn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(myAccessCommand);
myAccessConn.Open();
myDataAdapter.Fill(myDataSet,"table1");
}
catch (Exception ex)
{
error_handler.error_logger(ex.Message);
userNotFound = true;
for(int i = 0; i<4; i++) { rList.Add("Not Found"); }
return rList;
}
finally
{
myAccessConn.Close();
}
try
{
DataRowCollection dra = myDataSet.Tables[0].Rows;
foreach (DataRow dr in dra)
{
code that conditions the data, works fine when running the program
}
}
catch(Exception ex)
{
string returnString = ex.Message;
error_handler.error_logger(ex.Message);
userNotFound = true;
for(int i = 0; i<4; i++) { rList.Add("Not Found"); }
return rList;
}
return rList;
}
}
class error_handler
{
public static string filename = "error.txt";
public static void error_logger(string error_message)
{
error_message = onLoad.getUser() + "\t" + DateTime.Now.ToString("MM/dd/yy hh:mm:ss") + "\t" + onLoad.getComputer() + "\t" + "Error: " + error_message;
if (!File.Exists(filename))
//writes error_message to a new text file or appends if it already exists. works fine when running from windows explorer or vs debug
}
}
I bet that shortcut passes in the working directory as a parameter. The documentation for File.Exists() states that when using a relative path the relative path information is interpreted as relative to the current working directory.
You can use the Directory.GetCurrentDirectory() function to determine if the path is set correctly.
If you are using files that you know are going to be in a path relative to the application I would use Application's path or at least set Environment.CurrentDirectory = Application's path.
Also take a look at the Environment.GetCommandLineArgs()[0]. That is probally being set by the shortcut.