次の方法で共有


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:

  1. namespace MyWSSParts
  2. {
  3.     [Guid("815fbeb7-c1d2-46bb-b5cb-ef3db15c474f")]
  4.     public class AdRotatorPart : WebPart
  5.     {
  6.         public AdRotatorPart()
  7.         {
  8.             this.ExportMode = WebPartExportMode.All;
  9.         }
  10.         private string adsLibraryName = string.Empty;
  11.         [Personalizable(true), WebPartStorage(Storage.Shared),
  12.          WebBrowsable(true), WebDisplayName("Picture Library"),
  13.          WebDescription("Library to use")]
  14.         public string AdsLibraryName
  15.         {
  16.             get { return adsLibraryName; }
  17.             set { adsLibraryName = value; }
  18.         }
  19.         protected override void CreateChildControls()
  20.         {
  21.             base.CreateChildControls();
  22.             try
  23.             {
  24.                 if (string.IsNullOrEmpty(adsLibraryName))
  25.                     return;
  26.                 SPWeb web = SPContext.Current.Web;
  27.                 SPList list = web.Lists[adsLibraryName];
  28.                 if (list == null)
  29.                     throw new Exception("The Picture Library [" + adsLibraryName + "] could not be found.");
  30.                 Random rnd = new Random();
  31.                 int resourceIndex = rnd.Next(list.ItemCount);
  32.                 SPListItem li = list.Items[resourceIndex];
  33.                 string webUrl = web.ServerRelativeUrl;
  34.                 if (webUrl != "/")
  35.                 {
  36.                     webUrl = webUrl + "/";
  37.                 }
  38.                 Image imgControl = new Image();
  39.                 imgControl.ImageUrl = webUrl + li.Url;
  40.                 imgControl.ToolTip = li.Title;
  41.                 HyperLink hl = new HyperLink();
  42.                 hl.NavigateUrl = li.Title;
  43.                 hl.Target = "_blank";
  44.                 hl.Controls.Add(imgControl);
  45.                 this.Controls.Add(hl);
  46.             }
  47.             catch (Exception ex)
  48.             {
  49.                 Label label = new Label();
  50.                 label.Text = ex.Message;
  51.                 this.Controls.Add(label);
  52.             }
  53.         }
  54.     }
  55. }

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" />

Comments