Surendra Sharma

Surendra Sharma

Search This Blog

Sunday, October 15, 2017

5 different ways of find and replace content in Sitecore

Find and Replace functionality in Sitecore
Find and Replace functionality in Sitecore


Find and replace technique is very useful for editors and developers when they want to change some or bulk of content in Sitecore instance. I am listing out 5 possible ways to do this operation in Sitecore.
 

1.Manual

Ofcourse even if you don’t know any other way, its always there. This is mostly a first approach for any non-technical user.

Advantage

·         You don’t need any tool for this.
·         Useful for less than 10 items

Disadvantage

·         As a human being, content editor can easily make a mistake with this approach
·         Don’t use this technique if changes are to be done in more than 10 items.

2 . Find and replace using Sitecore search


This is inbuilt and somewhat hidden functionality available in Sitecore which is pretty straight forward and very powerful. For this
1.    Select parent item under which we need to find some text
2.    Click on Search icon in right top section
3.    This should open search window
4.    Enter text to be search in box
5.    Click on search icon button. This should displayed searched items as a result.
6.    Click on “More Search Options” arrow in left side of search box.
7.    Select “Search Operations” which will displayed all operations that you can do with this search result.
8.    Select “Search and replace” option.
9.    Enter new text
10.  Click Ok.

Search and replace in Sitecore
Search and replace in Sitecore


That’s it. Your new text should be appeared in all the items that are part of find result.

Advatnage

·         Quick and default functionality available in Sitecore
·         No special tool required to run
·         One can filter result with additional search facets

Disadvantage

·         Sometimes this functionality not work even text is available in items. 

3. From database


Sometimes we want to demo existing projects to new client. At this time we want to assign new client company name and logo on all the places in existing Sitecore instance. For this kind of situation, one can use this database find and replace approach.

I already covered this approach in one of my article at http://www.sitecorelessons.com/2016/10/changing-data-from-sitecore-database.html

In short, you have to fire update stament in VersionedFields table as

Update VersionedFields set Value = 'www.sitecorelessons.com from Surendra Sharma' + Value where Id = '61C78797-DD31-41AB-976B-A6800F2E9403'

Clear the Sitecore cache and you will get the new data in Sitecore content tree.

Advantage

·         With single update statement, you can change the entire database.

Disadvantage

·         Require access of database
·         Only developers can used this approach. This is not for content editors
·         Find data and verify before updating
·         Can’t be rollback once you done the changes. [Can be used with combination of SQL transacations to roll back.]
·         Sitecore not recommended this approach as its very risky.

4.Code


As a developer, we can write a code to find the data and then replace it. Instead of writing in C# file, write code directly in “.aspx” file with server side tags to avoid code build. A sample code can be like given below which will find text in item’s all languages in all versions

<%@ page language="C#" autoeventwireup="true" %>


<%@ import namespace="System.IO" %>
<%@ import namespace="Sitecore.Data" %>
<%@ import namespace="Sitecore.Data.Items" %>
<%@ import namespace="Sitecore.Links" %>
<%@ import namespace="Sitecore.Globalization" %>
<%@ import namespace="System.Data.SqlClient" %>
<%@ import namespace="System.Data" %>
<%@ import namespace="Sitecore.Data.Fields" %>
<%@ import namespace="System.Text.RegularExpressions" %>
<%@ import namespace="System.Collections.Specialized" %>
<%@ import namespace="Sitecore.Data.Managers" %>
<%@ import namespace="Sitecore.Collections" %>
<%@ import namespace="Sitecore.SecurityModel" %>
<%@ import namespace="Sitecore.Data.Managers" %>


<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head2" runat="server">
<script runat="server">
StringBuilder log = new StringBuilder();

Sitecore.Data.Database db = null;

LanguageCollection languages = null;

protected void Page_Load(object sender, EventArgs e)
{

    db = Database.GetDatabase("master");

    languages = LanguageManager.GetLanguages(db);

    builderText.Text = GetJunkDataItem();
}


private string GetJunkDataItem()
{
    var objRootItem = db.GetItem("{AE4F3D24-5C19-4F0C-BD40-D8952F758F32}");

    //Get Home Item details
    WriteItemDetails(objRootItem);

    foreach (Item objChild in objRootItem.Children)
    {
        //Get Child of Home Item details
        WriteItemDetails(objChild);
        AddSubItem(objChild);
    }

    return log.ToString();
}

private void AddSubItem(Item child)
{
    foreach (Item objChildItem in child.Children)
    {
        WriteItemDetails(objChildItem);

        if (objChildItem.HasChildren)
        {
            AddSubItem(objChildItem);
        }
    }
}

private void WriteItemDetails(Item child)
{
    foreach (Language language in languages)
    {
        Item languageSpecificItem = db.GetItem(child.ID, language);
        if (languageSpecificItem != null && !languageSpecificItem.IsFallback && languageSpecificItem.Versions.Count > 0)
        {
            foreach (var versionItem in languageSpecificItem.Versions.GetVersions())
            {
                var searchFields = versionItem.Fields.Where(x => FieldTypeManager.GetField(x) is HtmlField
                && (x.Value.ToUpper().Contains("Oldtext"))).ToList();

                if (searchFields != null && searchFields.Count > 0)
                {
                    using (new Sitecore.SecurityModel.SecurityDisabler())
                    {
                        versionItem.Editing.BeginEdit();

                        foreach (var tempField in searchFields)
                        {
                            tempField.Value = tempField.Value.Replace("Oldtext", "Newtext");
                        }
                        versionItem.Editing.EndEdit();

                        log.Append(language.Name + ";" + languageSpecificItem.Version.Number + "--------<br/>");
                    }
                }
            }
        }
    }
}     
</script>
</head>
<body>

<form id="form2" runat="server">
        <asp:button id="Button1" visible="false" runat="server" text="Edit Blog Items" />
        <div>
            <asp:literal id="builderText" runat="server" />
            <asp:textbox id="builderText1" visible="false" runat="server" textmode="multiline" height="702px" width="1258px" />

        </div>
    </form>
</body>
</html>

Advantage

·         C# code is familiar to developer so its very easy to write this.

Disadvantage

·         Need to deploy the code or file on website environment
·         As URL may be publicly available, anybody can fire it which may corrupt data.  

5. Sitecore Powershell


You wondered if single command can do the find and replace work and that’s the magic of Sitecore Powershell. You can execute below script to find and replace in sitecore Powershell ISE

$old_content = "Oldcontent"
$new_content = "Newcontent";
get-childitem -recurse `
  | where-object {$_.Text -match $old_content} `
  | foreach-object {$_.Text = $_.Text.Replace($old_content, $new_content) }


Advantage

·         Whatever developers can do with C# code can be same done by Sitecore Powershell in one or fewer lines.
·         Easily create find text items report in well-format manner

Disadvantage

·         Need to install this module in Sitecore instance
·         Need to learn how to write and execute Powershell command.

I wish Powershell should be by default available in Sitecore installation.

Its feasible to comment out which is best way to find and replace approach as its entirely depend on situation and user skillset. But personally I like Sitecore Search-replace functionality and Powershell approach.

Let me know if you come across with any other way to find and replace content in Sitecore.

I hope you enjoy this Sitecore article. Stay tuned for more Sitecore related articles.

Till that happy Sitecoring :)

Please leave your comments or share this article if it’s useful for you.


No comments:

Post a Comment