blog.scoreman.net

JQuery: disable all input controls before postback

June 16th, 2010

If you have very eager users that keeps pushing the submit buttons like a maniac you may want to disable the submit button(s). Here is a script that you can use if you have a UpdatePanel with asynchronous post-backs. The script hooks up to the begin request event and calls a function that finds all submit buttons and disables them.

<asp:UpdatePanel runat="server">
  <contenttemplate>

    <!-- Here goes all input controls -->

    <script type="text/javascript">

      var prm = Sys.WebForms.PageRequestManager.getInstance();
      prm.add_beginRequest(function() {
        disableSubmitButtons();
      });

    </script>

  </contenttemplate>
</asp:UpdatePanel>

<script language="javascript">

  function disableSubmitButtons() {
    $("input[type=submit]").attr("disabled", true);
}

</script>

Huge limitation in MOSS Search and Search Server Express using the FREETEXT clause

May 23rd, 2010

A while ago I was working in a project where the customer had problem searching the content of columns with type multiple line of text in SharePoint. We were using the FullTextSqlQuery class with the FREETEXT keyword. After some investigation I found out that there is a huge limitation in the search engine. As it turns out when the crawler indexes content it stores the data in two columns in the MSSDocProps table. The first is strVal which is a nvarchar(64) and the second is binVal which is a image-type. When you run a fulltext query with the FREETEXT clause it runs against the strVal column which only contains the first 64 charcters of the crawled content.

This limitation got even more frusterating when we needed to search for document in a specific sub web. Since there is no way to search on the SPWeb’s guid we thought we could filter the search on the documents path put since this limitation also affects the CONTAINS clause we only got the first 64 characters of the url which was of no use.

 

The only workaround I’ve found is not to use FREETEXT and do some post-filtering of the dataset returned from ExecuteQuery. This is possible since the value of the fields you have in the SELECT clause fetches the data from the binVal column which contains the full text.

I understand that because of performance and disk space there is a limit of 64 characters but it would have been nice if Microsoft had made it possible to search the full content of a field.

SharePoint 2010 Foundation vs. Server

May 12th, 2010

Interested in what features are included in SharePoint 2010 Foundation and what’s not included. This is a really good summary:

http://www.fpweb.net/sharepoint-hosting/2010/features/foundation-vs-server.asp

Week number in Gantt view

May 1st, 2010

I’ve already made previous post on how to add week number in the SharePoint monthly view of the calendar. This post is about how to add week numbers to the Gantt view. A customer wanted to display the headings in the Gantt view like YYWW (two digits representing the year and two digits representing the week number). This was solved using jquery and some date manipulation with javascript. The code runs on sites with English(american) regional settings but you can easily modify the script to run with other culture settings. Put the script in a content editor web part above the Gantt view or incorporate it into your master page.

Before adding the script:

After the script is added it looks like this:

Here is the script. Please change the protocol for the jquery script link depending on if you run http or https.

<script src="https://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.min.js" type="text/javascript"></script>

<script type="text/javascript">

Date.prototype.getWeek = function() {
    var year = this.getFullYear();
    var month = this.getMonth();
    var day = this.getDate();

    month += 1; //use 1-12
    var a = Math.floor((14 - (month)) / 12);
    var y = year + 4800 - a;
    var m = (month) + (12 * a) - 3;
    var jd = day + Math.floor(((153 * m) + 2) / 5) +
                 (365 * y) + Math.floor(y / 4) - Math.floor(y / 100) +
                 Math.floor(y / 400) - 32045;      // (gregorian calendar)

    var d4 = (jd + 31741 - (jd % 7)) % 146097 % 36524 % 1461;
    var L = Math.floor(d4 / 1460);
    var d1 = ((d4 - L) % 365) + L;
    NumberOfWeek = Math.floor(d1 / 7) + 1;
    return NumberOfWeek;
};

