Code generation persistance

Jun 19, 2012 at 8:12 AM

By default, the generate code is not able to persist the edits back to the .config, so is there any way to generate persistent configuration classes or modify the code generation strategy (e.g plug in some T4 somewhere)?

Jun 21, 2012 at 6:48 AM

I'm not sure what you're asking to do here. Could you be more specific?

Jun 22, 2012 at 10:33 AM
Edited Jun 22, 2012 at 10:34 AM

I'll try to explain better:

When i create a custom section, the tool automatically generate for me a list of classes with the properties that i have added in the designer with getter and setter by default.

Since i have the setter, i can override at run time the value of the setting stored in the app.config (e.g MyCustomSection.Instance.MyProperty = someValue;) but i'm not able to persist it to the app.config, what i want is the ability to save to the app.config all the edits were made (e.g. like ConfigurationManager.Save(...) do).

It would be also nice to have the ability to use custom T4 template for classes generation (like EF)

Jun 22, 2012 at 12:29 PM

Saving configuration sections that have been modified during run-time is not our responsibility. That feature is already perfectly possible using the .NET configuration classes. The "MyCustomSection.Instance" property is a shortcut access only meant for reading the configuration. If you mean to be able to change it during run-time, you must code your own opening and saving.

We do what you're asking for in the company I work for. We store our settings in machine.config, but this code is relatively easy to adopt for using a local app.config. Here's some sample code that should help you get started:

// Open the configuration file you want to work with.
// If you are working with a local app.config and not machine config,
// look into using ConfigurationManager.OpenExeConfiguration(string); instead.
var machineConfiguration = ConfigurationManager.OpenMachineConfiguration();
// Get your configuration section this way. (Or however you want, really...)
var myCustomSection = machineConfiguration.Sections["myCustomSection"];
// At my company, we actually do it this way:
var configType = typeof(MyCustomSection);
var myCustomSection = machineConfiguration.FindConfigurationSectionOfType(configType);
// Where FindConfigurationSectionOfType is an extension method that looks like this:
public static ConfigurationSection FindConfigurationSectionOfType( this ConfigurationSectionCollection sectionCollection, Type sectionType )
	forint i = 0; i < sectionCollection.Count; i++ )
			if( sectionCollection[i].GetType() == sectionType )
				return sectionCollection[i];
		catchConfigurationException )
		{ }
	return null;
// Anyway, to the point. After you have yourSection, you can make changes to it:
myCustomSection.MyProperty = someValue;
// And finally, you can save it:

I hope that helps you figure it out. :) Let me know if you have any further questions.