AdRotator.cs 8.6 KB

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