MVVMCross 4.0 Xamarin Forms Page not Found - mvvmcross

We've been using MVVMCross for the 18 months. Great Stuff. But, we're looking to migrate from Xamarin.iOS to Xamarin.Forms in an effort to speed development time.
We have a PCL with our ViewModels. But, would like to have our View (Pages) in a separate PCL library, to allow parallel development with Native application.
MVVMCross can not seem to locate the Page if it's located in a separate PCL library, OR if it's located in the Application. However, if I put the Page in the same PCL as the ViewModels, things work like a champ.
I've tried putting the following code in our Setup.cs
protected override IEnumerable<Assembly> GetViewAssemblies()
{
var list = new List<Assembly>();
list.AddRange(base.GetViewAssemblies());
list.Add(typeof(NuSales.Forms.Pages.TestPage).GetTypeInfo().Assembly);
return list;
}
But, still no joy.
Any hints on how to fix the resolver to find the View (Page)?
Thanks

Looking at https://github.com/MvvmCross/MvvmCross-Forms/blob/master/MvvmCross.Forms.Presenter.Core/MvxFormsPageLoader.cs#L44
protected virtual Type GetPageType(string pageName)
{
return _request.ViewModelType.GetTypeInfo().Assembly.CreatableTypes()
.FirstOrDefault(t => t.Name == pageName);
}
... I'd say you need to override the default IMvxFormsPageLoader to change that single Assembly lookup.
...or (for bonus points) you could send in a Pull Request that changes the default behaviour to use the view assemblies collection - and it could also store a Dictionary to avoid multiple Reflection passes and to speed up lookup times.

Hopefully, I'm doing this right in terms of StackOverflow etiquette. Using Stuart's suggestion... A quick fix is.
Create a FormPageLoader like below.
public class MyFormsPageLoader : MvxFormsPageLoader
{
public MyFormsPageLoader() {
}
protected override Type GetPageType(string pageName)
{
return typeof(NuSales.Forms.Pages.TestPage).GetTypeInfo().Assembly.CreatableTypes().FirstOrDefault(t => t.Name == pageName);
}
}
Then you need to register it. I did it in my App.Initialize code
public class FormsApp : MvxApplication
{
public override void Initialize()
{
base.Initialize();
Mvx.RegisterSingleton(typeof(IMvxFormsPageLoader), new MyFormsPageLoader());
RegisterAppStart<TestViewModel>();
}
}

Related

Replacement for #helper in ASP.NET Core

