Segregating to 3 tiers from existing ASP.NET project - asp.net

In my asp.net project currently i have business logic and and data access code in two sub folders(BLL,DAL) which are itself located web site project's app_code folder. I need to segregate them to two separate projects(one project for business layer and one project for Data access code).
How can I maintain connection strings necessary to Data access project which are currently in web.config file?(i.e if I choose Class library template for creating DAL and BLL projects)
How can I maintain various other web.config key values that are currently used in BLL, DAL code files?
How can I deploy compiled project? (ie Web site project I am currently deploying bin folder to Staging> production but this way where should i put DAL.dll and BLL.dll and relevant config files)

1 and 2) Add a 'using System.Configuration' and just reference them. Since their referenced in the project, asp.net will pick it up.
For example:
using System.Configuration;
namespace DataLayer
{
public class BaseDataAccess
{
public static string ConnectionString_Logging
{
get
{
return ConfigurationManager.ConnectionStrings["ConnectionString_Logging_Legacy"].ToString();
}
}
}
}
3) If properly referenced, upon compile, your BLL and DAL dlls will be in your bin folder of the main/ui project. If using web.config, your good to go.

Fundamentally, you should be wrapping those configuration bits up in objects along the way. But in any case, you can move them to a different class project without worry here -- it will pick up the configuration settings from whatever project it is hosted by, so you don't need to somehow provide the configuration to your library.

Your existing code should work, as the settings are read from the Config file of the running process, in this case your Web.Config, however i suggest you use custom configuration settings, these would be read from your Web.Config file, a typical implementation could look something like :
<YourCompany>
<YourCompany.ProjectName>
<Data ConnectionName="NameOfConnectionToUse" SomethingElse="XZY" />
<Business SomeValue="12345" />
</YourCompany.ProjectName>
</YourCompany>

Without getting into ideal settings/custom config etc, as asked - during runtime, your class libraries will get the configuration from the web.config if referenced as such from within these layers with no change. System.Configuration.AppSettings/ConnectionStrings will still work.

Related

Access .NET Core Configuration Class From Another Assembly

In The Olden Days
In a web.config file, settings could be placed in an appSettings section like so:
<appSettings>
<add key="mysetting" value="123"/>
</appSettings>
Even though my web.config file was in my web project, any assemblies/libraries used in that project could access the settings using:
ConfigurationManager.AppSettings["mysetting"]
Today (and the problem)
I am starting to use .NET core, and just like before, I have assemblies/libraries that are not web projects in of themselves and need to access various configuration settings.
Microsoft's Configuration documentation (https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration) along with all of the other examples I can find, have the configuration class being consumed by a controller and don't provide any guidance on how to make it work with a class in another assembly/library that is not a controller.
For ONE example, if I have a custom attribute that I can decorate a class with and that custom attribute is defined in another library (not in a web project) and it needs to access a configuration setting, how do I do that today? I can't pass in anything to a constructor in such an instance either.
I'm going to assume you're talking about a ASPNET Core project as you specifically mention web.config.
Here's what you need to do.
IOptions<FooSettingsClass> is usually configured at application start which means that it's available at runtime with code that looks something like this.
// Adds services required for using options.
services.AddOptions();
services.Configure<AppSettings>(Configuration.GetSection("FooAppSettings"));
The easiest way is to have the framework inject it through the constructor. Typically you'll see it (as you mentioned) being injected in the controller like this:
class FooController : Controller {
public FooController(IOptions<FooSettingsClass> settings) { .
//..
}
}
If you need to access this configuration is say, a service, then you simply have a constructor, in a different assembly, which accepts those options. So:
public class SomeServiceInAnotherAssembly {
public SomeServiceInAnotherAssembly(IOptions<FooSettingsClass> settings) {
//..
}
}
This obviously means that your FooSettingsClass class needs to be outside of your ASPNET Core project (to avoid circular dependencies), but this is one way of propagating your configuration without writing any code, which is what I've seen other developers do. To me, writing code is a hoop jumping solution bound to have bugs.
Don't forget that your class (in this exampe SomeServiceInAnotherAssembly) needs to be registered at startup, i.e. services.AddScoped<SomeServiceInAnotherAssembly>();
The nice thing about this approach is that it makes your classes testable.
In 8-2017 Microsoft came out with System.Configuration.Manager for .NET CORE v4.4. Currently v4.5 and v4.6 preview.
Install this nuget package. Add directive to a code file
using System.Configuration;
Now, you can do your
var val = ConfigurationManager.AppSettings["mysetting"];
There is one trick for web sites though - you no longer use web.config for application settings and configuration sections. You use app.config as well as other types of projects. But if you deploy in ISS, you might need to use both. In web.config you supply strictly ISS-related entries. Your app-specific entries go to app.config

