31 October 2014

Sitecore 7.2 MVC, Personalisation issue with WFFM


Not long ago, I faced an issue when using personalization. It is usually straight forward to setup but somehow this time it did not work. This was quite annoying and get me going for a bit of time. So I wanted to share it in case anybody out there would faced the same issue.

So for the project we were using:
  • Sitecore 7.2 MVC, 
  • GlassMapper
  • WFFM for all the forms on the website. 
As you can imagine most of the presentation elements were View renderings, except a few controller renderings. When setting up the personalisation rules, everything seems to be working perfectly at first until the testing team reported an issue:
When personalisation rules were set on an item, none of them was triggered. Looked like the rules engine was not working correctly. 







After investigating the issue it seems like it was only when personalisation was applied on Controller rendering. After trying the rule engine on a fresh Sitecore install, everything was working perfectly. So I started to take out our customisation elements one by one. After commenting all pipeline actions I could think of having anything to do with the issue and no luck, the issue was still there. Until "light bulb": let's check the Showconfig.aspx page:


And there you go, the pipeline action where the rule engine is triggered is the "CustomizeRendering" from the Sitecore.Mvc.Analytics.config


As you can see from the pipeline, One processor is intercepting the GetRenderer before it was hitting the rules engine. The pipeline action is from the Sitecore.Forms.MVC.config file. Looking at the code in this processor you will see the following:

if (args.Rendering.RenderingItem.ID != IDs.FormMvcInterpreterID)
{
    return base.GetRenderer(rendering, args);
}
Tuple< string, string> controllerAndAction = this.GetControllerAndAction(rendering, args);
if (controllerAndAction == null)
{
    return null;
} 


This will obviously intercept the Controller rendering and return the Conntroller and action prior evaluating the Rules...

If you are looking at the configuration file: Sitecore.Forms.MVC.config then you will realized that the intend is to place this processor before the GetControllerRenderer to ensure that the form controller will be executed before a normal ControllerRenderer:


When Sitecore is parsing the Configuration files the Sitecore.MVC.Analytics.config is parsed after the Sitecore.Forms.MVC.config... Which means that the GetFormControllerRenderer will get executed before the Rule engine...

Solution:
rename the config file to be "t_Sitecore.Forms.MVC.config". This will ensure that the processor will happen after the rules engine kicks in:

29 October 2014

Restricting renderings selection for placeholder

Today, I just wanted to talk about a simple thing but quite helpful when starting to develop with Page Editor: How can you specify which rendering can be inserted in a placeholder. This is really useful for Side panels for insance. You have created different types of panel (renderings) and now you want the to allow content editor to insert only those through the Page Editor such as the follownig:



Well, this is quite simple:

1- Placeholder in your code

Let's say you have a 2 columns rendering that will placed int your main layout. This 2 columns rendering will have 2 laceholders: one for the Main content and one for the Side Column. Something like:

< div class="row">
    < h1 class="col-sm-12">@Html.Sitecore().Placeholder("imagebanner")< /h1>
< /div>

< div class="row">
     < h1 class="col-sm-12">@Html.Sitecore().Placeholder("contenttitle")< /h1>
< /div>
< div class="row">
    < div class="col-sm-9 main-column">
        < article class="col-sm-12">
            @Html.Sitecore().Placeholder("contentcolumn")
        < /article>
    < /div>
    < div class="col-sm-3 sidebar">
        @Html.Sitecore().Placeholder("sidecolumn")
    < /div>
< /div>


2- Sitecore elements

On the sitecore side, the only thing you will need to define the Placeholder Settings under the path: /sitecore/layout/Placeholder Settings/xxx

You can noticed the Placeolder Key match the definition of the placeholder in our code:
@Html.Sitecore().Placeholder("sidecolumn")

You can also notice that you can select the Allowed Controls. Those will be the controls that are display to the Content Author when adding a new element in the placeholder. Once this is defined, Sitecore will automatically make the mapping. and now on the Page Editor you will see the "Add" buttons when you select the placeholder...In a future post I will describe how you can overwrite this placeholder settings for specific template...

