Home » Sitecore Item Web API

Category Archives: Sitecore Item Web API

Clone Items using the Sitecore Item Web API

Yesterday, I had the privilege to present with Ben Lipson and Jamie Michalski, both of Velir, on the Sitecore Item Web API at the New England Sitecore User Group — if you want to see us in action, check out the recording of our presentation!

Plus, my slides are available here!

During my presentation, I demonstrated how easy it is to customize the Sitecore Item API by adding a custom <itemWebApiRequest> pipeline processor, and a custom pipeline to handle a cloning request — for another example on adding a custom <itemWebApiRequest> pipeline processor, and another pipeline to execute a different custom operation, have a look at this post where I show how to publish Items using the Sitecore Item Web API.

For any custom pipeline you build for the Sitecore Item Web API, you must define a Parameter Object that inherits from Sitecore.ItemWebApi.Pipelines.OperationArgs:

using System.Collections.Generic;

using Sitecore.Data.Items;

using Sitecore.ItemWebApi.Pipelines;

namespace Sitecore.Sandbox.ItemWebApi.Pipelines.Clone
{
    public class CloneArgs : OperationArgs
    {
        public CloneArgs(Item[] scope)
            : base(scope)
        {
        }

        public IEnumerable<Item> Destinations { get; set; }

        public bool IsRecursive { get; set; }

        public IEnumerable<Item> Clones { get; set; }
    }
}

I added three properties to the class above: a property to hold parent destinations for clones; another indicating whether all descendants should be cloned; and a property to hold a collection of the clones.

I then created a base class for processors of my custom pipeline for cloning:

using Sitecore.ItemWebApi.Pipelines;

namespace Sitecore.Sandbox.ItemWebApi.Pipelines.Clone
{
    public abstract class CloneProcessor : OperationProcessor<CloneArgs>
    {
        protected CloneProcessor()
        {
        }
    }
}

The above class inherits from Sitecore.ItemWebApi.Pipelines.OperationProcessor which is the base class for most Sitecore Item Web API pipelines.

The following class serves as one processor of my custom cloning pipeline:

using System.Collections.Generic;

using Sitecore.Data.Items;
using Sitecore.Diagnostics;

namespace Sitecore.Sandbox.ItemWebApi.Pipelines.Clone
{
    public class CloneItems : CloneProcessor
    {
        public override void Process(CloneArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            Assert.ArgumentNotNull(args.Scope, "args.Scope");
            Assert.ArgumentNotNull(args.Destinations, "args.Destinations");
            IList<Item> clones = new List<Item>();
            foreach (Item itemToClone in args.Scope)
            {
                foreach (Item destination in args.Destinations)
                {
                    clones.Add(CloneItem(itemToClone, destination, args.IsRecursive));
                }   
            }

            args.Clones = clones;
        }

        private Item CloneItem(Item item, Item destination, bool isRecursive)
        {
            Assert.ArgumentNotNull(item, "item");
            Assert.ArgumentNotNull(destination, "destination");
            return item.CloneTo(destination, isRecursive);
        }
    }
}

The class above iterates over all Items in scope — these are the Items being cloned — and clones all to the specified destinations (parent Items of the clones).

I then spun up the following class to serve as another processor in my custom cloning pipeline:

using System.Linq;

using Sitecore.Diagnostics;
using Sitecore.Pipelines;

using Sitecore.ItemWebApi.Pipelines.Read;

namespace Sitecore.Sandbox.ItemWebApi.Pipelines.Clone
{
    public class SetResult : CloneProcessor
    {
        public override void Process(CloneArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            Assert.ArgumentNotNull(args.Clones, "args.Clones");
            if (args.Result == null)
            {
                ReadArgs readArgs = new ReadArgs(args.Clones.ToArray());
                CorePipeline.Run("itemWebApiRead", readArgs);
                args.Result = readArgs.Result;
            }
        }
    }
}

The above class delegates to the <itemWebApiRead> pipeline which retrieves the clones from Sitecore, and stores these in the Parameter Object instance for the custom cloning pipeline.

In order to handle custom requests in the Sitecore Item Web API, you must create a custom <itemWebApiRequest> pipeline processor. I put together the following class to handle my cloning operation:

using System;
using System.Collections.Generic;
using System.Linq;

using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.ItemWebApi;
using Sitecore.ItemWebApi.Pipelines.Request;
using Sitecore.Pipelines;
using Sitecore.Text;
using Sitecore.Web;

using Sitecore.Sandbox.ItemWebApi.Pipelines.Clone;

namespace Sitecore.Sandbox.ItemWebApi.Pipelines.Request
{
    public class ResolveCloneAction : RequestProcessor
    {
        public override void Process(RequestArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            Assert.ArgumentNotNullOrEmpty(RequestMethod, "RequestMethod");
            Assert.ArgumentNotNullOrEmpty(MultipleItemsDelimiter, "MultipleItemsDelimiter");
            if (!ShouldProcessRequest(args))
            {
                return;
            }

            IEnumerable<Item> destinations = GetDestinationItems();
            if (!destinations.Any())
            {
                Logger.Warn("Cannot process clone action: there are no destination items!");
                return;
            }
            
            CloneArgs cloneArgs = new CloneArgs(args.Scope) 
            { 
                Destinations = destinations,
                IsRecursive = DoRecursiveCloning() 
            };
            CorePipeline.Run("itemWebApiClone", cloneArgs);
            args.Result = cloneArgs.Result;
        }

        private bool ShouldProcessRequest(RequestArgs args)
        {
            // Is this the request method we care about?
            if (!AreEqualIgnoreCase(args.Context.HttpContext.Request.HttpMethod, RequestMethod))
            {
                return false;
            }

            // are multiple axes supplied?
            if (WebUtil.GetQueryString("scope").Contains(MultipleItemsDelimiter))
            {
                Logger.Warn("Cannot process clone action: multiple axes detected!");
                return false;
            }

            // are there any items in scope?
            if (!args.Scope.Any())
            {
                Logger.Warn("Cannot process clone action: there are no items in Scope!");
                return false;
            }

            return true;
        }

        private static bool AreEqualIgnoreCase(string one, string two)
        {
            return string.Equals(one, two, StringComparison.CurrentCultureIgnoreCase);
        }
        
        private IEnumerable<Item> GetDestinationItems()
        {
            char delimiter;
            Assert.ArgumentCondition(char.TryParse(MultipleItemsDelimiter, out delimiter), "MultipleItemsDelimiter", "MultipleItemsDelimiter must be a single character!");
            ListString destinations = new ListString(WebUtil.GetQueryString("destinations"), delimiter);
            return (from destination in destinations
                    let destinationItem = GetItem(destination)
                    where destinationItem != null
                    select destinationItem).ToList();
        }

        private Item GetItem(string path)
        {
            try
            {
                return Sitecore.ItemWebApi.Context.Current.Database.Items[path];
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }

            return null;
        }

        private bool DoRecursiveCloning()
        {
            bool recursive;
            if (bool.TryParse(WebUtil.GetQueryString("recursive"), out recursive))
            {
                return recursive;
            }
            
            return false;
        }

        private string RequestMethod { get; set; }

        private string MultipleItemsDelimiter { get; set; }
    }
}

The above class ascertains whether it should handle the request: is the RequestMethod passed via configuration equal to the request method detected, and are there any Items in scope? I also built this processor to handle only one axe in order to keep the code simple.

Once the class determines it should handle the request, it grabs all destination Items from the context database — this is Sitecore.ItemWebApi.Context.Current.Database which is populated via the sc_database query string parameter passed via the request.

Further, the class above detects whether the cloning operation is recursive: should we clone all descendants of the Items in scope? This is also passed by a query string parameter.

I then glued everything together using the following Sitecore configuration file:

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <itemWebApiClone>
        <processor type="Sitecore.Sandbox.ItemWebApi.Pipelines.Clone.CloneItems, Sitecore.Sandbox" />
        <processor type="Sitecore.Sandbox.ItemWebApi.Pipelines.Clone.SetResult, Sitecore.Sandbox" />
      </itemWebApiClone>
      <itemWebApiRequest>
        <processor patch:before="*[@type='Sitecore.ItemWebApi.Pipelines.Request.ResolveAction, Sitecore.ItemWebApi']"
                   type="Sitecore.Sandbox.ItemWebApi.Pipelines.Request.ResolveCloneAction, Sitecore.Sandbox">
          <RequestMethod>clone</RequestMethod>
          <MultipleItemsDelimiter>|</MultipleItemsDelimiter>
        </processor>
      </itemWebApiRequest>
    </pipelines>
  </sitecore>