$(document).ready(function() {

    $(".ms-ganttMajorTimeUnitHeaderCell").each(
    function(intIndex) {
        var obj = $(this).attr("innerHTML");
        var firstDay = new Date(obj);

        if (firstDay.toString() != "NaN" && firstDay.toString() != "Invalid Date") {
            var week = firstDay.getWeek(firstDay.getDay());
            week = (week.toString().length == 1) ? '0' + week.toString() : week.toString();
            week = firstDay.getFullYear().toString().substr(2, 2) + week;
            $(this).attr("innerHTML", week);
        }
    });

});

</script>

Week numbers in SharePoint monthly calendar view

June 23rd, 2009

For some organizations working with week number is very important. Although you can turn on showing week numbers in the Date Navigator under Regional Settings there will be no week numbers showing in the monthly view of the calendar. My goal was to have week numbers printed like in the image below.

This is how I did it.

Step 1: Override CalendarViewmonthChrome template

SharePoint uses different templates to render the different views(day, week, month) of a calendar. In order to change the way the monthly view gets rendered you need to add a custom ascx file to the CONTROLTEMPLATES folder i the 12-hive. This file needs to override the CalendarViewmonthChrome rendering template. What I have done is to copy the default rendering template and replaced the MonthlyCalenderView control with my own MyMonthlyCalendarView.