13 October 2014

Chrome and issue with User Manager


This entry will be quite quick to write. But still worth having it here as this might help a few people who like me had to investigate an issue with the User Manager...

Most of our clients love to use Chrome to edit their content. Eventhough everything seems to be working fine, from time to time there are few things here and there. Here is a good one:

When creating a user using the User Manager and Chrome (Sitecore 7.2), you will get the following issue:


Obviously if you are like me (big fan of Firefox), then you may not have this issue :)

Anyway, after reviewing the log files and trying to debug... I came across this article in the Sitecore Knowledge Base. The issue is well described as well as the fix:



 1- Open the /Website/sitecore/shell/Applications/Security/SelectRoles/SelectRoles.xaml.xml file.

 2- Replace the following block of code in the update() function:

    if(typeof(option.innerText) != 'undefined')
    {
      optionValue = option.innerText;
    }
    else
    {
      optionValue = option.textContent;
    }

    with the following:

if(typeof(option.textContent) == 'undefined')
    {
      optionValue = option.innerText;
    }
    else
    {
      optionValue = option.textContent;
    }

3- Clear the browser cache.

29 September 2014

AD module - Reset Password and Port Number


Active Directory Module. This is a nice module to play with. It is quite powerful and quite easy to configure following the documentation provided.

On a recent project we had the situation where we needed to allow the user to change their password. That sounds like the easiest task in the world and somehow whatever we tried we ended up with the following issue:


Exception: System.Reflection.TargetInvocationException
Message: Exception has been thrown by the target of an invocation.
Source: System.DirectoryServices
   at System.DirectoryServices.DirectoryEntry.Invoke(String methodName, Object[] args)
   at System.Web.Security.ActiveDirectoryMembershipProvider.ChangePassword(String username, String oldPassword, String newPassword)
   at Sitecore.Security.Accounts.MembershipUserWrapper.ChangePassword(String oldPassword, String newPassword)
   at Sitecore.Shell.Applications.Security.SetPassword.SetPasswordPage.OK_Click()

Nested Exception

Exception: System.Runtime.InteropServices.COMException
Message: Configuration information could not be read from the domain controller, either because the machine is unavailable or access has been denied. (Exception from HRESULT: 0x80070547)

This error was logged from the front end but also when trying to change the user password from the Sitecore Desktop Interface. We have tried quite a few things with user permission... nothing work until we added the port number to the connection string:

  < add connectionstring="LDAP://adconnection:389/OU=Users,DC=mycomany,DC=external" name="MyAdConnString"> 

So just in case you are getting similar issues, it is worth adding the port number to the connection string... Hoping that wil save a few hours of debugging...

14 September 2014

Retrieve Datasource from a Controller Rendering

If you are using Sitecore MVC then I am sure you have been using Controller Rendering. When using personlisation you are most likely either switch the Rendering or simply change the Datasource to point at different items. In your controller code, you may have tried the following:

SitecoreContext.GetCurrentItem< Item>()

With the SitecreContext being the Glass.Mapper.Sc.ISitecoreContext...

The GetCurrentItem in the controller will always return the Context Item, not the Datasource. So you need to actually retrieve the Datasource with Code. What you can use is something similar to:

        /// 
        /// Get either the data source or the context item
        /// 
        private Item Datasource
        {
            get
            {
                var dataSource = SitecoreContext.GetCurrentItem< Item>();
                string datasourceId = RenderingContext.Current.Rendering.DataSource;
                if (Sitecore.Data.ID.IsID(datasourceId))
                {
                    dataSource = SitecoreContext.GetItem< Item>(new Guid(datasourceId));
                }

                return dataSource;
            }
        }

From the above code you can see that this will either return the Context Item if the Datasource is not set, OR the datasource item if set.

Now, I am sure you will have to create multiple Controller Renderings in your solution. So it could be a great idea to create an abstract class Controller and all your controller will be based on this:

