Handle backslash in the connection string - c#

I have a following connection string in app.config
<add name="myDBConnectionString"
connectionString="Data Source=ASDFG\SQLEXPRESS;
Initial Catalog=ZAQ;
Integrated Security=True;"/>
in my C# code then, when I get this string DB is always evaluated as "ASDFG\\SQLEXPRESS"
I couldn't put # since app.config doesn't like it. Also, if I say
ASDFG\\SQLEXPRESS
it gets evaluated as
ASDFG\\\\SQLEXPRESS
and not open the connection.
Thank You,

The debugger may display it as ASDFG\\SQLEXPRESS, but it's just escaping that backslash for display purposes.

use this in codebehind
string conString =
System.Configuration.ConfigurationManager
.ConnectionStrings["myDBConnectionString"].ToString();

always evaluated as "ASDFG\SQLEXPRESS"
Which is quite correct. Any actual problems opening the Db?

Related

An OLE DB Provider was not specified in the ConnectionString. 'Provider=SQLOLEDB

I am creating an application which uses access file from shared network.The application works fine when the access file is placed local.But when I placed it in shared path and trying to connect.It is throwing an exception."An OLE DB Provider was not specified in the ConnectionString. 'Provider=SQLOLEDB
Here is my code:
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\server\\MyFirstProject\\SampleDB2.accdb";
using (OleDbConnection con = new OleDbConnection(connectionString))
{
string command = "INSERT INTO emp_status(emp_id,hours,feeded_on,comments)";
command += "VALUES(#emp_id,#hours,#feeded_on,#comments)";
Could anyone help me how to resolve this issue and Am I missing something?
I am using OLEB as a datasourse and Access 2013
Any Suggestions or explanations would definitely helps me.
Thanks in advance!!
You need to escape the leading double slash as well...
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\\\server\\MyFirstProject\\SampleDB2.accdb";
I haven't got anything to check this on here, but I'm fairly sure this is your answer. Also, watch out for reserved words, E.g. "hours" might be one in which case it should be [hours].
Also, you haven't specifically included adding the parameter values in your question. I assume you are doing it but if not then see my coding example here...
VB 2010 error (INSERT INTO) syntax error

Check Database ConnectionState

I'm connecting to Firebird Database using C#
I can't find where to check the ConnectionState to the database
If I make new fbConnection inside project it's easy to check it by fbConnection.ConnectionState
but I have made this connection with wizard and it's saved in App.config file
I tried to use System.Configuration.ConfigurationManager but it doesn't have ConnectionState
So how can I check connection state that defined in App.config file.
It seems that you don't understand how this thing (the connection) works or what it is. The ConfigurationManager class just helps you to retrieve the connectionstring (note the word string. It is just a string nothing more).
With this string you can build your real instance of an FBConnection and try to open that connection. Now you could check the ConnectionState.
So
string connectionString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
using(FbConnection myConnection = new FbConnection(connectionString))
{
// At this point the myConnection instance is certainly closed so
// it is total useless to check the ConnectionState
myConnection.Open();
// At this point the myConnection instance is certainly opened,
// otherwise you get an exception and your code cannot contine,
// so also here it is useless to check the ConnectionState
// however...
if(myConnection.ConnectionState == ConnectionState.Open)
{
.... do your stuff with the connection.....
}
}
For this code to work you need to have in your App.Config the appropriate section where you store the details required to connect to your database under the symbolic name "MyConnection"
<connectionStrings>
<add name="MyConnection" connectionString="Data Source=localhost;
Database=YourDatabaseFile.fdb;
User=YourUserName;
Password=????whatever???;
Pooling=True" />
</connectionStrings>
So I really have never needed to check the connection state of a connection. The only possible use if this property is when you want to keep a global connection instance and in various part of your code you need to check the ConnectionState before trying to open or close this global instance. This scenario is not the best way to work with a disposable object like the connection that should be opened for the shortest period of time possible and the immediately destroyed (disposed) And exiting from the using block disposes the connection.
Check out this link, it may be useful for you.
https://sourceforge.net/p/firebird/NETProvider/ci/0475d606c597498a99be50393646c1c92d773dd4/tree/examples/ASP.NET/web.config

How do I create a runtime envrionmental variable from a build time environmental variable?

I am not sure this is possible but I want to create a runtime environmental variable that gets evaluated at build time.
The idea being that three developers can use different servers for testing and not have to change it every time the project is checked out.
This is in C# .net
I do stuff like that sometimes.
<connectionStrings>
<add name="BobServer" connectionString="bob's connection string" />
<add name="MaryServer" connectionString="mary's connection string" />
<add name="JimServer" connectionString="jim's connection string" />
</connectionStrings>
string
ConnectionName = Environment.UserName + "Server",
ConString = ConfigurationManager.ConnectionStrings[ConnectionName].ConnectionString;
using (SqlConnection con = new SqlConnection(ConString))
{
}
If Environment.UserName is Bob, it will use the BobServer connection string. If it's Mary, it will use MaryServer. You'd probably need to make some modifications, but this should help put you in the right direction.

Using an entity framework connection string in ADO

We have a need to use an old fashioned ADO database connection in one tiny part of the main entity framework application.
We can manually specify the connection string in this part of code, but given that the connection string is already present in the App.Config this seems redundant.
However when we use the configuration manager to retrieve the connection string, it brings with it all of the metadata stuff that entity framework uses.
This causes an error as ADO doesnt recognise the metadata keyword.
How can I parse this connection string to remove the metadata and just get the plain ADO connection string?
You can get DbConnection instance from DbContext:
var context = new YourDbContext();
var connection = context.Database.Connection;
Of course, you can get connection string from connection, but you don't need thus you can use already existing connection object.
Here is Quick Watch of connection object - as you can see it's simple ADO.NET SqlConnection object with ordinal connection string.
In config file I have Entity Framework connection string with metadata:
<connectionStrings>
<add name="NorthwindEntities"
connectionString="metadata=res://*/Northwind.csdl|res://*/Northwind.ssdl|res://*/Northwind.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=Northwind;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
Below should work :
var efConn = new System.Data.EntityClient.EntityConnectionStringBuilder(efConnection);
string adoConn = efConn.ProviderConnectionString;
I was trying to the same and ended up using this approach:
private static string RemoveEntityFrameworkMetadata(string efConnection)
{
int start = efConnection.IndexOf("\"", StringComparison.OrdinalIgnoreCase);
int end = efConnection.LastIndexOf("\"", StringComparison.OrdinalIgnoreCase);
// We do not want to include the quotation marks
start++;
int length = end - start;
string pureSqlConnection = entityFrameworkConnection.Substring(start, length);
return pureSqlConnection;
}
This may not be the most elegant solution, but it works.
(I also tried Regex but can't get my head around it.)

Creating an SQL Server connection string without importing a datasource in C#

I am going off of this tutorial: http://www.dotnetperls.com/sqlclient . Instead of adding a data source and a having visual studio compile my connecting string - I want to do it myself. The reason being is that the database will not always be the same and I want this application to be able to use different databases depending on which I point it to.
So how can I manually create the connection string? I am using SQL Server 2005.
Step 1: Go to connectionstrings.com and find the proper format for your database.
Step 2: Plug in the appropriate values to the connection string.
Step 3: Pass that string to the constructor of SqlConnection.
I would also suggest storing your connection string in your app.config/web.config file. You can then modify them easily if needed. The proper format can be found at MSDN - connectionStrings element. You then change your code to:
SqlConnection sqlConn = new SqlConnection(
ConfigurationManager.ConnectionStrings["ConnStringName"].ConnectionString);
I don't see where the connection string is "compiled".
In the code
SqlConnection con = new SqlConnection(
ConsoleApplication1.Properties.Settings.Default.masterConnectionString)
ConsoleApplication1.Properties.Settings.Default.masterConnectionString is a field and it can be replaced with any other appropriate string.
for SQL Server format of the connection string is
"Data Source = server_address; Initial Catalog = database_name; User ID = UserId; Password = **;"
save this connection string in a string variable and use with connection object.
either way you can add in web.config file.
<ConnectionString>
<add name = "name_of_connecctionString" ConnectionString = "Data Source = server_address; Initial Catalog = database_name; User ID = UserId; Password = ****;" ProviderName = "system.Data.SqlClient"/>
</ConnectionString>
you can change the provider as needed by you.
then in code behind file access this particular connection string using configuration manager.

Categories