How to solve issue with 'ClientConfigurationHost::Init' in my project.exe.config

Moah885 0 Reputation points
2023-05-19T07:24:23.5866667+00:00

I have created two projects where first handles setting up the DB connection information and send it to App.config of another project where the second project handles the connection of the DB to SQL server.

So, I done the following in my App.Config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="applicationSettings" (.....)  >
            <section name="Form.Properties.Settings" (.....) />
        </sectionGroup>
        <connectionStrings>
            <add name="Form.Properties.Settings.DBConn" connectionString="Server=servername;Database=databasename;User Id=username;Password=password;"
                providerName="System.Data.SqlClient" />
        </connectionStrings>
    </configSections>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
</configuration>

And In file which handles sending the connection string:

    var appconfigpath = txtbx_appConfigPath.Text;
    var servername = txtbx_serverName.Text;
    var databasename = txtbx_Database.Text;
    var username = txtbx_Username.Text;
    var password = txtbx_Password.Text;

    var PlaceholderConnectionString = $"Server={servername};Database={databasename};User Id={username};Password={password};";

    try
    {
        ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
        configFileMap.ExeConfigFilename = appconfigpath;
        try
        {
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
            // Modify the connection string value
            config.ConnectionStrings.ConnectionStrings["Form.Properties.Settings.DBConn"].ConnectionString = PlaceholderConnectionString;

            // Save the modified configuration
            config.Save(ConfigurationSaveMode.Modified);

            // Refresh the section
            ConfigurationManager.RefreshSection("connectionStrings");

            MessageBox.Show("Configuration Saved", "Output", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        catch (ConfigurationErrorsException ex)
        {
            // Handle any configuration loading errors
            MessageBox.Show($"Error loading configuration file: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
        }
    }
    catch (Exception ex)
    {
        // Connection string not found in app.config
        MessageBox.Show($"Error Message: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        return;
    }
}

However, everytime I run the code, it gets to the line `Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);`, gets to the exception and prints following error `System.InvalidOperationException: 'An unexpected error occurred in 'ClientConfigurationHost::Init'.'`. Yesterday, it worked and when I started working on encryption then this started to happen.

Can you please explain to me what could be the issue (why can't I save the SQL connection into my secondproject.exe.config), how can I solve it and why when I tried to debug I was not able to access the function to pinpoint the error (it automatically jumps to the exception)?

Edit 1:

I tried to use following code:

    try
    {
    
        // Update the connection string in the configuration file
        var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    
        var connectionStringsSection = config.ConnectionStrings;
    
        // Check if the connection string entry exists and update its value
        if (connectionStringsSection.ConnectionStrings["Form.Properties.Settings.DBConn"] != null)
        {
            connectionStringsSection.ConnectionStrings["Form.Properties.Settings.DBConn"].ConnectionString = ConnectionString;
    
            // Save the changes to the configuration file
            config.Save(ConfigurationSaveMode.Modified);
    
            // Refresh the configuration manager
            ConfigurationManager.RefreshSection("connectionStrings");
    
            // Use the connection string in your application logic
            MessageBox.Show("Configuration Saved", "Output", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        else
        {
            Console.WriteLine("Connection string entry 'DBConn' does not exist in the configuration file.");
        }
    }
    catch (Exception ex)
    {
        // Connection string not found in app.config
        MessageBox.Show($"Error Message: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        return;
    }

I get the message for the configuration being saved but when I checked the config file, I still get the `'Server=servername;Database=databasename;User Id=username;Password=password;'`

Edit 2:

I have tried to trace the errors and I have found these fields were affected:

- CustomAttributes	Method System.Reflection.MemberInfo.get_CustomAttributes cannot be called in this context. System.Collections.Generic.IEnumerable<System.Reflection.CustomAttributeData>
- Method System.Reflection.RuntimeMethodInfo.get_ReturnTypeCustomAttributes cannot be called in this context.
- '((System.Reflection.RuntimeMethodInfo)($exception).TargetSite).ReflectedType' threw an exception of type 'System.NotSupportedException'
- MethodImplementationFlags	Method System.Reflection.MethodBase.get_MethodImplementationFlags cannot be called in this context.	System.Reflection.MethodImplAttributes
- IsSecurityTransparent	Method System.Reflection.RuntimeMethodInfo.get_IsSecurityTransparent cannot be called in this context.	bool
- IsSecuritySafeCritical	Method System.Reflection.RuntimeMethodInfo.get_IsSecuritySafeCritical cannot be called in this context.	bool
- IsSecurityCritical	Method System.Reflection.RuntimeMethodInfo.get_IsSecurityCritical cannot be called in this context.	bool

I am using 4.7.2 for the .Net framework with 7.0.101 for the dotnet version.

Edit 3:

I found the following reference to the code for the ClientConfigurationHost ([.Net Source code to ClientConfigurationHost) and from what I understand is that I might have got the first error exception in code in Init (40% sure),

    if (fileMap != null && !String.IsNullOrEmpty(_exePath)) {
                        throw ExceptionUtil.UnexpectedError("ClientConfigurationHost::Init");
                    }

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,638 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,640 questions
Microsoft Configuration Manager Application
Microsoft Configuration Manager Application
Microsoft Configuration Manager: An integrated solution for for managing large groups of personal computers and servers.Application: A computer program designed to carry out a specific task other than one relating to the operation of the computer itself, typically to be used by end users.
474 questions
Microsoft Configuration Manager
{count} votes

1 answer

Sort by: Most helpful
  1. Moah885 0 Reputation points
    2023-06-15T08:55:47.96+00:00

    I managed to find out the reason when I was copying the path for the config file, it seems an extra character appears with the path which caused the error.

    0 comments No comments