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-415Programmatic Access To…
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 25 of 55
    Topic Study Note Illustration
    25

    Programmatic Access to Configuration

    Programmatically accessing configuration settings allows your application to retrieve values at runtime, enabling dynamic behavior based on external configurations. This is particularly important for scenarios like deployment,...

    Programmatic Access to Configuration in C#

    Programmatically accessing configuration settings allows your application to retrieve values at runtime, enabling dynamic behavior based on external configurations. This is particularly important for scenarios like deployment, multi-environment setups, and modifying application settings without modifying the source code.

    In C# and the .NET ecosystem, configuration values can be accessed through various mechanisms, depending on whether you are working in a .NET Framework or .NET Core/.NET 5+ application.

    1. Accessing Configuration in .NET Framework

    In .NET Framework (such as WinForms, WPF, or Console applications), configuration data is commonly stored in XML configuration files like app.config or web.config, and you can access these settings programmatically through the ConfigurationManager class.

    A. Example of app.config:

    <?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;" />
      </connectionStrings>
    </configuration>
    

    B. Accessing Configuration with ConfigurationManager:

    To read the values from the app.config file in .NET Framework, you use the ConfigurationManager class from the System.Configuration namespace.

    Example (Accessing AppSettings and Connection Strings):
    using System;
    using System.Configuration;
    
    class Program
    {
        static void Main()
        {
            // Accessing appSettings
            string appTitle = ConfigurationManager.AppSettings["AppTitle"];
            Console.WriteLine("App Title: " + appTitle);
    
            // Accessing connectionStrings
            string connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnection"].ConnectionString;
            Console.WriteLine("Database Connection String: " + connectionString);
        }
    }
    
    • AppSettings: Key-value pairs can be accessed using ConfigurationManager.AppSettings["KeyName"].
    • ConnectionStrings: Connection strings are accessed using ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString.

    2. Accessing Configuration in .NET Core / .NET 5+

    In .NET Core and .NET 5+, configuration management is more flexible and is built around the IConfiguration interface. Configuration can be loaded from multiple sources, such as JSON files (appsettings.json), environment variables, command-line arguments, and more.

    A. 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"
        }
      }
    }
    

    B. Accessing Configuration with IConfiguration in .NET Core / .NET 5+:

    In .NET Core and .NET 5+, you need to use the IConfiguration interface, which is typically injected into classes via Dependency Injection.

    1. Add appsettings.json in the Program.cs or Startup.cs:
    using Microsoft.Extensions.Configuration;
    
    public class Program
    {
        public static void Main(string[] args)
        {
            // Build the configuration
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory()) // Sets the base path
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) // Adds appsettings.json file
                .Build();
    
            // Access configuration settings
            string appTitle = configuration["AppSettings:AppTitle"];
            int maxUsers = int.Parse(configuration["AppSettings:MaxUsers"]);
            string dbConnection = configuration.GetConnectionString("DatabaseConnection");
    
            // Output the settings to the console
            Console.WriteLine($"App Title: {appTitle}");
            Console.WriteLine($"Max Users: {maxUsers}");
            Console.WriteLine($"Database Connection: {dbConnection}");
        }
    }
    
    1. Accessing Nested Configuration:

    You can also access nested configuration sections using a colon (:) to denote the hierarchy (e.g., AppSettings:AppTitle).

    string appTitle = configuration["AppSettings:AppTitle"];
    

    For more complex settings, you can use the GetSection() method to retrieve entire sections:

    IConfigurationSection appSettingsSection = configuration.GetSection("AppSettings");
    string appTitle = appSettingsSection["AppTitle"];
    int maxUsers = int.Parse(appSettingsSection["MaxUsers"]);
    
    1. Binding Configuration to Strongly Typed Objects:

    You can also bind an entire section of the configuration to a strongly typed class, making it easier to work with settings in a more object-oriented way.

    Example of Binding:

    Define a class that matches the structure of your configuration:

    public class AppSettings
    {
        public string AppTitle { get; set; }
        public int MaxUsers { get; set; }
    }
    

    Then bind the AppSettings section of the configuration to this class:

    IConfigurationSection appSettingsSection = configuration.GetSection("AppSettings");
    AppSettings appSettings = appSettingsSection.Get<AppSettings>();
    
    Console.WriteLine($"App Title: {appSettings.AppTitle}");
    Console.WriteLine($"Max Users: {appSettings.MaxUsers}");
    

    This approach automatically maps the configuration settings into an object that can be accessed in a strongly-typed manner.

    1. Accessing Connection Strings:

    Connection strings can be accessed using the GetConnectionString() method in .NET Core and .NET 5+:

    string dbConnection = configuration.GetConnectionString("DatabaseConnection");
    

    3. Accessing Environment-Specific Configuration Files

    .NET Core and .NET 5+ allow you to have environment-specific configuration files. These files override settings in appsettings.json depending on the environment in which the application is running. The common pattern is to use files like:

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

    This is useful for managing different settings in different environments (e.g., Development, Staging, Production).

    1. Set the Environment:

    You can specify the environment by setting the ASPNETCORE_ENVIRONMENT environment variable.

    set ASPNETCORE_ENVIRONMENT=Development
    
    1. Loading Environment-Specific Files:

    You can configure the ConfigurationBuilder to load the appropriate configuration file based on the environment.

    public class Program
    {
        public static void Main(string[] args)
        {
            var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production";
    
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{environment}.json", optional: true, reloadOnChange: true)
                .Build();
    
            // Access configuration
            string appTitle = configuration["AppSettings:AppTitle"];
            Console.WriteLine($"App Title: {appTitle}");
        }
    }
    

    In this case, the application will load appsettings.json by default, and if the environment is set to Development, it will override the settings with appsettings.Development.json.


    4. Accessing Configuration from Other Sources

    In addition to JSON files, .NET Core and .NET 5+ support loading configuration from various sources, such as:

    • Environment Variables: Configuration values can be stored in environment variables.
    • Command-line Arguments: Configuration values can be passed directly via command-line arguments.
    • In-memory Data: You can use in-memory configuration data.
    • Azure App Configuration: For cloud-based applications, Azure App Configuration can be used.

    For example, to load configuration from environment variables:

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((context, config) =>
            {
                var environment = context.HostingEnvironment.EnvironmentName;
                config.AddEnvironmentVariables();
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
    

    5. Summary

    • In .NET Framework, configuration is accessed via the ConfigurationManager class from XML-based app.config or web.config files.
    • In .NET Core and .NET 5+, configuration is handled via the IConfiguration interface, which supports multiple sources like appsettings.json, environment variables, and command-line arguments.
    • Environment-Specific Configuration: You can have environment-specific configuration files like appsettings.Development.json and appsettings.Production.json to manage different configurations for different environments.
    • Binding to Strongly Typed Objects: In .NET Core, you can bind configuration sections to C# objects for easier access and type safety.

    By leveraging these mechanisms, you can manage your application's configuration in a way that is both flexible and maintainable, providing

    ← Previous topic 24
    Configuration Files
    Next topic 26 →
    Using SDK Tools for Signing and Deployment

    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