Mock Umbraco configuration in test project - c#

When running unit tests on code using some Umbraco Core extensions, such as string.ToUrlSegement(), the following error is thrown:
System.Configuration.ConfigurationErrorsException: Could not load the Umbraco.Core.Configuration.UmbracoSettings.IUmbracoSettingsSection from config file, ensure the web.config and umbracoSettings.config files are formatted correctly
How do you prevent this happening?

Beside copying all Umbraco settings into your test projects app.config, you can add the following configuration:
<configSections>
<sectionGroup name="umbracoConfiguration">
<section name="settings" type="Umbraco.Core.Configuration.UmbracoSettings.UmbracoSettingsSection, Umbraco.Core" requirePermission="false" />
</sectionGroup>
</configSections>
This prevents that exception being thrown when using Umbraco core functions dependent on configuration of a main project.
Discovered this and some other great tips here.

Related

No connection string could be found in the App.config file

Visual Studio Solution:
(Project 1) I have a ASP .NET Framework API project that uses Entity Framework to access to Database.
(Project 2) Now I created NUnit project that is calling methods of project 1. Some of project1's methods are calling EF methods, so:
I added nuget package of Entity framework to project 2
I created an App.config file in project 2
But after executing test methods I get:
Test method Test.SchedulerTesting.TestMethod5 threw exception:
System.InvalidOperationException: No connection string named
'MyEntities1' could be found in the application config
file.
My app.config (project 2) content:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="MyEntities1" connectionString="provider=System.Data.SqlClient;provider connection string="data source=**********;initial catalog=******;user id=sa;password=**********;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
My Model.Context.cs (project 1) first lines:
public partial class MyEntities1: DbContext
{
public MyEntities1()
: base("name=MyEntities1")
{
}
//...
}
An app.config file applies when your production application is running. When running tests under a test runner, you need to set up a config for use with your tests. It will usually contain the same stuff as your production config.
In your case, you need a config file named something like project2.dll.config in order for the configuration to be made available to your tests. Visual Studio will not automatically rename an App.config for you because it doesn't know you want to use NUnit.
Funny thing, the first blog post I ever wrote (2005) talks about this and has many more details: http://charliepoole.org/technical/how-nunit-finds-config-files.html

Allowing Class Library to use App.config from UI Project

I recently decoupled my UI layer from my Models and Service layer by splitting them into separate projects. Now I get the following error upon compiling my solution:
System.Configuration.ConfigurationErrorsException: 'An error occurred creating the configuration section handler
for IOLegend: Could not load file or assembly 'Laborare.Core' or one of its dependencies.
The system cannot find the file specified.'
In my class library, I use ConfigurationManager to read application configuration settings such as:
var IoLegendConfig = (IOLegendConfig)ConfigurationManager.GetSection("IOLegend");
var Rs232Config = (RS232ConnectionConfig)ConfigurationManager.GetSection("RS232Connection");
public static string _Metric_Setting = ConfigurationManager.AppSettings["metric_setting"];
Here is my configSections in the app.config:
<configSections>
<section name="TCPConnection"
type="Laborare.Core.Configuration.TCPConnectionConfig, Laborare.Core"/>
<section name="RS232Connection"
type="Laborare.Core.Configuration.RS232ConnectionConfig, Laborare.Core"/>
<section name="IOLegend"
type="Laborare.Core.Configuration.IOLegendConfig, Laborare.Core" />
</configSections>
The app.config is located in my UI project. What is the problem here? Am I not correctly directing the ConfigurationManager in my class library? I seem to be using the correct namespaces. Any help would be greatly appreciated.
Here is a picture of my current solution structure.

Code First can't enable migrations

