AdRotator.cs 7.5 KB

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