<%@ Control Language="C#"   AutoEventWireup="false" %>
<%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" namespace="Microsoft.SharePoint.WebControls"%>
<%@ Register TagPrefix="SPHttpUtility" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" namespace="Microsoft.SharePoint.Utilities"%>
<%@ Register TagPrefix="wssuc" TagName="ToolBar" src="~/_controltemplates/ToolBar.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="ToolBarButton" src="~/_controltemplates/ToolBarButton.ascx" %>
<%@ Register TagPrefix="myControls" Namespace="MyNamespace" Assembly="MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=XXXXXXXXXXX" %>
<SharePoint:RenderingTemplate ID="CalendarViewmonthChrome" runat="server">
  <Template>
    <div id=MontlyViewDefault_CalendarView style="display:block; overflow:auto; width:<%# SPHttpUtility.HtmlEncode(DataBinder.Eval(Container,"ChromeWidth",""))%>; height:<%# SPHttpUtility.HtmlEncode(DataBinder.Eval(Container,"ChromeHeight",""))%>; "  dir="<%# DataBinder.Eval(Container,"Direction","")%>">
    <input type=hidden id=ExpandedWeeksId name=ExpandedWeeks value="">
    <table border=0 width=100% id="CalViewTable1" style="border-collapse: collapse"  cellpadding=0>
      <tr><td><IMG SRC="/_layouts/images/blank.gif" width=742 height=1 alt=""></td></tr>
      <tr>
         <td>
         <table border="0" width="100%" cellspacing="1" cellpadding="0" id="CalViewTable12" style="border-collapse: collapse">
          <tr>
            <td nowrap>
              <div nowrap>
                <a href="javascript:MoveToViewDate('<%# DataBinder.Eval(Container,"PreviousDate","") %>', null);" tabindex=1 style="visibility:<%# DataBinder.Eval(Container,"PreviousDateVisible","")%>" accesskey="<SharePoint:EncodedLiteral runat='server' text='<%$Resources:wss,calendar_prev_AK%>' EncodeMethod='HtmlEncode'/>">
                <img border="0" src="/_layouts/images/prevbutton<%# DataBinder.Eval(Container,"Direction","")%>.gif" width="15" height="15" alt="<SharePoint:EncodedLiteral runat='server' text='<%$Resources:wss,calendar_prevmonth%>' EncodeMethod='HtmlEncode'/>" ></a>
                 <a href="javascript:MoveToViewDate('<%# DataBinder.Eval(Container,"NextDate","") %>', null);" tabindex=1 style="visibility:<%# DataBinder.Eval(Container,"NextDateVisible","")%>" accesskey="<SharePoint:EncodedLiteral runat='server' text='<%$Resources:wss,calendar_next_AK%>' EncodeMethod='HtmlEncode'/>" >
                <img border="0" src="/_layouts/images/nextbutton<%# DataBinder.Eval(Container,"Direction","")%>.gif" width="15" height="15" alt="<SharePoint:EncodedLiteral runat='server' text='<%$Resources:wss,calendar_nextmonth%>' EncodeMethod='HtmlEncode'/>" ></a>
                &nbsp;<%# DataBinder.Eval(Container,"HeaderDate","") %>&nbsp;
               </div>
            </td>
            <td>&nbsp;</td>
            <tdDirection","")%>">
              <span id=ExpandAllId dir="<%# DataBinder.Eval(Container,"Direction","")%>">
                <a href="javascript:" onclick="javascript:GetMonthView('1111111');return false;" tabindex=1 accesskey="<SharePoint:EncodedLiteral runat='server' text='<%$Resources:wss,calendar_expandall_AK%>' EncodeMethod='HtmlEncode'/>" nowrap ><NOBR><SharePoint:EncodedLiteral runat="server" text="<%$Resources:wss,calendar_expandall%>" EncodeMethod='HtmlEncode'/></NOBR></a>
              </span>
              &nbsp;
              <span id=CollapseAllId dir="<%# DataBinder.Eval(Container,"Direction","")%>">
                <a href="javascript:" onclick="javascript:GetMonthView('0000000');return false;" tabindex=1 accesskey="<SharePoint:EncodedLiteral runat='server' text='<%$Resources:wss,calendar_collapseall_AK%>' EncodeMethod='HtmlEncode'/>" nowrap ><NOBR><SharePoint:EncodedLiteral runat="server" text="<%$Resources:wss,calendar_collapseall%>" EncodeMethod='HtmlEncode'/></NOBR></a>
              </span>
              <span> &nbsp;|</span>
              <Sharepoint:SPCalendarTabs runat="server"
              SelectedViewTab='<%# SPHttpUtility.HtmlEncode(DataBinder.Eval(Container,"ViewType","")) %>'
              ListName='<%# SPHttpUtility.HtmlEncode(DataBinder.Eval(Container,"ListName","")) %>'
              ViewGuid='<%# SPHttpUtility.HtmlEncode(DataBinder.Eval(Container,"ViewName","")) %>'
              >
              </Sharepoint:SPCalendarTabs>
            </td>
          </tr>
        </table>
         </td>
      </tr>
      <tr>
        <td>
          <myControls:MyMonthlyCalendarView runat="server"
          SelectedDate='<%# DataBinder.Eval(Container,"SelectedDate","") %>'
          ExpandedWeeks='<%# SPHttpUtility.HtmlEncode( DataBinder.Eval(Container,"ExpandedWeeks","")) %>'
          ItemTemplateName="CalendarViewMonthItemTemplate"
          ItemAllDayTemplateName="CalendarViewMonthItemAllDayTemplate"
          ItemMultiDayTemplateName="CalendarViewMonthItemMultiDayTemplate"
          TabIndex=2
          >
          </myControls:MyMonthlyCalendarView>
        </td>
      </tr>
     </table>
    </div>
  </Template>
</SharePoint:RenderingTemplate>

Step 2: Intercepting and rewriting html output

The rendering of the table cell where I wanted to insert the week number is well hidden in the MonthlyCalendarView control. What I did instead was to override the AppendEmptyTD and AppendEventTD methods and checked if it was the first day in the week. If so I knew that the StringBuilder object would contain some html with an empty image tag that had an alt-attribute containing text for the week span. Using a regular expression I replaced the image tag with the week number for the current date. Notice that the function that gets the week number is somewhat hard coded and could be rewritten so that Regional Settings for the SPWeb is taken into account.