</configuration>

Let’s clone the following Sitecore Item with descendants to two folders:

item-to-clone-destinations

In order to make this happen, I spun up the following HTML page using jQuery — no doubt the front-end gurus reading this are cringing when seeing the following code, but I am not much of a front-end developer:

<!DOCTYPE html>
<html lang="en">
	<head>
		<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
		<script src="//cdnjs.cloudflare.com/ajax/libs/json3/3.3.2/json3.min.js"></script>
		<script src="//cdnjs.cloudflare.com/ajax/libs/prettify/r224/prettify.js"></script>
		<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/prettify/r224/prettify.css" />
	</head>
	<body>
		<img width="400" style="display: block; margin-left: auto; margin-right: auto" src="/assets/img/clone-all-the-things.jpg" />
		<input type="button" id="button" value="Clone" style="width:100px;height:50px;font-size: 24px;" />
		<h2 id="confirmation" style="display: none;">Whoa! Something happened!</h2>
		<div id="working" style="display: none;"><img style="display: block; margin-left: auto; margin-right: auto" src="/assets/img/arrow-working.gif" /></div>
		<pre id="responseContainer" class="prettyprint" style="display: none;"><code id="response" class="language-javascript"></code></pre>
		<script type="text/javascript">
		$('#button').click(function() {
			$('#confirmation').hide();
			$('#responseContainer').hide();
			$('#working').show();
			$.ajax({
					type:'clone',
					url: "http://sandbox7/-/item/v1/sitecore/content/Home/Landing Page One?scope=s&destinations=/sitecore/content/Home/Clones|/sitecore/content/Home/Some More Clones&recursive=true&sc_database=master",
					headers:{
						"X-Scitemwebapi-Username":"extranet\\ItemWebAPI",
						"X-Scitemwebapi-Password":"1t3mW3bAP1"}
				}).done(function(response) {
					$('#confirmation').show();
					$('#response').html(JSON.stringify(response, null, 4));
					$('#working').hide();
					$('#responseContainer').show();
				});
		});
		</script>
	</body>
</html>

Plus, please pardon the hard-coded Sitecore credentials — I know you would never store a username and password in front-end code, right? 😉

The above HTML page looks like this on initial load:

clone-items-html-page-no-data

I then clicked the ‘Clone’ button, and saw the following:

cloned-items-html-page

As you can see, the target Item with descendants were cloned to the destination folders set in the jQuery above:

items-cloned-sitecore

If you have any thoughts on this, or have other ideas around customizing the Sitecore Item Web API, please share in a comment.

Add ‘Has Content In Language’ Property to Sitecore Item Web API Responses

The other day I had read a forum thread on SDN where the poster had asked whether one could determine if content returned from the Sitecore Item Web API for an Item was the actual content for the Item in the requested language.

I was intrigued by this question because I would have assumed that no results would be returned for the Item when it does not have content in the requested language but that is not the case: I had replicated what the poster had seen.

As a workaround, I built the following class to serve as an <itemWebApiGetProperties> pipeline processor which sets a property in the response indicating whether the Item has content in the requested language (check out my previous post on adding additional properties to Sitecore Item Web API responses for more information on this topic):

using System.Collections.Generic;
using System.Linq;

using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Globalization;
using Sitecore.ItemWebApi.Pipelines.GetProperties;

namespace Sitecore.Sandbox.ItemWebApi.Pipelines.GetProperties
{
    public class SetHasContentInLanguageProperty : GetPropertiesProcessor
    {
        public override void Process(GetPropertiesArgs arguments)
        {
            Assert.ArgumentNotNull(arguments, "arguments");
            Assert.ArgumentNotNull(arguments.Item, "arguments.Item");
            arguments.Properties.Add("HasContentInLanguage", IsLanguageInCollection(arguments.Item.Languages, arguments.Item.Language));
        }

        private static bool IsLanguageInCollection(IEnumerable<Language> languages, Language language)
        {
            Assert.ArgumentNotNull(languages, "languages");
            Assert.ArgumentNotNull(language, "language");
            return languages.Any(lang => lang == language);
        }
    }
}

The code in the above class checks to see if the Item has content in the requested language — the latter is set in the Language property of the Item instance, and the Languages property contains a list of all languages it has content for.

I then added the above pipeline processor via the following configuration file:

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <itemWebApiGetProperties>
        <processor patch:after="processor[@type='Sitecore.ItemWebApi.Pipelines.GetProperties.GetProperties, Sitecore.ItemWebApi']"
            type="Sitecore.Sandbox.ItemWebApi.Pipelines.GetProperties.SetHasContentInLanguageProperty, Sitecore.Sandbox" />
      </itemWebApiGetProperties>
    </pipelines>
  </sitecore>
</configuration>

Let’s see how this works!

I first created an Item for testing:

content-in-language-test

This Item only has content in English:

content-in-language-test-en

I then toggled my Sitecore Item Web API configuration to allow for anonymous access so that I can make requests in my browser, and made a request for the test Item in English:

english-has-content

The Item does have content in English, and this is denoted by the ‘HasContentInLanguage’ property.

I then made a request for the Item in French:

french-does-not-have-content

As expected, the ‘HasContentInLanguage’ is false since the Item does not have content in French.

If you have any questions or thoughts on this, please drop a comment.

Set New Media Library Item Fields Via the Sitecore Item Web API

On a recent project, I found the need to set field data on new media library items using the Sitecore Item Web API — a feature that is not supported “out of the box”.

After digging through Sitecore.ItemWebApi.dll, I discovered where one could add the ability to update fields on newly created media library items:

CreateMediaItems-out-of-box

Unfortunately, the CreateMediaItems method in the Sitecore.ItemWebApi.Pipelines.Request.ResolveAction class is declared private — introducing code to set fields on new media library items will require some copying and pasting of code.

Honestly, I loathe duplicating code. 😦

Unfortunately, we must do it in order to add the capability of setting fields on media library items via the Sitecore Item Web API (if you can think of a better way, please leave a comment).

I did just that on the following subclass of Sitecore.ItemWebApi.Pipelines.Request.ResolveAction:

using System;
using System.Collections.Generic;
using System.IO;
using System.Web;

using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.IO;
using Sitecore.ItemWebApi;
using Sitecore.ItemWebApi.Pipelines.Read;
using Sitecore.ItemWebApi.Pipelines.Request;
using Sitecore.Pipelines;
using Sitecore.Resources.Media;
using Sitecore.Text;
using Sitecore.Data.Fields;

namespace Sitecore.Sandbox.ItemWebApi.Pipelines.Request
{
    public class ResolveActionMediaItems : ResolveAction
    {
        protected override void ExecuteCreateRequest(RequestArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            if (IsMediaCreation(args.Context))
            {
                CreateMediaItems(args);
                return;
            }

            base.ExecuteCreateRequest(args);
        }

        private void CreateMediaItems(RequestArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            Item parent = args.Context.Item;
            if (parent == null)
            {
                throw new Exception("The specified location not found.");
            }
            string fullPath = parent.Paths.FullPath;
            if (!fullPath.StartsWith("/sitecore/media library"))
            {
                throw new Exception(string.Format("The specified location of media items is not in the Media Library ({0}).", fullPath));
            }
            string name = args.Context.HttpContext.Request.Params["name"];
            if (string.IsNullOrEmpty(name))
            {
                throw new Exception("Item name not specified (HTTP parameter 'name').");
            }
            Database database = args.Context.Database;
            Assert.IsNotNull(database, "Database not resolved.");
            HttpFileCollection files = args.Context.HttpContext.Request.Files;
            Assert.IsTrue(files.Count > 0, "Files not found.");
            List<Item> list = new List<Item>();

            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFile file = files[i];
                if (file.ContentLength != 0)
                {
                    string fileName = file.FileName;
                    string uniqueName = ItemUtil.GetUniqueName(parent, name);
                    string destination = string.Format("{0}/{1}", fullPath, uniqueName);
                    MediaCreatorOptions options = new MediaCreatorOptions
                    {
                        AlternateText = fileName,
                        Database = database,
                        Destination = destination,
                        Versioned = false
                    };
                    Stream inputStream = file.InputStream;
                    string extension = FileUtil.GetExtension(fileName);
                    string filePath = string.Format("{0}.{1}", uniqueName, extension);
                    try
                    {
                        Item item = MediaManager.Creator.CreateFromStream(inputStream, filePath, options);
                        SetFields(item, args.Context.HttpContext.Request["fields"]); // MR: set field data on item if data is passed
                        list.Add(item);
                    }
                    catch
                    {
                        Logger.Warn("Cannot create the media item.");
                    }
                }
            }
            ReadArgs readArgs = new ReadArgs(list.ToArray());
            CorePipeline.Run("itemWebApiRead", readArgs);
            args.Result = readArgs.Result;
        }

