Tuesday, 28 February 2017

Sitecore development basics - Tools overview

As a Sitecore beginner it is very hard to get to know with all the tools used in Sitecore development process. Especially that you don't even know that some of them even exist. In this article I will try to collect must-haves that every Sitecore developer should know and use.

Object mapping

Object mapping frameworks are very useful in Sitecore. Using some objects based on transparent classes with full Intellisense support is more comfy than using Items with fields explicitly.

Glass.Mapper is the most popular ORM for Sitecore. It gives the availability to map Sitecore items to strongly typed objects, then they can be used in general code and unit tests as well. Glass is well optimized and easy to use.

Glass.Mapper has its own website - http://glass.lu/.
Tutorials can be found there also - http://glass.lu/Mapper/Sc/Tutorials.
 


 

Fortis is a tool similar to Glass but it is more like a wrapper than the mapper. It encapsulates Sitecore items with interfaces. Code is available here: https://github.com/Fortis-Collection/fortis and more info about usage here: http://fortis.ws/quick-start/ and here: http://fortis.ws/about/


Synthesis takes different approach than the two ones described earlier. It generates code based on templates in Sitecore instead of mapping fields or wrapping items. It is also very fast. Synthesis code is available on GitHub - https://github.com/kamsar/Synthesis and more info on wiki there https://github.com/kamsar/Synthesis/wiki

Serialization

Data serialization is a must in Sitecore projects. Solution must have a way to transfer templates, layouts and other types of items to different environments. It also should be automated for e.g deployments. Luckily there are some cool tools that solve this problem.

Team Development for Sitecore (TDS) is a tool from Hedgehog Development that gives availability to put and manage Sitecore items from the Visual Studio. Beside the serialization features it has a lot of other functionalities like code generation, .update package generation, delta deployments and many more. It is easy to use as well.

Official website - http://www.teamdevelopmentforsitecore.com/
Documentation - http://hedgehogdevelopment.github.io/tds/


Unicorn - tool from Connective DX, created by Kam Figy. Solves the same problems as TDS but in a bit different way. Whole serialization setup is configured in config patches and also there is a web console to fire the synchronization. Worth to mention are also Rainbow - new serialization engine using yaml files for items (they merge excellently) and also transparent sync. And off course it is free to use.

Repo at GitHub - https://github.com/kamsar/Unicorn
Kam's blog - http://kamsar.net/ - highly recommended source for new versions information.


Sitecore Courier is a tool that can build Sitecore update packages automatically. It can analyze serialized items and pack only changed ones. It comes with console runner, so builing packages is even easier. You can find it at Sitecore Marketplace: https://marketplace.sitecore.net/en/Modules/Sitecore_Courier.aspx and the code is located at GitHub: https://github.com/adoprog/Sitecore-Courier. More info can be found at blog by Alexander Doroshenko: http://sitecoresnippets.blogspot.com/2012/10/sitecore-courier-effortless-packaging.html



Continuous Integration


Sitecore Ship is a tool that gives availability to install Sitecore update packages remotely. As TDS and Unicorn have their own hooks for integrating with CI systems, Sitecore Ship fills a lack of it in Sitecore Courier. Full code is available on GitHub: https://github.com/kevinobee/Sitecore.Ship. Api documentation is here: http://docs.sitecoreship.apiary.io/. There are also PowerShell functions by Patrick Perrone https://github.com/patrickperrone/Sitecore.Ship-PowerShell-Functions




Sitecore Package Deployer from Hedgehog Development is a similar tool to Sitecore Ship. Instead of deploying packages sent by HTTP it deploys them from file system. More info you can find on TDS website: https://www.teamdevelopmentforsitecore.com/Blog/sitecore-package-deployer. Full codebase is available at GitHub: https://github.com/HedgehogDevelopment/SitecorePackageDeployer - you can find there installer also - built as .update package.

Data migration

Sometimes we need to transfer data between some Sitecore instances. It might be for update UAT environment with production content or maybe for Sitecore upgrade purposes, with approach of setting fresh new Sitecore instance.

RAZL is another nice tool from Hedgehog Development. It's purpose is to add availability to compare databases of two Sitecore instances and look for differences. It also adds option to move and synchronize data between instances.


