AdRotator.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. //
  2. // System.Web.UI.WebControls.AdRotator.cs
  3. //
  4. // Authors:
  5. // Gaurav Vaish ([email protected])
  6. // Gonzalo Paniagua Javier ([email protected])
  7. // Andreas Nahr ([email protected])
  8. //
  9. // (c) 2002 Ximian, Inc. (http://www.ximian.com)
  10. // (C) Gaurav Vaish (2002)
  11. // (C) 2003 Andreas Nahr
  12. //
  13. //
  14. // Permission is hereby granted, free of charge, to any person obtaining
  15. // a copy of this software and associated documentation files (the
  16. // "Software"), to deal in the Software without restriction, including
  17. // without limitation the rights to use, copy, modify, merge, publish,
  18. // distribute, sublicense, and/or sell copies of the Software, and to
  19. // permit persons to whom the Software is furnished to do so, subject to
  20. // the following conditions:
  21. //
  22. // The above copyright notice and this permission notice shall be
  23. // included in all copies or substantial portions of the Software.
  24. //
  25. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  26. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  28. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  29. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  30. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  31. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. //
  33. using System;
  34. using System.IO;
  35. using System.Collections;
  36. using System.Collections.Specialized;
  37. using System.Web;
  38. using System.Web.Caching;
  39. using System.Web.UI;
  40. using System.Xml;
  41. using System.Web.Util;
  42. using System.ComponentModel;
  43. using System.ComponentModel.Design;
  44. namespace System.Web.UI.WebControls
  45. {
  46. [DefaultEvent("AdCreated")]
  47. [DefaultProperty("AdvertisementFile")]
  48. [Designer ("System.Web.UI.Design.WebControls.AdRotatorDesigner, " + Consts.AssemblySystem_Design, typeof (IDesigner))]
  49. [ToolboxData("<{0}:AdRotator runat=\"server\" Height=\"60px\" "
  50. + "Width=\"468\"></{0}:AdRotator>")]
  51. public class AdRotator: WebControl
  52. {
  53. string advertisementFile;
  54. static readonly object AdCreatedEvent = new object();
  55. // Will be set values during (On)PreRender-ing
  56. string alternateText;
  57. string imageUrl;
  58. string navigateUrl;
  59. string fileDirectory;
  60. Random random;
  61. public AdRotator ()
  62. {
  63. advertisementFile = "";
  64. fileDirectory = null;
  65. }
  66. AdRecord[] LoadAdFile (string file)
  67. {
  68. Stream fStream;
  69. try {
  70. fStream = new FileStream (file, FileMode.Open, FileAccess.Read, FileShare.Read);
  71. } catch (Exception e) {
  72. throw new HttpException("AdRotator: Unable to open file", e);
  73. }
  74. ArrayList list = new ArrayList ();
  75. try {
  76. IDictionary hybridDict = null;
  77. XmlDocument document = new XmlDocument ();
  78. document.Load (fStream);
  79. XmlElement docElem = document.DocumentElement;
  80. if (docElem == null)
  81. throw new HttpException ("No advertisements found");
  82. if (docElem.LocalName != "Advertisements")
  83. throw new HttpException ("No advertisements found: invalid document element");
  84. XmlNode node = docElem.FirstChild;
  85. while (node != null) {
  86. if (node.LocalName == "Ad") {
  87. XmlNode innerNode = node.FirstChild;
  88. while (innerNode != null) {
  89. if (node.NodeType == XmlNodeType.Element) {
  90. if (hybridDict == null)
  91. hybridDict = new HybridDictionary ();
  92. hybridDict.Add (innerNode.LocalName, innerNode.InnerText);
  93. }
  94. innerNode = innerNode.NextSibling;
  95. }
  96. if (hybridDict != null) {
  97. list.Add (hybridDict);
  98. hybridDict = null;
  99. }
  100. }
  101. node = node.NextSibling;
  102. }
  103. } catch(Exception e) {
  104. throw new HttpException("Parse error:" + file, e);
  105. } finally {
  106. if (fStream != null)
  107. fStream.Close();
  108. }
  109. if (list.Count == 0)
  110. throw new HttpException ("No advertisements found");
  111. AdRecord [] adsArray = new AdRecord [list.Count];
  112. int count = list.Count;
  113. for (int i = 0; i < count; i++)
  114. adsArray [i] = new AdRecord ((IDictionary) list [i]);
  115. return adsArray;
  116. }
  117. AdRecord [] GetData (string file)
  118. {
  119. string physPath = MapPathSecure (file);
  120. string AdKey = "AdRotatorCache: " + physPath;
  121. fileDirectory = UrlUtils.GetDirectory (UrlUtils.Combine (TemplateSourceDirectory, file));
  122. Cache cache = HttpRuntime.Cache;
  123. AdRecord[] records = (AdRecord[]) cache [AdKey];
  124. if (records == null) {
  125. records = LoadAdFile (physPath);
  126. cache.Insert (AdKey, records, new CacheDependency (physPath));
  127. }
  128. return records;
  129. }
  130. IDictionary SelectAd ()
  131. {
  132. AdRecord[] records = GetData (AdvertisementFile);
  133. if (records == null || records.Length ==0)
  134. return null;
  135. int impressions = 0;
  136. int rlength = records.Length;
  137. for (int i=0 ; i < rlength; i++) {
  138. if (IsAdMatching (records [i]))
  139. impressions += records [i].Hits;
  140. }
  141. if (impressions == 0)
  142. return null;
  143. if (random == null)
  144. random = new Random ();
  145. int rnd = random.Next (impressions) + 1;
  146. int counter = 0;
  147. int index = 0;
  148. for (int i = 0; i < rlength; i++) {
  149. if(IsAdMatching(records[i])) {
  150. if (rnd <= (counter + records [i].Hits)) {
  151. index = i;
  152. break;
  153. }
  154. counter += records [i].Hits;
  155. }
  156. }
  157. return records [index].Properties;
  158. }
  159. private bool IsAdMatching (AdRecord currAd)
  160. {
  161. if (KeywordFilter != String.Empty)
  162. return (0 == String.Compare (currAd.Keyword, KeywordFilter, true));
  163. return true;
  164. }
  165. private string ResolveAdUrl (string relativeUrl)
  166. {
  167. if (relativeUrl.Length==0 || !UrlUtils.IsRelativeUrl (relativeUrl))
  168. return relativeUrl;
  169. string fullUrl;
  170. if (fileDirectory != null)
  171. fullUrl = fileDirectory;
  172. else
  173. fullUrl = TemplateSourceDirectory;
  174. if (fullUrl.Length == 0)
  175. return relativeUrl;
  176. return UrlUtils.Combine (fullUrl, relativeUrl);
  177. }
  178. [WebCategory("Action")]
  179. [WebSysDescription("AdRotator_OnAdCreated")]
  180. public event AdCreatedEventHandler AdCreated {
  181. add { Events.AddHandler (AdCreatedEvent, value); }
  182. remove { Events.RemoveHandler (AdCreatedEvent, value); }
  183. }
  184. [Bindable(true)]
  185. [DefaultValue("")]
  186. [Editor ("System.Web.UI.Design.XmlUrlEditor, " + Consts.AssemblySystem_Design, typeof (System.Drawing.Design.UITypeEditor))]
  187. [WebCategory("Behaviour")]
  188. [WebSysDescription("AdRotator_AdvertisementFile")]
  189. public string AdvertisementFile {
  190. get { return ((advertisementFile != null) ? advertisementFile : ""); }
  191. set { advertisementFile = value; }
  192. }
  193. [Browsable (false), EditorBrowsable (EditorBrowsableState.Never)]
  194. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  195. public override FontInfo Font {
  196. get { return base.Font; }
  197. }
  198. [Bindable(true)]
  199. [DefaultValue("")]
  200. [WebCategory("Behaviour")]
  201. [WebSysDescription("AdRotator_KeywordFilter")]
  202. public string KeywordFilter {
  203. get {
  204. object o = ViewState ["KeywordFilter"];
  205. if (o != null)
  206. return (string) o;
  207. return String.Empty;
  208. }
  209. set {
  210. if(value != null)
  211. ViewState ["KeywordFilter"] = value.Trim ();
  212. }
  213. }
  214. [Bindable(true)]
  215. [DefaultValue("")]
  216. [TypeConverter(typeof(TargetConverter))]
  217. [WebCategory("Behaviour")]
  218. [WebSysDescription("AdRotator_Target")]
  219. public string Target {
  220. get {
  221. object o = ViewState ["Target"];
  222. if (o != null)
  223. return (string) o;
  224. return "_top";
  225. }
  226. set {
  227. ViewState["Target"] = value;
  228. }
  229. }
  230. protected override ControlCollection CreateControlCollection ()
  231. {
  232. return new EmptyControlCollection (this);
  233. }
  234. protected virtual void OnAdCreated (AdCreatedEventArgs e)
  235. {
  236. if (Events == null)
  237. return;
  238. AdCreatedEventHandler aceh = (AdCreatedEventHandler) Events [AdCreatedEvent];
  239. if (aceh != null)
  240. aceh (this, e);
  241. }
  242. protected override void OnPreRender (EventArgs e)
  243. {
  244. if(AdvertisementFile == String.Empty)
  245. return;
  246. AdCreatedEventArgs acea = new AdCreatedEventArgs (SelectAd ());
  247. OnAdCreated (acea);
  248. imageUrl = acea.ImageUrl;
  249. navigateUrl = acea.NavigateUrl;
  250. alternateText = acea.AlternateText;
  251. }
  252. protected override void Render (HtmlTextWriter writer)
  253. {
  254. HyperLink hLink = new HyperLink ();
  255. Image adImage = new Image();
  256. foreach (string current in Attributes.Keys)
  257. hLink.Attributes [current] = Attributes [current];
  258. if (ID != null && ID.Length > 0)
  259. hLink.ID = ID;
  260. hLink.Target = Target;
  261. hLink.AccessKey = AccessKey;
  262. hLink.Enabled = Enabled;
  263. hLink.TabIndex = TabIndex;
  264. if (navigateUrl != null && navigateUrl.Length != 0)
  265. hLink.NavigateUrl = ResolveAdUrl (navigateUrl);
  266. hLink.RenderBeginTag (writer);
  267. if (ControlStyleCreated)
  268. adImage.ApplyStyle(ControlStyle);
  269. if(imageUrl!=null && imageUrl.Length > 0)
  270. adImage.ImageUrl = ResolveAdUrl (imageUrl);
  271. adImage.AlternateText = alternateText;
  272. adImage.ToolTip = ToolTip;
  273. adImage.RenderControl (writer);
  274. hLink.RenderEndTag (writer);
  275. }
  276. class AdRecord
  277. {
  278. public IDictionary Properties;
  279. public int Hits; // or impressions or clicks
  280. public string Keyword;
  281. public AdRecord (IDictionary adProps)
  282. {
  283. this.Properties = adProps;
  284. Keyword = Properties ["Keyword"] as string;
  285. if (Keyword == null)
  286. Keyword = "";
  287. string imp = Properties ["Impressions"] as string;
  288. Hits = 1;
  289. if (imp != null) {
  290. try {
  291. Hits = Int32.Parse (imp);
  292. } catch {
  293. }
  294. }
  295. }
  296. }
  297. }
  298. }