Wednesday, August 24, 2011

Sharepoint 2010 : Display Thumbnail view for Picture library

here is the post with out customization i mean with out writing any code



if you implement below code, finally picture library shows as see in the below picture. when you click on more it brings you to actual picture library. here you can upload new pictures by clicking on "add new"



.cs file
===================================
public partial class UCPictureLibrary : UserControl
    {
        const string LIST_NAME = "Picture Gallery";

        #region Variable Declarations
        protected EncodedLiteral encodedLiteral = null;
        private string sSiteUrl = SPContext.Current.Web.Url;
        private string sAddNew = "Add New Pictures";
        private string ThumbNailImageURL = string.Empty;
        private string ImageName = string.Empty;
        private string ImageExtension = string.Empty;
        private string ThumbnailImagesFolder = string.Empty;

        #endregion



        protected void Page_Load(object sender, EventArgs e)
        {
           //System.Diagnostics.Debugger.Break();
           // dvSummaryView.Controls.Clear();
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    
                    if (!string.IsNullOrEmpty(Request.QueryString["title"]))
                    {
                        sWorkspaceTitle = Request.QueryString["title"].ToString();
                    }
                  
                    using (SPWeb oHomeWeb = new SPSite(SPContext.Current.Site.Url).OpenWeb())
                    {
                        SPList oPictureGalleryList = oHomeWeb.Lists["Picture Gallery"];
                        SPView oCustomView = oPictureGalleryList.Views["All Pictures"];
                        oCustomView.RowLimit = 5;

                        int Count = 0;
                        System.Web.UI.WebControls.Table tblMain =new System.Web.UI.WebControls.Table();
                        tblMain.CellPadding = 7;
                        tblMain.CellSpacing = 7;
                        TableRow rowImage = new TableRow();
                        TableRow rowImgLabel = new TableRow();
                        rowImage.Height = Unit.Pixel(165);
                        rowImgLabel.Height = Unit.Pixel(10);
                        ThumbnailImagesFolder = oPictureGalleryList.RootFolder.ServerRelativeUrl + "/" + sWorkspaceTitle + "/_t/";
                        SPFolder oCurrentFolder = oHomeWeb.GetFolder(oPictureGalleryList.ParentWebUrl + "/" + oPictureGalleryList.Title + "/" + sWorkspaceTitle);

                        if (oCurrentFolder != null)
                        {
                            SPQuery query = new SPQuery();
                            query.Query = "<OrderBy ><FieldRef Name='Created' Ascending='False' /></OrderBy>";
                            //query.Query = "<Where><FieldRef Name='Title'/><OrderBy><FieldRef Name='Created' /></OrderBy>";
                            query.Folder = oCurrentFolder;
                            SPListItemCollection itemCol = oPictureGalleryList.GetItems(query);

                            if (itemCol.Count > 0)
                            {
                                foreach (Microsoft.SharePoint.SPListItem listItem in itemCol)
                                {
                                    TableCell cellImage = new TableCell();
                                    TableCell cellImgLabel = new TableCell();
                                    cellImage.Width = Unit.Pixel(164);
                                    cellImage.VerticalAlign = VerticalAlign.Middle;
                                    cellImage.CssClass = "ms-imglibthumbnail";
                                    cellImgLabel.VerticalAlign = VerticalAlign.Top;
                                    cellImgLabel.Wrap = false;
                                    cellImgLabel.HorizontalAlign = HorizontalAlign.Center;
                                   
                                    ImageName = listItem.Name;
                                    ImageExtension =ImageName.Substring(ImageName.LastIndexOf(".") + 1);

                                   // if (!ImageName.LastIndexOf(".").Equals(-1))
                                   // {
                                        ThumbNailImageURL = ThumbnailImagesFolder + ImageName.Substring(0, ImageName.LastIndexOf(".")) + "_" + ImageExtension + ".jpg";
                                    //}
                                    string sUrl = oPictureGalleryList.ParentWebUrl + "/" + oPictureGalleryList.Title + "/Forms/DispForm.aspx?ID=" + listItem.ID+ " &RootFolder=" + oPictureGalleryList.ParentWebUrl + "/" + oPictureGalleryList.Title + "/" + sWorkspaceTitle + "&Source=" + oPictureGalleryList.ParentWebUrl + "/_layouts/OPS/opsworkspace.aspx?title=" + sWorkspaceTitle + "&IsDlg = 1";
                                    HyperLink link = new HyperLink();
                                    sUrl = "javascript:OpenDialogPictures('" + sUrl + "')";
                                    link.Attributes.Add("href", sUrl);
                                    link.Attributes.Add("onclick", "ClickThumbnail(" + Count + ")");

                                    Image image = new Image();
                                    image.CssClass = "thumbnail";
                                    image.ImageUrl = ThumbNailImageURL;
                                    image.AlternateText = listItem.File.Name;
                                   
                                    link.Controls.Add(image);
                                    cellImage.Controls.Add(link);
                                    rowImage.Controls.Add(cellImage);

                                    Label lblName = new Label();
                                    lblName.Text = "<br>" + listItem.File.Name;
                                    cellImgLabel.Controls.Add(lblName);
                                    rowImgLabel.Controls.Add(cellImgLabel);

                                    Count++;
                                    if (Count % 5 == 0)
                                    {
                                        tblMain.Controls.Add(rowImage);
                                        tblMain.Controls.Add(rowImgLabel);
                                        rowImage = new TableRow();
                                        rowImgLabel = new TableRow();

                                        break;

                                    }
                                }

                                if (Count > 0)
                                {
                                    tblMain.Controls.Add(rowImage);
                                    tblMain.Controls.Add(rowImgLabel);
                                    //Controls.Add(tblMain);
                                    dvSummaryView.Controls.Add(tblMain);
                                }
                            }
                        }
                        else
                        {
                            DisplayMessage();
                        }

                        if (sSiteUrl.Trim().ToString() != string.Empty)
                        {
                            ahMore.HRef = oHomeWeb.Url + "/" + oPictureGalleryList.Title + "/" + sWorkspaceTitle;

                            ahAddNew.Visible = true;

                            //"&Source=" + oWorkingDocumentsList.ParentWebUrl + "/_layouts/OPS/opsworkspace.aspx?title=" + sWorkspaceTitle + "&IsDlg = 1";
                            ahAddNew.HRef = "javascript:OpenDialogPictures('" + oHomeWeb.Url + "/_layouts/upload.aspx?List={" + oPictureGalleryList.ID + "}&RootFolder=" + oPictureGalleryList.ParentWebUrl + "/" + oPictureGalleryList.Title + "/" + sWorkspaceTitle + "&Source=" + oPictureGalleryList.ParentWebUrl + "/_layouts/OPS/opsworkspace.aspx?title=" + sWorkspaceTitle + "&IsDlg=1&postback=true" + "')";
                            ahAddNew.InnerText = string.Empty;
                            ahAddNew.InnerText = sAddNew;// +" " + oWorkingDocumentsList.Title;
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #region Helper Methods
        private void DisplayMessage()
        {
            encodedLiteral = new EncodedLiteral();
            encodedLiteral.Text = "This webpart is not configured. Contact OPS portal administrator.";
            this.Controls.Add(encodedLiteral);
        }

        private static void SetPrivateFieldValue(object _oObj, string _sFieldName, string _sVal)
        {
            FieldInfo oFieldInfo = _oObj.GetType().GetField(_sFieldName, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            oFieldInfo.SetValue(_oObj, _sVal);
        }

        private static void DisableToolbar(SPView _oCustomView, ListViewWebPart _lvwpShowFiles)
        {
            System.Reflection.PropertyInfo NodeProp = _oCustomView.GetType().GetProperty("Node",
              System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

            System.Reflection.PropertyInfo NodeProp1 = _oCustomView.GetType().GetProperty("RootFolder",
             System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

            XmlNode node = NodeProp.GetValue(_oCustomView, null) as XmlNode;

            XmlNode tBarNode = node.SelectSingleNode("Toolbar");

            if (tBarNode != null)
            {
                XmlAttribute typeNode = tBarNode.Attributes["Type"];

                // make the contents empty so we realy remove the toolbar .....
                tBarNode.RemoveAll();

                // re-add the type attribute
                tBarNode.Attributes.Append(typeNode);

                // finally set the toolbar to not show....
                typeNode.Value = "None";
            }

            //This forces a refresh of the views internal xml or the node's cild nodes are not populated            
            _oCustomView.Update();
        }
        #endregion
    }

aspx Page 
=================================================
<script type="text/javascript">


    function OpenDialogPictures(sPageURL) {

      options = SP.UI.$create_DialogOptions();
        options.width = 750;
        options.height = 670;
        options.url = sPageURL;
        options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);
        SP.UI.ModalDialog.showModalDialog(options);

    }

    function CloseCallback(result, target) {
        location.reload(true);
    }
   

</script>
<style type="text/css">
    .ms-summarystandardbody > tbody > tr > th, .ms-summarystandardbody > tbody > tr > td
    {
        border: 1px solid #eee;
    }
   
    td table.ms-listviewtable, td table.ms-listviewtable, td table.ms-listviewtable td, .ms-summarystandardbody, th.ms-summarystandardbody > tbody > tr > td
    {
        border: 0px solid #eee;
    }
   
    .ms-imnImg
    {
        display: inline-block;
        vertical-align: top;
        margin-right: 3px;
    }
   
    .ms-imnlink
    {
        cursor: default;
    }
   
    .ms-alternating ms-itmhover
    {
        background-color: #fff;
    }
</style>
<div id="dvSummaryView" runat="server" />
<div id="dvMain" runat="server" style="width: 100%">
    <table id="tblMain" cellspacing="2" cellpadding="2" width="100%">
        <tr>
          <td style="text-align: left">
                <img id="imgAdd" src="/_layouts/images/caladd.gif" /> 
                <a href="\" id="ahAddNew" runat="server" visible="False"></a>
            </td>
            <td style="text-align: right">
                <a href="\" id="ahMore" runat="server">more...</a>
            </td>
        </tr>
    </table>
</div>


I hope this would be helpful to u.

3 comments:

  1. Hi surya

    How to copy this code into sharepoint 2010...please advise..

    ReplyDelete
  2. Create a UserControl which is under sharepoint hive (14\TEMPLATE\CONTROLTEMPLATES) and register usercontrol in the application page (which is under Layouts folder).

    ReplyDelete
  3. Hi Surya,

    Where will I place the .cs file and where will I place the .aspx file?

    Thanks.

    ReplyDelete

Followers

Blog Archive