I want to put my connection string on a USB dongle lock and make my app to read connection string from the lock.
But I don't know how to pass the string to ado.net and the connection string placed on app.config.(I'm using ado.net)The following code is my connection string tag:
<connectionStrings><add name="Db_ReceptionEntities1" connectionString="metadata=res://*/Model.DBReception.csdl|res://*/Model.DBReception.ssdl|res://*/Model.DBReception.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=Db_Reception;user id=sa;password=******;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings>
How to put string as connection string to app.config?
You do not need to read from the dongle and put it into app.config. You can just read from the dongle and give the connection string to your context.
Your connection string looks like an EF database first connection string. The DbContext class has a constructor which accepts a connection string name or a full connection string. You can use that and pass the connection string to it.
Create your context like this:
public class StackContext : DbContext
{
public StackContext(string connection) : base(connection)
{
}
}
Then read the connection string from the dongle and pass it to your context like this:
// read from dongle
var connectionString = ...;
var ctx = new StackContext(connectionString);
this helped:
public Db_ReceptionEntities1(string x)
: base("name=Db_ReceptionEntities1")
{
Database.Connection.ConnectionString = x;
}
Related
I am writing an application on WPF (MVVM) using the Entity Framework (DataBase first). I want users to set the server name through interface, tell me how to do it please. If I pass the variable from the settings, I get a: System.ArgumentException keyword not supported 'data source'.
using (var db = new PronetsDataBaseEntities(Properties.Settings.Default.ConnectionString)) { ...}
The ConnectionString is the same as it generated EntityFramework
(metadata=res://*/Data.PronetsDB.csdl|res://*/Data.PronetsDB.ssdl|res://*/Data.PronetsDB.msl;provider=System.Data.SqlClient;provider connection string="data source=DESKTOP-D6JRGFG\SQLEXPRESS;initial catalog=PronetsDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework")
Constructor on Entity:
public PronetsDataBaseEntities(string connectionString)
: base(connectionString)
{
}
The connection string must only be the part after "provider connection string=", so in your case: "data source=DESKTOP-D6JRGFG\SQLEXPRESS;initial catalog=PronetsDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"
I have an app that the connection string changes by per user and machine. that said I have made a test connection string just to get it testing. Then once that is working I will add the dynamic connection string.
After some research I have figured out that there is a problem with the connection string.
If someone could please tell me where I am wrong I would appreciate it.
var s = #"metadata=res://*/ProcurementModel.csdl|res://*/ProcurementModel.ssdl|
res://*/ProcurementModel.msl;provider=System.Data.SqlClient;
provider connection string=&';data source=JAMES-DESKTOP\SQLEXPRESS;initial catalog=MyDatabase;persist security info=True;user id=User;password=*****;MultipleActiveResultSets=True;App=EntityFramework&';";
Update:
public ProcurementContext()
{
var s =
#"metadata=res://*/ProcurementModel.csdl|res://*/ProcurementModel.ssdl|
res://*/ProcurementModel.msl;provider=System.Data.SqlClient;
provider connection string=&';data source=JAMES-DESKTOP\SQLEXPRESS;initial catalog=MyDatabase;persist security info=True;user id=jd;password=P#ssw0rd;MultipleActiveResultSets=True;App=EntityFramework&';";
_connectionString = s;
}
Getting data:
public List<Procurement> ParcelListByUser(string userName)
{
using (var context = new ProcurementEntities(_connectionString))
{
return context.Procurements.Where(p => p.UserName == userName).ToList();
}
}
Constructor:
public ProcurementEntities(string connectionString)
: base(connectionString)
{
}
Error message:
Format of the initialization string does not conform to specification
starting at index 165.
Configuration:
The configuration of the Procurement
public class ProcurementConfiguration:DbConfiguration
{
public ProcurementConfiguration()
{
SetExecutionStrategy("System.Data.SqlClient", () => new SqlAzureExecutionStrategy());
SetDefaultConnectionFactory(new SqlConnectionFactory(ConnectionStrings.LocalConnectionString));
}
}
I think the issue is in your connection string. I've made the same thing and I have a function to create the connection string in an automatic way.
The code:
public static string GetConnectionString()
{
// Build the provider connection string with configurable settings
string cn = "server=" + mdlImpostazioni.p.dbServer;
cn += ";database=" + mdlImpostazioni.p.dbName;
cn += ";uid=" + mdlImpostazioni.p.dbUser;
cn += ";pwd=" + mdlImpostazioni.p.dbPassword + ";";
var providerSB = new SqlConnectionStringBuilder(cn);
var efConnection = new EntityConnectionStringBuilder();
// or the config file based connection without provider connection string
efConnection.Provider = "System.Data.SqlClient";
efConnection.ProviderConnectionString = providerSB.ConnectionString;
// based on whether you choose to supply the app.config connection string to the constructor
efConnection.Metadata = #"res://*"; //-----> very important
return efConnection.ToString();
}
In this way, I pass the return value to my db context constructor, like in your code. My constructor is:
public partial class Entities : DbContext
{
public Entities(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
public void Close()
{
this.Dispose();
}
}
Try it and ask if you have some problem.
One way to change your connection string dynamically is to only change entity framework underlying connection's connection string. Something like this:
myDbContext.Database.Connection.ConnectionString = "Data source=JAMES-DESKTOP\SQLEXPRESS;initial catalog=MyDatabase;persist security info=True;user id=DynamicUser;password=DynamicPassword;MultipleActiveResultSets=True;App=EntityFrameworkForUser";
This way, your application does not have to hardcode tokens related to entity framework (i.e. metadata).
I need to set my Entity Framework connection string at runtime. Right now, I have the following:
string connectionString = "metadata=res://*/DataModels.CustomerDataModel.csdl|res://*/DataModels.CustomerDataModel.ssdl|res://*/DataModels.CustomerDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=tcp:{serverName},{portNumber};initial catalog={databaseName};user id={username};multipleactiveresultsets=True;application name=EntityFramework"";
using (CustomerEntities entities = new CustomerEntities(connectionString))
{
CustomerEntity entity = new CustomerEntity();
// do more
entities.CustomerEntities.Add(entity);
entities.SaveChanges();
}
When I execute the code above (with the {parameter} values replaced), I get the following error:
Keyword not supported: 'data source'.
What am I doing wrong?
Change this.
string connectionString = "metadata=res://*/DataModels.CustomerDataModel.csdl|res://*/DataModels.CustomerDataModel.ssdl|res://*/DataModels.CustomerDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=tcp:{serverName},{portNumber};initial catalog={databaseName};user id={username};multipleactiveresultsets=True;application name=EntityFramework"";
To this (note how i escaped the " character as "" )
string connectionString = #"metadata=res://*/DataModels.CustomerDataModel.csdl|res://*/DataModels.CustomerDataModel.ssdl|res://*/DataModels.CustomerDataModel.msl;provider=System.Data.SqlClient;provider connection string= ""data source=tcp:{serverName},{portNumber};initial catalog={databaseName};user id={username};multipleactiveresultsets=True;application name=EntityFramework""";
I know this was asked 10 months ago, but I found an easier way to specify the connectionString:
If your config file has it as:
<connectionStrings>
<add name="CustomerDataModel" connectionString="metadata=res://*/EntityFramework.CustomerDataModel.csdl|res://*/EntityFramework.CustomerDataModel.ssdl|res://*/EntityFramework.CustomerDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\CustomerDataModel;initial catalog=CustomerDB;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
You can specify it as -
public const string ConnectionString = #"name=CustomerDataModel";
..
CustomerDBContext context = new CustomerDBContext(ConnectionString );
No need to worry about quotes. Lot cleaner.
It is easier to use EntityConnectionStringBuilder and SqlConnectionStringBuilder to change parameters as you want.
set multiple connection strings in your web.config, and follow below:
public partial class MyDatabaseEntities
{
public MyDatabaseEntities(string connection)
: base(connection)
{
}
}
and then wherever you want to create instance of entities, pass connection string name in parameter:
MyDatabaseEntities entities = new MyDatabaseEntities("CONNECTION_STRING_NAME");
I hope this will help.
Thanks
I already have a connection string in my config file
<connectionStrings>
<add
name="ConnectionString"
connectionString="Data Source=*;Initial Catalog=*;User ID=*;Password=*"
providerName=".NET Framework Data Provider for SQL Server" />
Currently I am just adding another connection string in my .cs file:
SqlConnection myConnection =
new SqlConnection("user id=*;password=*;server=localhost;");
I want to use config file string to connect to a database in the .cs file without adding another string. How can I do that?
using (SqlConnection cn =
new SqlConnection(
ConfigurationManager.ConnectionStrings["MyDbConn"].ToString()))
This was the code I found, is there any shorter way?
Using ConnectionStrings property of System.Web.Configuration.WebConfigurationManager to get connection string in config file
Not really, but you could wrap it in its own little helper function:
private static string GetConnectionString(string name)
{
return WebConfigurationManager.ConnectionStrings[name].ConnectionString;
}
using (var cn = new SqlConnection(GetConnectionString("MyDbConn"))) { ... }
Just use System.Configuration.ConfigurationManager.ConnectionStrings to get access to the connection string defined in your config file.
var myconnectionString = System.Configuration.ConfigurationManager
.ConnectionStrings["ConnectionString"].ConnectionString;
You can create a static helper class, named Config or something similar and give it a property ConnectionString, that will return the long "WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString" thing. That is the approach I usually go with in my projects and it's actually very easy to use.
public static class Config
{
public static string ConnectionString
{
get
{
return WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
}
}
}
This approach is the most useful when more classes need to acccess the connection string and this way you have a centralized access to it and easy to change solution.
While using the Entity Framework I have split it out to it's own project:
RivWorks.Model - Contains Entity Model
RivWorks.Controller - Uses the Entity Model and contains the biz rules
RivWorks.View.Web - The web site
RivWorks.View.Services - WCF project
Everything in the web site is working fine. I am able to call into the Controller and get a valid Model back. When I try the same thing from the Web.Service I am getting this error:
ERROR:
The underlying provider failed on ConnectionString.
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 RivWorks.Model.Entities.RivFeedsEntities1..ctor(String connectionString)
at RivWorks.Model.FeedStoreReadOnly..ctor(String connectionString)
at RivWorks.Controller.ProductManager.LookupProduct(String productID, String sku, String urlRef, String env, String logPath)
I am a bit confused as to why and digging through the error logs I finally figured out the connection strings were not being read from the Web Site's config file. So, I added some code to catch that and, for now, hard coded the values in. Like:
public dataObjects.NegotiateSetup LookupProduct(string productID, string sku, string urlRef, string env, string logPath)
{
string feedConnString = "";
string rivConnString = "";
log.InitializeLogFile(logPath);
dataObjects.NegotiateSetup resultSet = new dataObjects.NegotiateSetup();
try { feedConnString = AppSettings.FeedAutosEntities_connString; }
catch { feedConnString = #"metadata=res://*/Entities.FeedEntities.csdl|res://*/Entities.FeedEntities.ssdl|res://*/Entities.FeedEntities.msl;provider=System.Data.SqlClient;provider connection string='Data Source=***.***.***.***;Initial Catalog=******;Persist Security Info=True;User ID=******;Password="******";MultipleActiveResultSets=True'"; }
try { rivConnString = AppSettings.RivWorkEntities_connString; }
catch { rivConnString = #"metadata=res://*/Entities.RivEntities.csdl|res://*/Entities.RivEntities.ssdl|res://*/Entities.RivEntities.msl;provider=System.Data.SqlClient;provider connection string='Data Source=******;Initial Catalog=******_Dev;Persist Security Info=True;User ID=******;Password="******";MultipleActiveResultSets=True'"; }
try
{
using (RivFeedsEntities1 _dbFeed = new FeedStoreReadOnly(feedConnString).ReadOnlyEntities())
{
using (RivEntities _dbRiv = new RivWorksStore(rivConnString).NegotiationEntities())
{
But, alas, it is still giving me the above error! Any ideas why?
I know you've been mucking around with your connection strings to sanitize them but I'm guessing you didn't put the "'s around the password in?
Are they actually required?
Double check your connection string is correct, little typo's can cause this same error.
This is wrong:
<add name="Entities" connectionString="metadata=res://*/OnlineAB.csdl|res://*/OnlineAB.ssdl|res://*/OnlineABSuperAdmin.msl;provider=System.Data.SqlClient;provider connection string="data source.;initial catalog=
This is right:
<add name="Entities" connectionString="metadata=res://*/OnlineAB.csdl|res://*/OnlineAB.ssdl|res://*/OnlineABSuperAdmin.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=
See after the DataSource I was missing an equal sign.