26 September 2015

Sitecore 8 setup a preview site

The out of the box capabilities of sitecore are quite large in terms of preview, experience editor... In most case scenario those are more than enough for content editor to preview their content before publishing the pages. However, from time to time it happens that part of approval process, a link to a person need to be sent so this person can view the page(s) and review it outside the workflow process. This can happen for Legal team to review any information on the page... well Obviously in those cases, it is quite tricky to set them up with a login details so they have to login into sitecore then preview the page.

What we could do in this situation is to setup a Preview site. Although this sounds great you will say that well since only item in the last step of the workflow can be published, this will not really work... Well here comes the power of publishing Target.

You will need to setup a new Publishing Target "Preview":



You can see that on the new Publishing target item you can tick the checkbox: "Preview publishing target". By ticking this checkbox you are allowing items that are not in final state to be published there. That is awesome...

Now, you will need to setup a new database and a new entry in the connection string config

  
  
  
  
  

  
  
  
  


When setting up the new database, you will also need to add the following configuration for the Preview Database:


  
    
      
      
        $(id)
        Images/database_web.png
        true
        
          
            publishing
            
              
              
            
          
        
        false
        
        
          
          
        
        
          100MB
          50MB
          2500KB
          50MB
          2500KB
        
      
    
  


You can also setup a few config to ensure that search index will also be created for your new Target DB. Create a new config file on your App_config/Include/XXX folder. Call the file: XXX.ContentSearch.Lucene.Index.Preview.config. Copy the following there:


  
    
      
        
          
            $(id)
            $(id)
            
            
            
            
              
              
            
            
              
                
              
            
            
              
                preview
                /sitecore
              
            
            

            
          
        
      
    
  



You can now define a new Site in your siteDefinition:


  
    
      
    
  


Finally ensure that you update the Sitecore.ContentSearch.DefaultConfigurations.config to add the new strategy:

          
            preview
            
            true
          


Now the final spte is to ensure that the users you are editing the content is in a role that has write permission on the Publishing target item. This will make sure that your editor will see the target in the publishing window. This will also make sure that he can check or uncheck this target.



Now on the workflow step you will now see that when the page is in the Awaiting for approval, you will still be able to publish it to the Preview site:


13 September 2015

Sitecore 8 and admin page to rebuild aggregation data

As sitecore devs, I am sure you are familiar with all the cool admin pages for clearing cache, viewing configuration file... Well since xDb I always wandered: all my analytics data goes into the mongo DB then Gets aggregatred but what if I need to trigger it manually? Well lucky sitecore thought about it. you have a nice page for that: /sitecore/admin/RebuildReportingDB.aspx.



Well if you start rebuilding straight away, you will encounter an error saying your reporting.secondary DB is not configured.

You can find more information about the secondray.reporting on the following links:

https://doc.sitecore.net/Sitecore%20Experience%20Platform/xDB%20configuration/Walkthrough%20Rebuilding%20the%20reporting%20database


25 August 2015

Sitecore 8 tracking media download

As part of the implementation, we sometime have question about tracking. It happened few time in the past where clients wanted to track PDF download on there website. Using Sitecore 6 was a bit tricky as it was kind of tricky. In the past, I tried a few things including overriding the  Media Handler to trigger an event "Download PDF". Eventhough this was working I did not like the idea of overridding the media handler as it is always painful for Sitecore upgrade and else.

Well I have to say that I was quite pleased to see that this is now handled out of the box on Sitecore 8. This is done through Media Assets. You can find more about it in the following link: https://doc.sitecore.net/sitecore%20experience%20platform/marketing%20taxonomies/classify%20a%20media%20item%20as%20a%20digital%20marketing%20asset

So what do you need to do:

1- Open your Marketing Control Panel and add a New Taxonomy Asset Item:


2- Deploy your Media Asset folder:


3- You can now use your Media Asset on your Media Item directly:

4- Now the only thing left to do is to setup the Event tracking on your media item:

5- setting up the event on the media item, means that everytime someone will request the media item, sitecore will track the Media Assets with the corresponding event: Download. The event already exist in sitecore and is already hooked to the Marketing report:

