blog.boro2g.co.uk

Some ideas about ASP.Net & Sitecore
  • scissors
    May 3rd, 2012boroSitecore

    During the lifecycle of a Sitecore project, the content editor will be used by several types of user. Here are some tips on how to navigate quickly around the Sitecore Content Editor. As a developer, a lot of these techniques have been discovered trying to save time during the development phase of a project. That’s not to say they don’t apply for anyone!

    1. Every item in the Sitecore tree has a unique guid – this is seen in the ‘Quick Info’ bar. If you know an items guid, use this to your advantage! You can either search at the top of the content tree or alternatively the search box in the taskbar. Both options will jump you to the item if it exists.
    2. Raw values is useful for tracking down related items. If you have a multilist / treelist etc then toggling raw values will show the guid’s of all the selected items. Plug this into step 1 and you can very quickly jump to the related items. You can toggle ‘raw values’ from the ‘View’ section of the ribbon.
    3. The ‘Links’ flyout in the navigation panel gives you the relationship between items – here you can see all the items ‘referring to’ or ‘referred by’ the current item. A good example of this is seeing all the items which are of a certain template type.
    4. Single clicking the items path / guid / template path / template guid selects the whole value. This might seem like a minor point but saves clicks when navigating the content editor.
    5. Shortcuts – the content editor is packed with them – highlighting items in the content editor often shows the keyboard shortcut . A lot of them are listed at http://www.sitecore.net/Community/Technical-Blogs/Sitecore-Australia-Blog/Posts/2010/06/Top-100-List-of-Sitecore.aspx
    6. ‘Go to template’ available in the developer section of the ribbon. This jumps you directly to an items template.
    7. The ‘inheritance’ tab of a template. Here you can see all the templates that make up the item in question – clicking any takes you to that field section / field.
  • scissors
    April 11th, 2012boroSitecore

    In a recent build we had a request from the client to automatically set the language of the content editor based on where in the tree they were viewing. The rules for selecting the language were quite simple:

    - sitecore
    – Content
    — English site – field with value for default language set to be ‘en’
    — French site – field with value for default language set to be ‘fr-fr’

    If the user was making changes within the English site, they wanted the Content Editor to default to ‘en’. If they were editing within the French site, they wanted the Content Editor to default to ‘fr-fr’.

    With the help of support, the following solution was suggested:

    1. Create your own class inherited from Sitecore.Shell.Applications.ContentManager.ContentEditorForm
    2. Add a new method:
      public void ChangeLanguage(string id)
      {
          Error.AssertString(id, "id", false);
          if (ShortID.IsShortID(id))
          {
              id = ShortID.Decode(id);
          }
      
          //get the selected item
          Item item = Sitecore.Configuration.Factory.GetDatabase(Context.ContentDatabase.ToString()).GetItem(id);
      
          if (item != null)
          {
              //get the current site root
              Item currentSiteRoot = item.Axes.GetAncestors().FirstOrDefault(a => a.TemplateID == new ID(new Guid(....)));
      
              if (currentSiteRoot != null)
              {
                  //if the current language doesnt match the expected language, set the language
                  Language siteLanguage = Language.Parse(currentSiteRoot.Fields["...."].Value);
      
                  if (ContentEditorDataContext.Language != siteLanguage)
                  {
                      ContentEditorDataContext.Language = siteLanguage;
                  }
              }
          }
      }
      
    3. Edit \sitecore\shell\Applications\Content Manager\Default.aspx, changing the sc:CodeBeside reference to point to your new class:
      <sc:CodeBeside runat="server" Type="YourNamespase.YourClass,YourAssembly" />
      

      Note, you need to keep the CodeBeside reference on one line as per the out the box version (the other controls are eg DataContext, RegisterKey etc)

    4. Edit \sitecore\shell\Applications\Content Manager\Content editor.js, adding a call to your new method. This needs to happen in the onTreeNodeClick method after LoadItem.
      scContentEditor.prototype.onTreeNodeClick = function (sender, id) {
          ...
          scForm.postRequest("", "", "", "LoadItem(\"" + id + "\")");
          //new call to ChangeLanguage
          scForm.postRequest("", "", "", "ChangeLanguage(\"" + id + "\")");
          ...
      }
      
  • scissors
    April 4th, 2012boroasp.net, Test Driven Development

    During a recent XP programming course we made use of the Moq’ing framework. I’d not used this before so tried to come up with some example moq basic tests. There are several tutorials on the internet which offer up the basics so do hunt around. Hopefully the following provides some simple examples for people to get started with.

    The following code relies on the following assemblies:

    The real crux of TDD is that you program your functionality to interfaces – here we have a simple interface and dto:

    public interface IMyInterface
    {
        int IntMethod(int value);
    
        int HarderIntMethod(int value, int anotherValue);
    
        MyObject MyObjectMethod(int value);
    }
    
    public class MyObject
    {
        public virtual string MyVirtualProperty { get; set; }
        public string MyProperty { get; set; }
    }

    Note the importance of the virtual property in MyObject will be highlighted in the tests. In the following examples not all the tests pass – this is intentional! Failing tests are included to demonstrate specific features of Moq. Apologies for the long dump of test code – the idea is really to copy it into a test class and let NUnit do the work.

    [TestFixture]
    public class MyTests
    {
        [Test]
        [TestCase(1, TestName = "1")]
        public void A_TestMockBehaviourDefault(int value)
        {
            Mock<IMyInterface> myInterface = new Mock<IMyInterface>();
    
            int result = myInterface.Object.IntMethod(value);
    
            //we havent setup mock for value = 1
            Assert.AreEqual(value, result);
    
            myInterface.Verify();
        }
    
        [Test]
        [TestCase(1, TestName = "1")]
        public void B_TestMockBehaviourStrict(int value)
        {
            Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict);
    
            int result = myInterface.Object.IntMethod(value);
    
            //now in strict mode
            //again, we havent setup mock for value = 1
            Assert.AreEqual(value, result);
    
            myInterface.Verify();
        }
    
        [Test]
        [TestCase(1, TestName = "1")]
        [TestCase(2, TestName = "2")]
        public void C_TestMockBehaviourStrictWithSpecificValue(int value)
        {
            Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict);
    
            myInterface.Setup(a => a.IntMethod(1)).Returns(1);
    
            int result = myInterface.Object.IntMethod(value);
    
            //we have setup the mock for value = 1 but not value = 2
            Assert.AreEqual(value, result);
    
            myInterface.Verify();
        }       
    
        [Test]
        [TestCase(1, TestName = "1")]
        [TestCase(2, TestName = "2")]
        public void D_TestMockBehaviourStrictWithTypedValue(int value)
        {
            Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict);
    
            myInterface.Setup(a => a.IntMethod(It.IsAny<int>())).Returns((int a) => a);
    
            int result = myInterface.Object.IntMethod(value);
    
            //any int will pass
            Assert.AreEqual(value, result);
    
            myInterface.Verify();
        }
    
        private int _count = 0;
    
        [Test]
        [TestCase(1, TestName = "1")]
        [TestCase(2, TestName = "2")]
        public void E_TestMockBehaviourStrictWithTypedValueAndCallback(int value)
        {
            Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict);            
    
            myInterface.Setup(a => a.IntMethod(It.IsAny<int>())).Returns((int a) => a).Callback(() => _count++);
    
            int result = myInterface.Object.IntMethod(value);
    
            //we can log callbacks before or after the Returns call
            Console.WriteLine(String.Format("Called E_TestMockBehaviourStrictWithTypedValueAndCallback {0} times", _count));
    
            Assert.AreEqual(value, result);
    
            myInterface.Verify();
        }
    
        [Test]
        [TestCase(1, TestName = "1")]
        [TestCase(2, TestName = "2")]
        public void E1_TestMockBehaviourStrictWithTypedValueAndCallbackBefore(int value)
        {
            Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict);
    
            //callbacks can happen before and after the Returns call
            myInterface.Setup(a => a.IntMethod(It.IsAny<int>())).Callback(() => Console.WriteLine("before")).Returns((int a) => a).Callback(() => Console.WriteLine("after"));
    
            int result = myInterface.Object.IntMethod(value);
    
            Assert.AreEqual(value, result);
    
            myInterface.Verify();
        }
    
        [Test]
        [TestCase(1, TestName = "1")]
        [TestCase(2, TestName = "2")]
        [ExpectedException(typeof(Exception))]
        public void F_TestMockBehaviourStrictWithException(int value)
        {
            Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict);
    
            //this can throw specific exceptions if we want
            //catching at a test level is a bit loose since other code could exception - see F1 for alternative
            myInterface.Setup(a => a.IntMethod(It.IsAny<int>())).Throws<Exception>();
    
            int result = myInterface.Object.IntMethod(value);
    
            myInterface.Verify();
        }
    
        [Test]
        [TestCase(1, TestName = "1")]
        [TestCase(2, TestName = "2")]
        public void F1_TestMockBehaviourStrictWithException(int value)
        {
            Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict);
    
            //this can throw specific exceptions if we want
            myInterface.Setup(a => a.IntMethod(It.IsAny<int>())).Throws<Exception>();
    
            //here we can catch specific exceptions
            Assert.Throws<Exception>(() => myInterface.Object.IntMethod(value));
    
            myInterface.Verify();
        }
    
        [Test]
        [TestCase(1, TestName = "1")]
        [TestCase(2, TestName = "2")]
        public void G_TestMockBehaviourStrictVerify(int value)
        {
            Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict);
    
            myInterface.Setup(a => a.IntMethod(It.IsAny<int>())).Returns((int a) => a).Verifiable();
            myInterface.Setup(a => a.HarderIntMethod(It.IsAny<int>(), (It.IsAny<int>()))).Returns((int a, int b) => a).Verifiable();
    
            int result = myInterface.Object.IntMethod(value);
    
            //we havent called HarderIntMethod
            myInterface.Verify();
        }
    
        [Test]
        [TestCase(1, TestName = "1")]
        [TestCase(2, TestName = "2")]
        public void H_TestMockBehaviourStrictVerifySuccess(int value)
        {
            Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict);
    
            myInterface.Setup(a => a.IntMethod(It.IsAny<int>())).Returns((int a) => a).Verifiable();
            myInterface.Setup(a => a.HarderIntMethod(It.IsAny<int>(), It.IsAny<int>())).Returns((int a, int b) => a).Verifiable();
    
            int result = myInterface.Object.IntMethod(value);
    
            int anotherResult = myInterface.Object.HarderIntMethod(value, value);
    
            myInterface.Verify();
        }
    
        [Test]
        [TestCase(1, TestName = "1")]
        [TestCase(2, TestName = "2")]
        public void I_TestMockBehaviourStrictWithTypedValueAndLogicOnInput(int value)
        {
            Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict);
    
            //setup can perform logic based on input to determine return value(s)
            myInterface.Setup(a => a.IntMethod(It.Is<int>(b => b % 2 == 0))).Returns((int a) => a);
            myInterface.Setup(a => a.IntMethod(It.Is<int>(b => b % 2 != 0))).Returns((int a) => -a);
    
            int result = myInterface.Object.IntMethod(value);
    
            Assert.AreEqual(value, result);
    
            myInterface.Verify();
        }
    
        [Test]
        [TestCase(1, TestName = "1")]
        [TestCase(2, TestName = "2")]
        [TestCase(4, TestName = "4")]
        public void J_TestMockBehaviourStrictWithTypedValueAndRangeLogicOnInput(int value)
        {
            Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict);
    
            //rather than specific logic, instead we can make use of Ranges
            myInterface.Setup(a => a.IntMethod(It.IsInRange<int>(0,3, Range.Inclusive))).Returns((int a) => a);
    
            int result = myInterface.Object.IntMethod(value);
    
            Assert.AreEqual(value, result);
    
            //we haven't setup a return value for 4
            myInterface.Verify();
        }
    
        [Test]
        [TestCase(1, TestName = "1")]
        [TestCase(2, TestName = "2")]
        public void K_TestMockBehaviourStrictWithProperties(int value)
        {
            Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict);
    
            //we can manipulate objects being returned
            myInterface.Setup(a => a.MyObjectMethod(value)).Returns((int a) => new MyObject() { MyProperty = a.ToString() });
    
            MyObject result = myInterface.Object.MyObjectMethod(value);
    
            Assert.AreEqual(value.ToString(), result.MyProperty);
    
            myInterface.Verify();
        }
    
        [Test]
        public void L_TestMockBehaviourStrictWithPropertiesVerifyGet()
        {
            Mock<MyObject> myObject = new Mock<MyObject>(MockBehavior.Strict);
    
            //this is where you need virtual properties
            myObject.Setup(a => a.MyProperty).Returns("blah");
    
            myObject.Verify();
    
            myObject.VerifyGet(a => a.MyProperty);
        }
    
        [Test]
        public void L1_TestMockBehaviourStrictWithPropertiesVerifyGet()
        {
            Mock<MyObject> myObject = new Mock<MyObject>(MockBehavior.Strict);
    
            myObject.Setup(a => a.MyVirtualProperty).Returns("blah");
    
            myObject.Verify();
    
            //we have never accessed MyVirtualProperty hence the VerifyGet fails
            myObject.VerifyGet(a => a.MyVirtualProperty);
        }
    
        [Test]
        public void L2_TestMockBehaviourStrictWithPropertiesVerifyGet()
        {
            Mock<MyObject> myObject = new Mock<MyObject>(MockBehavior.Strict);
    
            myObject.Setup(a => a.MyVirtualProperty).Returns("blah");
    
            Assert.IsNotEmpty(myObject.Object.MyVirtualProperty);
    
            myObject.Verify();
    
            //we have accessed both properties
            myObject.VerifyGet(a => a.MyVirtualProperty);
        }
    
        [Test]
        public void L3_TestMockBehaviourStrictWithPropertiesSetupProperty()
        {
            Mock<MyObject> myObject = new Mock<MyObject>(MockBehavior.Strict);
    
            //rather than setup and then adding Returns method, SetupProperty achieves the same thing
            myObject.SetupProperty(a => a.MyVirtualProperty, "blah");
    
            Assert.IsNotEmpty(myObject.Object.MyVirtualProperty);
    
            myObject.Verify();
    
            myObject.VerifyGet(a => a.MyVirtualProperty);
        }
    
        [Test]
        [TestCase(1, TestName = "1")]
        [TestCase(2, TestName = "2")]
        public void M_TestMockBehaviourStrictWithTypedValueAndDetailedCallback(int value)
        {
            Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict);
    
            //Callback and Returns can both deal with multiple parameters via Generics or parameters.
            // M1 shows the opposite of each
            myInterface.Setup(a => a.HarderIntMethod(It.IsAny<int>(), It.IsAny<int>()))
                .Returns((int a, int b) => a)
                .Callback<int, int>((a, b) => Console.WriteLine("A is " + a + " B is " + b));
    
            int result = myInterface.Object.HarderIntMethod(value, value + 1);
    
            Assert.AreEqual(value, result);
    
            myInterface.Verify();
        }
    
        [Test]
        [TestCase(1, TestName = "1")]
        [TestCase(2, TestName = "2")]
        public void M1_TestMockBehaviourStrictWithTypedValueAndDetailedCallbackAlternativeSyntax(int value)
        {
            Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict);
    
            //demonstrates the opposite of M in terms of the syntax required into Callback and Returns
            myInterface.Setup(a => a.HarderIntMethod(It.IsAny<int>(), It.IsAny<int>()))
                .Returns<int , int>((a, b) => a)
                .Callback((int a, int b) => Console.WriteLine("A is " + a + " B is " + b));
    
            int result = myInterface.Object.HarderIntMethod(value, value + 1);
    
            Assert.AreEqual(value, result);
    
            myInterface.Verify();
        }
    }

    Here is the expected results when evaluated in NUnit:

  • scissors
    March 12th, 2012boroSitecore

    One issue that seems to regularly occur in Sitecore builds is pages showing $name in the content. Its the sort of problem that seems to creep into projects the further through you get.

    Why does it happen?

    When you setup Sitecore templates they are typically built up from several other templates eg:

    • A content page is comprised from:
      • Page Title field section
      • Meta Data field section
      • etc

    Down the line you decide you want to add ‘Page Content – (Header and Body fields)’ to all pages so you setup a new Field Section template along with corresponding fields and __standard values. So that new pages automatically push the item name to the Header field, you set the __standard values to contain $name.

    All this gets published and you then come to check the front end of the site – pages created before adding the Page Content field section now have the new header and body fields but the header field shows $name :(

    The reason being these fields are inheriting their value from __standard values – variables such as $name are processed when items are created. See http://adeneys.wordpress.com/2009/12/29/custom-tokens-and-nvelocity-for-item-creation/ for info on how to create custom replacement tokens. There is also more information on http://learnsitecore.cmsuniverse.net/en/Developers/Articles/2010/08/Standard-values-in-sitecore.aspx

    How to solve the problem?

    When items are created they are processed by a set of pipelines. An example of this is expandInitialFieldValue pipeline. Out the box, this makes use of  the MasterVariablesReplacer.

    You now have a couple options, either you can call the MasterVariablesReplacer for the problematic items or you could manually script the same functionality. The following code demonstrates the manual approach:

    <%@ Page Language="C#" AutoEventWireup="true" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <%@ Import Namespace="Sitecore.Data.Items" %>
    <%@ Import Namespace="Sitecore.Data.Fields" %>
    <%@ Import Namespace="Sitecore.Data" %>
    
    <script runat="server">    
    
        public void FixNames_Click(object sender, EventArgs e)
        {
            //note, this doesn't error check the root guid is valid item
            Item root = Database.GetDatabase("master").GetItem(new ID(new Guid(RootIdTextBox.Text)));
            int fixes = 0;
    
            using (new Sitecore.SecurityModel.SecurityDisabler())
            {
                fixes = RecurseAndFix(root);
            }
    
            ResultsLiteral.Text = String.Format("<hr />Fixed {0} cases of '$name'", fixes);
        }
    
        private int RecurseAndFix(Item root)
        {
            int fixes = 0;
    
            if (root.Template != null)
            {
                foreach (TemplateFieldItem field in root.Template.Fields)
                {
                    Field existingField = root.Fields[field.ID];
    
                    if (existingField != null)
                    {
                        bool fixMe = false;
    
                        if (existingField.Value.Equals("$name"))
                        {
                            fixMe = true;
                        }
    
                        if (existingField.ContainsStandardValue && existingField.GetStandardValue().Equals("$name"))
                        {
                            fixMe = true;
                        }
    
                        if (fixMe)
                        {
                            using (new EditContext(root))
                            {
                                existingField.Value = root.Name;
                                fixes++;
                            }
                        }
                    }
                    else
                    {
                        if (root.Template.StandardValues[field.ID].Equals("$name"))
                        {
                            using (new EditContext(root))
                            {
                                root[field.ID] = root.Name;
                                fixes++;
                            }
                        }
                    }
                }
            }
    
            foreach (Item child in root.Children)
            {
                fixes += RecurseAndFix(child);
            }
    
            return fixes;
        }
    
    </script>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head id="Head1" runat="server">
        <title>'$name' Fixer </title>
    </head>
    <body>
        <form id="form1" runat="server">
            <p>'$name' Fixer </p>
            <p>
                Running the code on this page searches through all the content in the tree and replaces
                any '$name' values with the item's name.
            </p>
            <h2>Note: Be careful, only run on content nodes and children and not templates!</h2>
            <hr />
            <div>
                Root id: <asp:TextBox runat="server" ID="RootIdTextBox" Width="600"></asp:TextBox>
                <asp:Button runat="server" OnClick="FixNames_Click" Text="Fix '$name'" />
            </div>
            <asp:Literal runat="server" ID="ResultsLiteral" />
        </form>
    </body>

    Its worth noting this can introduce some interesting challenges if Language Fallback is used on your site. The script above works fine for content items on a single language site. If you need similar functionality when language fallback is in place it may actually be meaningful to set $name = ” for non-primary languages. This will ensure the fallback will occur correctly, rather than finding $name and thinking it is valid content.

    Tags: ,
  • scissors
    February 23rd, 2012boroSitecore

    Under the hood the Sitecore api offers huge amounts of functionality. When you are using the cms environment, chances are you are triggering this functionality via sitecore commands.

    Most buttons in the cms are tied into these commands so how do you pair up specific buttons to specific code?

    There is an excellent Firefox plugin – Firebug, which is essential if you do a lot of web development. If you haven’t ever used this, download it now!

    Once installed, run through the following steps:

    1. Fire-up your cms environment inFirefox (once firebug is installed)
    2. Activate firebug and select ‘inspect element’ – then click the button you are interested in
    3. Check the firebug window for the JavaScript attached to the button click – this should be wrapped in a sitecore form post JavaScript method eg javascript:return scForm.postEvent(this,event,’item:setdisplayname’)
    4. Open /app_config/commands.config and search for the command name. Examples of this are: item:setdisplayname, item:publish
    5. Find the assembly referenced in the commands file and fire up your favourite decompiler eg reflector or ilspy and search for eg <command name=”item:setdisplayname” type=”Sitecore.Shell.Framework.Commands.SetDisplayName,Sitecore.Kernel” />

    You should now have a route into the source code for each button in the cms!

  • scissors
    February 14th, 2012boroSitecore

    If you have ever developed with Sitecore, chances are you will have deployed content via Sitecore Packages.

    A sitecore package is essentially a zip file containing the xml to be stored in the sitecore databases along with any files you choose to deploy. Some upgrades make use of *.update files – this is out the scope of this post.

    When you install content from packages, items should have the same guid. If conflicts are found during an install you are presented with several options. One word of caution – if you choose overwrite, its pretty easy to blow away large chunks of the tree if you package only contains a few items.

    If you want to see what is in a package you have a few options:

    1. Drill into the zip file with your favourite zip program – content items are nested by database and then path
    2. Load the package into the Sitecore Package Designer (I wish I knew about this one sooner!!!!!)

    For the second option, there is a hidden button (why this is hidden I dont know!) in the package designer:

    When you click ‘From Existing’ you are shown the contents of your data -> packages folder. If you have been sent the package, copy it to this folder.

    Once the package is selected you should see items in the package designer as if you had created the package yourself. From here you can then save the xml definition as per normal.

  • scissors
    February 8th, 2012boroSitecore

    Consider the following scenario: you setup a new Sitecore template (or branch) which you want to add anywhere in the tree without setting any sitecore insert options

    The reason you may want to do this is you have several templates in place throughout the tree, if the insert options can’t be inherited then you would need to update a lot of standard values!

    If you dont use the rule engine for this (see this post) you can still achieve the same solution.

    In the following example, we want the user to be able to add a Generic Form anywhere under the home node of the site.

    using System;
    using System.Linq;
    using ###.DataSource.Cms;
    using Sitecore.Data;
    using Sitecore.Pipelines.GetMasters;
    
    namespace ###.Domain.Cms.Specialization.Processors.GetMasters
    {
        /// <summary>
        /// Allow content editor to add a generic form anywhere under the home node
        /// </summary>
        public class GetGenericForm
        {
            public void Process(GetMastersArgs args)
            {
                if (args.Item.ID.Guid == ItemKeys.Home || args.Item.Axes.GetAncestors().Any(a => a.ID.Guid == ItemKeys.Home))
                {
                    args.Masters.Add(Sitecore.Context.ContentDatabase.GetItem(new ID(TemplateKeys.GenericForm)));
                }
            }
        }
    }

    Which then needs patching into the uiGetMasters pipeline (/App_Config/Include):

    <configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
        <sitecore>
        <processors>
          <uiGetMasters>
            <processor
              patch:after="processor[@type='Sitecore.Pipelines.GetMasters.RunRules, Sitecore.Kernel']"
              type="###.Domain.Cms.Specialization.Processors.GetMasters.GetGenericForm, ###.Domain.Cms" />
          </uiGetMasters>
        </processors>
        </sitecore>
    </configuration>

    After the talk at the Bristol Sitecore User Group yesterday, Raul demonstrated the rule engine for this kind of thing – the exact same problem can be solved without any code :)

    You need to set yourself up a rule eg:

    Note, one step remains – you need to select the root item.

  • scissors
    January 26th, 2012boroSitecore

    Sitecore offers various methods for accessing items in the sitecore tree. The following shows some examples:

    //access item by specific id
    Item itemByGuid = Sitecore.Context.Database.GetItem(new ID("{5071E33C-C56D-4D8F-9BBB-88DADA911DA5}"));
    
    //access item by sitecore path
    Item itemByPath = Sitecore.Context.Database.GetItem("/sitecore/Content/home/news/article");
    
    //access item by specific id in specific language
    Item itemByGuidInLanguage = Sitecore.Context.Database.GetItem(new ID("{5071E33C-C56D-4D8F-9BBB-88DADA911DA5}"), LanguageManager.GetLanguage("fr-fr"));
    
    //access item by sitecore path in specific language
    Item itemByPathInLanguage = Sitecore.Context.Database.GetItem(new ID("/sitecore/Content/home/news/article"), LanguageManager.GetLanguage("fr-fr"));
    

    Typically we will store key item guids and key template guids in static classes so they can be used throughout the code.

    From experience it is rare to use path to access items since an items path can change over time – essentially it is content rather than something fixed. An items guid should never change even when it is packaged up and distributed to multiple environments.

    Its worth noting that once you have accessed an item, it may be it is null. Another scenario is that it doesnt have any versions – this can be caused by an item being published when it isnt in a final workflow state.
    These are easy things to check:

    //check the item actually exists
    if (itemByGuid != null && itemByGuid.Versions.Count > 0)
    {
    
    }
    
  • scissors
    November 17th, 2011boroSitecore

    Out the box, sitecore offers several options for caching the output of sublayouts. Some of the options you have for this are things like ‘vary by querystring’ and ‘vary by data’. This post will demonstrate how to setup custom sublayout cache keys.

    Behind the scenes Sitecore builds up a cache key by appending together information from the current request based on the parameters selected in the caching options. The result of this being the cache key is longer, the more permutations you select.

    For typical builds, the out the box options cover all scenarios however what do you do if you need to customise this?

    In a recent project we exploited * (or wildcard) items so we could accomodate data fed from an external api. This would map known url patterns to one node in the tree, allowing the presentation components on the page to be set in sitecore but the data in the body content be fed from and external system. The mvc routing dll solves the same problem in a similar fashion.

    With the default cache options we ran into the issue that the cache key for each wildcard page would always be the same since the ‘vary by data’ option used the items id, rather than the dynamic url we were assigning. Essentially every page would share the cache key for the * node.

    Solution
    There are only two steps needed for this implementation:

    1. Create custom implementation of a sublayout
    2. Create custom sublayout factory

    Custom sublayout

    using System;
    using System.Web;
    using Sitecore.Web.UI.WebControls;
    
    namespace ###.Presentation.Cms.UI
    {
        public class StarItemSublayout : Sublayout
        {
            /// <summary>
            /// Setup custom cache key which includes Rawurl, hence allowing caching for * item sublayouts
            /// </summary>
            public override string GetCacheKey()
            {
                if (!String.IsNullOrEmpty(base.GetCacheKey()))
                {
                    return String.Concat(base.GetCacheKey(), HttpContext.Current.Request.RawUrl).ToLower();
                }
    
                return String.Empty;
            }
        }
    }

    To use this on the front end, you would then embed in the markup using:

    <tc:StarItemSublayout runat="server" Path="~/###/Sublayouts/Common/Header.ascx" Cacheable="false" />

    If you want sublayouts instantiated from Sitecore to make use of your new type, you need to update the sublayout renderingControl in the config:

    <renderingControls>
      ...
      <control template="sublayout" type="###.Presentation.Cms.UI.StarItemRenderingType, ###.Presentation.Cms" propertyMap="Path=path" />
      ...
    </renderingControls>

    And finally the new rendering type:

    using System;
    using System.Collections.Specialized;
    using System.Web.UI;
    using ###.Domain.Cms.Specialization.MvcRouting.Extensions;
    using Sitecore;
    using Sitecore.Diagnostics;
    using Sitecore.Reflection;
    using Sitecore.Web.UI;
    using Sitecore.Web.UI.WebControls;
    
    namespace ###.Presentation.Cms.UI
    {
        /// <summary>
        /// Custom rendering type which allows creation of StarItemSublayout
        /// </summary>
        public class StarItemRenderingType : SublayoutRenderingType
        {
            public override Control GetControl(NameValueCollection parameters, bool assert)
            {
                Sublayout sublayout = new Sublayout();
    
                ///Check if we are on a wildcard (or mvc routed) item
                if (Sitecore.Context.Item.Name == "*" || !String.IsNullOrEmpty(MvcRouteUtility.MatchedRoute()))
                {
                    ///Create custom sublayout which has more detailed cachekey
                    sublayout = new StarItemSublayout();
                }
    
                foreach (string str in parameters.Keys)
                {
                    string str2 = parameters[str];
                    ReflectionUtil.SetProperty(sublayout, str, str2);
                }
                return sublayout;
            }
        }
    }

    In the example above the new sublayout is used for wildcard items as well as items which match an MVCRoute – this is some new functionality currently being developed by Steven Pope @ Sitecore UK.

  • scissors
    August 26th, 2011boroSitecore

    One of the common issues when using Sitecore HTML Caching is how to execute dynamic scripts based on code behind actions when the control front end is being cached.

    The solution listed below defines the theory behind the approach rather than the concrete implementations.

    Consider the following scenario:
    You need to display the date to the user using javascript. To solve the issue, you decide to make use of either RegisterClientScriptBlock or RegisterStartupScript and register some javascript to write out alert(‘DateTime.Now’) [psuedo code].

    This works fine during development since you are building your project a lot and the full use of caching isnt implemented. Down the line, you tune up / turn on caches and the date is only shown the first load after the caches are emptied :(

    Do not fear, there is a solution to the issue and that is to make use of Sitecore Html Cache. Rather than calling asp.net RegisterClientScriptInclude(Block, Resource), setup your own methods (for the demo, these are exposed off SScriptManager):

    SScriptManager.RegisterClientScriptInclude(mediaUrl);
    

    In your master page, add another control (for the demo, known as SScriptManager).

    When you register the script includes / blocks, store this information in the html cache remembering to build the cache key from current item, current language and script key.

    During the Render/PreRender phase of the page lifecycle, the SScriptManager can then iterate through all keys in html cache and if the keys match the current page, relay on the script calls to the page.

  • « Older Entries