Creating items into multiple locations using SPE

When we work with Multisite solution where in the same Sitecore instance we have different sites for different regions/country, or when we go with several micro sites configuration based on Master site, there are scenarios when we have to create new item(s) based on specific template(s) on all the sites that has been created as part of the instance.

There is absolutely no issue when we are dealing with few sites and pages, but how about when we have more sites? and what if we have to create more than one item under each site?

As a solution we can go to each site node and create the expected items manually, but this approach is going to take good amount of time to complete the full process.

Sitecore Powershell Extensions-1

Solution:

Instead we can leverage Sitecore PowerShell Extensions (SPE) to perform this activity, this is much fast and one of the best approach to complete this operation.

For example– If we want to add two items based on two different templates on the same Sitecore Instance, you can use the following script for that and this will get the job done.

Get-Item master: -Query "/sitecore/content//*[@@templatename='Home Page']" | ForEach-Object {
$newpath= $_.FullPath
$item = New-Item $newpath -Name TestArticle -type "/sitecore/templates/User Defined/Sandbox/Article"
$item = New-Item $newpath -Name FAQ -type "/sitecore/templates/User Defined/Sandbox/FAQ"
}

Sitecore Powershell Extensions

In the above example what i have done is:

  1. Querying all the home nodes under /sitecore/content – based on “Home Page” template.
  2. Taking each home item as context and running “New-Item” SPE command to create an item based on template passed.
  3. As we are running two commands, two items will get created under each site.

Thanks to Michael West and Adam Najmanowicz for this great module.

Hope this is helpful and can save someone’s time who is trying to do something similar.

Happy learning 🙂

References:

  1. https://doc.sitecorepowershell.com/
  2. https://sitecorepowershell.com/

 

Advertisements

Sitecore Basics- Introduction to Personalization

The scope of this blog post is to give an idea about personalization in Sitecore, why it’s required and steps to create  and configure personalization for the components, this is for beginners who are trying to understand the concept and how it can be implemented.

Personalization enables you to deliver targeted content to your visitors. For example, you can implement rules that show personalized content to visitors based on their browsing behavior and their accumulated profile values.
This is really important as you don’t want to show something to users which really doesn’t makes any sense to them.

Sitecore-Personalization

As an example- For an e-Commerce application as an business you want to show relevant information to users to get most of the conversions, this depends on number of factors, some of them includes:

  • User behavior
  • Location
  • Goals users have triggered.
  • Anonymous Vs Logged in users
  • Based on Subscription
  • Showing different banner images.

Sitecore XP lets you choose from several personalization approaches:

  1. Rules-based personalization: You define the conditions under which content is delivered to a customer. For example, you can set rules based on the IP address or physical location of your visitors, the keywords they use to reach your site, their mobile device, or the goals that they achieve on your website to determine the content that is displayed.
  2. Adaptive personalization- Use visitor profiles and pattern-card matching to dynamically adapt the content shown to visitors in real time. You can set adaptive personalization rules in Sitecore XP’s Rules Set Editor.
  3. Historical personalization: You can set rules that personalize content based on a contact’s historical or past behavior, rather than their actions from the current session (after all, context is what comes before and after the present).
  4. Test and then personalize: With Sitecore XP, you can use A/B and multivariate testing to assess your content and use the test results to optimize for conversion rates against your site’s goals. You can also use testing to assess which type of content works best with certain segments of your visitors.
  5. Journey-based personalization: Design user journeys with Sitecore XP using advanced business logic, and use them to help assess where your customers are in their journey with your brand. Then you can use triggers to advance them through their journeys in context of how far along they are.