Content Migrator Sidekick App by Jeff Darchuk is a tool for moving data between instances. It's core is Rainbow - serialization engine designed by Kam Figy for Unicorn. It needs a Sidekick installed first: https://jeffdarchuk.com/2016/10/03/sitecore-sidekick/. More info you can find at Jeff's blog: https://jeffdarchuk.com/2016/10/24/sitecore-sidekick-content-migrator/.


Coast for Sitecore is a module that was designed to give an easy copy-paste functionality for moving items between Sitecore instances. Here is more info about that: https://www.geekhive.com/buzz/post/2016/11/introducing-coast-for-sitecore/. Now, there is a version 3.0: https://www.geekhive.com/buzz/post/2017/02/introducing-coast-for-sitecore-version-3-0/. You can find it on Sitecore Marketplace: https://marketplace.sitecore.net/en/Modules/S/Sitecore_Coast.aspx.

Visual Studio plugins


 Sitecore Rocks was designed to integrate whole Sitecore stuff with Visual Studio. You can connect with your instance, edit items and manage just like in the Content Editor. It can really increase developer productivity. Plugin is available here: https://marketplace.visualstudio.com/items?itemName=JakobChristensen.SitecoreRocks and code on GitHub: https://github.com/JakobChristensen/Sitecore.Rocks

Unit testing

FakeDb is a unit testing framework for Sitecore. It enables creating fake Sitecore database, so then it can be used in tests. It can be found on GitHub: https://github.com/sergeyshushlyapin/Sitecore.FakeDb. There is also a pretty nice documentation: https://github.com/sergeyshushlyapin/Sitecore.FakeDb/wiki


AutoSitecore is a bunch of AutoFixture customizations prepared to use new testability features in Sitecore 8.2. It was created by Dan Soloway and it is available here https://github.com/dsolovay/AutoSitecore


Solution architecture


Helix, as the documentation says, is a set of overall design principles and conventions for Sitecore development. You might heard of this from Habitat project, which was the introduction to that approach. Helix was prepared to structurize all of that principals. Full documentation is here: http://helix.sitecore.net/. Full code of Habitat is here: https://github.com/sitecore/habitat.

Ignition - this is a development accelerator designed by team at Perficient. You can read more about that at Perficient website http://blogs.perficient.com/microsoft/2016/06/sitecore-developers-start-your-ignition/. Whole code is available on GitHub https://github.com/sitecoreignition/SitecoreIgnition. Here is also quick start guide: https://www.youtube.com/watch?v=rtd1XkWFKhw.






Sitecore official modules

Web Forms For Marketers (WFFM)
Module that adds availability to create forms in Sitecore and use them to collect user information and store it for analytics purposes. Official documentation is here: https://doc.sitecore.net/web_forms_for_marketers/

Email Experience Manager (EXM)
EXM is a module that enables creating e-mail campaigns. Official documentation: https://doc.sitecore.net/email_experience_manager

Federated Experience Manager (FXM)
FXM module is used to integrate non-Sitecore sites with existing Sitecore instance. You can track user information and collect that to extend whole user profile in Sitecore. Official documentation: https://doc.sitecore.net/sitecore_experience_platform/digital_marketing/federated_experience_manager

Sitecore Experience Accelerator (SXA) 
SXA provides reusable layouts and components for rapid website development. Official documentation: https://doc.sitecore.net/sitecore_experience_accelerator

Sitecore marketplace modules

Sitecore PowerShell Extensions - this module gives you the power of PowerShell inside Sitecore. It is incredibly useful and fast for advanced usage. A lot of examples can be found on blog by Adam Najmanowicz: http://blog.najmanowicz.com/sitecore-powershell-console/. You can download it from Sitecore Marketplace: https://marketplace.sitecore.net/en/Modules/Sitecore_PowerShell_console.aspx.



Front-End development

Feydra is another great tool from Hedgehog development. It gives front-end developers availability to work directly on virtualized Sitecore instance using their own tools. They can commit changes without intervention of back-end developers. More info about Feydra can be found here: http://www.teamdevelopmentforsitecore.com/Feydra.


Other stuff

Dianoga is a tool from Kam Figy that optimizes images for the media library. Full code is available here: https://github.com/kamsar/Dianoga.