        private static void SetFields(Item item, string fieldsQueryString)
        {
            if (!string.IsNullOrWhiteSpace(fieldsQueryString))
            {
                SetFields(item, new UrlString(fieldsQueryString));
            }
        }

        private static void SetFields(Item item, UrlString fields)
        {
            Assert.ArgumentNotNull(item, "item");
            Assert.ArgumentNotNull(fields, "fields");

            if (fields.Parameters.Count < 1)
            {
                return;
            }

            item.Editing.BeginEdit();

            foreach (string fieldName in fields.Parameters.Keys)
            {
                Field field = item.Fields[fieldName];
                if(field != null)
                {
                    field.Value = fields.Parameters[fieldName];
                }
            }

            item.Editing.EndEdit();
        }

        private bool IsMediaCreation(Sitecore.ItemWebApi.Context context)
        {
            Assert.ArgumentNotNull(context, "context");
            return context.HttpContext.Request.Files.Count > 0;
        }
    }
}

The above class reads fields supplied by client code via a query string passed in a query string parameter — the fields query string must be “url encoded” by the client code before being passed in the outer query string.

We then delegate to an instance of the Sitecore.Text.UrlString class when fields are supplied by client code — if you don’t check to see if the query string is null, empty or whitespace, the UrlString class will throw an exception if it’s not set — to parse the fields query string, and loop over the parameters within it — each parameter represents a field to be set on the item, and is set if it exists (see the SetFields methods above).

I replaced Sitecore.ItemWebApi.Pipelines.Request.ResolveAction in \App_Config\Include\Sitecore.ItemWebApi.config with our new pipeline processor above:

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
	<sitecore>
		<pipelines>
		<!-- there is more stuff up here -->
		<!--Processes Item Web API requests. -->
		<itemWebApiRequest>
			<!-- there are more pipeline processors up here -->
			<processor type="Sitecore.Sandbox.ItemWebApi.Pipelines.Request.ResolveActionMediaItems, Sitecore.Sandbox" />
			<!-- there are more pipeline processors down here -->
		</itemWebApiRequest>
		<!-- there is more stuff down here -->
		</pipelines>
	</sitecore>
</configuration>

I then modified the media library item creation code in my copy of the console application written by Kern Herskind Nightingale — Director of Technical Services at Sitecore UK — to send field data to the Sitecore Item Web API:

create-media-console-2

I set some fields using test data:

create-media-console-1

After I ran the console application, I got a response — this is a good sign 🙂

pizza-created-result

As you can see, our test field data has been set on our pizza media library item:

pizza-in-media-library

If you have any thoughts or suggestions on this, please drop a comment.

Now I’m hungry — perhaps I’ll order a pizza! 🙂

Change the Data Serialization Format in the Sitecore Item Web API

I had a major urge yesterday to continue my tinkering of the Sitecore Item Web API, and wondered how one would go about changing the serialization format of its response.

Without re-reading the documentation on how one could go about doing this — I forgot that this was discussed in its documentation (check out pages 16-17 in the Sitecore Item Web API 1.0.0 Developer’s Guide where you can see how to use an XML serializer) — I tackled this by experimentation, and came up with a slightly different solution than the one offered in the Developer’s Guide.

I considered using an XML serializer for this blog post, but decided to fish around on the internet to see what other data serialization formats exist, and discovered YAML — a format that looks similar to JSON.

I continued my internet surfing — I mean research — and found a .NET library — YamlDotNet — that assists developers in converting objects into YAML, and decided to give it a go.

The following Sitecore item Web API Serializer uses this YAML library:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

using Sitecore.Diagnostics;
using Sitecore.ItemWebApi.Serialization;

using YamlDotNet.RepresentationModel.Serialization;

namespace Sitecore.Sandbox.ItemWebApi.Serialization
{
    public class YamlSerializer : ISerializer
    {
        // Serializer in YamlDotNet.RepresentationModel.Serialization
        private static readonly Serializer Serializer = new Serializer();

        public YamlSerializer()
        {
        }

        public string Serialize(object value)
        {
            Assert.ArgumentNotNull(value, "value");
            string yaml = string.Empty;
            using(StringWriter stringWriter = new StringWriter())
            {
                Serializer.Serialize(stringWriter, value);
                yaml = stringWriter.ToString();
            }

            return yaml;
        }

        public string SerializedDataMediaType
        {
            get
            {
                return "application/x-yaml";
            }
        }
    }
}

The Serializer above just delegates responsibility to the YamlDotNet’s YAML serializer.

Now that we have our YamlSerializer ready to go, we have to somehow wire it up to the Sitecore Item Web API.

After some digging in Sitecore.ItemWebApi.dll, I learned the out of the box JsonSerializer is set in a preprocessRequest pipeline processor:

JsonSerializer

Following this lead, I created a custom preprocessRequest pipeline processor for setting our new YamlSerializer:

using System;
using System.Web;

using Sitecore.Pipelines.PreprocessRequest;
using Sitecore.Diagnostics;
using Sitecore.ItemWebApi.Serialization;

using Sitecore.Sandbox.ItemWebApi.Serialization;

namespace Sitecore.Sandbox.ItemWebApi.Pipelines.PreprocessRequest
{
    public class ResolveSerializer : PreprocessRequestProcessor
    {
        public override void Process(PreprocessRequestArgs arguments)
        {
            Assert.ArgumentNotNull(arguments, "arguments");
            Assert.ArgumentNotNull(arguments.Context, "arguments.Context");
            Assert.ArgumentNotNull(arguments.Context.Request, "arguments.Context.Request");
            ISerializer serializer = GetSerializer(arguments.Context.Request);
            if (serializer != null)
            {
                Sitecore.ItemWebApi.Context.Current.Serializer = serializer;
            }
        }

        private static ISerializer GetSerializer(HttpRequest request)
        {
            if(IsYamlRequest(request))
            {
                return new YamlSerializer();
            }

            return null;
        }

        private static bool IsYamlRequest(HttpRequest request)
        {
            Assert.ArgumentNotNull(request, "request");
            return string.Equals(request["format"], "yaml", StringComparison.CurrentCultureIgnoreCase);
        }
    }
}

We only set our YamlSerializer when client code requests data to be returned as YAML — this is made known when the client code sets “Yaml” in a HTTP request parameter named “format” (an example of this would be &format=Yaml via a query string).

I then added the new preprocessRequest pipeline processor in \App_Config\Include\Sitecore.ItemWebApi.config, and made sure it’s called right after /configuration/sitecore/pipelines/preprocessRequest/processor[@type=”Sitecore.ItemWebApi.Pipelines.PreprocessRequest.RewriteUrl, Sitecore.ItemWebApi”] — default instances are set here on the Sitecore Item Web API’s Context instance, and we should ensure this object exits before changing properties on it:

<?xml version="1.0" encoding="utf-8"?>
	<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
		<sitecore>
			<pipelines>
			<!-- there is stuff up here -->
				<preprocessRequest>
					<processor type="Sitecore.Sandbox.ItemWebApi.Pipelines.PreprocessRequest.ResolveSerializer, Sitecore.Sandbox" patch:before="processor[@type='Sitecore.Pipelines.PreprocessRequest.CheckIgnoreFlag, Sitecore.Kernel']" />
					<processor type="Sitecore.ItemWebApi.Pipelines.PreprocessRequest.RewriteUrl, Sitecore.ItemWebApi" patch:before="processor[@type='Sitecore.Sandbox.ItemWebApi.Pipelines.PreprocessRequest.ResolveSerializer, Sitecore.Sandbox']" />
				</preprocessRequest>
			<!-- and more stuff down here -->
		</sitecore>
	</configuration>

After modifying some code in my copy of the console application written by Kern Herskind Nightingale, Director of Technical Services at Sitecore UK — I added &format=yaml as a query string parameter — I invoked it to retrieve an item in my local instance of Sitecore:

yaml-output

As you can see, the response is now in YAML.

If you have any thoughts on this, or have any recommendations on using other serialization formats, please drop a comment.

