Custom Webpart – Displays the latest image from picture library

Here is the simple custom webpart which displays the latest image from picture library.

Latest Image - Displays the latest image from Picture Library

Latest Image – Displays the latest image from Picture Library

Download complete source code

using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
namespace LatestImage
{
    [Guid("8c21451d-1763-4a7f-817c-f4330a5b1fd8")]
    public class LatestImage : System.Web.UI.WebControls.WebParts.WebPart
    {
        Image myimage = new Image();        
        protected override void CreateChildControls()
        {
            myimage.Height = 256;
            myimage.Width = 256;
            SPSite mysite = new SPSite("http://"+System.Environment.MachineName);
            mysite = SPControl.GetContextSite(Context);
            SPWeb myweb = mysite.OpenWeb();
            SPList mylist=myweb.Lists["Pic Lib"];
            SPQuery myquery = new SPQuery();
            myquery.Query = "";
            string serverpath=mysite.ServerRelativeUrl.ToString();            
            SPListItemCollection mylistitem = mylist.GetItems(myquery);
            if (mylistitem.Count > 0)
            {
                myimage.ImageUrl = serverpath + mylistitem[mylistitem.Count - 1].Url.ToString();
            }
            else
            {
                this.Page.Response.Write("No image found");
            }
            base.CreateChildControls();
        }
        protected override void Render(HtmlTextWriter writer)
        {
            myimage.RenderControl(writer);            
            // TODO: add custom rendering code here.
            // writer.Write("Output HTML");
        }
    }
}