So far, i don't think ViewComponent solves that neither does TagHelper. Is there any replacement to this? Something that takes parameters and returns a HtmlString?
I don't see anything harmful with:
#helper foo(string something) {
<div>Say #something</div>
}
var emailbody = classfilenameinAppCodefolder.foo("hello"); //store result in a variable for further processes
For now i believe its a temporary delete before RC. https://github.com/aspnet/Razor/issues/281 and https://github.com/aspnet/Mvc/issues/1130 Well! it better be. I hope someone is working on it. Without #helper, building large HtmlString or 'template' would be a serious pain.
Note: Partial View doesn't seem to do the trick. I think it only renders views not return view to variable.
Secondly, what happened to the App_Code folder?
According to the following Github issue, it looks like #helper is coming back and will be included in asp .net core 3.0.0 preview 4.
https://github.com/aspnet/AspNetCore/issues/5110
UPDATE
Starting in asp .net core 3, you can now define a local function within a Razor code block.
#{
void RenderName(string name)
{
<p>Name: <strong>#name</strong></p>
}
RenderName("Mahatma Gandhi");
RenderName("Martin Luther King, Jr.");
}
https://learn.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-3.1#razor-code-blocks
Alternatively you can use the #functions directive like this:
#{
RenderName("Mahatma Gandhi");
RenderName("Martin Luther King, Jr.");
}
#functions {
private void RenderName(string name)
{
<p>Name: <strong>#name</strong></p>
}
}
https://learn.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-3.1#functions
#{
Func<String, IHtmlContent> foo = #<div>Say #item</div>;
}
I'd like to expand on #Alexaku's answer and show how I've implemented a helper like function. It's only useful on one specific page but it allows you to execute a piece of razor code multiple times with input parameters. The syntax is not great but I've found it very useful in the absence of razor's #helper function. First declare some kind of Dto that will contain the input parameters into the function.
#functions {
private class Dto
{
public string Data { get;set; }
}
}
Then declare the razor function. Note that the displayItem value can be multi-line and also note that you access the Dto variable using the #item.
#{
Func<Dto, IHtmlContent> displayItem = #<span>#item.Data</span>;
}
Then when you want to use the razor template you can call it like the following from anywhere in the page.
<div>
#displayItem(new Dto {Data = "testingData1" });
</div>
<div>
#displayItem(new Dto {Data = "testingData2" });
</div>
For .NET Core 3, you can use local functions:
#{
void RenderName(string name)
{
<p>Name: <strong>#name</strong></p>
}
RenderName("Mahatma Gandhi");
RenderName("Martin Luther King, Jr.");
}
https://learn.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-3.1#razor-code-blocks
As #scott pointed out in his answer, local functions are finally available as of .NET Core 3. In prior versions one can resort to templated Razor delegates.
But none of the answers addresses the question "what happened to the App_Code folder?" The aforementioned features are local solutions, that is, helper functions defined in these ways cannot be shared between multiple views. But global helper functions could often be more convenient than the solutions MS provide out-of-the-box for view-related code re-use. (Tag helpers, partial views, view components all have their cons.) This was thoroughly discussed in this and this GitHub issue. According to these discourses, unfortunately, there's not much understanding from MS's side, so not much hope is left that this feature will be added any time soon, if ever.
However, after digging into the framework sources, I think, I could come up with a viable solution to the problem.
The core idea is that we can utilize the Razor view engine to look up an arbitrary view for us: e.g. a partial view which defines some local functions we want to use globally. Once we manage to get hold of a reference to this view, nothing prevents us from calling its public methods.
The GlobalRazorHelpersFactory class below encapsulates this idea:
public interface IGlobalRazorHelpersFactory
{
dynamic Create(string helpersViewPath, ViewContext viewContext);
THelpers Create<THelpers>(ViewContext viewContext) where THelpers : class;
}
public class GlobalRazorHelpersOptions
{
public Dictionary<Type, string> HelpersTypeViewPathMappings { get; } = new Dictionary<Type, string>();
}
public sealed class GlobalRazorHelpersFactory : IGlobalRazorHelpersFactory
{
private readonly ICompositeViewEngine _viewEngine;
private readonly IRazorPageActivator _razorPageActivator;
private readonly ConcurrentDictionary<Type, string> _helpersTypeViewPathMappings;
public GlobalRazorHelpersFactory(ICompositeViewEngine viewEngine, IRazorPageActivator razorPageActivator, IOptions<GlobalRazorHelpersOptions>? options)
{
_viewEngine = viewEngine ?? throw new ArgumentNullException(nameof(viewEngine));
_razorPageActivator = razorPageActivator ?? throw new ArgumentNullException(nameof(razorPageActivator));
var optionsValue = options?.Value;
_helpersTypeViewPathMappings = new ConcurrentDictionary<Type, string>(optionsValue?.HelpersTypeViewPathMappings ?? Enumerable.Empty<KeyValuePair<Type, string>>());
}
public IRazorPage CreateRazorPage(string helpersViewPath, ViewContext viewContext)
{
var viewEngineResult = _viewEngine.GetView(viewContext.ExecutingFilePath, helpersViewPath, isMainPage: false);
var originalLocations = viewEngineResult.SearchedLocations;
if (!viewEngineResult.Success)
viewEngineResult = _viewEngine.FindView(viewContext, helpersViewPath, isMainPage: false);
if (!viewEngineResult.Success)
{
var locations = string.Empty;
if (originalLocations.Any())
locations = Environment.NewLine + string.Join(Environment.NewLine, originalLocations);
if (viewEngineResult.SearchedLocations.Any())
locations += Environment.NewLine + string.Join(Environment.NewLine, viewEngineResult.SearchedLocations);
throw new InvalidOperationException($"The Razor helpers view '{helpersViewPath}' was not found. The following locations were searched:{locations}");
}
var razorPage = ((RazorView)viewEngineResult.View).RazorPage;
razorPage.ViewContext = viewContext;
// we need to save and restore the original view data dictionary as it is changed by IRazorPageActivator.Activate
// https://github.com/dotnet/aspnetcore/blob/v3.1.6/src/Mvc/Mvc.Razor/src/RazorPagePropertyActivator.cs#L59
var originalViewData = viewContext.ViewData;
try { _razorPageActivator.Activate(razorPage, viewContext); }
finally { viewContext.ViewData = originalViewData; }
return razorPage;
}
public dynamic Create(string helpersViewPath, ViewContext viewContext) => CreateRazorPage(helpersViewPath, viewContext);
public THelpers Create<THelpers>(ViewContext viewContext) where THelpers : class
{
var helpersViewPath = _helpersTypeViewPathMappings.GetOrAdd(typeof(THelpers), type => "_" + (type.Name.StartsWith("I", StringComparison.Ordinal) ? type.Name.Substring(1) : type.Name));
return (THelpers)CreateRazorPage(helpersViewPath, viewContext);
}
}
After introducing the singleton IGlobalRazorHelpersFactory service to DI, we could inject it in views and call the Create method to acquire an instance of the view which contains our helper functions.
By using the #implements directive in the helper view, we can even get type-safe access:
#inherits Microsoft.AspNetCore.Mvc.Razor.RazorPage
#implements IMyGlobalHelpers
#functions {
public void MyAwesomeGlobalFunction(string someParam)
{
<div>#someParam</div>
}
}
(One can define the interface type to view path mappings explicitly by configuring the GlobalRazorHelpersOptions in the ordinary way - by services.Configure<GlobalRazorHelpersOptions>(o => ...) - but usually we can simply rely on the naming convention of the implementation: in the case of the IMyGlobalHelpers interface, it will look for a view named _MyGlobalHelpers.cshtml at the regular locations. Best to put it in /Views/Shared.)
Nice so far but we can do even better! It'd be much more convenient if we could inject the helper instance directly in the consumer view. We can easily achieve this using the ideas behind IOptions<T>/HtmlLocalizer<T>/ViewLocalizer:
public interface IGlobalRazorHelpers<out THelpers> : IViewContextAware
where THelpers : class
{
THelpers Instance { get; }
}
public sealed class GlobalRazorHelpers<THelpers> : IGlobalRazorHelpers<THelpers>
where THelpers : class
{
private readonly IGlobalRazorHelpersFactory _razorHelpersFactory;
public GlobalRazorHelpers(IGlobalRazorHelpersFactory razorHelpersFactory)
{
_razorHelpersFactory = razorHelpersFactory ?? throw new ArgumentNullException(nameof(razorHelpersFactory));
}
private THelpers? _instance;
public THelpers Instance => _instance ?? throw new InvalidOperationException("The service was not contextualized.");
public void Contextualize(ViewContext viewContext) => _instance = _razorHelpersFactory.Create<THelpers>(viewContext);
}
Now we have to register our services in Startup.ConfigureServices:
services.AddSingleton<IGlobalRazorHelpersFactory, GlobalRazorHelpersFactory>();
services.AddTransient(typeof(IGlobalRazorHelpers<>), typeof(GlobalRazorHelpers<>));
Finally, we're ready for consuming our global Razor functions in our views:
#inject IGlobalRazorHelpers<IMyGlobalHelpers> MyGlobalHelpers;
#{ MyGlobalHelpers.Instance.MyAwesomeGlobalFunction("Here we go!"); }
This is a bit more complicated than the original App_Code + static methods feature but I think this is the closest we can get. According to my tests, the solution also works nicely with runtime compilation enabled. I haven't had the time so far to do benchmarks but, in theory, it should generally be faster than using partial views as the shared view is looked up only once per consumer view and after that it's just plain method calls. I'm not sure about tag helpers though. It'd be interesting to do some benchmarks comparing them. But I leave that up to the adopter.
(Tested on .NET Core 3.1.)
Update
You can find a working demo of this concept in my ASP.NET boilerplate project:
Infrastructure (relevant files are only those whose name contains GlobalRazorHelpers)
Registration
Helper interface sample
Helper implementation sample
Usage sample
The #helper directive was removed since it was incomplete and its current design did not fit in the new 'ASP.NET 5 way'. One of the reasons is that helpers should be declared in the App_Code folder while ASP.NET 5 has no concept of special folders. Therefore the team decided to temporarily remove the feature.
There are plans to bring it back in the future though. See this and this.
You can easily replace that "feature" with a ViewComponent (and a TagHelper if you want). ASP.NET Core is much more friendly to web designers, and the ViewComponents allow you to write HTML without any (weird to most) razor code.
For example:
Create a SayComponent : ViewComponent class:
public class SayComponent : ViewComponent
{
public void Render(string message)
{
return View(message);
}
}
Create a View file under Views/Shared/Say/Default.cshtml with just
#model string
<div>Message: #Model.</div>
And call it:
#await Component.RenderAsync("Say", "some message")
For a better experience, add this to your _ViewImports.cshtml file:
#addTagHelper *, YourSolutionName
And then you can use it as a tag helper:
<vc:say message="some message"></vc:say>
How about using partials to recreate reusable tags?
MyProject/Views/Shared/_foo.cshtml
#model string
<div>#Model</div>
MyProject/Views/Courses/Index.cshtml
#{
Layout = "_Layout";
}
<div>
<partial name="_foo" model="foo" />
<partial name="_foo" model="bar" />
<partial name="_foo" model="baz" />
</div>

