Avoid writing the connection string in the code - entity-framework-4

I already finished my first c# application which manages some tables on a sql server 2005,but I want to modify it so that it could read the connection string from a text file . By doing that I can move my application to another PC by only changing the connection string in the text file and avoid any change in the code itself. How can I do this?

Take a look at System.Configuration (http://msdn.microsoft.com/en-us/library/system.configuration.aspx). There are some built in methods for reading configuration files (App.Config)

You should use the connectionStrings section in your app/web.config file:
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-EditorTemplateCollectiosns-20130404170435;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-EditorTemplateCollectiosns-20130404170435.mdf" />
</connectionStrings>
Then, when you want to access it in code, do this:
var connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"];
More on ConfigurationManager here, on configuration files here.

if you are developing desktop app, the preffered place is app.config
<connectionStrings>
<add name="TailorShop.Properties.Settings.TailorShopConnectionString" connectionString="Data Source=.\sqlexpress;Initial Catalog=TailorShop;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
Notice the connection name here, coz it is defined in the properties (double click on the properties node in your project solution explorer and go to settings)
And then you can add your connection string there. After that you will see as shown above;
Now, in-order to access it, you can do this in code;
Settings.Default.TailorShopConnectionString
In-order to work this code, you must add a reference e.g yourprojectname.properties;
using TailorShop.Properties;

You can manage your connection strings from a dedicated configuration section in your App.config file. Look here for more information on this.
Instead of using plain text files on non-standard solutions, see what .NET already provides. You can change the value in the config file when you move the application without needing to recompile it, because config is being read at runtime.
Here is an example:
<configuration>
<connectionStrings>
<add name="MyConnectionString"
connectionString="Data Source=.;Initial Catalog=MyDatabaseName;IntegratedSecurity=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Access it from code using ConfigurationManager.ConnectionStrings["MyConnectionString"].
If you really have to use a text file, then you should take a slightly different approach.
First you have to use a fixed path on the filesystem for the connection string file. You can either hardcode it in your app - a BAD PRACTICE, or use Settings or the App.config file to define the text file path.
You have to read the file programmatically. If it is plain text, you can use System.IO.File.ReadAllText(filePath); where the filePath argument is the absolute path to the file. For having the need to change the path when compiling the app, you can use the configuration/settings approach to define the physical path to the file, since changing them will not require recompilation (as earlier addressed for connection strings)

Related

Servicestack MySql connection string

I'm trying to figure out how to create a connection string in Servicestack for (in this case) MySql.
The question is: what is the connection string in Web.config supposed to look like ?
I stumbled on two ways:
1)
<appSettings>
<add key= "ConnectionString"
value= "Uid={User};
Password={Password};
Server= {EndpointUrl};
Port= {EndpointPort};
Database= customers" />
</appSettings>
and
2)
<connectionStrings>
<add name="testDb"
connectionString=
"Server= localhost;
Database= test;
UID= root;
Password= test"
providerName="MySql.Data.MySqlClient" />
</connectionStrings>
The question above is due to the fact that I have had a hard time to find an answer to this (apparently trivial) question. The answers I find are usually answering more complicated problems.
The Servicestack dokumentation looks like it's tuned to a rather more experienced audience than myself. Not by much but just, I'm a rookie at this.
This is a general problem I guess, in any documentation of a system. It's easy to go blind when it comes to fundamentals. What's self-evident to me is complicated for the next person.
A connection string should contain your database connection in a single string, this is an example of a MySql connection string to the “test” database on “localhost”:
Server=localhost;Database=test;UID=root;Password=test;SslMode=none
You can use this as a template and replace it with the parameters with your database info.
You can add this in your web.config with:
<add key="ConnectionString"
value="Server=localhost;Database=test;UID=root;Password=test;SslMode=none" />
Which you can then access with ServiceStack's AppSettings API:
container.Register<IDbConnectionFactory>(c => new OrmLiteConnectionFactory(
AppSettings.GetString("ConnectionString"), MySqlDialect.Provider));

Could not determine storage version error, EF 6 code first

I'm using EF code first approach in MVC and my web.config's connection string looks like-
<connectionStrings>
<add name="SchoolContext" connectionString="XYZ-server;integrated security=True;" providerName="System.Data.SqlClient"/>
</connectionStrings>
And I'm getting following error-
Server Error in '/' Application.
Could not determine storage version; a valid storage connection or a
version hint is required.
I also checked duplicates but none of them worked in my case-
Duplicate question1
Duplicate question2
I solved the issue by looking closely to the connection string, actually data source was missing, correct one is-
<add name="SchoolContext" connectionString="Data Source=XYZ-server;integrated security=True;" providerName="System.Data.SqlClient"/>

Splitting an Solution into multiple projects