namespace MySite.Controllers
{
    public abstract class BaseController: SitecoreController
    {
        protected readonly ISitecoreContext BaseSitecoreContext;

        public BaseController(ISitecoreContext sitecoreContext)
        {
            this.BaseSitecoreContext = sitecoreContext;
        }

        /// 
        /// Get either the data source or the context item
        /// 
        public Item Datasource
        {
            get
            {
                var dataSource = BaseSitecoreContext.GetCurrentItem< Item>();
                string datasourceId = RenderingContext.Current.Rendering.DataSource;
                if (Sitecore.Data.ID.IsID(datasourceId))
                {
                    dataSource = BaseSitecoreContext.GetItem< Item>(new Guid(datasourceId));
                }

                return dataSource;
            }
        }
    }
}


You can now use the base Controller to derive your custom controller:
    public class CalculatorController : BaseController
    {
        private readonly ISitecoreContext sitecoreContext;

        public CalculatorController(ISitecoreContext sitecore)
            : base(sitecore)
        {
             // Do whatever
        }
    }

2 September 2014

Email function in Sitecore

Just a quick reminder for those who wants to send an email from Sitecore. There are times where you have to write your own method and this is completely understandable. However, dont forget to check if there is already a method that does it for you... I have seen a SendEmail Method where the SMTP, username, password and port were defined on the item fields. Well for this specific example, you have a method that already send email in sitecore:

Sitecore.MainUtil.SendMail(System.Net.Mail.MailMessage message)

This method is using the System.Net.Mail.SmtpClient to send the email which what most of us will actually implement on custom code. So why not using it... Here is the Method:

  /// 
  /// Sends the mail.
  /// 
  /// The message.
  public static void SendMail(System.Net.Mail.MailMessage message)
  {
   string mailServer = Settings.MailServer;
   System.Net.Mail.SmtpClient smtpClient;
   if (string.IsNullOrEmpty(mailServer))
   {
    smtpClient = new System.Net.Mail.SmtpClient();
   }
   else
   {
    int mailServerPort = Settings.MailServerPort;
    if (mailServerPort > 0)
    {
     smtpClient = new System.Net.Mail.SmtpClient(mailServer, mailServerPort);
    }
    else
    {
     smtpClient = new System.Net.Mail.SmtpClient(mailServer);
    }
   }
   string mailServerUserName = Settings.MailServerUserName;
   if (mailServerUserName.Length > 0)
   {
    string mailServerPassword = Settings.MailServerPassword;
    System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(mailServerUserName, mailServerPassword);
    smtpClient.Credentials = credentials;
   }
   smtpClient.Send(message);
  }



So you should be able to use it straight away as per the following:

var myMessage = new MailMessage(from, to, subject, body);
  Sitecore.MainUtil.SendMail(myMessage);


RE-EDITED the post: obviously you need to setup your SMTP in the web.config for this to work:
      < !--  MAIL SERVER
            SMTP server used for sending mails by the Sitecore server
            Is used by MainUtil.SendMail()
            Default value: ""
      -->
      < setting name="MailServer" value="" />
      < !--  MAIL SERVER USER
            If the SMTP server requires login, enter the user name in this setting
      -->
      < setting name="MailServerUserName" value="" />
      < !--  MAIL SERVER PASSWORD
            If the SMTP server requires login, enter the password in this setting
      -->
      < setting name="MailServerPassword" value="" />
      < !--  MAIL SERVER PORT
            If the SMTP server requires a custom port number, enter the value in this setting.
            The default value is: 25
      -->
      < setting name="MailServerPort" value="25" />


I hope that will help...

20 July 2014

301 Redirect Handling

In previous post we saw that we could create a Custom Field and store values we wanted in it. In our case we took a simple example to store data for a 301 redirect. We saw the use of a button on the field to regenerate the data whenever we wanted... Also for that example we chose to store the data in Json format. This was totally arbitratory and you can choose to store your data in whatever format you need. Well let's try to finish the code to see how we can integrate that plus pipeline action (like here) to handle the 301 redirects.

1- We need to define our templates

We will need 3 templates
  • The Redirection Status: 301, 302... this will help us to define the status code and the status text to pass to the Response. The template will looks like:


  • The Domain Redirection Item: This item will store the Json list objects as per our previous post as well as the domain we want the redirection to be applicable. Here we are thinking about 301 for multi-sites. Indeed, if your sitecore instance has multiple sites and you are setting up a redirection for /applications, this might be a valid  redirection for Site 1 but /applications could exist on Site 2... So better to plan for it. Now, when we had a look at the Domain Dictionary, we saw that in the configuration of your site you will have the attribute "dictionaryDomain". well we will use the same attribute to find our site domain for redirection. The template should look like the following (note the second field is our custom field):

  • Finally we will need a Redirect Item template. This template will have 3 fields: the requested URL (single line text), Redirect To: droptree that can point to a media or content item... and Status Code: droptree pointing at our Redirection Status folder as per above image...\

 2- Custom Field

well we already saw that part... under our "Redirections", we will have our Domain Item that will store the domain and the Json Data... Under this domain item, we will define all the redirection items.
Our Custom Field, will have a button which will trigger an action to get all the children and build the Json List of objects... You can follow this post to setup the field.

So we now that the data we are going to use on the HTTP Request Begin pipeline is stored on the domain item, so theoretically, we just need to retrieve this item, get the data, deserialise and get the relevant redirect if any... then proceed with redirection

3- Configuration

Easy part, we just need a processor on the HTTPRequestBegin Piepline:

      < httpRequestBegin>
        < processor type="MySite.Business.Sitecore.Pipelines.PermanentRedirect, MySite.Business" patch:after="processor[@type='Sitecore.Pipelines.HttpRequest.ItemResolver, Sitecore.Kernel']" />
      < /httpRequestBegin>

4- Code

Now we have our data, we have our pipeline configure, let's intercept the request and handle some 301 shall we?
Create your class PermanentRedirect based on the HttpReqiestProcessor...

namespace MySite.Business.Sitecore.Pipelines
{
    /// 
    /// This processor will check for 301 redirects
    /// 
    public class PermanentRedirect : HttpRequestProcessor
    {
        public override void Process(HttpRequestArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            if (Context.Database == null || args.Url.ItemPath.Length == 0 || Context.Site == null)
                return;
        }
    }
}

Now let's think about what we will need:

we will need a method to set the Response: status, status code, header for the location to redirect to...
So let's create that method. Don't forget, you can modify the response from the Args.Context:

        /// 
        /// Set the Header for the reponse
        /// 
        /// 
        /// 
        /// 
        /// 
        private void SetResponse(string redirectTo, string status, int statusCode, HttpRequestArgs args)
        {
            args.Context.Response.Status = status;
            args.Context.Response.StatusCode = statusCode;
            args.Context.Response.AddHeader("Location", redirectTo);
            args.Context.Response.End();
        }

The next thing we will need is a URL resolver. If you remember on our Json object we will store the RedirectTo value as Sitecore ID (to either a content or a media). So we would need a method to get the item and get either the content URL or a media URL if it is pointing at a document... Notes, that we could have tried to store the nice URL on the Json object but the jSon object is generate from the Custom Field button which would have the Sitecore Context Site as Shell so you would have to pass your website context as UrlOptions. Also you want to check that the item you are redirecting to exsits in your delivery site so it is always better to resolve this item on the pipeline action...

        /// 
        /// This will resolve either the media URL or the Content URL
        /// 
        /// 
        /// 
        private string GetSitecoreUrl(Item redirectToItem)
        {
            string mediaLibraryPath = Settings.GetSetting(SitecoreSettings.MediaPath).ToLower();

            // if the item is not a media item
            if (!redirectToItem.Paths.Path.StartsWith(mediaLibraryPath))
            {
                return LinkManager.GetItemUrl(redirectToItem);
            }

            // media item
            var mediaItem = (MediaItem)redirectToItem;
            var mediaUrl = MediaManager.GetMediaUrl(mediaItem);
            return StringUtil.EnsurePrefix('/', mediaUrl);

        }