How does ConfigurationManager merge or build configurations for a referenced project?

Suppose I have a C# class library project with an app.config file and I reference it an ASP.NET project that has a web.config file. Suppose I have a key in my web.config AppSettings called SmtpServerHostname. If I need the SmtpServerHostname in my referenced class library as well, how should I handle configuring the configuration files? Specifically,
If I don't define the SmtpServerHostname key in my class library, will that "pass through" because it is being referenced by another project where it is defined?
If I do define the key in my class library, which one will take precedence?
I currently make use of web.config transforms when publishing my application. Is it possible to transform the app.config file similarly?
It doesn't work that way. There is no merging. In the ASP.NET application, the app.config settings (or library.dll.config) will not be used in any way. You have to set the web.config yourself for the settings you want the ASP.NET application to see.
This is a duplicate, but I'll answer until I or someone else can properly close it as a duplicate.

IIS Web application and class-library configuration - config file is lost when deployed

I have an ASP.NET web application written in C# 4.0. The application references a class library that comes with its own configuration file. At runtime, the class library uses similar to the following code to load this specific configuration:
var exeConfigPath = this.GetType().Assembly.Location;
var config = ConfigurationManager.OpenExeConfiguration(exeConfigPath);
This is done because the library has to load its bundled configuration rather than the application configuration. The application configuration should not be concerned of the library's settings and should not be able to alter them.
Now, there are a few other things that need to be done for this concept to work. I have to set the library's configuration file build operation as Content in the properties window and the Copy to be Copy Always or Copy If Newer. So far so good - the file gets automatically both into the class library's bin directory, and the web applications's bin directory, and is correctly renamed from App.config to CustomLibrary.dll.config (as supposed, the library's dll is CustomLibrary.dll).
Now I am facing two issues.
1) When I publish the web application to a filesystem location (mapped in IIS), the CustomLibrary.dll.config appears back as App.config in the bin folder of the published app. OK - I will rename it in the class library project to match the expected convention - and problem solved.
2) Even when published, the IIS compiles the application again and stores it in the ASP.NET Temporary Files. There is a fancy directory structure with a folder dedicated for each assembly referenced. The folder corresponding to the CustomLibrary.dll does not contain the config file in it. Since this.GetType().Assembly.Location will return the path to the temp folder, the application fails to load the configuration and crashes as it should.
I need to preserve the pattern of having the configuration in the class library, and be able to make it work in the web application. When manually copying the .config to the temp folder, the app works, but see, I really hate manual copying to randomly-named folders.
Is there a way to either prevent IIS from using the temp folders, or to make it copy along the config files? I believe the problem I am facing is configuration-related rather than conceptual since the application works as expected when the config file is in place. I'd prefer not to mess with using hard-coded physical paths to the config file either.
Edit:
To make it clearer, I will point out what and why I want to achieve. The idea is that the library and the web project will be developed as separate products - there will be no user or application specific information in the configuration of the library, so it will not change for different use scenarios. It is also rather specific to the class library functionality rather than the end application. It makes sense for me to keep the library's configuration information bundled within it (similar to Java, where a spring context xml file, or a properties file, get bundled with the jar of the library). I'd like to avoid having to copy the configuration in each app/web config of the consumer application. There will be cases where the consumer application is developed by third parties, and I do not want to rely on them doing their configuration right for my stuff to work. Again, the only issue here is not having the config file copied to the right place.
If those are static, internal settings that nobody should see or change, wouldn't you be better off having a file with the configuration included within the class library as an embedded resource? Either that or just a static class with the settings.
That way you'd be certain that nobody alters it, which in your scenario seems to be a plus.
I have come along a way to work arround the described issue, still not a very pleasant one to my requirements.
The solution is to take advantage of the application configuration (web.config in web apps, or app.config) which is always available. I have added as settings the absolute paths to the config file for each library. So I ended up with:
<!--
THIS IS IN THE WEB.CONFIG FILE
-->
<appSettings>
<add key ="ClassLibrary_ConfigPath"
value ="{My Publish Output Folder}\ClassLibrary.dll.config"/>
</appSettings>
and the class library now uses the following code to load its configuration:
Configuration config = null;
try
{
var exeConfigPath = this.GetType().Assembly.Location;
config = ConfigurationManager.OpenExeConfiguration(exeConfigPath);
}
catch (Exception e)
{
if (!IsConfigurationNotFoundError(e))
{
// IsConfigurationNotFoundError logic skipped for brevity
var exeConfigPath =
ConfigurationManager.AppSettings["ClassLibrary_ConfigPath"];
if (exeConfigPath != null)
{
config = ConfigurationManager.OpenExeConfiguration(exeConfigPath);
}
}
else
{
throw;
}
}
While this works, I will wait for a better solution if possible. Still, I do not have to copy the entire ClassLibrary.dll.config into the web.config file, but now I must manage filesystem locations and be aware of app-setting names. What I really want is the consumer app of the ClassLibrary.dll not to deal with its configuration in any way. If it were a desktop app, I have this covered, as Visual Studio copies the ClassLibary.dll.config appropriately. I hope there is a way to make it work smoothly for web apps.
The short answer is: you can't. You have to merge both configuration sections and place all settings in the main configuration file of your application. In case of the web application it would be the web.config. Read this

