C# change custom connection string at runtime - c#

Bit new on EF. I'm, creating application where user selects database from computer. and now i want to change connection string to match location of the database for example : this is current connection string that points to database location somewhere on disk (C:\Users\student\Documents\TestData.md) :
add name="test" connectionString="metadata=res://*/Model2.csdl|res://*/Model2.ssdl|res://*/Model2.msl;provider=System.Data.SqlClient;provider connection string='data source=(LocalDB)\v11.0;attachdbfilename="C:\Users\student\Documents\TestData.mdf";integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework'" providerName="System.Data.EntityClient" />
now when user selects new database from disk the connection sting needs to change to location where new database is located (C:\Users\student\Desktop\NewSelectedDatabase.mdf) :
add name="test" connectionString="metadata=res://*/Model2.csdl|res://*/Model2.ssdl|res://*/Model2.msl;provider=System.Data.SqlClient;provider connection string='data source=(LocalDB)\v11.0;attachdbfilename="C:\Users\student\Desktop\NewSelectedDatabase.mdf";integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework'" providerName="System.Data.EntityClient" />
now i've created filedialog so user can select database and to get its adress . i've also changed my edmax to to recive custom connection string :
public partial class Tester : DbContext
{
public Tester()
: base("name=Test")
{
}
public Tester(string customcs)
: base(customcs)
{
}
now my problem is what do i pass to constructor as custom connection string ? i hope you understood me because i'm realy bad at english and explainig things

When you have the EF designer up, on the properties window is a connectionstring setting. Once you have everything set as you like, clear that setting to none. It rewrites the generated code to accept a connection string passed in on instantiating.
var mything= new dbcontext (connstring)
Another option would be to just create a new class (.cs) file giving it the same namespace that your Tester EF context belongs to, and paste this in there:
public partial class Tester : DbContext {
public Tester(string _connectionString) : base(ConnectionString(_connectionString)) {
this.Configuration.ProxyCreationEnabled = false;
this.Configuration.AutoDetectChangesEnabled = false;
}
private static string ConnectionString(string _connectionString) {
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.ProviderConnectionString = _connectionString;
entityBuilder.Metadata = "res://*/Models.Tester.csdl|res://*/Models.Tester.ssdl|res://*/Models.Tester.msl";
entityBuilder.Provider = "System.Data.SqlClient";
return entityBuilder.ToString();
}
}
Notice it's a partial class (just like the auto-generated ones for Tester are) -- and so you're adding to the auto-generated class made by EF (again, make sure they're in the same namespaces, so it really is an addition to the partial class, not just you off making your own little one).
This way, you're adding a new construction instantiation (that's passing a connection string) that gets modified into the right entity-connection-string builder (via the private static ConnectionString method).
var myThing = new Tester(ConfigurationManager.ConnectionStrings["db_DBName"].ToString());
I have one line in the web.config for the connection:
<add name="db_DBName" connectionString="Data Source=DBSERVER;initial Catalog=DBNAME;" providerName="System.Data.SqlClient" />
the build target defines its transformantion, and I just pass the same string into the code all the time.

Related

Why is this connection string invalid?

I read:
This ASP.NET page
whatched through the whole EF part of this pluralsight tutorial
And read nearly every web page ( including SO ones ) containing this error:
Format of the initialization string does not conform to specification starting at index 0
I still do not understand why this connection string is invalid:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-couleur-emotion.mdf;Initial Catalog=aspnet-couleur-emotion;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
My DBContext looks like this:
namespace couleur_emotion.Models
{
public class CouleurEmotionDB : DbContext
{
public CouleurEmotionDB()
: base("name==DefaultConnection")
{
}
public DbSet<PageModel> Pages {get;set;}
}
}
I've tried many different connection strings. Not even once was the database file even created. IT fails at the first call to:
var model = _db.Pages.ToList();
When trying to create the DB. Note the above line is in a class containing:
CouleurEmotionDB _db = new CouleurEmotionDB();

Add Entity Framework Model to Class Library

I have created a class library and added a EF Model but as soon as I declare a variable my project just skip the rest of my code without any error. I do not understand what is causing this to happen.
Library Code
public class Phisc
{
//Global DB Entity variable
live_restoreEntities db = new live_restoreEntities();
//Write data to file
public void PhiscFile(int value)
{
string strFileName, strFilePath;
StreamWriter stm;
//Create a file name that will be created
strFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "_PHISC";
//The path that were the file will be saved
strFilePath = "c:\\" + strFileName + ".txt";
//Validate if file exists
if (!System.IO.File.Exists(strFilePath))
System.IO.File.Create(strFilePath).Dispose();
stm = new StreamWriter(strFilePath, false);
stm.Write("This is a test message from C#");
stm.Close();
}
}
WinForm Code
private void Form1_Load(object sender, EventArgs e)
{
Phisc.Phisc pFile = new Phisc.Phisc();
pFile.PhiscFile(14);
}
When I create a instance of the library it does not hit my PhiscFile Method.
I have added a breakpoint to it and it stops at this constructor
public live_restoreEntities() : base("name=live_restoreEntities", "live_restoreEntities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
I am using a windows application to test my library
The parameterless constructor goes out and look for the conenctionstring in the App.config file. It look next to the .exe file.
I'm guessing that you need to include your App.config (from your entity library) to your WinForms library.
In the App.config, it should look like this:
<configuration>
<connectionStrings>
<add name="live_restoreEntities"
connectionString="<your connection string here>"
providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>

How can I get a connection string from a text file?

I have developed a Windows application with the backend of SQL Server to insert employee names. I am going to insert the employee details on three databases one by one. So, I like to get connecting values from text file. Whenever I want to change the connection, I just want to enter the login details in the text file.
How can I get a connection string from a text file?
Use an app.config (MSDN) file.
Allows you to configure multiple named connection strings which you can access via the System.Configuration.ConfigurationManager class' ConnectionStrings property
Plaese try like this
using System;
using System.IO;
class Test
{
public static void Main()
{
string txtpath = #"c:\textfile.txt";
try
{
if (File.Exists(txtpath))
{
using (StreamReader sr = new StreamReader(txtpath))
{
while (sr.Peek() >= 0)
{
string ss = sr.ReadLine();
string [] txtsplit = ss.Split(';');
//now loop through array
string server=txtsplit[0].Tostring();
string userid= split[1].Tostring(); // user id
string password= split[2].Tostring(); // password
}
}
}
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.ToString());
}
}
}
You don’t need to use plain text file to do this. There is a special configuration file you can use and a set of classes to make your life easier.
Add configuration file to you project
Go to Add new item in the solution and select Application Configuration File
Add connection strings to the configuration file
Just copy / paste this and modify connection string and connection string name as needed
<configuration>
<connectionStrings>
<add name="Conn1" connectionString="Data Source=SERVER_NAME;Initial Catalog=DATABASE;Persist Security Info=True;User ID=USER;Password=12345678" providerName="System.Data.SqlClient"/>
<add name="Conn2" connectionString="Data Source=SERVER_NAME;Initial Catalog=DATABASE;Persist Security Info=True;User ID=USER;Password=12345678" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
Add System.Configuration reference to your project
Right click references, go to add new and select System.Configuration from .NET tab
Add wrapper class
This is not needed but it will make your life easier. Create a class like this so you don’t have to call configuration manager every time you need to connect to database
using System;
using System.Configuration;
using System.Text;
namespace WindowsFormsApplication4
{
class Config
{
public static string CONNECTION_STRING_1
{
get
{
return ConfigurationManager.ConnectionStrings["Conn1"].ConnectionString;
}
}
public static string CONNECTION_STRING_2
{
get
{
return ConfigurationManager.ConnectionStrings["Conn2"].ConnectionString;
}
}
}
}
Use connection strings in other methods like this
SqlConnection conn = new SqlConnection(Config.CONNECTION_STRING_1);
class Sql
{
public static string ReadCS()
{
using (var streamReader = File.OpenText("SqlSettings.txt"))//Enter FileName
{
var lines = streamReader.ReadToEnd();
return lines;
}
}
public SqlConnection con = new SqlConnection(Sql.ReadCS());
}

Data Source in connection string - Setup project

I'm creating a setup project for my C# desktop application.
What the data source should be written in the connection string for the access database ?and where I should put my database file in the solution project ?
Assuming you're using the VS setup project, you need to add the access database file as content and place it in the application directory, for example. To specify the location in the configuration file, you need to write a custom action that modifies the connection string accordingly.
The following example is an installer class that sets the connection string after install phase (not tested):
[RunInstaller(true)]
public partial class Installer1 : System.Configuration.Install.Installer
{
public Installer1()
{
InitializeComponent();
this.AfterInstall += new InstallEventHandler(Installer1_AfterInstall);
}
void Installer1_AfterInstall(object sender, InstallEventArgs e)
{
string sTargetDir = Context.Parameters["TargetDir"];
string sAppConfig = Path.Combine(sTargetDir, "<your app>.exe.config");
string sDBPath = Path.Combine(sTargetDir, "<your db>.mdb");
XDocument doc = XDocument.Load(sAppConfig);
var elem = doc.Root.Element("/configuration/connectionStrings/add[#name='<your connection name>']");
string connectionString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};", sDBPath);
elem.SetAttributeValue("connectionString", connectionString);
doc.Save(sAppConfig);
}
}
Alternatively, you can use Wix which has the XmlFile utility in the util extension which does it for you without you writing a custom action.

Trouble getting the MvcMiniProfiler to work with EF4.1 and our Repository Pattern

We're having lots of problems trying to get the MvcMiniProfiler to work with our EF implementation of the Repository Pattern.
Error:
The entity type CustomEntityPewPewFooFoo is not part of the model for
the current context.
Ok. this is the code we've done.
Custom UnitOfWork Context class
public class UnitOfWork : DbContext
{
public UnitOfWork(string connectionString)
: base(GetProfiledConnection(connectionString))
{ }
private static DbConnection GetProfiledConnection(string connectionString)
{
var parsedConnectionString = new
EntityConnectionStringBuilder(connectionString);
var connection = new
SqlConnection(parsedConnectionString.ProviderConnectionString);
return ProfiledDbConnection.Get(connection);
}
public void Commit() { ... }
}
Add the factory settings stuff...
// NOTE: If this is not added, I get an error:
// Unable to find the requested .Net Framework Data Provider.
// It may not be installed.
// In web.config ...
<system.data>
<DbProviderFactories>
<remove invariant="MvcMiniProfiler.Data.ProfiledDbProvider" />
<add name="MvcMiniProfiler.Data.ProfiledDbProvider" invariant="MvcMiniProfiler.Data.ProfiledDbProvider" description="MvcMiniProfiler.Data.ProfiledDbProvider" type="MvcMiniProfiler.Data.ProfiledDbProviderFactory, MvcMiniProfiler, Version=1.7.0.0, Culture=neutral, PublicKeyToken=b44f9351044011a3" />
</DbProviderFactories>
</system.data>
And finally, add this extra stuff....
// global.asax, in Application_Start().. because I'm caching
// some database data on startup.
var factory = new SqlConnectionFactory(ConfigurationManager.ConnectionStrings[0].ConnectionString);
var profiled = new MvcMiniProfiler.Data.ProfiledDbConnectionFactory(factory);
Database.DefaultConnectionFactory = profiled;
LoadApplicationDataToBeCachedForAllRequests(); // Go and hit the Db! Go Forth!!!
My connection string...
<connectionStrings>
<clear />
<add name="XWing_SqlServer_EF" connectionString="metadata=res://*/SqlServer.XWingModel.csdl|
res://*/SqlServer.XWingModel.ssdl|
res://*/SqlServer.XWingModel.msl;provider=System.Data.SqlClient;
provider connection string='Data Source=Tarantino;Initial Catalog=XWing;Integrated Security=SSPI;MultipleActiveResultSets=True;'"
providerName="System.Data.EntityClient" />
</connectionStrings>
And finally (again), then edmx info ..
- Entity Container Name: XWingEntities
- Namespace: XWing.Repositories.SqlServer
- Filename: XWingModel.edmx
It might be that you have the same kind of problem I had here. Basically, if the UnitOfWork class is not in the same assembly as the edmx, it will not work.

Categories

Resources