Making an ASP.NET Core front-end for WordPress – 1

I always try to find an excuse to code, I just love doing it. It rarely ends in a real life usable product, but I’m having a blast doing it.

For my latest project, I thought I would bring you around, just to get back into the blogging game, but also to keep my self on a schedule to, at least try to finalize this project.


It’s no secret, my blog runs on WordPress, it has done so since 2007. I have tried, many times to move to Umbraco, but I never really got there, so here we are.

This project, is a way for me to start that transition. I want to move all public content away from the CMS, into a standalone application based on ASP.NET Core. This way, I will be able to isolate my WordPress backend and have a greater control over my frontend.

I will also like be able to try switching to Umbraco Headless or a full, local, Umbraco install without changing the frontend or needing to rebuild the front-end completely.

I usually use Visual Studio for my programming, but I will try to make this post as “cross platform” as possible.

My project names are all prefixed with NDesoft, feel free to call yours what you want.

I will also use my own WordPress API endpoint, feel free to use that as well. Everything is cached by Cloudflare, so go nuts.

Resources / Documentation

I am using the following resources to help me along in this endeavor:


.NET Core CLI:

WordPress Rest API:


It must be based on ASP.NET Core.

Data access must be isolated from the web app, making it possible to add an App, Rest API or whatever later on without changing the code base.

CMS Api access must be isolated in a way that more can be added later on without rebuilding the applications completely from scratch.

This might make the project a bit over-engineered, but hey, we’re just having some fun here!

Getting started

First you must find a folder suitable for development. There, you open up a console, I prefer PowerShell, and run this command:

dotnet new sln

This creates a new Visual Studio solution file, nothing to it other than that.

Next we create a folder for our application, I call mine for “NDesoft.App”

In this folder we will create a new ASP.NET Core project, using the MVC template:

dotnet new mvc; dotnet sln ../NDesoft.sln add ./NDesoft.Web.csproj

This will create a new ASP.NET Core MVC project, and add it to our solution file.

Next, we need two more projects: One for wrapping the WordPress API, and one used as an interface between the web-app and the WordPress wrapper:

dotnet new classlib -o NDesoft.Wrapper;
dotnet new classlib -o NDesoft.Wrapper.WordPress;
dotnet sln add NDesoft.Wrapper;
dotnet sln add NDesoft.Wrapper.WordPress;

This will create two new folders, each with their own class library, (dll), project and add them to our solution file.

In each folder, the template has created a file called Class1.cs, please delete that. We don’t need that.

We’ll need to add some references between our newly created projects, to make them play nice together.

NDesoft.Web must have a reference to NDesoft.Wrapper and NDesoft.Wrapper.WordPress

NDesoft.Wrapper.WordPress must have a reference to NDesoft.Wrapper

To do that, we need to run the following commands:

dotnet add NDesoft.Web reference NDesoft.Wrapper NDesoft.Wrapper.WordPress;
dotnet add NDesoft.Wrapper.WordPress reference NDesoft.Wrapper;


We also need to install a few packages:

Newtonsoft.Json, AutoMapper and AutoMapper.Extensions.Microsoft.DependencyInjection

Automapper is used later on, but we might as well install it now.

dotnet add NDesoft.Web package automapper;
dotnet add NDesoft.Web package AutoMapper.Extensions.Microsoft.DependencyInjection;
dotnet add NDesoft.Web package Newtonsoft.Json;
dotnet add NDesoft.Wrapper package Newtonsoft.Json;
dotnet add NDesoft.Wrapper.WordPress package automapper;

And now, our solution and projects are up and running and we can start coding.


ASP.NET Core has native dependency injection, and since we are building a highly decoupled platform it makes sense to utilize that. So let’s start by adding a ton of interfaces. These will just be the bare minimum for this post, more will come.

In the NDesoft.Wrapper project, we’ll add a folder called “Interfaces” and under that another called “Helpers”.

In the Helpers folder, we’ll create to interfaces, (One file per interface):


This interface manages requests to the Rest API and deserializes the responds, I might add an interface for the deserialization, but for now it’s handled by this manager.

public interface IRequestManager
    Task<TResult> Get<TResult>(string url, CancellationToken cancellationToken, object parameters = default);


This interface helps us handle URL parameters in a shared way. No copy/pasting anything.

public interface IUrlParameterHelper
    string ConvertToUrlParameters(object parameters);

In the “Interfaces”-folder, we’ll create two new interfaces:


This is an interface that handles everything related to blog posts. It has nothing to do with authors, tags, categories, media, comments, pages and so on, only posts.

Please note the “PostModel”-class, this will be implemented in a bit.

public interface IPosts
    Task<IEnumerable<PostModel>> GetPosts(int currentPage = 1, int? pageSize = default, CancellationToken cancellationToken = default);


The name might change, I do not like the name, but for now it’s IClient. It’s the main entry point handling almost everything.

public interface IClient
    IPosts Posts { get; }


Now we have the basic interfaces going, let’s implement them.

First of we need a class that represents a single blog post:



Place this class in a folder, in the NDesoft.Wrapper project called “Models”.

public class PostModel
    public string Id { get; set; }
    public DateTime Date { get; set; }
    public DateTime Modified { get; set; }
    public string Slug { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public string Excerpt { get; set; }
    public string AuthorId { get; set; }
    public string FeaturedMediaId { get; set; }
    public bool IsSticky { get; set; }
    public IEnumerable<string> CategoryIds { get; set; }
    public IEnumerable<string> TagIds { get; set; }

This class is based off of the response from the following request for a single post:


The properties contains, what I think is, the minimum required number of properties to display a blog post. You might want more or less.

You might want to add a reference to this class in the IPosts interface.


In NDesoft.Wrapper create a folder called Helpers. In here, create a class called RequestManager:

public class RequestManager : IRequestManager
    public static readonly HttpClient httpClient = new HttpClient();
    private readonly string baseUrl;
    private readonly IUrlParameterHelper urlParameterHelper;

    public RequestManager(string baseUrl, IUrlParameterHelper urlParameterHelper)
        this.baseUrl = baseUrl;
        this.urlParameterHelper = urlParameterHelper;

    public virtual async Task<TResult> Get<TResult>(string url, CancellationToken cancellationToken, object parameters = default)
        var fullUrl = this.GetFullUrl(url, parameters);

        var response = await httpClient.GetAsync(fullUrl, cancellationToken).ConfigureAwait(false);

        var bodyContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

        var result = JsonConvert.DeserializeObject<TResult>(bodyContent);
        return result;

    protected virtual string GetFullUrl(string url, object parameters = default)
        var parameterString = this.urlParameterHelper.ConvertToUrlParameters(parameters);
        return $"{baseUrl}{url}{parameterString}";

Worth noting: The constructor takes a string as first parameter. It contains the base URL of the Rest API. The value is, later on, set using app settings. However, I would like to not add it as a parameter, since it adds to the complexity of setting up the dependency injector.

Also noteworthy, this class has a static readonly HttpClient. This way we always use the same HttpClient for all requests. I do know about RestSharp and the like, but I prefer HttpClient as I thinks it’s easier to use.

I have a habit to always pass a Cancellation token into every async method that supports it. To me it makes sense because if a user aborts a request, every subrequest I make on my site will be aborted as well releasing resources.

It might be beneficial to add some caching here to reduce response times and load on the source server.


Next to the RequestManager, add a class called “UrlParameterHelper”:

public class UrlParameterHelper : IUrlParameterHelper
    public string ConvertToUrlParameters(object parameters)
        if (parameters == default)
            return string.Empty;

        var type = parameters.GetType();
        var properties = type.GetProperties();
        var urlBuilder = new StringBuilder();

        if (properties.Any())
            string joinedParams = GetParameterString(parameters, properties);

        return urlBuilder.ToString();

    private static string GetParameterString(object parameters, PropertyInfo[] properties)
        var urlParams = new List<string>(properties.Count());
        foreach (var property in properties)
            var value = property.GetValue(parameters);
            if (value != null)
                var stringValue = value.ToString();
                if (string.IsNullOrWhiteSpace(stringValue) == false)
                    var encodedValue = HttpUtility.UrlEncode(stringValue);
                    var urlParam = $"{property.Name}={encodedValue}";

        var parameterString = string.Join("&", urlParams.ToArray());
        return parameterString;

This class is used to help converting an object to url parameters, making it easier to create url’s with objects rather than string manipulation.

In the future, this class might be extended to handle number and datetime formatting better than it does now, as well as flattening nested properties.


And now, the last class in the NDesoft.Wrapper project, before moving on to the WordPress specific classes. This class should be located in the root of the project.

public class Client : IClient
    public Client(
        IRequestManager requestManager, 
        IPosts posts)
        this.RequestManager = requestManager;
        Posts = posts;

    protected IRequestManager RequestManager { get; }
    public IPosts Posts { get; }

There’s nothing much to this class at the moment, but we will add more in a future post.


Now we move on to some of the WordPress specific implementations.


This is not a class but a folder, we need to create a lot of classes that represents the json returned from the WordPress Rest API, and instead of me posting all those classes I’ll tell you how to generate all those classes.

First get the Json, I use Postman:


Copy the response body and:

In Visual Studio:

Edit -> Paste Special -> Paste JSON As Classes

Or use


In the root of the project, add a class called Posts:

public class Posts : IPosts
    private const string BaseUrl = "/wp/v2/posts";
    private readonly IRequestManager requestManager;

    public Posts(IRequestManager requestManager)
        this.requestManager = requestManager;

    public async Task<IEnumerable<PostModel>> GetPosts(int currentPage = 1, int? pageSize = null, CancellationToken cancellationToken = default)
        var parameters = new
            page = currentPage,
            per_page = pageSize

        var response = await requestManager.Get<IEnumerable<Post>>(BaseUrl, cancellationToken, parameters).ConfigureAwait(false);
        return Mapper.Map<IEnumerable<PostModel>>(response);

Some background here: The method “GetPosts” loads all posts from the API by calling this URL:


However, loading all posts at the same time would be overkill and slow down response times and over time only become slower. So, we need to add some paging parameters to the URL.

How to do that, we’ll look at this page it tells us that the API has two parameters we can use for our needs: “page” and “per_page”. Page, oddly enough is not zero-based so the first page is “1”.


Speaking of AutoMapper, we need some configuration to map the weird WordPress models the more leaner PostModel class. To do that, we need an AutoMapper profile.

Create a folder called “AutoMapperProfiles” and add a class called PostProfile:

public class PostProfile : Profile
    public PostProfile()
        CreateMap<Post, PostModel>()
            .ForMember(dest => dest.Date, m => m.MapFrom(src => src.date_gmt))
            .ForMember(dest => dest.Modified, m => m.MapFrom(src => src.modified_gmt))
            .ForMember(dest => dest.Title, m => m.MapFrom(src => src.title.rendered))
            .ForMember(dest => dest.Content, m => m.MapFrom(src => src.content.rendered))
            .ForMember(dest => dest.Excerpt, m => m.MapFrom(src => src.excerpt))
            .ForMember(dest => dest.AuthorId, m => m.MapFrom(src =>
            .ForMember(dest => dest.FeaturedMediaId, m => m.MapFrom(src => src.featured_media))
            .ForMember(dest => dest.IsSticky, m => m.MapFrom(src => src.sticky))
            .ForMember(dest => dest.CategoryIds, m => m.MapFrom(src => src.categories))
            .ForMember(dest => dest.TagIds, m => m.MapFrom(src => src.tags));

Again, nothing special here. All we do is we flatten out some of the weird constructs of the WordPress json and maps everything to a more lean model.


Now we have setup everything needed to access the WordPress API and have a solid base to build on. All we need to do now is wire everything up in the web project.

Configure AutoMapper

First things first, we need to configure AutoMapper. Open up the Startup-class and add the following method at the bottom of the class:

private void SetupAutoMapper(IServiceCollection services)
    services.AddAutoMapper(cfg =>

All we do here is adding AutoMapper to our services, and adds our PostProfile to the AutoMapper collection.

Setting up the Dependency Injector

Next up, adding our services to the Dependency Injector. Again in the Startup-class add the following method to the bottom of the class

private void SetupWrappers(IServiceCollection services)
    services.AddTransient<IUrlParameterHelper, UrlParameterHelper>();
    var baseUrl = Configuration["WrapperConfig:BaseUrl"];
    services.AddTransient<IRequestManager, RequestManager>((provider) => new RequestManager(baseUrl, provider.GetRequiredService<IUrlParameterHelper>()));
    services.AddTransient<IClient, Client>();

    // Service specifics:
    services.AddTransient<IPosts, Posts>();

All we do here is telling the DI, what services we have, and where to find their implementations. Note that everything uses the NDesoft.Wrapper classes, but only Posts uses the NDesoft.Wrapper.WordPress classes.

Before we’re done here, we need to add the following to the appsettings.json-file:


By doing this, we tell the wrapper where to find the endpoints needed to get the data.

Finishing up Startup

In the ConfigureServices-method, add these two lines at the top of the method:


And now we are set, and can start building our controller.


In the HomeController, remove everything except the Index-method and add the following:

private readonly IClient client;

public HomeController(IClient client)
    this.client = client;

This injects the client into the controller and we’re ready to use it.

Replace the Index-method with this:

public async Task<IActionResult> Index(CancellationToken cancellationToken)
    var posts =  await this.client.Posts.GetPosts(1, 5, cancellationToken).ConfigureAwait(false);
    return View(posts);

This code gets the first 5 posts from my blog and sends them to the view.

Final thing, we need to update the view. Open the file /Views/Home/Index.cshtml and replace everything with this:

@model IEnumerable<NDesoft.Wrapper.Models.PostModel>
@using System.Globalization;
    ViewData["Title"] = "Home Page";

@foreach (var item in Model)
        <a href="/@item.Date.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture)/@item.Slug"><h2>@Html.Raw(item.Title)</h2></a>

Trying it out

Let’s try to run the darn thing:

dotnet build;
dotnet run --project ./NDesoft.Web;

You should now be able to go to http://localhost:5000 or https://localhost:5001 and se something like this:


The source code for this blog post can be found on Github:

Next part

In the next part, I’ll try getting pages, author, tags and categories up and running.

Umbraco and .NET magic

Wouldn’t it be fun, if you could simply call one method on an IPublishedContent, and get any property as the right type, always, without parsing or converting the data, passing any type-parameter or calling different methods? Wouldn’t it be cool if said method knew that a rich text editor property is always an IHtmlString and a content picker is an IPublishedContent rather than a string or an integer? Wouldn’t it be awesome if the same method returning an IPublishedContent could return an integer or a string with no additional code other than a type parameter? And how about this method is seamlessly put on top of Umbraco without interfering with existing code, but still used in the same manner?

Would your mind be blown if I told you it is possible and how to accomplish exactly that?

Basic theory

The idea behind this “method” is basically this:

“Everytime I need a property I have to call GetPropertyValue(), add a type parameter, and a magic string with the alias of the property from which I want the value.

Nine out of ten times, that value is either a string or an int that I have to parse or convert to a different type. Why do I have to pass two values each time? And what if said property is a content picker? I can’t pass IPublishedContent as a type parameter. How should umbraco know if I want a media item or a content item?

If we could “learn” umbraco to automatically give me the right value each time, so I don’t need to know if this property is a string, a media item or a DateTime. It would make our lives a bit easier.

Let’s take a look at some code

First off, we need to know what type, each of our properties have. So we look into our doctypes and each of their properties. We need two informations: Alias and Data Type.

Then we make a small class. Nothing big, just a small one:

public abstract class DocTypeProperty
     protected DocTypeProperty(){}

    public string Alias {get;set;}

This class contains half of what we need, but it’s okay.

Please note, it’s marked as abstract, and it constructor is protected. This is because, it’s purpose is not to be instantiated directly, but to serve as a base / master class, that has to be inherited.

Then we need to store our data type. This is where magic begins:

public class DocTypeProperty<TValue>
    public DocTypeProperty() : base(){}

Is that it?! No!! As I wrote: “The magic begins”.

We have now both information needed to perform the real magic, we know the alias of the property and the type we want the data as. As the smart developer you propably are, you have noticed that I have no parameters in my constructors. That is correct. More on that later.

To instantiate our “DocTypeProperty’s” we do this:

var myProp = new DocTypeProperty<string>(){ Alias = “someAlias” }

Please take note of the variable name: “myProp”. We are going to need that later.

How and when you do this I will not tell in this post, as it’s a complete post on its own. All I can tell is T4 templating IS an option!

So now we have our alias, and the type we want to convert the value into. But we are not done yet.

As I wrote ealier, I would like this to be seamlessly integrated on top of umbraco, but I cannot just pass my DocTypeProperty into the GetPropertyValue-method as is. To do this, we need to add an implicit operator, that can “transform” our neet DocTypeProperty to an old school string containing our alias:

public static implicit operator string(DocTypeProperty prop)
    return prop.Alias;

Now we can do this:


This works exactly like oldschool umbraco. No magic yet, other than the implicit operator.

Now we need to get rid of the type parameter. To do this, we need to add an extension method to IPublishedContent:

public static class PublishedContentExtensions
    public static TValue GetPropertyValue<TValue>(this IPublishedContent content , DocTypeProperty<TValue> property)
        return content.GetPropertyValue<TValue>(property);

This will result in an overload to the standard umbraco GetPropertyValue-method.
Now, we can do this:


See, simple. This will return the value of the property as a string. But this is great for standard data types, but what about other types like media pickers, content pickers, multiitem whatever picker? We still need to learn our DocTypeProperty-class, how to handle those types.

So we add this method to the generic DocTypeProperty:

public virtual TValue Map(IPublishedContent content)
    return content.GetPropertyValue<TValue>(this);

This is the generic / default mapper. It handles all default umbraco data types, like string, DateTime, int and so on.

Furthermore, we need to update our own GetPropertyValue()-method:

return property.Map(content);

So this is all jolly, but we still need to be able to get an IPublishedContent instead of just an integer with a node/media id. To do this, we need to override the mapper:

public class MediaPickerProperty : DocTypeProperty<IPublishedContent>
    public override IPublishedContent Map(IPublishedContent content)
        var umbracoHelper = new UmbracoHelper(UmbracoContext.Current); // This should not be done each time we call this method. Put it outside in a cached field!
        return umbracoHelper.TypedMedia(content.GetPropertyValue<int>(this));

Now we can make an instance of the MediaPickerProperty:

var myMediaProp = new MediaPickerProperty(){ Alias = “someMediaPicker”};

Again, note the property name. Now I have a few options:

The old fashioned:

someContent.GetPropertyValue<int>(“alias”) // returns an int.
someContent.GetPropertyValue<int>(myMediaProp) // Also returns an int.

and the new:

someContent.GetPropertyValue(myMediaProp) // Returns IPublishedContent.

And if I did this:


It would return string.

But let’s say we have myProp registered as DocType<string>, but I would like it as an IHtmlString more than just once, but not as often as I want it as string. I don’t want to have the same property registered twice. And what if I have more properties that needs to be IHtmlString once or twice?

Well, first we need to define an IHtmlStringProperty-class, and create a mapper. Like we did with the MediaPickerProperty. The mapper however, is a bit simpler, just:

return new HtmlString(content.GetPropertyValue<string>(this));

Now I need to be able to transform my DocTypeProperty<string> into my IHtmlStringProperty.

To do this, as simple as possible, we need to add a method to the base DocTypeProperty:

public TProp As<TProp>()
    where TProp : DocTypeProperty, new()
    return new TProp() { Alias = this.Alias };

It doesn’t get any simpler than that. And now you can see why I needed to have a parameterless constructor. Otherwise, this would have been a pain in the arse.

So now I can do this:

someContent.GetPropertyValue(myProp) // string

someContent.GetPropertyValue(myProp.As<IHtmlStringProperty>()); // IHtmlString

As you can see, this is completely transparent. You can write less code. , and you don’t have to remember hundreds of aliases, and update each and everyone of them when they change. You have the alias registered once. Especially if you autogenerates the properties using T4. You can always go back to umbraco’s own GetPropertyValue. Just add a type parameter. You have complete control over what types your property values are fetched as and the code is 100% reusable!

We use this approach, including the T4 templating, in all our new projects, and we are able to put upon existing applications, without interfering with code already written.

Real MVC App using Umbraco – revisited

So, it seems that my latest post has generated a lot of debate throughout the umbraco community. Thank you!

Me and my coworkers at Lund & Andresen IT (in Danish), has been using this method for a couple of months now, and we’ve found a couple of issues that I didn’t think of. But now I have taken in some input from the community as well as from my coworkers and now I am revisiting the method.

The main theme throughout the post still remains: No data access or umbraco logic in the views! The views must only display what they are being served. Nothing more, nothing less.

Where I was wrong

In the old post, I suggested that all doctypes must be mapped to a model using a mapper class. This is no longer true! The problem quickly showed it self when building a large site: With mappers, we essentially get waay to much data per view, and we generalize how data is extracted without taking in account for different circumstances. An other problem was that our controllers no longer have any work to do, other than calling a mapper and serving a view. So my MVC (Model View Controller) became a “MMVC” (Model Mapper View Controller), which was not intended.

Sample project

As promised on twitter, I have made a simple sample project that illustrates my points. Please feel free to download it and tell me what you think.

What has changed

Not that much has changed. I have only redefined the mapper roles and reinstated the controller roles:


I have two types of models in mind for a basic umbraco site:

  • Document type model
  • Data model

Document type models represent real document types. They have the same inheritance structure as doctypes, meaning if a doctype is a child of a master doctype so must the representative model.
So if you have a doctype tree looking like this:

  • MasterDocType
    • TextPage

Then you will have these two models:

public class MasterDocTypeModel{}
// Please note, we inherit from the MasterDocTypeModel:
public class TextPageModel : MasterDocTypeModel {}

This way, when you add a property on the MasterDocType, you will only have to add said property on one model.

Besides containing properties mapped from a doctype, a Document Type Model, may also contain other properties, like menu items.

Data models are models that are not in any way related to doctypes. A great example is for menus. You don’t want to build an entire document type model for each item and descended items in a menu tree, when the only information you want are “Name”, “Url”, “IsActive” and “ChildNodes”.

This is where data models come in. A menu would list NavigationItemModels instead of a mixture of TextPageModel, NewsArchiveModel and so on and so forth.


Controllers are more important than ever!

Controllers are the ones that builds models and serves them to the views. In other words, controllers build Document Type Models, and passes them to the views.

Again, I have two different types of controllers:

  • Master controllers
  • Document type controllers

Essentially, there must be a master controller for each master doctype, (a master doctype is a document type that has children), and a document type controller for each document that has a template attached.

So in my example above, we should have a master controller called MasterDocTypeController. This controller inherits from Umbraco.Web.Mvc.RenderMvcController and should not contain any actions!
The only thing these controllers must contain are two overloads of the inherited View()-method:

protected ViewResult View(MasterDocTypeModel model)
    return this.View(null, model);
protected ViewResult View(string view, MasterDocTypeModel model)
    // TODO: Set master doctype model values.
    return base.View(view,model);

By creating these two methods, we are able to set values that are to be set on all models that inherits from MasterDocTypeModel.

Please note, Master controllers, can also inherit from each other, depending on the doctype structure.

A doctype controller, would then inherit from this master controller, and set values essential for said doctype and return the result from the View-method created before.


Mappers have a much lesser role, but not less important role! Mappers are used to map data models. Data models are shared across controllers and are not doctype dependent, so we will only have a few properties to map, and can to it in a very generalized way.

Data models are inheritable, and this inheritability must be addressed in the mappers as well. It’s quite simple, so why not just do it when we build the mappers?
A mapper class is a static class with a single static method called Map().

It looks like this:

internal static class NavigationItemMappers
    internal static TModel Map(TModel model, IPublishedContent content)
        where TModel : NavigationItemModel
        // TODO: Add mapping logic here.
        return model;

Please note that the method is generic. This way we can call the mapper like so: Map(new SomeInheritedModel(), CurrentPage) and get SomeInheritedModel back, on which we can continue our work without type casting. This is quite useful in linq statements:

IEnumerable original = from c in someSource
                                            select NavigationItemMappers.Map(new NavigationItemModel(),CurrentPage);

// This works, as well as the one above:
IEnumerable inherited = from c in someSource
                                            select NavigationItemMappers.Map(new SomeInheritedModel(){
                                            SomeProperty = c.SomeValue

// This also works:
IEnumerable inheritedToOriginal = from c in someSource
                                                       select NavigationItemMappers.Map(new SomeInheritedModel(){
                                                       SomeProperty = c.SomeValue

// This does not:
IEnumerable originalToInherited = from c in someSource
                                                      select NavigationItemMappers.Map(new NavigationItemModel(),CurrentPage);

As you see, same mapper, different methods and different types, meaning greater flexibility.

A not on the mappers: Mappers should not map lists or child elements! These can differ from page to page. What works on a front page might not work as well on descending pages.

To summarize

The original post is still valid!
Controllers must have greater responsibility and must be the ones to handle doctypes, not mappers!
Mappers should map only simple data models and not map lists or child elements.
Controllers must use mappers as they see fit. Controllers control the mappers, not the other way around!

How to make localized models in Umbraco MVC

MVC, it’s the sh*t. Everything is so much easier when we use MVC. So when Umbraco came out with version 5, I was super happy, because I could now use my favorite framework on my favorite CMS. Then Umbraco killed v5 and we had to go back to webforms and simple razors…

BUT, then Umbraco announced they would implement MVC in the v4 branch and port many of the MVC features from v5 to v4. I was happy, for a while, I feared v4+ would end up just like v5. Mostly because of the weird mix of MVC and webforms. But no, the mix was elegant and seamlessly and super fast, so we began using it at my work. Everything was Good!

UNTIL, we had to make some more advanced stuff, like forms. Yeah, some of our customers wants forms, I know right! So we build a couple of forms, and the problems started to appear.

Umbraco is a “Content Management System”, meaing it manages content. One of the main forces of Umbraco is its ability to handle multiple languages. And the customers know that, well most of them do. So our customers wanted to be able to localize all the texts on the forms. This is something Umbraco cannot do, not easily and definitely not pretty.

When I build MVC forms I usually have a view model or two:

public string Name { get; set; }
public DateTime Birthday { get; set; }
public int NumberOfKids { get; set; }

This is a decent model. In MVC, I would build a form in one of three ways:

// One:

// Two



// Three



I would preferably go for number one, or in some cases where I need to be in control of the markup, number two. I see no reason to use anything but EditorFor().

So from where do I get labels, display names and validation messages?

In MVC I would do something like this:

[Display(Name="Name", ResourceType=typeof(SomeResourceFile))]
[Required(ErrorMessageResourceName = "NameRequired", ResourceType = typeof(SomeResourceFile))]
public string Name { get; set; }

[Display(Name = "Birthday", ResourceType = typeof(SomeResourceFile))]
[Required(ErrorMessageResourceName = "BirthdayRequired", ResourceType = typeof(SomeResourceFile))]
public DateTime Birthday { get; set; }

[Display(Name = "NumberOfKids", ResourceType = typeof(SomeResourceFile))]
[Required(ErrorMessageResourceName = "NumberOfKidsRequired", ResourceType = typeof(SomeResourceFile))]
public int NumberOfKids { get; set; }

In MVC, I would get my localized texts from a Resource file, but Umbraco has no resource files, nor does it have a resource provider or some feature that allows to extract texts from the dictionary and add it to our model attributes. And I, for one, don’t think we can hand over a product being part CMS and part resource files. So how do I solve that problem.

It’s quite simple. No I am NOT going to write a resource provider for umbraco!

What I am doing is actually as simple as extending the attributes I use. So lets take the first one, Display. What I essentially want is just to pass in my dictionary key and then get a text from Umbraco.  The problem here is, I cannot extend DisplayAttribute, it would have been overkill anyway, so instead I will extend the DisplayNameAttribute-class:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public sealed class UmbracoDisplayAttribute : DisplayNameAttribute
    // This is a positional argument
    public UmbracoDisplayAttribute(string dictionaryKey) : base(dictionaryKey)

This is simple, but all we get now, is just the key to the Umbraco dictionary. I want the value. Also easy. We just need to override one property:

public override string DisplayName
        return umbraco.library.GetDictionaryItem(base.DisplayName);

What this does, is each time I, or the framework, needs to get the DisplayName, we return the value from the dictionary. Simple as that.

So to use this new attribute, all you need to do is use this:



The other attribute (RequiredAttribute) is a bit different, it’s a validation attribute.

But still, equally able of being extended:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
sealed class UmbracoRequiredAttribute : RequiredAttribute
    public UmbracoRequiredAttribute(string dictionaryKey)
        this.ErrorMessage = dictionaryKey;

Please note, I don’t have a DisplayName property available, so I cannot set or override that one. What I can do instead, is setting the ErrorMessage property. But I cannot override that one either. It’s okay, I just won’t do it. Now you might think, “hey dumbass, you haven’t gotten anything from the dictionary yet!” You’re absolutely right, I haven’t.

We need to override a method called FormatErrorMessage. It looks like this:

public override string FormatErrorMessage(string name)
    return umbraco.library.GetDictionaryItem(base.FormatErrorMessage(name));

Please note, I still call the base method. This is because the base method gives us our error message (in this case, a dictionary key). If our key contained a, I think this is true, “{0}” the display name of the field would be added.

If you where to run this, you will see, that our required-attribute is not being used client side. This is because the RequiredAttribute does not implement the IClientValidatable-interface. So we must implement that:

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(System.Web.Mvc.ModelMetadata metadata, ControllerContext context)
    // Kodus to "Chad"
    yield return new ModelClientValidationRule
        ErrorMessage = this.ErrorMessage,
        ValidationType = "required"

If you run the code again, you will find, that the client side, and the server side validation messages are now localized, using the Umbraco dictionary.

This approach described here, can be used on most of the different attributes, we use in MVC. Happy coding!

Database design on user defined properties

As a developer, I often get across some database designs, that are quite complex caused by a developer not quite understanding the problem (we’ve all been there!), and therefore cannot solve it correctly.

The problem is as follows (or similar):

You have 2+ tables:

No references

Initial tables – no references

It’s quite simple, you have two types of data (media and documents), that you want to store in your database. I get that, I would too.

Now the requirements are as follows:

Both media and document has a set of user defined properties.

Said properties must store the following values: Type and Value, and a reference to both Media and Document.

There are a couple of ways to solve this lil’ problem, one (the one I encounter the most):

References(1) - Database Inheritance

Property-table added and References are added to media and document.

In this setup the Property-table knows about both media and document. We could make the two foreign keys nullable, either way we depend heavily on our code to keep media and document properties separated. And what happens if we add an other type (say Users), then we have to add a new foreign key to the property-table, and expand our code even more.

An other approach is this:

<img class="size-full wp-image-762" alt="References(2) – Database Inheritance" src=" cialis overnight shipping.png” width=”404″ height=”444″ srcset=” 404w,×300.png 272w” sizes=”(max-width: 404px) 100vw, 404px” />

Media and document property references are stored in separate tables.

I must admit, I have done this one as well as the other one, and just admit it, so have you at some point!

So what are the pro’s and con’s of this setup: Well the pros are simple, neither media or document are referenced in the property table, we can have as many properties as we want per media and document, and we can quite simple add other types, such as Users. BUT:

When we have this setup, we must rely heavily on our code to help us not to have the same property on more than one media, and to ensure we don’t mix media properties with documents and users. And if we add an other type (Users) we must create, not only one, but two new tables, and still expand a complex code to handle that new type as well as the other types.

So how can we solve this problem?

We have Media, Documents and more types, that has dynamic  properties without the other types must know about it, we could do this:

References(3) – Database Inheritance

Each type now has its own set of properties

Yeah, I’ve also done this one. And this is almost, (I wrote, almost), as bad as the other ones. Well no property can be on more than one media (or document, or whatever), and no property can be on both media and document, so whats the problem?!

Well, for starters, we have to tables instead of one, per type. If we add an other field to our properties, we must add them to all of our *Property-tables. And if we want to list all properties, including the media/document/user/whatever it is attached to, it’s nearly impossible.

So here’s the solution, I find most fitting for the problem:

References, Inheritance – Database Inheritance

Added a Node-table, with the shared fields from Media and Document. Removed ID- and Name-fields from Media and Document, added a NodeID field, as both PK and FK. Added a Property-table, that references the Node-table.

So, this is my solution. I have added a Node-table, with the shared fields from Media and Document (ID and Name). Removed ID- and Name-fields from Media and Document, added a NodeID field, as both primary key and foreign key, this field must NOT be autoincremented! It will not work, then I added a Property-table, that references the Node-table.

The pros and cons: The pros are easy, One table per type, each type gets its ID from the Node-table, all properties are stored in one table, referencing the Node-table, so a Document can get its properties, using only its primary key. No property can ever be on two entities at once, and no entity knows about other entities or properties, except its own.

The cons are, that we must have some code that handles the inheritance. When I make a SELECT * FROM Media, I must make a JOIN on the Node-table as well. If you’re a .NET developer, like I, then you should take a look at the Entity Framework, as it handles this smoothly. I will write a post on that later on.

IEnumerable, why use it?

Okay, first off: I really love the IEnumerable<T> interface, and I use it excessively throughout my applications.

Almost any list or collection throughout the .NET framework implements this interface. It exposes only one method (GetEnumerator), but this method is your friend in almost any circumstance.

This method returns an Enumerator, which again exposes methods used to traverse (or loop through) the collection. This means you can make a method definition like this:

public void MyMethod(IEnumerable<string> someEnumerable)


I could call this method with any sort of collection, it could be string[], List<string>, IList<string>, IQueryable<string> or even a basic IEnumerable<string>. I don’t give a damn. I don’t care what the implementation is, I just want a collection to work with, nothin’ more.

This means I don’t need to force other developers who use my code, to pass an array or a List or some custom collection, they just pass whatever collection they have, and I will be able to work with it. That’s awesome!

But wait! How do you get an IEnumerable<T> in the first place? How can we make our own?

Well, in “ye olde times” one would make an abomination like this:

public List<string> MyMethod()
List<string> myResult = newList<string>();
for (int i = 0; i < dataSource.Length; i++)
// Do some work.
return myResult;

Can you see what’s wrong here?

There’s actually more than one thing that’s wrong with this snippet.

First off: When we return a specific implementation, in this case List<T>, we force our code to use this implementation. We kinda dictates the use of our result which is a major drawback on agile Development. What if the consumer don’t want or need a list?

Second: In line 3, we create an instance of an object we actually don’t need, so that we can return a list.

Third: We loop through a collection of an unknown size. This Collection could potentially contain a billion items.

Fourth: We have to wait until the loop has ended. Which could take forever. Think about what would happen to your app, when you loop though a billion items and only need the first five.

This is where .NET provides a concept of Enumerators. These are methods that only returns data when said data is ready to be returned on not when all data is ready to be returned. And it is actually the same method called from the GetEnumerator()-method.

To convert our method from above into an Enumerator, we must make some changes. First we need to return an IEnumerable<string> instead of a List. Second we need to remove the list-object. And finally rewrite the loop to use the keyword “yield”.

This is how our method would then look like:

public IEnumerable<string> MyMethod()
for (int i = 0; i < dataSource.Length; i++)
// Do some work.
yield return dataSource[i].SomeProperty;
yield break;

As you can see, the code looks way simpler. We don’t force our consumer to take a list. And the yield-keyword, changes the method into an Enumerator, which gives us a LOT of benefits:

The yield return, returns our data when the property Current is called on the Enumerator-instance. This property is usually called each time the MoveNext()-method is called. This Means you do not have to wait until all items are looped. You can stop at any moment. the yield-return is only called when you request the next item.

So if your consumer needs to loop through each of your items, you will only have to loop once, whereas the List-thingy above, would loop through the same items twice. That’s two billion items! Secondly the first example would always loop though each item, but the second one only loops through as many items as you want it to. Nothin more nothin less.


The essence of it all: Always use IEnumerable, only use lists where it cannot be done without it.

For performance reasons, always use Enumerators. They will save the day.


This is my first attempt on a “professional”-programming guide. Please provide feedback!

NMultiSelect – Et jQuery Plugin



This has become quite an old version, it’s good to get started, but to get the latest version, please take a look here:

Quick links

About NMultiSelect

Okay, I have been foolin’ around with javascripts again, i know, can’t help it. This time I have made me a jQuery plug-in. I chose jQuery because it’s so much easier to do cross browser compatible stuff with that framework, compared to time it will take for me to build it on my own.

The last 3/4 of a year, i have worked on and off with the Microsoft ASP.NET MVC framework, and found it quite likeable, in terms of development speed and possibilities in the markup and, in this case, JavaScript.

While working with the MVC framework, I have been looking for a nice, easy to implement method for a user to choose multiple values from a list. The good ol’ “hold ctrl while clicking”-method doesn’t quite do the job, so I decided to build my own control.

It’s, like most of the other stuff I’ve made, quite easy to use.

Seen from a user’s perspective, it’s simple, click or double click, select and click or what ever he or she feels like. For the developer, it’s also quite easy. A few lines of code, and you’re ready to go:


Getting started

First we need to include a few scripts:

<span class="kwrd">&lt;</span><span class="html">script</span> <span class="attr">type</span><span class="kwrd">="text/javascript"</span> <span class="attr">src</span><span class="kwrd">=""</span><span class="kwrd">&gt;&lt;/</span><span class="html">script</span><span class="kwrd">&gt;</span>

<span class="kwrd"> </span><span class="kwrd">&lt;</span><span class="html">script</span> <span class="attr">type</span><span class="kwrd">="text/javascript"</span> <span class="attr">src</span><span class="kwrd">=""</span><span class="kwrd">&gt;&lt;/</span><span class="html">script</span><span class="kwrd">&gt;</span>

<span class="kwrd"> </span><span class="kwrd">&lt;</span><span class="html">script</span> <span class="attr">type</span><span class="kwrd">="text/javascript"</span> <span class="attr">src</span><span class="kwrd">=""</span><span class="kwrd">&gt;&lt;/</span><span class="html">script</span><span class="kwrd">&gt;</span>

Where you wan’t to place your box, you just put a div:

<span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">id</span><span class="kwrd">="EmptySelectContainer"</span><span class="kwrd">&gt;&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span>

We wan’t to remember this ID for later…

To transform the div, to a multi select box, we will have to write the following piece of code:

    <span class="kwrd">function</span> () {
        <span class="kwrd">var</span> m1 = $(<span class="str">"#EmptySelectContainer"</span>).NMultiSelect(<span class="str">"mySelection"</span>);

What happens here is:

  1. $(document).ready – We will wait until the page is ready before doing anything.
  2. $(“#EmptySelectContainer”) – We select’s our div, using the ID from earlier. You can use any form of selectors here.
  3. NMultiSelect(“mySelection”) – Transform our div to a multi select box. The parameter (mySelection) is the name of the field getting posted to the server. In this case, we will be able to get our data using $_POST[“mySelection”] (using php, but more on that later.)

Now, we have transformed our div to a multi select box, but it’s a bit useless. Lets fill it with some values. To do so, use this function:


The function AddItemToList, takes 3 parameters.

The first, is the value posted to the server. Usually an ID.

The second, is the text shown in the box.

The third, is a boolean value (not mandatory). If true, the item will be selected and visible in the right hand side box.

You can add as many items you want, Below is an example:

m1 = $(<span class="str">"#EmptySelectContainer"</span>).NMultiSelect(<span class="str">"mySelection"</span>);

m1.AddItemToList(<span class="str">"1-1"</span>,<span class="str">"Value 1"</span>,<span class="kwrd">false</span>);
m1.AddItemToList(<span class="str">"2-1"</span>,<span class="str">"Value 2"</span>,<span class="kwrd">false</span>);
m1.AddItemToList(<span class="str">"3-1"</span>,<span class="str">"Value 3"</span>,<span class="kwrd">true</span>);
m1.AddItemToList(<span class="str">"4-1"</span>,<span class="str">"Value 4"</span>,<span class="kwrd">true</span>);

Here we add 4 items to our box. Whereof the last two are pre-selected.

Now we have our items, it could be nice, to track how the user chooses, for statistics or calling AJAX methods or whatever. To do se, we can subscribe to the event:


The parameter (code), is code that will be executed, when a user selects or deselects one or more items.

An example:

m1.SelectionChanged(<span class="kwrd">function</span>(data)
    <span class="rem">// Do stuff here.</span>

The function, or code, that is being executed, must take one parameter, (call it whatever you feel like, i would recommend “data”, because, that is what it is). This parameter contains two properties:

  • Items
    • Contains all elements we have added.
  • Selection
    • Contains all chosen elements.

The objects contained in the lists, has the following properties:

  • Text
  • Value
  • Selected

Full example

Bellow is a full example. You could also see nmultiselect live here.

<span class="kwrd">&lt;!</span><span class="html">DOCTYPE</span> <span class="attr">html</span> <span class="attr">PUBLIC</span> <span class="kwrd">"-//W3C//DTD XHTML 1.1//EN"</span> <span class="kwrd">""</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;</span><span class="html">html</span> <span class="attr">xmlns</span><span class="kwrd">=""</span> <span class="attr">xml:lang</span><span class="kwrd">="da"</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;</span><span class="html">head</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">title</span><span class="kwrd">&gt;</span>NMultiselect<span class="kwrd">&lt;/</span><span class="html">title</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">link</span> <span class="attr">rel</span><span class="kwrd">="stylesheet"</span> <span class="attr">type</span><span class="kwrd">="text/css"</span> <span class="attr">href</span><span class="kwrd">="/styles/style.css"</span><span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">script</span> <span class="attr">type</span><span class="kwrd">="text/javascript"</span> <span class="attr">src</span><span class="kwrd">=""</span><span class="kwrd">&gt;&lt;/</span><span class="html">script</span><span class="kwrd">&gt;</span>
    &lt;script type=<span class="str">"text/javascript"</span> src=<span class="str">"/scripts/jquery.nmultiselect.min.js"</span>&gt;&lt;/script&gt;
        <span class="kwrd">var</span> m1;
        <span class="kwrd">var</span> m2;

            <span class="kwrd">function</span> () {
                m1 = $(<span class="str">"#EmptySelectContainer"</span>).NMultiSelect(<span class="str">"mySelection",<span class="kwrd">true</span></span>);

                m1.AddItemToList(<span class="str">"1-1"</span>,<span class="str">"Value 1"</span>,<span class="kwrd">false</span>);
                m1.AddItemToList(<span class="str">"2-1"</span>,<span class="str">"Value 2"</span>,<span class="kwrd">false</span>);
                m1.AddItemToList(<span class="str">"3-1"</span>,<span class="str">"Value 3"</span>,<span class="kwrd">true</span>);
                m1.AddItemToList(<span class="str">"4-1"</span>,<span class="str">"Value 4"</span>,<span class="kwrd">true</span>);

                m1.SelectionChanged(<span class="kwrd">function</span>(data)
                    console.log(<span class="str">'List 1, selected values: '</span>+(data.Selection.length));

                m2 = $(<span class="str">"#EmptySelectContainer2"</span>).NMultiSelect(<span class="str">"mySelection2"</span>);
                m2.AddItemToList(<span class="str">"1-2"</span>,<span class="str">"Value 1"</span>,<span class="kwrd">true</span>);
                m2.AddItemToList(<span class="str">"2-2"</span>,<span class="str">"Value 2"</span>,<span class="kwrd">false</span>);
                m2.AddItemToList(<span class="str">"3-2"</span>,<span class="str">"Value 3"</span>,<span class="kwrd">false</span>);
                m2.AddItemToList(<span class="str">"4-2"</span>,<span class="str">"Value 4"</span>,<span class="kwrd">true</span>);
                m2.AddItemToList(<span class="str">"5-2"</span>,<span class="str">"Value 5"</span>,<span class="kwrd">true</span>);
                m2.AddItemToList(<span class="str">"6-2"</span>,<span class="str">"Value 6"</span>,<span class="kwrd">true</span>);
                m2.AddItemToList(<span class="str">"7-2"</span>,<span class="str">"Value 7"</span>,<span class="kwrd">false</span>);
                m2.AddItemToList(<span class="str">"8-2"</span>,<span class="str">"Value 8"</span>,<span class="kwrd">false</span>);

                m2.SelectionChanged(<span class="kwrd">function</span>(data)
                    console.log(<span class="str">'List 2, selected values: '</span>+(data.Selection.length));
    <span class="kwrd">&lt;/</span><span class="html">script</span><span class="kwrd">&gt;</span>

<span class="kwrd">&lt;/</span><span class="html">head</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;</span><span class="html">body</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;</span><span class="html">form</span> <span class="attr">method</span><span class="kwrd">="get"</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">id</span><span class="kwrd">="EmptySelectContainer"</span><span class="kwrd">&gt;&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">p</span><span class="kwrd">&gt;</span>hejsa<span class="kwrd">&lt;/</span><span class="html">p</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">id</span><span class="kwrd">="EmptySelectContainer2"</span><span class="kwrd">&gt;</span>

    <span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">input</span> <span class="attr">type</span><span class="kwrd">="submit"</span> <span class="attr">value</span><span class="kwrd">="submit"</span><span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">form</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">body</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">html</span><span class="kwrd">&gt;</span>



So, what to do on the serverside to get the data?

Well, the name you apply in the NMultiSelect function above, is the name of the field getting posted to the server.

If we say, you use the ASP.NET MVC framework, your backend would look somewhat like this:

<span class="kwrd">public</span> <span class="kwrd">void</span> GiveMeData(<span class="kwrd">string</span> mySelection)
    <span class="rem">// Først splittes værdierne:</span>
    <span class="rem">// Ja, vi splitter på komma, i en fremtidig version kan dette ændres!</span>
    <span class="kwrd">string</span>[] mySelectionItems = mySelection.Split(<span class="str">','</span>);

    <span class="rem">// Gennemløb værdierne:</span>
    <span class="kwrd">foreach</span>(<span class="kwrd">string</span> itemId <span class="kwrd">in</span> mySelectionItems)
        <span class="rem">// Du kan her behandle værdierne som du ønsker.</span>


    <span class="rem"># Få fat i værdierne:</span>
    $selection = $_POST[<span class="str">"mySelection"</span>];

    <span class="rem"># Split værdierne:</span>
    $values = explode(<span class="str">","</span>, $selection);

    <span class="rem"># Gennemløb værdierne:</span>
    <span class="kwrd">foreach</span> ($values as &amp;$value) {
            <span class="rem"># Gør med dataene hvad du vil.</span>

    <span class="rem"># Husk at ryde op:</span>



Heres a short reference of all the functions available:

NMultiSelect(name,[move]) Creates a new instance of the NMultiSelect-box on the first item in the applied jQuery object. See exampe above.Name: Name of the field that is posted to the server.

move: Not mandatory! If true, the items will be moved between the boxes, instead of just being copied to the right hand side box. Default is false.

AddSelection() Chooses all selected items in the left hand box.
AddAll() Chooses all items in the left hand box.
RemoveSelection() Removes selected items from the right hand side box.
RemoveAll() Removes all items from the right hand side box.
AddItemToList(value,text,[selected]) Adds an item to the box.value: Value the item should have.

text: Text of the item.

selected: Not mandatory, if true, the item is pre-selected.

SelectionChanged(code) Event you can subscribe. Is called each time a change in the chosen items occur.code: Code to be executed, when the event is fired. The code, must have a parameter, that accepts the same objects as data(‘values’) returns.
data(‘values’) Returns all added items, and all chosen items.More details about data(‘values’) below.


If you call data(‘values’), (it’s importent to include the ‘values’ part. This is a jQuery thingy!), you will get an object with two properties:

  • Items
  • Selection

Each of these properties contains a list of objects. Items – A list of all items we’ve added, and selection – A list of all chosen items. Each of these objects has the following properties:

  • Value
  • Text
  • Selected

In the Items-list, all values will be the ones, the item was created with.

In the Selection-list, the only difference would be, that the selected-property will be true.


You can grap the code and an example here:

Download NMultiSelect 1.0


Efter lang tids stilhed kommer her en lille opdatering på hvad jeg har gang i for tiden.

Jeg arbejder på et database-testnings system, DBTesting, til at oprette og køre automatiserede tests af en database under udvikling, så man sikre sig, at de data man får ud, er præcis som de skal være og ikke bliver ændret på nogen måder.

Jeg vil ikke gå så meget i dybden her, men du kan læse mere på hjemmesiden:

Start ny mail i MS Outlook fra MS Access

Dette er en mindre fortsættelse til “Start Skype fra MS Access” som jeg skrev for leden.

1. Opret tabel

Vi bruger blot den samme tabel som sidst, denne gang tilføjer vi bare et nyt felt med navnet e-mail:

2. Opret formular

Hvis du har læst foregående guide, vil du have en formular hvor du blot skal tilføje et nyt felt til e-mailen. Hvis du ikke har nogen formular, så opretter du bare en fra guiden. Det er nemmest.

3.  Tilføj knap

De næste trin er nemme nok, du gør blot som i trin 3-5 i “Start Skype fra Access” guiden. Den eneste forskel er blot, at du skal vælge “Kuvert”, “Brev”, “Envelope” eller hvad den hedder som billede.

4. Tilføj VB kode

Du skulle gerne nu have noget kode, der ser nogenlunde sådanne ud:

<span class="kwrd">Private</span> <span class="kwrd">Sub</span> Command20_Click()

<span class="kwrd">End</span> Sub

I mellemrummet tilføjer du denne kode:

<span class="kwrd">Dim</span> Cmd <span class="kwrd">As</span> <span class="kwrd">String</span>
<span class="kwrd">Dim</span> Dir64 <span class="kwrd">As</span> <span class="kwrd">String</span>
<span class="kwrd">Dim</span> Dir32 <span class="kwrd">As</span> <span class="kwrd">String</span>
<span class="kwrd">Dim</span> EmailField <span class="kwrd">As</span> <span class="kwrd">String</span>

<span class="rem">' Name of the field, containing the phonenumber:</span>
EmailField = <span class="str">"email"</span>

<span class="rem">' Outlook default install dir, on both 32 and 64 bit Windows.</span>
<span class="rem">' Change "Office14" to your Office version. 11 = 2003, 12 = 2007, 14 = 2010</span>
Dir32 = <span class="str">"C:Program FilesMicrosoft OfficeOffice14OUTLOOK.exe"</span>
Dir64 = <span class="str">"C:Program Files (x86)Microsoft OfficeOffice14OUTLOOK.exe"</span>

<span class="rem">' Do not edit below this line!</span>

<span class="kwrd">Me</span>(EmailField).SetFocus

Cmd = <span class="str">" /c ipm.note /m "</span> + <span class="kwrd">Me</span>(EmailField).Text

<span class="kwrd">If</span> Dir$(Dir32) &lt;&gt; <span class="str">""</span> <span class="kwrd">Then</span>

    Shell (Dir32 + Cmd)
<span class="kwrd">Else</span>
<span class="kwrd">If</span> Dir$(Dir64) &lt;&gt; <span class="str">""</span> <span class="kwrd">Then</span>

    Shell (Dir64 + Cmd)

<span class="kwrd">Else</span>
    MsgBox (<span class="str">"Microsoft Outlook was not found in default install dir!"</span> &amp; vbCrLf &amp; <span class="str">"Check Office version and/or dir!"</span>)
<span class="kwrd">End</span> <span class="kwrd">If</span>
<span class="kwrd">End</span> If

Den minder lidt om den fra sidst, det du skal ligge mærke til her er felterne “EmailField”, “Dir32/” og “Dir64”. “EmailField” skal selvfølgelig indeholde navnet på det felt, der indeholder e-mail adressen.

“Dir32” og “Dir64” skal tilpasses din version af Office, dvs. teksten “Office14” skal erstattes med “Office11” for Office 2003, “Office 12” for Office 2007 og “Office14” for Office 2010.

Scriptet kan udvides med flere funktioner, læs mere her:

Start Skype fra MS Access

For leden fik kom en af mine kollegaer og beklagede sig over at han ikke var i stand til at klikke på en knap i Microsoft Access, som så åbnede Skype og ringede op til et telefon nummer, der er angivet i et felt på formularen.

Jeg fandt, så hurtigt på en løsning. Ved at tilføje en lille stump VB kode til en knap, kan jeg starte Skype og ringe op, helt uden at skulle klippe eller klistre.

Metoden er ganske simpel:

1. Starter med en tabel:

Først opretter vi en tabel med to felter: ID (autonummereret) og telephonenumber (datatypen er underordnet!)

2. Opret formular:

Så opretter vi en formular til at indtaste vores data og vise vores data. Du kan bare bruge auto genereringen hvis ikke du vil designe den fra bunden.

3. Tilføj knap:

Så tilføjer vi en knap på formen, lettest at gøre i layout visningen.

4. Tilpasser knappen:

Gør knappen mere brugervenlig med et lille ikon, fremfor teksten:

I egenskabsfeltet, slet teksten i "Caption" eller "Tekst" feltet, alt efter versionen af Access du har (Der skulle gerne stå noget i stil med "Command" eller "Kommando" efterfulgt af et nummer.

Klik på knappen med de tre prikker ud for feltet "Picture" eller "Billede" og vælg "Phone" eller "Telefon" på listen.

Klik OK.

5. Tilføj handling (Event):

Klik på fanen handling, eller event, og klik på knappen med tre prikker ud for feltet "on click" eller "ved klik".

6. Tilføj VB script, og du er kørende:

Du skulle gerne få et vindue, hvor indholdet minder om dette:

<span class="kwrd">Private</span> <span class="kwrd">Sub</span> Command14_Click()

<span class="kwrd">End</span> Sub

.csharpcode, .csharpcode pre
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
background-color: #f4f4f4;
width: 100%;
margin: 0em;
.csharpcode .lnum { color: #606060; }
.csharpcode, .csharpcode pre
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
background-color: #f4f4f4;
width: 100%;
margin: 0em;
.csharpcode .lnum { color: #606060; }

I mellemrummet skal du tilføje denne kode:

<span class="kwrd">Dim</span> Cmd <span class="kwrd">As</span> <span class="kwrd">String</span>
<span class="kwrd">Dim</span> Dir64 <span class="kwrd">As</span> <span class="kwrd">String</span>
<span class="kwrd">Dim</span> Dir32 <span class="kwrd">As</span> <span class="kwrd">String</span>
<span class="kwrd">Dim</span> CountryCode <span class="kwrd">As</span> <span class="kwrd">String</span>
<span class="kwrd">Dim</span> PhoneNumberField <span class="kwrd">As</span> <span class="kwrd">String</span>

<span class="rem">' Name of the field, containing the phonenumber:</span>
PhoneNumberField = <span class="str">&quot;telephone&quot;</span>

<span class="rem">' Country code. +45 for Denmark.</span>
CountryCode = <span class="str">&quot;+45&quot;</span>

<span class="rem">' Skype default install dir, on both 32 and 64 bit Windows.</span>
Dir32 = <span class="str">&quot;C:Program FilesSkypePhoneSkype.exe&quot;</span>
Dir64 = <span class="str">&quot;C:Program Files (x86)SkypePhoneSkype.exe&quot;</span>

<span class="rem">' Do not edit below this line!</span>

<span class="kwrd">Me</span>(PhoneNumberField).SetFocus

Cmd = <span class="str">&quot; /callto:&quot;</span> + CountryCode + <span class="kwrd">Me</span>(PhoneNumberField).Text

<span class="kwrd">If</span> Dir$(Dir32) &lt;&gt; <span class="str">&quot;&quot;</span> <span class="kwrd">Then</span>

    Shell (Dir32 + Cmd)
<span class="kwrd">Else</span>
<span class="kwrd">If</span> Dir$(Dir64) &lt;&gt; <span class="str">&quot;&quot;</span> <span class="kwrd">Then</span>

    Shell (Dir64 + Cmd)

<span class="kwrd">Else</span>
    MsgBox (<span class="str">&quot;Skype Client was not found in default install dir!&quot;</span>)
<span class="kwrd">End</span> <span class="kwrd">If</span>
<span class="kwrd">End</span> If

.csharpcode, .csharpcode pre
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
background-color: #f4f4f4;
width: 100%;
margin: 0em;
.csharpcode .lnum { color: #606060; }

Lig mærke til felterne PhoneNumberField og CountryCode.

PhoneNumberField, skal være navnet på det felt, hvor telefonnummeret findes, i dette tilfælde “telephone” og CountryCode, skal være landekoden for modtageren af opkaldet. Skype spørger dog selv, om landekoden, men vil ikke starte uden.