Publish Items With the Sitecore Item Web API Using a Custom ResolveAction itemWebApiRequest Pipeline Processor

At the end of last week, when many people were probably thinking about what to do over the weekend, or were making plans with family and/or friends, I started thinking about what I might need to do next on the project I’m working on.

I realized I might need a way to publish Sitecore items I’ve touched via the Sitecore Item Web API — a feature that appears to be missing, or I just cannot figure out how to use from its documentation (if there is a way to do this “out of the box”, please share in a comment below).

After some digging around in Sitecore.ItemWebApi.dll and \App_Config\Include\Sitecore.ItemWebApi.config, I thought it would be a good idea to define a new action that employs a request method other than get, post, put, delete — these request methods are used by a vanilla install of the Sitecore Item Web API.

Where would one find a list of “standard” request methods? Of course Google knows all — I learned about the patch request method, and decided to use it.

According to Wikipedia — see this entry subsection discussing request methods — the patch request method is “used to apply partial modifications to a resource”, and one could argue that a publishing an item in Sitecore is a partial modification to that item — it’s being pushed to another database which is really an update on that item in the target database.

Now that our research is behind us — and we’ve learned about the patch request method — let’s get our hands dirty with some code.

Following the pipeline processor convention set forth in code for the Sitecore Item Web API for other request methods, I decide to box our new patch requests into a new pipeline, and doing this called for creating a new data transfer object for the new pipeline processor we will define below:

using Sitecore.Data.Items;

using Sitecore.ItemWebApi.Pipelines;

namespace Sitecore.Sandbox.ItemWebApi.Pipelines.Patch.DTO
{
    public class PatchArgs : OperationArgs
    {
        public PatchArgs(Item[] scope)
            : base(scope)
        {
        }
    }
}

Next, I created a base class for our new patch processor:

using Sitecore.ItemWebApi.Pipelines;

using Sitecore.Sandbox.ItemWebApi.Pipelines.Patch.DTO;

namespace Sitecore.Sandbox.ItemWebApi.Pipelines.Patch
{
    public abstract class PatchProcessor : OperationProcessor<PatchArgs>
    {
        protected PatchProcessor()
        {
        }
    }
}

I then created a new pipeline processor that will publish items passed to it:

using System;
using System.Collections.Generic;
using System.Linq;

using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.ItemWebApi;
using Sitecore.Publishing;
using Sitecore.Web;

using Sitecore.Sandbox.ItemWebApi.Pipelines.Patch.DTO;

namespace Sitecore.Sandbox.ItemWebApi.Pipelines.Patch
{
    public class PublishScope : PatchProcessor
    {
        private string DefaultTargetDatabase { get; set; }

        public override void Process(PatchArgs arguments)
        {
            Assert.ArgumentNotNull(arguments, "arguments");
            Assert.IsNotNull(arguments.Scope, "The scope is null!");
            PublishItems(arguments.Scope, GetTargetDatabase());
            arguments.Result = GetResult(arguments.Scope);
        }

        private Database GetTargetDatabase()
        {
            return Factory.GetDatabase(GetTargetDatabaseName());
        }

        private string GetTargetDatabaseName()
        {
            string databaseName = WebUtil.GetQueryString("sc_target_database");
            if(!string.IsNullOrWhiteSpace(databaseName))
            {
                return databaseName;
            }

            Assert.IsNotNullOrEmpty(DefaultTargetDatabase, "DefaultTargetDatabase must be set!");
            return DefaultTargetDatabase;
        }

        private static void PublishItems(IEnumerable<Item> items, Database database)
        {
            foreach(Item item in items)
            {
                PublishItem(item, database);
            }
        }

        private static void PublishItem(Item item, Database database)
        {
           PublishOptions publishOptions = new PublishOptions
           (
               item.Database,
               database,
               Sitecore.Publishing.PublishMode.SingleItem,
               item.Language,
               DateTime.Now
           );

            Publisher publisher = new Publisher(publishOptions);
            publisher.Options.RootItem = item;
            publisher.Publish();
        }

        private static Dynamic GetResult(IEnumerable<Item> scope)
        {
            Assert.ArgumentNotNull(scope, "scope");
            Dynamic dynamic = new Dynamic();
            dynamic["statusCode"] = 200;
            dynamic["result"] = GetInnerResult(scope);
            return dynamic;
        }

        private static Dynamic GetInnerResult(IEnumerable<Item> scope)
        {
            Assert.ArgumentNotNull(scope, "scope");
            Dynamic dynamic = new Dynamic();
            dynamic["count"] = scope.Count();
            dynamic["itemIds"] = scope.Select(item => item.ID.ToString());
            return dynamic;
        }
    }
}

The above pipeline processor class serially publishes each item passed to it, and returns a Sitecore.ItemWebApi.Dynamic instance containing information on how many items were published; a collection of IDs of the items that were published; and an OK status code.

If the calling code does not supply a publishing target database via the sc_target_database query string parameter, the processor will use the value defined in DefaultTargetDatabase — this value is set in \App_Config\Include\Sitecore.ItemWebApi.config, which you will see later when I show changes I made to this file.

It had been awhile since I’ve had to publish items in code, so I searched for a refresher on how to do this.

In my quest for some Sitecore API code, I rediscovered this article by Sitecore MVP
Brian Pedersen showing how one can publish Sitecore items programmatically — many thanks to Brian for this article!

If you haven’t read Brian’s article, you should go check it out now. Don’t worry, I’ll wait. 🙂

I then created a new ResolveAction itemWebApiRequest pipeline processor:

using System;

using Sitecore.Diagnostics;
using Sitecore.Exceptions;
using Sitecore.ItemWebApi.Pipelines.Request;
using Sitecore.ItemWebApi.Security;
using Sitecore.Pipelines;

using Sitecore.Sandbox.ItemWebApi.Pipelines.Patch.DTO;

namespace Sitecore.Sandbox.ItemWebApi.Pipelines.Request
{
    public class ResolveAction : Sitecore.ItemWebApi.Pipelines.Request.ResolveAction
    {
        public override void Process(RequestArgs requestArgs)
        {
            Assert.ArgumentNotNull(requestArgs, "requestArgs");
            string method = GetMethod(requestArgs.Context);
            AssertOperation(requestArgs, method);
            
            if(IsCreateRequest(method))
            {
	            ExecuteCreateRequest(requestArgs);
	            return;
            }

            if(IsReadRequest(method))
            {
	            ExecuteReadRequest(requestArgs);
	            return;
            }

            if(IsUpdateRequest(method))
            {
               ExecuteUpdateRequest(requestArgs);
               return;
            }

            if(IsDeleteRequest(method))
            {
	            ExecuteDeleteRequest(requestArgs);
	            return;
            }

            if (IsPatchRequest(method))
            {
	            ExecutePatchRequest(requestArgs);
	            return;
            }
        }

        private static void AssertOperation(RequestArgs requestArgs, string method)
        {
            Assert.ArgumentNotNull(requestArgs, "requestArgs");
            if (requestArgs.Context.Settings.Access == AccessType.ReadOnly && !AreEqual(method, "get"))
            {
                throw new AccessDeniedException("The operation is not allowed.");
            }
        }

        private static bool IsCreateRequest(string method)
        {
            return AreEqual(method, "post");
        }

        private static bool IsReadRequest(string method)
        {
            return AreEqual(method, "get");
        }

        private static bool IsUpdateRequest(string method)
        {
            return AreEqual(method, "put");
        }

        private static bool IsDeleteRequest(string method)
        {
            return AreEqual(method, "delete");
        }

        private static bool IsPatchRequest(string method)
        {
            return AreEqual(method, "patch");
        }

        private static bool AreEqual(string one, string two)
        {
            return string.Equals(one, two, StringComparison.InvariantCultureIgnoreCase);
        }

        protected virtual void ExecutePatchRequest(RequestArgs requestArgs)
        {
            Assert.ArgumentNotNull(requestArgs, "requestArgs");
            PatchArgs patchArgsArgs = new PatchArgs(requestArgs.Scope);
            CorePipeline.Run("itemWebApiPatch", patchArgsArgs);
            requestArgs.Result = patchArgsArgs.Result;
        }

        private string GetMethod(Sitecore.ItemWebApi.Context context)
        {
            Assert.ArgumentNotNull(context, "context");
            return context.HttpContext.Request.HttpMethod.ToLower();
        }
    }
}

