Sitecore MVC – Bundling and Optimization

Hi everyone,

Some time before I had posted a stackoverflow question on how we can implement optimization in the blogs without using Global.asax file. After doing some research and discussion with Peter Prochazka, I am quickly writing a post on how I implemented Bundling and optimize them in my Sitecore MVC project.

All the projects will have multiple javascripts and css files so that we can maintain the readability of the code. But it also degrades the performance with the increase in load time of pages. As per definition from Microsoft : Bundling and minification improves load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript.).

So lets get into how we can implement bundling and optimize those bundled js or css for debugging purposes.

  1. Add Microsoft ASP.NET Web Optimization Framework to your solution from nuget packages. You might need to install dependency packages (Microsoft.Web.Infrastructure, WebGrease, Antlr, Newtonsoft.Json). So while installing these, make sure that it does not overwrite the same Sitecore dlls (because versions differ) and there is a possibility for you to get NewtonSoft Json dependency error.
  2. Create a folder App_Start and a BundleConfig.cs file which will have the following code logicBundleconfig
  3. Now here is the challenge. Sitecore ships with a standard Global.asax file and a lot of Sitecore developers choose to make changes directly in this to hook into application and session level events. But I prefer not to use the Global.asax file to Register the bundles, instead we can use Sitecore pipelines. The details about the Sitecore pipelines that can be used instead of the Global.asax event handlers are provided in https://laubplusco.net/global-asax-sitecore-pipelines/.
  4. So I created an initialize pipeline and injected the BundleConfig which was created earlierBudleconfigpipeline
  5. In web.config set an ignore url prefix for your bundle so that Sitecore won’t try to resolve the URL to the bundle. Update setting IgnoreUrlPrefixes according to your bundle name. I have added “/bundles” in my IgnoreURlPrefixes
  6. Render the css and js as follows in the layout fileLayout.PNG
  7. So now the js and css files are now bundled and you can see them in your website source code as followsBundled output
  8. Next what if you need to optimize those bundles. You can do it in different ways :
    As Peter Prochazka had suggested to me, creating a settings item and calling it from the Bundle Config. But here the problem is every time you make a change to the config, it need to have Sitecore restarted again and again.
    So again I chose to inject using pipelines. Also the optimization is usually done from the Application_Start method of Global asax. So as we chose to use pipelines, we use the PreprocessRequest/HttpRequestBegin of the Sitecore pipelines. And here i chose to add in the end of the preprocessrequest pipeline
    Now what if you need to optimize the bundles using a query string? (You can find the example in https://www.bugdebugzone.com/2015/07/bundling-and-minification-in-sitecore.html
  9. For this you can create a class which inherits from PreprocessRequestProcessor and write the code logic for Optimization and then add the class to the pipeline as follows :optimizationcode.png
  10. Then adding it into the preprocessrequestoptimizationconfig.png
  11. We can add the same using HttpRequestBegin also, but when I created it what I noticed was, when we are adding the processor to the end of the HttpRequest pipeline, it is not getting implemented as expected. The optimization is not happening. Then i tried to put it on top of the HttpRequestBegin pipeline and it works. But since I had my confusions, I preferred to implement the same at the end of preprocessrequest pipeline
  12. Now if you browse your URL with ?debug=true, for example, if the URL is http://www.example.local?debug=true, then you can see the following output in the source  optimizedoutput

And there it is!!! The scripts are de-optimized so that you can debug it in your website.

This was just my method for implementing Bundling and Optimization in your Sitecore MVC project. There are many other methods also without using pipelines and just using Global.asax, without optimizing etc.

Feel free to share your thoughts on this.

Till then Bye. Happy Sitecoring !!! 🙂

MODIFYING FIELD VALUE – SHARED, VERSIONED – DATABASE GET CORRUPTED

Hi everyone,

This time I am coming up with a small but major issue which troubled us for long time.

Here is the brief description of the issue :

When our Content Authors were editing an item (Example : Country) and they were modifying its address field value. Suddenly the authors reported saying the item is not reflecting in the live website even after they published, republished etc.
We thought the issue might be with the publishing not running as expected or the cache not getting cleared after publishing.
But those were not the issue, We tried many methods, clearing cache, publishing again and again, deleting the item and creating new item and publishing , still we could not find out what caused the issue.

Then we came across a parameter that was changed recently for the item in the template. In the template, the field for address was actually versioned at first, and then it was made to shared and then for some purpose again the field was made to versioned.

shared1                  Versioned

Now the field is finally made to be Versioned (unchecking the shared checkbox means the value is not shared)

So we executed the following query in both the dbo.SharedFields and dbo.VersionedFields tables in the master database.

SELECT * FROM [dbo].[SharedFields] where ItemId = ‘xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx’ and FieldId = ‘yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy’
SELECT * FROM [dbo].[VersionedFields] where ItemId = ‘xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx’ and FieldId = ‘yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy’

Here xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx gives the Item ID which you are facing the issue and yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy gives the ID of the field (you can get it from the template) which has the issue.

Surprisingly we could see the same result in both the tables dbo.SharedFields and dbo.VersionedFields. The expected result should be the result should occur only in the dbo.VersionedFields table only.

So after investigating, we could see from the following article : https://kb.sitecore.net/articles/045873

When changing the value of the Shared or Unversioned property of a particular field, every item based on the modified template is updated and the corresponding field values are moved to the appropriate data table in the Sitecore database – SharedFields, UnversionedFields, or VersionedFields.

However, in situations when the field sharing properties on a template are changed as part of a package installation, related items may not be updated properly, and corresponding field values may be located in different Sitecore database tables.

In this case, an author may experience various issues when working with items.

For example, field values may not be changed as expected upon save operation, or the data may not be published in an expected manner.

In the article they also have mentioned a fix, which installs a dll and a config and through which they run a process from FixFieldSharing.aspx.
But here the problem is like it will run for entire database and takes too much time. Also as they have mentioned, it may cause data loss in the items affected by changing field sharing properties.

So we had the issue only in one or two items and fields, so we did not run the fix suggested by Sitecore. Instead went to the template and changed the value to shared once (waited for some time so that the Sitecore background process finishes) and then again changed back to versioned (and waited till that operation finished).
Actually the issue occurs because, whenever we changed the field value to shared or versioned, Sitecore runs a background job which might have not executed properly which caused the data to be corrupted.

Hurray !!!. We have fixed that big issue which troubled us for almost a month in within 1 hour. Then we published the item (also with the templates as it had changed the field values) and then it was successfully published.

Next time I will meet you with different post. Until then Bye Bye!!!

Follow me on Twitter and Linkedin for more Sitecore related updates and shares (About)

Happy Sitecoring!

Campaign Creator – Issue while creating and loading campaigns

Hi everyone,

Today I am here to share an issue which we faced while creating and loading campaigns.

We are using Sitecore 8.2 Update 3 instance and we started to use the Campaign Creator option, very recently and that’s when we noticed about these issues.

Here is the description of the issue :

When a user is trying to create a campaign from Campaign creator, we are getting the following error.
campaign 1

But the campaigns can be viewed from the Marketing Control panel.
campaign 2

When the campaign creator dashboard is loading in the startup, it must display the list of campaigns that are created and deployed. But it is showing ”No campaign activities found”.
campaign 3

In the logs, the following error was shown :

Exception System.ArgumentException: the definition was not found: {3288EF08-CC53-45E6-9804-29DD1B397695}
Parameter name: definitionId
at Sitecore.Diagnostics.Assert.ArgumentCondition(Boolean condition, String argumentName, String message)
at Sitecore.Marketing.Definitions.DefinitionManagerBase`1.<>c__DisplayClass5`1.<Activate>b__0()
at Sitecore.Marketing.Core.IgnoreRecursiveCalls.Run(ID id, Action action)
at Sitecore.Marketing.Definitions.DefinitionManagerBase`1.Activate[TRecord](ID definitionId, IDefinitionRepository`1 repository, Func`2 toDefinition)
at Sitecore.Marketing.Definitions.Campaigns.CampaignDefinitionManager.ActivateAsync(ID definitionId)
at Sitecore.Marketing.Definitions.DefinitionManagerBase`1.Save[TRecord](TDefinition definition, Boolean activate, IDefinitionRepository`1 repository, Action`2 setCustomFields)
at Sitecore.Marketing.Definitions.Campaigns.CampaignDefinitionManager.SaveAsync(ICampaignActivityDefinition definition, Boolean activate)
at Sitecore.Marketing.Definitions.DefinitionManagerBase`1.Save(TDefinition definition, Boolean activate)
at Sitecore.Marketing.Campaigns.Services.Data.CampaignRepository.Add(CampaignEntity entity)
at Sitecore.Services.Infrastructure.Services.EntityServiceBase`1.CreateEntity(T entity)
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
— End of stack trace from previous location where exception was thrown —
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()

We contacted Sitecore support for the issue, and after some analysis they got back to us with the following findings :

The issue was related to the fact that we were using Publishing Service module (2.0) in our instance. And also it is specified in the installation guide of the Sitecore Publishing Service that, the “content availability” feature must be turned off in CM server and should be turned on only on CD.

https://dev.sitecore.net/~/media/6A0A9E06FBD549059473643F4ADE19DB.ashx

The “Sitecore.Publishing.Service.Delivery.ContentSearch.ApplyGlobalAvailabilityLinqFilters, Sitecore.Publishing.Service.Delivery” processor from the “Sitecore.Publishing.Service.ContentAvailability.config” file breaks search on CM server and causes Campaign Creator to show empty dashboard page. Also the issue with the saving new campaign activity, is also related to the “content availability” feature and is caused by “filterItems” and “enableWorkflow” settings enabled in Sitecore.Publishing.Service.ContentAvailability.config configuration file.

We had enabled this feature that the CM server also should act as CD server for the content availablity for some purpose.

Campaign_Contentavailability

But as Sitecore suggested we disabled the “content availability” feature from the CM servers and BINGO!!! Both the issues which we mentioned were solved. Now we were able to create new campaigns and also see them in the dashboard.
But now, when the campaign dashboard was loading, it was showing only the newly created campaigns. But there were some default campaigns (Ex : Social) that are present in Sitecore and also some campaigns that are already created through our Marketing Control Panel under a folder , which were not getting displayed in the Campaign list. For solving this issue we have performed a rebuild of “sitecore_marketingdefinitions_master” and now all the campaigns are shown including the default ones.

rebuild marketing definitions

This was an implementation issue which occurred from our side, where we did not disable the “content availability” feature from the CM servers. I guess many other people also usually faces these kind of implementing issues and the main aim of this post was to notify everyone to implement the features/modules in Sitecore as per the installation guide and make sure that you disable/enable the configs listed as per the installation guide/Config Enable Disable Excel spreadsheet in both CM and CD servers.

Hope you enjoyed this post.

Will meet you all soom with a new issue or implementation.

Till then Bye. Happy Sitecoring!!!

Querying Sitecore Forms DB – Sitecore xDB Mongo Database

Hi all,

Welcome to my post on Querying Sitecore Forms collection in the xDB – Mongo Database.

MongoDB collection database is an important part of a Sitecore Experience Database (xDB) that allows the companies/organizations to collect all of their customer interactions/data from all channels that allows marketers to better optimize the customer experience in real-time. In xDB, the collection database acts as a central repository for storing contact, device, interaction, history and automation data.

Suppose we have created a form using WFFM and a user is submitting the form. If the form is submitted successfully, the Form Reports can be accessed from the “Form Reports” tab, when we click on a form in Sitecore. The same data is also saved in the MongoDB collection named “FormData” under the analytics database.

Screenshot 1

We all might face an issue with the the form that the email messages received is not same as the data shown in the Form Reports. For example, if there is an event form, and the event coordinator gets 50 emails as registered and when they check the form reports it shows only 45. Unless we go to the database directly and check the data, we are not able to confirm the issue. Also if we need to confirm whether a particular email id value is saved in the database.

So we can check some examples on how to query the MongoDB database using 2 tools : Robo 3T and Studio 3T (both are tools provided by formerly used tool Robomongo)

You can download the tool from https://robomongo.org/

Robo3T is used just by the MongoDB enthusiasists, who are interested just in querying the database and playing around the data using differnt queries.
Studio 3T is used mainly by the professionals and it provides following advantages :
1. Fully featured IDE with embedded shell
2. Visual Query Builder
3. In-Place editing
4. IntelliShell with Auto-Completion
5. Query MongoDB with SQL
6. Export to / import from SQL DB
7. Export to csv

There are three encoding supported for Legacy UUID subtype 3:

Legacy Java Encoding, Legacy .NET Encoding, Legacy Python Encoding

By default, when we open a collection, it opens the Raw data without any encoding. For understanding and easy querying, we use .NET encoding. We can select .NET encoding (in Robo 3T) by Navigating to Options -> Legacy UUID Encoding -> Use .NET Encoding

Screenshot 2

Now i will get on to how we can query the FormData. For that first we need to take the ID of the form where the issue is getting reflected.

The item ID of the form which we have used is {8E08E97B-0D58-4988-87CE-F5D354ECFC30}. This is the same ID which we use with querying with the NUUID.

1. To get all the records from the Form Data collection:

db.getCollection('FormData').find({"FormID":NUUID("8e08e97b-0d58-4988-87ce-f5d354ecfc30")})

This query gives the following results :

Screenshot 3

2. To get a particular value of any field of the form – Suppose i have a field called First Name and the value i have given is “Test”. Here is how we query it :

db.getCollection('FormData').find({"FormID":NUUID("8e08e97b-0d58-4988-87ce-f5d354ecfc30"),"Fields.Value":"Test"})

Screenshot 4

But here we get three different results which has the same Name : “Test”

3. Now lets choose an unique identifier (Email ID) so that i get a particular formdata which has FirstName as “Test” and Email ID as “test@test.com” . Here we get this using “AND” query.

db.getCollection('FormData').find({$and : [ {"FormID":NUUID("8e08e97b-0d58-4988-87ce-f5d354ecfc30")},{"Fields.Value":"test@test.com"}, {"Fields.Value":"Test"}]})

Screenshot 5

Here is the result when there is requirement to find whether the user with name “Test” and email ID “test@test.com” has submitted the form.

These were just very few examples on how to get forms data via querying through MongoDB. In similar way we can also query Interactions, Contact collections also to get more details on the Visitor data (Page count, Time, Browser, Site Name etc)
More details on the querying is provided in the series of blogs written by Brijesh Patel : https://horizontalintegration.blog/2017/01/22/query-sitecore-xdb-mongodatabases-part-1/

In my next blog, I will explain on how to query using Studio 3T, using Visual Query Builder, Importing the data to csv or excel. If you have any queries or doubts, please feel free to contact me.

Till then Bye Bye ! Happy Querying

Sitecore Powershell Extensions- Making work easier – Part 1

Hi all,

This time I am going to share a few powershell scripts that can be used for various requirements and reduce a big amount of time.

Before going on to those, first I would like to give some introduction about how I started scripting using SPE and how it helped me to proceed further.

So this was before 2 years, when I was working in a project and it was using Zen Garden, The first ever Sitecore Development Accelerator (Now Sitecore has stopped supporting the same and is discontinued) which had a similar properties as of Sitecore Experience Accelarator (SXA), which was used to created Multi-Sites using Tenants, Markets etc. So it was told that when we just right click on an item and select “Create a Tenant”, it showed some dialog boxes asking for templates, site name , language etc. and when given the necessary details, the site node was created immediately. There I was curious on how this is happening and after some research and debugging, I came to know that these all could be possible only because of Sitecore Powershell Extensions. There started my first step to SPE.

The Sitecore PowerShell module is especially handy when you’ve been tasked with applying changes to items in bulk. Then I started working on various scripts for different tasks that requires time saving and easy to be automated and was happy to know that it was working and still I am continuing my PowerShell scripting journey.

There are a large number of blogs for studying and implementing SPE. Of those i am suggesting following blogs to go through the basics of the same

https://marketplace.sitecore.net/en/Modules/Sitecore_PowerShell_console.aspx

https://doc.sitecorepowershell.com/

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

http://sitecore-masters.com/en/starting-with-sitecore-powershell/

Here I would like to share some scripts that can be handy on some occasions. Some of these scripts are also available in other websites also and these scripts might not be the only solution for the tasks but you could also try these scripts also as part of your investigation.

This blog post is heavily inspired from the posts and help provided by Adam Najmanowicz and Michael West on Sitecore PowerShell Extensions, through their blogs, Slack, Stack overflow etc. I have seen both of them working and helping really a lot for the people who are facing any difficulties in implementing the same. For joining the group which helps you to interact with Adam Najmanowicz and Michael West and more Powershell experts, please join the Sitecore Slack channel.

Now lets move on to the scripts one by one.

1. To change the template of all the child items

$path="Item path here"
$item = Get-ChildItem -path "$($path)"
$newTemplate = [Sitecore.Configuration.Factory]::GetDatabase("master").Templates["Template path here"];
$item | ForEach-Object {
    if($_.TemplateName -eq "TemplateName")
    {
        $_.ChangeTemplate($newTemplate)
    }
}
$item

2. To delete the sub item of all the child items of main item

$path="item path here"
$item = Get-ChildItem -path "$($path)" -Recurse
$item | ForEach-Object {
    if($_.TemplateName -eq "TemplateName")
    {
        Get-ChildItem $_.ProviderPath | Remove-Item
    }
}

3. Export the list of item under a particular item excluding a particular template to csv

$path="item path here"
$item = Get-ChildItem -path "$($path)" -Recurse | Where-Object { $_.TemplateName -ne "Template Name of items to be exported" }
 
$item | Show-ListView -Property `
    @{ Name="Item Name"; Expression={$_.DisplayName}}, # property renamed
    @{ Name="Item path"; Expression={$_.FullPath}}

4. To create items under an item from csv

$itempath = "item path here"
$templatePath = "template path here"
$InputcsvFile = Show-Input "Input file path"
$csv = Import-CSV $InputcsvFile -delimiter ","
 
$bulk = New-Object "Sitecore.Data.BulkUpdateContext"
try
{
	foreach($record in $csv)
	{
		$item = New-Item -Path $itempath -Name $record.ItemName -ItemType $templatePath
		$item.Editing.BeginEdit()
    		$item["__Display name"] = $record.ItemName 
   		$item.Editing.EndEdit()
		Write-Host "Item created: " $record.ItemName
	}
}
finally
{
 $bulk.Dispose()
}

5. To get all the links starting with ‘a’ tag in the items (from a richtext editor or single line text)

$itempath = "item path here"
$allItems = Get-ChildItem -Path $itempath -Recurse -language * -version *
$links = @() 
$allItems | ForEach-Object {
    foreach($field in $_.Fields) {
    # Only look within Single-line and Rich Text fields     
    if($field.Type -eq "Single-Line Text" -or $field.Type -eq "Rich Text") {
            $html = $field.Value
            $htmlDocument = New-Object -TypeName HtmlAgilityPack.HtmlDocument
            $htmlDocument.LoadHtml($html)
            foreach($x in $htmlDocument.DocumentNode.SelectNodes("//a")) {                
               $links +=@{Id=&{$_.id.toString()};Path=&{$_.paths.fullpath};Language=&{$_.language};Version=&{$_.version};Link=&{$x.OuterHtml}}                
            }
        }
    }
}
$links | Show-Listview -Prop Id,Path,Language,Version,Link

These were a few scripts which i think will be useful for someone who is curious to learn powershell and use them for reducing the amount of time in their projects.

Please feel free to contact me if any of you face any issues or having doubts in using the scripts.

I will continue with some new scripts in my upcoming blogs.
Till then, See you all. Happy Scripting …

“Forged request detected” exception – submitting WFFM form after period of activity

Hi all,

Today i am planning to share an issue which we faced in our webforms. I am using WFFM 8.2 Update 3.
The issue can be described as follows :

When a user starts filling a form which has more fields, he/she is filling some fields, and they are waiting for 25-30 mins for filling the rest of the fields, and clicks submit, the form will not get submitted and it displays an errorTechnical dificulty errorAt first we were thinking this issue might be because of the Mail service was not working, but when started investigating in the logs, we could not find any log error which corresponds to mail service.

But at the same time we received following in the logs :

5728 12:57:20 INFO AUDIT (extranet\Anonymous): Upload: example.pdf
5728 12:57:20 INFO Media Item has been uploaded to database: /{11111111-1111-1111-1111-111111111111}/{3D6658D8-A0BF-4E75-B3E2-D050FABCF4E1}/{25D39E8F-719B-4C95-9F43-A106C2C0EC54}/{338F9B9A-75A5-4304-A34B-A1F2F9B5F01C}/{CAA45999-AC9B-4F6F-89C6-B9F949030CDD}/{82D54811-0DA9-4CA8-B4A2-744C47321AD2}/example.pdf
5728 12:57:20 INFO AUDIT (extranet\Anonymous): [WFFM] Form {7100FF18-8969-48B0-833B-49C035C8A19C} is saving to db
5580 13:01:26 WARN [WFFM] Web Forms for Marketers: an exception: WFFM: Forged request detected! has occured while trying to execute an action.
5580 13:01:26 ERROR WFFM: Forged request detected!

In our further analysis we could find that this issue occurs when the session is expired.
Expiration is controlled by timeout value of the session state configuration in the web.config:

As described in the following blogspot : https://sitecoredoc.wordpress.com/2017/01/04/sitecore-wffm-v8-1-2-form-times-out-after-a-period-of-inactivity/, This is because of an anticsrf and the logic is simple. There is some value (guid) stored in the session and another value is on the form (hidden input control with “_anticsrf” postfix in id and name). If at the submission these values are different or session is null, this message about forged request will be logged and the submission will be aborted.
In my case, the session is expired in 20 minutes and session value at submission is null.

Possible workarounds :

1. Increase session timeout to 60 minutes.

2. There is a Sitecore support reference number for this : 456464, Please mention your WFFM version and this reference number to the Sitecore support.

3. We can temporarily bypass the forged request problem by adding some code logic for the same.
Create a class named ForgedRequestBypass.cs with following code

using System;
using Sitecore.Diagnostics;
using Sitecore.Form.Web.UI.Controls;

namespace YourNamespace
{
    /// <summary>
    /// This class is intended to be a temporary bypass for the forged request problem with the WFFM module.
    /// It's an implementation of #2 listed at https://community.sitecore.net/developers/f/10/t/3822.
    /// </summary>
    public class ForgedRequestBypass : SitecoreSimpleFormAscx
    {
        protected override void OnClick(object sender, EventArgs e)
        {
            Assert.ArgumentNotNull(sender, "sender");

            if (bool.Parse(Sitecore.Configuration.Settings.GetSetting("WFM.EnableAntiCsrf", "true")))
            {
                base.OnClick(sender, e);
            }
            else
            {
                object sessionValue = Sitecore.Form.Core.Utility.SessionUtil.GetSessionValue<object>(this.AntiCsrf.ID);

                if (sessionValue == null || !(sessionValue.ToString() == this.AntiCsrf.Value))
                {
                    Sitecore.Form.Core.Utility.SessionUtil.SetSessionValue(this.AntiCsrf.ID, this.AntiCsrf.Value);
                    Log.Info("Successfully Bypass forged request - Session value successfully stored",this);
                }

                base.OnClick(sender, e);
            }
        }
    }
}

Update the Control directive’s inherits attribute in the \Website\sitecore modules\Web\Web Forms for Marketers\control\SitecoreSimpleFormAscx.ascx file:

<%@ Control Language=”C#” AutoEventWireup=”true” CodeBehind=”SitecoreSimpleFormAscx.ascx.cs” Inherits=”YourNamespace.ForgedRequestBypass” %>

Also we need to create a patch for Sitecore.Forms.config and add the following setting to that

<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/">
  <sitecore>
<!-- SETTING VALUE FOR ANTICSRF COOKIE-->
      <setting name="WFM.EnableAntiCsrf" value="false" /> 
    </settings>
  </sitecore>
</configuration>

After applying this fix, when you try to submit the same form even after the session is timed out, the form will be submitted successfully and you can see the following message in the logs.

5000 11:28:06 INFO Successfully Bypass forged request – Session value successfully stored
5000 11:28:06 INFO AUDIT (extranet\Anonymous): [WFFM] Form {7100FF18-8969-48B0-833B-49C035C8A19C} is saving to db

How i tested the issue : I changed the session timeout to 1 minute and then tried to submit form after 2-3 minutes, so before i applied the fix, it showed the error and after applying the fix, the form was submitted successfully.

And Finally the issue was solved !!!

I guess everyone liked my post. If anyone faces such type of issue and requires help please feel free to contact me. You are also welcome for any suggestions on the above post.

Happy Sitecoring !!!

ISSUES FACED IN SITECORE PROJECT

Hello everyone,

This time I am sharing some issue that we have faced in our project and the solution we had provided.

#1 : Media Items are served with extensions .ashx instead of .jpg, .pdf etc
By default media items(.jpg, .pdf, .xls etc) will be rendered as .ashx.
This can be handled from Media.requestExtension setting in Sitecore.config. By Default the value is

1

By setting the value to blank, we can render media url with relevant extension. We used custom patch for the setting

2

#2 : Sitecore Hyperlink manager/Mail template editor not clickable/broken
a) One morning we faced an issue that when we select hyperlink manager, a link builder dialogue opens, and the bottom of this dialogue has two small square. They look like small versions of buttons, but content is not there and are not clickable.
b) Similarly when we open mail template editor, to send email message through WFFM, The mail template editor opens, but:
* The content field of the template is blank
* It’s not possible to click the HTML button
* No values can be selected from the field dropdown
* If you start resizing the window it goes completely haywire with weird alert boxes

We could find that both of these are related to single issue. Because in the Console we were getting errors related to ScriptResource.axd.

This can be handled using the IgnoreURLPrefixes setting in Sitecore.config, adding script resource.axd.

3

After that, everything started working fine
(These two are the issues which we faced, there can be some other issues also due to unavailabilty of ScriptResource.axd in IgnoreURLPrefixes)

#3 : We have observed that there are multiple failed connections sparks on the Azure PaaS SQL DB causing application unavailability issue which looks transient error.

When we reached to Microsoft about this issue with the Error log for SQL DB, they replied that Reconfigurations happened in the databases.
Reconfiguration (briefly)
Reconfigurations are a common part of SQL Azure databases. Due to high availability architecture of Azure, its database has three replicas.Every time we need to point your application to a secondary replica, send an exception to the application so you can handle the error and resubmit the request to the database. These disconnections may occur during maintenance of database, or due to some error in the system, updating, patching the operating system, etc. Adding a retry logic to your code should help resolve these errors.

Reconfigurations generally occurs within 5-30 seconds for no impact to be seen, but application must reconnect to the healthy copy of the database. With an appropriate retry logic this would be transparent as the application could automatically connect as soon as the database is available. Below is more information on the connection recommendations for Azure SQL DB as well as retry logic configurations and suggestions.

So we enabled the retryer logic in Sitecore config file

By default it will be

4We had modified it to

8

#4 : Sitecore Media Library is very slow
The Sitecore Media Library is extremely slow at loading. The initial load is ok, but unfolding a main folder can take several minutes.

Based on the sitecore recommendation from the below blog

https://kb.sitecore.net/articles/723979

Set the value of the Media.MediaLinkPrefix setting in the Sitecore.config to the alternative prefix:

6

Add the following line to the customHandlers section (make sure NOT to remove the existing one that is mapped to “~/media”):7

Now the Media Library is loading better compared to previous.

These are some of the issues we faced in our Sitecore project. These might not be the Only solution for the same kind of issue. If you face such kind of issue, you could try these fixes also as part of your investigation. Please feel free to contact me if you have similar kind of issue or any doubts or you have any other solution.