There you go you are now tracking the Media requests.

Just a quick look at the magic behind, if you quickly uncompile the Sitecore DLL, look for the MediaRequestHandler class that processes '~/media' requests raise 'media:request' event.



Analytics defined in 'Sitecore.Analytics.RobotDetection.Media.MediaRequestHandler' handler that is supposed to do processing will checks:
  1. If Analytics is enabled for the site
  2. If requested item has some data in a tracking field
  3. Launches 'Tracker.StartTracking()' API which would initialize tracker ( 'startAnalytics' pipeline )
Happy coding

16 August 2015

Loop through renderings in presentation and get the associated datasource

Today I was asked for how you can programmatically loop through all the renderings for an item and get the datasource information for each of the rendering. That sounded like an interesting question so I decided to post it here... What we wanted to do was to push the datasource items through workflow when the main item is beeing approved. We will split this in 2 posts so it is not too long here. So on this first post we will just see some code that will loop through the presentation and retrieve the list of item set in the renderings datasource. To make it a little different, lets try to find those where the rendering is inside a specific placeholder and a device

Well I first started to create a context class that will have method like the following:  
        /// 
        /// Return renderings for a specific Placeholder for the current item and a specific device
        /// 
        /// 
        /// 
        /// 
        public IEnumerable GetRenderings(string placeholderKey, string deviceName)
        {
            var currentItem = Sitecore.Context.Item;

            Sitecore.Data.Fields.LayoutField layoutField = new Sitecore.Data.Fields.LayoutField(currentItem);
            Sitecore.Layouts.RenderingReference[] renderings = layoutField.GetReferences(GetDeviceItem(deviceName));

            var filteredRenderingList = new List();

            foreach (var rendering in renderings)
            {
                if (rendering.Placeholder.Contains(placeholderKey))
                {
                    filteredRenderingList.Add(new RenderingItemWrapper(rendering.RenderingItem));
                }
            }

            return filteredRenderingList;
        }

        /// 
        /// Return the settings including datasource ID for the renderings in a specific placeholder 
        /// For current item and specific device
        /// 
        /// 
        /// 
        /// 
        public IEnumerable GetRenderingsSettings(string placeholderKey, string deviceName)
        {
            var currentItem = Sitecore.Context.Item;

            Sitecore.Data.Fields.LayoutField layoutField = new Sitecore.Data.Fields.LayoutField(currentItem);
            Sitecore.Layouts.RenderingReference[] renderings = layoutField.GetReferences(GetDeviceItem(deviceName));

            var filteredRenderingList = new List();

            foreach (var rendering in renderings)
            {
                if (rendering.Placeholder.Contains(placeholderKey))
                {
                    filteredRenderingList.Add(new RenderingSettingsWrapper(rendering.Settings));
                }
            }

            return filteredRenderingList;
        }

        /// 
        /// Get the Device from the context database and the Device name
        /// 
        /// 
        /// 
        private Sitecore.Data.Items.DeviceItem GetDeviceItem(string deviceName)
        {
            if (Sitecore.Data.ID.IsID(deviceName))
            {
                return Sitecore.Context.Database.Resources.Devices.GetAll().Where(d => d.ID.Guid == new Guid(deviceName)).First();
            }
            else
            {
                return Sitecore.Context.Database.Resources.Devices.GetAll().Where(d => d.Name.ToLower() == deviceName.ToLower()).First();
            }
        }



You will note the difference between the IRenderingItemWrapper and IRenderingSettingsWrapper
The later has all the information about the Datasource Item.

Then you can have a method that will loop through your IEnumerable then check your datasource information:

        /// 
        /// Get the Datasources for all renderings inside a placeholders
        /// 
        /// 
        /// 
        public IEnumerable GetRenderingDatasources(string placeholderKey)
        {
            var renderingDatasources = new List();

            IEnumerable renderingsSettings = _presentationContext.GetRenderingsSettings(placeholderKey);
            foreach (var renderingSettings in renderingsSettings)
            {
                if (renderingSettings.DataSource != null)
                {
                    Sitecore.Data.Items.Item datasourceItem;
                    if (Sitecore.Data.ID.IsID(renderingSettings.DataSource))
                    {
                        datasourceItem = _sitecoreContext.GetItem(new Guid(renderingSettings.DataSource));
                    }
                    else
                    {
                        datasourceItem = _sitecoreContext.GetItem(renderingSettings.DataSource);
                    }

                    if (datasourceItem == null)
                        continue;

                    renderingDatasources.Add(datasourceItem);
                }
            }

            return renderingDatasources;
        }