Bundle Helper for bundling and splitting coffeescript

I was experimenting with Bundle and Minification in MVC4 and came across an interesting problem.
I am using Coffeescript and I would like a Render helper that works a bit like the #Scripts.Render() method.
For example, let's say I have this bundle config:
new ScriptBundle("~/bundle/appfiles").Include(
"~/Scripts/app/sample.js",
"~/Scripts/app/myApp.js");
In the cshtml, when I do #Scripts.Render() I get different results based on the debug setting in the web.config. If debug is true I get one script tag per file, otherwise I get a single script tag that returns the bundled and minified js. This is fine.
Let-s assume now that I want to do the same with my Coffeescripts. I create a bundle like this:
new Bundle("~/bundle/appfiles", new CoffeeBundler(), new JsMinify()).Include(
"~/Scripts/app/sample.coffee",
"~/Scripts/app/myApp.coffee");
The problem now is that if I use #Scripts.Render() I get, while in debug, one script per file but this is not transformed at all. The only use I could do is this:
<script type="text/javascript" src="#(BundleTable.Bundles.ResolveBundleUrl("~/bundle/appfiles"))"></script>
But this will, even in debug mode, bundle everything together and then minify, which of course is not what I want.
I have tried to create a Coffee.Render() helper similar to the Scripts one but it uses the AssetManager class which is internal to the System.Web.Optimization assembly.
I was wondering if you have an idea on how to do this in a clean way (i.e: using the available public classes, not copying and pasting the whole AssetManager code, not doing fancy Directory.EnumerateFiles when creating the bundle).
Thanks!
PS: I know that a quicker solution would be to use Mindscape Workbench and bundle the generated js files, I am looking for something that uses what the framework has, maybe also avoiding to have to tell the team to install a tool that people may not like...
In the end I went for a HtmlHelper solution for this. Still in early stage but working as I would like. It is detailed in a blog post for the time being.
Here is the full Helper code in case the blog goes lost...
public static class HtmlHelperExtensions
{
public static MvcHtmlString RenderCoffeeBundle(this HtmlHelper htmlHelper, string virtualPath)
{
if (String.IsNullOrEmpty(virtualPath))
throw new ArgumentException("virtualPath must be defined", "virtualPath");
var list = GetPathsList(virtualPath);
//TODO: Nice and cleaner EliminateDuplicatesAndResolveUrls(list);
var stringBuilder = new StringBuilder();
foreach (string path in list)
{
stringBuilder.Append(RenderScriptTag(path));
stringBuilder.Append(Environment.NewLine);
}
return MvcHtmlString.Create(stringBuilder.ToString());
}
private static IEnumerable<string> GetPathsList(string virtualPath)
{
var list = new List<string>();
if (BundleResolver.Current.IsBundleVirtualPath(virtualPath))
{
if (!BundleTable.EnableOptimizations)
{
foreach (var path in BundleResolver.Current.GetBundleContents(virtualPath))
{
var bundlePath = "~/autoBundle" + ResolveVirtualPath(path.Replace("coffee", "js"));
BundleTable.Bundles.Add(new Bundle(bundlePath, new CoffeeBundler()).Include(path));
// TODO: Get the actual CustomTransform used in the Bundle
// rather than forcing "new CoffeeBundler()" like here
list.Add(bundlePath);
}
}
else
list.Add(BundleResolver.Current.GetBundleUrl(virtualPath));
}
else
list.Add(virtualPath);
return list.Select(ResolveVirtualPath).ToList();
}
private static string RenderScriptTag(string path)
{
return "<script src=\"" + HttpUtility.UrlPathEncode(path) + "\"></script>";
}
private static string ResolveVirtualPath(string virtualPath)
{
return VirtualPathUtility.ToAbsolute(virtualPath);;
}
}
I'm sorry I'm not addressing your exact question, but I do want to speak to your PS at the end of the post.
At this time, I don't really think we have a "no tools" story, but I do agree with the sentiment of "using what the framework has".
To that end, I would strongly recommend using TypeScript. You don't have to learn a new language (like you do with CoffeeScript) and yet it gives you a strongly-typed version of JavaScript that you can use a lot more like c# (with type validation etc.).
It will take you 20 mins to go through some of the tutorials:
http://www.typescriptlang.org/Playground/
Or, better yet, have a look at the BUILD session from the fall:
http://channel9.msdn.com/Events/Build/2012/3-012
Btw...if this isn't a direction you are wanting to go, no worries...I just find a lot of devs don't even know about TypeScript yet as an option.
Hope this helps in your quest to simplify things for your team.
Cheers.

