PageRenderTime 72ms CodeModel.GetById 59ms app.highlight 11ms RepoModel.GetById 1ms app.codeStats 0ms

/mcs/class/System.Web/System.Web.UI.WebControls/AdRotator.cs

https://github.com/pruiz/mono
C# | 310 lines | 223 code | 48 blank | 39 comment | 32 complexity | a15d49b1ec9170bbefc195c3e0696984 MD5 | raw file
Possible License(s): LGPL-2.0, MPL-2.0-no-copyleft-exception, CC-BY-SA-3.0, GPL-2.0
  1// 
  2// System.Web.UI.WebControls.AdRotator
  3//
  4// Author:
  5//        Ben Maurer <bmaurer@novell.com>
  6//
  7// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
  8//
  9// Permission is hereby granted, free of charge, to any person obtaining
 10// a copy of this software and associated documentation files (the
 11// "Software"), to deal in the Software without restriction, including
 12// without limitation the rights to use, copy, modify, merge, publish,
 13// distribute, sublicense, and/or sell copies of the Software, and to
 14// permit persons to whom the Software is furnished to do so, subject to
 15// the following conditions:
 16// 
 17// The above copyright notice and this permission notice shall be
 18// included in all copies or substantial portions of the Software.
 19// 
 20// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 21// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 22// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 23// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 24// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 25// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 26// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 27//
 28
 29using System.Xml;
 30using System.Collections;
 31using System.ComponentModel;
 32using System.Security.Permissions;
 33using System.Web.Util;
 34
 35namespace System.Web.UI.WebControls
 36{
 37	// CAS
 38	[AspNetHostingPermissionAttribute (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
 39	[AspNetHostingPermissionAttribute (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
 40	// attributes
 41	[DefaultEvent("AdCreated")]
 42	[DefaultProperty("AdvertisementFile")]
 43	[Designer("System.Web.UI.Design.WebControls.AdRotatorDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
 44	[ToolboxData("<{0}:AdRotator runat=\"server\"></{0}:AdRotator>")]
 45	public class AdRotator : DataBoundControl
 46	{
 47		AdCreatedEventArgs createdargs;
 48		ArrayList ads = new ArrayList ();
 49		string ad_file = String.Empty;
 50
 51		protected internal override void OnInit (EventArgs e)
 52		{
 53			base.OnInit(e);
 54		}
 55
 56		protected internal override void OnPreRender (EventArgs e)
 57		{
 58			Hashtable ht = null;
 59			
 60			if (!String.IsNullOrEmpty (ad_file)) {
 61				ReadAdsFromFile (GetPhysicalFilePath (ad_file));
 62				ht = ChooseAd ();
 63			}
 64
 65		 	AdCreatedEventArgs ev = new AdCreatedEventArgs (ht);
 66			OnAdCreated (ev);
 67			createdargs = ev;
 68			
 69		}
 70
 71		[MonoTODO ("Not implemented")]
 72		protected internal override void PerformDataBinding (IEnumerable data)
 73		{
 74			throw new NotImplementedException ();
 75		}
 76
 77		[MonoTODO ("Not implemented")]
 78		protected override void PerformSelect ()
 79		{
 80			throw new NotImplementedException ();
 81		}
 82
 83		protected internal override void Render (HtmlTextWriter writer)
 84		{
 85			AdCreatedEventArgs e = createdargs;
 86
 87			base.AddAttributesToRender (writer);
 88
 89			if (e.NavigateUrl != null && e.NavigateUrl.Length > 0)
 90				writer.AddAttribute (HtmlTextWriterAttribute.Href, ResolveAdUrl (e.NavigateUrl));
 91			if (Target != null && Target.Length > 0)
 92				writer.AddAttribute (HtmlTextWriterAttribute.Target, Target);
 93			
 94			writer.RenderBeginTag (HtmlTextWriterTag.A);
 95
 96			if (e.ImageUrl != null && e.ImageUrl.Length > 0)
 97				writer.AddAttribute (HtmlTextWriterAttribute.Src, ResolveAdUrl (e.ImageUrl));
 98
 99			writer.AddAttribute (HtmlTextWriterAttribute.Alt, e.AlternateText == null ? String.Empty : e.AlternateText);
100			writer.AddAttribute (HtmlTextWriterAttribute.Border, "0", false);
101			writer.RenderBeginTag (HtmlTextWriterTag.Img);
102			writer.RenderEndTag (); // img
103			writer.RenderEndTag (); // a
104		}
105
106		string ResolveAdUrl (string url)
107		{
108			string path = url;
109
110			if (AdvertisementFile != null && AdvertisementFile.Length > 0 && path [0] != '/' && path [0] != '~')
111				try {
112					new Uri (path);
113				}
114				catch {
115					return UrlUtils.Combine (UrlUtils.GetDirectory (ResolveUrl (AdvertisementFile)), path);
116				}
117			
118			return ResolveUrl (path);
119		}
120
121		//
122		// We take all the ads in the ad file and add up their
123		// impression weight. We then take a random number [0,
124		// TotalImpressions). We then choose the ad that is
125		// that number or less impressions for the beginning
126		// of the file. This lets us respect the weights
127		// given.
128		//
129		Hashtable ChooseAd ()
130		{
131			// cache for performance
132			string KeywordFilter = this.KeywordFilter;
133			
134			int total_imp = 0;
135			int cur_imp = 0;
136			bool keywordFilterEmpty = KeywordFilter.Length == 0;
137			
138			foreach (Hashtable a in ads) {
139				if (keywordFilterEmpty || KeywordFilter == (string) a ["Keyword"])
140					total_imp += a ["Impressions"] != null ? int.Parse ((string) a ["Impressions"]) : 1;
141			}
142
143			int r = new Random ().Next (total_imp);
144
145			foreach (Hashtable a in ads) {
146				if (!keywordFilterEmpty && KeywordFilter != (string) a ["Keyword"])
147					continue;
148				cur_imp += a ["Impressions"] != null ? int.Parse ((string) a ["Impressions"]) : 1;
149				
150				if (cur_imp > r)
151					return a;
152			}
153
154			if (total_imp != 0)
155				throw new Exception ("I should only get here if no ads matched");
156			
157			return null;
158		}
159		
160		void ReadAdsFromFile (string s)
161		{
162			XmlDocument d = new XmlDocument ();
163			try {
164				d.Load (s);
165			} catch (Exception e) {
166				throw new HttpException ("AdRotator could not parse the xml file", e);
167			}
168			
169			ads.Clear ();
170			
171			foreach (XmlNode n in d.DocumentElement.ChildNodes) {
172
173				Hashtable ad = new Hashtable ();
174				
175				foreach (XmlNode nn in n.ChildNodes)
176					ad.Add (nn.Name, nn.InnerText);
177				
178				ads.Add (ad);
179			}
180		}
181
182
183		[UrlProperty]
184		[Bindable(true)]
185		[DefaultValue("")]
186		[Editor("System.Web.UI.Design.XmlUrlEditor, " + Consts.AssemblySystem_Design, typeof(System.Drawing.Design.UITypeEditor))]
187		[WebSysDescription("")]
188		[WebCategory("Behavior")]
189		public string AdvertisementFile {
190			get {
191				return ad_file;
192			}
193			set {
194				ad_file = value;
195			}
196			
197		}
198
199		[DefaultValue ("AlternateText")]
200		[WebSysDescriptionAttribute ("")]
201		[WebCategoryAttribute ("Behavior")]
202		[MonoTODO ("Not implemented")]
203		public string AlternateTextField 
204		{
205			get {
206				throw new NotImplementedException ();
207			}
208			set {
209				throw new NotImplementedException ();
210			}
211		}
212		
213		[Browsable(false)]
214		[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
215		[EditorBrowsable(EditorBrowsableState.Never)]
216		public override FontInfo Font {
217			get {
218				return base.Font;
219			}
220		}
221
222		[DefaultValue ("ImageUrl")]
223		[MonoTODO ("Not implemented")]
224		[WebSysDescriptionAttribute ("")]
225		[WebCategoryAttribute ("Behavior")]
226		public string ImageUrlField 
227		{
228			get {
229				throw new NotImplementedException ();
230			}
231			set {
232				throw new NotImplementedException ();
233			}
234		}
235
236		[Bindable(true)]
237		[DefaultValue("")]
238		[WebSysDescription("")]
239		[WebCategory("Behavior")]
240		public string KeywordFilter {
241			get {
242				return ViewState.GetString ("KeywordFilter", String.Empty);
243			}
244			set {
245				ViewState ["KeywordFilter"] = value;
246			}
247			
248		}
249
250		[DefaultValue ("NavigateUrl")]
251		[MonoTODO ("Not implemented")]
252		[WebSysDescriptionAttribute ("")]
253		[WebCategoryAttribute ("Behavior")]
254		public string NavigateUrlField 
255		{
256			get {
257				throw new NotImplementedException ();
258			}
259			set {
260				throw new NotImplementedException ();
261			}
262		}
263		
264		[Bindable(true)]
265		[DefaultValue("_top")]
266		[TypeConverter(typeof(System.Web.UI.WebControls.TargetConverter))]
267		[WebSysDescription("")]
268		[WebCategory("Behavior")]
269		public string Target {
270			get {
271				return ViewState.GetString ("Target", "_top");
272			}
273			set {
274				ViewState ["Target"] = value;
275			}
276			
277		}
278
279		/* all these are listed in corcompare */
280		public override string UniqueID
281		{
282			get {
283				return base.UniqueID;
284			}
285		}
286
287		protected override HtmlTextWriterTag TagKey 
288		{
289			get {
290				return base.TagKey;
291			}
292		}
293	
294		protected virtual void OnAdCreated (AdCreatedEventArgs e)
295		{
296			AdCreatedEventHandler h = (AdCreatedEventHandler) Events [AdCreatedEvent];
297			if (h != null)
298				h (this, e);
299		}
300
301		static readonly object AdCreatedEvent = new object ();
302
303		[WebSysDescription("")]
304		[WebCategory("Action")]
305		public event AdCreatedEventHandler AdCreated {
306			add { Events.AddHandler (AdCreatedEvent, value); }
307			remove { Events.RemoveHandler (AdCreatedEvent, value); }
308		}
309	}
310}