Tuesday 9 February 2021

Sitecore - Check Media Item size on Upload

Hello Sitecore Developers,

We had a unique requirement from client where they want to limit the Upload size for Images and PDFs to 600 KB and 10 MB respectively.

This can be handled through a small setting in the sitecore.config where we can adjust the default value of the media items to be uploaded. If we change the value from 500MB to any other size (i.e. 1 MB, 2MB etc.) it won’t allow to upload the items more than the specified size limit.



<!-- MEDIA - MAX SIZE IN DATABASE

The maximum allowed size of media intended to be stored in a database (binary blob).

This value must be less than the ASP.NET httpRuntime.maxRequestLength setting.

Default value: 500MB

-->

<setting name="Media.MaxSizeInDatabase" value="500MB" />


Since we only want to make this change for the Images and PDFs this solution wouldn’t be feasible for us. Instead we need to build something custom.

We started looking into the Sitecore Kernel through reflector to find out the Pipeline/Processor responsible to check the size of media items.

The Pipeline which handles the Upload request for Media Items is Upload and the processor is Check Size. We decided to replace the processor with our custom processor.

As a best practice, created custom patch file.

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">

<sitecore>

<processors>

<uiUpload>

<processor mode="on" type="[YOUR_PROJECT_NAME].Pipelines.Upload.CheckImageandPdfSize, [YOUR_PROJECT_NAME]" patch:instead="processor[@type='Sitecore.Pipelines.Upload.CheckSize, Sitecore.Kernel']"></processor>

</uiUpload>

</processors>

</sitecore>

</configuration>

 

Custom Processor

public class CheckImageandPdfSize : UploadProcessor
    {
        public List<string> ValidExtensions { get; set; }
 
        public CheckImageandPdfSize()
        {
            ValidExtensions = new List<string> { ".jpg", ".jpeg", ".png", ".tiff", ".tif", ".gif" };
        }
 
        public void Process(UploadArgs args)
        {
            Assert.ArgumentNotNull((object)args, nameof(args));
 
            if (args.Destination == UploadDestination.File)
                return;
 
            foreach (string index in args.Files)
            {
                HttpPostedFile file = args.Files[index];
                if (!string.IsNullOrEmpty(file.FileName))
                {
                    bool isPDF = Path.GetExtension(file.FileName).Equals(".pdf", StringComparison.OrdinalIgnoreCase);
 
                    if (isPDF && (long)file.ContentLength > AllowedPDFSize)
                    {
                        string text = StringUtil.EscapeJavascriptString(file.FileName);
                        args.UiResponseHandlerEx.FileCannotBeUploaded(text, StringUtil.EscapeJavascriptString($"You must select a PDF file smaller than {(object)MainUtil.FormatSize(AllowedPDFSize)} in size."));
                        args.ErrorText = $"The file {(object)text} is too big to be uploaded. You must upload PDF file smaller than {(object)MainUtil.FormatSize(AllowedPDFSize)} in size.";
                        args.AbortPipeline();
                        break;
                    }
                    else if ((long)file.ContentLength > AllowedImageSize && ValidExtensions.Any(ext => ext.Equals(Path.GetExtension(file.FileName))))
                    {
                        string text = StringUtil.EscapeJavascriptString(file.FileName);
                        args.UiResponseHandlerEx.FileCannotBeUploaded(text, StringUtil.EscapeJavascriptString($"You must select an image smaller than {(object)MainUtil.FormatSize(AllowedImageSize)} in size with one of the following file extensions : .jpg, .png, .gif, .jpeg, .tif, .tiff "));
                        args.ErrorText = $"The file {(object)text} is too big to be uploaded. You must select an image smaller than {(object)MainUtil.FormatSize(AllowedImageSize)} in size with one of the following file extensions : .jpg, .png, .gif, .jpeg, .tif, .tiff.";
                        args.AbortPipeline();
                        break;
                    }
                }
            }
        }
 
        public static long AllowedImageSize
        {
            get
            {
                return Settings.GetLongSetting("Media.AllowedImageSize", 614400); //600 KB = 614400
            }
        }
        public static long AllowedPDFSize
        {
            get
            {
                return Settings.GetLongSetting("Media.AllowedPDFSize", 10485760); //10 MB = 10485760
            }
        }
    }

  

Now, when you try to upload a file using Media Library upload and if the size is more

than the specified limit it won’t allow to upload the file (i.e. image/PDF)

For Image,

 

 

 

 

 

 

For PDF,

 

 

 

 

 

 

This would also work when you try to upload the image or PDF using Upload Files(Advanced) and through sitecore field.



 

 


Saturday 22 June 2019

Sitecore 9.1 Experience Editor stopped working after code deployment


Hello Sitecore fellows,

As we are in a process of upgrading our version to Sitecore 9.1, we are facing new challenges as a part of the journey.

That said, a very good quote which says.

Enjoy the journey and try to get better every day. And don’t lose the passion and the love for what you do.

