Skip to content

Text Based Content Search Based On Tagging

Out of the box Sitecore offers Content Editors the power to create tags, and assign them to content items using the Tagging field in standard values.

Tagging Standard Value

Tagging Standard Value

When analysing the indexes using LUKE, you can see that Sitecore indexes the ID’s of each tag. This makes it difficult to perform a text based content search that also matches on tags.

Luke Index View

Luke Index View

However Sitecore gives us the power to create computed fields in search indexes. This means we can create new fields within the index and programmatically create text into the index.

This example below uses a computed field that instead of indexing the ID of the tag, instead adds the item name of each tag seperated by a space. This then allows you to perform a text based search against the tag. (Sitecore by default indexes the __Semantics field, so here i’m creating a new field in the index called “tags” not to override any standard Sitecore functionality)

 

Computed Field Class

namespace MikeRobbins.CMS.ComputedFields
{
public class Tags : IComputedIndexField
{
public object ComputeFieldValue(Sitecore.ContentSearch.IIndexable indexable)
{
var tags = new StringBuilder();

Item obj = (Item)(indexable as SitecoreIndexableItem);

if (obj != null)
{
var tagField = (Sitecore.Data.Fields.MultilistField)obj.Fields["__Semantics"];

if (tagField != null)
{
var items = tagField.GetItems();

foreach (var item in items)
{
tags.Append(item.Name + " ");
}
}
}

return tags.Length != 0? tags.ToString():null;
}

public string FieldName { get; set; }
public string ReturnType { get; set; }
}
}

XML Config

Add this XML to the “AddComputedIndexField” section of your search index config.

<field fieldName="tags"                           >MikeRobbins.CMS.ComputedFields.Tags,MikeRobbins.CMS</field>

Sitecore Item Web API XML Maintaining Sitecore SPEAK

Recently I have had a client request asking to use Sitecore Item Web API in XML format rather than JSON. Luckily within the Item Web API documentation Sitecore provide a Pipeline Processor to output XML rather than JSON.  http://sdn.sitecore.net/upload/sdn5/modules/sitecore%20item%20web%20api/sitecore_item_web_api_developer_guide_sc66-71-a4.pdf

Sitecore SPEAK also makes use of the Sitecore Item Web API, but an unfortunate side effect of this code snippet is that it breaks Sitecore SPEAK as it expects JSON responses back from the web service. The code snippet below is an adapted version of the Sitecore code snippet. It allows bypassing the XMLSerializer by default unless a query string parameter of “type=xml” is present.

This allows you to maintain Sitecore SPEAK functionality while allowing the calling client to easily switch between JSON and XML. Add this XML to the include folder in app_config

<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
 <sitecore>
 <pipelines>
 <itemWebApiRequest>
 <processor patch:before="*[@type='Sitecore.ItemWebApi.Pipelines.Request.SerializeResponse, Sitecore.ItemWebApi']" type="MikeRobbins.CMS.WebItemAPI.SwitchToXmlSerializer,MikeRobbins.CMS" />
 </itemWebApiRequest>
 </pipelines>
 </sitecore>
</configuration>
namespace MikeRobbins.CMS.WebItemAPI
{
 public class SwitchToXmlSerializer : RequestProcessor
 {
 public override void Process([NotNull] RequestArgs arguments)
 {
 if (System.Web.HttpContext.Current.Request.QueryString["type"] == "xml")
 {
 Context.Current.Serializer = new XmlSerializer();
 }
 }
 }
}
namespace MikeRobbins.CMS.WebItemAPI
{
 public class XmlSerializer : ISerializer
 {
 public string SerializedDataMediaType
 {
 get
 {
 return "text/xml";
 }
 }

 public string Serialize(object value)
 {
 return Serialize((Dynamic)value).ToString();
 }

 private XElement Serialize(Dynamic value)
 {
 var element = XElement.Parse("<object/>");

 foreach (var property in value)
 {
 var propertyName = string.Format("_{0}", property.Key);
 propertyName = propertyName.Replace("{", "");
 propertyName = propertyName.Replace("}", "");
 propertyName = propertyName.Replace(" ", "-");

 var child = XElement.Parse(string.Format("<{0}/>", propertyName));
 var array = property.Value as Dynamic[];

 if (array != null)
 {
 foreach (var item in array)
 {
 child.Add(Serialize(item));
 }
 }
 else if (property.Value is Dynamic)
 {
 child.Add(Serialize((Dynamic)property.Value));
 }
 else
 {
 child.Add(property.Value.ToString());
 }

 element.Add(child);
 }

 return element;
 }
 }
}