So now we have our methods, we can start with the main business logic. The first thing we want is to get the root item for our redirection. This root item is the parent of all the Domain Redirection Items. This will allow us to go retrieve all Domain Redirection Items, and select only the ones matching our context.Site.DictionaryDomain:

            String domain = Context.Site.DictionaryDomain;
            if (string.IsNullOrEmpty(domain))
                return;

            // Root for the redirect folder
            Item rootFolder = Context.Database.GetItem(new SC.Data.ID(ItemId.System.Redirection.RedirectionRootFolder));
            if (rootFolder == null)
                return;

            if(!rootFolder.HasChildren)
                return;

            var validDomainItems = rootFolder.Children.Where(x => x.TemplateID.ToGuid() == new Guid(TemplateIds.System.RedirectionDomain)
                                                && x[FieldIds.System.RedirectionDomain.SiteDomain].ToLower() == domain.ToLower());


            if (!validDomainItems.Any())
                return;


Finally we can now loop through all the valid Domain Redirect Item, Get the Json Data field, Deserialize and find the relevant item to redirect to:

                    List redirectItems = (List)Newtonsoft.Json.JsonConvert.DeserializeObject(dataField, typeof(List));
                    if(redirectItems.Any(x=> x.redirectFrom.ToLower().Contains(requestedPath.ToLower())))
                    {
                        RedirectItem item = redirectItems.First(x =>  x.redirectFrom.ToLower().Contains(requestedPath.ToLower()));

                        // Only get the URL at this point to ensure permission, site context...
                        var redirectToItem = SC.Context.Database.GetItem(item.redirectTo);
                        if (redirectToItem == null)
                            continue;

                        string redirectToUrl = this.GetSitecoreUrl(redirectToItem);

                        SetResponse(redirectToUrl, item.status, item.statusCode, args);
                        return;
                    }



So all together, that could looks like something:
namespace MySite.Business.Sitecore.Pipelines
{
    /// 
    /// This processor will check for 301 redirects
    /// 
    public class PermanentRedirect : HttpRequestProcessor
    {
        public override void Process(HttpRequestArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            if (Context.Database == null || args.Url.ItemPath.Length == 0 || Context.Site == null)
                return;

            if (!Settings.GetSetting(SitecoreSettings.ValidSites).ToLower().Contains(Context.Site.Name))
                return;

            String domain = Context.Site.DictionaryDomain;
            if (string.IsNullOrEmpty(domain))
                return;

            // Root for the redirect folder
            Item rootFolder = Context.Database.GetItem(new SC.Data.ID(ItemId.System.Redirection.RedirectionRootFolder));
            if (rootFolder == null)
                return;

            if(!rootFolder.HasChildren)
                return;

            var validDomainItems = rootFolder.Children.Where(x => x.TemplateID.ToGuid() == new Guid(TemplateIds.System.RedirectionDomain)
                                                && x[FieldIds.System.RedirectionDomain.SiteDomain].ToLower() == domain.ToLower());


            if (!validDomainItems.Any())
                return;

            // get the actual request
            var requestedUrl = HttpContext.Current.Request.Url.ToString();
            var requestedPath = HttpContext.Current.Request.Url.AbsolutePath;

            // Get XML from the field... 
            foreach (var redirectDomainItem in validDomainItems)
            {
                string dataField = redirectDomainItem[FieldIds.System.RedirectionDomain.RedirectionData];
                if (string.IsNullOrEmpty(dataField))
                    continue;

                try
                {
                    //Deserialize the List
                    List redirectItems = (List)Newtonsoft.Json.JsonConvert.DeserializeObject(dataField, typeof(List));
                    if(redirectItems.Any(x=> x.redirectFrom.ToLower().Contains(requestedPath.ToLower())))
                    {
                        RedirectItem item = redirectItems.First(x =>  x.redirectFrom.ToLower().Contains(requestedPath.ToLower()));

                        // Only get the URL at this point to ensure permission, site context...
                        var redirectToItem = SC.Context.Database.GetItem(item.redirectTo);
                        if (redirectToItem == null)
                            continue;

                        string redirectToUrl = this.GetSitecoreUrl(redirectToItem);

                        SetResponse(redirectToUrl, item.status, item.statusCode, args);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    SC.Diagnostics.Log.Warn("Could not deserialize the Json for redirection Object - ex: " + ex.StackTrace , this);
                }
 
            }
        }

        /// 
        /// Set the Header for the reponse
        /// 
        /// 
        /// 
        /// 
        /// 
        private void SetResponse(string redirectTo, string status, int statusCode, HttpRequestArgs args)
        {
            args.Context.Response.Status = status;
            args.Context.Response.StatusCode = statusCode;
            args.Context.Response.AddHeader("Location", redirectTo);
            args.Context.Response.End();
        }

        /// 
        /// This will resolve either the media URL or the Content URL
        /// 
        /// 
        /// 
        private string GetSitecoreUrl(Item redirectToItem)
        {
            string mediaLibraryPath = Settings.GetSetting(SitecoreSettings.MediaPath).ToLower();

            // if the item is not a media item
            if (!redirectToItem.Paths.Path.StartsWith(mediaLibraryPath))
            {
                return LinkManager.GetItemUrl(redirectToItem).Replace("/site content", "");
            }

            // media item
            var mediaItem = (MediaItem)redirectToItem;
            var mediaUrl = MediaManager.GetMediaUrl(mediaItem);
            return StringUtil.EnsurePrefix('/', mediaUrl);

        }
    }
}



You can now try to call your redirect URL and see the redirection happening...

7 July 2014

Custom FIeld


Today I just wanted to show how you can create a custom field. Even if you will not really use this everyday. I found it quite handy from time to time. You can use custom fields for lots of reason: getting data from third party (Youtube, Google Map...) and store it in the field. You can also use it to display your field value in a certain way: preview your video... I guess it all depends on where your imagination can take you.

So on this example, I did not wanted to tackle something too tricky and connecting to third party... So what I was thinking about doing something like having this field to store a list of Json Object that could be used for a 301 redirect... Let say for example that you want to create a 301 redirect system that would look like:


Ok, so obviously when you will create your pipeline action to intercept the HttpRequestBegin to resolve the 301, you could just loop through all the items and find the item relevant to your request. Well, it is totally possible. Also considering a full site rebuild with a large amount of pages you would need to loop through 1000 links (I made up the number...). Anyway for our purpose today, the approach we will take is to define the list of JSon objects that will represent all our redirect items and store it on the parent item in our custom field. In our pipeline action we will then need to get the field value and deserialize the data and find the relevant redirect item. Here is how the field would appear


Well as you can image, this list will not be updated unless a content editor add a new item... That is why in that case a custom field is quite handy... especially with a nice little button at the top to regenerate the data when you will need to.

1- Defining the field type.

 To define the field type, you need to go to the CORE DB in the desktop. Under the System folder, you need to locate the item: Field Type. Create a new folder underneath which you can call Custom Field Types.
Under this newly created folder, you can create an Item from template Template field type. You can see the value to the control field: myfields:JsonField


2- Defining the menu item: button appearing at the top of the field

To define the menu item, you need to create a new folder under the field type you just created. The template to use is /Common/Folder. Under this folder, you will need to create a anew item from the template Menu item. The Display name field will be used for the text that will be displayed on the button. Also note the value placed on the Message field: myfields:regeneratejson.



3- Configurations

As you may have noticed we created some reference to controls: myfields:...
We now need to map it to the code we will write. So create a new config file in the Include folder. In this configuration file, we are going to define the Control to point it to a .net class that we will create.

