1

If using Microsoft.Practices.EnterpriseLibrary it uses the web.config file to set the database configuration and connection. How would this work with MVC6 .Net Core/Vnext? To get this working? Does something need to be set on the Startup file??

Web.Config

<configSections>
<section name="dataConfiguration"    type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings,   Microsoft.Practices.EnterpriseLibrary.Data, Version=6.0.0.0, Culture=neutral,   PublicKeyToken=31bf3856ad364e35" requirePermission="false" />
  </configSections>
<dataConfiguration defaultDatabase="MyDBConnectionString" />
<connectionStrings>
<add name="MyDBConnectionString" connectionString="Data Source=MyDatabaseServer;Database=MyDatabase; Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>

appsettings.json

{
 "Data": {
   "dataConfiguration": {
     "type":"Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35",
       "requirePermission": "false"
},
"DefaultConnection": {
  "ConnectionString": "Data Source=MyDatabaseServer;Database=MyDatabase; Integrated Security=SSPI;",
  "providerName": "System.Data.SqlClient"
 }
},

Data Access

    public static Model.Record GetRecordByID(Int32 ID)
    {

        //Declare the variables
        Amendment obj = new Record();
        object xml = null;
        DbCommand dbCmd = null;
        Database db = null; 
        try
        {

            // Create the database object, using the default database service. The
            // default database service is determined through configuration.


            DatabaseProviderFactory factory = new DatabaseProviderFactory(new SystemConfigurationSource());
            DatabaseFactory.SetDatabaseProviderFactory(factory, false);


           db = DatabaseFactory.CreateDatabase();


             dbCmd = db.GetStoredProcCommand("spXMLGetRecordByID");

            db.AddInParameter(dbCmd, "RecordID", DbType.Int32, ID);
            db.AddInParameter(dbCmd, "@xml", DbType.Xml, 1);



            if (!xml.Equals(DBNull.Value))
            {


                obj = (Amendment)Deserialize(xml.ToString(), typeof(Record));
            }


        }
        catch (SqlException sqlEx)
        {
            // ExceptionUtility.SendError(sqlEx, "DAL", "GetRecordByID");
        }
        catch (Exception ex)
        {
            //ExceptionUtility.SendError(ex, "DAL", "GetRecordByID");

        }
        finally
        {
            // DALCleanUp(db, dbCmd);

        }

        return obj;

    }
wolfeh
  • 666
  • 1
  • 8
  • 23

2 Answers2

0

To use the settings in appsettings.json (or any other json file) the first step is to add the file(s) to an IConfigurationRoot member variable in class Startup. This code is generated for you when you create a project with the ASP.NET 5 template.

public IConfigurationRoot Configuration { get; set; }

public class Startup
{
    var builder = new ConfigurationBuilder()
                    .AddJsonFile("appsettings.json")
                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

    builder.AddEnvironmentVariables();
    Configuration = builder.Build();
}

After that you can use the IConfigurationRoot member variable to access individual values from the json file.

this.Configuration["Data:DefaultConnection:ConnectionString"]

You can also get sections of the configuration file if you have a class that matches the json.

Public class DataConfiguration
{
    public string type { get; set; }
    public bool RequirePermission { get; set; }
}

In the ConfigureServices() method of class Startup, add that class with the values from the json file to the IoC container.

services.Configure<DataConfiguration>(Configuration.GetSection("Data:dataConfiguration"));

This is how you access those settings in the Configure() method of class Startup

DataConfiguration dataConfig;
bool requirePermission;

dataConfig= app.ApplicationServices.GetService<DataConfiguration>();
requirePermission = dataConfg.RequirePermission ;

You can also access the settings from any class that is called by the framework (because your instantiated class is in the IoC container).

public class MyController : Controller
{
    private IOptions<DataConfiguration> dataConfig;

    public MyController(IOptions<DataConfiguration> dataConfig)
    {
        this.dataConfig= dataConfig;
    } 

    ...
}
Clint B
  • 4,610
  • 2
  • 18
  • 22
  • When I hit the line of code db = DatabaseFactory.CreateDatabase(); I get the error "The configuration file does not define a default database." – wolfeh May 02 '16 at 15:03
  • This didn't work for me Enterprise Library Database could not define the default database. – wolfeh May 02 '16 at 17:15
  • Sorry about that. I thought you just needed some information on how to use the ASP.NET Core application settings. For the Enterprise Library properties that expect XML, you can use the XmlSerializer class to convert your configuration class to XML. – Clint B May 02 '16 at 19:27
  • You could be right I just can't access the connection string. I was able to get it to work within my DAL. But I have to directly put in my connection string. db = new Microsoft.Practices.EnterpriseLibrary.Data.Sql.SqlDatabase("Data Source=MyServer;Database=MyDatabase; Integrated Security=SSPI;"); What I need to do is somehow access the connection string within the appsettings.json instead of putting the connection string directly within the createdatabase method of enterpriselibary. I have these everywhere throughout my DAL. – wolfeh May 02 '16 at 19:31
  • You could pass your configuration class that contains your connection string to your DAL. – Clint B May 02 '16 at 19:49
  • So how is this explaining how to use appsettings.json to load the connectionstring needed for enterprise library. Or is that not possible? I want to use the appsettings file to load my connection string into enterprise library. – V. Benavides Mar 07 '18 at 16:02
0

For all people who are trying to use EnterpriseLibrary.NetCore in a ASP.NET Core project:

The configuration will only be read if you store it in a app.config file.

If you're migrating a project from ASP.NET to ASP.NET Core, you have to rename the web.config to app.config.

See also this: https://stackoverflow.com/a/50572248/7500260

Zavog
  • 181
  • 4