public class MyMonthlyCalendarView : MonthlyCalendarView
{
    private static Regex weekRegex = new Regex(@"<img border=0 src='/_layouts/images/blank.gif' class='ms-cal-blankimage' alt='[a-z]+s[0-9]{2}s-s[a-z]+s[0-9]{2}'>", RegexOptions.IgnoreCase | RegexOptions.Multiline);

    protected override void AppendEmptyTD(ref StringBuilder str, int iday, Microsoft.SharePoint.Utilities.SimpleDate currDateInWeek)
    {
        if (iday == 0)
        {
            this.AppendWeekNumber(ref str, currDateInWeek);
        }
        base.AppendEmptyTD(ref str, iday, currDateInWeek);
    }

    protected override void AppendEventTD(ref StringBuilder str, int iday, SPCalendarItemContainer oEvent, int colspan, int rowspan, Microsoft.SharePoint.Utilities.SimpleDate currDateInWeek, int tabIndex)
    {
        if (iday == 0)
        {
            this.AppendWeekNumber(ref str, currDateInWeek);
        }
        base.AppendEventTD(ref str, iday, oEvent, colspan, rowspan, currDateInWeek, tabIndex);
    }
   
    private void AppendWeekNumber(ref StringBuilder str, Microsoft.SharePoint.Utilities.SimpleDate currDateInWeek)
    {
        string content = str.ToString();         
        if (weekRegex.IsMatch(content))
        {               
            int week = GetWeekNumber(currDateInWeek);
            content = weekRegex.Replace(content, week.ToString());
            str = new StringBuilder(content);
        }
    }