Sitecore Instance Manager (SIM) is a great app that will help you manage your Sitecore instances. You can rapidly install new fresh instance with just few clicks. That is really helpful while investigating if some bugs are present in clean Sitecore or just in your code. You can download it from Marketplace: https://marketplace.sitecore.net/en/Modules/Sitecore_Instance_Manager.aspx and the code is available on GitHub: https://github.com/Sitecore/Sitecore-Instance-Manager

Sitecore Log Analyzer (SCLA) is a tool for analyzing Sitecore logs. It is very handy in situation when you need to find some entries but logs are splitted. You can search by dates and entry types. You can download it from Marketplace: https://marketplace.sitecore.net/en/Modules/Sitecore_Log_Analyzer.aspx

Sitecore Support Package Generator (SSPG) was designed for helping developers collecting all crucial data needed to investigate problem by Sitecore Support. It is very useful - it can take all required Sitecore and IIS logs, pack it and send right to Support. It is available at Sitecore Marketplace: https://marketplace.sitecore.net/en/Modules/Sitecore_Support_Package_Generator.aspx

Summary

Off course this list is just a quick overview of available Sitecore tools, but I hope it will give you more information how efficiently develop Sitecore applications. Happy Sitecoring!


Friday, 13 January 2017

Razl scripting with PowerShell

Razl, tool from Hedgehog Development, that was designed to transfer items between Sitecore instances and compare them, has some nice scripting features.

I needed to use Razl scripting for Sitecore upgrade process. I created new fresh Sitecore instance (it was big jump, from 6.5 to 8.1) and started preparing what should be moved to new database. Old instance had a lot of datasource items and huge amount of media library items. Transfer all of this things was huge deal and was processing for over a dozen of hours. I decided to make some changes in my approach.

Preparation of Sitecore instances

I was using Razl 3.0.5. Unfortunately I had some problems with my solution that I couldn't connect with this tool to the Sitecore that had all of solution code deployed, so I've created a clean instance of version 6.5 and a clean version of 8.1. I've changed the connection strings of this two to the correct solution databases and I used this two clean instances just for transferring purposes - worked like a charm. You might not have exact problem, but this is how I went through that.

Preparing Razl script file

First you have to prepare the script file in the Razl. You can do it just like in general, by adding tasks to Task List:


Then, instead of running transfer, you can click 'Export Tasks' button. You will be prompted to save the script file. Let's take a look into the one:
<?xml version="1.0" encoding="utf-8"?>
<razl>
  <connection name="SC65VanillaWithSW.Master" readOnly="false" install="true">
    <url>http://sc650vanilla/</url>
    <accessGuid>047c5600-e111-449c-9e2b-179b06f17190</accessGuid>
    <database>master</database>
    <path>C:\inetpub\wwwroot\sc650Vanilla\Website</path>
  </connection>
  <connection name="SC81VanillaForSW.Master" readOnly="false" install="true">
    <url>http://sc81u2vanillaforconnection/</url>
    <accessGuid>8db29355-a8d4-4102-969a-537cc8c54f30</accessGuid>
    <database>master</database>
    <path>C:\inetpub\wwwroot\sc81u2vanillaforconnection\Website</path>
  </connection>
  <operation name="CopyAll" source="SC65VanillaWithSW.Master" target="SC81VanillaForSW.Master">
    <!--Copy with overwrite '/sitecore/templates/SW', all missing parents and all child items from 'SC65VanillaWithSW.Master' to 'SC81VanillaForSW.Master'-->
    <parameter name="itemId">b80ae69f-4212-43e6-af97-2f86ddcddae1</parameter>
    <parameter name="overwrite">True</parameter>
    <parameter name="lightningMode">False</parameter>
  </operation>
  <operation name="CopyAll" source="SC65VanillaWithSW.Master" target="SC81VanillaForSW.Master">
    <!--Copy with overwrite '/sitecore/templates/User Defined', all missing parents and all child items from 'SC65VanillaWithSW.Master' to 'SC81VanillaForSW.Master'-->
    <parameter name="itemId">b29ee504-861c-492f-95a3-0d890b6fca09</parameter>
    <parameter name="overwrite">True</parameter>
    <parameter name="lightningMode">False</parameter>
  </operation>
  <operation name="CopyAll" source="SC65VanillaWithSW.Master" target="SC81VanillaForSW.Master">
    <!--Copy with overwrite '/sitecore/layout/Layouts/SW', all missing parents and all child items from 'SC65VanillaWithSW.Master' to 'SC81VanillaForSW.Master'-->
    <parameter name="itemId">2141e479-3f72-447c-9afa-3b4db1ea283d</parameter>
    <parameter name="overwrite">True</parameter>
    <parameter name="lightningMode">False</parameter>
  </operation>
