2 // System.Web.UI.WebControls.AdRotator.cs
5 // Gaurav Vaish (gvaish@iitk.ac.in)
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // Andreas Nahr (ClassDevelopment@A-SoftTech.com)
9 // (c) 2002 Ximian, Inc. (http://www.ximian.com)
10 // (C) Gaurav Vaish (2002)
11 // (C) 2003 Andreas Nahr
16 using System.Collections;
17 using System.Collections.Specialized;
19 using System.Web.Caching;
22 using System.Web.Util;
23 using System.ComponentModel;
24 using System.ComponentModel.Design;
26 namespace System.Web.UI.WebControls
28 [DefaultEvent("AdCreated")]
29 [DefaultProperty("AdvertisementFile")]
30 [Designer ("System.Web.UI.Design.WebControls.AdRotatorDesigner, " + Consts.AssemblySystem_Design, typeof (IDesigner))]
31 [ToolboxData("<{0}:AdRotator runat=\"server\" Height=\"60px\" "
32 + "Width=\"468\"></{0}:AdRotator>")]
33 public class AdRotator: WebControl
35 string advertisementFile;
36 static readonly object AdCreatedEvent = new object();
38 // Will be set values during (On)PreRender-ing
47 advertisementFile = "";
51 AdRecord[] LoadAdFile (string file)
55 fStream = new FileStream (file, FileMode.Open, FileAccess.Read, FileShare.Read);
56 } catch (Exception e) {
57 throw new HttpException("AdRotator: Unable to open file", e);
60 ArrayList list = new ArrayList ();
62 IDictionary hybridDict = null;
63 XmlDocument document = new XmlDocument ();
64 document.Load (fStream);
66 XmlElement docElem = document.DocumentElement;
69 throw new HttpException ("No advertisements found");
71 if (docElem.LocalName != "Advertisements")
72 throw new HttpException ("No advertisements found: invalid document element");
74 XmlNode node = docElem.FirstChild;
75 while (node != null) {
76 if (node.LocalName == "Ad") {
77 XmlNode innerNode = node.FirstChild;
78 while (innerNode != null) {
79 if (node.NodeType == XmlNodeType.Element) {
80 if (hybridDict == null)
81 hybridDict = new HybridDictionary ();
83 hybridDict.Add (innerNode.LocalName, innerNode.InnerText);
85 innerNode = innerNode.NextSibling;
88 if (hybridDict != null) {
89 list.Add (hybridDict);
93 node = node.NextSibling;
96 } catch(Exception e) {
97 throw new HttpException("Parse error:" + file, e);
104 throw new HttpException ("No advertisements found");
106 AdRecord [] adsArray = new AdRecord [list.Count];
107 int count = list.Count;
108 for (int i = 0; i < count; i++)
109 adsArray [i] = new AdRecord ((IDictionary) list [i]);
114 AdRecord [] GetData (string file)
116 string physPath = MapPathSecure (file);
117 string AdKey = "AdRotatorCache: " + physPath;
118 fileDirectory = UrlUtils.GetDirectory (UrlUtils.Combine (TemplateSourceDirectory, file));
119 Cache cache = HttpRuntime.Cache;
120 AdRecord[] records = (AdRecord[]) cache [AdKey];
121 if (records == null) {
122 records = LoadAdFile (physPath);
123 cache.Insert (AdKey, records, new CacheDependency (physPath));
129 IDictionary SelectAd ()
131 AdRecord[] records = GetData (AdvertisementFile);
132 if (records == null || records.Length ==0)
136 int rlength = records.Length;
137 for (int i=0 ; i < rlength; i++) {
138 if (IsAdMatching (records [i]))
139 impressions += records [i].Hits;
142 if (impressions == 0)
146 random = new Random ();
148 int rnd = random.Next (impressions) + 1;
151 for (int i = 0; i < rlength; i++) {
152 if(IsAdMatching(records[i])) {
153 if (rnd <= (counter + records [i].Hits)) {
157 counter += records [i].Hits;
161 return records [index].Properties;
164 private bool IsAdMatching (AdRecord currAd)
166 if (KeywordFilter != String.Empty)
167 return (0 == String.Compare (currAd.Keyword, KeywordFilter, true));
172 private string ResolveAdUrl (string relativeUrl)
174 if (relativeUrl.Length==0 || !UrlUtils.IsRelativeUrl (relativeUrl))
178 if (fileDirectory != null)
179 fullUrl = fileDirectory;
181 fullUrl = TemplateSourceDirectory;
183 if (fullUrl.Length == 0)
186 return UrlUtils.Combine (fullUrl, relativeUrl);
189 [WebCategory("Action")]
190 [WebSysDescription("AdRotator_OnAdCreated")]
191 public event AdCreatedEventHandler AdCreated {
192 add { Events.AddHandler (AdCreatedEvent, value); }
193 remove { Events.RemoveHandler (AdCreatedEvent, value); }
198 [Editor ("System.Web.UI.Design.XmlUrlEditor, " + Consts.AssemblySystem_Design, typeof (System.Drawing.Design.UITypeEditor))]
199 [WebCategory("Behaviour")]
200 [WebSysDescription("AdRotator_AdvertisementFile")]
201 public string AdvertisementFile {
202 get { return ((advertisementFile != null) ? advertisementFile : ""); }
203 set { advertisementFile = value; }
206 [Browsable (false), EditorBrowsable (EditorBrowsableState.Never)]
207 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
208 public override FontInfo Font {
209 get { return base.Font; }
214 [WebCategory("Behaviour")]
215 [WebSysDescription("AdRotator_KeywordFilter")]
216 public string KeywordFilter {
218 object o = ViewState ["KeywordFilter"];
226 ViewState ["KeywordFilter"] = value.Trim ();
232 [TypeConverter(typeof(TargetConverter))]
233 [WebCategory("Behaviour")]
234 [WebSysDescription("AdRotator_Target")]
235 public string Target {
237 object o = ViewState ["Target"];
244 ViewState["Target"] = value;
248 protected override ControlCollection CreateControlCollection ()
250 return new EmptyControlCollection (this);
253 protected virtual void OnAdCreated (AdCreatedEventArgs e)
258 AdCreatedEventHandler aceh = (AdCreatedEventHandler) Events [AdCreatedEvent];
263 protected override void OnPreRender (EventArgs e)
265 if(AdvertisementFile == String.Empty)
268 AdCreatedEventArgs acea = new AdCreatedEventArgs (SelectAd ());
270 imageUrl = acea.ImageUrl;
271 navigateUrl = acea.NavigateUrl;
272 alternateText = acea.AlternateText;
275 protected override void Render (HtmlTextWriter writer)
277 HyperLink hLink = new HyperLink ();
278 Image adImage = new Image();
279 foreach (string current in Attributes.Keys)
280 hLink.Attributes [current] = Attributes [current];
282 if (ID != null && ID.Length > 0)
285 hLink.Target = Target;
286 hLink.AccessKey = AccessKey;
287 hLink.Enabled = Enabled;
288 hLink.TabIndex = TabIndex;
289 if (navigateUrl != null && navigateUrl.Length != 0)
290 hLink.NavigateUrl = ResolveAdUrl (navigateUrl);
292 hLink.RenderBeginTag (writer);
293 if (ControlStyleCreated)
294 adImage.ApplyStyle(ControlStyle);
296 if(imageUrl!=null && imageUrl.Length > 0)
297 adImage.ImageUrl = ResolveAdUrl (imageUrl);
299 adImage.AlternateText = alternateText;
300 adImage.ToolTip = ToolTip;
301 adImage.RenderControl (writer);
302 hLink.RenderEndTag (writer);
307 public IDictionary Properties;
308 public int Hits; // or impressions or clicks
309 public string Keyword;
311 public AdRecord (IDictionary adProps)
313 this.Properties = adProps;
314 Keyword = Properties ["Keyword"] as string;
318 string imp = Properties ["Impressions"] as string;
322 Hits = Int32.Parse (imp);