Different configuaration string for specific build configuration - c#

how can i configure my Visual Studio 2010 C# solution/project so
that when i select a Debug configuration - ConnectionString#1 would be used
Release - Connection string #2
and
"Myconfiguarion1" (which was copied from debug) -> Connection string #3
I got to it work with debug in such a way:
if (ConfigurationManager.ConnectionStrings["ConnectionString1"] != null)
{
winApplication.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString;
}
#if DEBUG
if(ConfigurationManager.ConnectionStrings["ConnectionString2"] != null)
{
winApplication.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString;
}
#endif
but this doesn't work with "MybuildConfiguration"

If you're trying to do this for the web.config file of an ASP.NET project in Visual Studio 2010, it's built-in via XML Transformations for web.config.
Web Deployment: Web.Config Transformations
If you're trying to do this for an app.config file, you can use the same transformations but working with them is a bit of a hack:
Visual Studio App.config XML Transformations
Both boil down to actually using separate config files for the different environments you are going to be running your app in. That allows you to supply different values for any of the keys based on what environment you're running in.

I think you can use conditional compilation constants. To define them,
you have to open project property window, select compilation tab, and define a name in the conditional constants field, e.g. CONN1.
This constants get defined only for your active build configuration, so you can define CONN1 for Debug configuration,CONN2 for Release configuration,CONN3 for your custom configuration etc.
then, in your code, you can use:
#ifdef CONN1
//use connection 1
#else
#ifdef CONN2
//use connection 2
#else
//use connection 3
#endif
#endif

Related

Visual Studio 2017 multi-line Debug environment variables

Is VS 2017 (or even earlier versions), when you navigate to Debug -> <ProjectName> Properties -> Debug tab, you can add environment variables that your program can then use via Environment.GetEnvironmentVariable("var_name").
This works great when using a single line value for the variable, but has a character limit.
I have some programs which rely on multi-line variables that are defined on the system they run on when the application is deployed, such as:
string rsaPrivateKey = Environment.GetEnvironmentVariable("PRIVATE_KEY");
However, this is an RSA private keys, and those are multi-line. I want to be able to debug the application on my workstation, and have those environment variables declared in my VS 2017, and not hard-coded so that the logic that uses these variables can actually succeed.
Has anyone ran into this, and can you provide an alternative for declaring multi-line environment variables for Debugging purposes which will not be committed to source code?
Use:
string rsaPrivateKey;
string rsaPrivateKeyPath = Environment.GetEnvironmentVariable("PRIVATE_KEY_Path");
using (StreamReader sr = File.OpenText(rsaPrivateKeyPath ))
{
rsaPrivateKey = sr.ReadToEnd();
}

Application built mode in c# [duplicate]

This question already has answers here:
How do I check the active solution configuration Visual Studio built with at runtime?
(4 answers)
Closed 9 years ago.
I have a C# windows application with 4 App Modes - Debug,Pre-Release, Release and UAT. I have to display in the footer of my main form as to what is my current Operating mode. Any idea how I can retrieve the same?
You could use C#'s #if directive http://msdn.microsoft.com/en-us/library/4y6tbswk.aspx
string mode;
#if DEBUG
mode = "DEBUG";
#elseif RELEASE
mode = "RELEASE";
#else
mode = "UAT";
#end
You would also need to set up the symbol in the project file so that the code can pick up on it. You'll find it by selecting the project properties. (Select the project file and press Alt+Enter)
Visual Studio doesn't provide for applying the configuration names to your .NET code.
However, you may want to define a custom symbol for each of your configurations in your project build settings and query these symbols in your code, like this:
#if DEBUG
...
#elif PRERELEASE
...
#elif RELEASE
...
#elif UAT
...
#endif
you must use #if reference.
check http://msdn.microsoft.com/tr-tr/library/4y6tbswk.aspx

Managing A Debug and Release Connection String