</razl>

It has a two connections for the instances which will be used in transfer. It comes from the Razl configuration, where firstly I created that connections. Under that elements there is a list of operations with specified source instance, target instance, ID of the item and configuration of the operation type - in my case it will be CopyAll with overwriting the target instance.

As far as I knew at that time, there was no way to edit exported script with Razl, so I was editing it manually.

Preparing PowerShell run script

At last I wanted to have a PowerShell script that will run my transfer script with just one click. I have prepared a PSs that run razl.exe with specified scripts. For core database this is quite simple - set your directory where Razl script are located in:


For master database I decided to split Razl script into smaller parts, so the I was able to comment out some of them to run just specific ones:


Also these scripts log full log into specific files. So everything that happens while transfer is saved for analysis. Here is some example part of the log:

    1 13:00:31,579 INFO  CopyAll Started Id: 563a2ddb-ad89-4182-9706-eb1512abe0b1, Path: /sitecore/system/Field types/List Types/Google Maps Multilist, From: SC65VanillaWithSW.Core, To: SC81VanillaForSW.Core, Overwrite: True
   1 13:00:31,579 INFO  CopyAll Processing /sitecore/system/Field types/List Types/Google Maps Multilist
   1 13:00:31,580 INFO  CopyItem Started Id: 563a2ddb-ad89-4182-9706-eb1512abe0b1, Path: /sitecore/system/Field types/List Types/Google Maps Multilist, From: SC65VanillaWithSW.Core, To: SC81VanillaForSW.Core
   1 13:00:31,847 INFO  CopyItem Finish Id: 563a2ddb-ad89-4182-9706-eb1512abe0b1, Path: /sitecore/system/Field types/List Types/Google Maps Multilist, From: SC65VanillaWithSW.Core, To: SC81VanillaForSW.Core
   1 13:00:31,928 INFO  CopyAll processing children of /sitecore/system/Field types/List Types/Google Maps Multilist
   1 13:00:31,928 INFO  CopyAll Processing /sitecore/system/Field types/List Types/Google Maps Multilist/Menu
   1 13:00:31,929 INFO  CopyItem Started Id: 60daf681-8069-46a2-aa39-5490741f6cec, Path: /sitecore/system/Field types/List Types/Google Maps Multilist/Menu, From: SC65VanillaWithSW.Core, To: SC81VanillaForSW.Core
   1 13:00:32,196 INFO  CopyItem Finish Id: 60daf681-8069-46a2-aa39-5490741f6cec, Path: /sitecore/system/Field types/List Types/Google Maps Multilist/Menu, From: SC65VanillaWithSW.Core, To: SC81VanillaForSW.Core
   1 13:00:32,252 INFO  CopyAll processing children of /sitecore/system/Field types/List Types/Google Maps Multilist/Menu
   1 13:00:32,252 INFO  CopyAll Processing /sitecore/system/Field types/List Types/Google Maps Multilist/Menu/Show Map
   1 13:00:32,252 INFO  CopyItem Started Id: ce073686-11cb-4921-b4db-61c98bc1f54a, Path: /sitecore/system/Field types/List Types/Google Maps Multilist/Menu/Show Map, From: SC65VanillaWithSW.Core, To: SC81VanillaForSW.Core
   1 13:00:32,519 INFO  CopyItem Finish Id: ce073686-11cb-4921-b4db-61c98bc1f54a, Path: /sitecore/system/Field types/List Types/Google Maps Multilist/Menu/Show Map, From: SC65VanillaWithSW.Core, To: SC81VanillaForSW.Core
   1 13:00:32,576 INFO  CopyAll processing children of /sitecore/system/Field types/List Types/Google Maps Multilist/Menu/Show Map
   1 13:00:32,576 INFO  CopyAll Processing /sitecore/system/Field types/List Types/Google Maps Multilist/Menu/Select All
   1 13:00:32,577 INFO  CopyItem Started Id: bbe0cd71-aac7-47bc-971a-49265078d17c, Path: /sitecore/system/Field types/List Types/Google Maps Multilist/Menu/Select All, From: SC65VanillaWithSW.Core, To: SC81VanillaForSW.Core
   1 13:00:33,153 INFO  CopyItem Finish Id: bbe0cd71-aac7-47bc-971a-49265078d17c, Path: /sitecore/system/Field types/List Types/Google Maps Multilist/Menu/Select All, From: SC65VanillaWithSW.Core, To: SC81VanillaForSW.Core
   1 13:00:33,209 INFO  CopyAll processing children of /sitecore/system/Field types/List Types/Google Maps Multilist/Menu/Select All
   1 13:00:33,209 INFO  CopyAll Processing /sitecore/system/Field types/List Types/Google Maps Multilist/Menu/Deselect All
   1 13:00:33,209 INFO  CopyItem Started Id: b54acbc5-0fc0-4d6d-a863-0f8657e50504, Path: /sitecore/system/Field types/List Types/Google Maps Multilist/Menu/Deselect All, From: SC65VanillaWithSW.Core, To: SC81VanillaForSW.Core
   1 13:00:38,480 INFO  CopyItem Finish Id: b54acbc5-0fc0-4d6d-a863-0f8657e50504, Path: /sitecore/system/Field types/List Types/Google Maps Multilist/Menu/Deselect All, From: SC65VanillaWithSW.Core, To: SC81VanillaForSW.Core
   1 13:00:38,537 INFO  CopyAll processing children of /sitecore/system/Field types/List Types/Google Maps Multilist/Menu/Deselect All
   1 13:00:38,593 INFO  CopyAll Finish Id: 563a2ddb-ad89-4182-9706-eb1512abe0b1, Path: /sitecore/system/Field types/List Types/Google Maps Multilist, From: SC65VanillaWithSW.Core, To: SC81VanillaForSW.Core, Overwrite: True
   1 13:00:38,705 INFO  CopyAll Started Id: 5cee31bf-120d-4936-b9c6-930cbf63cb57, Path: /sitecore/system/Field types/Simple Types/Google Maps Single Point, From: SC65VanillaWithSW.Core, To: SC81VanillaForSW.Core, Overwrite: True