Creating Separate DAL Project in MVC3 Application

I'm starting a new ASP.NET project, and I'm trying to follow the multi-project approach I've seen mentioned in multiple questions around Stackoverflow.
I managed to set up the connection string (I think) successfully, by placing it in my presentation layer's Web.config file.
<add name="MyDbContext" connectionString="Data Source=|DataDirectory|MyDb.sdf" providerName="System.Data.SqlServerCe.4.0"/>
However, when I run the following code from my BLL, no DB is created.
using (var db = new MyDbContext())
{
db.MyEntities.Add(new MyEntity()
{
EntityName = "Entity 1"
});
db.SaveChanges();
}
So first of all, where will the actual sdf file be created? I'm assuming in my DAL project. And secondly, is there any further configuration I need to perform to get this to work properly? A link to a tutorial would be splendid.
I've tried following this tutorial, but my DAL project doesn't have a Global.asax file I can play around with.
where will the actual sdf file be created?
It'll be created in the presentation layer. Make sure you have an App_Data subfolder in there. That's what bit me the first time I tried it. Also make sure that you turn on Show all files in Solution explorer or open a Windows Explorer to the App_Data subfolder to see it appear there.
but my DAL project doesn't have a Global.asax file I can play around with.
The Global.asax is living in the presentation layer, not in the DAL. The problem with the tutorial you mentioned is that it makes use of only one project. In the real world you'll likely spread this out over multiple project, typical one ASP.NET (MVC) project and several Class Library template based projects. This causes things to be put in the right project.
|DataDirectory| is a macro that evaluates to ~/App_Data/ in your web project. So look for your .sdf file in path/to/your/project/App_Data/MyDb.sdf.
You'll need to copy any other settings you added in App.config to Web.config.

where should inheritance classes be stored?

I want to create classes that can be inherited by other classes to use along my project.
i.e. i want to create a separate class for each Mail method, each class will implement differently the Compose method, and more Mail classes will be created in the future.
My question is - Where should I create these classes/interfaces? in the App_Code ?
I would suggest creating a separate assembly and include that assembly as a reference in your Web Project. That will enable you to write independent test cases against your classes / interfaces.
Other than user controls you can store source files in App_Code. In your case you can store Interfaces/classes in App_Code. You can have multiple folders for group of class/interfaces inside the AppCode.
AppCode
You can store source code in the App_Code folder, and it will be
automatically compiled at run time. The resulting assembly is
accessible to any other code in the Web application. The App_Code
folder therefore works much like the Bin folder, except that you can
store source code in it instead of compiled code. The App_Code folder
and its special status in an ASP.NET Web application makes it possible
to create custom classes and other source-code-only files and use them
in your Web application without having to compile them independently.
Edit: You may see this discuss: How to organize ASP.NET app_code folder?

Resources