AS3 internal and custom namespaces

I have the following packages:
spark
spark.engine
Within spark I have a class SeCore; and within spark.engine I have SeStepper and SeKeyboard.
What I'm trying to achieve is have SeCore as being the only class that can create an instance of SeStepper or SeKeyboard. This can be achieved by moving SeCore into the spark.engine package and making the other two classes internal, but I'd like to have SeCore in the spark package if possible.
I've tried making my own namespace to handle this, like so:
package spark.engine
{
import spark.namespaces.spark_core;
use namespace spark_core;
spark_core class SeStepper extends SeObject
{
//
}
}
However I get the error:
1116: A user-defined namespace attribute can only be used at the top
level of a class definition.
Are there any other approaches I can take to achieve what I'm after?
99% of the time, marking anything as 'internal' is a bad idea. It's better to have a naming convention for 'off-limits' classes and members, and allow developers to go there at their own risk. Marking things as 'internal' or 'private' is something that should only be done rarely, and with great forethought.
However, you could enforce this behavior at run time by using a read-only property in SeCore and checking its value from SeStepper and SeKeyboard.
Following is pseudocode, haven't used AS3 in a while.
In SeCore
private var _createAuthorized = false;
public function get CreateAuthorized():boolean {return _createAuthorized;}
private function createSeStepper(){
_createAuthorized = true;
var obj = new SeStepper(this)
_createAuthorized = false;
return obj;
}
in SeStepper
public function SeStepper(core:SeCore){
if (!core.CreateAuthorized) throw new Error("Only SeCore can do this");
}
I can't agree with the answer, i mean making things public is way to invite hackers. I can execute any public functions in any flash running on my computer in any context i want, i can even override their execution in memory since they are easy to find, whereas doing something like that with private/internal functions is almost impossible.