More info about Razl scripting is in official Razl documentation: https://hedgehogdevelopment.github.io/razl/script.html.

Tuesday, 10 January 2017

Sitecore Module - Dynamic Sitemap XML

After a lot of work spent on creating project specific sitemap xml implementations I have prepared my own generic sitemap xml module. It is based on original marketplace sitemap module but adds some new great features.


It has two main assumptions:
  • Flexible configuration - to give end user as many as possible configuration options, because it is easier to edit Sitecore items than edit and deploy config files.
  • Extensibility - code functionality should be extensible and override-able. It should be easy to extend or override functionality, without decompiling and copy-pasting a lot of code.

Specifying your own logic

To use or not to use marketplace module - that is the question! Most times main reason to write your own sitemap implementation is thought if there will be some custom tricky functionalities needed. Something like some static html pages or other links that exist outside Sitecore.

 
You can specify your own logic, that can add your custom items to the sitemap.

You should create class that implements IItemsProcessor interface, put it in your assembly and attach your class to the site configuration item, in format MyType, MyAssembly.


In this approach, main functionality of module can be easily changed. More info here https://github.com/ReoKzK/Sitecore.SharedSource.DynamicSitemap/wiki/Specifying-your-own-logic

Separation from content

I also decided to definitely separate sitemap things from the actual content. So deciding whether the item goes to sitemap or nor or setting the change frequency or priority, is set on the sitemap configuration item in Sitecore. This approach will keep your items clean. More info here https://github.com/ReoKzK/Sitecore.SharedSource.DynamicSitemap/wiki/Creating-new-sitemap-configuration

That's all :)

Module is uploaded to official Sitecore Marketplace https://marketplace.sitecore.net/Modules/D/Dynamic_Sitemap_XML_Module.aspx