    private static int GetWeekNumber(SimpleDate date)
    {
        CultureInfo culture = SPContext.Current.Web.Locale;
        return culture.Calendar.GetWeekOfYear(new DateTime(date.Year, date.Month, date.Day), CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
    }
}

Flush Cache for Publishing Pages

April 16th, 2009

A while back I wrote some custom code that redirected the user directly to the edit mode of a publishing page. This was done by passing querystring parameters “ControlMode=Edit&DisplayMode=Design”. The only problem was that if the user had hit the page before the publishing console was cached and would not display the right buttons for edit mode. Using Reflector I found out that the Publishing Console uses a cache and that there where internal classes for managing the cache. With a little bit of reflection I could call into these classes and flush the cache.

private static void FlushItemCachedState(string page, SPSite site)
{
    Assembly assembly = Assembly.GetAssembly(typeof(PublishingPage));
    Type cacheManagerType = assembly.GetType("Microsoft.SharePoint.Publishing.CacheManager");
    MethodInfo miGetManager = cacheManagerType.GetMethod("GetManager", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance, null, new Type[] { typeof(SPSite) }, null);
    object manager = miGetManager.Invoke(null, new object[] { site });
    PropertyInfo piObjectFactory = cacheManagerType.GetProperty("ObjectFactory");
    object objectFactory = piObjectFactory.GetValue(manager, null);
    Type cacheObjectFactoryType = assembly.GetType("Microsoft.SharePoint.Publishing.CachedObjectFactory");
    MethodInfo miFlushItem = cacheObjectFactoryType.GetMethod("FlushItem", new Type[] { typeof(string) });
    string cacheKey = new Uri(page).LocalPath;
    miFlushItem.Invoke(objectFactory, new object[] { cacheKey });
}

CAML query with “Today” that includes time value

February 17th, 2009

I was trying to create a CAML query that would filter out all pages with a valid publishing date (and time) using the CrossListQueryInfo object. When I used the <Today/> element in the query it ignored the time.

I remembered reading some were that you could use <Now/> instead of <Today/> but that didn’t do it.

<Leq>
   <FieldRef Name="PublishingStartDate" Nullable="True" Type="DateTime"/>
   <Value Type="DateTime"><Now/></Value>
</Leq>

It turns out that you should use the <Today/> element but that you also need to add a IncludeTimeValue=TRUE attribute.

<Leq>
   <FieldRef Name="PublishingStartDate" Nullable="True" Type="DateTime"/>
   <Value Type="DateTime" IncludeTimeValue="TRUE"><Today/></Value>
</Leq>

Changing page layout and content type of a publishing page

February 6th, 2009

Yesterday i wrote to extension methods that helps changing page layout and content type of a publishing page. The first method finds the layout by name, sets the content type on the list item and changes the layout. The second method (EnsureContentTypeOnPagesList) ensures that the new content type will be added to the Pages library if not already present (Content types will be added to the Pages library first when you add a page using that content type).

public static void ChangePageLayout(this PublishingPage page, string layoutName)
{
    PageLayout[] pageLayouts = page.PublishingWeb.GetAvailablePageLayouts();
    PageLayout newLayout = pageLayouts.SingleOrDefault(p => p.Name == layoutName);
    if (newLayout != null)
    {
        page.PublishingWeb.EnsureContentTypeOnPagesList(newLayout.AssociatedContentType);
        page.ListItem[SPBuiltInFieldId.ContentTypeId] = newLayout.AssociatedContentType.Id;
        page.Layout = newLayout;
        page.ListItem.SystemUpdate();
    }
}
public static void EnsureContentTypeOnPagesList(this PublishingWeb publishingWeb, SPContentType contentType)
{
    SPContentType listContentType = publishingWeb.PagesList.ContentTypes.Cast<SPContentType>()
        .SingleOrDefault(ct => ct.Id.ToString().StartsWith(contentType.Id.ToString()));
    if (listContentType == null)
    {
        SPSecurity.RunWithElevatedPrivileges(delegate
        {
            using (var elevatedSite = new SPSite(publishingWeb.Web.Site.ID))
            {
                using (var elevatedWeb = elevatedSite.OpenWeb(publishingWeb.Web.ID))
                {
                    elevatedWeb.AllowUnsafeUpdates = true;
                    Guid listId = PublishingWeb.GetPagesListId(elevatedWeb);
                    elevatedWeb.Lists[listId].ContentTypes.Add(contentType);
                    elevatedWeb.AllowUnsafeUpdates = false;
                }
            }
        });
    }
}

Running SPDisposeCheck on Microsoft.*

February 6th, 2009

I found it interesting that SPDisposeCheck ignored files and namespaces that started with Microsoft and System. With a little bit of .net reflection I managed to come around the “problem”:

Microsoft.SharePoint.dll 9 varnings
Microsoft.Office.Policy.dll 1 varning
Microsoft.Office.Server.Search.dll 1 varning
microsoft.sharepoint.portal.dll 2 varnings
Microsoft.SharePoint.Publishing.dll 10 varnings
Microsoft.SharePoint.Search.dll 1 varning

Using Telerik Image/Asset Picker to choose images in publishing pages

February 6th, 2009

Telerik is a great third party tools for providing the SharePoint user with a richer toolbar when editing rich html fields. It has features for resizing and cropping images as well as a much easier way to navigate when selecting images. What I wanted to do was to use this image picker outside the context of the toolbar. I wanted the image picker to pop up when you click on Edit Picture in a MOSS publishing page that had an image in the page layout.

The way I implemented it was just like a regular publishing field control that could be put on the publishing page and save the image information to the page’s metadata.

Step 1: Custom rendering template for the control

First of we need to have a rendering template for the control. This is put in a ascx-file in the CONTROLTEMPLATES folder in the 12-hive. The control have a Telerik DialogOpener and some html to make it look like the standard publising image field.

<%@ Control Language="C#" Debug="true" %>
<%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" namespace="Microsoft.SharePoint.WebControls"%>
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI, Version=2008.3.1125.20, Culture=neutral, PublicKeyToken=121fae78165ba3d4" %>
<SharePoint:RenderingTemplate ID="TelerikImageField" runat="server">
    <Template>
        <telerik:dialogopener
            HandlerUrl="/_wpresources/RadEditorSharePoint/5.3.1.0__1f131a624888eeed/Resources/Telerik.Web.UI.DialogHandler.aspx"
            runat="server" id="dialogOpener">
        </telerik:dialogopener>       
        <div height="100%" width="100%" style="padding:4px">
            <div width="100%">               
        <div>
            <asp:HyperLink ID="insertImagePictureLink" NavigateUrl="#" TabIndex="-1" runat="server"><asp:Image ID="insertImagePicture" ImageUrl="/_layouts/1033/IMAGES/rteimg.gif" BorderWidth="0" runat="server" /></asp:HyperLink><asp:HyperLink ID="insertImageTextLink" NavigateUrl="#" runat="server" />
        </div>
        <div id="divClearImage" runat="server">
            <asp:HyperLink ID="clearImagePictureLink" NavigateUrl="#" TabIndex="-1" runat="server"><asp:Image ID="clearImagePicture" ImageUrl="/_layouts/IMAGES/CMSRemoveImage.GIF" BorderWidth="0" runat="server" /></asp:HyperLink><asp:HyperLink ID="clearImageTextLink" NavigateUrl="#" runat="server" />
        </div>       
            </div>
        </div>              
        <div id="divImageContent" runat="server" />
        <div  id="divEmptyPanel" runat="server">
            <div height="100%" width="100%" style="padding:4px" align="center" valign="center">
                <asp:HyperLink ToolTip="InsertButtonTooltip" ID="emptyPanelLink" NavigateUrl="#" CssClass="ms-toolbar ms-selectorlink" runat="server" />
            </div>
        </div>
        <input id="hiddenContent" type="hidden" runat="server" />
    </Template>
</SharePoint:RenderingTemplate>

Step 2: Implement the Code Behind for the control

I’m not going to to through the hole code but basically what it does is to initialize the Telerik DialogOpener, registers JavaScript functions for opening the dialog and handling the result it returns.

public class TelerikImageField : BaseFieldControl
{
    protected DialogOpener dialogOpener;
    protected HtmlGenericControl divImageContent, divEmptyPanel, divClearImage;
    protected HtmlInputHidden hiddenContent;
    protected HyperLink insertImagePictureLink, insertImageTextLink, clearImagePictureLink, clearImageTextLink, emptyPanelLink;
    protected Image insertImagePicture, clearImagePicture;
    private readonly string telerikContentProviderName = "Telerik.SharePoint.Editor.SPContentProvider, RadEditorSharePoint, Version=5.3.1.0, Culture=neutral, PublicKeyToken=1f131a624888eeed";
   