We use Rule set editor (https://doc.sitecore.net/sitecore_experience_platform/digital_marketing/personalization/the_rule_set_editor ) to set the rules and action to perform and configure personalization for the individual components.

There are several out of the box categories which we can use to personalize the components, which includes:

  1. Campaigns
  2. Channels
  3. Date
  4. Device
  5. Fields
  6. GeoIP
  7. Tracking
  8. Visit and etc.

Personalizing the Component:

In order to personalize the component we have to make sure that the component which you are targeting to personalize should support datasource, this would help us in assigning different contents based on different criteria set.

Here are the steps to configure personalization for specific component(s):

  1. Select the component that you want to personalize, you can select the component either from presentation or from Experience editor.Personalization-1
  2. Select the component and click on Personalize button.
  3. Click on the “New Condition” button and add the rule which you want to add based on the requirement.
  4. Click on Edit button and add the rule.Personalization-2
  5. As an example- i am adding the rule which is based on field name compares to specific value.Personalization-3
  6. We can also define the default or fallback component datasource, if none of the conditions matches the default will be used.Personalization-4
  7. Once the configurations are done on the component, we can see an indicator in the presentation which shows that personalization has been applied to the specific rendering/component.Personalization-5
  8. We can personalize the component from experience editor as well.Personalization-6
  9. Now based on the condition which is added on the component, related content will be rendered else the default content will be displayed.

 

Custom Personalization:

There are certain scenarios where out of the box personalization which are available are not enough to handle the business scenarios, in those cases we have to think about creating custom personalization rules.

We need to create a class that inherits from Sitecore.Rules.Context and implement the Execute() method,and this is where all the business rule exits for the custom rule. We will be covering in a separate blog post about how to create custom personalization rule and applying it on the renderings.

Hope this helps.

Happy learning and wish you all a very Happy New Year 2018 🙂

References:

https://www.sitecore.net/solutions/personalization-segmentation

https://doc.sitecore.net/sitecore_experience_platform/digital_marketing/personalization

Faceted Search with Sitecore

Facets are used to group and classify content items, it’s used to aggregate the count of terms in a field to help a user filter their search more and more to get to the specific results they are after.

Search-Facets

As per the documentation of SOLR, facets are described as “… the arrangement of search results into categories based on indexed terms…”. faceting makes it really easy for the end users to look and explore for something which they are looking for. An example can be amazon.com which provides faceted navigation based on the selected keyword, which facilitates users to do look into specific category and narrowing down their results.

Sitecore+Search

Lucene and SOLR both provides support for Facets using ContentSearch API,which means you write facets one and that can be re-used for other search engines as well.
Using ContentSearch API we can use FacetOn() method on the IQueryable<T> instance to set what to facet on, and then call GetFactes() method to get the list of results.

context.GetQueryable<SearchResultModel>().Where(predicate).FacetOn(x => x[“ProperyName”], 1).GetFacets();

The second parameter to FacetOn() method is optional, it’s a min count and if we provide the min count, it means it’s going to return facets that is greater then equal >= to the value which has been set there.

Complete example:

using (IProviderSearchContext context = selectedIndex.CreateSearchContext())
{

var searchResults = context.GetQueryable<SearchResultItem>().Where(predicate).FacetOn(x => x[“ProperyName”], 1).GetResults();

// To check if we have any facet categories exists or not…
if (searchResults.Facets != null && searchResults.Facets.Categories.Any())

{

// Get all the facet categories…

// get facet category values and fetch facet name and aggregate count for each

// var facetName=facet.Name;

//  var facetCount= facet.AggregateCount;

}

}

If we want to facet based on multiple fields, we can just do it with adding chain of method calls and we should be all set to go.

context.GetQueryable<SearchResultItem>().Where(predicate).FacetOn(x => x[“Propery1Name”], 1).FacetOn(x => x[“Propery2Name”], 1).GetFacets();

Facets with tokenized fields:

Default field type in SOLR is tokenized which means it will split the string value in your index, and if the facet field value has space on it, it will be considered as two facets, as a workaround we should create a new computed untokenized index field and use that field instead.

Please see the below page for more details:

Sitecore Drop List Faceting Phrase Space Issue with Solr Search

Hope this helps.

Happy learning  and wish you all a very happy New Year 2018 🙂

Perform basic search with Sitecore

In this blog post I’ll be doing a introduction of the ContentSearch API found in Sitecore followed with a basic search example.
There are several articles which are available, but i will show a very simple working example of it.

Sitecore+Search

ContentSearch API:

ContentSearch API acts like an abstraction over the low level details of search technologies like Lucene or Solr. Sitecore provides an API that can be used to work with Lucene or SOLR, there might be some changes between the two, but those will be just configuration changes.

Same code can be leveraged for Lucene or SOLR, this also helps and provides flexibility during Sitecore upgrade or switching the search providers, you will end up making configuration changes to match the version and you will be all set.

It depends on the business requirements what search provider best fits your needs, there is official documentation provided by Sitecore on Lucene Or SOLR- https://doc.sitecore.net/sitecore_experience_platform/setting_up_and_maintaining/search_and_indexing/indexing/using_solr_or_lucene

Sample Search:

Here are the steps that are required to perform a simple search.

  1. Get the search index you want to use.
  2. Get the search context (which is also known as opening the connection) and
  3. Use the search context and perform queries.

Get the search index you want to use:

We need to get the index that we are going to use in the application, it can be out of the box indexes or custom indexes that we created, some of the indexes that can be referred are as follows:

  • sitecore_master_index
  • sitecore_web_index
  • sitecore_product_index (custom index)

We need to call GetIndex() method of ContentSearchManager class, which returns ISearchIndex instance.

ISearchIndex selectedIndex = ContentSearchManager.GetIndex(“sitecore_master_index”);

Once we have the index we can get other index details out of it, and can also perform operations like rebuilding of the index if required.

Get the search context:

This is more of opening a connection to search index, once we have the index available, next step is to create search context which allows us to perform search queries and operations against the selected index.
We create the search context using CreateSearchContext() method.

using (IProviderSearchContext context = selectedIndex.CreateSearchContext())
{

}

The search context is wrapped in using statement, so that it can be disposed when we are done performing the queries.

Perform queries:

Once we have the search context, it can be used to perform queries,
By using GetQueryable<T>() we can define our LINQ statements for filtering and getting the results.

using (IProviderSearchContext context = selectedIndex.CreateSearchContext())
{
var searchResults = context.GetQueryable<SearchResultItem>().Where(x => x.Content.Contains(“hello”));
}

By default the API will map to the SearchResultItem class for the result

This is a very basic example where we covered how get the index for search, create the context so that queries can be performed and finally using the context to perform the queries.

I hope this helps someone who is writing it’s first search code in Sitecore.

Happy learning 🙂

Please let me know your thoughts and feedback.

Sitecore Developer License-60 days free trial

Are you obsessed with Sitecore? but don’t have the playground to get started?

Don’t worry! Sitecore has made this easy for you now!!

How??

Sitecore has come up with Developer Trial Program which gives you a 60-day trial license..

So, what you are waiting for?, go ahead and request for it now and learn about:

  1. Working with Sitecore APIs and the Helix framework.
  2. Sitecore development recommended practices and
  3. Implementation and extensibility of the Sitecore platform.

For more details on how to get started, please visit:

https://www.sitecore.net/getting-started/implementation/developing-on-sitecore

Welcome to the Sitecore world!

developing-with-sitecore

Return null or String.Empty for Computed fields in Sitecore

It is quite obvious that we have to create computed fields in Sitecore, to process some of the information well before it get indexed, and not processing it while requesting for the data.

ankit-sitecore-download

There are chances when you don’t find any value to be added to you computed field, in those cases we can return either null or String.Empty().

Returning null basically tells that there is nothing to be indexed, and it won’t take any space in your index, but when we return string.Empty() , it actually creates an entry in index with no value.

Returning String.Empty() is helpful when you want to validate something based on empty string, but most of the case it is not worth.

Also, consider a case when you are dealing with several thousands Sitecore items, and if you are going to return String.Empty() for few thousands also, it will just get indexed that takes up space in you index.

We should carefully think about this, if there is a need to return String.Empty() we should do the same, but if not we should always try to return null.

Hope this helps someone.

Happy learning 🙂

Introduction to Sitecore Patching

There are several instances when you make updates to your Sitecore.config file, changes can include:

  • Adding new pipelines and processors for any custom feature implementation.
  • Updating/overriding the default values for some of the setting values like cache sizes and etc.
  • Adding new Sitedefination for your Sitecore instances.

So, to make any of the updates mentioned above, we have to perform following task(s):

  • Code changes (class file updates) and/or
  • Configuration file(s) changes (this is to make sure we register the changes in Sitecore)

Once you are done with you class and config changes, we need to register the changes in Sitecore, this is required so that Sitecore can identify the changes you made, and the functionality works as expected.

There are two approaches for registering the custom updates in Sitecore:

  1. By adding/updating the config changes directly in Sitecore.config file (not recommended)  or
  2. Creating a patch file (with extension .config)  which includes all the changes required, and placing file under App_Config/Include folder, we can create separate sub folders as well.

 

ankit-sitecore-download

Both the approaches works fine as expected, but there is an issue with approach 1.

How would you handle the updates in Sitecore.config file when you are planning for an upgrade later?, provided that you made several changes to Sitecore.config file, it may results issues after the upgrade.(think about it carefully before making changes directly to default Sitecore.config file)

How about if we think about creating a patch file, and putting all our changes there?, and this works well even if you are going for an upgrade at later stage, as you are not adding/updating anything on default Sitecore.config file directly, all the custom changes are coming as part of your patch file(s), This also helps in easy maintenance and troubleshooting.

Patch files are merged with Sitecore.config in alphabetical order. This means configuration in a patch file named a.config will appear before configuration in a patch file named b.config.

If the same configuration is found in multiple patch files, the configuration from the last patch file processed is the configuration that is used.

We can create as many patch files as we want, it all depends on the feature/requirement(s) and the way you want to organize your configuration files in your solution.

For example – you can create separate patch file for any Import functionality we have in the system, and this includes all the settings that needs to be added for specific one, also, there can exists separate patch file which includes custom indexes if exists any?

Note: Patching only works on the Sitecore configuration section, no other file or section can be patched with this.

Place in solution where patch files are placed, i.e under “App_Config/Include” folder

/App_Config/Include/zCustom.config
/App_Config/Include/events/zCustomEvents.config
/App_Config/Include/etl/zCustomEtl.config

Sitecore patching can be used for following operation(s):

  1. Adding a new setting
  2. Deleting a setting
  3. Adding or updating an attribute.
  4. Inserting an element before a specific element.
  5. Inserting an element after a specific element.

Simple example of Sitecore Patching:

This will set the default database for your website to master, this helps in testing the application without publising changes to web db
(Make sure to revert it back once you are done- and never make this change in QA/Production)

Sitecore-patching

How to see the result after Patching?

Now, how we can see the file which includes all the patches which we have applied, there is no physical .config file which can be used, In order to see the final result, please use this URL

http://%5Byour-localhost-name%5D/sitecore/admin/ShowConfig.aspx

Sitecore patching is an important part of day to day development, and we should leverage this as much as possible, to make sure we can make the system more stable and maintainable.

You can learn more about Sitecore Patching here:

Thanks and let me know if you have any feedback/comments on the same.

Happy learning 🙂

Sitecore security practices

Security is one of the very important considerations for any website.Today I want to share on how to make sure we keep site’s security in mind while implementing the solution, security is equally important as your build.

change-password

Following are few points which contribute in website security:

  • Change the administrator password : 
    • Sitecore recommends that we create a new administrator account, with a unique name, and delete the out-of-the-box administrator account.
    • Before you deploy your Sitecore installation, you must change the administrator password to a strong password.
    • Changing the password prevents unauthorized users from using the default password to access the admin account.
  • Enforce a strong password policy:
    • Sitecore leverages the Microsoft ASP.NET Membership Provider as the out-of-the-box user management system.
    • Sitecore recommends that you change the password policies to one that works for your organization.
  • Separate Content management and Content delivery Servers:
    • We should setup Separate content management and delivery servers, and content management server shouldn’t be internet facing.
    • If you have to expose your content management environment to the internet, you must:
      • Use HTTPS to secure the content management server.
      • Consider using IP Filtering to allow only whitelisted clients to connect to the Content Management environment.
  • Protect the connectionstrings section in the web.config file:
    • Sitecore stores sensitive information in the web.config file in the <connectionStrings> section.
    • You should encrypt the <connectionStrings> section to prevent this information from being exposed if the web.config file is accessed without authorization.
    • The Microsoft ASP.NET IIS Registration Tool (aspnet_regiis.exe) can be used to encrypt this section.
  • Separate Database server:
    • The CMS and database should be in two different servers.
  • Security rights on content item(s):
    • We should make sure that security rights has been configured for users and more specifically on roles, which users will be a part of.
    • Setting security rights on the  roles level helps administrators to change the configuration, if user moves to a different department, which all together has a different role.
  • Anonymous access to /data and /indexes folder:
    • We should make sure that data/indexes folder are not accessible to anonymous users(This prevents unwanted access to files), and it should be outside of website folder.

These are few of the things which we should take care while implementing/deploying Sitecore solution, this helps us in dealing with hacks and security breaches to some extent.

References: https://doc.sitecore.net/sitecore_experience_platform/setting_up_and_maintaining/security_hardening/security_considerations

Happy learning 🙂

 

 

 

Sitecore items mass delete through serialization

In one of the Sitecore application i worked, we had to sync large amount of data from XML, XML had several thousands of records, there was also a business rule in place which used to check certain conditions/fields before it can be inserted as item in Sitecore.

We performed several tests in local environment, before that utility can be executed in QA and other high end environment, but in this process, we have to go back and delete all existing imported items several times.

This was a time consuming process, as deleting several thousand items in Sitecore, can make your Sitecore instance slow, so, we used Sitecore Serialization to delete the items in bulk.

serialize

The Sitecore serialization functionality is designed to help teams of developers that
work on the same Sitecore solution to synchronize database changes between their
individual development environments, but is also valuable when a single developer
works on a solution.

Serialization allows you to serialize an entire Sitecore database or a series of items in
a database to text files. You can then use these text files to transfer this database or
series of items to another database or Sitecore solution.

This is particularly helpful when we use Sitecore Item buckets to structure all our content items.

Serialization option can be enabled from “Developer” ribbon.

sitecore-developer

In this example, I have created a folder called “Generic Items” and added few items under it.

serialize-s1

Follow the following steps to bulk delete the items:

  • Select the folder whose child items you want to delete, in this case, it’s “Generic Items” folder.
  • In next step, from “Developer” ribbon, click on “Serialize tree” link, this will serialize selected item and child items.
  • Serialization process will start and, it will create .item file for Generic Items folder and all child items under it.
  • Sitecore will store the .item files in data\serialization folder- in my case it’s Data\serialization\master\sitecore\content\Helix\Home\Test Eventsserialize-s2
  • Let’s assume we want to delete all items of “Generic Items” folder, delete the .item files from file system.
  • Once .items files are deleted, go back to Sitecore and from Developer ribbon click on “Revert tree” link.
  • Sitecore will start synching your items back from file system.Serialization-Sync
  • Once the process end, refresh your “Generic Items” folder, and you won’t find any child items there.
  • Sitecore serialization can delete several thousand of items in just few mins, which is way faster then manually deleting the items, which affects performance as well.

This can reduce your development and testing time, when working with large amount of data.

Please let me know if you have any questions, or want to share thoughts around this.

Happy learning 🙂

 

Reading and writing items using Sitecore powershell extensions

Sitecore Powershell Extension is a great tool/module developed by Adam Najmanowicz and Michael West that provides a command line and scripting environment for automating tasks.

In my previous blog post on Sitecore Powershell extensions, we learned very basics of this great module, like it’s introduction, how to install this module, and it’s features.

I would like to take another step in continuation of previous blog post, and like to show some features which can be leveraged out of it.

Retrieve Sitecore Item

We can fetch Sitecore Item based on ID or Path:

If we know the Sitecore item ID, it can be retrieved in following way:

PS-ID

We have to make sure that we are adding the context for database, in this case I have added “master

If we know the Sitecore item path, it can be retrieved in following way:

PS-Path

Retrieve Items from all languages and versions

We just need to pass language and version parameter, if we want items  based on specific language or version, we can specify that language and version as parameter values, instead of passing * to it.

PS-Item-language-version

Retrieve child Items

We can get all child items based on Sitecore path, this is how it can be used:

PS-ChildItems

If you want to retrieve all descendants from the given path, we can add recurse parameter, please see following for ref:

PS-ChildItems-recurse

Bulk Updates

There can be scenarios, where certain field(s) are not updated or empty for some reasons, and now you want to update that specific field for all the items, this is now not so easy, as you have several hundreds of items, but,there is an easy way to make this bulk update using powershell extensions.

PS-Bulkupdates

In the above example- we are trying to filter all the child items under /content/helix/home node where “Browser Title” field is empty, once we have a list of all items, we are iterating over all such items and updating the field with the “Display Name” value of the item.

Bulk updates for “Alt” text

Another very valid scenario for bulk updates can be updating all the Image items where “Alt” text is missing, following can be used to update all such Image items:

PS-Bulkupdates-Images

In the above example- we have used Sitecore query to get all the items based on template name “Image” and then finding such items which has missing “Alt” text, once we have a list we just updated the “Alt” text with item display name value, and then it can be updated by content authors to put something more specific, if required.

I strongly encourage all Sitecore developers to start using this module, and see how this can be leveraged into your solution, this is for sure helping and going to help everyone a lot.

I will continue sharing my thoughts and experiences on this topic, please let me know if you have any questions.

References:

http://blog.najmanowicz.com/sitecore-powershell-console/

https://michaellwest.blogspot.in/

Happy learning 🙂