Whole documentation is available here https://github.com/ReoKzK/Sitecore.SharedSource.DynamicSitemap/wiki

Library is also available at nuget:
Install-Package Sitecore.SharedSource.DynamicSitemap
Hope that my module will be useful and will improve your websites development process.

Tuesday, 6 December 2016

Language Fallback on Final Layout

Last time I was struggling with translating items to different languages. I was using the ClayTablet Sitecore Translation Connector module - it basically sends the content to translator, waits till it will be returned, receives the translated content and creates new version in desired language. Sitecore was in Initial Release of 8.1.

Then I realized, that new versions of items in other languages had missing value in Final Renderings field. Unfortunately solution which I was working on, was using this field widely from the beginning - by the Experience Editor. I tried to set the Language Fallback on that field but in vain.

I have successfully reproduced this behaviour on clean instance of 8.1 Initial Release. I have enabled Language Fallback:

    <sites>
      <site name="shell">
        <patch:attribute name="enableItemLanguageFallback">true</patch:attribute>
        <patch:attribute name="enableFieldLanguageFallback">true</patch:attribute>
      </site>
      <site name="website">
        <patch:attribute name="enableItemLanguageFallback">true</patch:attribute>
        <patch:attribute name="enableFieldLanguageFallback">true</patch:attribute>
      </site>
    </sites>

Also I have set the fallback path in the language item:


After that I have added new rendering from Experience Editor:


Unfortunately, I wasn't able to fallback this field from the base language. I have sent my problem to Sitecore Support and they confirmed, that this feature is missing. Sadly I had nothing more to do but manually set these renderings or use a PowerShell to automate it. Fortunately this bug reported by me was labelled as feature request and now it is present on version 8.2 Update-1!


The public reference number was set to 105306.

I have downloaded the package and started to testing it out. Fresh instance was set up by the SIM.
I went to the Final Renderings field:

/sitecore/templates/System/Templates/Sections/Layout/Layout/__Final Renderings

And I have enabled field level fallback:


Everything works ok now - additional "Sample rendering" added from Experience Editor is present now on other languages that have Fallback set:



Also, the Update-1 comes with really great features like wide Azure support. You should definitely check this out!


Thursday, 8 September 2016

Error while using WFFM save action Send Email Campaign Message

Last time while I was playing with EXM and WFFM I have experienced strange issue. I am using Sitecore 8.1 Update-2, EXM 3.2.1 and WFFM 8.1 Update-2. I have added Send Email Campaign Message Save Action to my form, set up message and destination e-mail.



After form submit I got an error:

 5276 15:43:58 INFO  AUDIT (extranet\Anonymous): [WFFM] Form {B9C58542-7A02-4191-94B1-186C87EC74D9} is saving to db   5276 15:43:58 WARN  [WFFM] Object reference not set to an instance of an object.   Exception: System.NullReferenceException   Message: Object reference not set to an instance of an object.   Source: Sitecore.Forms.Custom      at Sitecore.Form.Submit.SendStandardMessage.Send(AdaptedResultList fields)      at Sitecore.Forms.Core.Dependencies.DefaultImplActionExecutor.ExecuteSaving(ID formID, ControlResult[] fields, IActionDefinition[] actionDefinitions, Boolean simpleAdapt, ID sessionID)   5276 15:43:58 WARN  [WFFM] The 'Send Email Campaign Message[id={EB59E095-5B61-4C04-8286-9469DAFD9A13}]' save action failed: We experienced a technical difficulty while processing your request. Your data may not have been correctly saved.   5276 15:43:58 WARN  [WFFM] Web Forms for Marketers: an exception: We experienced a technical difficulty while processing your request. Your data may not have been correctly saved. has occured while trying to execute an action.

NullReferenceException was rather strange for me, so I started deep investigation. I have decompiled some WFFM and EXM classes and I found the problem. Some missing checks caused that issue.

The main cause of that situation is the EXM Message is being in state other than Active. Sitecore Support provided me with package, that solves this glitch.

Public reference number is 120449.

