I've read a few links but most are in relation to when deploying or i've missed a trick in the middle so dont fully understand hence asking the below question......
I have a live, test and local environment (all have their own individual connection strings). I create a solution with 2 projects (for example) 1 is a ASP .Net website and other is a Class Library. Within the class library i add a Linq to SQL and add a connection to it. The connection string is stored in an app.config file.
What i would like to do is be able to switch between the environments so the connection string is updated to reflect the environment i am using without having to manually type in the connection string. I've seen this done but not sure how to do it myself? Im using VS2010. Could anyone advise or point me in the right direction?
Thanks
You could potentially use #if DEBUG and have two connections strings in your app.config - one called Test one called Live - I would suspect that debugging would indicate that you are in the test environment and on release you would be live.
Please refer to this link http://msdn.microsoft.com/en-us/library/4y6tbswk.aspx
Another option is to simply have an input at some point to indicate which environment the application is running on - you could do this with a checkbox or radio button or even through appSettings in app.config by specifying ConnectionMode and setting it to 1 or 2 if the setting reads 1, then use the test connection string, if it reads 2 Live connection string.
Related
Visual studio creates a new database out of thin air to store my data. This is my DbContext:
public class LinkedDataContext : DbContext
{
public DbSet<LinkedData> LinkedData { get; set; }
}
No errors are being thrown, I just end up with another database that is only visible through the SQL Server Object Explorer unlike my initially created database which is the top one in the screenshot.
Edit
I migrated the whole accounts database generated by the MVC project to the MSSQL 2014 server. I simply added a database there and changed the connection string, then it automaticaly populated the database with the needed tables.
So I created my custom table, exactly as it was in the local database. I removed the local databases, the other connection strings and the Controller. Then I rebuild my project and created the controller again. But VS/MVC/EF or whomever is responsible is still creating a local database for my custom data.
When I create the controller it seems to find my table in MSSQL SERVER 2014, otherwise I would get a safe dialogue to store the sql file locally. So what is really happening here? Like I said, the account functionality worked instantly like a charm. My custom table in MSSQL simply won't get used.
EDIT
So I set the DefaultConnectionFactory in Web.config to my MSSQL SERVER 2014 and now it is generating a new Database inside my MSSQL SERVER. It seems to be the namespace, when I create a controller I need to pass in the namespace for the both the Model class and Context class.
Model class: LinkedData (DataVisualization.Models)
Data context class: LinkedDataContext (DataVisualization.Models)
The databases that keep getting generated automatically to hold my custom data are called: DataVisualization.Model.LinkedDataContext.
Does anyone have any idea what is really going on here?
I believe it is just the connection string in your Web.config. When you create a DbContext from an existing database outside of your project, Visual Studio prompts
The connection you selected uses a local data file that is not in the
current project. Would you like to copy the file to your project and
modify the connection?
If you select Yes, this copies the database file into your project, sets its Build Action to Content, sets a relative reference to it in your connection string and sets it to copy to your output directory on build.
If you modify the connectionString in your Web.config to point to the correct database you should be set (for future reference, answer No when asked if you want to copy it, unless that is really what you want to do - e.g. for a database file you're distributing with your binaries).
As an example, see the two connections listed below. You would see something like ProjectContext if you selected Yes, or something like ExternalContext if you selected No.
<connectionStrings>
<add name="ProjectContext" connectionString="data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=|DataDirectory|\Database.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
<add name="ExternalContext" connectionString="data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=C:\Programming\.Net\DataVisualization\Data\DataVisualization\App_Data\Database.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
Note that the actual syntax of the connectionString may be different in your app depending on settings used, but the key part is the |DataDirectory| reference vs the correct path. The path is what you'd need to modify.
The shorthand solution is this:
public class LinkedDataContext : DbContext
{
public DbSet<LinkedData> LinkedData { get; set; }
public LinkedDataContext() : base("DefaultConnection")
{
}
}
I was assuming it would take the default connection if there was no connection named after the context. The reason was that I did not get a error so the connections would have been fine. Yet without specifying a connectionString in web.config it just seem to take part of the default string, since it does find my database and throws in it's namespace and creates a new database out of thin air. I might be new to MVC but I find this ridiculous default behavior. So I still have no clue what the idea behind this is.
Unless you want to have a couple of hundred connection strings for a fairly sized application the only way to go seems to be to call the parent constructor and specify the DefaultConnection there. Kind of ironic you have to "specify" default behavior.
Unlike what #tomtom told me, in almost 10 hours I did not find a single scenario that resembles mine. Maybe I was not clear but in my initial post I did specify each step I took. Using a MSSQL SERVER does not seem to be necessary.
Hope this helps someone else out.
STANDARD BEHAVIOR. As bad as it is. Your db template is copied to the runtime every time you hit the "debug" button, so you always start with a new datababase. Painfull as hell. Not sure how other's solve this - I never use this side of visual studio, I have a sql server installed and create my databases there manually. Makes sure i am always working against a defined copy. Obviously VS has no rights to create databases there ;)
If you bother using google or the site search a little you find tons of similar questions - this is a standard problem people regularly get trapped in because it is totally not what they expect.
(if you ask me, the whole db maintenance side of EF is broken anyway, including the "migrations" that hardly can use SQL Server most basic features).
Normally, in a .NET application, you store your database connection strings in the app.config.
For a single .exe, there's a single .exe.config. And we're using Entity Framework, which defaults to using a .config setting that matches the DbContext name. Which all works fine, so long as you follow the common pattern of having a single instance of an application talking to a single database.
But our problem requires we have multiple instances of our application, each with its own distinct database connection.
Possible solutions:
Create multiple copies of the .exe, each with its own copy of the .config, and put a different connection string in each. Advantage? No coding changes. Disadvantage? Maintaining all the different copies, making sure they all get updated, etc.
Keep one copy of the .exe, with one copy of the .config, and put multiple connection strings in the .config. Then pass a command-line argument to the program that selects which connection string to use. Advantage? Only one .exe to manage. Disadvantage? Coding change, likelihood that someone's going to mess up the command-line arguments.
Some other brilliant idea, that someone here on Stack Overflow is going to point out to me.
Any ideas?
I'm sure people have dealt with this issue, before. Is there a common way of handling the issue?
You can also think of creating copies of config file and load the appropriate one based on command line parameter using following code:
AppDomain.CurrentDomain.SetData ("APP_CONFIG_FILE", "path to config file")
See this for detail: Relocating app.config file to a custom path
You could try something like this within some C# applications to change the connection string per application.
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringSection.ConnectionStrings["database"].ConnectionString = string.Format("Data Source={0}", userCon);
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
We are moving database from one server to another. There are many connection strings of applications that needs to changed due to this. Is there any generic way where we can keep the connection string so that if we move the database again then this issue doesn't arise??
There are so many ways to resolve this problem.
Ultimately what it sounds like you want to do is centralize your database connection strings in such a way that a database migration is (mostly) transparent to your application. I can think of a few options here:
Use a "control database" that houses your connection strings and configurations. If you migrate to a new database server, you only have to update a single connection string in your application, and perform data updates for everything else. This is what I personally use.
Use a central XML configuration file that is parsed on application startup.
Use SQL Server Aliases and/or add additional IPs to the machine that you can migrate between servers. This way when you move to a new database server you can still bring along the existing aliases/IPs to that server (unless they need to run in parallel of course) and theoretically not need to update anything in your code, provided that you've referenced the appropriate aliases. See here for more info: https://dba.stackexchange.com/questions/56642/how-to-create-a-server-alias-in-sql-server-2012
Over here we ultimately went with option 1 because that gave us more flexibility and reliability than an XML configuration file (#2) and required less configuration and special cases to be documented with our DBAs, since we have no ownership of any database servers outside of our DEV environment.
Have the connection string in an xml file and read the xml file and get the connection string from it. You only need to change the connection string in the xml file and not in the published code. By the way you can have multiple connection strings for Debug and Release modes and make your application choose it.
You could store them in a database. ^_^
Jokes aside, I do not have experience with this myself, but using an Alias sound like it might suit you best:
http://blog.idera.com/sharepoint/performance-webcasts/plan-your-sharepoint-farm-right-with-a-sql-server-alias/
First, you can store your connection strings in external file (custom storage or .config file) - so you will be able to change them without recompiling the code.
Second, you can use domain name instead of IP address
And third, you can store your connection strings in parts and build them in runtime by ConnectionStringBuilder - so you can change only server part.
If I could make the connection string a "User" setting for them to edit, that would do nicely for now. At the moment the string contains a reference to my machine, where my test DB sits. I want to build an alpha for somebody else to try, but they'll need to point it to their own DB instance.
More generally, what is the correct approach to keep DataSets in the Visual Studio designer whilst having a connection string capable of being pointed to the configured server by the user? - at the moment they seem dependant on the Connection String in my Settings.
Use app.config with System.Configuration, they can then set the correct connection string in the config.
See this question for how:
Get connection string from App.config
Because, presumably, the ConnectionString back to your database contains highly sensitive information, such as server names, database names, even user ID's and passwords; as such, that information is inherently designed to be disguised or kept secret from the user community. Malevolent users of your application would very much enjoy the opportunity to leverage a user-controlled connection string.
It would seem that if you need to control data in this way, you should consider some kind of profiling mechanism that performs the specific data host selection in the background, not in an entirely user-controlled manner.
Edit
One possible alternative I would suggest is to determine the "alternative" servers in advance, and add the corresponding connection strings to the app's configuration file. In the application itself, provide some sort of user-friendly identifier that ties to the dataset the user wants to use, then tie that identifier behind the scenes to the proper connection string, thus keeping the particulars of the connection string private.
I have used Ruby on Rails with ActiveRecord, so I am quite used to switching to Production/Development database.
I am wondering, how do people implement Development and Production Database difference in ASP.NET MVC (preferably with ado.net entity).
I tried to have it by creating 2 entity datasets with the same name in a different namespace, so I would only need to switch the used namespace in my database code. Unfortunately, this didn't work because the entity datasets do not allow equal names...
The way I do it (with a web app) is to have separate versions of the Web.config file for each of Development (web.config), QA (web-qa.config), and Production (web-prod.config) installs. The config files have different connection strings pointing to the corresponding instances of the database. The default connection string points to the SQL server instance on my local machine which isn't available to the network.
As part of the publishing step, I manually delete the web.config file and rename the appropriate QA/Prod configuration to web.config. This hooks up that instance of the app to the correct instance of the database.
The easiest way (though it's still not as easy as in Rails) will be to include connection strings into App.config.
You should have one entity dataset, and instatiate the entities object using the constructor that takes a ConnectionString, which you can read in from:
WebConfigurationManager.ConnectionStrings["ConnStrName"].ConnectionString;
The ConnectionStrings element also supports the general configSource attribute.
You can therefore have something like:
<connectionStrings configSource="PathToConnectionStrings.config" />
This allows you to have all the connection strings held in a seperate file, that can then have different values on each environment.
Note that unlike the appSettings file attribute, this doesn't do a merge, it completely replaces the section.
Note that in VS2010, you will have the facility to modify the .config based on the build configuration, so could change the values just by setting your build to "Production" say.