We were able to successfully deploy code to our new Sitecore 9.1 (initial release) and most of the things went well except one and which was a big one “Experience Editor”.

When we tried to add any component to a page in Experience Editor with its data source item it started to give us a JavaScript alert in browser as well as error in console.

This was something that I haven’t faced before and looking at the console error it looked to be a generic error.

The error says,

“could not find the rendering in the Html loaded from the server”

I Googled this error and found


We raised a support ticket for better understanding of the issue, and they asked us to capture the fiddler session of the same.

Sitecore Support came up with an answer as below,

“I believe the issue lies within GET vs POST request. In Sitecore 9.0 onwards, Experience Editor architecture was changed and part of this included some requests making a POST request which initially were making a GET request. 

I compared the "Palette.aspx" call from your fiddler session to mine. In the response of this POST call, in yours, there is no element with ' id="r_****" ', this implies that the POST request was not handled on controller side if I am not mistaken. 

I would encourage checking your Controller handling and change to handle POST request rather than GET. “

Ours is a Multisite Solution and we have many re-usable components which are used across the sites and it seemed to be a very time-consuming process to check each component in the solution.

But for every problem there is a Solution and we found one.

Suddenly for one of the Site which had fewer content pages, Experience Editor was working. But for our 2 main sites it was not.

As mentioned previously we have components which are re-usable across all the Sites, I decided to use a trick.

The home page for all the Sites were almost identical except one component.
It was a Search Component which was different from the one where the Experience Editor was working, and it was a global component which is used on all the pages.

I removed the search component from the page and tried to add a component and it worked.

I was successfully able to add a component to the page.

Now what's there in that component which is not allowing the experience editor to function?

In the POST request at the end of the code it was basically doing Redirect to a particular URL and that was causing conflict with the Experience Editor POST method.

The Solution was simple. I added below line of code and was able to fix the issue

if (!Sitecore.Context.PageMode.IsExperienceEditorEditing)
                return Redirect(redirectUrl);

Phewwww…. and the Experience Editor started working.


Note : Thanks to Yogini Zope for Identifying that it worked for one of the sites.


Wednesday 12 June 2019

Sitecore 9.1 : Access denied error when trying to open Sitecore admin page without login when identity server is disabled



Hello Sitecore Devs,

We have a Sitecore 9.1 instance (initial release) where Identity Server is disabled.

To know more about Identity server follow this link : 


If you want to disable identity Server for some reason, Sitecore OOTB provides 2 disabler configs namely,

Sitecore.Owin.Authentication.Disabler.config
Sitecore.Owin.Authentication.IdentityServer.Disabler.config

I found one strange thing on my Sitecore instance after the identity server is disabled.

Whenever I tried to open any admin page (e.g. http://<yourhostname>/sitecore/admin) without login, instead of redirecting me to the login page it was showing me access denied error page.

This was something unexpected. So, I raised a Support ticket with Sitecore to understand this behavior.

Sitecore Support accepted this as a bug in Sitecore 9.1.

Now what’s the solution?

As per Sitecore they would no longer provide patches for Sitecore 9.1 or later versions.

Check the Sitecore KB article on this: https://kb.sitecore.net/articles/077333

But they were kind on me. They did mention a workaround for this.
  • Create an item under the item '/sitecore/system/Aliases' using Alias item
  • Insert an external link. For example, create the admin item with the link http://<HostName>/sitecore/login?ReturnUrl=%2fsitecore%2fadmin%2f
  • The shell item - with the link http://<HostName>/sitecore/login
  • Publish your items.

View below screencast to reproduce and fix the issue: https://www.screencast.com/t/koGEsQDXszn

That’s it for now!!!

Tuesday 9 April 2019

Sitecore XP 9.1 – Marketing Automation/Processing Engine Services not getting started automatically after installation

Hello Devs,

After installing Sitecore 9.1 (Development/Scaled) environment you might face an issue where Marketing Automation/Processing Engine services doesn’t get start automatically.

First Step - Try starting them manually. If they start you are good there.
If not follow below stack overflow links for troubleshooting:


Still facing issues while trying to start services?

Follow below steps to troubleshoot:

1.Check the XConnect site in the IIS to verify whether valid certificate is associated with the XConnect site.
    
     2.Check whether XConnect loads successfully in browser with a valid certificate  associated.
    
     3.Verify the thumbprint value of the certificate associated with the XConnect site with the below mentioned locations. It should be same, if not update thumbprint values to match with the Certificate thumbprint associated with the XConnect site.

Sitename.XConnect\app_config\AppSettings.config
Sitename.XConnect\App_Data\jobs\continuous\AutomationEngine\App_Config\ConnectionStrings.config
Sitename.XConnect\App_Data\jobs\continuous\ProcessingEngine\App_Config\ConnectionStrings.config

Once all this is done try to re-start the machine and check whether the services started automatically. If not, try to start them manually.

Hope this helps!!!