Simple "Sponsors" WebPart (AdRotator)
Here's a very simple webpart that randomly shows pictures from a picturelibrary. The part is configured with the name of a picturelibrary. Pictures should have the Title property set to the URL of the sponsor web site ... very few lines of code solves the problem:
-
namespace MyWSSParts
-
{
-
[Guid("815fbeb7-c1d2-46bb-b5cb-ef3db15c474f")]
-
public class AdRotatorPart : WebPart
-
{
-
public AdRotatorPart()
-
{
-
this.ExportMode = WebPartExportMode.All;
-
}
-
private string adsLibraryName = string.Empty;
-
[Personalizable(true), WebPartStorage(Storage.Shared),
-
WebBrowsable(true), WebDisplayName("Picture Library"),
-
WebDescription("Library to use")]
-
public string AdsLibraryName
-
{
-
get { return adsLibraryName; }
-
set { adsLibraryName = value; }
-
}
-
protected override void CreateChildControls()
-
{
-
base.CreateChildControls();
-
try
-
{
-
if (string.IsNullOrEmpty(adsLibraryName))
-
return;
-
SPWeb web = SPContext.Current.Web;
-
SPList list = web.Lists[adsLibraryName];
-
if (list == null)
-
throw new Exception("The Picture Library [" + adsLibraryName + "] could not be found.");
-
Random rnd = new Random();
-
int resourceIndex = rnd.Next(list.ItemCount);
-
SPListItem li = list.Items[resourceIndex];
-
string webUrl = web.ServerRelativeUrl;
-
if (webUrl != "/")
-
{
-
webUrl = webUrl + "/";
-
}
-
Image imgControl = new Image();
-
imgControl.ImageUrl = webUrl + li.Url;
-
imgControl.ToolTip = li.Title;
-
HyperLink hl = new HyperLink();
-
hl.NavigateUrl = li.Title;
-
hl.Target = "_blank";
-
hl.Controls.Add(imgControl);
-
this.Controls.Add(hl);
-
}
-
catch (Exception ex)
-
{
-
Label label = new Label();
-
label.Text = ex.Message;
-
this.Controls.Add(label);
-
}
-
}
-
}
-
}
Remember to add it to safecontrols in web.config
<
SafeControl Assembly="AdRotatorPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5" Namespace="MyWSSParts" TypeName="*" Safe="True" AllowRemoteDesigner="True" />