    protected override string DefaultTemplateName
    {
        get
        {
            return "TelerikImageField";
        }
    }
    public override object Value
    {
        get
        {
            EnsureChildControls();
            if (!string.IsNullOrEmpty(hiddenContent.Value))
            {
                return hiddenContent.Value;
            }
            else
            {
                return null;
            }
        }
        set
        {
            EnsureChildControls();
            if (value != null)
            {
                var image = value as ImageFieldValue;
                divImageContent.InnerHtml = image.ToString();
                hiddenContent.Value = image.ToString();
                divClearImage.Attributes["class"] = "ms-toolbarItem ms-selectorlink";
                divEmptyPanel.Style[HtmlTextWriterStyle.Display] = "none";
            }               
        }
    }
    protected override void CreateChildControls()
    {
        if (Field == null)
        {
            return;
        }
        if (ControlMode == SPControlMode.Display)
        {
            return;
        }
        base.CreateChildControls();
        this.InitControls();
        this.CreateDialogParameters();
        this.CreateClientScripts();
        this.SetResources();
        divEmptyPanel.Style.Add(HtmlTextWriterStyle.Display, "inline");
        divClearImage.Attributes.Add("class", "ms-toolbarItem ms-selectorlink ms-selectorlinkdis");
        insertImagePictureLink.Attributes.Add("onclick", string.Format("$find('{0}').open('ImageManager');return false;", dialogOpener.ClientID));
        insertImageTextLink.Attributes.Add("onclick", string.Format("$find('{0}').open('ImageManager');return false;", dialogOpener.ClientID));
        emptyPanelLink.Attributes.Add("onclick", string.Format("$find('{0}').open('ImageManager');return false;", dialogOpener.ClientID));
        clearImagePictureLink.Attributes.Add("onclick", "ImageManagerClear();return false;");
        clearImageTextLink.Attributes.Add("onclick", "ImageManagerClear();return false;");
    }
    private void SetResources()
    {
        Assembly assembly = Assembly.Load("Microsoft.SharePoint.Publishing.intl, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c");
        ResourceManager rm = new ResourceManager("Microsoft.SharePoint.Publishing.Strings", assembly);
       
        insertImagePicture.AlternateText = rm.GetString("FieldSelectorControlsImageInsertButtonTooltip", Web.Locale);
        insertImageTextLink.ToolTip = rm.GetString("FieldSelectorControlsImageInsertButtonTooltip", Web.Locale);
        insertImageTextLink.Text = rm.GetString("FieldSelectorControlsImageInsertButtonText", Web.Locale);
        clearImagePicture.AlternateText = rm.GetString("FieldSelectorControlsClearAssetButtonText", Web.Locale);
        clearImageTextLink.ToolTip = rm.GetString("FieldSelectorControlsClearAssetButtonText", Web.Locale);
        clearImageTextLink.Text = rm.GetString("FieldSelectorControlsClearAssetButtonText", Web.Locale);
        emptyPanelLink.ToolTip = rm.GetString("FieldSelectorControlsImageInsertButtonTooltip", Web.Locale);
        emptyPanelLink.Text = rm.GetString("FieldSelectorControlsImageAddPromptLinkText", Web.Locale);
    }
    private void InitControls()
    {
        dialogOpener = FindAndValidateControl("dialogOpener") as DialogOpener;
        divImageContent = FindAndValidateControl("divImageContent") as HtmlGenericControl;
        hiddenContent = FindAndValidateControl("hiddenContent") as HtmlInputHidden;
        insertImagePictureLink = FindAndValidateControl("insertImagePictureLink") as HyperLink;
        insertImageTextLink = FindAndValidateControl("insertImageTextLink") as HyperLink;
        insertImagePicture = FindAndValidateControl("insertImagePicture") as Image;
        clearImagePicture = FindAndValidateControl("clearImagePicture") as Image;
        clearImagePictureLink = FindAndValidateControl("clearImagePictureLink") as HyperLink;
        clearImageTextLink = FindAndValidateControl("clearImageTextLink") as HyperLink;
        emptyPanelLink = FindAndValidateControl("emptyPanelLink") as HyperLink;
        divEmptyPanel = FindAndValidateControl("divEmptyPanel") as HtmlGenericControl;
        divClearImage = FindAndValidateControl("divClearImage") as HtmlGenericControl;
    }
    private void CreateClientScripts()
    {
        ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
        string script = @"
            function ImageManagerInsert(sender, args)  
            {  
                var selectedItem = args.SelectedItem;  
                var resultImageObject = args.Result;                       
                var divContent = $get('" + divImageContent.ClientID + @"');  
                var divEmptyPanel = $get('" + divEmptyPanel.ClientID + @"');  
                var hiddenContent = $get('" + hiddenContent.ClientID + @"');  
                var divClearImage = $get('" + divClearImage.ClientID + @"');  
                divEmptyPanel.style.display = 'none';
                divContent.style.display = 'inline';
               
                var parentCssClass = divClearImage.className;
                var myRegex=new RegExp("" ms-selectorlinkdis"", ""ig"");
                parentCssClass = parentCssClass.replace(myRegex, """");
                divClearImage.className = parentCssClass;
                if (document.all)  
                {  
                    divContent.innerHTML = resultImageObject.outerHTML;  
                    hiddenContent.value = resultImageObject.outerHTML;  
                }  
                else  
                {  
                    divContent.innerHTML = ""<img src='"" +  selectedItem.getPath() + ""' />"";  
                    hiddenContent.value = ""<img src='"" +  selectedItem.getPath() + ""' />"";  
                }  
            }
            function ImageManagerClear(sender)  
            {  
                var divContent = $get('" + divImageContent.ClientID + @"');  
                var divEmptyPanel = $get('" + divEmptyPanel.ClientID + @"');  
                var hiddenContent = $get('" + hiddenContent.ClientID + @"');
                var divClearImage = $get('" + divClearImage.ClientID + @"');     
                  
                divContent.innerHTML = '';  
                divContent.style.display = 'none';
                hiddenContent.value = '';                                     
                divEmptyPanel.style.display = 'inline'; 
                divClearImage.className = divClearImage.className + ' ms-selectorlinkdis'; 
            } 
        ";
        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), string.Concat("TelerikImageField_", this.ClientID), script, true);
    }
    private void CreateDialogParameters()
    {
        string[] paths = new string[] { "PublishingImages", "/SiteCollectionImages" };
        string siteUrl = SPContext.Current.Site.Url;
        string webUrl = SPContext.Current.Web.ServerRelativeUrl;
        string webId = string.Empty;
        FileManagerDialogParameters imageManagerParameters = new FileManagerDialogParameters();
        imageManagerParameters.ViewPaths = paths;
        imageManagerParameters.UploadPaths = paths;
        imageManagerParameters.DeletePaths = paths;
        imageManagerParameters.MaxUploadFileSize = 5000000;
        imageManagerParameters.FileBrowserContentProviderTypeName = telerikContentProviderName;
        imageManagerParameters.Add("SiteUrl", siteUrl);
        imageManagerParameters.Add("WebUrl", webUrl);
        imageManagerParameters.Add("WebID", webId);
                   
        DialogDefinition imageManager = new DialogDefinition(typeof(ImageManagerDialog), imageManagerParameters);
        imageManager.ClientCallbackFunction = "ImageManagerInsert";
        imageManager.Width = Unit.Pixel(694);
        imageManager.Height = Unit.Pixel(440);
        dialogOpener.DialogDefinitions.Add("ImageManager", imageManager);
        FileManagerDialogParameters imageEditorParameters = new FileManagerDialogParameters();
        imageEditorParameters.ViewPaths = paths;
        imageEditorParameters.UploadPaths = paths;
        imageEditorParameters.DeletePaths = paths;  
        imageEditorParameters.MaxUploadFileSize = 5000000;
        imageEditorParameters.FileBrowserContentProviderTypeName = telerikContentProviderName;
        imageEditorParameters.Add("SiteUrl", siteUrl);
        imageEditorParameters.Add("WebUrl", webUrl);
        imageEditorParameters.Add("WebID", webId);
        DialogDefinition imageEditor = new DialogDefinition(typeof(ImageEditorDialog), imageEditorParameters);
        imageEditor.Width = Unit.Pixel(832);
        imageEditor.Height = Unit.Pixel(520);
        dialogOpener.DialogDefinitions.Add("ImageEditor", imageEditor);
    }
    protected virtual Control FindAndValidateControl(string id)
    {
        Control ctrl = TemplateContainer.FindControl(id);
        if (ctrl == null)
            throw new ArgumentException(string.Format("{0} is null. Corrupted ascx file.", id));
        return ctrl;
    }
}

Step 3: Modifying the page layout

As a last step you just need to change the page layout. Instead of this:

<PublishingWebControls:RichImageField id="ContentQueryImage" FieldName="PublishingRollupImage" AllowHyperLinks="false" runat="server"/>

You change it to this:

<myControls:TelerikImageField ID="RichImageField1" FieldName="PublishingRollupImage" runat="server" />

The final result looks like this: