February 19th, 2015
  • Programmically change items
  • EPiServer
  • NullReferenceException
  • Html.RenderAction

Programmatically changing EPiServer items - The nice way

When you use MVC and you use Html.RenderAction within your view, you cannot use the 'Alloy' logic to programmatically add, update or remove pages and/or blocks in EPiServer within your action or constructor. If you do, you can expect an 'Object reference not set to an instance of an object' upon your 'Html.RenderAction' line when you try to edit the page in the EPiServer backend.

With the 'Alloy' logic I mean:

PrincipalInfo.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("Task"), new[] { "Administrators" });
/* Update, modify or delete EPiServer items */
PrincipalInfo.CurrentPrincipal = null

This NullReferenceException occurs because you dump your EPiServer user for the rest of your request and this causes EPiServer to not know which language, etc. to use to render the action.

But even without the NullReferenceException, this is not the right way to remove the temporary created administrator principal.

You could better create a SecurityDisabler:

using EPiServer.Security;
using System;
using System.Security.Principal;

namespace Your.Namespace
{
    public class SecurityDisabler : IDisposable
    {
        private readonly IPrincipal _principal;

        public SecurityDisabler()
        {
            _principal = PrincipalInfo.CurrentPrincipal;
            PrincipalInfo.CurrentPrincipal = new GenericPrincipal(
            new GenericIdentity("Task"),
            new[] { "Administrators" });
        }

        public void Dispose()
        {
            PrincipalInfo.CurrentPrincipal = _principal;
        }
    }
}

Using it you can change EPiServer pages and/or blocks programmatically without ever having any side effects:

using (new SecurityDisabler())
{
    /* Update, modify or delete EPiServer items */
}
< Previous post Overview posts Next post >
<a href=http://sildenafil.buzz>does viagra make you harder</a> In fact, the administration of oestrogen to post menopausal women is associated with a decrease of bone resorption
Peergiz, January 5th, 2024
Lipids 2008; 43 3 251 258 <a href=https://vardenafil.one>cout levitra belgique</a>
opintense, November 4th, 2023
com 20 E2 AD 90 20How 20To 20Get 20Viagra 20Online 20 20Viagra 20Kopen 20Den 20Haag viagra kopen den haag Twenty five containers were discovered inside the ship, more than previously reported, according to a recent report by Panamanian authorities and the United Nations Organization on Drugs and Crime Container Control Program <a href=https://cialiss.makeup>buy cheap cialis discount online</a>
vVPCGd, October 18th, 2023
<a href=http://clomid.homes>what is clomid</a> Who interprets the results and how do I get them
rooloulky, April 3rd, 2023

Leave a comment

= Thanks for your comment =