AdRotator.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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. private AdRecord[] GetData(string file)
  134. {
  135. string physPath = MapPathSecure(file);
  136. string AdKey = "AdRotatorCache: " + physPath;
  137. fileDirectory = UrlUtils.GetDirectory(UrlUtils.Combine(TemplateSourceDirectory, file));
  138. Cache cache = HttpRuntime.Cache;
  139. AdRecord[] records = (AdRecord[])cache[AdKey];
  140. if(records==null)
  141. {
  142. records = LoadAdFile(physPath);
  143. if(records==null)
  144. {
  145. return null;
  146. }
  147. cache.Insert(AdKey, records, new CacheDependency(physPath));
  148. }
  149. return records;
  150. }
  151. private IDictionary SelectAd()
  152. {
  153. AdRecord[] records = GetData(AdvertisementFile);
  154. if(records!=null && records.Length!=0)
  155. {
  156. int impressions = 0;
  157. for(int i=0 ; i < records.Length; i++)
  158. {
  159. if(IsAdMatching(records[i]))
  160. impressions += records[1].hits;
  161. }
  162. if(impressions!=0)
  163. {
  164. int rnd = (new Random()).Next(impressions) + 1;
  165. int counter = 0;
  166. int index = 0;
  167. for(int i=0; i < records.Length; i++)
  168. {
  169. if(IsAdMatching(records[i]))
  170. {
  171. if(rnd <= (counter + records[i].hits))
  172. {
  173. index = i;
  174. break;
  175. }
  176. counter += records[i].hits;
  177. }
  178. }
  179. return records[index].adProps;
  180. }
  181. }
  182. return null;
  183. }
  184. private bool IsAdMatching(AdRecord currAd)
  185. {
  186. if(KeywordFilter!=String.Empty)
  187. {
  188. if(currAd.keyword.ToLower() == KeywordFilter.ToLower())
  189. return false;
  190. }
  191. return true;
  192. }
  193. private string ResolveAdUrl(string relativeUrl)
  194. {
  195. if(relativeUrl.Length==0 || !UrlUtils.IsRelativeUrl(relativeUrl))
  196. return relativeUrl;
  197. string fullUrl = String.Empty;
  198. if(fileDirectory != null)
  199. fullUrl = fileDirectory;
  200. if(fullUrl.Length == 0)
  201. fullUrl = TemplateSourceDirectory;
  202. if(fullUrl.Length == 0)
  203. return relativeUrl;
  204. return (fullUrl + relativeUrl);
  205. }
  206. [WebCategory("Action")]
  207. [WebSysDescription("AdRotator_OnAdCreated")]
  208. public event AdCreatedEventHandler AdCreated
  209. {
  210. add
  211. {
  212. Events.AddHandler(AdCreatedEvent, value);
  213. }
  214. remove
  215. {
  216. Events.RemoveHandler(AdCreatedEvent, value);
  217. }
  218. }
  219. public AdRotator(): base()
  220. {
  221. advertisementFile = string.Empty;
  222. fileDirectory = null;
  223. }
  224. [Bindable(true)]
  225. [DefaultValue("")]
  226. //[Editor("??")]
  227. [WebCategory("Behaviour")]
  228. [WebSysDescription("AdRotator_AdvertisementFile")]
  229. public string AdvertisementFile
  230. {
  231. get
  232. {
  233. return advertisementFile;
  234. }
  235. set
  236. {
  237. advertisementFile = value;
  238. }
  239. }
  240. public override FontInfo Font
  241. {
  242. get
  243. {
  244. return Font;
  245. }
  246. }
  247. [Bindable(true)]
  248. [DefaultValue("")]
  249. [WebCategory("Behaviour")]
  250. [WebSysDescription("AdRotator_KeywordFilter")]
  251. public string KeywordFilter
  252. {
  253. get
  254. {
  255. object o = ViewState["KeywordFilter"];
  256. if(o!=null)
  257. return (string)o;
  258. return String.Empty;
  259. }
  260. set
  261. {
  262. if(value!=null)
  263. ViewState["KeywordFilter"] = value.Trim();
  264. }
  265. }
  266. [Bindable(true)]
  267. [DefaultValue("")]
  268. [TypeConverter(typeof(TargetConverter))]
  269. [WebCategory("Behaviour")]
  270. [WebSysDescription("AdRotator_Target")]
  271. public string Target
  272. {
  273. get
  274. {
  275. object o = ViewState["Target"];
  276. if(o!=null)
  277. return (string)o;
  278. return String.Empty;
  279. }
  280. set
  281. {
  282. ViewState["Target"] = value;
  283. }
  284. }
  285. protected override ControlCollection CreateControlCollection()
  286. {
  287. return new EmptyControlCollection(this);
  288. }
  289. protected virtual void OnAdCreated(AdCreatedEventArgs e)
  290. {
  291. if(Events!=null)
  292. {
  293. AdCreatedEventHandler aceh = (AdCreatedEventHandler)(Events[AdCreatedEvent]);
  294. if(aceh!=null)
  295. aceh(this, e);
  296. }
  297. }
  298. protected override void OnPreRender(EventArgs e)
  299. {
  300. if(AdvertisementFile!=String.Empty)
  301. {
  302. AdCreatedEventArgs acea = new AdCreatedEventArgs(SelectAd());
  303. imageUrl = acea.ImageUrl;
  304. navigateUrl = acea.NavigateUrl;
  305. alternateText = acea.AlternateText;
  306. }
  307. }
  308. protected override void Render(HtmlTextWriter writer)
  309. {
  310. HyperLink hLink = new HyperLink();
  311. Image adImage = new Image();
  312. foreach(IEnumerable current in Attributes.Keys)
  313. {
  314. hLink.Attributes[(string)current] = Attributes[(string)current];
  315. }
  316. if(ID != null && ID.Length > 0)
  317. hLink.ID = ID;
  318. hLink.Target = Target;
  319. hLink.AccessKey = AccessKey;
  320. hLink.Enabled = Enabled;
  321. hLink.TabIndex = TabIndex;
  322. hLink.RenderBeginTag(writer);
  323. if(ControlStyleCreated)
  324. {
  325. adImage.ApplyStyle(ControlStyle);
  326. }
  327. if(imageUrl!=null && imageUrl.Length > 0)
  328. adImage.ImageUrl = ResolveAdUrl(imageUrl);
  329. adImage.AlternateText = alternateText;
  330. adImage.ToolTip = ToolTip;
  331. adImage.RenderControl(writer);
  332. hLink.RenderEndTag(writer);
  333. }
  334. }
  335. }