Hope that help anyone...

25 July 2015

Site search and Predictive

I had an interesting requirement about a predictive search. The requirement was to propose terms when a user start entering text on the Search Box:


After a few thoughts we have considered the following approach let's make those terms propositions coming from the website content. As a matter of fact why not using the index to search for the term and return the short list required. What would we need:

  1. WebAPI call from the View
  2. A search Service on the .NET side that will query the index and bring the result
So It sounds quite simple.

So let's setup the Controller for your WebAPI. this could be something like:

namespace XXX.Web.Controllers.XXX.API
{
    [RoutePrefix("webapi/v1/search")]
    public class SuggestiveSearchController : ServicesApiController
    {
        private readonly ISuggestiveSearch _searchService;

        public SuggestiveSearchController(ISuggestiveSearch suggestiveSearchServices)
        {
            _searchService = suggestiveSearchServices;
        }

        [HttpGet]
        [Route("autocomplete")]
        public AutoCompleteSuggestionList Autocomplete(string query)
        {
            if (string.IsNullOrEmpty(query))
                return null;

            return _searchService.AutoCompleteTerm(query);
        }
    }
}


Now, on your View you will have something that calls your WebApi:

            $(document).ready(function () {
                $("#keyword.autocomplete").autocomplete({
                    serviceUrl: '/webapi/v1/search/autocomplete'
                });
            });


Make sure your route will resolve and Sitecore will not resolve your WebAPI route. For that you could use the Attribute routing as per the really nice article from Bart Bovendeerdt on the following link: http://wp-bartbovendeerdtcom.azurewebsites.net/sitecore-8-webapi-v2-mvc-and-attribute-routing/

Then on your service level, you will then retrieve your list of suggestion through Sitecore Content Search - here would be a quick draft...

        public AutoCompleteSuggestionList AutoCompleteTerm(string term)
        {
            var result = new AutoCompleteSuggestionList();
            var list = new List();

            if (String.IsNullOrEmpty(term))
                return result;

            result.query = term;

            var sitecoreService = new SitecoreService(_databaseContext.GetDatabaseName());
            var home = sitecoreService.GetItem(_siteContext.GetStartPath());
            var index = _contentSearchContext.GetIndex(new SitecoreIndexableItem(home));

            using (var context = index.CreateSearchContext(SearchSecurityOptions.DisableSecurityCheck))
            {
                var suggestionsKeywords = context.GetTermsByFieldName("keywords", term);
                foreach (var suggestion in suggestionsKeywords 
                {
                    list.Add(suggestion.Term);
                }
            }
            if (list.Count <= 0)
            {
                result.suggestions = list;
                return result;
 
            }

            result.suggestions = list.Distinct().Take(10).ToList();
            return result;
        }
    }

9 July 2015

Sitecore 8 Upload Zip File with Unpack options broken

Interresting topic for the day. I went on a client side for a training today and I show Sitecore capability for batch upload. Which I used quite all the time on Sitecore 7. So quite confidently, I decided to go ahead and demo it on the fly. Well unfortunately for me this did not go as planned...

I prepared my zip files with the different images, folder and subfolders



Went to the media library to upload the Zip file


Selected the unpack option


And... quite abbarassing


Well this has been reported as a bug and the workaround has been provided. If you face the same issue, you will need to edit the content of the MediaFolder.js file in the location /Website/Sitecore/Shell/Applications/Media/MediaFolder 
replace the line 320 with the following:



 //Sitecore.Support.439231
    this.yUploader.upload(file, this.destination, params);
 //Sitecore.Support.439231
 


12 June 2015

Experience Editor Edit Frame Button

