ConfigurationSettings.AppSettings is empty, throws null exception - fitnesse

I have a class like this:
public class RxNormFolderMgr
{
// properties
public string RxNormFolder { get { return ConfigurationSettings.AppSettings["rootFolder"].ToString(); } }
}
When I try to use it like this:
public class TestRxNormFolderManager : ColumnFixture
{
public string RxNormFolder()
{
RxNormFolderMgr folderMgr = new RxNormFolderMgr();
return folderMgr.RxNormFolder;
}
}
I get an error: "System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object." The AllKeys property for AppSettings is an array of zero length where I am expecting length of 1.
My app.config file in the project looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="rootFolder" value ="C:\RxNorm" />
<!-- Root folder must not end with slash. -->
</appSettings>
</configuration>
I know ConfigurationSettings.AppSettings is supposed to be obsolete and I should use ConfigurationManager.AppSettings, but I can't even get that to compile. I do have a reference in the project to System.configuration (c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.configuration.dll on my machine) and using statement at top of my code.
I am using Fitnesse to test the code, and that's when I get the error. It's my understanding that I should also place a copy of the app.config file in the Bin>Debug folder of the test fixtures project which I have done. So, I don't know why I'm getting this error still.
Please, help.

Also: try using the ConfigurationManager class instead of "ConfigurationSettings":
Use a check for NOT NULL first:
public class RxNormFolderMgr
{
// properties
public string RxNormFolder
{
get
{
if(ConfigurationManager.AppSettings["rootFolder"] != null)
{
return ConfigurationManager.AppSettings["rootFolder"].ToString();
}
return string.Empty;
}
}
}
Is this inside a class library assembly? Those never use their own app.config - but instead the use the host app's app.config (the app that uses the class library).
Marc

When you are testing with FitNesse, the actual executable running is "FitServer.exe" so AppSettings is looking for a "FitServer.exe.config" in the directory with FitServer.exe lives. So a quick and dirty solution is to copy your app.config there and rename it.
A better solution is to specify the app config as described here:
http://www.syterra.com/FitnesseDotNet/ApplicationConfigurationFile.html
or if you're using fitSharp (which is an enhancement of FitNesse.NET):
http://www.syterra.com/Fit/AppConfigFiles.html

Do not put it in appsettings. Use <connectionStrings>
example:
<appSettings/>
<connectionStrings>
<add name="NORTHWNDConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NORTHWND.MDF;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
string cnstr = ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ToString();

Related

RhinoETL unable to connect to sql server

I am sure, I am missing something obvious here. I am trying to get my sample RhinoETL based app to talk to a sql server. It just would not do that. I am following the video tutorial by Paul Barriere.
using Rhino.Etl.Core.Operations;
namespace RhinoETLTest01.Operations
{
class WriteJoinedRecordsToSql : SqlBulkInsertOperation
{
public WriteJoinedRecordsToSql() : base("TestEtl", "dbo.NameAndTitle") {}
protected override void PrepareSchema()
{
Schema["Id"] = typeof(int);
Schema["FullName"] = typeof (string);
Schema["JobTitle"] = typeof (string);
}
}
}
I am able to merge data from 2 files and write them into a 3rd text file. But, I cant get the merged records to get into a sql table. What am I missing please? My App.Config has the correct connectionstring setting.
Thanks
I had a similar problem. The solution was to fully qualify the sql provider in the connection string in the App.config
<configuration>
<connectionStrings>
<add name="TestEtl"
connectionString="Data Source=TestEtl;Initial Catalog=NameAndTitle;Integrated Security=SSPI;Timeout=300;"
providerName="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</connectionStrings>
</configuration>
After that check your sql commands for correctness. I downloaded the full source and stepped through to find these and related issues.

Identity Model Claims With XML Characters Within Them