The class above contains the same logic as Sitecore.ItemWebApi.Pipelines.Request.ResolveAction, though I refactored it a bit — the nested conditional statements in the Process method were driving me bonkers, and I atomized logic by placing into new methods.

Plus, I added an additional check to see if the request we are to execute is a patch request — this is true when HttpContext.Request.HttpMethod.ToLower() in our Sitecore.ItemWebApi.Context instance is equal to “patch” — and call our new patch pipeline if this is the case.

I then added the new itemWebApiPatch pipeline with its new PublishScope processor, and replaced /configuration/sitecore/pipelines/itemWebApiRequest/processor[@type=”Sitecore.ItemWebApi.Pipelines.Request.ResolveAction, Sitecore.ItemWebApi”] with /configuration/sitecore/pipelines/itemWebApiRequest/processor[@type=”Sitecore.Sandbox.ItemWebApi.Pipelines.Request.ResolveAction, Sitecore.Sandbox”] in \App_Config\Include\Sitecore.ItemWebApi.config:

<?xml version="1.0" encoding="utf-8"?>
	<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
		<sitecore>
			<pipelines>
				<itemWebApiRequest>
					<!-- stuff is defined up here -->
					<processor type="Sitecore.Sandbox.ItemWebApi.Pipelines.Request.ResolveAction, Sitecore.Sandbox" />
					<!-- stuff is defined right here -->
				</itemWebApiRequest>
				<!-- more stuff is defined here -->
				<itemWebApiPatch>
					<processor type="Sitecore.Sandbox.ItemWebApi.Pipelines.Patch.PublishScope, Sitecore.Sandbox">
						<DefaultTargetDatabase>web</DefaultTargetDatabase>
					</processor>
				</itemWebApiPatch>
			</pipelines>
			<!-- there's even more stuff defined down here -->
		</sitecore>
	</configuration>

Let’s test this out, and see how we did.

We’ll be publishing these items:

master-items-to-publish

As you can see, they aren’t in the web database right now:

arent-there-yet-web

I had to modify code in my copy of the console application written by Kern Herskind Nightingale, Director of Technical Services at Sitecore UK, to use the patch request method for the ancestor home item shown above, and set a scope of self and recursive (scope=s|r) — checkout out this post where I added the recursive axe to the Sitecore Item Web API. I am excluding the console application code modification for the sake of brevity.

I then ran the console application above, and saw this:

after-publishing-output

All of these items now live in the web database:

all-in-web-after-publish

If you have any thoughts on this, or ideas on other useful actions for the Sitecore Item Web API, please drop a comment.

Expand Your Scope: Add Additional Axes Via a Custom Sitecore Item Web API itemWebApiRequest Pipeline Processor

The Sitecore Item Web API offers client code the choice of retrieving an Item’s parent, the Item itself, all of its children, or any combination of these by simply setting the scope query string parameter in the request.

For example, if you want an Item’s children, you would only set the scope query string parameter to be the axe “c” — this would be scope=c — or if you wanted all data for the Item and its children, you would just set the scope query string parameter to be the self and children axes separated by a pipe — e.g. scope=s|c. Multiple axes must be separated by a pipe.

The other day, however, for my current project, I realized I needed a way to retrieve all data for an Item and all of its descendants via the Sitecore Item Web API.

The three options that ship with the Sitecore Item Web API cannot help me here, unless I want to make multiple requests to get data for an Item and all of it’s children, and then loop over all children and get their children, ad infinitum (well, hopefully it does stop somewhere).

Such a solution would require more development time — I would have to write additional code to do all of the looping — and this would — without a doubt — yield poorer performance versus getting all data upfront in a single request.

Through my excavating efforts in \App_Config\Include\Sitecore.ItemWebApi.config and Sitecore.ItemWebApi.dll, I discovered we can replace this “out of the box” functionality — this lives in /configuration/sitecore/pipelines/itemWebApiRequest/processor[@type=”Sitecore.ItemWebApi.Pipelines.Request.ResolveScope, Sitecore.ItemWebApi”] in the Sitecore.ItemWebApi.config — via a custom itemWebApiRequest pipeline processor.

I thought it would be a good idea to define each of our scope operations in its own pipeline processor, albeit have all of these pipeline processors be nested within our itemWebApiRequest pipeline processor.

For the lack of a better term, I’m calling each of these a scope sub-pipeline processor (if you can think of a better name, or have seen this approach done before, please drop a comment).

The first thing I did was create a custom processor class to house two additional properties for our sub-pipeline processor:

using System.Xml;

using Sitecore.Pipelines;
using Sitecore.Diagnostics;

namespace Sitecore.Sandbox.ItemWebApi.Pipelines.Request
{
    public class ScopeProcessor : Processor
    {
        public string Suppresses { get; private set; }
        public string QueryString { get; private set; }

        public ScopeProcessor(XmlNode configNode)
            : base(GetAttributeValue(configNode, "name"), GetAttributeValue(configNode, "type"), GetAttributeValue(configNode, "methodName"))
        {
            Suppresses = GetAttributeValue(configNode, "suppresses");
            QueryString = GetAttributeValue(configNode, "queryString");
        }
        public ScopeProcessor(string name, string type, string methodName, string suppresses, string queryString)
            : base(name, type, methodName)
        {
            Suppresses = suppresses;
            QueryString = queryString;
        }

        private static string GetAttributeValue(XmlNode configNode, string attributeName)
        {
            Assert.ArgumentNotNull(configNode, "configNode");
            Assert.ArgumentNotNullOrEmpty(attributeName, "attributeName");
            XmlAttribute attribute = configNode.Attributes[attributeName];

            if (attribute != null)
            {
                return attribute.Value;
            }

            return string.Empty;
        }
    }
}

The QueryString property will contain the axe for the given scope, and Suppresses property maps to another scope sub-pipeline processor query string value that will be ignored when both are present.

I then created a new PipelineArgs class for the scope sub-pipeline processors:

using System.Collections.Generic;

using Sitecore.Data.Items;
using Sitecore.Pipelines;

namespace Sitecore.Sandbox.ItemWebApi.Pipelines.Request.DTO
{
    public class ScopeProcessorRequestArgs : PipelineArgs
    {
        private List<Item> _Items;
        public List<Item> Items
        {
            get
            {
                if (_Items == null)
                {
                    _Items = new List<Item>();
                }

                return _Items;
            }
            set
            {
                _Items = value;
            }
        }


        private List<Item> _Scope;
        public List<Item> Scope
        {
            get
            {
                if (_Scope == null)
                {
                    _Scope = new List<Item>();
                }

                return _Scope;
            }
            set
            {
                _Scope = value;
            }
        }

        public ScopeProcessorRequestArgs()
        {
        }
    }
}

Basically, the above class just holds Items that will be processed, and keeps track of Items in scope — these Items are added via the scope sub-pipeline processors for the supplied axes.

Now it’s time for our itemWebApiRequest pipeline processor:

using System.Collections.Generic;
using System.Linq;
using System.Xml;

using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.ItemWebApi;
using Sitecore.ItemWebApi.Pipelines.Request;
using Sitecore.Web;

using Sitecore.Sandbox.ItemWebApi.Pipelines.Request.DTO;

namespace Sitecore.Sandbox.ItemWebApi.Pipelines.Request
{
    public class ResolveScope : RequestProcessor
    {
        private IDictionary<string, ScopeProcessor> _ScopeProcessors;
        private IDictionary<string, ScopeProcessor> ScopeProcessors
        {
            get
            {
                if(_ScopeProcessors == null)
                {
                    _ScopeProcessors = new Dictionary<string, ScopeProcessor>();
                }

                return _ScopeProcessors;
            }
        }

        public override void Process(RequestArgs arguments)
        {
            if(!HasItemsInSet(arguments))
            {
                return;
            }

            arguments.Scope = GetItemsInScope(arguments).ToArray();
        }

        private static bool HasItemsInSet(RequestArgs arguments)
        {
            Assert.ArgumentNotNull(arguments, "arguments");
            Assert.ArgumentNotNull(arguments.Items, "arguments.Items");
            if (arguments.Items.Length < 1)
            {
                Logger.Warn("Cannot resolve the scope because the item set is empty.");
                arguments.Scope = new Item[0];
                return false;
            }

            return true;
        }

        private IEnumerable<Item> GetItemsInScope(RequestArgs arguments)
        {
            List<Item> itemsInScope = new List<Item>();
            foreach (Item item in arguments.Items)
            {
                ScopeProcessorRequestArgs args = new ScopeProcessorRequestArgs();
                args.Items.Add(item);
                GetItemsInScope(args);
                itemsInScope.AddRange(args.Scope);
            }

            return itemsInScope;
        }

