ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCSI-415Configuration Overview
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CSI-415

    Advanced Programming

    Progress0 / 55 done
    Topics55
    1Visual Programming Basics2Introduction to Events3Fundamentals of Event-Driven Programming4Message Handling5User Interfaces6Graphics Device Interface7Painting and Drawing8Windows Management9Input Devices10Resources11String and Menu Resource12Dialogs and Windows Controls13Common Controls14Dynamic Link Libraries (DLLs)15Threads and Synchronization16Network Programming17Building Class Libraries at the Command Line18Class Libraries19Using References20Assemblies21Private Assembly Deployment22Shared Assembly Deployment23Configuration Overview24Configuration Files25Programmatic Access to Configuration26Using SDK Tools for Signing and Deployment27Metadata28Reflection29Late Binding30Directories and Files31Serialization32Attributes33Memory Management and Garbage Collection34Threading and Synchronization35Asynchronous Delegates36Application Domains37Marshal by Value38Marshal by Reference39Authentication and Authorization40Configuring Security41Code Access Security42Code Groups43Evidence44Permissions45Role-Based Security46Principals and Identities47Using Data Readers48Using Data Sets49Interacting with XML Data50Tracing Event Logs51Using the Boolean Switch and Trace Switch Classes52Print Debugging Information with the Debug Class53Instrumenting Release Builds with the Trace Class54Using Listeners55Implementing Custom Listeners
    7 min read
    Topic 23 of 55
    Topic Study Note Illustration
    23

    Configuration Overview

    Configuration is a fundamental aspect of software development, especially for enterprise applications. In C#, configuration management involves specifying how the application should behave under different environments, such...

    Configuration Overview in C#

    Configuration is a fundamental aspect of software development, especially for enterprise applications. In C#, configuration management involves specifying how the application should behave under different environments, such as development, testing, or production. This configuration typically includes settings like connection strings, file paths, logging options, application behavior, and other environment-specific values. The goal is to externalize these settings from the application's code so that they can be easily modified without changing the codebase.

    In .NET applications, configuration data is often stored in configuration files, such as XML-based files (app.config or web.config) or more modern approaches like JSON-based files (appsettings.json).


    1. Types of Configuration Files in C#

    A. App.config / Web.config

    In older versions of .NET (e.g., .NET Framework), XML-based configuration files like app.config and web.config were commonly used. These files store various configuration settings, including application-specific settings, security, database connections, and more.

    • app.config: Used in desktop applications (WinForms, WPF, Console apps).
    • web.config: Used in web applications (ASP.NET WebForms, MVC).
    Example of app.config (XML format):
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <appSettings>
        <add key="AppTitle" value="My Application" />
        <add key="MaxUsers" value="100" />
      </appSettings>
    
      <connectionStrings>
        <add name="DatabaseConnection" connectionString="Server=myServer;Database=myDB;User Id=myUser;Password=myPassword;" providerName="System.Data.SqlClient" />
      </connectionStrings>
    
      <system.web>
        <compilation debug="true" targetFramework="4.5" />
      </system.web>
    </configuration>
    
    • appSettings section: Holds simple key-value pairs that can be used throughout the application.
    • connectionStrings section: Stores database connection strings.
    • system.web section: Contains configuration settings specific to web applications, like compilation and authentication settings.

    These settings can be read at runtime using ConfigurationManager class in C#.

    using System.Configuration;
    
    string appTitle = ConfigurationManager.AppSettings["AppTitle"];
    string connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnection"].ConnectionString;
    

    B. appsettings.json

    With the introduction of .NET Core and .NET 5+, the configuration system has evolved. One of the major changes was the adoption of JSON as the default configuration file format, particularly for ASP.NET Core applications. The appsettings.json file is now commonly used to store application settings.

    Example of appsettings.json:
    {
      "AppSettings": {
        "AppTitle": "My Application",
        "MaxUsers": 100
      },
      "ConnectionStrings": {
        "DatabaseConnection": "Server=myServer;Database=myDB;User Id=myUser;Password=myPassword;"
      },
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      }
    }
    

    How to Access Configuration in .NET Core:

    In .NET Core (or .NET 5+), the appsettings.json file is accessed via IConfiguration interface.

    using Microsoft.Extensions.Configuration;
    
    public class MyService
    {
        private readonly IConfiguration _configuration;
    
        public MyService(IConfiguration configuration)
        {
            _configuration = configuration;
        }
    
        public void PrintAppTitle()
        {
            string appTitle = _configuration["AppSettings:AppTitle"];
            Console.WriteLine(appTitle);
        }
    }
    

    This system allows for easier binding of configuration data to objects, improved dependency injection, and greater flexibility in how configuration is structured and accessed.


    2. Key Configuration Concepts

    A. Configuration Hierarchy

    In modern .NET applications, configuration files can be nested and follow a hierarchical structure. This allows for more granular control over different sections of the application.

    For example, in appsettings.json, you can have nested sections, like:

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "ConnectionStrings": {
        "DefaultConnection": "Server=localhost;Database=myDB;"
      },
      "AppSettings": {
        "Title": "My App"
      }
    }
    

    Accessing nested values would look like this:

    string logLevel = _configuration["Logging:LogLevel:Default"];
    

    B. Configuration Sources and Providers

    .NET supports multiple configuration providers, which allow different sources of configuration data, such as:

    • JSON files (appsettings.json, appsettings.{Environment}.json).
    • Environment variables.
    • Command-line arguments.
    • In-memory collections.
    • Custom configuration sources.

    For example, a common pattern in ASP.NET Core is to load configurations from multiple sources, with the last loaded source taking precedence.

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((context, config) =>
            {
                var environment = context.HostingEnvironment.EnvironmentName;
                config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                      .AddJsonFile($"appsettings.{environment}.json", optional: true)
                      .AddEnvironmentVariables();
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
    

    C. Environment-Specific Configuration

    In .NET, you can have environment-specific configurations for different environments like Development, Staging, and Production. This is especially useful in cloud-based applications and when managing different configurations for different deployment environments.

    • appsettings.Development.json
    • appsettings.Production.json
    • appsettings.Staging.json

    .NET automatically selects the appropriate configuration file based on the environment.

    For example:

    {
      "ConnectionStrings": {
        "DefaultConnection": "Server=localhost;Database=devDB;"
      }
    }
    

    And for production:

    {
      "ConnectionStrings": {
        "DefaultConnection": "Server=prodServer;Database=prodDB;"
      }
    }
    

    You can set the environment using the ASPNETCORE_ENVIRONMENT environment variable:

    set ASPNETCORE_ENVIRONMENT=Production
    

    D. Configuration Reloading

    In ASP.NET Core, configuration files such as appsettings.json can be reloaded automatically if they are changed. This is achieved through the reloadOnChange flag when adding configuration sources.

    config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
    

    3. Accessing Configuration in C#

    In both .NET Framework and .NET Core, configuration can be accessed through different mechanisms.

    A. Accessing Configuration in .NET Framework

    In .NET Framework, configuration is typically accessed using ConfigurationManager class, which reads data from the app.config or web.config file.

    using System.Configuration;
    
    string appTitle = ConfigurationManager.AppSettings["AppTitle"];
    string connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnection"].ConnectionString;
    

    B. Accessing Configuration in .NET Core

    In .NET Core, configuration is accessed using IConfiguration, which is part of the dependency injection system. You can inject IConfiguration into your classes to access configuration values.

    public class MyService
    {
        private readonly IConfiguration _configuration;
    
        public MyService(IConfiguration configuration)
        {
            _configuration = configuration;
        }
    
        public void PrintAppTitle()
        {
            string appTitle = _configuration["AppSettings:AppTitle"];
            Console.WriteLine(appTitle);
        }
    }
    

    4. Common Configuration Sections

    Here are a few common sections you might find in configuration files:

    A. Connection Strings

    Connection strings for databases, message brokers, and other services are often stored in the connectionStrings section.

    Example (in app.config or appsettings.json):

    <connectionStrings>
        <add name="MyDb" connectionString="Server=localhost;Database=MyDb;Integrated Security=True;" />
    </connectionStrings>
    

    Or in appsettings.json:

    {
      "ConnectionStrings": {
        "MyDb": "Server=localhost;Database=MyDb;Integrated Security=True;"
      }
    }
    

    B. Logging Configuration

    You can configure logging options in configuration files, such as the log level or the log file path.

    Example (in appsettings.json):

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning"
        }
      }
    }
    

    5. Summary

    • Configuration in C# is a way of managing application settings externally, allowing for easier maintenance and flexibility.
    • Configuration files include app.config, web.config, and appsettings.json (for .NET Core).
    • Environment-specific configurations allow different settings for different deployment environments (Development, Production, etc.).
    • .NET offers a flexible configuration system where settings can be loaded from various sources
    ← Previous topic 22
    Shared Assembly Deployment
    Next topic 24 →
    Configuration Files

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    7mremaining
    1.1kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Advanced Programming