I created a Black Solution (Arhi) with a ASP.NET MVC 4 Internet project (Arhi.Core) and Class library project for data (Arhi.Data) where I'm storing my EDMX Model.
I added a reference for Arhi.Data into Arhi.Core and I tried to add a Controller with a Model class from Arhi.Data (People entity) and I got this error.
'Unable to retrive metadata for 'Arhi.Core.People'. The specified
named connection is either not found in the configuration, not
inteneded to be used with the EntityClient provider, or not valid.'
Q : Why did I get this error ? Is my approach wrong / any recommendations?
Q2 : If I want to add RDLC reports to my solution, should I also use a Class Library project ?
Connection string from Arhi.Core
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=aspnet-SalvamontMVC-20121108140556;Integrated Security=SSPI" />
and Arhi.Data
<add name="SalvamontEntities" connectionString="metadata=res://*/ModelSalva.csdl|res://*/ModelSalva.ssdl|res://*/ModelSalva.msl;provider=System.Data.SqlClient;provider connection string="data source=www.arhimedes.ro,1433;initial catalog=Salvamont;persist security info=True;user id=sa;password=********;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
in your first connection string not have user name and password if two database deference then give user name and password in first connection string

Change server Entity Framework

I'm working on an mvc .net application and I'm using Entity Framework. I have the same database in different servers and I want to change the current server. I tried to change the connection string in the web.config file but it didn't work. How to safely change the server?
You must replace Data Source
<connectionStrings>
<add
name="AdventureWorksEntities"
connectionString="metadata=.\AdventureWorks.csdl|.\AdventureWorks.ssdl|.\AdventureWorks.msl;
provider=System.Data.SqlClient;
provider connection string='Data Source=.....;
Initial Catalog=....;
Integrated Security=True;
Connection Timeout=60;
multipleactiveresultsets=true'"
providerName="System.Data.EntityClient" />
</connectionStrings>
Changing the connection string in web.config is all you need to do.
Make sure you are changing the right connection string (the one with the metadata). Entity Framework will automatically put a connection string in the web.config when the model is first created.
The correct connection string will look something like this:
<add name="AdventureWorksEntities"
connectionString="metadata=.\AdventureWorks.csdl|.\AdventureWorks.ssdl|.\AdventureWorks.msl;
provider=System.Data.SqlClient;provider connection string='Data Source=localhost;
Initial Catalog=AdventureWorks;Integrated Security=True;Connection Timeout=60;
multipleactiveresultsets=true'" providerName="System.Data.EntityClient" />

MVC Entity Framework connection string references other project

I'm doing a Model first approach for a Microsoft MVC application. The solution is named "TutorialPile" divided into two projects, Domain and WebUI. I try to add a controller for the Tutorial object to the WebUI project, and I select the domain class and the DB context. However, I get the error, "Unable to retrieve metadata for TutorialPile.Tutorial. Unable to load the specified metadata resource."
Looking around online it looks like it can't find the edmx object in the connection string in the web.config file. I copied the connection string from the Domain project's app.config file but it still doesn't work. Here are the connection strings from the web.config file.
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
<add name="TutorialPileModelContainer" connectionString="metadata=res://*/Models.TutorialPileModel.csdl|res://*/Models.TutorialPileModel.ssdl|res://*/Models.TutorialPileModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLEXPRESS;initial catalog=TutorialPileDB;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="TutorialPileDbContext" connectionString="metadata=res://*/Models.TutorialPileModel.csdl|res://*/Models.TutorialPileModel.ssdl|res://*/Models.TutorialPileModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLEXPRESS;initial catalog=TutorialPileDB;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
And here is the connection string that I copied.
<add name="TutorialPileDBEntities" connectionString="metadata=res://*/TutorialPile.csdl|res://*/TutorialPile.ssdl|res://*/TutorialPile.msl;provider=System.Data.SqlClient;provider connection string="data source=.\sqlexpress;initial catalog=TutorialPileDB;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
Any ideas on what I need to change?
Make sure...
the edmx file's build action is set to EntityDeploy (select the file and go to the properties window).
Your WebUI project references the Domain project
Edit the connection string on your WebUI project to reference the metadata from the other project. Using * means it can come from any dll. BUT, if your edmx file is inside a folder, you have to map the hierarchy.
Eg:
Path to EDMX: TutorialPile.Domain/Model/TutorialPile.edmx
Connection string: res://*/Model.TutorialPile.csdl|res://*/Model.TutorialPile.ssdl|res://*/Model.TutorialPile.msl
Even better:
The documentation suggests you specify the assembly (for performance reasons) using the full name of the assembly (something like: AdventureWorks, 1.0.0.0, neutral, a14f3033def15840). I couldn't make it work. But, using only the name of the assembly works for me. So, if your domain project outputs a TutotialPile.Domain.dll, you can use:
res://TutorialPile.Domain/Model.TutorialPile.csdl|res://TutorialPile.Domain/Model.TutorialPile.ssdl|res://TutorialPile.Domain/Model.TutorialPile.msl

Resources