Maximum 'Units of Work' in one page request?

Its not One is it? I have a method that gets five Lists from different repositories. Each call opens and closes a new Datacontext. Is this ok to do or should I wrap everything in One datacontext. In this case it is not straightforward to use the same datacontext, but i am afraid that opening and closing numerous datacontext in one page request is not good.
Here is an article on just that subject...
Linq to SQL DataContext Lifetime Management
He recommends one per request and I have implemented that pattern in a few applications and it has worked well for me.
He talk a little about that in is article... His quick and dirty version makes a reference to System.Web and does something like this:
private TDataContext _DataContext;
public TDataContext DataContext
{
get
{
if (_DataContext == null)
{
if (HttpContext.Current != null)
{
if (HttpContext.Current.Items[DataContextKey] == null)
{
HttpContext.Current.Items[DataContextKey] = new TDataContext();
}
_DataContext = (TDataContext)HttpContext.Current.Items[DataContextKey];
}
else
{
_DataContext = new TDataContext();
}
}
return _DataContext;
}
}
But then he recommends you take the next step and get rid of the reference to System.Web and use dependency injection and create your own IContainer that could determine the life span of your datacontext based on whether your running in unit test, web application, etc.
Example:
public class YourRepository
{
public YourRepository(IContainer<DataContext> container)
{
}
}
then replace HttpContext.Current.Items[DataContextKey] with _Container[DataContextKey]
hope this helps...
I use on Unit of Work per request and built a IHttpModule that manages unit of work lifecycle, creating it on request and diposing it afterwards. The current unit of work is stored in HttpContext.Current.Items (hidden in Local.Data).

