Share via


How to automatically reset/clear the Blob Cache/Disk Cache (programmatically)

Blob Cache(Binary Large Objects Cache) OR Disk-based caching controls caching for binary large objects (BLOBs) such as image, sound, and video files, as well as code fragments. Disk-based caching is extremely fast and eliminates the need for database round trips. BLOBs are retrieved from the database once and stored on the Web client. Further requests are served from the cache and trimmed based on security.

How to enable or disable the Blob Cache

Disk-based caching is disabled by default. To enable and customize the disk-based cache, you must modify the following statement in the web.config file for the SharePoint Web application.

By default, it looks like this:

<BlobCache location="C:\blobCache" path="\.(gif|jpg|png|css|js)$" maxSize="10" enabled="false" />

In order to improve the performance of your site, the BlobCache should be enabled.

<BlobCache location="C:\blobCache" path="\.(gif|jpg|png|css|js)$" maxSize="10" enabled="true" />

Example:

<BlobCache location="C:\blobCache" path="\.(gif|jpg|png|css|js)$" maxSize="10" max-age="86400" enabled="false"/>

In the preceding example:

location - is the directory where the cached files will be stored

path - specifies in the form of a regular expression which files are cached based on the file extension

maxSize - is the maximum allowable size of the disk-based cache in gigabytes

max-age - specifies the maximum amount of time in seconds that the client browser caches BLOBs downloaded to the client computer. If the downloaded items have not expired since the last download, the same items are not re-requested when the page is requested. The max-age attribute is set by default to 86400 seconds (that is, 24 hours), but it can be set to a time period of 0 or greater.

enabled - is a Boolean that disables or enables the cache.

How to reset/flush off Blob Cache

We can flush current site collection object cache.

Site collection administration -> site collection object cache -> disk based cache reset.

If we have multiple WFE in a farm, each WFE will maintain its own copy of Disk-based Cache. MOSS does not have a Web user interface (UI) to flush Disk-based Cache on all the servers in a farm and there is no option to select specific WFE. ”. To completely delete all the images and reset the bin files back to 1KB, so that next request will go to database and the complete index will be getting rebuilt.

We have to reset index file by Site settings -> Site collection object cache -> Check the box for “Force this server to reset its disk based cache.

How to reset/flush off Blob Cache Programmatically

The below code can be run from a windows/console application to reset/clear the Blob cache :-

SPWebApplication

webaplication = this.Parent as SPWebApplication;

string s = "0";

if (webaplication.Properties.ContainsKey("blobcacheflushcount") && webaplication.Properties["blobcacheflushcount"] != null)

s = webaplication.Properties[

"blobcacheflushcount"] as string;

webaplication.Properties[

"blobcacheflushcount"] = (int.Parse(s, CultureInfo.InvariantCulture) + 1).ToString(CultureInfo.InvariantCulture);

webaplication.Update();

How to reset/flush off Blob Cache Programmatically on a Timely basis (using a timer job)

A timer job can be created which does the blob cache flushing at a specified interval. So no need to do it from UI whenever a reset is needed.The code used here is the same code that is called by the CheckBox on the Force this server to reset its disk based cache from UI(as above).

Sample Code and the Steps to deploy the timer job to clear the Blob Cache automatically at a specified interval :-

Feature Receiver

===============

using System;

using Microsoft.SharePoint;

using Microsoft.SharePoint.Administration;

namespace FlushBlobCacheTimerJob

{

class Class2:SPFeatureReceiver

{

const string FlushBlobcache_Job_Name = "TimerJob:FlushBlobCache";

public override void FeatureInstalled(SPFeatureReceiverProperties properties)

{

}

public override void FeatureUninstalling(SPFeatureReceiverProperties properties)

{

}

public override void FeatureActivated(SPFeatureReceiverProperties properties)

{

SPWebApplication webapplication = properties.Feature.Parent as SPWebApplication;

foreach (SPJobDefinition job in webapplication.JobDefinitions)

{

if (job.Name == FlushBlobcache_Job_Name)

job.Delete();

}

Class1 flushcachejob = new Class1(FlushBlobcache_Job_Name, webapplication);

SPMinuteSchedule schedule = new SPMinuteSchedule();

schedule.BeginSecond = 0;

schedule.EndSecond = 59;

schedule.Interval = 5;

flushcachejob.Schedule = schedule;

flushcachejob.Update();

}

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)

{

SPWebApplication webapplication = properties.Feature.Parent as SPWebApplication;

foreach (SPJobDefinition job in webapplication.JobDefinitions)

{

if (job.Name == FlushBlobcache_Job_Name)

job.Delete();

}

}

}

}

Timer Job Class that contains the code to clear the cache

=================================================

using

System;

using System.Collections.Generic;

using System.Text;

using Microsoft.SharePoint;

using Microsoft.SharePoint.Administration;

using System.Configuration;

using System.Diagnostics;

using System.Globalization;

using System.IO;

namespace FlushBlobCacheTimerJob

{

public class Class1 : SPJobDefinition

{

public Class1()

: base()

{

}

public Class1(string jobName, SPService service, SPServer server, SPJobLockType targetType): base(jobName, service, server, targetType)

{

}

public Class1(string jobName, SPWebApplication webApplication): base(jobName, webApplication, null, SPJobLockType.ContentDatabase)

{

this.Title = "TimerJob:FlushBlobCache";

}

public override void Execute(Guid contentDbId)

{

try

{

SPWebApplication webaplication = this.Parent as SPWebApplication;

string s = "0";

if (webaplication.Properties.ContainsKey("blobcacheflushcount") && webaplication.Properties["blobcacheflushcount"] != null)

s = webaplication.Properties["blobcacheflushcount"] as string;

webaplication.Properties["blobcacheflushcount"] = (int.Parse(s, CultureInfo.InvariantCulture) + 1).ToString(CultureInfo.InvariantCulture);

webaplication.Update();

}

catch (Exception ex)

{

FileStream objStream = new FileStream("C:\\blobcache\\AppLog.txt", FileMode.OpenOrCreate);

TextWriterTraceListener objTraceListener = new TextWriterTraceListener(objStream);

Trace.Listeners.Add(objTraceListener);

Trace.WriteLine(ex.StackTrace);

Trace.Flush();

objStream.Close();

}

}

}

}

Feature File

==========

<?

xml version="1.0" encoding="utf-8" ?>

<Feature xmlns="https://schemas.microsoft.com/sharepoint/"

Id="DAC50E58-90A3-4c29-8F7D-FA80FB21A943"

Title="Custom Timer Job to Flush the Blob Cache"

Description="Installs the custom timer job to flush the Blob cache for a web application"

Scope="WebApplication"

Hidden="TRUE"

Version="1.0.0.0"

ReceiverAssembly="FlushBlobCacheTimerJob, Version=1.0.0.0, Culture=neutral, PublicKeyToken=7b9076cf3401b198"

ReceiverClass="FlushBlobCacheTimerJob.Class2">

</Feature>

Steps:

1) Create a timer job that is deployed using feature

2) Use a feature file and specify the name of the feature class

3) Strong-name the assembly and deploy to GAC

4) Copy the feature file to a folder <name> in 12\template\features folder

5) Install the feature using STSADM command

6) Activate the feature and specify the url parameter value as the Web app where you want to activate this job

7) The interval for the job can be changed to run according to your needs and it will clear/reset the blob cache automatically.

Once the Timer job is deployed and activated on a web application, it will automatically reset the Blob Cache for that web application at the mentioned interval :)

Comments