blog.scoreman.net

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

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:

Tags: ,

Leave a Reply