I have my login page, and 2 separate modules other then my login page. After login, it sends you to the login page with the links unhidden. The links only become available after your role has been confirmed. My question is how do I link my 2 separate webconfigs to my separate modules. I was told I could do this straight on the webconfig file without adding the Page_Load event in C#. If that’s true can I get an example? Thank you!
Maybe you should adds two connection string declare in web.config. Because Web.Config not unalterable in runtime. Choose connection string as need.
<connectionStrings>
<add name="dbConnectionString1" connectionString=""/>
<add name="dbConnectionString2" connectionString=""/>
</connectionStrings>
Or get the connection string from different database. You create function to get connection string method. Function get connection string as need. Or return static connection string. For example:
public string GetConnectionString()
{
if ()
return "connectionstring1";
else
return "connectionstring2";
}
Related
I'm an Entity Framework newbie who is trying to develop some simple add-on to Sitefinity CMS on top of MySql database.
The database is working perfectly with Sitefinity itself; however, when my own EF code trying to connect with it, I always got the error:
Cannot open database "MyDatabase" requested by the login. The login failed. Login failed for user 'IIS APPPOOL\myApp'.
The connection string I'm using is:
<add connectionString="Server=localhost;Uid=MyUserId;Pwd=MyPassword;Database=dev_MyDatabase;CharacterSet=utf8" providerName="System.Data.SqlClient" dbType="MySQL" name="MyDatabase" />
The user (id and password) is created in MySQL, thus, when trying putting it in IIS (Application Pools > Advanced Settings...), it says "The specified user name does not exist".
Any idea what I'm missing here?
Thanks,
Harry
I see that you are using Entity Framework.
What does your Context look like? If you have a constructor that inherits the base constructor of DbContext, you need to make sure that you pass along the correct name in the parameter. In your case, it should look like this:
public class MyContext : DbContext
{
public MyContext():
base("MyDatabase")
{
}
}
I am attempting to create a db using EF 5 Code First on SQL Server 2008. I can create the db using Integrated Security, but I cannot create the db using a custom user. The code runs the initializer on my home machine for both integrated security and custom user.
The difference in the connection strings is as follows. In addition to these I changed Data Source to Server and Initial Catalog to Database per connectionstrings.com.
<!--<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=MVCTesting;Integrated Security=False;User Id=Green;Password=******" providerName="System.Data.SqlClient" />-->
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=MVCTesting;Integrated Security=True;" providerName="System.Data.SqlClient" />
I compared the SQL users MachineName/LoginName and Green. They both have server roles of public and sysadmin, neither have any user mappings till a db is created then they are mapped to that db.
In global.asax.cs I have
protected void Application_Start()
{
Database.SetInitializer(new MVCTestingInitializer());
//Database.SetInitializer(new DropCreateDatabaseAlways<MVCTestingContext>());
ViewDb();
//Other setup
}
//Init the db by looking up a contact
private void ViewDb()
{
using (var context = new MVCTestingContext())
{
var user = context.Contacts.Where(u => u.FirstName.StartsWith("T"));
var asdf = "";
}
}
And my initializer is ...
public class MVCTestingInitializer : DropCreateDatabaseAlways<MVCTestingContext>
{
protected override sealed void Seed(MVCTestingContext context)
{
//Code to init the db
}
}
Using NLog I am able to verify if the seed is run or not. When I have integrated security it runs, when I do not the seed does not run.
I have also created an account on the machine, added that account to the AppPool and SQL Server, then retested. I still see a failure to connect.
System.Data.SqlClient.SqlException: Login failed for user 'Green'.
In a mad fit I decided to add all possible permissions to the user 'Green', I still see the above error. Does anyone see what I am missing? I am sure it is so simple and I will smack myself in the head afterwards, but I just do not see it.
If I am really far off, please provide the steps to create a SQL Account/Permissions that I can use in my web config and please include app pool setup.
Thanks,
TJ
I will post it as answer :)
If you ever have problem with connecting to db, open ssms and use the same credentials to login to db. This will confirm you have right credentials ;)
I am using the EntLib in an environment where database connection strings are retrieved from a separate library call that decrypts a proprietary config file. I have no say over this practice or the format of the config file.
I want to do EntLib exception logging to the database in this setting. I therefore need to set up a EntLib database configuration instance with the name of the database, with the connection string. Since I can't get the connection string until run time, but EntLib does allow run-time configuration, I use the following code, as described in this:
builder.ConfigureData()
.ForDatabaseNamed("Ann")
.ThatIs.ASqlDatabase()
.WithConnectionString(connectionString)
.AsDefault();
The parameter connectionString is the one I've retrieved from the separate library.
The sample code goes on to merge the created configuration info with an empty DictionaryConfigurationSource. I, however, need to merge it with the rest of the configuration code from the app.config. So I do this:
var configSource = new SystemConfigurationSource();
builder.UpdateConfigurationWithReplace(configSource);
EnterpriseLibraryContainer.Current
= EnterpriseLibraryContainer.CreateDefaultContainer(configSource);
... which is based very closely on the sample code.
But: I get an internal error in Microsoft.Practices.EnterpriseLibrary.Common.Configuration.SystemConfigurationSource.Save. The failing code is this:
var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = ConfigurationFilePath };
var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
config.Sections.Remove(section);
config.Sections.Add(section, configurationSection);
config.Save();
... where 'section' is "connectionStrings". The code fails on the Add method call, saying that you can't add a duplicate section. Inspection shows that the connectionStrings section is still there even after the Remove.
I know from experience that there's always a default entry under connectionStrings when the configuration files are actually read and interpreted, inherited from the machine.config. So perhaps you can never really remove the connectionStrings section.
That would appear to leave me out of luck, though, unless I want to modify the EntLib source, which I do not.
I could perhaps build all the configuration information for the EntLib at run time, using the fluent API. But I'd rather not. The users want their Operations staff to be able to make small changes to the logging without having to involve a developer.
So my question, in several parts: is there a nice simple workaround for this? Does it require a change to the EntLib source? Or have I missed something really simple that would do away with the problem?
I found a workaround, thanks to this post. Rather than taking the system configuration source and attempting to update it from the builder, I copy the sections I set up in app.config into the builder, and then do an UpdateConfigurationWithReplace on an empty dummy configuration source object in order to create a ConfigurationSource that can be used to create the default container.
var builder = new ConfigurationSourceBuilder();
var configSource = new SystemConfigurationSource();
CopyConfigSettings("loggingConfiguration", builder, configSource);
CopyConfigSettings("exceptionHandling", builder, configSource);
// Manually configure the database settings
builder.ConfigureData()
.ForDatabaseNamed("Ann")
.ThatIs.ASqlDatabase()
.WithConnectionString(connectionString)
.AsDefault();
// Update a dummy, empty ConfigSource object with the settings we have built up.
// Remember, this is a config settings object for the EntLib, not for the entire program.
// So it doesn't need all 24 sections or however many you can set in the app.config.
DictionaryConfigurationSource dummySource = new DictionaryConfigurationSource();
builder.UpdateConfigurationWithReplace(dummySource);
// Create the default container using our new ConfigurationSource object.
EnterpriseLibraryContainer.Current
= EnterpriseLibraryContainer.CreateDefaultContainer(dummySource);
The key is this subroutine:
/// <summary>
/// Copies a configuration section from the SystemConfigurationSource to the ConfigurationSourceBuilder.
/// </summary>
/// <param name="sectionName"></param>
/// <param name="builder"></param>
/// <param name="configSource"></param>
private static void CopyConfigSettings(string sectionName, ConfigurationSourceBuilder builder, SystemConfigurationSource configSource)
{
ConfigurationSection section = configSource.GetSection(sectionName);
builder.AddSection(sectionName, section);
}
Is there a way to pass a connection string to the DbContext constructor.
I really hate the idea of having a configuration setting in the app or web.config
When you want to reference your dll containing your EF model, you have to be aware of copying that stupid configuration, instead of having it in a central location and having the constructor access that setting, no matter where the dll goes.
Is this possible or are we forced to live with this frustration? Not every EF model lives in a web application or an exe.
Thanks
UPDATE:
I thought this error was related to a missing connection string in a config file. I'm passing a SqlConnection object and it gives me the same error. Why is this error happening?
You can use the DbContext constructor overload that takes a string which can be the connection string.
string connectionString = "metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=\"data source=localhost;initial catalog=Test;integrated security=True;multipleactiveresultsets=True;App=EntityFramework\"";
using (DbContext db = new DbContext(connectionString))
{
var m = db.Set<Main>().Take(1).First();
Console.WriteLine(m.Id);
}
I need to use the appsettings/key for my connection string in a web project, and want to re-use this for my connectionstring in the datacontext designer, but it seems all I can use there is the web.config's connectionStrings, so I have to have my DB location in 2 places in the web.config, how can I force the designer (dbml) to use the appsettings instead?
You can pass the connection string into the datacontext constructor.
So you get it from the location you like and pass it in onstructor.