Question

Problem

When grabbing the _mailSettings.Smtp.Network.Host, even though it's in the application configuration file, it's returning null.


Code

First and foremost, because the project is just a Class Library, I have the following post-build event to build the properly named configuration file:

copy "$(ProjectDir)App.config" "$(TargetDir)ApplicationSupport.Email.dll.config"

next I have a class that is intended to load the configuration and make it available:

public class Startup
{
    SmtpSection _smtpSection = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection;

    public string SmtpServer
    {
        get
        {
            if (_smtpSection == null) { return string.Empty; }
            return _smtpSection.Network.Host;
        }
    }

    ...
}

and I'm trying to unit test it:

[TestMethod]
public void TestStartupSettings()
{
    var sut = new ApplicationSupport.Email.Startup();
    Assert.AreEqual("test.mail.com", sut.SmtpServer);
}

and I thought I should be getting data since I've got this configured in the application configuration file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.net>
    <mailSettings>
      <smtp from="somebody@test.com">
        <network host="test.mail.com" defaultCredentials="true" port="25"/>
      </smtp>
    </mailSettings>
  </system.net>
</configuration>
Was it helpful?

Solution

Since there are some issues surrounding using the ConfigurationManager in a Class Library, I chose to simply use the Settings tab in the Project Properties because that generates an app.config file with data that I can simply copy and paste into the web.config of the running application for example.

It also allows me to easily unit test the application.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top