I have a Windows Installer prompting a user for MySQL information (server, port, username, password) and would like to make sure the parameters are correct prior to completing the setup.
I have have an Installer project with Custom Actions linked to the Installer Class and am doing my error checking there in the "Install" method. My error occurs at the catch() portion.
Any suggestions or comments greatly appreciated.
Edit: When I hit [Next] the installer installs the application and then prompts the MessageBox (if there's an error) but completes the installation. I was hoping for it to Rollback and bring up the previous screen.
Edit2: The exception caught from MySqlException is: "Unable to connect any of the specified MySQL hosts," which is correct, but the installer does not return/roll back.
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
// parameters from installer
// generate connection string conStr
MySqlConnection conn = new MySqlConnection(conStr);
MySqlCommand cmd = new MySqlCommand();
// open connection and create database
try
{
conn.Open();
cmd.Connection = conn;
// create database
// create table
// insert values to test
}
catch (MySqlException ex)
{
//I would like this to go back to the prior page
//where it asks for user input
MessageBox.Show("There was a problem connecting to the database.");
this.Rollback(stateSaver); // not working?
}
// close connection
conn.Close();
}
To force a rollback of your current installation you can rethrow the exception. you did just display in your messagebox.
Related
I'm currently writing code to save information to a database.
I think I'm at now approaching the last hurdle for getting it to work.
My issue is that when I click save I get a message box saying, Cannot open Database [Database file path] requested by the login. The login failed. Login failed for 'User-PC\User'.
However I didn't create any login details for the database as in the future I want anyone who uses the program to be able to log information into it.
I'm not quite sure where to look to solve the issue, but I am currently downloading SSMS to see if I can fix it there?
Any help would be great, thanks!
My code is,
string constring = "Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=c: \users\user\documents\visual studio 2015\Projects\LossApplication\LossApplication\LossDB.mdf;Integrated Security=Yes; Trusted_Connection=True; ";
string query = " insert into LossDB.LossTable (lossid,Equipment, Event, responsinility, start) values(#lossid, #equipment, #Cause, #reason, #start) ;";
SqlConnection conLossDB = new SqlConnection(constring);
SqlCommand cmdLossDB = new SqlCommand(query, conLossDB);
cmdLossDB.Parameters.AddWithValue("#lossid", textBox1.Text);
cmdLossDB.Parameters.AddWithValue("#Equipment", comboBox1.Text);
cmdLossDB.Parameters.AddWithValue("#Cause", comboBox2.Text);
cmdLossDB.Parameters.AddWithValue("#Reason", comboBox3.Text);
cmdLossDB.Parameters.AddWithValue("#start", dateTimePicker1.Text);
//Defines which boxes to read in order to input the text from the defined boxes into the corresponding columns
SqlDataReader myReader;
try
{
conLossDB.Open();
myReader = cmdLossDB.ExecuteReader();
MessageBox.Show("Loss Entry Saved");
//Opens the database and carries out the defined command outlined in the code above
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Using Integrated Security means Windows Authentication mode of the sql server, there must be a valid Windows user that has access to the database. If you want to use this mode and give access to all user on the computer, you can configure Windows Users group (to which all users typically belongs to) to have access to your database (see Security->Logins in your database configuration).
Another approach is to create a SQL user and user SQL Server Authentication mode. Then you use this user login and password to get access to the database regardless of Windows user. In this case your connection string will looks like
(LocalDB)\MSSQLLocalDB;Initial Catalog=<path>\LossDB.mdf;User ID=<UserLogin>;Password=<***>;Trusted_Connection=True;
I have a very strange case of SQL connection timeout from an application written in C# .NET.
The SqlCommand.ExecuteNonQuery() is being used to sequentially execute several scripts in SQL Server, one after another. Each script contains a command to create just one table (no data update/insert/delete operations at all). For some reason, at one of the scripts, the SqlCommand.ExecuteNonQuery throws a timeout exception.
When I execute creation of all these tables in SQL Server Management Studio, they get executed just fine and almost instantaneously.
Does anyone has an idea what could be causing timeout when the tables are created from the application?
All sql scripts look similar like following:
SQL:
create table dbo.Test
(
Code varchar(10) not null
, Name varchar(50) not null
, other columns...
primary key
, unique key
, foreign key
)
The scripts are shipped from C# using this code:
try
{
using (SqlConnection conSQL = new SqlConnection ("[connection string]"))
{
using (SqlCommand cmdSQL = new SqlCommand(sSQL, conSQL))
{
cmdSQL.CommandTimeout = iTimeOut;
conSQL.Open();
cmdSQL.ExecuteNonQuery(); // this is where it jumps to catch part and
// throws out timeout exception
conSQL.Close();
}
}
}
catch(Exception ex)
{
throw (ex);
}
This is happening on the Test server, meaning nothing else is happening on the server while the application is executing these scripts.
You can override the default time out setting for sql transactions by updating the machine.config, which can be found here:
%windir%\Microsoft.NET\Framework\[version]\config\machine.config
64-bit
%windir%\Microsoft.NET\Framework64\[version]\config\machine.config
At the end of the machine.config add or update the following line:
<system.transactions>
<machineSettings maxTimeout="01:00:00" /> --> set this to desired value.
</system.transactions>
</configuration>
If the above doesn't work, you can specify the Timeout setting for SqlCommand through code as well:
using (SqlConnection connection = new SqlConnection(connectionString)) {
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
// Setting command timeout in seconds:
command.CommandTimeout = 3600;
try {
command.ExecuteNonQuery();
}
catch (SqlException e) {
Console.WriteLine(e);
}
}
more information here
Just stop it from running and run again your problem will be solved.... It is generally occur first time only when their are lot of files to load maybe it is bug in visual studio.
New:
After stop try to refresh open Web page (in browser where error displays ) instead of relaunch it again...
I have a C# winform app named xyz.exe. It operates using xyz.config file. The config file is a plain text file and in it I put my settings I need to run my app , such as how many times it has to iterate, what files to read, what are the default values etc etc. It works just fine. All is working OK. Today I started to work on some enhancement request, I need to make a connection to a sql server database and retrieve some information. Very straight forward.
If I run debug (F5) all is working OK. But if I run it from command prompt by typing xyz.exe it throws exception "The type initializer for 'System.Data.SqlClient.SqlConnectionFactory' threw an exception." and it points to the connection section. if I rename xyz.config to something else , the exception went away. if I create a blank App.config (this will generate xyz.exe.config), the exception went away.
What is going on? Can anybody explain this to me and what are the possible solutions, options, best solution? is is possible to make the app to not looking for xyz.config and xyz.exe.config w/o throwing exception. It was ok before I introduce connection to db.
SqlConnection connection = new SqlConnection(
"user id=xx;" +
"password=xx;" +
"server=xx;" +
"database=xx; " +
"connection timeout=xx");
try
{
connection.Open();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
try
{
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from xx",
connection);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine(myReader["xx"].ToString());
Console.WriteLine(myReader["xx"].ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
connection.Close();
Config files should be named <exename>.exe.config, e.g. if your exe name is xyz.exe, its config file name should be xyz.exe.config.
If you want to use non-standard names, you have to read config files manually.
I have a very peculiar problem. In the VS2010 Server Explorer, I can connect to a SQL Server and execute a stored procedure just fine. However, when I try to do this in the code I get an exception thrown:
The xp_cmdshell proxy account information cannot be retrieved or is
invalid. Verify that the '##xp_cmdshell_proxy_account##' credential
exists and contains valid information.
Now maybe I used the wrong credentials in the code, but then I copied the connection string from the server explorer and put it into my connection string in my config file. Still, the same error.
Here is the code that does the connecting and calling of the stored procedure:
public static DataSet callStoredProcedure(string procedure, params SqlParameter[] args)
{
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet dataSet = new DataSet();
string connString = ConfigurationManager.ConnectionStrings["App"].ConnectionString;
try
{
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand command = conn.CreateCommand())
{
conn.Open();
if (args != null)
{
foreach (SqlParameter param in args) command.Parameters.Add(param);
}
command.CommandText = procedure;
command.CommandType = CommandType.StoredProcedure;
adapter.SelectCommand = command;
adapter.Fill(dataSet, "tabela");
}
}
catch (SqlException exception)
{
throw new Exception("SqlClient exception", exception);
}
return dataSet;
}
And here is the relevant config XML for the connection string, which is copied from the connection string the Server Explorer uses:
<connectionStrings>
<add name="App" connectionString="Data Source=db2.myapp.com,49178\hosting;Initial Catalog=app;User ID=appuser;Password=f00barbaz" providerName="System.Data.SqlClient" />
</connectionStrings>
Again, the Server Explorer can connect to the server and execute the stored procedure, but my code constantly throws the same Exception. What could be causing this?
Thank you
EDIT
To make it clear: the Server Explorer can both connect and execute stored procedures with the same connection string that my code uses. Yet my code throws an exception.
Does your sproc call xp_cmdshell?
If so, see:
http://msdn.microsoft.com/en-us/library/ms175046.aspx
When it is called by a user that is not a member of the sysadmin fixed
server role, xp_cmdshell connects to Windows by using the account name
and password stored in the credential named
xp_cmdshell_proxy_account. If this proxy credential does not exist, xp_cmdshell will fail.
The proxy account credential can be created by executing
sp_xp_cmdshell_proxy_account. As arguments, this stored procedure
takes a Windows user name and password. For example, the following
command creates a proxy credential for Windows domain user
SHIPPING\KobeR that has the Windows password sdfh%dkc93vcMt0.
can you debug and confirm that the conenction string from the web.config is actually beeing loaded into the connString variable?
also, this Data Source=db2.myapp.com,49178\hosting looks strange. I see server,port but what is hosting?
Initial Catalog=app is app the name of your DB?
I have been working on a c# project that connects to a access database, but a certain sequence of events causes it to crash with a AccessViolationException
The issue comes after calling a database connection using oledb in a separate form than the savefiledialog, and than calling savefiledialog1.ShowDialog()
Note: This also applies to the open file dialog.
It might be a bug in Access Database Engine 2010. Use 2007 instead.
connect.microsoft.com: oledb-operations-cause-accessviolationexception-during-savefiledialog
Codeproject: OpenFileDialog + OleDbConnection = AccessViolationException
Be sure you are using System.Data.OleDb from System.data.dll
Then try something like this:
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
// Declare Command
OleDbCommand command = new OleDbCommand(YourSQL);
// Set the Connection to the new OleDbConnection.
command.Connection = connection;
// Open the connection and execute the 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.
}
I had a similar issue, too, and this helped me:
I added "OLE DB Services=-1" in my connectionstring, now the problem is solved.
See: http://www.codeproject.com/Questions/106826/OpenFileDialog-plus-OleDbConnection-equals-AccessV.aspx SOLUTION 8