I'm trying to enable migrations but it's throwing an exception:
Checking if the context targets an existing database...
System.TypeInitializationException: The type initializer for 'System.Data.Entity.Migrations.DbMigrationsConfiguration`1' threw an exception. ---> System.TypeInitializationException: The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception. ---> System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize ---> System.Configuration.ConfigurationErrorsException: The 'name' attribute must be specified on the 'section' tag.
I'm assuming that the App.config file is not correctly set up (it was automatically set up when I added EF package). All I did was add the connection string:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section Name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
<connectionStrings>
<add Name="MyContext" connectionString="data source=MYSERVER;initial catalog=CodeFirstTest;user id=***;password=***;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
I'm using SQL Server 2008 R2.
As I do have a connection string, I don't believe I need the defaultconnectionfactory. Am I correct? (Note: Even without this section I'm still getting the same exception)
What else am I missing?
I had the same issue when my <connectionString /> entry is on top part of the Web.config, Right after <configuration>. Then I tried moving it right before </configuration>, and it worked.
This is mainly to do with the config file. So the actual stack trace that helps is "System.Configuration.ConfigurationErrorsException".
There can be many reasons but they all majorly include the correction in the config file as answered earlier.
Couple of possibilities which are little different than this are given below (But the stack really tells us)
One possible out of the way reason can be that, your project where the migrations are getting enabled can be different from the startup project. So be sure to add -StartUpProject to your nuget commmand.
Version of the entity framework used can be different in case of two different projects.
I met with the same issue. My problem is that there are double connection string on the Web.config file. like as below:
<add name="DB1234" ..../>
<add name="DB1234" ..../>
So we have to check our web.config file first!
Good Luck!
check the spelling of your 'connectionString' and make sure it is 'connectionStrings' I omitted the 's' before in my own case.
After adding the 's', that solved it.
In my case I had several projects in the solution and another project was set as the StartUp project. Setting the project that I was trying to enable migrations for as the StartUp project resolved it.
In my case, using DevExpress MVC generated template, it need to add extra lines after <sectionGroup name="devExpress">...<sectionGroup/> in web.config
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
in my experiences, for example is that all the information that is used to establish a connection with the database is the one that comes from the config file that is in the startup-project, and not the one that is in the project where i am generating or using the enable-migrations or update-database instructions, example i have project PRINCIPAL and another project DATA,i use the DATA project as my default-project only when running the packages in Packager console Manager, but the config file that really use is the one in PRINCIPAL.
Include this into <configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
In my case this line is omitted when I have 2 instances of Visual Studio open.
Close all instances of the Visual Studio, open and reinstall EF via interface Nuget or Console to avoid this error
Check the webconfig, For example: I had the app settings like this:
<configuration>
<appSettings>
<add key="dhx_license" value="value"/>
</appSetting>
.....
and threw that error. But then I realized appSetting was duplicated below so I moved the and the error vanished. Thanks.
Like #Lester answer check web config. It must look like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
...
</configSections>
<appSettings>
...
</appSettings>
...
<configuration>
I had the same issue. But I found there are two <connectionString /> in my Web.config,
I had to remove one connection string and it work fine for me.

NService bus and the GAC