I'd like to do something like
outputIdentity.Claims.Add(new Claim("Claim1", "<test>Hi</test>"))
However the security node within the response header itself shows it as
<Attribute Name="Claim1"><AttributeValue><test>Hi</test></AttributeValue></Attribute>
I know they are reserved XML characters getting translated but can't I specify that I want that node structure in my attribute?
NOTE: I've also tried wrapping it in CDATA however it serializes that tag too. When I replace the translated characters, it works.
Serialization of security tokens is done by the SecurityTokenHandler (in your case probably the Saml11SecurityTokenHandler).
If you want to customize serialization you have to overwrite the default behaviour by extending the Saml11SecurityTokenHandler class:
class CustomHandler : Saml11SecurityTokenHandler
{
public Saml11SecurityTokenHandler()
: base()
{
}
public Saml11SecurityTokenHandler(SamlSecurityTokenRequirement samlSecurityTokenRequirement)
: base(samlSecurityTokenRequirement)
{
}
public Saml11SecurityTokenHandler(XmlNodeList customConfigElements)
: base(customConfigElements)
{
}
protected override void WriteAttribute(XmlWriter writer, SamlAttribute attribute)
{
// your code here
}
}
You also have to add your custom security token handler in the web.config file:
<securityTokenHandlers>
<add type="Your.Namespace.CustomHandler, Your.Dll.Name, Version=1.0.0.0, Culture=neutral" />
</securityTokenHandlers>
EDIT: removed <clear />
Can you try wrapping the value in CDATA section? As:
<![CDATA[<test>Hi</test>]]> Not sure whether your SecurityTokenHandler class will handle that properly, but it's worth a try, and easier than introducing custom handlers.

EntityFramework - Where is the connection string?

I've deleted the connection string from my web.config and Entity Framework is still connecting to the database! Where is the connection string being set? This is an issue because I need to make the live version of my website point to the live database.
Here's a gotcha I found with the "convention over configuration" philosophy when it comes to trying to connect to existing databases (like you're doing).
If your DbContext class (e.g. Northwind) is in a namespace (e.g. MvcProject), for some reason EF won't match the name of the class with a connection string in web.config named "Northwind" (or "MvcProject.Northwind"), and then it will just create a connection string defaulting to the local SQLEXPRESS instance, with a database called "MvcProject.Northwind". This will be an empty database. And you'll break your head trying to figure out why you're getting no data back, until you realize that you're not connected to the right DB.
The way I got around this (not elegant but it's the quickest way I found to fix it): add a constructor to your DbContext class that calls the base with the name of the connection string in web.config - e.g.
namespace MvcProject
{
public class Northwind : DbContext
{
public Northwind() : base("Northwind") {}
}
}
Hope that helps someone out there ;-)
You'll need something like this:
<configuration>
<connectionStrings>
<add name="MyContext"
connectionString="Data Source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=YourDatabaseName"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Or if your database resides is App_Data folder:
<configuration>
<connectionStrings>
<add name="MyContext"
connectionString="Data Source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|YourDatabaseFilename.mdf;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Replace MyContext with name of your class that extends DbContext.
The EF couldn´t find the connection for me but I used the connection string in the base():
namespace MvcProject
{
public class Northwind : DbContext
{
public Northwind() :
base("Data Source=servername;Initial Catalog=database;User ID=yourID;Password=yourPass;Trusted_Connection=False;") {}
}
}
Just to test the connection and it´s worked.
Convention > Configuration, right?
By default, EF Code fist will create a database in your local SQL express instance.
Look in App.Config. It will store it there too.
I faced the same problem and simply changed my connection string name as suggested in web.config file as the name of context db and all went well.
Right click on your Entity Framework mode (edmx file) > goto Properties. You'll see the connection string there.
If your Entity Model is in a separate project, then it must be in it's own settings file.
If You are using codefirst aproach with DbContext you can place a connection string with name matching your context class name in your web.config and it will work just fine.
Connection strings with Database First Approach using EntityFrameWork 5.0 This is how it looks..
<add name="DbEntities" ConnectionString="metadata=res:///Models.DbEntities.csdl|res:/// Models.DbEntities.ssdl|res://*/Models.DbEntities.msl;provider=Oracle.ManagedDataAccess.Client;provider connection string="TNS_ADMIN =( Here we write the location where tns file is located) --example of tns file location is D:\app\client\oracle\product\12.2.0\client_2\network\admin\sample;
USER ID='';PASSWORD='';DATASOURCE='';PERSIST SECURITY INFO= True"" providerName="System.Data.EntityClient"/