To resolve the issue, I had to:
  1. Put the Sitecore.Support.120449.dll into bin folder
  2. Navigate to the /sitecore/system/Modules/Web Forms for Marketers/Settings/Actions/Save Actions/Send Email Campaign Message item and perform the following changes with its fields:
  • Assembly -> Sitecore.Support.120449
  • Class -> Sitecore.Support.Form.Submit.SendStandardMessage
         3. Publish the changes

After that it worked for me. Hope that post will be helpful :)

Saturday, 25 June 2016

Error in event item:saved when migrating old WFFM items by Razl

Last time when I was upgrading another website from version 6.5 to 8.1, I have faced the problem with WFFM forms. I was transferring all content from old database to new one, using Razl. Almost everything went OK, but WFFM Form items.

The error I got, was rather misterious:



18684 11:12:39 ERROR One or more exceptions occurred while processing the subscribers to the 'item:saved' event.
Exception[1]: System.FormatException
Message[1]: Unrecognized Guid format.
Source[1]: mscorlib
   at System.Guid.GuidResult.SetFailure(ParseFailureKind failure, String failureMessageID, Object failureMessageFormatArgument, String failureArgumentName, Exception innerException)
   at System.Guid.TryParseGuid(String g, GuidStyles flags, GuidResult& result)
   at System.Guid..ctor(String g)
   at Sitecore.Analytics.Data.TrackingField.<>c__DisplayClass21.b__20(XElement e)
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at Sitecore.Analytics.Data.TrackingField.ValidateLinks(LinksValidationResult result)
   at Sitecore.Links.ItemLinks.AddLinks(Field field, List`1 links, ItemLinkState linkState)
   at Sitecore.Links.ItemLinks.GetLinks(ItemLinkState linkState, Boolean allVersions, Boolean includeStandardValuesLinks)
   at Sitecore.Links.SqlLinkDatabase.UpdateItemVersionReferences(Item item)
   at Sitecore.Links.ItemEventHandler.OnItemSaved(Object sender, EventArgs args)
   at Sitecore.Events.Event.EventSubscribers.RaiseEvent(String eventName, Object[] parameters, EventResult result)


18684 11:12:39 ERROR Razl service error
Exception: System.AggregateException
Message: One or more exceptions occurred while processing the subscribers to the 'item:saved' event.
Source: Sitecore.Kernel
   at Sitecore.Events.Event.EventSubscribers.RaiseEvent(String eventName, Object[] parameters, EventResult result)
   at Sitecore.Events.Event.RaiseEvent(String eventName, Object[] parameters)
   at Sitecore.Events.Event.RaiseItemSaved(Object sender, ItemSavedEventArgs args)
   at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
   at Sitecore.Data.Engines.EngineCommand`2.RaiseEvent[TArgs](EventHandler`1 handlers, Func`2 argsCreator)
   at Sitecore.Data.Engines.EngineCommand`2.Execute()
   at Sitecore.Data.Engines.DataEngine.SaveItem(Item item)
   at Sitecore.Data.Managers.ItemProvider.SaveItem(Item item)
   at Sitecore.Data.Managers.PipelineBasedItemProvider.ExecuteAndReturnResult[TArgs,TResult](String pipelineName, String pipelineDomain, Func`1 pipelineArgsCreator, Func`1 fallbackResult)
   at Sitecore.Data.Managers.PipelineBasedItemProvider.SaveItem(Item item)
   at Sitecore.Data.Items.ItemEditing.AcceptChanges(Boolean updateStatistics, Boolean silent)
   at Sitecore.Data.Items.EditContext.Dispose()
   at HedgehogDevelopment.Razl.Service.RazlService.SetItemDetails(Guid accessGuid, String database, Guid itemId, ItemDetails itemDetails)

It was really confusing for me. Later, I realized that it was caused by value of field Tracking in Personalization section. In my old database the value was:

<tracking>
     <event name="Field Changed" />
     <event name="Field Completed" />
     <event name="Field Not Completed" />
     <event name="Field Out of Boundary" />
     <event name="Invalid Field Syntax" />
</tracking>

In new version those events need an id parameter, not only name.

I decided to prepare that items by hand and put them in Sitecore package. I really wanted to make it all automated, but on the other hand, that solution wasn't really bad.

So I prepared that field in a way like this (Tracking field in 8.1 is in Advanced section):

<tracking>
    <event id="{AA3AE715-E87D-4B4D-80C7-4290546F770F}" name="Field changed" />
    <event id="{F0113A93-570A-4F69-8C7C-BA08037D1E34}" name="Field Completed" />
    <event id="{7E86B2F5-ACEC-4C60-8922-4EB5AE5D9874}" name="Field Not Completed" />
    <event id="{F3D7B20C-675C-4707-84CC-5E5B4481B0EE}" name="Field Out of Boundary" />
    <event id="{844BBD40-91F6-42CE-8823-5EA4D089ECA2}" name="Invalid Field Syntax" />
</tracking>

And it works :)


Thursday, 9 June 2016

WFFM - Creating custom hidden field with Context Item ID

Last time I was creating article comment functionality using Web Forms For Marketers. I have designed it that all comments was saved as Sitecore items and put into bucket in specified location. One of the problems was to put some information about article we are commenting.

I have chose Sitecore ID to be put inside that comment item. Unfortunately I wasn't able to do it out-of the-box. I needed to write some custom code and I thought that custom WFFM field would be the best idea.

WFFM version I was using was 8.1 rev. 151217 (Update-1). It's code changes very frequently so tutorials found in internet was a bit of outdated (very probably that mine will be soon too ;)).

I decided that the best and pretty easy way, will be create control that will put hidden html field and populate it with context item ID. I was told that the best way to achieve it will be create derivative from SingleLineText field. Tools like ILSpy or dotPeek was very helpful to take a look at the code inside. The value of Sitecore.Context.Item.ID is taken in OnLoad() method. To make it more flexible I have added field that made it switchable.

Here is the code:

using Sitecore.Form.Core.Attributes;
using Sitecore.Form.Web.UI.Controls;
using System.ComponentModel;
using System.ComponentModel.Design;
 
namespace SitecoreCoffee.WFFM.CustomFields
{
    /// <summary>
    /// Hidden Id Field
    /// </summary>
    [Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))]
    public class HiddenIdField : SingleLineText
    {
        private bool _isHidden = true;
 
        /// <summary>
        /// Used to switch hidden/visible
        /// </summary>
        [VisualCategory("Configuration")]
        [VisualFieldType(typeof(Sitecore.Form.Core.Visual.BooleanField))]
        [VisualProperty("Is Hidden?", 10), DefaultValue("Yes")]
        public string IsHidden
        {
            get
            {
                return _isHidden ? "Yes" : "No";
            }
 
            set
            {
                _isHidden = value == "Yes";
            }
        }
 
        protected override void OnLoad(System.EventArgs e)
        {
            Text = Sitecore.Context.Item.ID.ToString();
 
            if (_isHidden)
            {
                Attributes["style"] = "display: none";
            }
        }
    }
} 

If you are using MVC you should also create ViewModel for that field:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
 
namespace SitecoreCoffee.WFFM.CustomFields
{
    /// <summary>
    /// View Model for Hidden Id Field
    /// </summary>
    public class HiddenIdFieldViewModel : Sitecore.Forms.Mvc.ViewModels.Fields.SingleLineTextField
    {
        [DataType(DataType.Text)]
        public override string Value { get; set; }
 
        /// <summary>
        /// Initializes field
        /// </summary>
        public override void Initialize()
        {
            KeyValuePair<string, string> isHidden = Parameters.FirstOrDefault(x => x.Key.ToUpper() == "ISHIDDEN");
 
            if (isHidden.Value.ToUpper() != "NO")
            {
                if (!string.IsNullOrWhiteSpace(CssClass))
                {
                    CssClass += " hidden";
                }
 
                else
                {
                    CssClass = "hidden";
                }
            }
 
            ShowTitle = false;
 
            Value = Sitecore.Context.Item.ID.ToString();
        }
    }
}

The last part is to create Sitecore item. It should be added below /sitecore/system/Modules/Web Forms for Marketers/Settings/Field Types. This item should be based on template /sitecore/templates/Web Forms for Marketers/Field Type and be populated with:
  • Assembly - file name of code assembly
  • Class - class name of field type with full namespace
  • MVC Type - class name of field type view model with full namespace and its assembly name (after comma)


And it can be used in form:



Hope it will be helpful :)