        private void GetItemsInScope(ScopeProcessorRequestArgs arguments)
        {
            IEnumerable<ScopeProcessor> scopeProcessors = GetScopeProcessorsForRequest();
            foreach (ScopeProcessor scopeProcessor in scopeProcessors)
            {
                scopeProcessor.Invoke(arguments);
            }
        }

        private IEnumerable<ScopeProcessor> GetScopeProcessorsForRequest()
        {
            List<ScopeProcessor> scopeProcessors = GetScopeProcessorsForAxes();
            List<ScopeProcessor> scopeProcessorsForRequest = new List<ScopeProcessor>();
            foreach(ScopeProcessor scopeProcessor in scopeProcessors)
            {
                bool canAddProcessor = !scopeProcessors.Exists(processor => processor.Suppresses.Equals(scopeProcessor.QueryString));
                if (canAddProcessor)
                {
                    scopeProcessorsForRequest.Add(scopeProcessor);
                }
            }

            return scopeProcessorsForRequest;
        }

        private List<ScopeProcessor> GetScopeProcessorsForAxes()
        {
            List<ScopeProcessor> scopeProcessors = new List<ScopeProcessor>();
            foreach (string axe in GetAxes())
            {
                ScopeProcessor scopeProcessor;
                ScopeProcessors.TryGetValue(axe, out scopeProcessor);
                if(scopeProcessor != null && !scopeProcessors.Contains(scopeProcessor))
                {
                    scopeProcessors.Add(scopeProcessor);
                }
            }

            return scopeProcessors;
        }

        private IEnumerable<string> GetAxes()
        {
            string queryString = WebUtil.GetQueryString("scope", null);
            if (string.IsNullOrWhiteSpace(queryString))
            {
                return new string[] { "s" };
            }

            return queryString.Split(new char[] { '|' }).Distinct();
        }

        private IEnumerable<string> GetScopeProcessorQueryStringValues()
        {
            return ScopeProcessors.Values.Select(scopeProcessors => scopeProcessors.QueryString).ToList();
        }

        public virtual void AddScopeProcessor(XmlNode configNode)
        {
            ScopeProcessor scopeProcessor = new ScopeProcessor(configNode);
            bool canAdd = !string.IsNullOrEmpty(scopeProcessor.QueryString)
                            && !ScopeProcessors.ContainsKey(scopeProcessor.QueryString);

            if (canAdd)
            {
                ScopeProcessors.Add(scopeProcessor.QueryString, scopeProcessor);
            }
        }

        public virtual void AddItemSelf(ScopeProcessorRequestArgs arguments)
        {
            foreach (Item item in arguments.Items)
            {
                arguments.Scope.AddRange(GetCanBeReadItems(new Item[] { item }));
            }
        }

        public virtual void AddItemParent(ScopeProcessorRequestArgs arguments)
        {
            foreach (Item item in arguments.Items)
            {
                arguments.Scope.AddRange(GetCanBeReadItems(new Item[] { item.Parent }));
            }
        }
            
        public virtual void AddItemDescendants(ScopeProcessorRequestArgs arguments)
        {
            foreach (Item item in arguments.Items)
            {
                arguments.Scope.AddRange(GetCanBeReadItems(item.Axes.GetDescendants()));
            }
        }

        public virtual void AddItemChildren(ScopeProcessorRequestArgs arguments)
        {
            foreach(Item item in arguments.Items)
            {
                arguments.Scope.AddRange(GetCanBeReadItems(item.GetChildren()));
            }
        }

        private static IEnumerable<Item> GetCanBeReadItems(IEnumerable<Item> list)
        {
            if (list == null)
            {
                return new List<Item>();
            }

            return list.Where(item => CanReadItem(item));
        }

        private static bool CanReadItem(Item item)
        {
            return Context.Site.Name != "shell"
                    && item.Access.CanRead()
                    && item.Access.CanReadLanguage();
        }
    }
}

When this class is instantiated, each scope sub-pipeline processor is added to a dictionary, keyed by its query string axe value.

When this processor is invoked, it performs some validation — similarly to what is being done in the “out of the box” Sitecore.ItemWebApi.Pipelines.Request.ResolveScope class — and determines which scope processors are applicable for the given request. Only those that found in the dictionary via the supplied axes are used, minus those that are suppressed.

Once the collection of scope sub-pipeline processors is in place, each are invoked with a ScopeProcessorRequestArgs instance containing an Item to be processed.

When a scope sub-pipeline processor is done executing, Items that were retrieved from it are added into master list of scope Items to be returned to the caller.

I then glued all of this together — including the scope sub-pipeline processors — in \App_Config\Include\Sitecore.ItemWebApi.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <!-- stuff is defined up here too -->
      <itemWebApiRequest>
		<!-- stuff is defined up here -->
		<processor type="Sitecore.Sandbox.ItemWebApi.Pipelines.Request.ResolveScope, Sitecore.Sandbox">
		  <scopeProcessors hint="raw:AddScopeProcessor">
			<scopeProcessor type="Sitecore.Sandbox.ItemWebApi.Pipelines.Request.ResolveScope, Sitecore.Sandbox" methodName="AddItemSelf" name="self" queryString="s" />
			<scopeProcessor type="Sitecore.Sandbox.ItemWebApi.Pipelines.Request.ResolveScope, Sitecore.Sandbox" methodName="AddItemParent" name="parent" queryString="p" />
			<scopeProcessor type="Sitecore.Sandbox.ItemWebApi.Pipelines.Request.ResolveScope, Sitecore.Sandbox" methodName="AddItemDescendants" name="recursive" queryString="r" suppresses="c" />
			<scopeProcessor type="Sitecore.Sandbox.ItemWebApi.Pipelines.Request.ResolveScope, Sitecore.Sandbox" methodName="AddItemChildren" name="children" queryString="c" />
		  </scopeProcessors>
		</processor>
		<!-- some stuff is defined down here -->
		</itemWebApiRequest>
    </pipelines>
      <!-- there's more stuff defined down here -->
  </sitecore>
</configuration>

Let’s take the above for a spin.

First we need some items for testing. Lucky for me, I hadn’t cleaned up after myself when creating a previous blog post — yes, now I have a legitimate excuse for not picking up after myself — so let’s use these for testing:

items-in-sitecore-scope

After modifying some code in my copy of the console application written by Kern Herskind Nightingale, Director of Technical Services at Sitecore UK — I updated which item we are requesting conjoined for our scope query string parameter (scope=r) — I launched it to retrieve our test items:

scope-request-output

If you have any thoughts on this, or ideas on improving the above, please leave a comment.

Go Green: Put Items in the Recycle Bin When Deleting Via the Sitecore Item Web API

This morning I discovered that items are permanently deleted by the Sitecore Item Web API during a delete action. This is probably called out somewhere in its developer’s guide but I don’t recall having read this.

Regardless of whether it’s highlighted somewhere in documentation, I decided to investigate why this happens.

After combing through Sitecore Item Web API pipelines defined in \App_Config\Include\Sitecore.ItemWebApi.config and code in Sitecore.ItemWebApi.dll, I honed in on the following:

delete-scope-bye-bye

This above code lives in the only itemWebApiDelete pipeline processor that comes with the Sitecore Item Web API, and this processor can be found at /configuration/sitecore/pipelines/itemWebApiDelete/processor[@type=”Sitecore.ItemWebApi.Pipelines.Delete.DeleteScope, Sitecore.ItemWebApi”] in the \App_Config\Include\Sitecore.ItemWebApi.config file.

I don’t know about you, but I’m not always comfortable with deleting items permanently in Sitecore. I heavily rely on Sitecore’s Recycle Bin — yes, I have deleted items erroneously in the past, but recovered quickly by restoring them from the Recycle Bin (I hope I’m not the only one who has done this. :-/)

Unearthing the above prompted me to write a new itemWebApiDelete pipeline processor that puts items in the Recycle Bin when the Recycle Bin setting — see /configuration/sitecore/settings/setting[@name=”RecycleBinActive”] in the Web.config — is enabled:

using System.Collections.Generic;
using System.Linq;

using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.ItemWebApi;
using Sitecore.ItemWebApi.Pipelines.Delete;

namespace Sitecore.Sandbox.ItemWebApi.Pipelines.Delete
{
    public class RecycleScope : DeleteProcessor
    {
        private const int OKStatusCode = 200;