Workflow RSS Feed Custom Email Action

I have worked with a number of clients that have asked why the email notifications they receive from workflow didn’t reflect what is available from the RSS feed within the workbox.

This seems to have been a goal of a number of developers in the past, but nothing concrete has been created to replicate the feature. There is a awesome workaround from Nick Wesselman using Rss2email. http://www.techphoria414.com/Blog/2012/April/Sitecore_Workflow_Emails_with_rss2email

As part of a recent hacking session I decided to see if I could replicate the RSS feed within a more advance email action.

Solution
The solution is available as a Sitecore package on the marketplace or the source is available of GitHub at the bottom of this blog. Please feel free to extend and contribute.

Workflow history

Using the GetWorkflow().GetHistory(Item) API gives full access to the entire workflow history or a particular Sitecore Item.

   var workflowItemHistory = Item.State.GetWorkflow().GetHistory(Item);

However on testing this code threw up an unexpected error. Due to the email action being called from a command the workflow command hasn’t been fully executed, so the workflow history doesn’t contain the currently executing workflow command. This was solved by creating a function that gets the current workflow command that has fired, working out the target state of the action before appending this data to a collection of workflow history.

        private ItemWorkflowHistory GetCurrentWorkflowHistoryItem()
        {

            var history = new ItemWorkflowHistory()
            {
                ItemDateTime = DateTime.Now,
                User = Sitecore.Context.GetUserName(),
                PreviousState = workflowPipelineArgs.DataItem.State.GetWorkflowState().DisplayName,
                CurrentState = GetCorrectWorkflowState().DisplayName,
                Comment = workflowPipelineArgs.Comments
            };

            return history;
        }

private WorkflowState GetCorrectWorkflowState()
        {
            var emailAction = GetEmailAction();

            var command = emailAction.Parent;

            var nextStateId = command[&amp;amp;amp;quot;Next state&amp;amp;amp;quot;];

            var itemWorkflow = Sitecore.Data.Database.GetDatabase(&amp;amp;amp;quot;master&amp;amp;amp;quot;).WorkflowProvider.GetWorkflow(workflowPipelineArgs.DataItem);

            return itemWorkflow.GetState(nextStateId.ToString());
        }

Workflow commands
The biggest challenge was to build the command links to allow the user to fire the correct commands at the relevant stage of workflow.

This suffered from the same issue as the workflow history, the correct workflow commands weren’t shown because the currently executing command hasn’t completed. Again this was solved using the method above of getting the firing command and getting its target state of workflow. The correct workflow commands can then be taken from this target state of workflow.

private string GetCommandLinks(Item workflowItem, WorkflowState state)
        {
            var sb = new StringBuilder();

            var workflow = Sitecore.Data.Database.GetDatabase(&amp;amp;amp;amp;quot;master&amp;amp;amp;amp;quot;).WorkflowProvider.GetWorkflow(workflowItem);

            var commands = workflow.GetCommands(state.StateID);

            sb.Append(&amp;amp;amp;amp;quot;&amp;amp;amp;amp;lt;ul&amp;amp;amp;amp;gt;&amp;amp;amp;amp;quot;);

            foreach (var command in commands)
            {
                var submit = Tools.GetContentEditorLink(ContentEditorMode.Submit, workflowItem, HostName, new ID(command.CommandID));
                var submitComment = Tools.GetContentEditorLink(ContentEditorMode.Submit, workflowItem,HostName, new ID(command.CommandID));

                sb.Append(&amp;amp;amp;amp;quot;&amp;amp;amp;amp;lt;li&amp;amp;amp;amp;gt;&amp;amp;amp;amp;lt;a&amp;amp;amp;amp;gt;&amp;amp;amp;amp;quot; + command.DisplayName + &amp;amp;amp;amp;quot;&amp;amp;amp;amp;lt;/a&amp;amp;amp;amp;gt; or &amp;amp;amp;amp;lt;a&amp;amp;amp;amp;gt;&amp;amp;amp;amp;quot; + command.DisplayName + &amp;amp;amp;amp;quot; &amp;amp;amp;amp;amp;amp; comment&amp;amp;amp;amp;lt;/a&amp;amp;amp;amp;gt;&amp;amp;amp;amp;lt;/li&amp;amp;amp;amp;gt;&amp;amp;amp;amp;quot;);
            }

            string editLink = Tools.GetContentEditorLink(ContentEditorMode.Editor, workflowItem, HostName, ID.NewID);
            string previewLink = Tools.GetContentEditorLink(ContentEditorMode.Preview, workflowItem,HostName, ID.NewID);

            sb.Append(&amp;amp;amp;amp;quot;&amp;amp;amp;amp;lt;li&amp;amp;amp;amp;gt;&amp;amp;amp;amp;lt;a&amp;amp;amp;amp;gt;Edit&amp;amp;amp;amp;lt;/li&amp;amp;amp;amp;gt;&amp;amp;amp;amp;quot;);
            sb.Append(&amp;amp;amp;amp;quot;&amp;amp;amp;amp;lt;li&amp;amp;amp;amp;gt;&amp;amp;amp;amp;lt;a&amp;amp;amp;amp;gt;Preview&amp;amp;amp;amp;lt;/li&amp;amp;amp;amp;gt;&amp;amp;amp;amp;quot;);
            sb.Append(&amp;amp;amp;amp;quot;&amp;amp;amp;amp;lt;li&amp;amp;amp;amp;gt;&amp;amp;amp;amp;lt;a /&amp;amp;amp;amp;gt;Workbox&amp;amp;amp;amp;lt;/li&amp;amp;amp;amp;gt;&amp;amp;amp;amp;quot;);

            sb.Append(&amp;amp;amp;amp;quot;&amp;amp;amp;amp;lt;/ul&amp;amp;amp;amp;gt;&amp;amp;amp;amp;quot;);

            return sb.ToString();
        }