What is a good approach to managing a debug and release connection string in a .NET / SQLServer application?
I have two SQL Servers, a production and a build/debug and I need a method of switching between the two when my ASP.NET application is deployed.
Currently I simply store them in the web.config and comment one or the other out, however that is error prone when deploying.
Create a Debug and Release version of the Web.config file, e.g. Web.debug.config and Web.release.config. Then add a pre-compile condition that copies the relevant version into the web.config based upon the current Target.
Edit: To add the pre compile condition right click on you project and select "Properties" then goto the "Build Events" tab and add the code below to the precompile condition. Obviously, you will have to ammend the code to your needs, see image below.
#echo off
echo Configuring web.config pre-build event ...
if exist "$(ProjectDir)web.config" del /F / Q "$(ProjectDir)web.config"
if "$(ConfigurationName)" == "Debug Test" goto test
if "$(ConfigurationName)" == "Debug M" goto M
if "$(ConfigurationName)" == "Debug BA" goto BA
if "$(ConfigurationName)" == "Release Test" goto test
if "$(ConfigurationName)" == "Release M" goto M
if "$(ConfigurationName)" == "Release BA" goto BA
echo No web.config found for configuration $(ConfigurationName). Abort batch.
exit -1
goto :end
:test
copy /Y "$(ProjectDir)web.config.test" "$(ProjectDir)web.config"
GOTO end
:BA
copy /Y "$(ProjectDir)web.config.BA" "$(ProjectDir)web.config"
GOTO end
:M
copy /Y "$(ProjectDir)web.config.M" "$(ProjectDir)web.config"
GOTO end
:end
echo Pre-build event finished
Project Properties http://img442.imageshack.us/img442/1843/propsa.jpg
The good news is that .NET4 has a provision for just that, you can have separate configs for each Configuration (web.Release.config, web.Debug.config).
The bad news is ... you're probably not using that yet.
Use preprocessor directives: when your project is configured to run in the debug mode, the debug connection string will be chosen, otherwise the release connection string will be chosen automatically.
In Visual studio you will notice that statements are dimmed exclusively according to the project configuration (debug or release).
Just add something like the following in your code:
string myConnectionString;
#if DEBUG
myConnectionString = "your debug connection string";//may be read from your debug connection string from the config file
#else
myConnectionString = "your release connection string"; //may be read from your relase connection string from the config file
#endif
for more detail,check this.
I usually set an Environment variable on my production servers that denotes the server is a production server. I then read the correct connection string from my web.config based on whether this Environment variable exists and is set to the production value.
I use a combination of Sameh's and Obalix's method in .net 3.5.
public static class DataConnection
{
#if LOCALDEV
public const string Env = "Debug";
#endif
#if STAGING
public const string Env="Staging";
#endif
#if RELEASE
public const string Env="Release";
#endif
private static ConnectionStringSettingsCollection _connections;
static DataConnection()
{
_connections = ConfigurationManager.ConnectionStrings;
}
public static string BoloConnectionString
{
get
{
return _connections["DB1."+Env].ConnectionString;
}
}
public static string AOAConnectionString
{
get
{
return _connections["DB2."+Env].ConnectionString;
}
}
public static string DocVueConnectionString
{
get
{
return _connections["DB3."+Env].ConnectionString;
}
}
}
Then in my project properties, I define the right conditional compilation symbols. This way I don't have to keep my connection strings hard coded like Sameh's, but the code only looks for the string based on how it was built. This lets me have (if I need to) one config file for all the builds, but in reality I don't deploy the config files in my build process. Although the conditional app.Relase.config stuff for .net 4 looks like the right way to go in the future.
As of 2018 for newer versions of Visual Studio, Microsoft has taken over the SlowCheetah extension. Installing this will give you an option to split the app.config file into three separate files. One is a base file that has code that always applies, and then you get an app.debug.config file and an app.release.config file.
Note that pulling this as a NuGet package in the project is not enough. If you want the Visual Studio UI menu option, you need to actually download the installer from the site below and run it. Then, install SlowCheetah specifically on any projects you want to use this on using NuGet.
Also note that the original SlowCheetah program by the original developer still exists, but use the one published by Microsoft for newer versions of Visual Studio.
https://marketplace.visualstudio.com/items?itemName=VisualStudioProductTeam.SlowCheetah-XMLTransforms
Well perhaps this is a bit outdated, but the ODBC DSN solves this problem quite well -- I still use -- with rigour -- DNS settings to differentiate between production and debug environments.
p.s., I am expecting loads of down-votes, perhaps this will be a gauge of what people think of a level of indirection for database identifiers.
I can say other solution for this issue. In csproj file file create folow:
<Content Include="DB.config">
<SubType>Designer</SubType>
</Content>
<Content Include="DB.Debug.config">
<DependentUpon>DB.config</DependentUpon>
<SubType>Designer</SubType>
</Content>
<Content Include="DB.Release.config">
<DependentUpon>DB.config</DependentUpon>
<SubType>Designer</SubType>
</Content>
In xml written set the two version for release and debug.
When you open a web project you'll get 2 extra files of the Web.Config out of the box - Web.Debug.config & Web.Release.config.
1.Add your desired connection string to those files with XSLT attributes xdt:Transform="SetAttributes" xdt:Locator="Match(name)"
<connectionStrings>
<add name="myConnectionString" connectionString="myConnectionString" xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
</connectionStrings>"
2.Edit your csproj and add a TransformXml target:
<Target Name="TransformActiveConfiguration" Condition="Exists('$(ProjectDir)/Web.$(Configuration).config')" BeforeTargets="Compile" >
<TransformXml Source="$(ProjectDir)/Web.Config" Transform="$(ProjectDir)/Web.$(Configuration).config" Destination="$(TargetDir)/Web.config" />
</Target>
The second step will make the transform on each build (according to your active configuration) and not only on publish, giving you a better debug experience. I learnt it from this post.

