AdRotator.cs 7.4 KB

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