On a recent project using Sitecore 8, we have extensively used the Experience Editor, which I have to say was really nice to work with. As usual, we have used MVC along side with GlassMapper. For one of our template page, we had some of the fields that needed to be editable but should not show on the page. This is where WebEdits frame buttons came quite handy. That is something you would have never used if you are not using the Experience editor.

So what is the web edit frame buttons. Well those are the buttons that appears when you select an element on your experience editor and allows you to edit either external elements and/or fields that are not displayed on your page. They appears as per the below:


Once you click on the button then you will see a new popup to edit whatever fields you want on the item you want:


To configure it is quite simple:

Go to the Core Database and locate the WebEdit section: 


Locate the folder called Edit Frame Buttons (/sitecore/content/Applications/WebEdit/Edit Frame Buttons), this will give you a good sample of the buttons, especially the Edit one.

You can duplicate the folder and rename it as you would like. Then on the edit button you will be able to edit the following field:


You will notice that on the "Fields" field you will be able to add the "|" separated list of the fields you want to allow user to edit on the frame as per the below:


After defining the fields list available on your Edit button, you will need to do a bit of coding to ensure the webedit frame appears on the Experience Editor. 

1- go to your view rendering and locate the section where you want the frame to appear
2- add the following using:

    using (BeginEditFrame(XXX.Common.Constants.ButtonItemPaths.Common.AddThisButtons, Model.Path))
    {
        
[+ Edit Add This for the Page]
}

The first parameter of your BeginEditFrame will be the path to the Folder you created on the Core DB:
XXX.Common.Constants.ButtonItemPaths.Common.AddThisButtons

will be something like
/sitecore/content/Applications/WebEdit/XXX/Edit Frame Buttons/Common/Add This Buttons

The second Parameter will be the path to the item you would like to edit:
Model.Path

will be something similar to
/sitecore/content/XXX/Home/About Us

There you go... you now have your Webedit buttons on your experience editor.

29 May 2015

Sitecore MVC and Castle.Windsor

I just wanted to add do a quick post today about Castle.Windsor, Sitecore MVC and your own project solution. I am usually using Castle.Windsor as IOC. I am quite sure a few of us encountered the following issue when running Sitecore some application on the Sitecore Client:




4976 16:45:28 ERROR Application error.
Exception: Sitecore.Mvc.Diagnostics.ControllerCreationException
Message: Could not create controller: 'Media'. 
The current route url is: 'api/sitecore/{controller}/{action}'. 
Source: Sitecore.Mvc
   at Sitecore.Mvc.Controllers.SitecoreControllerFactory.CreateController(RequestContext requestContext, String controllerName)
   at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
   at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
 
Nested Exception
 
Exception: Castle.MicroKernel.ComponentNotFoundException
Message: No component for supporting the service Sitecore.Controllers.MediaController was found
Source: Castle.Windsor
   at Castle.MicroKernel.DefaultKernel.Castle.MicroKernel.IKernelInternal.Resolve(Type service, IDictionary arguments, IReleasePolicy policy)
   at DPE.Business.DI.WindsorControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) in r:\Projects\XXX\Trunk\XXX.Business\DI\WindsorControllerFactory.cs:line 34
   at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName)
   at Sitecore.Mvc.Controllers.SitecoreControllerFactory.CreateController(RequestContext requestContext, String controllerName)

The issue there is if you are defining your IOC, you may need to ensure that This is resolving your Sitecore controllers correctly as well. here is the few controller I needed on my Initialisation:

            container.Register(Classes.FromAssemblyNamed("Sitecore.Speak.Client").BasedOn().LifestylePerWebRequest());
            container.Register(Classes.FromAssemblyNamed("Sitecore.Mvc").BasedOn().LifestylePerWebRequest());
            container.Register(Classes.FromAssemblyNamed("Sitecore.Mvc.DeviceSimulator").BasedOn().LifestylePerWebRequest());
            container.Register(Classes.FromAssemblyNamed("Sitecore.Marketing.Client").BasedOn().LifestylePerWebRequest());
            container.Register(Classes.FromAssemblyNamed("Sitecore.Client.LicenseOptions").BasedOn().LifestylePerWebRequest());