Empty connection string still opening w/o error - c#

I recently converted a Delphi app to C#, and I'm having an issue with an SQL connection. For some reason, when calling the CheckConnection function (shown below), IF my connection string has empty parameters, the connection is still able to .Open() without errors. Why is this? I feel like my CheckConnection function has an issue, or maybe I'm not understanding how .Open() actually works.
How it's set up - There are some textboxes that contain the hostname, user, etc. which are used as the parameters for the the connection string. Everything works fine when those are filled out correctly, but when the parameters (aka the textboxes) are all left blank, the connection still opens.
String hostname, user, password, database, protocol, query;
string connString;
IDbConnection SqlConn;
DbProviderFactory factory;
public void SetConnectionParams()
{
hostname = ServerTextBox.Text.Trim();
port = StrToIntDef(PortTextBox.Text, 3306);
user = UserIDTextBox.Text;
password = PasswordTextBox.Text;
database = DBTextBox.Text;
protocol = ProtocolTextBox.Text; //MIGHT not need
GetConnectionString(); //Get the correct connection string
}
//Gets the connection string from app.config
//The parameters for the string are all set via textboxes in diff. part of code
public void GetConnectionString()
{
if (MySqlRB.IsChecked == true) //Sets up connection for MySQL
{
var cs = ConfigurationManager.ConnectionStrings["MySQL"];
connString = ConfigurationManager.ConnectionStrings["MySQL"].ToString();
factory = DbProviderFactories.GetFactory(cs.ProviderName);
connString = String.Format(connString, hostname, port, database, user, password);
}
else //Sets up connection for MS SQL
{
if (WindowsAuth.IsChecked == true) //If windows authentication checkbox is checked
{
var cs = ConfigurationManager.ConnectionStrings["MSSQL_WA"];
connString = ConfigurationManager.ConnectionStrings["MSSQL_WA"].ToString();
factory = DbProviderFactories.GetFactory(cs.ProviderName);
connString = string.Format(connString, hostname, database);
}
else //don't use windows authentication
{
var cs = ConfigurationManager.ConnectionStrings["MSSQL"];
connString = ConfigurationManager.ConnectionStrings["MSSQL"].ToString();
factory = DbProviderFactories.GetFactory(cs.ProviderName);
connString = string.Format(connString, hostname, database, user, password);
}
}
}
//Supposed to check if the connection works or not
//This is working even if the connection string has empty parameters
public Boolean CheckConnection(bool check)
{
try
{
if (!CloseFirst && (SqlConn.State != System.Data.ConnectionState.Open))
{
return false;
}
else
{
using (SqlConn = factory.CreateConnection()) //make the connection
{
SqlConn.Close(); //make sure it's closed first just in case
SqlConn.ConnectionString = connString;
SqlConn.Open(); // Open the connection
if (SqlConn.State == System.Data.ConnectionState.Open)
{
SqlConn.Close();
return true;
}
else
{
return false;
}
}
}
}
catch
{
return false;
}
}
Example: Here's a connection string that's in my app.config for a sql server string:
<add name="MSSQL" providerName="System.Data.SqlClient"
connectionString="Data Source={0}; Initial Catalog={1}; User={2}; Password={3};" />
When debugging through the program, if I don't set any of the parameters, the string turns out like this:
connString = "Data Source=; Initial Catalog=; User=; Password=;"
That shouldn't be able to open right? It does though, and only when using SQL Server it seems, MySQL throws an error properly.
Edit:
Okay, turns out an error is not being thrown only when I use SQL Server windows authentication with this connection string:
<add name="MSSQL_WA" providerName="System.Data.SqlClient" connectionString="Data Source={0}; Initial Catalog={1}; Integrated Security=SSPI;"/>
Debugging through, the Data Source and Initial Catalog are empty, but the connection still opens. Not sure why this is?

Related

how to write connectionstring in web.config file

My code works well but after trying to host it. Its database always response with the null value . I failed to host it. and now when i try to debug in my PC its also have the same problem of null response.
my class file and its scalar query code.
public Object ExecuteScalarQuery(String sp)
{
String _ConnString = System.Configuration.ConfigurationManager.ConnectionStrings["rfid"].ConnectionString;
// string _ConnString = ConfigurationManager.ConnectionStrings["rfid"].ConnectionString;
SqlConnection myConnection = new SqlConnection(_ConnString);
SqlCommand cmd = new SqlCommand(sp, myConnection);
Object result = 0;
try
{
myConnection.Open();
result = cmd.ExecuteScalar();
}
catch (Exception ex)
{
//if (myConnection.State == ConnectionState.Open)
// myConnection.Close();
}
finally
{
//if (myConnection.State == ConnectionState.Open)
// myConnection.Close();
}
return result;
}
And web.config file having connectionstring
<connectionStrings>
<add name="rfid" connectionString="Data Source=CHINTAN-PC\SQLEXPRESS;Initial Catalog=msdb;Integrated Security=True " providerName="System.Data.SqlClient"/>
while doing step by step debugging its connectionstring look like this which is not being working.
"Data Source=CHINTAN-PC\\SQLEXPRESS;Initial Catalog=msdb;Integrated Security=True "
One thing to check is that results are being returned by your stored procedure. I copied your code, made a table and a stored procedure to query all records from it, and it returned null when the table was empty and the value of the first column of the first row when I added a couple records.
add the property 'pooling'.
<add name="rfid" connectionString="Data Source=CHINTAN-PC\SQLEXPRESS;Initial Catalog=msdb;Integrated Security=True; pooling=false;" providerName="System.Data.SqlClient"/>
go to server explorer, select you data base. in the right pane(Properties) copy connection string and paste it. if that doesn't work. go to sql management studio. its your windows authentication and sql authentication problem. make a new sql authentication login and give userid="" and password="" like "sa" and "sa123" in the connection string.
Use toString to retrieve the string value
String _ConnString = System.Configuration.ConfigurationManager.ConnectionStrings["rfid"].ConnectionString.toString();

convert string to ConnectionStringSettings

In my project I have a method which needs to return a ConnectionStringSettings object. As the database and server name will change dynamically, I need to dynamically
construct the connection string.
How do I convert a string to ConnectionStringSettings?
public ConnectionStringSettings getConnection(string server, string database)
{
//ConnectionStringSettings connsettings = new ConnectionStringSettings();
string connection = ConfigurationManager.ConnectionStrings["myConnString"].ToString();
connection = string.Format(connection, server, database);
// Need to convert connection to ConnectionStringSettings
// Return ConnectionStringSettings
}
--Web.config
<add name="myConnString" connectionString="server={0};Initial Catalog={1};uid=user1;pwd=blah; Connection Timeout = 1000"/>
The ConnectionStringSettings class constructor has an overload that takes two strings (first is the name of the connection string and the second is the connection string itself).
public ConnectionStringSettings getConnection(string server, string database)
{
string connection = ConfigurationManager.ConnectionStrings["myConnString"].ToString();
connection = string.Format(connection, server, database);
return new ConnectionStringSettings("myConnString", connection);
}
There's a third overload that takes in an extra string for the name of the provider.

Troubles reconnecting to MySQL database from C#

I can successfully log on to the database with this:
MySqlConnection conn = new MySqlConnection();
MySqlConnectionStringBuilder connString = new MySqlConnectionStringBuilder();
connString.Server = textEditServer.Text;
connString.UserID = "root";
connString.Password = textEditServerPassword.Text;
connString.Database = "geysercontrol";
conn.ConnectionString = connString.ConnectionString;
try
{
conn.Open();
Properties.Settings.Default.Properties["ConnectionString"].DefaultValue = conn.ConnectionString;
conn.Close();
}
catch (MySqlException)
{
XtraMessageBox.Show("No connection could be established");
}
But when I try to use the ConnectionString property to reconnect with different class, I get an MySQLException saying
Access denied for user 'root'#'localhost' (using password: NO)
What can be the possible causes to this? The page on possible causes on the MySQL website doesn't include my situation.
The code I use to reconnect is:
connection = new MySqlConnection();
connection.ConnectionString = (String)Properties.Settings.Default.Properties["ConnectionString"].DefaultValue;
connection.Open();
And the connectionString definitely is the same in both cases. It is:
server=localhost;User Id=root;database=geysercontrol;password=password
Add persist security info = true to the connection string I think.
If it were me though I wouldn't put connection string with a password in it in there. If you ever call Save, it will be exposed in the config file.

c# - entity framework with SqlServerCe.3.5 - Connection exception

i have problem with entity framework with SqlServerCe.3.5 connection.
i have small project called Assets with .SDF database and entity(the model name is Main).
now,when i'm trying to connect to the entity happend something weird.
in the first time everything works fine but now i had must to added this:
if (edmConnection.State != ConnectionState.Open)
{
edmConnection.Open();
}
because the connection to the entity all time was closed.
after i added this lines,i can reach to the database and the entity,but i got this message:
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
this is the stack Trace:
at System.Data.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString)
at System.Data.EntityClient.EntityConnection..ctor(String connectionString)
at System.Data.Objects.ObjectContext.CreateEntityConnection(String connectionString)
at System.Data.Objects.ObjectContext..ctor(String connectionString, String defaultContainerName)
at BL.Model.DBEntities..ctor() in C:\Users\Orel\Documents\Visual Studio 2010\Projects\Assets\BL\Model\Main.Designer.cs:line 34
at BL.Handlers.mModelHandler..ctor()
at BL.Handlers.mModelHandler.GetOnlyInstance() in C:\Users\Orel\Documents\Visual Studio 2010\Projects\Assets\BL\Handlers\mModelHandler.cs:line 30
this is my code and the app.config:
private static mModelHandler _mInstance = null;
public static DBEntities m_context = null;
public static mModelHandler GetOnlyInstance()
{
if (_mInstance == null)
{
try
{
m_context = new DBEntities(GetConnectionString());
_mInstance = new mModelHandler();
}
catch (Exception)
{
throw;
}
}
return _mInstance;
}
public static EntityConnection GetConnectionString()
{
try
{
var filePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
if (filePath == null) throw new ArgumentNullException("filePath");
if (filePath.EndsWith("\\Assets\\bin\\Debug"))
{
filePath = filePath.Replace("\\Assets\\bin\\Debug", "\\BL\\DB.sdf");
}
var sqlCeConnectionString = string.Format("Data Source={0}", filePath);
// Create an EDM connection
EntityConnectionStringBuilder entity = new EntityConnectionStringBuilder();
entity.Metadata = "res://*/Model.Main.csdl|res://*/Model.Main.ssdl|res://*/Model.Main.msl";
entity.Provider = "System.Data.SqlServerCe.3.5";
entity.ProviderConnectionString = sqlCeConnectionString;
var edmConnectionString = entity.ToString();
var edmConnection = new EntityConnection(edmConnectionString);
if (edmConnection.State != ConnectionState.Open)
{
edmConnection.Open();
}
return edmConnection;
}
catch (Exception e)
{
throw;
}
}
the app.config:
<add name="DBEntities" connectionString="metadata=res://*/Model.Main.csdl|res://*/Model.Main.ssdl|res://*/Model.Main.msl;provider=System.Data.SqlServerCe.3.5;provider connection string='Data Source=|DataDirectory|\DB.sdf'" providerName="System.Data.EntityClient" />
i read in the fourm that the problem can be that the app.config and the connection string are not match,i tried this also and it dosen't work..
i just added an image of this:
Link
Help!
Orel
I think your connection string isn't being parsed correctly. Try using " in place of the '.
I also believe that, for SqlCE, the provider within the quotes should be provider=System.Data.SqlServerCe,3.5; instead of provider=System.Data.SqlServerCe.3.5;.
Notice the , just before the version 3.5.
Putting it all together, we have:
<add name="DBEntities"
connectionString="metadata=res://*/Model.Main.csdl|res://*/Model.Main.ssdl|res://*/Model.Main.msl;provider=System.Data.SqlServerCe,3.5;provider connection string= "Data Source=|DataDirectory|\DB.sdf""
providerName="System.Data.EntityClient" />
Hope this helps.

How to validate ConnectionString exists and if not do not throw error

The connection name 'MySqlServer' was not found in the applications configuration or the connection string is empty.
So, I have a page with a panel that will display when the connection in the web config is found and the connection is valid; using a try/catch as long as the add name"VALUE" is in the config connection strings if the server data is bad the page will load and the panel is set to invisible... I need to be able to handle the following...
If the named value in this case MySqlServer is used in the aspx; aspx.cs but not found in the config I do not want the error to occur; connection name was not found.... I just want to not show the panel like when the SqlConnection.Open fails when the name is found but data is bad...
aspx
<asp:SqlDataSource runat="server" ID="allowedIPsSqlDataSource"
ConnectionString="<%$ ConnectionStrings:MySqlServer %>"
aspx.cs
string connectionString = ConfigurationManager.ConnectionStrings["MySqlServer"].ToString();
SqlConnection SqlConnection = new SqlConnection(connectionString);
SqlCommand SqlCommand = new SqlCommand();
try
{
SqlConnection.Open();
config
<connectionStrings>
<add name="NotMySqlServer" providerName="System.Data.SqlClient" connectionString="server=TEST\SQL2005;database=ADB;Integrated Security=True"/>
<add name="NotMy2SqlServer" providerName="System.Data.SqlClient" connectionString="server=TEST\SQL2005;database=ADB;Integrated Security=True"/>
</connectionStrings>
You can try :
if(ConfigurationManager.ConnectionStrings["MySqlServer"] == null) throw ...
If you're using .NET 4.5+ and have access to C# 6.0, you can make use of the null conditional operator (?) to try and get the connection string without automatically throwing an exception:
string connectionString = ConfigurationManager.ConnectionStrings["MySqlServer"]?.ConnectionString;
//------------------------------------------------------------------------HERE-^-HERE-------------
if (string.IsNullOrWhiteSpace(connectionString))
{
// Don't even bother trying to open the connection.
// Log the error and either rethrow the exception (throw;) or exit from your current context (return;).
//return;
//throw;
}
// If your code has made it this far, it means you have a valid connection string. Now try to use it.
using (var sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
using (var sqlCommand = new SqlCommand)
{
// Do stuff.
}
}
You can check if there are any connections strings by using count.
var count = ConfigurationManager.ConnectionStrings.Count;
if (count > 0)
{
//There is at least more then one connection string.
}
Update
public static class Extension
{
public static bool HasConnectionString(this ConnectionStringSettingsCollection value, string key)
{
try
{
return value[key].ConnectionString.Length > 0;
}catch
{
return false;
}
}
}
You can use the extension as follow.
if (ConfigurationManager.ConnectionStrings.HasConnectionString("MySqlServer"))
{
//If true you know there is a valid connectionstring.
}

Categories