Access to global application settings

A database application that I'm currently working on, stores all sorts of settings in the database. Most of those settings are there to customize certain business rules, but there's also some other stuff in there.
The app contains objects that specifically do a certain task, e.g., a certain complicated calculation. Those non-UI objects are unit-tested, but also need access to lots of those global settings. The way we've implemented this right now, is by giving the objects properties that are filled by the Application Controller at runtime. When testing, we create the objects in the test and fill in values for testing (not from the database).
This works better, in any case much better than having all those objects need some global Settings object --- that of course effectively makes unit testing impossible :) Disadvantage can be that you sometimes need to set a dozen of properties, or that you need to let those properties 'percolate' into sub-objects.
So the general question is: how do you provide access to global application settings in your projects, without the need for global variables, while still being able to unit test your code? This must be a problem that's been solved 100's of times...
(Note: I'm not too much of an experienced programmer, as you'll have noticed; but I love to learn! And of course, I've already done research into this topic, but I'm really looking for some first-hand experiences)
You could use Martin Fowlers ServiceLocator pattern. In php it could look like this:
class ServiceLocator {
private static $soleInstance;
private $globalSettings;
public static function load($locator) {
self::$soleInstance = $locator;
}
public static function globalSettings() {
if (!isset(self::$soleInstance->globalSettings)) {
self::$soleInstance->setGlobalSettings(new GlobalSettings());
}
return self::$soleInstance->globalSettings;
}
}
Your production code then initializes the service locator like this:
ServiceLocator::load(new ServiceLocator());
In your test-code, you insert your mock-settings like this:
ServiceLocator s = new ServiceLocator();
s->setGlobalSettings(new MockGlobalSettings());
ServiceLocator::load(s);
It's a repository for singletons that can be exchanged for testing purposes.
I like to model my configuration access off of the Service Locator pattern. This gives me a single point to get any configuration value that I need and by putting it outside the application in a separate library, it allows reuse and testability. Here is some sample code, I am not sure what language you are using, but I wrote it in C#.
First I create a generic class that will models my ConfigurationItem.
public class ConfigurationItem<T>
{
private T item;
public ConfigurationItem(T item)
{
this.item = item;
}
public T GetValue()
{
return item;
}
}
Then I create a class that exposes public static readonly variables for the configuration item. Here I am just reading the ConnectionStringSettings from a config file, which is just xml. Of course for more items, you can read the values from any source.
public class ConfigurationItems
{
public static ConfigurationItem<ConnectionStringSettings> ConnectionSettings = new ConfigurationItem<ConnectionStringSettings>(RetrieveConnectionString());
private static ConnectionStringSettings RetrieveConnectionString()
{
// In .Net, we store our connection string in the application/web config file.
// We can access those values through the ConfigurationManager class.
return ConfigurationManager.ConnectionStrings[ConfigurationManager.AppSettings["ConnectionKey"]];
}
}
Then when I need a ConfigurationItem for use, I call it like this:
ConfigurationItems.ConnectionSettings.GetValue();
And it will return me a type safe value, which I can then cache or do whatever I want with.
Here's a sample test:
[TestFixture]
public class ConfigurationItemsTest
{
[Test]
public void ShouldBeAbleToAccessConnectionStringSettings()
{
ConnectionStringSettings item = ConfigurationItems.ConnectionSettings.GetValue();
Assert.IsNotNull(item);
}
}
Hope this helps.
Usually this is handled by an ini file or XML configuration file. Then you just have a class that reads the setting when neeed.
.NET has this built in with the ConfigurationManager classes, but it's quite easy to implement, just read text files, or load XML into DOM or parse them by hand in code.
Having config files in the database is ok, but it does tie you to the database, and creates an extra dependancy for your app that ini/xml files solve.
I did this:
public class MySettings
{
public static double Setting1
{ get { return SettingsCache.Instance.GetDouble("Setting1"); } }
public static string Setting2
{ get { return SettingsCache.Instance.GetString("Setting2"); } }
}
I put this in a separate infrastructure module to remove any issues with circular dependencies.
Doing this I am not tied to any specific configuration method, and have no strings running havoc in my applications code.