I have recently tried to migrate the NServiceBus libraries to the GAC as they are pretty big and are required in nearly all of my software. I am using the newest .NET 4.0 Build (2.0.0.1219) and have used GACUTIL to copy NServiceBus & NServiceBus.Core into the new GAC and log4net into the old 2.0 GAC. I have managed to get log4net working by wiring in the version and PublicKeyToken but I cannot get the NServiceBus.Core working. Every time I start a piece of software I get the following error:
"Type NServiceBus.Unicast.Transport.CompletionMessage was not registered in the serializer. Check that it appears in the list of configured assemblies/types to scan."
When I copy the DLL NServiceBus.Core to the local folder it works fine.
my config looks like this:
<configSections>
<section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core, Version=2.0.0.1219, Culture=neutral, PublicKeyToken=9fc386479f8a226c" />
<section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core, Version=2.0.0.1219, Culture=neutral, PublicKeyToken=9fc386479f8a226c" />
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" />
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, NServiceBus.Core, Version=2.0.0.1219, Culture=neutral, PublicKeyToken=9fc386479f8a226c"/>
</sectionGroup>
So i'm wondering has anyone else got NServiceBus successfully working with the GAC?
Cheers
It is an issue with NServiceBus stripping strong names. Use the <runtime> element in web.config:
<runtime>
<qualifyAssembly partialName="MessagesDll" fullName="MessagesDll, Version=1.0.0.0, Culture=neutral, PublicKeyToken=4d476a51357cea5c" />
NServiceBus scans the assemblies in a directory (the run directory for an application, the website's compiled directory for a web application) in order to load all the message handlers, and that means it needs to scan itself as well for all the types it needs for dependency injection.
I'm not sure that this model supports assemblies living in the GAC by default, although if you're configuring NServiceBus yourself, you can specify the assemblies to load yourself through the NServiceBus.Configure.With(params Assembly[] assemblies) overload, just make sure to include all the NServiceBus assemblies and Log4Net at the very least.
However, I would contend that GAC-ing the NSB assemblies might not be the best idea. Each endpoint having its own copy of the assembly reinforces the autonomy of the endpoints, and will make it much easier if you ever need to upgrade to a new version of NServiceBus, since you would be able to test each endpoint individually and not just put a new assembly in the GAC, add a binding redirect, and hope everything continues to run fine.

How do I reference configuration information from within multiple class libraries?

I've got a bunch of DLL projects that I'm pulling into my application, each contains their own Settings.settings/app.config. When I compile the app and run for debugging, everything works just fine, but come deployment time I can't get my DLLs to read their own settings files.
I've been doing some reading and it has become apparent that there's a couple of methods to getting each dll to read its own configuration - one is to dedicate a .dll.config to the library and the other is to embed the dll's configuration in the process.exe.config.
I'm having significant issues trying to implement either and I wondered if anyone has any good docs on this - there appears to be a shortage on the Net.
I'd like a separate .dll.config for each of the libraries if possible, but in a pinch, getting each of my libraries to read their own section of the process.exe.config will do.
Can anyone point me in the right direction because I'm so close to rolling this application out but this stumbling block is causing me a significant headache.
Edit: When I merge the configuration files, I start getting TypeInitializer exceptions when I initialize objects withing my libraries. This is likely just me being retarded, but does someone have a working example of a merged config file and some basic demonstrative code for reading it from multiple assemblies?
What are the "significant issues" you encountered? I started with embedding the dll's config in the exe's config, which worked, but was cumbersome. I now have all the config stuff in one dll project. The only thing I needed to do to make that work (besides copying the settings over) was to change the Settings class to be public.
Here's an example of a merged app.config that works:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="SharedConfig.Client.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- Begin copy from library app.config -->
<section name="SharedConfig.Library.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- End copy from library app.config -->
</sectionGroup>
</configSections>
<applicationSettings>
<SharedConfig.Client.Properties.Settings>
<setting name="Bar" serializeAs="String">
<value>BarFromClient</value>
</setting>
</SharedConfig.Client.Properties.Settings>
<!-- Begin copy from library app.config -->
<SharedConfig.Library.Properties.Settings>
<setting name="Bar" serializeAs="String">
<value>BarFromLibrary</value>
</setting>
</SharedConfig.Library.Properties.Settings>
<!-- End copy from library app.config -->
</applicationSettings>
</configuration>
Have each class library define configuration settings in a custom ConfigurationSection.
Then add custom section handlers to your process.exe.config file.
This MSDN article is pretty comprehensive in its explanation, with examples in both VB and C#.
See If app.config for a DLL should be in the "main config"… what do we do with WCF References in DLLs?. The real answer is "copy and paste". That's unfortunately the general solution Microsoft had in mind. In some cases, the .NET 2.0 Settings mechanism can be used, as it bakes the default values into the DLL itself. At runtime, the DLL can then save updated settings - into the .exe.config.

Categories