Detecting if a program was run by Visual Studio, as opposed to run from Windows Explorer

Is there a way to detect if your program was loaded through Visual Studio vs. whether it was started as a standalone executable?
Our software has a bug reporting feature to handle unhandled exceptions -- we need to be able to distribute debug builds to our beta testers, but we don't want the bug report to go off when we are in the middle of development, because the Exceptions are a lot more useful if VS catches them with a full stack trace, etc.
Right now, I'm disabling the bug report if Application.ExecutablePath includes bin\Debug or bin\Release, but I figure there is probably a more robust way of detecting whether the program was loaded through VS.
Obviously, we could set up a different build with some preprocessor macros, but for the sake of the question, assume that isn't a possibility -- I don't mind adding code, but I'm trying to make the fewest modifications to the build process, which is why command-line options are kind of a last resort as well.
If it matters, I'm using VS2003/.NET 1.1.
If you're doing this to determine if it is in any debugger (clarified by #JaredPar), you can use Debugger.IsAttached in the exception handler.
try
{
// ...
}
catch(Exception ex)
{
if (!Debugger.IsAttached)
{
ExceptionHandler.Frob(ex);
}
else
{
throw;
}
}
Alternatively:
public static void Frob(Exception ex)
{
if (Debugger.IsAttached)
{
Debugger.Break();
}
}
I don't do .net development, but in java I have done this by passing a flag into the startup options of the application. So you could pass a debug flag into the app from the IDE, and then check for that, when the app is run as an executable the flag would not be present. I would be surprised if .net didn't have something similar.
I know this is old but the provided solutions are not very satisfying.
I used the following class instead:
using System.IO;
using System.Reflection;
public static class Program
{
public static string ExecutablePath
{
get;
private set;
}
static Program()
{
var assemblyPath = Assembly.GetEntryAssembly().Location;
var assemblyDirectory = Path.GetDirectoryName(assemblyPath);
if (assemblyDirectory.EndsWith(#"\Debug") || assemblyDirectory.EndsWith(#"\Release"))
{
string projectFile = Path.GetFileNameWithoutExtension(assemblyPath) + ".csproj";
var root = new DirectoryInfo(assemblyDirectory);
while (root.Parent != null)
{
if (File.Exists(Path.Combine(root.FullName, projectFile)))
break;
root = root.Parent;
if (root.Parent == null) // we could not find it (should not happen)
ExecutablePath = assemblyDirectory;
}
ExecutablePath = root.FullName;
}
else
{
ExecutablePath = assemblyDirectory;
}
}
}
Then you can just use Program.ExecutablePath. If you already have a class named Program you can just extend it by those properties and methods.
If running from Visual Studio it will give you the project path where the csproj-file resides. This is the executable path without the "bin\*\Debug" or "bin\*\Release" stuff.
If not running from Visual Studio it will give you the path where the executable resides.
The solution is independent of debug settings, other attached debuggers or build configurations. The only important thing is, that your configurations are named "Release" and "Debug".
Note: As Troy Gizzi mentioned in the comments, this solution only works if you run the executable from another directory than the output directory. For my use case (simulate the deployment directory structure with the project directory as the root directory), this is a suitable solution. In general I copy my executable later to the deployment directory and expect the same behavior as if I run my program from within Visual Studio. Content and other dependencies are located relative to the project directory in my case.
Have you considered command line arguments? Run the program from Visual Studio with a --no-exception-handling flag (or whatever sounds appropriate), and don't handle exceptions if that argument is passed in. When you start the program elsewhere, without this argument, it'll behave normally.
Instead of tracking by process tree, I would add a configuration flag that enables the reporting feature. The flag can always default to "true" unless you are in your DEV environment then you set it to "false".
Sometimes the application is started outside the debugger and the debugger gets attached later. (Doubleclick on a file where the application is assigned to ...) I use this code to wait for the debugger attach.
using System.Diagnostics;
Process[] procName = Process.GetProcessesByName("devenv");
if(procName.Length > 0)
MessageBox.Show("Wait for debugger attach");

.NET Configuration (app.config/web.config/settings.settings)

I have a .NET application which has different configuration files for Debug and Release builds. E.g. the debug app.config file points to a development SQL Server which has debugging enabled and the release target points to the live SQL Server. There are also other settings, some of which are different in debug/release.
I currently use two separate configuration files (debug.app.config and release.app.config). I have a build event on the project which says if this is a release build then copy release.app.config to app.config, else copy debug.app.config to app.config.
The problem is that the application seems to get its settings from the settings.settings file, so I have to open settings.settings in Visual Studio which then prompts me that the settings have changed so I accept the changes, save settings.settings and have to rebuild to make it use the correct settings.
Is there a better/recommended/preferred method for achieving a similar effect? Or equally, have I approached this completely wrong and is there a better approach?
Any configuration that might differ across environments should be stored at the machine level, not the application level. (More info on configuration levels.)
These are the kinds of configuration elements that I typically store at the machine level:
Application settings
Connection strings
retail=true
Smtp settings
Health monitoring
Hosting environment
Machine key
When each environment (developer, integration, test, stage, live) has its own unique settings in the c:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG directory, then you can promote your application code between environments without any post-build modifications.
And obviously, the contents of the machine-level CONFIG directory get version-controlled in a different repository or a different folder structure from your app. You can make your .config files more source-control friendly through intelligent use of configSource.
I've been doing this for 7 years, on over 200 ASP.NET applications at 25+ different companies. (Not trying to brag, just want to let you know that I've never seen a situation where this approach doesn't work.)
This might help some people dealing with Settings.settings and App.config: Watch out for GenerateDefaultValueInCode attribute in the Properties pane while editing any of the values in the Settings.settings grid in Visual Studio (Visual Studio 2008 in my case).
If you set GenerateDefaultValueInCode to True (True is the default here!), the default value is compiled into the EXE (or DLL), you can find it embedded in the file when you open it in a plain text editor.
I was working on a console application and if I had defaulted in the EXE, the application always ignored the configuration file placed in the same directory! Quite a nightmare and no information about this on the whole Internet.
There is a related question here:
Improving Your Build Process
Config files come with a way to override the settings:
<appSettings file="Local.config">
Instead of checking in two files (or more), you only check in the default config file, and then on each target machine, you put a Local.config, with just the appSettings section that has the overrides for that particular machine.
If you are using config sections, the equivalent is:
configSource="Local.config"
Of course, it's a good idea to make backup copies of all the Local.config files from other machines and check them in somewhere, but not as a part of the actual solutions. Each developer puts an "ignore" on the Local.config file so it doesn't get checked in, which would overwrite everyone else's file.
(You don't actually have to call it "Local.config", that's just what I use)
From what I am reading, it sounds like you are using Visual Studio for your build process. Have you thought about using MSBuild and Nant instead?
Nant's xml syntax is a little weird but once you understand it, doing what you mentioned becomes pretty trivial.
<target name="build">
<property name="config.type" value="Release" />
<msbuild project="${filename}" target="Build" verbose="true" failonerror="true">
<property name="Configuration" value="${config.type}" />
</msbuild>
<if test="${config.type == 'Debug'}">
<copy file=${debug.app.config}" tofile="${app.config}" />
</if>
<if test="${config.type == 'Release'}">
<copy file=${release.app.config}" tofile="${app.config}" />
</if>
</target>
To me it seems that you can benefit from the Visual Studio 2005 Web Deployment Projects.
With that, you can tell it to update/modify sections of your web.config file depending on the build configuration.
Take a look at this blog entry from Scott Gu for a quick overview/sample.
We used to use Web Deployment projects but have since migrated to NAnt. Instead of branching and copying different setting files we currently embed the configuration values directly in the build script and inject them into our config files via xmlpoke tasks:
<xmlpoke
file="${stagingTarget}/web.config"
xpath="/configuration/system.web/compilation/#debug"
value="true"
/>
In either case, your config files can have whatever developer values you want and they'll work fine from within your dev environment without breaking your production systems. We've found that developers are less likely to arbitrarily change the build script variables when testing things out, so accidental misconfigurations have been rarer than with other techniques we've tried, though it's still necessary to add each var early in the process so that the dev value doesn't get pushed to prod by default.
My current employer solved this issue by first putting the dev level (debug, stage, live, etc) in the machine.config file. Then they wrote code to pick that up and use the right config file. That solved the issue with the wrong connection string after the app gets deployed.
They just recently wrote a central webservice that sends back the correct connection string from the value in the machine.config value.
Is this the best solution? Probably not, but it works for them.
One of the solutions that worked me fine was using a WebDeploymentProject.
I had 2/3 different web.config files in my site, and on publish, depending on the selected configuration mode (release/staging/etc...) I would copy over the Web.Release.config and rename it to web.config in the AfterBuild event, and delete the ones I don't need (Web.Staging.config for example).
<Target Name="AfterBuild">
<!--Web.config -->
<Copy Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' " SourceFiles="$(SourceWebPhysicalPath)\Web.Release.config" DestinationFiles="$(OutputPath)\Web.config" />
<Copy Condition=" '$(Configuration)|$(Platform)' == 'Staging|AnyCPU' " SourceFiles="$(SourceWebPhysicalPath)\Web.Staging.config" DestinationFiles="$(OutputPath)\Web.config" />
<!--Delete extra files -->
<Delete Files="$(OutputPath)\Web.Release.config" />
<Delete Files="$(OutputPath)\Web.Staging.config" />
<Delete Files="#(ProjFiles)" />
</Target>
You'll find another solution here: Best way to switch configuration between Development/UAT/Prod environments in ASP.NET? which uses XSLT to transfor the web.config.
There are also some good examples on using NAnt.
Our project has the same issue where we had to maintain configs for dev, qa, uat and prod. Here is what we followed (only applies if you are familiar with MSBuild):
Use MSBuild with the MSBuild Community tasks extension. It includes the 'XmlMassUpdate' task that can 'mass-update' entries in any XML file once you give it the correct node to start with.
To Implement:
1) You need to have one config file which will have your dev env entries; this is the config file in your solution.
2) You need to have a 'Substitutions.xml' file, that contains only the entries that are DIFFERENT (appSettings and ConnectionStrings mostly) for each environment. Entries that do not change across the environment need not be put in this file. They can live in the web.config file of the solution and will not be touched by the task
3) In your build file, just call the XML mass update task and provide the right environment as a parameter.
See example below:
<!-- Actual Config File -->
<appSettings>
<add key="ApplicationName" value="NameInDev"/>
<add key="ThisDoesNotChange" value="Do not put in substitution file" />
</appSettings>
<!-- Substitutions.xml -->
<configuration xmlns:xmu="urn:msbuildcommunitytasks-xmlmassupdate">
<substitutions>
<QA>
<appSettings>
<add xmu:key="key" key="ApplicationName" value="NameInQA"/>
</appSettings>
</QA>
<Prod>
<appSettings>
<add xmu:key="key" key="ApplicationName" value="NameInProd"/>
</appSettings>
</Prod>
</substitutions>
</configuration>
<!-- Build.xml file-->
<Target Name="UpdateConfigSections">
<XmlMassUpdate ContentFile="Path\of\copy\of\latest web.config" SubstitutionsFile="path\of\substitutionFile" ContentRoot="/configuration" SubstitutionsRoot="/configuration/substitutions/$(Environment)" />
</Target>
replace '$Environment' with 'QA' or 'Prod' based on what env. you are building for. Note that you should work on a copy of a config file and not the actual config file itself to avoid any possible non-recoverable mistakes.
Just run the build file and then move the updated config file to your deployment environment and you are done!
For a better overview, read this:
http://blogs.microsoft.co.il/blogs/dorony/archive/2008/01/18/easy-configuration-deployment-with-msbuild-and-the-xmlmassupdate-task.aspx
Like you I've also set up 'multi' app.config - eg app.configDEV, app.configTEST, app.config.LOCAL. I see some of the excellent alternatives suggested, but if you like the way it works for you, I'd add the following:
I have a
<appSettings>
<add key = "Env" value = "[Local] "/>
for each app I add this to the UI in the titlebar:
from ConfigurationManager.AppSettings.Get("Env");
I just rename the config to the one I'm targetting (I have a project with 8 apps with lots of database/wcf config against 4 evenioments). To deploy with clickonce into each I change 4 seetings in the project and go. (this I'd love to automate)
My only gotcha is to remember to 'clean all' after a change, as the old config is 'stuck' after a manual rename. (Which I think WILL fix you setting.setting issue).
I find this works really well (one day I'll get time to look at MSBuild/NAnt)
Web.config:
Web.config is needed when you want to host your application on IIS. Web.config is a mandatory config file for IIS to configure how it will behave as a reverse proxy in front of Kestrel. You have to maintain a web.config if you want to host it on IIS.
AppSetting.json:
For everything else that does not concern IIS, you use AppSetting.json.
AppSetting.json is used for Asp.Net Core hosting. ASP.NET Core uses the "ASPNETCORE_ENVIRONMENT" environment variable to determine the current environment. By default, if you run your application without setting this value, it will automatically default to the Production environment and uses "AppSetting.production.json" file. When you debug via Visual Studio it sets the environment to Development so it uses "AppSetting.json". See this website to understand how to set the hosting environment variable on Windows.
App.config:
App.config is another configuration file used by .NET which is mainly used for Windows Forms, Windows Services, Console Apps and WPF applications. When you start your Asp.Net Core hosting via console application app.config is also used.
TL;DR
The choice of the configuration file is determined by the hosting environment you choose for the service. If you are using IIS to host your service, use a Web.config file. If you are using any other hosting environment, use an App.config file.
See Configuring Services Using Configuration Files documentation
and also check out Configuration in ASP.NET Core.
It says asp.net above, so why not save your settings in the database and use a custom-cache to retrieve them?
The reason we did it because it's easier (for us) to update the continuously database than it is to get permission to continuously update production files.
Example of a Custom Cache:
public enum ConfigurationSection
{
AppSettings
}
public static class Utility
{
#region "Common.Configuration.Configurations"
private static Cache cache = System.Web.HttpRuntime.Cache;
public static String GetAppSetting(String key)
{
return GetConfigurationValue(ConfigurationSection.AppSettings, key);
}
public static String GetConfigurationValue(ConfigurationSection section, String key)
{
Configurations config = null;
if (!cache.TryGetItemFromCache<Configurations>(out config))
{
config = new Configurations();
config.List(SNCLavalin.US.Common.Enumerations.ConfigurationSection.AppSettings);
cache.AddToCache<Configurations>(config, DateTime.Now.AddMinutes(15));
}
var result = (from record in config
where record.Key == key
select record).FirstOrDefault();
return (result == null) ? null : result.Value;
}
#endregion
}
namespace Common.Configuration
{
public class Configurations : List<Configuration>
{
#region CONSTRUCTORS
public Configurations() : base()
{
initialize();
}
public Configurations(int capacity) : base(capacity)
{
initialize();
}
public Configurations(IEnumerable<Configuration> collection) : base(collection)
{
initialize();
}
#endregion
#region PROPERTIES & FIELDS
private Crud _crud; // Db-Access layer
#endregion
#region EVENTS
#endregion
#region METHODS
private void initialize()
{
_crud = new Crud(Utility.ConnectionName);
}
/// <summary>
/// Lists one-to-many records.
/// </summary>
public Configurations List(ConfigurationSection section)
{
using (DbCommand dbCommand = _crud.Db.GetStoredProcCommand("spa_LIST_MyConfiguration"))
{
_crud.Db.AddInParameter(dbCommand, "#Section", DbType.String, section.ToString());
_crud.List(dbCommand, PopulateFrom);
}
return this;
}
public void PopulateFrom(DataTable table)
{
this.Clear();
foreach (DataRow row in table.Rows)
{
Configuration instance = new Configuration();
instance.PopulateFrom(row);
this.Add(instance);
}
}
#endregion
}
public class Configuration
{
#region CONSTRUCTORS
public Configuration()
{
initialize();
}
#endregion
#region PROPERTIES & FIELDS
private Crud _crud;
public string Section { get; set; }
public string Key { get; set; }
public string Value { get; set; }
#endregion
#region EVENTS
#endregion
#region METHODS
private void initialize()
{
_crud = new Crud(Utility.ConnectionName);
Clear();
}
public void Clear()
{
this.Section = "";
this.Key = "";
this.Value = "";
}
public void PopulateFrom(DataRow row)
{
Clear();
this.Section = row["Section"].ToString();
this.Key = row["Key"].ToString();
this.Value = row["Value"].ToString();
}
#endregion
}
}

Categories