Castle Windsor cannot find System.Messaging

I realise this question is very similar to this one, but unfortunately it doesn't quite solve my problem.
I have a console app with the following in my castle config section:
<component id="LegacyMessageFormatter"
service="System.Messaging.IMessageFormatter, System.Messaging"
type="MsmqLogProcessor.Core.Services.LegacyMessageFormatter, MsmqLogProcessor.Core"/>
I initially got an exception "The type name System.Messaging.IMessageFormatter, System.Messaging could not be located." when newing up my WindsorContainer like so:
var container = new WindsorContainer(new XmlInterpreter());
I've set Copy Local to true on System.Messaging. That works when I hit F5.
However, when I publish my console app and run it on a production box I get the same issue. I cannot see the System.Messaging dll in the ApplicationFiles folder after install, presumably because it thinks it's in the GAC.
I've tried copying the dll into this folder, but still no joy.
Any ideas what I'm missing? Is it even a good idea to specify a System assembly as a service?
Try using the fully qualified type name:
<component id='LegacyMessageFormatter'
service='System.Messaging.IMessageFormatter, System.Messaging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
type='...'/>
Windsor does not lookup types in System assemblies, as you can see here
https://github.com/castleproject/Castle.Windsor/blob/master/src/Castle.Windsor/MicroKernel/SubSystems/Conversion/TypeNameConverter.cs#L170
it explicitly skips types defined in assemblies with a name starting with System.
Don't know why but you can workaround this by using your own ConversionManager
public class MyConversionManager : DefaultConversionManager
{
protected override void InitDefaultConverters()
{
Add(new SystemMessaging_TypeConverter(new TypeNameParser()));
base.InitDefaultConverters();
}
}
public class SystemMessaging_TypeConverter : TypeNameConverter
{
public SystemMessaging_TypeConverter(ITypeNameParser parser) : base(parser)
{
}
protected override bool ShouldSkipAssembly(System.Reflection.Assembly assembly)
{
return !assembly.FullName.StartsWith("System.Messaging") && base.ShouldSkipAssembly(assembly);
}
}
and install it in your container as follows:
var container = new WindsorContainer();
container.Kernel.AddSubSystem(SubSystemConstants.ConversionManagerKey, new MyConversionManager());
container.Install(Configuration.FromAppConfig());
And then register the service without the assembly name:
<component id="LegacyMessageFormatter"
service="System.Messaging.IMessageFormatter"
type="MsmqLogProcessor.Core.Services.LegacyMessageFormatter, MsmqLogProcessor.Core">

Entity Framework Code First Doesn't Generate Database

I created a db Context class and added a connection string in my web.config file as instructed in Scott Guthrie's Code First Development with Entity Framework 4. I am running it from a test method. I received several database errors running the tests, but when I finally cleaned up the classes so the test succeeded, I still had no database in the App_data folder.
I added Database.CreateIfNotExists() to the dbContext constructor, but still no sdf file. Anyone know what I am doing wrong?
For the database to be automatically created, the connection string name has to be named exactly as the DbContext subclass name (with namespace).
Eg. Say your DB class is like this:
namespace MyNamespace
{
public class FooDb : DbContext
{
public DbSet<XXX> ABC{ get; set; }
}
}
Your connection string should look like so:
<connectionStrings>
<add name="MyNamespace.FooDb" connectionString="Data Source=|DataDirectory|MyNamespace.FooDb.sdf" providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>
Check SQL Server Management Studio -> .\sqlexpress
That's where CF has been putting all my databases when I don't specify a connection string.
See here for auto-creating the .sdf with EF 4.1 and the SQL CE NuGet package (or a new MVC 3 project apparently):
http://www.goatly.net/2011/6/27/entity-framework-code-first-the-path-is-not-valid-check-the-directory-for-the-database.aspx
Long story short: Create an empty App_Data folder - the sdf is auto created, but only if the folder it goes in is present.
Make sure your dbcontext using correct connection string
Some thing similar like this
public class DBContext : IdentityDbContext<ApplicationUser>
{
public DBContext ()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
}
And in web.config
<add name="DefaultConnection" connectionString="Server=....;Connection Timeout=300;" providerName="System.Data.SqlClient" />

Resources