    < controlsources>
      < source assembly="MySite.Business" mode="on" namespace="MySite.Business.Sitecore.Fields" patch:after="source[@namespace='ComponentArt.Web.UI']" prefix="myfields" />
    < /controlsources>


As you can see the myfields prefix will be mapping to the Namespace MySite.Business.Sitecore.Fields. Now, I am sure you are wondering where is the class defined. Well "myfields:JsonField", your .NET class will need to be called JsonField.

4- our code

OK, now we have the config in place, we can create our class... Namespace is defined above and the class name: JsonField. The field will be quite simple: we just need a free text on which will store Text... If you look into the namespace: Sitecore.Shell.Applications.ContentEditor you will some base control that you can base your control on. In our case we will choose to Sitecore.Shell.Applications.ContentEditor.Text as base type. Our first draft of the code will be similar to

namespace MySite.Business.Sitecore.Fields
{
    public class JsonField : SC.Shell.Applications.ContentEditor.Text
    {
        protected override bool LoadPostData(string value)
        {
            value = SC.StringUtil.GetString(new string[1]
            {
                value
            });

            if (this.Value == value)
                return false;

            this.Value = value;

            return true;
        }
    }
}


you can verify that you field display as a text box and the value you place in the field will be saved correctly.

5- Button action

The button action. Well in the definition of the menu item (button), we defined the Message field: myfields:regeneratejson
If you decompile the code for the base control: Sitecore.Shell.Applications.ContentEditor.Text, you will see that there are a few method you can override. One of them is the HandleMessage. This will allow you to intercept the regeneratejson coming from the button and redirect your code to your own method to hande the action:

        public override void HandleMessage(Message message)
        {
            base.HandleMessage(message);
            switch (message.Name)
            {
                case "myfields:regeneratejson":
                    this.RegenerateData();
                    break;
            }
        }


In our case, you can note that we wanted to loop through all children and serialised the data to build our Json list of redirect item... So first, we need to ensure we can access the actual current Item. This can be done as per the following:

        public string ItemID
        {
            get
            {
                return base.GetViewStateString("ItemID");
            }
            set
            {
                Assert.ArgumentNotNull(value, "value");
                base.SetViewStateString("ItemID", value);
            }
        }
Now we have the item we can build our method to loop through children and build our serialisation. Here is the full code:

namespace MySite.Business.Sitecore.Fields
{
    public class JsonField : SC.Shell.Applications.ContentEditor.Text
    {
        public string ItemID
        {
            get
            {
                return base.GetViewStateString("ItemID");
            }
            set
            {
                Assert.ArgumentNotNull(value, "value");
                base.SetViewStateString("ItemID", value);
            }
        }

        public override void HandleMessage(Message message)
        {
            base.HandleMessage(message);
            switch (message.Name)
            {
                case "myfields:regeneratejson":
                    this.RegenerateData();
                    break;
            }
        }

        protected void RegenerateData()
        {
            var masterDB = SC.Data.Database.GetDatabase("master");
            if (masterDB == null)
            {
                SheerResponse.ShowError("Could not get master DB", "Error: Could not retrieve the Master Database");
            }

            var item = masterDB.GetItem(ItemID);
            if (item == null)
            {
                SheerResponse.ShowError("Could not resolve the current Item", "Error: Could not resolve the current Item");
            }

            if(!item.HasChildren)
                return;

            List list = new List();
            foreach (var child in item.Children)
            {
                RedirectItem rItem = new RedirectItem((Item)child);
                if (rItem.isValid)
                {
                    list.Add(rItem);
                }
            }

            string serialization = Newtonsoft.Json.JsonConvert.SerializeObject(list);

            this.Value = serialization;
        }

        protected override bool LoadPostData(string value)
        {
            value = SC.StringUtil.GetString(new string[1]
            {
                value
            });

            if (this.Value == value)
                return false;

            this.Value = value;

            return true;
        }
    }
}


You can now try to view the field and click on the button: