AdRotator.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. /**
  2. * Namespace: System.Web.UI.WebControls
  3. * Class: AdRotator
  4. *
  5. * Author: Gaurav Vaish
  6. * Maintainer: [email protected]
  7. * Implementation: yes
  8. * Contact: <[email protected]>
  9. * Status: 100%
  10. *
  11. * (C) Gaurav Vaish (2001)
  12. */
  13. using System;
  14. using System.IO;
  15. using System.Collections;
  16. using System.Collections.Specialized;
  17. using System.Web;
  18. using System.Web.Caching;
  19. using System.Web.UI;
  20. using System.Xml;
  21. using System.Web.Utils;
  22. using System.ComponentModel;
  23. namespace System.Web.UI.WebControls
  24. {
  25. [DefaultEvent("AdCreated")]
  26. [DefaultProperty("AdvertisementFile")]
  27. //TODO: [Designer("??")]
  28. [ToolboxData("<{0}:AdRotator runat=\"server\" Height=\"60px\" "
  29. + "Width=\"468\"></{0}:AdRotator>")]
  30. public class AdRotator: WebControl
  31. {
  32. private string advertisementFile;
  33. private static readonly object AdCreatedEvent = new object();
  34. // Will be set values during (On)PreRender-ing
  35. private string alternateText;
  36. private string imageUrl;
  37. private string navigateUrl;
  38. private string fileDirectory;
  39. class AdRecord
  40. {
  41. public IDictionary adProps;
  42. public int hits; // or impressions or clicks
  43. public string keyword;
  44. public AdRecord(IDictionary adProps)
  45. {
  46. this.adProps = adProps;
  47. hits = 0;
  48. keyword = String.Empty;
  49. }
  50. }
  51. /*
  52. * Loading / Saving data from/to ad file and all the manipulations wrt to the URL...
  53. * are incorporated by the following functions.
  54. * GetData(string)
  55. * LoadAdFile(string)
  56. * IsAdMatching(AdRecord)
  57. * ResolveAdUrl(string)
  58. * SelectAd()
  59. * The exact control flow will be detailed. Let me first write the functions
  60. */
  61. private AdRecord[] LoadAdFile(string file)
  62. {
  63. Stream fStream;
  64. ArrayList list;
  65. XmlReader reader;
  66. XmlDocument document;
  67. XmlNode topNode, innerNode;
  68. IDictionary hybridDict = null;
  69. AdRecord[] adsArray = null;
  70. try
  71. {
  72. fStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read);
  73. } catch(Exception e)
  74. {
  75. throw new HttpException("AdRotator: Unable to open file");
  76. }
  77. try
  78. {
  79. list = new ArrayList();
  80. reader = new XmlTextReader(fStream);
  81. document = new XmlDocument();
  82. document.Load(reader);
  83. if(document.DocumentElement!=null)
  84. {
  85. if(document.DocumentElement.LocalName=="Advertisements")
  86. {
  87. topNode = document.DocumentElement.FirstChild;
  88. while(topNode!=null)
  89. {
  90. if(topNode.LocalName=="Ad")
  91. {
  92. innerNode = topNode.FirstChild;
  93. while(innerNode!=null)
  94. {
  95. if(innerNode.NodeType==XmlNodeType.Element)
  96. {
  97. if(hybridDict==null)
  98. {
  99. hybridDict = new HybridDictionary();
  100. }
  101. hybridDict.Add(innerNode.LocalName, innerNode.InnerText);
  102. }
  103. innerNode = innerNode.NextSibling;
  104. }
  105. if(hybridDict!=null)
  106. list.Add(hybridDict);
  107. }
  108. topNode = topNode.NextSibling;
  109. }
  110. }
  111. }
  112. if(list.Count>0)
  113. {
  114. adsArray = new AdRecord[list.Count];
  115. for(int i=0; i < list.Count; i++)
  116. {
  117. adsArray[i] = new AdRecord((IDictionary)list[i]);
  118. }
  119. }
  120. } catch(Exception e)
  121. {
  122. throw new HttpException("AdRotator_Parse_Error" + file);
  123. } finally
  124. {
  125. fStream.Close();
  126. }
  127. if(adsArray == null)
  128. {
  129. throw new HttpException("AdRotator_No_Advertisements_Found");
  130. }
  131. return adsArray;
  132. }
  133. [MonoTODO("CacheDependency does nothing")]
  134. private AdRecord[] GetData(string file)
  135. {
  136. string physPath = MapPathSecure(file);
  137. string AdKey = "AdRotatorCache: " + physPath;
  138. fileDirectory = UrlUtils.GetDirectory(UrlUtils.Combine(TemplateSourceDirectory, file));
  139. Cache cache = HttpRuntime.Cache;
  140. AdRecord[] records = (AdRecord[])cache[AdKey];
  141. if(records==null)
  142. {
  143. records = LoadAdFile(physPath);
  144. if(records==null)
  145. {
  146. return null;
  147. }
  148. cache.Insert(AdKey, records, new CacheDependency(physPath));
  149. }
  150. return records;
  151. }
  152. private IDictionary SelectAd()
  153. {
  154. AdRecord[] records = GetData(AdvertisementFile);
  155. if(records!=null && records.Length!=0)
  156. {
  157. int impressions = 0;
  158. for(int i=0 ; i < records.Length; i++)
  159. {
  160. if(IsAdMatching(records[i]))
  161. impressions += records[i].hits;
  162. }
  163. if(impressions!=0)
  164. {
  165. int rnd = (new Random()).Next(impressions) + 1;
  166. int counter = 0;
  167. int index = 0;
  168. for(int i=0; i < records.Length; i++)
  169. {
  170. if(IsAdMatching(records[i]))
  171. {
  172. if(rnd <= (counter + records[i].hits))
  173. {
  174. index = i;
  175. break;
  176. }
  177. counter += records[i].hits;
  178. }
  179. }
  180. return records[index].adProps;
  181. }
  182. //FIXME: the line below added. Where should i init hits to make
  183. //impressions not be 0?
  184. return records [0].adProps;
  185. }
  186. return null;
  187. }
  188. private bool IsAdMatching(AdRecord currAd)
  189. {
  190. if (KeywordFilter != String.Empty)
  191. return (0 == String.Compare (currAd.keyword, KeywordFilter, true));
  192. return true;
  193. }
  194. private string ResolveAdUrl(string relativeUrl)
  195. {
  196. if(relativeUrl.Length==0 || !UrlUtils.IsRelativeUrl(relativeUrl))
  197. return relativeUrl;
  198. string fullUrl = String.Empty;
  199. if(fileDirectory != null)
  200. fullUrl = fileDirectory;
  201. if(fullUrl.Length == 0)
  202. fullUrl = TemplateSourceDirectory;
  203. if(fullUrl.Length == 0)
  204. return relativeUrl;
  205. return (fullUrl + relativeUrl);
  206. }
  207. [WebCategory("Action")]
  208. [WebSysDescription("AdRotator_OnAdCreated")]
  209. public event AdCreatedEventHandler AdCreated
  210. {
  211. add
  212. {
  213. Events.AddHandler(AdCreatedEvent, value);
  214. }
  215. remove
  216. {
  217. Events.RemoveHandler(AdCreatedEvent, value);
  218. }
  219. }
  220. public AdRotator(): base()
  221. {
  222. advertisementFile = string.Empty;
  223. fileDirectory = null;
  224. }
  225. [Bindable(true)]
  226. [DefaultValue("")]
  227. //[Editor("??")]
  228. [WebCategory("Behaviour")]
  229. [WebSysDescription("AdRotator_AdvertisementFile")]
  230. public string AdvertisementFile
  231. {
  232. get
  233. {
  234. return advertisementFile;
  235. }
  236. set
  237. {
  238. advertisementFile = value;
  239. }
  240. }
  241. public override FontInfo Font
  242. {
  243. get
  244. {
  245. return Font;
  246. }
  247. }
  248. [Bindable(true)]
  249. [DefaultValue("")]
  250. [WebCategory("Behaviour")]
  251. [WebSysDescription("AdRotator_KeywordFilter")]
  252. public string KeywordFilter
  253. {
  254. get
  255. {
  256. object o = ViewState["KeywordFilter"];
  257. if(o!=null)
  258. return (string)o;
  259. return String.Empty;
  260. }
  261. set
  262. {
  263. if(value!=null)
  264. ViewState["KeywordFilter"] = value.Trim();
  265. }
  266. }
  267. [Bindable(true)]
  268. [DefaultValue("")]
  269. [TypeConverter(typeof(TargetConverter))]
  270. [WebCategory("Behaviour")]
  271. [WebSysDescription("AdRotator_Target")]
  272. public string Target
  273. {
  274. get
  275. {
  276. object o = ViewState["Target"];
  277. if(o!=null)
  278. return (string)o;
  279. return String.Empty;
  280. }
  281. set
  282. {
  283. ViewState["Target"] = value;
  284. }
  285. }
  286. protected override ControlCollection CreateControlCollection()
  287. {
  288. return new EmptyControlCollection(this);
  289. }
  290. protected virtual void OnAdCreated(AdCreatedEventArgs e)
  291. {
  292. if(Events!=null)
  293. {
  294. AdCreatedEventHandler aceh = (AdCreatedEventHandler)(Events[AdCreatedEvent]);
  295. if(aceh!=null)
  296. aceh(this, e);
  297. }
  298. }
  299. protected override void OnPreRender(EventArgs e)
  300. {
  301. if(AdvertisementFile!=String.Empty)
  302. {
  303. AdCreatedEventArgs acea = new AdCreatedEventArgs(SelectAd());
  304. imageUrl = acea.ImageUrl;
  305. navigateUrl = acea.NavigateUrl;
  306. alternateText = acea.AlternateText;
  307. }
  308. }
  309. protected override void Render(HtmlTextWriter writer)
  310. {
  311. HyperLink hLink = new HyperLink();
  312. Image adImage = new Image();
  313. foreach(IEnumerable current in Attributes.Keys)
  314. {
  315. hLink.Attributes[(string)current] = Attributes[(string)current];
  316. }
  317. if(ID != null && ID.Length > 0)
  318. hLink.ID = ID;
  319. hLink.Target = Target;
  320. hLink.AccessKey = AccessKey;
  321. hLink.Enabled = Enabled;
  322. hLink.TabIndex = TabIndex;
  323. if (navigateUrl != null && navigateUrl.Length != 0)
  324. hLink.NavigateUrl = ResolveAdUrl (navigateUrl);
  325. hLink.RenderBeginTag(writer);
  326. if(ControlStyleCreated)
  327. {
  328. adImage.ApplyStyle(ControlStyle);
  329. }
  330. if(imageUrl!=null && imageUrl.Length > 0)
  331. adImage.ImageUrl = ResolveAdUrl(imageUrl);
  332. adImage.AlternateText = alternateText;
  333. adImage.ToolTip = ToolTip;
  334. adImage.RenderControl(writer);
  335. hLink.RenderEndTag(writer);
  336. }
  337. }
  338. }