I'm getting the following error when running my application:
An attempt to attach an auto-named database for file
C:\Users\Bryan\Documents\Visual Studio
2015\Projects\app\app.UI\App_Data\aspnetdb.mdf failed. A database with
the same name exists, or specified file cannot be opened, or it is
located on UNC share.
Here is my connection string:
<connectionStrings>
<add name="SoundyDB" connectionString="data source=BRYAN\SQLEXPRESS;initial catalog=MusicKarma;User id = BRYAN\bryan; password=; MultipleActiveResultSets=True;App=Soundy" providerName="System.Data.SqlClient" />
</connectionStrings>
I want to use SQL-server and my Database MusicKarma.
When I debug my application and inspect the connectionString-variable, It has the following value:
connectionString = "data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
I'm setting the connectionString variable this way:
public UserStore(string connectionString)
{
if (string.IsNullOrWhiteSpace(connectionString))
{
throw new ArgumentException("Connectionstring");
}
this.connectionString = connectionString;
}
public UserStore()
{
this.connectionString = ConfigurationManager.ConnectionStrings[0].ConnectionString;
}
You need to replace userStore method with the following:
public UserStore()
{
this.connectionString = ConfigurationManager.ConnectionStrings["SoundyDB"].ConnectionString;
}
Related
Need to have log4net configuring with sql in my project , but due to security reasons must not have the connection string details on the web.config . What are the alternatives ? Just need to hide the ConnectionString only .
{
var settings = ConfigurationManager.ConnectionStrings[1];
var fi = typeof(ConfigurationElement).GetField("_bReadOnly",
BindingFlags.Instance | BindingFlags.NonPublic);
fi.SetValue(settings, false);
string connection = GetConnection();//To get the connection
details using a service
settings.ConnectionString = connection;
}
This is not solving my issue , hiding the connection string
details . The connection details to be pass to the web.config to consume the log.net sql logging
Finally, the one which helped me to pass the connection information to ado.net appender
public static class LogConfigurator
{
public static void SetConnectionString(string connectionString)
{
Hierarchy logHierarchy = log4net.LogManager.GetRepository() as
Hierarchy;
if (logHierarchy == null)
{
throw new InvalidOperationException
("Can't set connection string as hierarchy is null.");
}
var appender = logHierarchy.GetAppenders()
.OfType<AdoNetAppender>()
.SingleOrDefault();
if (appender == null)
{
throw new InvalidOperationException
("Can't locate a database appender");
}
appender.ConnectionString = connectionString; // Using a service to get
//the connection information
appender.ActivateOptions();
}
}
web.config , give the same name for ado.net appender to take the connection
<connectionStringName value="ConnectionString" />
<connectionStrings>
<add name="ConnectionString" connectionString=""
providerName="System.Data.SqlClient" />
</connectionStrings>
You could store the connection string in a separate file which you can keep out of source control to avoid exposing the credentials. Add the following to your Web.config file:
<configuration>
<connectionStrings configSource="connections.secret.config" />
</configuration>
Then create a connections.secret.config file, but keep it away from your solution:
<connectionStrings>
<add name="connection_name" connectionString="your_connection" providerName="System.Data.SqlClient" />
</connectionStrings>
You will need to make sure you provide the connection string wherever you end up deploying your code using an environment variable or similar.
I'm using a WinForm form created with C # to connect to a Sql server database.
To connect to the database the user must provide a login and a password.
I use the configuration file App.config to store the connectionString as following :
<ConnectionStrings>
<Add name = "K1" connectionString = "Data Source = HP; Initial Catalog = TRVANALYT; User ID = {0}; Password = {1}
ProviderName = "System.Data.SqlClient" />
</ ConnectionStrings>
The problem that is posed to me does not save a new connectionString.
to refresh connextionString K1 I must rebuild the program and it gives the right result
If you have suggestions
What's the best practice?
thank you very much
My Code :
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
string connexionstring = ConfigurationManager.ConnectionStrings["K1"].ToString();
var connectionStringsSection = (ConnectionStringsSection) config.GetSection("connectionStrings");
string NewConnexionstring = string.Format(connexionstring, txtUser.Text, txtPwd.Text);
connectionStringsSection.ConnectionStrings["K1"].ConnectionString = NewConnexionstring; //Set new connectionString with user and password
connectionStringsSection.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Full);
ConfigurationManager.RefreshSection("connectionStrings");
App.config
<configSections>
</configSections>
<connectionStrings>
<add name="K1" connectionString="Data Source=HP;Initial Catalog=TRVANALYT;User ID={0};Password={1}" providerName="System.Data.SqlClient" />
</connectionStrings>
I have the same problem, but when I debug, I realize that the ConnectionString was saved, but when I create a new object, the Connectionstring of this is false.
I fix that by this way:
In the Entity.Context.cs file (In my case is QuanLySieuThi.Context.cs) you will see a partial class. You should add a new constructor with a Connectionstring parameter in this class:
Code
public partial class QuanLySieuThiEntities : DbContext
{
//This is the default constructor
public QuanLySieuThiEntities()
: base("name=QuanLySieuThiEntities")
{
}
//Add this constructor
public QuanLySieuThiEntities(String connString)
: base(connString)
{
}
}
Last, when you init a new object, you should use the new constructor with the connectionstring you need:
Code
string _conString = System.Configuration.ConfigurationManager.ConnectionStrings["QuanLySieuThiEntities"].ConnectionString;
QuanLySieuThiEntities newObject = new QuanLySieuThiEntities(_conString);
Here is my Connection.cs:
public class Connection
{
public static string connectionstr = ConfigurationManager.ConnectionStrings["connectionstr"].ToString();
public static OleDbConnection DBconnection()
{
//
// TODO: Add constructor logic here
//
OleDbConnection con = new OleDbConnection(connectionstr);
if (con.State == ConnectionState.Open)
con.Close();
con.Open();
return con;
}
}
when i enter input values and submit, it shows error something like this,
This is the error:
System.Data.OleDb.OleDbException`: Could not find installable ISAM
I'm new to .NET framework and I just created login.aspx, so I don't have add any source code.
My connection string is
<connectionStrings>
<add name="connectionstr" connectionString="Provider=Microsoft.Jet.OleDb.4.0;Data Source=|DataDirectory|\registration.mdb;User Instance=true" providerName="System.Data.OleDb" />
</connectionStrings>
Your connection string includes the argument
;User Instance=true
which does not apply to the Access OLEDB providers (Microsoft.Jet.OLEDB.4.0 and Microsoft.ACE.OLEDB.12.0).
When I included that argument I got the "Could not find installable ISAM" error like you did. When I removed that argument the error went away.
I want to make DB connection using constructor
DbContext(string nameOrConnectionString)
but i dont want to do it using application config file. like this
line in config file
<add name="DBEntities" connectionString="metadata=res://*/DB.csdl|
res://*/DB.ssdl|res://*/DB.msl;provider=System.Data.SqlClient;
provider connection string="data source=SERVER;
initialcatalog=DB;persist security info=True;
user id=XXX;password=YYY;MultipleActiveResultSets=True;
App=EntityFramework"" providerName="System.Data.EntityClient" />
and line in code
public DBEntities() : base("name=DBEntities"){}
instate i want something like this directly in code
public DBEntities() : base("connectionString=metadata=
res://*/DB.csdl|res://*/DB.ssdl|res://*/DB.msl;
provider=System.Data.SqlClient;provider connection string="
data source=SERVER;initial catalog=DB;
persist security info=True;
userid=XXX;password=YYY;MultipleActiveResultSets=True;
App=EntityFramework""){}
if I try so, I have the 'System.ArgumentException': Keyword not supported: 'connectionstring'.
It is possible? How to do what i want?
The problem seems to be twofold:
You have included the attribute name connectionString in the connection string
The " needs to be replaced with '
The correct code should then become:
public DBEntities()
: base("metadata=res://*/DB.csdl|res://*/DB.ssdl|res://*/DB.msl;provider=System.Data.SqlClient;provider connection string='data source=SERVER;initial catalog=DB;persist security info=True;userid=XXX;password=YYY;MultipleActiveResultSets=True;App=EntityFramework'")
{}
You can look here for more details of the elements a connection string consists of, and here for more details on Entity Framework connection string.
Old anwers, for reference:
The problem seems to be that you are including everything the web.config uses to define a connection string. The connection string is itself only what is contained between the quotation marks after the attribute connectionString, in your case data source=SERVER;initial catalog=DB;persist security info=True;userid=XXX;password=YYY;MultipleActiveResultSets=True;App=EntityFramework.
Try this instead:
public DBEntities() : base("data source=SERVER;initial catalog=DB;
persist security info=True;
userid=XXX;password=YYY;MultipleActiveResultSets=True;
App=EntityFramework"){}
Also, you can look here for more details of the elements a connection string consists of.
In your Model.Context.tt, add the following under the constructor;
public <#=code.Escape(container)#>(string connStr)
: base(connStr)
{
<#
if (!loader.IsLazyLoadingEnabled(container))
{
#>
this.Configuration.LazyLoadingEnabled = false;
<#
}
foreach (var entitySet in container.BaseEntitySets.OfType<EntitySet>())
{
// Note: the DbSet members are defined below such that the getter and
// setter always have the same accessibility as the DbSet definition
if (Accessibility.ForReadOnlyProperty(entitySet) != "public")
{
#>
<#=codeStringGenerator.DbSetInitializer(entitySet)#>
<#
}
}
#>
}
After rebuilding, you will now have a second constructor taking a string argument connStr;
public DBEntities() : base("name=DBEntities"){}
public DBEntities(string connStr) : base(connStr){}
You can now create your own connection string in your code and pass it to the constructor. Example;
public string connStr = "your connection string";
using (var db = new DBEntities(connStr))
{
//do things with db
}
The problem is with your connection string passed to constructor.
try this instead :
private const string _connectionString = #"data source=SERVER;initial catalog=DB;persist security info=True;user id=XXX;password=YYY;MultipleActiveResultSets=True";
public DBEntities() : base(_connectionString)
{
}
I am trying to setup a valid connection string for my database so that my WebSecurity.InitializeDatabaseConnection method can point to my database.
Here's my connection string:
<add name="Database_Entities1" connectionString="metadata=res://*/Models.DAL.Entities.MTG_Model.csdl|res://*/Models.DAL.Entities.MTG_Model.ssdl|res://*/Models.DAL.Entities.MTG_Model.msl;provider=System.Data.SqlClient;provider connection string="data source=**.**.***.***;initial catalog=Model_Name;persist security info=True;user id=*****;password=*********;multipleactiveresultsets=True;application name=EntityFramework;Pooling=True;Max Pool Size=1000"" providerName="System.Data.EntityClient" />
The problem here is the provider name which is System.Data.EntityClient. I actually need it to point toward System.Data.SqlClient, but when I try to copy/paste the connection string and replace the System.Data.EntityClient with the other provider name, I get such crash like Keyword not supported: 'metadata'..
So my understanding is that calling my method like this:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
{
private static SimpleMembershipInitializer _initializer;
private static object _initializerLock = new object();
private static bool _isInitialized;
public override void OnActionExecuting(ActionExecutingContext _filterContext)
{
// Ensure ASP.NET Simple Membership is initialized only once per app start
LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
}
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<Database_Entities1>(null);
try
{
using (var context = new Database_Entities1())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("Database_Entities2", "UserProfile", "UserId", "UserName", true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
}
}
Where Database_Entities2 is:
<add name="Database_Entities2" connectionString="metadata=res://*/Models.DAL.Entities.MTG_Model.csdl|res://*/Models.DAL.Entities.MTG_Model.ssdl|res://*/Models.DAL.Entities.MTG_Model.msl;provider=System.Data.SqlClient;provider connection string="data source=**.**.***.***;initial catalog=Model_Name;persist security info=True;user id=*****;password=*********;multipleactiveresultsets=True;application name=EntityFramework;Pooling=True;Max Pool Size=1000"" providerName="System.Data.SqlClient" />
Does not work because an SqlClient connection string does not work that way. Can anyone help me achive what I'm trying to do? Thanks a lot!
EDIT
Two additionnal piece of information: I have this connection string:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MyApp-20130829080410;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-MyApp-20130829080410.mdf" providerName="System.Data.SqlClient" />
Which was working; however, as you can see, it does not point toward my database, so if I try to retrieve any users in the table "UserProfile", it is not possible since the table was created in the local database (which I don't know why I have), and not in the main one (Database_Entities1), hence this question.
The SimpleMembershipProvider expects a normal connection string, not an entity framework connection string. You need to define a separate connection string that points to the same database as your entity framework connection string and use that:
<add name="MembershipDB"
connectionString="Data Source=**.**.***.***;Initial Catalog=Model_Name;[...]"
providerName="System.Data.SqlClient" />
If you use Entity Framework the connection string would be created by the IDE. And from your description i guess you created that connection string by your own, not via IDE.
So the IDE would place something like this in your app.config:
<add name="libraryEntities1" connectionString="metadata=res://*/privlibDBmodel.csdl|res://*/privlibDBmodel.ssdl|res://*/privlibDBmodel.msl;provider=System.Data.SqlClient;provider connection string="data source=[yourserver];initial catalog=library;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
To create the connection in your program you could use this:
libraryEntities1 dbconn = new libraryEnitits1();
Now you could handle the connections via dbcon object.