        public override void Process(DeleteArgs arguments)
        {
            Assert.ArgumentNotNull(arguments, "arguments");
            IEnumerable<Item> itemsToDelete = arguments.Scope;
            DeleteItems(itemsToDelete);
            arguments.Result = GetStatusInformation(OKStatusCode, GetDeletionInformation(itemsToDelete));
        }

        private static void DeleteItems(IEnumerable<Item> itemsToDelete)
        {
            foreach (Item itemToDelete in itemsToDelete)
            {
                DeleteItem(itemToDelete);
            }
        }

        private static void DeleteItem(Item itemToDelete)
        {
            Assert.ArgumentNotNull(itemToDelete, "itemToDelete");

            // put items in the recycle bin if it's turned on
            if (Settings.RecycleBinActive)
            {
                itemToDelete.Recycle();
            }
            else
            {
                itemToDelete.Delete();
            }
        }

        private static Dynamic GetDeletionInformation(IEnumerable<Item> itemsToDelete)
        {
            return GetDeletionInformation(itemsToDelete.Count(), GetItemIds(itemsToDelete));
        }

        private static Dynamic GetDeletionInformation(int count, IEnumerable<ID> itemIds)
        {
            Dynamic deletionInformation = new Dynamic();
            deletionInformation["count"] = count;
            deletionInformation["itemIds"] = itemIds.Select(id => id.ToString());
            return deletionInformation;
        }

        private static IEnumerable<ID> GetItemIds(IEnumerable<Item> items)
        {
            Assert.ArgumentNotNull(items, "items");
            return items.Select(item => item.ID);
        }

        private static Dynamic GetStatusInformation(int statusCode, Dynamic result)
        {
            Assert.ArgumentNotNull(result, "result");
            Dynamic status = new Dynamic();
            status["statusCode"] = statusCode;
            status["result"] = result;
            return status;
        }
    }
}

There really isn’t anything magical about the code above. It utilizes most of the same logic that comes with the itemWebApiDelete pipeline processor that ships with the Sitecore Item Web API, although I did move code around into new methods.

The only major difference is the invocation of the Recycle method on item instances when the Recycle Bin is enabled in Sitecore. If the Recycle Bin is not enabled, we call the Delete method instead — as does the “out of the box” pipeline processor.

I then replaced the existing itemWebApiDelete pipeline processor in \App_Config\Include\Sitecore.ItemWebApi.config with our new one defined above:

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <!-- stuff is defined up here -->
      <itemWebApiDelete>
        <processor type="Sitecore.Sandbox.ItemWebApi.Pipelines.Delete.RecycleScope, Sitecore.Sandbox" />
	  </itemWebApiDelete>
      <!-- there's more stuff defined down here -->
  </sitecore>
</configuration>

Let’s see this in action.

We first need a test item. Let’s create one together:

recycle-item-web-api-delete-test-item

I then tweaked the delete method in my copy of the console application written by Kern Herskind Nightingale, Director of Technical Services at Sitecore UK, to point to our test item in the master database — I have omitted this code for the sake of brevity — and then ran the console application calling the delete method only:

test-item-delete-console-response

As you can see, our test item is now in the Recycle Bin:

test-item-recycle-bin

If you have any thoughts on this, please leave a comment.

Add Additional Item Properties in Sitecore Item Web API Responses

The other day I was exploring pipelines of the Sitecore Item Web API, and took note of the itemWebApiGetProperties pipeline. This pipeline adds information about an item in the response returned by the Sitecore Item Web API. You can find this pipeline at /configuration/sitecore/pipelines/itemWebApiGetProperties in \App_Config\Include\Sitecore.ItemWebApi.config.

The following properties are set for an item in the response via the lonely pipeline processor — /configuration/sitecore/pipelines/itemWebApiGetProperties/processor[@type=”Sitecore.ItemWebApi.Pipelines.GetProperties.GetProperties, Sitecore.ItemWebApi”] — that ships with the Sitecore Item Web API:

out-of-the-box-properties

Here’s an example of what the properties set by the above pipeline processor look like in the response — I invoked a read request to the Sitecore Item Web API via a copy of the console application written by Kern Herskind Nightingale, Director of Technical Services at Sitecore UK:

properties-out-of-box-console

You might be asking “how difficult would it be to add in my own properties?” It’s not difficult at all!

I whipped up the following itemWebApiGetProperties pipeline processor to show how one can add more properties for an item:

using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.ItemWebApi;
using Sitecore.ItemWebApi.Pipelines.GetProperties;

namespace Sitecore.Sandbox.ItemWebApi.Pipelines.GetProperties
{
    public class GetEvenMoreProperties : GetPropertiesProcessor
    {
        public override void Process(GetPropertiesArgs arguments)
        {
            Assert.ArgumentNotNull(arguments, "arguments");
            arguments.Properties.Add("ParentID", arguments.Item.ParentID.ToString());
            arguments.Properties.Add("ChildrenCount", arguments.Item.Children.Count);
            arguments.Properties.Add("Level", arguments.Item.Axes.Level);
            arguments.Properties.Add("IsItemClone", arguments.Item.IsItemClone);
            arguments.Properties.Add("CreatedBy", arguments.Item["__Created by"]);
            arguments.Properties.Add("UpdatedBy", GetItemUpdatedBy(arguments.Item));
        }

        private static Dynamic GetItemUpdatedBy(Item item)
        {
            Assert.ArgumentNotNull(item, "item");
            string[] usernamePieces = item["__Updated by"].Split('\\');

            Dynamic username = new Dynamic();
            if (usernamePieces.Length > 1)
            {
                username["Domain"] = usernamePieces[0];
                username["Username"] = usernamePieces[1];
            }
            else if (usernamePieces.Length > 0)
            {
                username["Username"] = usernamePieces[0];
            }

            return username;
        }
    }
}

The ParentID, ChildrenCount, Level and IsItemClone properties are simply added to the properties SortedDictionary within the GetPropertiesArgs instance, and will be serialized as is.

For the UpdatedBy property, I decided to leverage the Sitecore.ItemWebApi.Dynamic class in order to have the username set in the “__Updated by” field be represented by a JSON object. This JSON object sets the domain and username — without the domain — into different JSON properties.

As a side note — when writing your own service code for the Sitecore Item Web API — I strongly recommend using instances of the Sitecore.ItemWebApi.Dynamic class — or something similar — for complex objects. Developers writing code to consume your JSON will thank you many times for it. 🙂

I registered my new processor to the itemWebApiGetProperties pipeline in my Sitecore instance’s \App_Config\Include\Sitecore.ItemWebApi.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <!-- there's stuff here -->
      <itemWebApiGetProperties>
        <processor type="Sitecore.ItemWebApi.Pipelines.GetProperties.GetProperties, Sitecore.ItemWebApi" />
        <processor type="Sitecore.Sandbox.ItemWebApi.Pipelines.GetProperties.GetEvenMoreProperties, Sitecore.Sandbox" />
      </itemWebApiGetProperties>
      <!-- there's stuff here as well -->
  </sitecore>
</configuration>

Let’s take this for a spin.

I ran the console application again to see what the response now looks like:

additional-properties

As you can see, our additional properties are now included in the response.

If you can think of other item properties that would be useful for Sitecore Item Web API client applications, please share in a comment.

Until next time, have a Sitecorelicious day!

Tailor Sitecore Item Web API Field Values On Read

Last week Sitecore MVP Kamruz Jaman asked me in this tweet if I could answer this question on Stack Overflow.

The person asking the question wanted to know why alt text for images aren’t returned in responses from the Sitecore Item Web API, and was curious if it were possible to include these.

After digging around the Sitecore.ItemWebApi.dll and my local copy of /App_Config/Include/Sitecore.ItemWebApi.config — this config file defines a bunch of pipelines and their processors that can be augmented or overridden — I learned field values are returned via logic in the Sitecore.ItemWebApi.Pipelines.Read.GetResult class, which is exposed in /configuration/sitecore/pipelines/itemWebApiRead/processor[@type=”Sitecore.ItemWebApi.Pipelines.Read.GetResult, Sitecore.ItemWebApi”] in /App_Config/Include/Sitecore.ItemWebApi.config:

sitecore-item-webapi-raw-field-value

This is an example of a raw value for an image field — it does not include the alt text for the image:

image-xml-content-editor

I spun up a copy of the console application written by Kern Herskind Nightingale — Director of Technical Services at Sitecore UK — to show the value returned by the above pipeline processor for an image field:

image-xml-out-of-the-box

The Sitecore.ItemWebApi.Pipelines.Read.GetResult class exposes a virtual method hook — the protected method GetFieldInfo() — that allows custom code to change a field’s value before it is returned.

I wrote the following class as an example for changing an image field’s value:

using System;
using System.IO;
using System.Web;
using System.Web.UI;

using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.ItemWebApi;
using Sitecore.ItemWebApi.Pipelines.Read;
using Sitecore.Web.UI.WebControls;

using HtmlAgilityPack;

namespace Sitecore.Sandbox.ItemWebApi.Pipelines.Read
{
    public class EnsureImageFieldAltText : GetResult
    {
        protected override Dynamic GetFieldInfo(Field field)
        {
            Assert.ArgumentNotNull(field, "field");
            Dynamic dynamic = base.GetFieldInfo(field);
            AddAltTextForImageField(dynamic, field);
            return dynamic;
        }

        private static void AddAltTextForImageField(Dynamic dynamic, Field field)
        {
            Assert.ArgumentNotNull(dynamic, "dynamic");
            Assert.ArgumentNotNull(field, "field");

            if(IsImageField(field))
            {
                dynamic["Value"] = AddAltTextToImages(field.Value, GetAltText(field));
            }
        }

        private static string AddAltTextToImages(string imagesXml, string altText)
        {
            if (string.IsNullOrWhiteSpace(imagesXml) || string.IsNullOrWhiteSpace(altText))
            {
                return imagesXml;
            }
            
            HtmlDocument htmlDocument = new HtmlDocument();
            htmlDocument.LoadHtml(imagesXml);
            HtmlNodeCollection images = htmlDocument.DocumentNode.SelectNodes("//image");
            foreach (HtmlNode image in images)
            {
                if (image.Attributes["src"] != null)
                {
                    image.SetAttributeValue("src", GetAbsoluteUrl(image.GetAttributeValue("src", string.Empty)));
                }
                
                image.SetAttributeValue("alt", altText);
            }
            
            return htmlDocument.DocumentNode.InnerHtml;
        }

        private static string GetAbsoluteUrl(string url)
        {
            Assert.ArgumentNotNullOrEmpty(url, "url");
            Uri uri = HttpContext.Current.Request.Url;

            if (url.StartsWith(uri.Scheme))
            {
                return url;
            }

            string port = string.Empty;

            if (uri.Port != 80)
            {
                port = string.Concat(":", uri.Port);
            }

            return string.Format("{0}://{1}{2}/~{3}", uri.Scheme, uri.Host, port, VirtualPathUtility.ToAbsolute(url));
        }

        private static string GetAltText(Field field)
        {
            Assert.ArgumentNotNull(field, "field");
            if (IsImageField(field))
            {
                ImageField imageField = field;
                if (imageField != null)
                {
                    return imageField.Alt;
                }
            }

            return string.Empty;
        }

        private static bool IsImageField(Field field)
        {
            Assert.ArgumentNotNull(field, "field");
            return field.Type == "Image";
        }
    }
}

The class above — with the help of the Sitecore.Data.Fields.ImageField class — gets the alt text for the image, and adds a new alt XML attribute to the XML before it is returned.

The class also changes the relative url defined in the src attribute in to be an absolute url.

I then swapped out /configuration/sitecore/pipelines/itemWebApiRead/processor[@type=”Sitecore.ItemWebApi.Pipelines.Read.GetResult, Sitecore.ItemWebApi”] with the class above in /App_Config/Include/Sitecore.ItemWebApi.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <!-- Lots of stuff here -->
      <!-- Handles the item read operation. -->
		<itemWebApiRead>
			<processor type="Sitecore.Sandbox.ItemWebApi.Pipelines.Read.EnsureImageFieldAltText, Sitecore.Sandbox" />
		</itemWebApiRead>
		  <!--Lots of stuff here too -->
		
    </pipelines>
	<!-- Even more stuff here -->
  </sitecore>
</configuration>

I then reran the console application to see what the XML now looks like, and as you can see the new alt attribute was added:

alt-image-xml

You might be thinking “Mike, image field XML values are great in Sitecore’s Content Editor, but client code consuming this data might have trouble with it. Is there anyway to have HTML be returned instead of XML?

You bet!

The following subclass of Sitecore.ItemWebApi.Pipelines.Read.GetResult returns HTML, not XML:

using System;
using System.IO;
using System.Web;
using System.Web.UI;

using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.ItemWebApi;
using Sitecore.ItemWebApi.Pipelines.Read;
using Sitecore.Web.UI.WebControls;

using HtmlAgilityPack;

namespace Sitecore.Sandbox.ItemWebApi.Pipelines.Read
{
    public class TailorFieldValue : GetResult
    {
        protected override Dynamic GetFieldInfo(Field field)
        {
            Assert.ArgumentNotNull(field, "field");
            Dynamic dynamic = base.GetFieldInfo(field);
            TailorValueForImageField(dynamic, field);
            return dynamic;
        }

        private static void TailorValueForImageField(Dynamic dynamic, Field field)
        {
            Assert.ArgumentNotNull(dynamic, "dynamic");
            Assert.ArgumentNotNull(field, "field");

            if (field.Type == "Image")
            {
                dynamic["Value"] = SetAbsoluteUrlsOnImages(GetImageHtml(field));
            }
        }

        private static string SetAbsoluteUrlsOnImages(string html)
        {
            if (string.IsNullOrWhiteSpace(html))
            {
                return html;
            }

            HtmlDocument htmlDocument = new HtmlDocument();
            htmlDocument.LoadHtml(html);
            HtmlNodeCollection images = htmlDocument.DocumentNode.SelectNodes("//img");
            foreach (HtmlNode image in images)
            {
                if (image.Attributes["src"] != null)
                {
                    image.SetAttributeValue("src", GetAbsoluteUrl(image.GetAttributeValue("src", string.Empty)));
                }
            }

            return htmlDocument.DocumentNode.InnerHtml;
        }

        private static string GetAbsoluteUrl(string url)
        {
            Assert.ArgumentNotNullOrEmpty(url, "url");
            Uri uri = HttpContext.Current.Request.Url;

            if (url.StartsWith(uri.Scheme))
            {
                return url;
            }

            string port = string.Empty;

            if (uri.Port != 80)
            {
                port = string.Concat(":", uri.Port);
            }

            return string.Format("{0}://{1}{2}{3}", uri.Scheme, uri.Host, port, VirtualPathUtility.ToAbsolute(url));
        }

        private static string GetImageHtml(Field field)
        {
            return GetImageHtml(field.Item, field.Name);
        }

        private static string GetImageHtml(Item item, string fieldName)
        {
            Assert.ArgumentNotNull(item, "item");
            Assert.ArgumentNotNullOrEmpty(fieldName, "fieldName");
            return RenderImageControlHtml(new Image { Item = item, Field = fieldName });
        }

        private static string RenderImageControlHtml(Image image)
        {
            Assert.ArgumentNotNull(image, "image");
            string html = string.Empty;

            using (TextWriter textWriter = new StringWriter())
            {
                using (HtmlTextWriter htmlTextWriter = new HtmlTextWriter(textWriter))
                {
                    image.RenderControl(htmlTextWriter);
                }

                html = textWriter.ToString();
            }

            return html;
        }
    }
}

The class above uses an instance of the Image field control (Sitecore.Web.UI.WebControls.Image) to do all the work for us around building the HTML for the image, and we also make sure the url within it is absolute — just as we had done above.

I then wired this up to my local Sitecore instance in /App_Config/Include/Sitecore.ItemWebApi.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <!-- Lots of stuff here -->
      <!-- Handles the item read operation. -->
		<itemWebApiRead>
			<processor type="Sitecore.Sandbox.ItemWebApi.Pipelines.Read.TailorFieldValue, Sitecore.Sandbox" />
		</itemWebApiRead>
		  <!--Lots of stuff here too -->
		
    </pipelines>
	<!-- Even more stuff here -->
  </sitecore>
</configuration>

I then executed the console application, and was given back HTML for the image:

image-html-returned

If you can think of other reasons for manipulating field values in subclasses of Sitecore.ItemWebApi.Pipelines.Read.GetResult, please drop a comment.

Addendum
Kieran Marron — a Lead Developer at Sitecore — wrote another Sitecore.ItemWebApi.Pipelines.Read.GetResult subclass example that returns an image’s alt text in the Sitecore Item Web API response via a new JSON property. Check it out!