Reviewing the command links in the Workbox RSS feed I was able to build a helper class to build the command links in the correct URL format for the links.

public static string GetContentEditorLink(ContentEditorMode contentEditorMode, Item item, string hostName, ID commandId)
        {
            switch (contentEditorMode)
            {
                case ContentEditorMode.Editor:
                    return (&amp;amp;amp;amp;quot;http://&amp;amp;amp;amp;quot; + hostName.Replace(&amp;amp;amp;amp;quot;http://&amp;amp;amp;amp;quot;, &amp;amp;amp;amp;quot;&amp;amp;amp;amp;quot;) + &amp;amp;amp;amp;quot;/sitecore/shell/Applications/Content%20editor.aspx?fo=&amp;amp;amp;amp;quot; + item.ID.ToString() + &amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;id=&amp;amp;amp;amp;quot; + item.ID.ToString() + &amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;la=&amp;amp;amp;amp;quot; + item.Language.Name + &amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;v=&amp;amp;amp;amp;quot; + item.Version.Number.ToString() + &amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;sc_bw=1&amp;amp;amp;amp;quot;);

                case ContentEditorMode.Preview:
                    return (&amp;amp;amp;amp;quot;http://&amp;amp;amp;amp;quot; + hostName.Replace(&amp;amp;amp;amp;quot;http://&amp;amp;amp;amp;quot;, &amp;amp;amp;amp;quot;&amp;amp;amp;amp;quot;) + &amp;amp;amp;amp;quot;/sitecore/shell/feeds/action.aspx?c=Preview&amp;amp;amp;amp;amp;id=&amp;amp;amp;amp;quot; + item.ID.ToString() + &amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;la=&amp;amp;amp;amp;quot; + item.Language.Name + &amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;v=&amp;amp;amp;amp;quot; + item.Version.Number.ToString());

                case ContentEditorMode.Submit:
                    return (&amp;amp;amp;amp;quot;http://&amp;amp;amp;amp;quot; + hostName.Replace(&amp;amp;amp;amp;quot;http://&amp;amp;amp;amp;quot;, &amp;amp;amp;amp;quot;&amp;amp;amp;amp;quot;) + &amp;amp;amp;amp;quot;/sitecore/shell/feeds/action.aspx?c=Workflow&amp;amp;amp;amp;amp;id=&amp;amp;amp;amp;quot; + item.ID.ToString() + &amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;la=&amp;amp;amp;amp;quot; + item.Language.Name + &amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;v=&amp;amp;amp;amp;quot; + item.Version.Number.ToString() + &amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;cmd=&amp;amp;amp;amp;quot; + commandId.ToString());

                case ContentEditorMode.SubmitComment:
                    return (&amp;amp;amp;amp;quot;http://&amp;amp;amp;amp;quot; + hostName.Replace(&amp;amp;amp;amp;quot;http://&amp;amp;amp;amp;quot;,&amp;amp;amp;amp;quot;&amp;amp;amp;amp;quot;) + &amp;amp;amp;amp;quot;/sitecore/shell/feeds/action.aspx?c=Workflow&amp;amp;amp;amp;amp;id=&amp;amp;amp;amp;quot; + item.ID.ToString() + &amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;la=&amp;amp;amp;amp;quot; + item.Language.Name + &amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;v=&amp;amp;amp;amp;quot; + item.Version.Number.ToString() + &amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;cmd=&amp;amp;amp;amp;quot; + commandId.ToString() + &amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;nc=1&amp;amp;amp;amp;quot;);
            }
            return &amp;amp;amp;amp;quot;&amp;amp;amp;amp;quot;;
        }
    }

Workflow History

20140521-194216-70936959.jpg

20140521-194216-70936793.jpg

Source

https://github.com/sobek1985/AdvancedEmailAction

Sitecore Marketplace

https://marketplace.sitecore.net/en/Modules/Sitecore_Advanced_Email_Action.aspx

Custom Tokens in Email Campaign Manager

Recently I had a requirement from a client where they wanted to use Sitecore Email Campaign Manager to send registration emails, containing registration details and other dynamic custom data. Here is how to create tokens within a Email Campaign message and replace them with variables in a manually triggered email.

  1. Add your token(s) into the body text of the campaign message in the format $key$, ensure that the key text is lower case.

    Sitecore Custom Tokens

    Sitecore Email Campaign Manager Custom Tokens

  2. Get the message using the Sitecore API, replace the variables using the CustomPersonTokens dictionary and then trigger the send pipeline. The CustomPersonToken dictionary requires the key to be in lower case and requires the surrounding $$ to be removed.
//Get the message using the Sitecore API
var mi = Sitecore.Modules.EmailCampaign.Factory.GetMessage(messageId);

//Use the custom person token dictionary to replace the key with a string variable. Remember that the token key has to be lower case and remove the $$ surrounding the key
 mi.CustomPersonTokens.Add("username", "MikeTest");

//Send the message
new AsyncSendingManager(mi).SendStandardMessage(contactFromName);

Trigger Email and Replace tokens

Here is a reusable function that allows you to send an email campaign message from code and replace custom tokens.

public void SendEmailCampaignMessage(ID messageId, string userName, Dictionary<string, string> customTokens = null)
        {
            var mi = Sitecore.Modules.EmailCampaign.Factory.GetMessage(messageId);

            if (customTokens != null)
            {
                foreach (var token in customTokens)
                {
                    mi.CustomPersonTokens.Add(token.Key, token.Value);
                }
            }

            var contactFromName = Contact.FromName(userName);

            new AsyncSendingManager(mi).SendStandardMessage(contactFromName);
        }

Publish And Send For Translate Workflow Action

Here is a useful Custom Workflow action I’ve written allowing a content editor to publish a content item to live while also sending its alternative language version to a translate workflow state. This allows a content item to be published to live in a single language without being held up waiting on a translation to be completed.

  • 1. Create a workflow command to publish the content to the published state in workflow.
  • 2. Create a new custom workflow action underneath the publish command.
  • 3. Use the code below to automatically create a new language version and set the workflow state to translation state.
  • 4. Replace the parameters in the screenshot of the custom workflow action. Replace the targetstate parameter with the ID of the target language state. Replace language with the name of the target language

Publish And Translate Action

using Sitecore;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Data.Managers;
using Sitecore.Diagnostics;
using Sitecore.Globalization;
using Sitecore.Web;
using Sitecore.Workflows.Simple;

namespace MikeRobbins.SitecoreComponents.WorkFlow
{
    public class PublishAction
    {
        public void Process(WorkflowPipelineArgs args)
        {
            Item workFlowItem = args.DataItem;

            var targetLanguage = GetTargetLanguage(args.ProcessorItem.InnerItem);
            var targetVersion = Sitecore.Context.ContentDatabase.GetItem(workFlowItem.ID, targetLanguage);

            if (targetVersion.Versions.Count == 0)
            {
                targetVersion = targetVersion.Versions.AddVersion();
            }

            var targetWorkflowState = GetWorkflowState(args.ProcessorItem.InnerItem);

            SetWorkflowState(targetVersion, targetWorkflowState.ID);
        }

        private static void SetWorkflowState(Item welshVersion, ID targetWorkflowState)
        {
            welshVersion.Editing.BeginEdit();
            welshVersion.Fields[FieldIDs.WorkflowState].Value = targetWorkflowState.ToString();
            welshVersion.Editing.EndEdit();
        }

        private static Item GetWorkflowState(Item actionItem)
        {
            ID translateId = null;

            return ID.TryParse(WebUtil.ParseUrlParameters(actionItem["parameters"])["targetstate"], out translateId) ? Sitecore.Context.ContentDatabase.GetItem(translateId) : null;
        }

        public Language GetTargetLanguage(Item actionItem)
        {
            var language = WebUtil.ParseUrlParameters(actionItem["parameters"])["language"];

            Assert.IsNotNullOrEmpty(language, "Language needs to be specified as a parameter (&language=cy-gb)");

            return LanguageManager.GetLanguage(language);
        }
    }
}

Sitecore 7 Search ID Array Type Converter

This is a simple type converter that allows you to convert a collection of Sitecore IDs stored in a Lucene search index into a List.

public class ListIDConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(List<ID>))
            {
                return true;
            }

            return base.CanConvertFrom(context, sourceType);
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(List<string>))
            {
                return true;
            }
            return base.CanConvertTo(context, destinationType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            var scIds = new List<ID>();

            var ids = (List<string>) value;

            foreach (var id in ids)
            {
                ID scId;
                if (ID.TryParse(id, out scId))
                {
                    scIds.Add(scId);
                }
            }

            return scIds;
        }
    }

To use the Type converter decorate your public property with the TypeConverter in your Search Result class.

    [TypeConverter(typeof(ListIDConverter))]
        [IndexField("_templates")]
        public List<ID> Templates { get; set; }

Sitecore 7 Search by base templates

Quick tip, when using Sitecore 7′s search API to build a general site search, you may want to return only pages rather than any other items within Sitecore. All my page items inherit from a base Item to implement page title, meta data and so on. Using linq we are able to check whether an item is based on a specific base template, to do this we need to tell Sitecore to index the base templates.

By default in Sitecore 7 indexing base templates is disabled to improve the indexing speed. This is very simple to switch on.

Inside the section within your index uncomment the line below.

 <field fieldName="_templates" storageType="yes" indexType="untokenized">Sitecore.ContentSearch.ComputedFields.AllTemplates, Sitecore.ContentSearch</field>

Rebuild your index and these base templates are now accessible in your search result class.

Sitecore Data Importer / Word docx Importer

I recently had a requirement from a client to allow them to import content into Sitecore items from word docx files. After looking on the Sitecore marketplace and git hub I realised nothing existed so decided on writing a module. I did quickly realise why nobody has written one before docx files are basically zip files containing a number of files with the main document content written in XML.

The document

To be useful I wanted the importer to be able to split the docx file into fields within a Sitecore item rather than drop the entire contents into one rich text editor field. This became an issue, how could I tell which section of the document related to which field.

The solution I came up was using the “Title” button in Microsoft Word to mark each section of the document. The title would match up exactly with the field name within Sitecore. Using this structure means that I could programmatically read all content between titles and know which field in Sitecore that content related too.

Sample Document

Sample Document

Import Module

The actual Sitecore data importer module has a simple interface allowing the upload of a file to import (Sitecore data importer supports docx files, csv’s and a zip file containing docx files) . The module also takes the path where you want the items created and the template of the items you want to create.

The main work of the importer parsing the docx file into fields is handled by the code below. Im using OpenXml to help read the docx format, and then iterating through each paragraph checking to see if it’s a title tag, storing the title in a variable and then grabbing the text paragraph(s). Each field name / value is stored in a dictionary which gets written out to the Sitecore API later on.  You can also upload a zip file containing multiple docx files which then gets uncompressed before passing each document off to this function.

Sitecore  Data Importer

Sitecore Data Importer

public Dictionary<string, string> ExtractFields(string path)

{

var fields = new Dictionary<string, string>();

using (var myDocument = WordprocessingDocument.Open(path, true))

{

var body = myDocument.MainDocumentPart.Document.Body;

var dictionaryKey = "";

foreach (var paragraph in body.Where(paragraph => !string.IsNullOrEmpty(paragraph.InnerText)))

{

if (paragraph.InnerXml.Contains("w:val=\"Title\""))

{

dictionaryKey = paragraph.InnerText;

}

else

{

if (fields.ContainsKey(dictionaryKey))

{

fields[dictionaryKey] = fields[dictionaryKey].EndsWith("</p>") ? fields[dictionaryKey] + "<p>" + paragraph.InnerText + "</p>" : "<p>" + fields[dictionaryKey] + "</p><p>" + paragraph.InnerText + "</p>";

}

else

{

fields.Add(dictionaryKey, paragraph.InnerText);

}

}

}

}

return fields;

}

Source Code and Sitecore Marketplace

Any issues or bugs with the module please let me know. The module does need testing with more docx structures, this is the initial release.

https://github.com/sobek1985/SitecoreDataImporter

http://marketplace.sitecore.net/en/Modules/Sitecore_Data_Importer.aspx

Sitecore YouTube Control

A very simple and useful YouTube control for Sitecore for embedding YouTube videos. You can either specify a Sitcore item to get the YouTube ID field from, otherwise it will use the context item.

  1. Create a class using the code below
  2. Register the control in the web.config
    <controls>
     <add tagPrefix="TB" namespace="ToolBox.SitecoreCMS.Web.UI.WebControls" assembly="ToolBox.SitecoreCMS" />
     </controls>
    
    
  3. Use the control within your sublayouts
    <tb:YouTube runat="server" Field="YouTubeID" Height="200" Width="400"/>
    

register the control within the web.config and use it within your sublayouts.

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Sitecore.Data.Items;

namespace ToolBox.SitecoreCMS.Web.UI.WebControls
{
 public class YouTube : WebControl
 {
 public Item Item { get; set; }
 public string Field { get; set; }
 public override Unit Height { get; set; }
 public override Unit Width { get; set; }

protected override void Render(HtmlTextWriter writer)
 {
 writer.Write(BuildYouTube());
 }

private string BuildYouTube()
 {
return "<i frame width='" + Convert.ToInt32(Width.Value) + "px' height='" + Convert.ToInt32(Height.Value) + "px' src='http://www.youtube.com/embed/" + GetYouTubeVID() + "' frameborder='0' allowfullscreen></i frame>";
}

private string GetYouTubeVID()
 {
 return Item != null ? Item[Field] : Sitecore.Context.Item[Field];
 }
 }
}

How to use Sitecore Nuget

If you have ever used NuGet within any of your Visual Studio projects you will know how easy it is install 3rd party dependencies, update them and bring new developers onto a project, Wouldn’t it be useful to take advantage of NuGet in Sitecore.

With the power of Nuget and Powershell you can add files to your solution, add files to the inetpub folder containing your website and best of all insert items directly into the master database of your Sitecore instance.

To create a custom NuGet Package i use NuGet Package explorer. Its a friendly GUI for creating, updating and publishing NuGet packages (.nupkg) or a public or private NuGet repository.

How To Create A Sitecore Nuget Package

  1. Download NuGet package explorer. http://nuget.codeplex.com/releases/view/59864
  2. Open the sample Sitecore Nuget package. Sitecore.NuGet.Sample
    Open NuGet Package

    Open NuGet Package

    Sitecore NuGet Package

    Sitecore NuGet Package

  3. Edit the metadata for the package using the edit button on the left.
  4. The content folder if for any items (css, c# files, java script etc.) you want to add to your solution. The files will be added to reflect the folder structure here.

    Content Node

    Content Node for adding to the VS solution

  5. The tools folder is where the Powershell and DLL for Sitecore NuGet are contained. You can extend the powershell for pre-install and post-install events.

    Tools Node

    Tools Node

  6. Next we want to serialise Sitecore items to include them in the package. Within the Sitecore content editor navigate to the items you want to serialise and press the Serialize Tree button to serialise the content item and all decendants, do this for all items you want to include in your package.

    Serialise Sitecore Items

    Serialise Sitecore Items

  7. The items are then serialised to the disk. Navigate to your sealisation folder. (C:\inetpub\wwwroot\(ProjectName)\Data\serialization) Copy the serialised items you need into the serialsation folder in NuGet.

    Serialisation

    Serialisation

  8. Save or publish your package to your NuGet repository

Using Your NuGet Package

  1. Install Sitecore Rocks
  2. Create a connection to your Sitecore instance (Make sure the connection is outside the folder Sitecore NuGet can’t see the connection in here)

    Sitecore Rocks

    Sitecore Rocks

  3. Add a connection between your project and the Sitecore Rocks connection

    Connect to Sitecore

    Connect to Sitecore

  4. Now you can install your NuGet package directly into your solution and Sitecore instance
    NuGet Package Installer

    Nuget Package Installer

  5. Powershell and Sitecore rocks will now copy any files into your project and push your serialised items into the master Sitecore database
Follow

Get every new post delivered to your Inbox.

Join 154 other followers

%d bloggers like this: