PageRenderTime 81ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/Server/IServV2/IPhone/Sites/IPWS/PageHandler.cs

https://bitbucket.org/fboltz/afpmobile
C# | 2788 lines | 2095 code | 407 blank | 286 comment | 423 complexity | fb268bc8cd9c86783ed46031a842560e MD5 | raw file
Possible License(s): Apache-2.0, MPL-2.0, LGPL-2.1, MIT, BSD-3-Clause, 0BSD, AGPL-3.0
  1. using System.Collections.Generic;
  2. using System.Web.Caching;
  3. using AFP.IPhone.Application;
  4. using AFP.IPhone.Extensions;
  5. using AFP.IPhone.Processor;
  6. using AFP.IPhone.Storage;
  7. using System;
  8. using System.IO;
  9. using System.IO.Compression;
  10. using System.Linq;
  11. using System.Threading;
  12. using System.Web;
  13. using System.Xml;
  14. using System.Security.Cryptography;
  15. using System.Text;
  16. namespace AFP.IPhone.Web
  17. {
  18. public class PageHandler : IHttpHandler
  19. {
  20. private class CachedDocument
  21. {
  22. private string GetChecksum(byte[] document)
  23. {
  24. MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();
  25. Byte[] ba = MD5.ComputeHash(document);
  26. StringBuilder hex = new StringBuilder(ba.Length * 2);
  27. foreach (byte b in ba)
  28. hex.AppendFormat("{0:x2}", b);
  29. return hex.ToString();
  30. }
  31. public CachedDocument(byte[] document, DateTime lastModified)
  32. {
  33. Document = document;
  34. LastModified = lastModified;
  35. Checksum = GetChecksum(document);
  36. }
  37. public string Checksum { get; private set; }
  38. public byte[] Document { get; private set; }
  39. public DateTime LastModified { get; private set; }
  40. }
  41. private static readonly object _lockRootCache = new object();
  42. private static readonly object _lockTopicCache = new object();
  43. private struct PathAndWCF
  44. {
  45. public string RootPath;
  46. public string EndPointName;
  47. public XmlDocument GeneratedSites;
  48. }
  49. private static System.Collections.Hashtable _services; // virtualdir ---> PathAndWCF config;
  50. private static System.Collections.Hashtable _idVD; // id service ---> virtualdir;
  51. private static System.Collections.Hashtable _VdByTopicId; // topicid ---> EndPointName;
  52. private static XmlDocument _BuildedSiteConfiguration;
  53. private static TimeSpan? _ExpireCacheVote = null;
  54. private static TimeSpan? _BuildWithXDay = null;
  55. public bool IsReusable
  56. {
  57. get { return false; }
  58. }
  59. private static FileInfo GetMediaInfo(string virtualdir, string format, string plugin, string mediaId)
  60. {
  61. return new System.IO.FileInfo(GetPath((string)(((PathAndWCF)_services[virtualdir]).RootPath), format, plugin, mediaId));
  62. //return new StorageServer().Info(format, plugin, mediaId);
  63. }
  64. private static void GetMedia(Stream output, string virtualdir, string format, string plugin, string mediaId)
  65. {
  66. var buffer = new byte[16384];
  67. int read;
  68. /* using (Stream document = new StorageServer().Restore(format, plugin, mediaId))
  69. {}
  70. */
  71. Stream document = new FileStream(GetPath(((PathAndWCF)_services[virtualdir]).RootPath, format, plugin, mediaId), FileMode.Open, FileAccess.Read, FileShare.Read);
  72. do
  73. {
  74. if ((read = document.Read(buffer, 0, buffer.Length)) > 0)
  75. output.Write(buffer, 0, read);
  76. } while (read > 0);
  77. document.Close();
  78. }
  79. private static void RequestAbout(HttpContext context)
  80. {
  81. // Préparation Http
  82. WebApplication.PageSetHeaders();
  83. context.Response.Charset = "utf-8";
  84. context.Response.ContentType = "text/html";
  85. // Compression Gzip
  86. if (context.Request.ServerVariables.AllKeys.Contains("HTTP_ACCEPT_ENCODING") && Convert.ToString(context.Request.ServerVariables["HTTP_ACCEPT_ENCODING"]).IndexOf("gzip") > -1)
  87. {
  88. context.Response.AddHeader("Content-Encoding", "gzip");
  89. context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
  90. }
  91. try
  92. {
  93. if (string.IsNullOrEmpty(context.Request.QueryString["site"]))
  94. {
  95. context.Response.TransmitFile(string.Format(@"{0}about\about-{1}.html", context.Request.PhysicalApplicationPath, (string.IsNullOrEmpty(context.Request.Headers["Accept-Language"])) ? "en" : context.Request.Headers["Accept-Language"].Substring(0, 2)));
  96. }
  97. else
  98. {
  99. // plusieurs produits...
  100. string fPath = string.Format(@"{0}about\{2}-{1}.html", context.Request.PhysicalApplicationPath, (string.IsNullOrEmpty(context.Request.Headers["Accept-Language"])) ? "en" : context.Request.Headers["Accept-Language"].Substring(0, 2), context.Request.QueryString["site"]);
  101. if (System.IO.File.Exists(fPath))
  102. {
  103. context.Response.TransmitFile(fPath);
  104. }
  105. else
  106. {
  107. context.Response.TransmitFile(string.Format(@"{0}about\about-{1}.html", context.Request.PhysicalApplicationPath, (string.IsNullOrEmpty(context.Request.Headers["Accept-Language"])) ? "en" : context.Request.Headers["Accept-Language"].Substring(0, 2)));
  108. }
  109. }
  110. }
  111. catch (Exception e)
  112. {
  113. try
  114. {
  115. context.Response.TransmitFile(string.Format(@"{0}about\about-en.html", context.Request.PhysicalApplicationPath));
  116. }
  117. catch
  118. {
  119. // Reporting
  120. Process.Trace(WebApplication.PageName, e.ToString(), System.Diagnostics.EventLogEntryType.Error);
  121. Process.Set(WebApplication.PageName, e.Message, System.Diagnostics.EventLogEntryType.Error);
  122. // Erreur de traitement
  123. context.Response.ContentType = "text/xml";
  124. context.Response.ClearContent();
  125. context.Response.Write(new ExceptionDocument(e, "About error"));
  126. }
  127. }
  128. }
  129. private static void RequestCheck(HttpContext context)
  130. {
  131. try
  132. {
  133. // Préparation Http
  134. WebApplication.PageSetHeaders();
  135. context.Response.ContentType = "text/html";
  136. if (context.Request.QueryString.Get("deep") == "1")
  137. try
  138. {
  139. using (var processorClient = new ProcessorClient(Process.Configuration.DocumentElement.GetAttribute("processorEndpointName")))
  140. {
  141. var processorServiceStatus = processorClient.Status();
  142. // Ecriture du tag ok
  143. switch (processorServiceStatus)
  144. {
  145. case System.Diagnostics.EventLogEntryType.Error:
  146. context.Response.Write("STATUS_ERROR");
  147. break;
  148. case System.Diagnostics.EventLogEntryType.Warning:
  149. context.Response.Write("STATUS_WARNING");
  150. break;
  151. default:
  152. context.Response.Write("STATUS_OK");
  153. break;
  154. }
  155. }
  156. }
  157. catch (Exception e)
  158. {
  159. // Reporting
  160. Process.Set(WebApplication.PageName, e.Message, System.Diagnostics.EventLogEntryType.Error);
  161. // Ecriture du tag error
  162. context.Response.Write("STATUS_ERROR");
  163. }
  164. else
  165. context.Response.Write("STATUS_OK");
  166. }
  167. catch (Exception e)
  168. {
  169. // Reporting
  170. Process.Set(WebApplication.PageName, e.Message, System.Diagnostics.EventLogEntryType.Error);
  171. // Ecriture de l'erreur sur la sortie
  172. context.Response.Write(e.ToString());
  173. }
  174. }
  175. private static void RequestDescription(HttpContext context)
  176. {
  177. // Préparation Http
  178. WebApplication.PageSetHeaders();
  179. context.Response.ContentType = "text/html";
  180. // Compression Gzip
  181. if (context.Request.ServerVariables.AllKeys.Contains("HTTP_ACCEPT_ENCODING") && Convert.ToString(context.Request.ServerVariables["HTTP_ACCEPT_ENCODING"]).IndexOf("gzip") > -1)
  182. {
  183. context.Response.AddHeader("Content-Encoding", "gzip");
  184. context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
  185. }
  186. try
  187. {
  188. context.Response.TransmitFile(string.Format(@"{0}description\{1}-{2}.html", context.Request.PhysicalApplicationPath, context.Request.QueryString["product"], (string.IsNullOrEmpty(context.Request.Headers["Accept-Language"])) ? "en" : context.Request.Headers["Accept-Language"].Substring(0, 2)));
  189. }
  190. catch (Exception e)
  191. {
  192. try
  193. {
  194. context.Response.TransmitFile(string.Format(@"{0}description\{1}-en.html", context.Request.PhysicalApplicationPath, context.Request.QueryString["product"]));
  195. }
  196. catch (Exception e2)
  197. {
  198. // Reporting
  199. Process.Trace(WebApplication.PageName, string.Format("{0},{1}", e.ToString(), e2.ToString()), System.Diagnostics.EventLogEntryType.Error);
  200. Process.Set(WebApplication.PageName, string.Format("{0},{1}", e.Message, e2.Message), System.Diagnostics.EventLogEntryType.Error);
  201. // Erreur de traitement
  202. context.Response.ContentType = "text/xml";
  203. context.Response.ClearContent();
  204. context.Response.Write(new ExceptionDocument(e, "About error"));
  205. }
  206. }
  207. }
  208. private static void RequestDisclaimer(HttpContext context)
  209. {
  210. // Préparation Http
  211. WebApplication.PageSetHeaders();
  212. context.Response.Charset = "utf-8";
  213. context.Response.ContentType = "text/html";
  214. // Compression Gzip
  215. if (context.Request.ServerVariables.AllKeys.Contains("HTTP_ACCEPT_ENCODING") && Convert.ToString(context.Request.ServerVariables["HTTP_ACCEPT_ENCODING"]).IndexOf("gzip") > -1)
  216. {
  217. context.Response.AddHeader("Content-Encoding", "gzip");
  218. context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
  219. }
  220. try
  221. {
  222. context.Response.TransmitFile(string.Format(@"{0}disclaimers\{1}\disclaimer-{2}.html", context.Request.PhysicalApplicationPath, context.Request.QueryString["SC"], (string.IsNullOrEmpty(context.Request.Headers["Accept-Language"])) ? "en" : context.Request.Headers["Accept-Language"].Substring(0, 2)));
  223. }
  224. catch (Exception e)
  225. {
  226. try
  227. {
  228. context.Response.TransmitFile(string.Format(@"{0}disclaimers\{1}\disclaimer-en.html", context.Request.PhysicalApplicationPath, context.Request.QueryString["SC"]));
  229. }
  230. catch
  231. {
  232. // Reporting
  233. Process.Trace(WebApplication.PageName, e.ToString(), System.Diagnostics.EventLogEntryType.Error);
  234. Process.Set(WebApplication.PageName, e.Message, System.Diagnostics.EventLogEntryType.Error);
  235. // Erreur de traitement
  236. context.Response.ContentType = "text/xml";
  237. context.Response.ClearContent();
  238. context.Response.Write(new ExceptionDocument(e, "About error"));
  239. }
  240. }
  241. }
  242. private static void RequestProducts(HttpContext context, List<String> StringsCachedDepency, DateTime? CachedDate)
  243. {
  244. try
  245. {
  246. #if DEBUG && DEBUGPRODUCT
  247. System.Diagnostics.Debugger.Break();
  248. #endif
  249. String FilePathConfig = Process.FileConfigurationPath;
  250. FileInfo info = null;
  251. if (string.IsNullOrEmpty(FilePathConfig) == false)
  252. {
  253. info = new FileInfo(FilePathConfig);
  254. }
  255. if (string.IsNullOrEmpty(FilePathConfig) == false)
  256. {
  257. if (StringsCachedDepency == null)
  258. {
  259. StringsCachedDepency = new List<string>();
  260. }
  261. StringsCachedDepency.Add(FilePathConfig);
  262. }
  263. CachedDocument products;
  264. try
  265. {
  266. Monitor.Enter(_lockRootCache);
  267. products = (CachedDocument)context.Cache[Constants._storageProductsFileId];
  268. // Products présent dans le cache ?
  269. if (products == null)
  270. {
  271. // Récupération des informations
  272. var productsDocument = new XmlDocument();
  273. productsDocument.LoadXml("<sites/>");
  274. foreach (XmlNode site in _BuildedSiteConfiguration.SelectNodes("//site"))
  275. {
  276. if (site is XmlElement)
  277. productsDocument.DocumentElement.AppendChild(productsDocument.ImportNode(site, false));
  278. }
  279. // Suppression des sites non requis
  280. if (Process.Configuration.DocumentElement.HasAttribute("sitesIdList"))
  281. {
  282. var allowedIds = Process.Configuration.DocumentElement.GetAttribute("sitesIdList").Split(';');
  283. var removedSites = new List<XmlElement>();
  284. // Recherche des sites non requis
  285. foreach (XmlElement site in _BuildedSiteConfiguration.SelectNodes("//site"))
  286. if (site.HasAttribute("id") && !allowedIds.Contains(site.GetAttribute("id")))
  287. removedSites.Add(site);
  288. // Suppression des sites non requis
  289. foreach (var site in removedSites)
  290. productsDocument.DocumentElement.RemoveChild(site);
  291. }
  292. // Mise en mémoire du document sites
  293. using (var buffer = new MemoryStream())
  294. {
  295. productsDocument.Save(buffer);
  296. if (info != null)
  297. products = new CachedDocument(buffer.ToArray(), info.LastWriteTimeUtc);
  298. }
  299. // Mise en cache
  300. if (info != null)
  301. context.Cache.Insert(Constants._storageProductsFileId, products, new CacheDependency(info.FullName));
  302. }
  303. }
  304. catch (Exception e3)
  305. {
  306. string Message = e3.ToString();
  307. products = null;
  308. }
  309. finally
  310. {
  311. Monitor.Exit(_lockRootCache);
  312. }
  313. // Vérification du cache
  314. Boolean bCache = true;
  315. if (context.Request.Headers.AllKeys.Contains("Cache-Control"))
  316. if (context.Request.Headers["Cache-Control"].ToLower() == "no-cache")
  317. bCache = false;
  318. if (context.Request.Headers.AllKeys.Contains("Pragma"))
  319. {
  320. // doit-on faire une boucle?
  321. if (context.Request.Headers["Pragma"].ToLower() == "no-cache")
  322. bCache = false;
  323. }
  324. if (bCache)
  325. if (context.Request.Headers.AllKeys.Contains("If-Modified-Since"))
  326. if (products.LastModified.ToUniversalTime().Subtract(DateTime.Parse(context.Request.Headers["If-Modified-Since"])).TotalSeconds <= 1)
  327. {
  328. context.Response.AddHeader("cache-control", "public");
  329. context.Response.StatusCode = 304;
  330. return;
  331. }
  332. // Préparation Http
  333. WebApplication.PageSetHeaders
  334. (
  335. new Dictionary<string, string>
  336. {
  337. { "##LM##", products.LastModified.ToUniversalTime ().ToHTTPHeaderString () } ,
  338. { "##ET##", products.Checksum },
  339. { "##EXP##", DateTime.Now.ToUniversalTime().AddSeconds (WebApplication.GetExpires()).ToHTTPHeaderString()}
  340. }
  341. );
  342. context.Response.Buffer = true;
  343. context.Response.BufferOutput = true;
  344. context.Response.ContentType = "text/xml";
  345. // Ecriture du document Sites
  346. context.Response.BinaryWrite(products.Document);
  347. // Compression Gzip
  348. if (context.Request.ServerVariables.AllKeys.Contains("HTTP_ACCEPT_ENCODING") && Convert.ToString(context.Request.ServerVariables["HTTP_ACCEPT_ENCODING"]).IndexOf("gzip") > -1)
  349. {
  350. context.Response.AddHeader("Content-Encoding", "gzip");
  351. context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
  352. }
  353. // Reporting
  354. Process.Set(WebApplication.PageName, "Hits", System.Diagnostics.EventLogEntryType.Information);
  355. }
  356. catch (Exception e)
  357. {
  358. // Reporting
  359. Process.Trace(WebApplication.PageName, e.ToString(), System.Diagnostics.EventLogEntryType.Error);
  360. Process.Set(WebApplication.PageName, e.Message, System.Diagnostics.EventLogEntryType.Error);
  361. // Erreur de traitement
  362. context.Response.ContentType = "text/xml";
  363. context.Response.ClearContent();
  364. context.Response.Write(new ExceptionDocument(e, "Products error"));
  365. }
  366. }
  367. private static void RequestRating(HttpContext context)
  368. {
  369. #if DEBUG && DEBUGRATING
  370. System.Diagnostics.Debugger.Break();
  371. #endif
  372. // Préparation Http
  373. WebApplication.PageSetHeaders();
  374. context.Response.ContentType = "text/xml";
  375. // Récupération des informations
  376. string productId = GetProductName(context, true);
  377. string device = GetDeviceName(context);
  378. string endPointName = GetEndPointName(context);
  379. // Vote selon type
  380. try
  381. {
  382. using (var processorClient = new ProcessorClient(endPointName))
  383. {
  384. // Vote
  385. switch (context.Request.QueryString["type"])
  386. {
  387. case "0":
  388. context.Response.Write(processorClient.SetRate(productId, context.Request.QueryString["id"], context.Request.QueryString["item"], float.Parse(context.Request.QueryString["rate"], System.Globalization.CultureInfo.InvariantCulture), device));
  389. break;
  390. case "1":
  391. context.Response.Write(processorClient.SetRate(productId, context.Request.QueryString["id"], context.Request.QueryString["parent"], context.Request.QueryString["item"], float.Parse(context.Request.QueryString["rate"], System.Globalization.CultureInfo.InvariantCulture), device));
  392. break;
  393. default:
  394. throw new Exception("Invalid type value.");
  395. }
  396. }
  397. }
  398. catch (Exception e)
  399. {
  400. // Reporting
  401. Process.Trace(WebApplication.PageName, string.Format(" endpointName {0} error {1} ", endPointName, e.ToString()), System.Diagnostics.EventLogEntryType.Error);
  402. Process.Set(WebApplication.PageName, string.Format(" endpointName {0} error {1} ", endPointName, e.Message), System.Diagnostics.EventLogEntryType.Error);
  403. // Réponse
  404. context.Response.ClearContent();
  405. context.Response.Write(new ExceptionDocument(e, string.Format(" {1} on endpointName {0} ProductId {2}", endPointName, "Rating error", productId)));
  406. }
  407. }
  408. private static void RequestSites(HttpContext context, Boolean rebuildSites)
  409. {
  410. #if DEBUG && DEBUG_SITE
  411. System.Diagnostics.Debugger.Break();
  412. #endif
  413. Process.Start();
  414. // on a reconstruit le document... sans les favoris toutefois a faire plus tard
  415. try
  416. {
  417. CachedDocument sites;
  418. /*
  419. * Raccourci de debuggage en prod...
  420. */
  421. /*
  422. List<string> StringsCachedDepency1;
  423. DateTime CachedDate1;
  424. var sitesDocument1 = BuildSites(out StringsCachedDepency1, out CachedDate1);
  425. */
  426. try
  427. {
  428. Monitor.Enter(_lockRootCache);
  429. // Vérification du cache
  430. sites = (CachedDocument)context.Cache[Constants._storageSitesFileId];
  431. // Sites présent dans le cache ?
  432. if (sites == null || rebuildSites)
  433. {
  434. _services = null; // on force la reconstruction totale... evitera le bug du cache pour la partie Ipad...
  435. // Récupération des informations
  436. var sitesDocument = new XmlDocument();
  437. context.Cache.Remove(Constants._storageSitesFileId);
  438. List<string> StringsCachedDepency;
  439. DateTime CachedDate;
  440. sitesDocument = BuildSites(out StringsCachedDepency, out CachedDate);
  441. //StringsCachedDepency.Add(Process.FileConfigurationPath); // Si la config change il faut que l'on s'adapte. déjà fait dans buildSites...
  442. // si le document sites.xml change il faut aussi se mettre à jour
  443. //StringsCachedDepency.Add(Process.FileConfigurationPath); // Si la config change il faut que l'on s'adapte.
  444. _BuildedSiteConfiguration = sitesDocument;
  445. // Site par défaut
  446. if (Process.Configuration.DocumentElement.HasAttribute("defaultSite"))
  447. sitesDocument.DocumentElement.SetAttribute("defaultSite", Process.Configuration.DocumentElement.GetAttribute("defaultSite"));
  448. // Suppression des attributs inutiles
  449. foreach (XmlElement item in sitesDocument.SelectNodes("//topic[@id]|//subtopic[@id]"))
  450. item.RemoveAttribute("id");
  451. foreach (XmlElement item in sitesDocument.SelectNodes("//topic[@product]|//subtopic[@product]"))
  452. item.RemoveAttribute("product");
  453. foreach (XmlElement item in sitesDocument.SelectNodes("//topic[@showcatchline]|//subtopic[@showcatchline]"))
  454. item.RemoveAttribute("showcatchline");
  455. foreach (XmlElement item in sitesDocument.SelectNodes("//site[@smallIconsPath]"))
  456. item.RemoveAttribute("smallIconsPath");
  457. foreach (XmlElement item in sitesDocument.SelectNodes("//site[@bigIconsPath]"))
  458. item.RemoveAttribute("bigIconsPath");
  459. foreach (XmlElement item in sitesDocument.SelectNodes("//topic[@maxAge]"))
  460. item.RemoveAttribute("maxAge");
  461. foreach (XmlElement item in sitesDocument.SelectNodes("//topic[@overrideuno]"))
  462. item.RemoveAttribute("overrideuno");
  463. // foreach (XmlElement item in sitesDocument.SelectNodes("//topic[@newuno]"))
  464. // item.RemoveAttribute("newuno");
  465. foreach (XmlElement item in sitesDocument.SelectNodes("//subtopic[@maxAge]"))
  466. item.RemoveAttribute("maxAge");
  467. foreach (XmlElement item in sitesDocument.SelectNodes("//site[@defaultIcon]"))
  468. item.RemoveAttribute("defaultIcon");
  469. foreach (XmlElement item in sitesDocument.SelectNodes("//topic[@announce]"))
  470. item.RemoveAttribute("announce");
  471. foreach (XmlElement item in sitesDocument.SelectNodes("//topic[@Serve]|//subtopic[@Serve]"))
  472. item.RemoveAttribute("Serve");
  473. foreach (XmlElement item in sitesDocument.SelectNodes("//site[@maxNumberOfItems]"))
  474. item.RemoveAttribute("maxNumberOfItems");
  475. foreach (XmlElement item in sitesDocument.SelectNodes("//site[@productVote]"))
  476. item.RemoveAttribute("productVote");
  477. /* foreach (XmlElement item in sitesDocument.SelectNodes("//site"))
  478. item.RemoveAttribute("maxNumberOfItems");
  479. */
  480. foreach (XmlElement item in sitesDocument.SelectNodes("//topic|//subtopic|//topics"))
  481. {
  482. item.RemoveAttribute("path");
  483. item.RemoveAttribute("file");
  484. item.RemoveAttribute("htmlModel");
  485. item.RemoveAttribute("serviceCongigPath");
  486. item.RemoveAttribute("virtualDir");
  487. item.RemoveAttribute("siteId");
  488. item.RemoveAttribute("service");
  489. if (item.HasAttribute("shortName") == false)
  490. {
  491. item.SetAttribute("shortName", item.GetAttributeValue("fullName", ""));
  492. }
  493. }
  494. sitesDocument.DocumentElement.SetAttribute("updateDate", DateTime.UtcNow.ToXmlElementString());
  495. // Mise en mémoire du document sites
  496. using (var buffer = new MemoryStream())
  497. {
  498. sitesDocument.Save(buffer);
  499. sites = new CachedDocument(buffer.ToArray(), CachedDate);
  500. Process.Trace(string.Format("Cached document {0}", CachedDate), System.Diagnostics.EventLogEntryType.Information);
  501. }
  502. // Mise en cache
  503. context.Cache.Remove(Constants._storageSitesFileId);
  504. context.Cache.Insert(Constants._storageSitesFileId, sites, new CacheDependency(StringsCachedDepency.ToArray()));
  505. }
  506. }
  507. catch (Exception e3)
  508. {
  509. throw e3;
  510. }
  511. finally
  512. {
  513. Monitor.Exit(_lockRootCache);
  514. }
  515. // Vérification du cache
  516. Boolean bCache = true;
  517. if (context.Request.Headers.AllKeys.Contains("Cache-Control"))
  518. if (context.Request.Headers["Cache-Control"].ToLower() == "no-cache")
  519. bCache = false;
  520. if (context.Request.Headers.AllKeys.Contains("Pragma"))
  521. {
  522. // doit-on faire une boucle?
  523. if (context.Request.Headers["Pragma"].ToLower() == "no-cache")
  524. bCache = false;
  525. }
  526. if (bCache)
  527. if (context.Request.Headers.AllKeys.Contains("If-Modified-Since"))
  528. if (sites.LastModified.ToUniversalTime().Subtract(DateTime.Parse(context.Request.Headers["If-Modified-Since"])).TotalSeconds <= 1)
  529. {
  530. context.Response.AddHeader("cache-control", "public");
  531. context.Response.StatusCode = 304;
  532. return;
  533. }
  534. // Préparation Http
  535. WebApplication.PageSetHeaders(
  536. new Dictionary<string, string>
  537. {
  538. { "##LM##", sites.LastModified.ToUniversalTime ().ToHTTPHeaderString () } ,
  539. { "##ET##", sites.Checksum} ,
  540. { "##EXP##", DateTime.UtcNow.ToUniversalTime().AddSeconds (WebApplication.GetExpires()).ToHTTPHeaderString()}
  541. });
  542. context.Response.Buffer = true;
  543. context.Response.BufferOutput = true;
  544. context.Response.ContentType = "text/xml";
  545. // Ecriture du document Sites
  546. context.Response.BinaryWrite(sites.Document);
  547. // Compression Gzip
  548. if (context.Request.ServerVariables.AllKeys.Contains("HTTP_ACCEPT_ENCODING") && Convert.ToString(context.Request.ServerVariables["HTTP_ACCEPT_ENCODING"]).IndexOf("gzip") > -1)
  549. {
  550. context.Response.AddHeader("Content-Encoding", "gzip");
  551. context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
  552. }
  553. // Reporting
  554. Process.Set(WebApplication.PageName, "Hits", System.Diagnostics.EventLogEntryType.Information);
  555. }
  556. catch (Exception e)
  557. {
  558. // Reporting
  559. Process.Trace(WebApplication.PageName, e.ToString(), System.Diagnostics.EventLogEntryType.Error);
  560. Process.Set(WebApplication.PageName, e.Message, System.Diagnostics.EventLogEntryType.Error);
  561. // Erreur de traitement
  562. context.Response.ContentType = "text/xml";
  563. context.Response.ClearContent();
  564. context.Response.Write(new ExceptionDocument(e, "Sites error"));
  565. }
  566. }
  567. private static void RequestTopic(HttpContext context)
  568. {
  569. String FilePathConfig = Process.FileConfigurationPath;
  570. List<string> StringsCachedDepency = null;
  571. int startAt = 0;
  572. string mes = "";
  573. string dmes = " start";
  574. String uno = "";
  575. if (string.IsNullOrEmpty(FilePathConfig) == false)
  576. {
  577. if (StringsCachedDepency == null)
  578. {
  579. StringsCachedDepency = new List<string>();
  580. }
  581. StringsCachedDepency.Add(FilePathConfig);
  582. }
  583. try
  584. {
  585. CachedDocument topic = null;
  586. String VirtualDirectory;
  587. String ProductID;
  588. XmlElement SelectedSite;
  589. String sCacheReference = "";
  590. uno = context.Request.QueryString["uno"];
  591. XmlDocument sitesDocument = new XmlDocument();
  592. XmlDocument xapplicationConfiguration = Process.Configuration;
  593. string overtype = "";
  594. ProductID = context.Request.QueryString["product"];
  595. if (string.IsNullOrEmpty(ProductID))
  596. {
  597. //TODO il faut mettre le DefaultSiteName dans SiteName
  598. }
  599. VirtualDirectory = context.Request.QueryString["vd"];
  600. if (string.IsNullOrEmpty(VirtualDirectory))
  601. {
  602. VirtualDirectory = context.Request.QueryString["product"];
  603. }
  604. dmes += " 1 ";
  605. using (var buffer = new MemoryStream())
  606. {
  607. GetMedia(buffer, VirtualDirectory, Constants._storageSitesFormatName, Constants._storageSitesKey, Constants._storageSitesFileId);
  608. buffer.Position = 0;
  609. sitesDocument.Load(buffer);
  610. }
  611. // Récupération de l'id topic
  612. // ici il faudrait faire le calcul du maxEntries??
  613. dmes += " on cherche avec le uno " + uno;
  614. dmes += "\n" + string.Format("//*[@uno='{0}']", uno);
  615. XmlNode topicElement = sitesDocument.SelectSingleNode(string.Format("//*[@uno='{0}']", uno));
  616. TopicDeclaration topicDeclaration;
  617. if (topicElement == null)
  618. {
  619. //cas des votes !!!
  620. if (uno.IndexOf("__") > -1)
  621. uno = uno.Substring(uno.IndexOf("__") + 2);
  622. dmes += " on re cherche avec le uno " + uno;
  623. dmes += "Process configuration \n" + Process.Configuration.OuterXml;
  624. topicElement = Process.Configuration.SelectSingleNode(string.Format("//*[@uno='{0}']", uno));
  625. if (((XmlElement)topicElement).HasAttribute("type"))
  626. {
  627. overtype = topicElement.Attributes["type"].Value.ToLower();
  628. }
  629. dmes += "Process configuration \n" + Process.Configuration.OuterXml;
  630. }
  631. dmes += "\n topicElement " + topicElement.OuterXml;
  632. topicDeclaration = new TopicDeclaration((XmlElement)topicElement);
  633. // Récupération des informations sur le topic source
  634. string idTopic = "";
  635. if (((XmlElement)topicElement).HasAttribute("id"))
  636. idTopic = topicElement.Attributes["id"].Value;
  637. else
  638. idTopic = " __" + uno;
  639. string nameMedia = idTopic;
  640. dmes += " et on a trouvé";
  641. if (topicElement.Name == "subtopic")
  642. {
  643. if (((XmlElement)topicElement).HasAttribute("type"))
  644. {
  645. if ((topicElement.Attributes["type"].Value == "diaporama") || (topicElement.Attributes["type"].Value == "magazin") || (topicElement.Attributes["type"].Value == "7") || (topicElement.Attributes["type"].Value == "8"))
  646. {
  647. nameMedia = string.Format("{0}__{1}", VirtualDirectory, nameMedia);
  648. }
  649. }
  650. }
  651. SelectedSite = (XmlElement)_BuildedSiteConfiguration.SelectSingleNode(string.Format("//site[@id='{0}']", ProductID));
  652. if (SelectedSite == null)
  653. {
  654. throw new Exception(string.Format("Configuration Error no product with id {0}", ProductID));
  655. }
  656. /******************************************************************************************************************************************/
  657. /******************************************************************************************************************************************/
  658. /******************************************************************************************************************************************/
  659. /******************************************************************************************************************************************/
  660. /******************************************************************************************************************************************/
  661. /******************************************************************************************************************************************/
  662. XmlElement curNode;
  663. String LocalId = idTopic.Substring(idTopic.IndexOf("__") + 2);
  664. XmlElement ConfigSiteNode = null;
  665. ConfigSiteNode = (XmlElement)Process.Configuration.SelectSingleNode(string.Format(".//site[@id='{0}']", ProductID));
  666. curNode = (XmlElement)ConfigSiteNode.SelectSingleNode(string.Format(".//*[@id='{0}']", LocalId));
  667. // et evidement ce n'est pas bon...
  668. // dans le cadre d'un Free/payant...
  669. int maxEntries;
  670. try
  671. {
  672. while (curNode is XmlElement && !(curNode.ParentNode is XmlDocument) && curNode.HasAttribute("maxNumberOfItems") == false)
  673. {
  674. curNode = (XmlElement)curNode.ParentNode;
  675. }
  676. if (curNode.HasAttribute("maxNumberOfItems"))
  677. maxEntries = int.Parse(curNode.GetAttribute("maxNumberOfItems"));
  678. else
  679. maxEntries = 30;
  680. }
  681. catch (Exception e)
  682. {
  683. string a = e.Message;
  684. maxEntries = 30;
  685. #if DEBUG && toto
  686. Process.Trace(WebApplication.PageName, string.Format(" Determination maxNumberOfItems {0} ProductId {1} LocalId{2} idTopic {4} \n\n ## {3}", e.ToString(), ProductID, LocalId, Process.Configuration.OuterXml, idTopic), System.Diagnostics.EventLogEntryType.Error);
  687. //Process.Set(WebApplication.PageName, string.Format(" Determination maxNumber {0}", e.ToString()), System.Diagnostics.EventLogEntryType.Error);
  688. #endif
  689. }
  690. //int maxEntries;
  691. //curNode = (XmlElement)sitesDocument.SelectSingleNode(string.Format(".//*[@uno='{0}']", uno));
  692. curNode = (XmlElement)ConfigSiteNode.SelectSingleNode(string.Format(".//*[@id='{0}']", LocalId));
  693. try
  694. {
  695. while (curNode is XmlElement && !(curNode.ParentNode is XmlDocument) && curNode.HasAttribute("startat") == false)
  696. {
  697. curNode = (XmlElement)curNode.ParentNode;
  698. }
  699. if (curNode.HasAttribute("startat"))
  700. startAt = int.Parse(curNode.GetAttribute("startat"));
  701. else
  702. startAt = 0;
  703. }
  704. catch (Exception e)
  705. {
  706. string a = e.Message;
  707. startAt = 0;
  708. }
  709. #if DEBUG_TOPIC
  710. System.Diagnostics.Debugger.Break();
  711. #endif
  712. try
  713. {
  714. Monitor.Enter(_lockTopicCache);
  715. // Vérification du cache
  716. sCacheReference = string.Format("{0}_{1}", uno, ProductID);
  717. topic = (CachedDocument)context.Cache[sCacheReference];
  718. // Topic présent dans le cache ?
  719. if (topic == null)
  720. {
  721. String topicType = GetType(uno);
  722. string lang = GetLang(uno);
  723. if (string.IsNullOrEmpty(overtype) == false)
  724. {
  725. topicType = overtype;
  726. }
  727. dmes += "\n" + overtype + "\n";
  728. var topicDocument = new XmlDocument();
  729. if (topicType == "heart" || topicType == "rated" || topicType == "mostviewed")
  730. {
  731. dmes += "\n on a bien un Rated\n";
  732. XmlDocument btopic = BuildRateTopic(context, topicType, 50, (TimeSpan)_BuildWithXDay, lang );
  733. dmes += "\n buildrated done \n";
  734. using (var buffer = new MemoryStream())
  735. {
  736. btopic.Save(buffer);
  737. topic = new CachedDocument(buffer.ToArray(), System.DateTime.UtcNow);
  738. }
  739. dmes += "\n " + btopic.OuterXml + "\n";
  740. #if DEBUG && DEBUGTRACERATING
  741. Process.Trace(WebApplication.PageName, string.Format(" Build Rated Topic {0}", dmes), System.Diagnostics.EventLogEntryType.Error);
  742. //Process.Set(WebApplication.PageName, string.Format(" Build Rated Topic {0}", dmes), System.Diagnostics.EventLogEntryType.Error);
  743. #endif
  744. if (_ExpireCacheVote != null)
  745. context.Cache.Insert(sCacheReference, topic, null, System.Web.Caching.Cache.NoAbsoluteExpiration, (TimeSpan)_ExpireCacheVote);
  746. else
  747. context.Cache.Insert(sCacheReference, topic, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromHours(2));
  748. }
  749. else
  750. {
  751. // Chargement du document sites
  752. dmes += " non Rated";
  753. var topicInfo = GetMediaInfo(VirtualDirectory, Constants._storageTopicFormatName, context.Request.QueryString["plugin"], string.Format("{0}.xml", nameMedia));
  754. // Chargement du document topic XAfp
  755. //TODO du ou des topics
  756. using (var buffer = new MemoryStream())
  757. {
  758. GetMedia(buffer, VirtualDirectory, Constants._storageTopicFormatName, context.Request.QueryString["plugin"], string.Format("{0}.xml", nameMedia));
  759. buffer.Position = 0;
  760. topicDocument.Load(buffer);
  761. }
  762. // Suppression des éléments en excédent et ajout du parentUno
  763. var bag = topicDocument.DocumentElement.SelectSingleNode("Bag");
  764. var rmv = 0;
  765. int currentI = 0;
  766. foreach (XmlNode item in bag.SelectNodes("Item"))
  767. {
  768. // présence de topicId ?
  769. //UpdateRating(context, item);
  770. if (((XmlElement)item).HasAttribute("topicId"))
  771. {
  772. if (topicDeclaration.Topics.SelectSingleNode(string.Format("*[@id='{0}']", ((XmlElement)item).GetAttribute("topicId"))) == null)
  773. {
  774. bag.RemoveChild(((XmlElement)item));
  775. rmv++;
  776. }
  777. else
  778. {
  779. ((XmlElement)item).RemoveAttribute("topicId");
  780. if (int.Parse(((XmlElement)item).GetAttributeValue("index", "0")) < maxEntries + rmv)
  781. {
  782. if (currentI < startAt)
  783. {
  784. bag.RemoveChild(((XmlElement)item));
  785. //currentI++;
  786. }
  787. else
  788. {
  789. ((XmlElement)item).RemoveAttribute("index");
  790. }
  791. currentI++;
  792. }
  793. else
  794. {
  795. bag.RemoveChild(((XmlElement)item));
  796. }
  797. }
  798. }
  799. else if (int.Parse(((XmlElement)item).GetAttributeValue("index", "0")) < maxEntries + rmv)
  800. {
  801. if (currentI < startAt)
  802. {
  803. bag.RemoveChild(((XmlElement)item));
  804. // rmv++;
  805. }
  806. else
  807. {
  808. ((XmlElement)item).RemoveAttribute("index");
  809. }
  810. currentI++;
  811. }
  812. else
  813. bag.RemoveChild(((XmlElement)item));
  814. }
  815. // Modification NumberOfItems
  816. var nbi = topicDocument.DocumentElement.SelectSingleNode("Head/NumberOfItems");
  817. if (nbi != null)
  818. nbi.InnerText = bag.SelectNodes("Item").Count.ToString();
  819. if (topicDocument.DocumentElement.SelectSingleNode("Xafp/CatchLine") != null)
  820. {
  821. topicDocument.DocumentElement.RemoveChild(topicDocument.DocumentElement.SelectSingleNode("Xafp/CatchLine"));
  822. }
  823. // Ajout namespace xml
  824. var topicDocumentNavigator = topicDocument.CreateNavigator();
  825. var topicDocumentManager = new XmlNamespaceManager(topicDocumentNavigator.NameTable);
  826. topicDocumentManager.AddNamespace("xml", "http://www.w3.org/XML/1998/namespace");
  827. // Attributs obligatoires
  828. if (topicDocument.DocumentElement.SelectSingleNode("@lang", topicDocumentManager) == null)
  829. topicDocument.DocumentElement.SetAttribute("xml:lang", topicDeclaration.Topics.GetAttribute("lang"));
  830. // Mise en mémoire
  831. using (var buffer = new MemoryStream())
  832. {
  833. topicDocument.Save(buffer);
  834. topic = new CachedDocument(buffer.ToArray(), topicInfo.LastWriteTimeUtc);
  835. #if DEBUG && TRACE_LASTMODIFIEDTOPIC
  836. StringBuilder text2;
  837. text2 = new StringBuilder();
  838. text2.AppendLine(string.Format("Topic Local ID {0} lastmodified {1} lastAccessTime {2} ", LocalId, topicInfo.LastWriteTimeUtc, topicInfo.LastAccessTimeUtc ));
  839. Process.Trace(text2.ToString(), "LastModified topic", System.Diagnostics.EventLogEntryType.Information);
  840. #endif
  841. }
  842. // Mise en cache
  843. // il faut aussi faire une dépendance selon le site...
  844. // doit on le cacher?
  845. StringsCachedDepency.Add(topicInfo.FullName);
  846. if (_ExpireCacheVote != null)
  847. context.Cache.Insert(sCacheReference, topic, new CacheDependency(StringsCachedDepency.ToArray()), System.Web.Caching.Cache.NoAbsoluteExpiration, (TimeSpan)_ExpireCacheVote);
  848. else
  849. context.Cache.Insert(sCacheReference, topic, new CacheDependency(StringsCachedDepency.ToArray()));
  850. }// topic == rated etc.
  851. }
  852. }
  853. catch (Exception e2)
  854. {
  855. mes = e2.Message;
  856. Process.Trace(e2, System.Diagnostics.EventLogEntryType.Error);
  857. #if DEBUG && DEBUGDEBE
  858. try
  859. {
  860. Process.Trace(e2, System.Diagnostics.EventLogEntryType.Error);
  861. System.Diagnostics.EventLog.WriteEntry("AFP Iphone", e2.StackTrace, System.Diagnostics.EventLogEntryType.Error);
  862. }
  863. catch
  864. { }
  865. #endif
  866. }
  867. finally
  868. {
  869. Monitor.Exit(_lockTopicCache);
  870. }
  871. // Vérification du cache
  872. Boolean bCache = true;
  873. if (context.Request.Headers.AllKeys.Contains("Cache-Control"))
  874. if (context.Request.Headers["Cache-Control"].ToLower() == "no-cache")
  875. bCache = false;
  876. if (context.Request.Headers.AllKeys.Contains("Pragma"))
  877. {
  878. // doit-on faire une boucle?
  879. if (context.Request.Headers["Pragma"].ToLower() == "no-cache")
  880. bCache = false;
  881. }
  882. if (bCache)
  883. if (context.Request.Headers.AllKeys.Contains("If-Modified-Since") && topic != null)
  884. if (topic.LastModified.ToUniversalTime().Subtract(DateTime.Parse(context.Request.Headers["If-Modified-Since"])).TotalSeconds <= 1)
  885. {
  886. context.Response.AddHeader("cache-control", "public");
  887. context.Response.StatusCode = 304;
  888. return;
  889. }
  890. #if DEBUG && TRACE_LASTMODIFIEDTOPIC
  891. StringBuilder text;
  892. text = new StringBuilder();
  893. text.AppendLine(string.Format ("Topic Local ID {0} lastmodified {1} " , LocalId , topic.LastModified.ToUniversalTime()) );
  894. Process.Trace(text.ToString(),"LastModified topic",System.Diagnostics.EventLogEntryType.Information );
  895. #endif
  896. // Préparation Http
  897. WebApplication.PageSetHeaders(new Dictionary<string, string>
  898. {
  899. { "##LM##", topic.LastModified.ToUniversalTime ().ToHTTPHeaderString () } ,
  900. { "##ET##", topic.Checksum } ,
  901. { "##EXP##", DateTime.UtcNow.ToUniversalTime ().AddSeconds (WebApplication.GetExpires()).ToHTTPHeaderString()}
  902. });
  903. context.Response.Buffer = true;
  904. context.Response.BufferOutput = true;
  905. context.Response.ContentType = "text/xml";
  906. // Ecriture du topic
  907. context.Response.BinaryWrite(topic.Document);
  908. // Compression Gzip
  909. if (context.Request.ServerVariables.AllKeys.Contains("HTTP_ACCEPT_ENCODING") && Convert.ToString(context.Request.ServerVariables["HTTP_ACCEPT_ENCODING"]).IndexOf("gzip") > -1)
  910. {
  911. context.Response.AddHeader("Content-Encoding", "gzip");
  912. context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
  913. }
  914. // Reporting
  915. Process.Set(WebApplication.PageName, "Hits", System.Diagnostics.EventLogEntryType.Information);
  916. }
  917. catch (Exception e)
  918. {
  919. // Reporting
  920. Process.Trace(WebApplication.PageName, string.Format("error {0}. Requested uno {1}", e.ToString(), uno), System.Diagnostics.EventLogEntryType.FailureAudit);
  921. Process.Set(WebApplication.PageName, e.Message, System.Diagnostics.EventLogEntryType.FailureAudit);
  922. // Préparation Http
  923. context.Response.Buffer = true;
  924. context.Response.BufferOutput = true;
  925. context.Response.ContentType = "text/xml";
  926. context.Response.ClearContent();
  927. // XAfp par défaut
  928. var defaultXml = XmlWriter.Create(context.Response.OutputStream);
  929. defaultXml.WriteStartElement("Xafp");
  930. {
  931. // Xafp
  932. defaultXml.WriteAttributeString("type", "collection");
  933. defaultXml.WriteAttributeString("uno", context.Request.QueryString["uno"]);
  934. defaultXml.WriteStartElement("Head");
  935. {
  936. // Xafp/Head
  937. defaultXml.WriteElementString("Name", "-");
  938. defaultXml.WriteElementString("DateCreated", DateTime.UtcNow.ToXmlElementString());
  939. defaultXml.WriteElementString("DateUpdated", DateTime.UtcNow.ToXmlElementString());
  940. defaultXml.WriteElementString("NumberOfItems", "0");
  941. }
  942. defaultXml.WriteEndElement();
  943. // /Xafp/Head
  944. defaultXml.WriteElementString("Bag", string.Empty);
  945. }
  946. defaultXml.WriteEndElement();
  947. // /Xafp
  948. #if DEBUG
  949. defaultXml.WriteComment(string.Format("e : {0} \n Stack trace {3} e2 :{1} debug : {2}", e.Message, mes, dmes, e.StackTrace));
  950. #endif
  951. defaultXml.Flush();
  952. }
  953. }
  954. /// <summary>
  955. /// construit les topics des plus votés...
  956. /// </summary>
  957. /// <param name="context"></param>
  958. /// <param name="topic"></param>
  959. private static XmlDocument BuildRateTopic(HttpContext context, String topicType, int MaxEntries, TimeSpan TimeCacheVote ,string lang )
  960. {
  961. // on va chercher la liste sur les differents serveurs.. .
  962. XmlDocument xRes = null;
  963. string lEndPointName = "";
  964. ProcessorClient processorRated;
  965. String DocFromService = "";
  966. foreach (string Vd in _services.Keys)
  967. {
  968. try
  969. {
  970. XmlDocument xDocFromService = new XmlDocument();
  971. DocFromService = "";
  972. int type = 1;
  973. //lEndPointName = ((PathAndWCF)_services[Vd]).EndPointName ;
  974. lEndPointName = GetEndPointName(context);
  975. processorRated = new ProcessorClient(lEndPointName);
  976. #if DEBUG && DEBUG_VOTE
  977. Process.Trace(string.Format("on incorpore {0} : ", lEndPointName), System.Diagnostics.EventLogEntryType.Information);
  978. #endif
  979. // on a le lien vers le serveur
  980. switch (topicType)
  981. {
  982. case "heart":
  983. DocFromService = processorRated.GetHeartRatedList("", GetProductName(context, false), context.Request.QueryString["uno"], TimeCacheVote, MaxEntries,lang);
  984. type = 0;
  985. break;
  986. case "rated":
  987. DocFromService = processorRated.GetArticleRatedList("", GetProductName(context, false), context.Request.QueryString["uno"], TimeCacheVote, MaxEntries, lang);
  988. type = 1;
  989. break;
  990. case "mostviewed":
  991. DocFromService = processorRated.GetMostViewed("", GetProductName(context, false), context.Request.QueryString["uno"], TimeCacheVote, MaxEntries);
  992. type = 2;
  993. break;
  994. }
  995. #if DEBUG && DEBUGTRACERATING
  996. Process.Trace(string.Format(" DocFromService{0} <==> {1}", DocFromService, lEndPointName ), System.Diagnostics.EventLogEntryType.Information);
  997. #endif
  998. if (string.IsNullOrEmpty(DocFromService) == false)
  999. {
  1000. #if DEBUG && DEBUG_VOTE
  1001. Process.Trace(string.Format("on incorpore {0} : ", lEndPointName), System.Diagnostics.EventLogEntryType.Information);
  1002. #endif
  1003. if (xRes == null)
  1004. {
  1005. // on est sur le premier
  1006. xRes = new XmlDocument();
  1007. xRes.LoadXml(DocFromService);
  1008. }
  1009. else
  1010. { // on incorpore
  1011. xDocFromService.LoadXml(DocFromService);
  1012. xRes = Mixte(xRes, xDocFromService, MaxEntries, type);
  1013. }
  1014. }
  1015. processorRated.Dispose();
  1016. }
  1017. catch (Exception debe)
  1018. {
  1019. // on prend le topic généré?
  1020. Process.Trace(debe, System.Diagnostics.EventLogEntryType.Error);
  1021. #if DEBUG
  1022. try
  1023. {
  1024. Process.Trace(debe, System.Diagnostics.EventLogEntryType.Error);
  1025. System.Diagnostics.EventLog.WriteEntry("AFP Iphone", debe.StackTrace, System.Diagnostics.EventLogEntryType.Error);
  1026. }
  1027. catch
  1028. { }
  1029. xRes = new XmlDocument();
  1030. Process.Trace(string.Format("{0}<!-- on va chercher sur : {3} topicType {4}--> <!-- DocFromService {5} --> <!--{1}-->{2}", "<ERROR>", debe.ToString(), "</ERROR>", lEndPointName, topicType, DocFromService), System.Diagnostics.EventLogEntryType.Error);
  1031. xRes.LoadXml(string.Format("{0}<!-- on va chercher sur : {3} topicType {4}--> <!-- DocFromService {5} --> <!--{1}-->{2}", "<ERROR>", debe.ToString(), "</ERROR>", lEndPointName, topicType, DocFromService));
  1032. #endif
  1033. }
  1034. }
  1035. return xRes;
  1036. }
  1037. // string.Format("{0}{1}", (((double)row["averageRating"] * 1000) / (1 + (Math.Truncate(DateTime.Now.Subtract(newsDate).TotalDays) * 10))).ToString("0000"), ((int)row["votes"]).ToString("0000000000"));
  1038. /// <summary>
  1039. /// Fusionne deux resultats de vote venant de deux services différents !!!
  1040. /// </summary>
  1041. /// <param name="BuildedRes"></param>
  1042. /// <param name="xDocFromService"></param>
  1043. /// <param name="MaxEntries"></param>
  1044. /// <param name="topicType"></param>
  1045. /// <returns></returns>
  1046. private static XmlDocument Mixte(XmlDocument BuildedRes, XmlDocument xDocFromService, int MaxEntries, int topicType)
  1047. {
  1048. XmlDocument xRes = new XmlDocument();
  1049. xRes.LoadXml("<Xafp><Bag/></Xafp>");
  1050. XmlNode Xbag = xRes.SelectSingleNode("//Xafp/Bag");
  1051. XmlNode SourceItem;
  1052. XmlNode NewItem;
  1053. int nbItem;
  1054. Boolean Exit = false;
  1055. XmlNode lastInserted = null;
  1056. xRes.SelectSingleNode("//Xafp").InsertBefore(xRes.ImportNode(BuildedRes.SelectSingleNode("//Xafp/Head"), true), Xbag);
  1057. nbItem = BuildedRes.DocumentElement.SelectSingleNode("//Xafp/Head/NumberOfItems").Value.toInt();
  1058. SourceItem = BuildedRes.SelectSingleNode("//Xafp/Bag/Item");
  1059. NewItem = xDocFromService.SelectSingleNode("//Xafp/Bag/Item");
  1060. if (NewItem == null) Exit = true; // si pas de resultat on sort de suite...
  1061. while (Exit == false)
  1062. {
  1063. if (nbItem <= MaxEntries)
  1064. {
  1065. if (SourceItem == null)
  1066. {
  1067. // recopie de tous les noeuds restant dans le source
  1068. while (nbItem <= MaxEntries && Exit == false)
  1069. {
  1070. if (NewItem != null)
  1071. {
  1072. XmlNode ImportedNode;
  1073. if (lastInserted == null)
  1074. {
  1075. ImportedNode = xRes.ImportNode(NewItem, true);
  1076. if (ImportedNode == null)
  1077. Exit = true;
  1078. lastInserted = Xbag.AppendChild(ImportedNode);
  1079. }
  1080. else
  1081. {
  1082. ImportedNode = xRes.ImportNode(NewItem, true);
  1083. if (ImportedNode == null)
  1084. Exit = true;
  1085. else
  1086. {
  1087. try
  1088. {
  1089. lastInserted = Xbag.InsertAfter(ImportedNode, lastInserted);
  1090. }
  1091. catch
  1092. {
  1093. Process.Trace(string.Format("ImporteNode {0}", ImportedNode.InnerXml), System.Diagnostics.EventLogEntryType.Information);
  1094. Process.Trace(string.Format("lastInserted {0}", lastInserted.InnerXml), System.Diagnostics.EventLogEntryType.Information);
  1095. Process.Trace(string.Format("Xbag {0}", Xbag.InnerXml), System.Diagnostics.EventLogEntryType.Information);
  1096. }
  1097. }
  1098. }
  1099. NewItem = NewItem.NextSibling;
  1100. }
  1101. if (NewItem == null) Exit = true;
  1102. nbItem++;
  1103. }
  1104. Exit = true;
  1105. }
  1106. if (NewItem == null && SourceItem != null)
  1107. {
  1108. //recopie de tous les noeuds restant dans le New
  1109. while (nbItem <= MaxEntries && Exit == false)
  1110. {
  1111. if (lastInserted == null)
  1112. {
  1113. lastInserted = Xbag.AppendChild(xRes.ImportNode(SourceItem, true));
  1114. }
  1115. else
  1116. {
  1117. lastInserted = Xbag.InsertAfter(xRes.ImportNode(SourceItem, true), lastInserted);
  1118. }
  1119. SourceItem = SourceItem.NextSibling;
  1120. if (SourceItem == null) Exit = true;
  1121. nbItem++;
  1122. }
  1123. Exit = true;
  1124. }
  1125. if (Exit != true)
  1126. {
  1127. nbItem += 1;
  1128. double averageratingFromSource = getGlobalRate(SourceItem, topicType);
  1129. double averageratingFromNew = getGlobalRate(NewItem, topicType);
  1130. DateTime DtFromSource = getDate(SourceItem, topicType);
  1131. DateTime DtFromNew = getDate(NewItem, topicType);
  1132. int voteFromSource = getVote(SourceItem, topicType);
  1133. int voteFromNew = getVote(NewItem, topicType);
  1134. string ratefromsource = string.Format("{0}{1}", ((averageratingFromSource * 1000) / (1 + (Math.Truncate(DateTime.Now.Subtract(DtFromSource).TotalDays) * 10))).ToString("0000"), voteFromSource.ToString("0000000000"));
  1135. string ratefromNEw = string.Format("{0}{1}", ((averageratingFromNew * 1000) / (1 + (Math.Truncate(DateTime.Now.Subtract(DtFromNew).TotalDays) * 10))).ToString("0000"), (voteFromNew).ToString("0000000000"));
  1136. if (ratefromsource.CompareTo(ratefromNEw) > 0)
  1137. {
  1138. if (nbItem == 1)
  1139. {
  1140. lastInserted = Xbag.AppendChild(xRes.ImportNode(SourceItem, true));
  1141. }
  1142. else
  1143. {
  1144. lastInserted = Xbag.InsertAfter(xRes.ImportNode(SourceItem, true), lastInserted);
  1145. }
  1146. }
  1147. else
  1148. {
  1149. if (nbItem == 1)
  1150. {
  1151. lastInserted = Xbag.AppendChild(xRes.ImportNode(NewItem, true));
  1152. }
  1153. else
  1154. {
  1155. lastInserted = Xbag.InsertAfter(xRes.ImportNode(SourceItem, true), lastInserted);
  1156. }
  1157. }
  1158. SourceItem = SourceItem.NextSibling;
  1159. NewItem = NewItem.NextSibling;
  1160. //if( SourceItem.Attributes[""]
  1161. }
  1162. }
  1163. else
  1164. { Exit = true; }
  1165. }
  1166. xRes.DocumentElement.SelectSingleNode("//Xafp/Head/NumberOfItems").InnerText = nbItem.ToString();
  1167. return xRes;
  1168. }
  1169. private static int getVote(XmlNode SourceItem, int topicType)
  1170. {
  1171. try
  1172. {
  1173. if (topicType != 0)
  1174. {
  1175. return SourceItem.Attributes["numberOfVote"].Value.toInt();
  1176. }
  1177. else
  1178. {
  1179. return SourceItem.SelectSingleNode("Bag").Attributes["numberOfVote"].Value.toInt();
  1180. }
  1181. }
  1182. catch (Exception ex)
  1183. {
  1184. #if DEBUG
  1185. Process.Trace(string.Format("{0} {1} ", ex.ToString(), SourceItem.InnerXml), System.Diagnostics.EventLogEntryType.Warning);
  1186. #endif
  1187. return 0;
  1188. }
  1189. }
  1190. private static DateTime getDate(XmlNode SourceItem, int topicType)
  1191. {
  1192. String articledate;
  1193. articledate = SourceItem.SelectSingleNode("//DatePublished").InnerText;
  1194. return DateTime.ParseExact(articledate, "yyyyMMddTHHmmssZ", System.Globalization.CultureInfo.InvariantCulture);
  1195. }
  1196. private static double getGlobalRate(XmlNode SourceItem, int topicType)
  1197. {
  1198. try
  1199. {
  1200. if (topicType != 0)
  1201. {
  1202. return SourceItem.Attributes["globalRate"].Value.toInt();
  1203. }
  1204. else
  1205. {
  1206. return SourceItem.SelectSingleNode("Bag").Attributes["globalRate"].Value.toInt();
  1207. }
  1208. }
  1209. catch (Exception ex)
  1210. {
  1211. #if DEBUG
  1212. Process.Trace(string.Format("{0} {1} ", ex.ToString(), SourceItem.InnerXml), System.Diagnostics.EventLogEntryType.Warning);
  1213. #endif
  1214. return 0;
  1215. }
  1216. }
  1217. private static string GetLang(string uno)
  1218. {
  1219. XmlElement xTopic = (XmlElement)_BuildedSiteConfiguration.SelectSingleNode(string.Format("//topic[@uno='{0}']", uno));
  1220. string reslang ="";
  1221. try
  1222. {
  1223. reslang = GetLocalOrParentAttribute(xTopic, "lang", "sites");
  1224. }catch
  1225. {}
  1226. return reslang ;
  1227. }
  1228. /// <summary>
  1229. /// int --> (string) TopicImplementation.TopicType
  1230. /// </summary>
  1231. /// <param name="uno"></param>
  1232. /// <returns></returns>
  1233. private static string GetType(string uno)
  1234. {
  1235. XmlElement xTopic = (XmlElement)_BuildedSiteConfiguration.SelectSingleNode(string.Format("//topic[@uno='{0}']", uno));
  1236. if (xTopic != null && xTopic.HasAttribute("type"))
  1237. {
  1238. int type;
  1239. if (int.TryParse(xTopic.Attributes["type"].Value, out type))
  1240. {
  1241. #if DEBUG && DEBUGDEBE
  1242. try
  1243. {
  1244. System.Diagnostics.EventLog.WriteEntry("AFP Iphone",
  1245. string.Format(" UNO {0} --> type {1} --> {2}", uno, type.ToString() , Enum.GetName(typeof(TopicImplementation.TopicType), type))
  1246. ,System.Diagnostics.EventLogEntryType.Error);
  1247. }
  1248. catch
  1249. { }
  1250. #endif
  1251. return Enum.GetName(typeof(TopicImplementation.TopicType), type);
  1252. }
  1253. }
  1254. #if DEBUG && DEBUGDEBE
  1255. try
  1256. {
  1257. System.Diagnostics.EventLog.WriteEntry("AFP Iphone",
  1258. string.Format(" UNO {0} --> type {1} --> standard", uno, xTopic.Attributes["type"].Value )
  1259. ,System.Diagnostics.EventLogEntryType.Error);
  1260. }
  1261. catch
  1262. { }
  1263. #endif
  1264. return Enum.GetName(typeof(TopicImplementation.TopicType), 0); //standard
  1265. }
  1266. /// <summary>
  1267. /// enregistre les pages lues en DB...
  1268. /// </summary>
  1269. /// <param name="context"></param>
  1270. private static void RequestViewed(HttpContext context)
  1271. {
  1272. #if DEBUG && DEBUGVIEWED
  1273. System.Diagnostics.Debugger.Break();
  1274. #endif
  1275. context.Response.Buffer = true;
  1276. context.Response.BufferOutput = true;
  1277. context.Response.ContentType = "text/xml";
  1278. context.Response.ClearContent();
  1279. var defaultXml = XmlWriter.Create(context.Response.OutputStream);
  1280. defaultXml.WriteStartElement("Ok");
  1281. defaultXml.WriteEndElement();
  1282. defaultXml.Flush();
  1283. try
  1284. {
  1285. // connexion au service de production...
  1286. string productId = GetProductName(context, false);
  1287. string device = GetDeviceName(context);
  1288. using (var processorClient = new ProcessorClient(GetEndPointName(context)))
  1289. {
  1290. processorClient.InsertViewed(
  1291. productId,
  1292. context.Request.QueryString["uno"],
  1293. context.Request.QueryString["item"],
  1294. context.Request.QueryString["mediaId"],
  1295. device)
  1296. ;
  1297. }
  1298. }
  1299. catch (Exception e)
  1300. {
  1301. Process.Trace(e, System.Diagnostics.EventLogEntryType.Error);
  1302. }
  1303. }
  1304. private static void RequestNeutral(HttpContext context)
  1305. {
  1306. context.Response.Buffer = true;
  1307. context.Response.BufferOutput = true;
  1308. context.Response.ContentType = "text/xml";
  1309. context.Response.ClearContent();
  1310. var defaultXml = XmlWriter.Create(context.Response.OutputStream);
  1311. defaultXml.WriteStartElement("Ok");
  1312. defaultXml.WriteEndElement();
  1313. defaultXml.Flush();
  1314. }
  1315. public void ProcessRequest(HttpContext context)
  1316. {
  1317. // Bufferisation
  1318. #if DEBUG && TRACE_CONTEXT
  1319. int loop1, loop2;
  1320. System.Collections.Specialized.NameValueCollection coll;
  1321. // Load Header collection into NameValueCollection object.
  1322. coll = context.Request.Headers;
  1323. StringBuilder text;
  1324. text = new StringBuilder();
  1325. //text.AppendLine(message.Message);
  1326. // Put the names of all keys into a string array.
  1327. String[] arr1 = coll.AllKeys;
  1328. for (loop1 = 0; loop1 < arr1.Length; loop1++)
  1329. {
  1330. text.AppendLine("");
  1331. text.AppendLine(string.Format("Key {0}",arr1[loop1]));
  1332. // Get all values under this key.
  1333. String[] arr2=coll.GetValues(arr1[loop1]);
  1334. for (loop2 = 0; loop2 < arr2.Length; loop2++)
  1335. {
  1336. text.AppendLine(string.Format(" Value {0}", arr2[loop2]));
  1337. }
  1338. }
  1339. Process.Trace(text.ToString(), "TraceRequest", System.Diagnostics.EventLogEntryType.Information);
  1340. #endif
  1341. context.Response.Buffer = true;
  1342. context.Response.BufferOutput = true;
  1343. List<String> StringsCachedDepency = null;
  1344. DateTime CachedDate = System.DateTime.MinValue;
  1345. Boolean reDoSites = false;
  1346. String page = Path.GetFileNameWithoutExtension(context.Request.Url.Segments[context.Request.Url.Segments.Length - 1]).ToLower();
  1347. if (_services == null && page != "sites")
  1348. {
  1349. try
  1350. {
  1351. Monitor.Enter(_lockRootCache);
  1352. _BuildedSiteConfiguration = BuildSites(out StringsCachedDepency, out CachedDate);
  1353. }
  1354. finally
  1355. {
  1356. Monitor.Exit(_lockRootCache);
  1357. }
  1358. reDoSites = true;
  1359. }
  1360. if (string.IsNullOrEmpty(context.Request.QueryString["rebuild"]) == false)
  1361. {
  1362. reDoSites = true;
  1363. }
  1364. switch (page)
  1365. {
  1366. case "about":
  1367. RequestAbout(context);
  1368. break;
  1369. case "check":
  1370. RequestCheck(context);
  1371. break;
  1372. case "description":
  1373. RequestDescription(context);
  1374. break;
  1375. case "disclaimer":
  1376. RequestDisclaimer(context);
  1377. break;
  1378. case "products":
  1379. RequestProducts(context, StringsCachedDepency, CachedDate);
  1380. break;
  1381. case "rating":
  1382. RequestRating(context);
  1383. break;
  1384. case "sites":
  1385. RequestSites(context, reDoSites);
  1386. break;
  1387. case "topic":
  1388. RequestTopic(context);
  1389. break;
  1390. case "mostviewed":
  1391. RequestMostViewed(context);
  1392. break;
  1393. /* case "view":
  1394. RequestView(context);
  1395. break;
  1396. */
  1397. case "viewed":
  1398. RequestViewed(context);
  1399. break;
  1400. case "emailed":
  1401. case "saved":
  1402. RequestNeutral(context);
  1403. break;
  1404. case "location":
  1405. RequestAround(context);
  1406. break;
  1407. default:
  1408. context.Response.StatusCode = 404;
  1409. break;
  1410. }
  1411. // Fin de traitement
  1412. context.Response.End();
  1413. }
  1414. private void RequestAround(HttpContext context)
  1415. {
  1416. // on va chercher toutes les dépeches avoisinant le point donné
  1417. // par latitude longitude
  1418. // limité par distance
  1419. // Préparation Http
  1420. WebApplication.PageSetHeaders();
  1421. context.Response.ContentType = "text/xml";
  1422. // Récupération des informations
  1423. string productId = GetProductName(context, true);
  1424. string device = GetDeviceName(context);
  1425. string endPointName = GetEndPointName(context);
  1426. string longitude = context.Request.QueryString["longitude"];
  1427. string latitude = context.Request.QueryString["latitude"];
  1428. string range = context.Request.QueryString["range"];
  1429. string lang = context.Request.QueryString["lang"];
  1430. if (string.IsNullOrEmpty(range))
  1431. {
  1432. range = "30"; //TO DO configurer par le fichier XML
  1433. }
  1434. /*
  1435. lEndPointName = GetEndPointName(context);
  1436. processorRated = new ProcessorClient(lEndPointName);
  1437. DocFromService = processorRated.GetHeartRatedList("", GetProductName(context, false), context.Request.QueryString["uno"], TimeCacheVote, MaxEntries);
  1438. */
  1439. try
  1440. {
  1441. Process.Trace(string.Format("AroundMe endpoint Name {0}", endPointName), System.Diagnostics.EventLogEntryType.Information);
  1442. var processorClient = new ProcessorClient(endPointName);
  1443. string reponse = processorClient.GetAroundMe(latitude, longitude, range, 40, lang);
  1444. Process.Trace(string.Format("AroundMe retour du server {0}", reponse), System.Diagnostics.EventLogEntryType.Information);
  1445. context.Response.Write(reponse );
  1446. }
  1447. catch (Exception e)
  1448. {
  1449. // Reporting
  1450. Process.Trace(WebApplication.PageName, string.Format(" endpointName {0} error {1} ", endPointName, e.ToString()), System.Diagnostics.EventLogEntryType.Error);
  1451. Process.Set(WebApplication.PageName, string.Format(" endpointName {0} error {1} ", endPointName, e.Message), System.Diagnostics.EventLogEntryType.Error);
  1452. // Réponse
  1453. context.Response.ClearContent();
  1454. context.Response.Write(new ExceptionDocument(e, string.Format(" {1} on endpointName {0} ProductId {2}", endPointName, "Rating error", productId)));
  1455. }
  1456. }
  1457. private void RequestMostViewed(HttpContext context)
  1458. {
  1459. throw new NotImplementedException();
  1460. }
  1461. static XmlDocument BuildSites(out List<String> sitesPath, out DateTime CachedDate)
  1462. {
  1463. XmlDocument WebConfig = Process.Configuration;
  1464. string VdG = "";
  1465. //Process.FileConfigurationPath
  1466. Process.ReloadConfiguration(); // il faudrait le faire uniquement pour le changement du fichier de config...
  1467. try
  1468. {
  1469. XmlElement xCache = (XmlElement)Process.Configuration.SelectSingleNode("//config/rated");
  1470. if (xCache != null)
  1471. {
  1472. if (xCache.HasAttribute("expiration"))
  1473. {
  1474. _ExpireCacheVote = xCache.Attributes["expiration"].Value.DurationToTimeSpan();
  1475. }
  1476. if (xCache.HasAttribute("buildedWithXDay"))
  1477. {
  1478. _BuildWithXDay = xCache.Attributes["buildedWithXDay"].Value.DurationToTimeSpan();
  1479. }
  1480. }
  1481. XmlElement xDir = (XmlElement)Process.Configuration.SelectSingleNode("//*[@virtualDir]");
  1482. if (xDir != null)
  1483. VdG = xDir.Attributes["virtualDir"].Value;
  1484. }
  1485. catch
  1486. {
  1487. _ExpireCacheVote = null; // 20 mn
  1488. _BuildWithXDay = null; //30 jours
  1489. }
  1490. sitesPath = new List<string>();
  1491. CachedDate = System.DateTime.MinValue;
  1492. XmlDocument buildedSites = new XmlDocument();
  1493. XmlNode xbuildedIcones;
  1494. String FilePathConfig = Process.FileConfigurationPath;
  1495. if (_VdByTopicId == null)
  1496. {
  1497. _VdByTopicId = new System.Collections.Hashtable();
  1498. }
  1499. else
  1500. {
  1501. _VdByTopicId.Clear();
  1502. }
  1503. if (string.IsNullOrEmpty(FilePathConfig) == false)
  1504. {
  1505. sitesPath.Add(FilePathConfig);
  1506. Process.Trace(string.Format("Added {0} in sitesPath ", FilePathConfig), System.Diagnostics.EventLogEntryType.Information);
  1507. }
  1508. // le generated XMl n'est pas bon...
  1509. if (_services == null)
  1510. {
  1511. #if DEBUG
  1512. Process.Trace(WebApplication.PageName, "Build Sites start", System.Diagnostics.EventLogEntryType.Information);
  1513. #endif
  1514. _services = new System.Collections.Hashtable();
  1515. _idVD = new System.Collections.Hashtable();
  1516. // lecture de la configuration des parametres WCF
  1517. foreach (XmlElement xService in WebConfig.SelectSingleNode("//config/services").ChildNodes)
  1518. {
  1519. PathAndWCF newconfig = new PathAndWCF();
  1520. if (xService.HasAttribute("endpoint"))
  1521. {
  1522. newconfig.EndPointName = xService.Attributes["endpoint"].Value;
  1523. }
  1524. // mandatory...
  1525. XmlDocument XConfigServices = new XmlDocument();
  1526. XConfigServices.Load(xService.Attributes["serviceConfigPath"].Value);
  1527. string BuildedStoragePath;
  1528. BuildedStoragePath = XConfigServices.SelectSingleNode("//config/storage").Attributes["storePath"].Value;
  1529. newconfig.RootPath = BuildedStoragePath;
  1530. string PathGeneratedXml = GetPath(BuildedStoragePath, Constants._storageSitesFormatName, Constants._storageSitesKey, Constants._storageSitesFileId);
  1531. if (string.IsNullOrEmpty(PathGeneratedXml) == false)
  1532. {
  1533. DateTime fd = System.IO.File.GetLastWriteTimeUtc(PathGeneratedXml);
  1534. if (CachedDate < fd)
  1535. CachedDate = fd;
  1536. sitesPath.Add(PathGeneratedXml);
  1537. XmlDocument loadX = new XmlDocument();
  1538. loadX.Load(PathGeneratedXml);
  1539. newconfig.GeneratedSites = new XmlDocument();
  1540. newconfig.GeneratedSites.LoadXml(loadX.OuterXml);
  1541. }
  1542. _services.Add(xService.Attributes["virtualDir"].Value, newconfig);
  1543. _idVD.Add(xService.Attributes["id"].Value, xService.Attributes["virtualDir"].Value);
  1544. }
  1545. }// if (_services == null )
  1546. buildedSites.LoadXml("<sites dataCenter='1'><icones/></sites>");
  1547. foreach (XmlAttribute xatt in WebConfig.SelectSingleNode("//config/sites").Attributes)
  1548. {
  1549. ((XmlElement)(buildedSites.SelectSingleNode("//sites"))).SetAttribute(xatt.Name, xatt.Value);
  1550. }
  1551. xbuildedIcones = buildedSites.SelectSingleNode("//icones");
  1552. foreach (XmlNode curWebSite in WebConfig.SelectNodes("//config/sites/site"))
  1553. {
  1554. XmlNode curResSites;
  1555. String ProductVoteName = "";
  1556. String CurProductId = "";
  1557. if (((XmlElement)curWebSite).HasAttribute("productVote"))
  1558. {
  1559. ProductVoteName = curWebSite.Attributes["productVote"].Value;
  1560. }
  1561. else
  1562. {
  1563. //TODO trace
  1564. }
  1565. if (((XmlElement)curWebSite).HasAttribute("id"))
  1566. {
  1567. CurProductId = curWebSite.Attributes["id"].Value;
  1568. }
  1569. else
  1570. {
  1571. //TODO trace
  1572. }
  1573. curResSites = buildedSites.DocumentElement.AppendChild(buildedSites.ImportNode(curWebSite, false));
  1574. if (((XmlElement)curResSites).HasAttribute("icon"))
  1575. {
  1576. curResSites.Attributes["icon"].Value = System.IO.Path.GetFileNameWithoutExtension(curResSites.Attributes["icon"].Value.Replace(@"\", "/"));
  1577. }
  1578. foreach (XmlNode curAdv in curWebSite.SelectNodes("advisories"))
  1579. {
  1580. curResSites.AppendChild(buildedSites.ImportNode(curAdv, true));
  1581. }
  1582. foreach (XmlNode curConfigTopics in curWebSite.SelectNodes("./topics"))
  1583. {
  1584. XmlNode curResTopics;
  1585. XmlDocument GeneratedSites;
  1586. curResTopics = curResSites.AppendChild(buildedSites.ImportNode(curConfigTopics, false));
  1587. foreach (XmlAttribute xXmlTopicAttribute in curConfigTopics.Attributes)
  1588. {
  1589. if (xXmlTopicAttribute.Name == "icon")
  1590. ((XmlElement)curResTopics).SetAttribute(xXmlTopicAttribute.Name, System.IO.Path.GetFileNameWithoutExtension(xXmlTopicAttribute.Value.Replace(@"\", "/")));
  1591. else
  1592. ((XmlElement)curResTopics).SetAttribute(xXmlTopicAttribute.Name, xXmlTopicAttribute.Value);
  1593. }
  1594. /* List<string> icons;
  1595. icons = new List<string>();
  1596. */
  1597. //GeneratedSites = new XmlDocument();
  1598. // partie de fusion des Documents sites filtré par le WebConfig...
  1599. foreach (XmlNode curConfigTopic in curConfigTopics.SelectNodes("topic"))
  1600. {
  1601. // il faut remplire le Generated Sites
  1602. string idVD = GetLocalOrParentAttribute((XmlElement)curConfigTopic, "service", "site");
  1603. if (string.IsNullOrEmpty(idVD) == false)
  1604. {
  1605. string vd = (string)_idVD[idVD];
  1606. // note determination storagepath
  1607. GeneratedSites = ((PathAndWCF)_services[vd]).GeneratedSites;
  1608. // on va aller chercher dans le site generé le topic correspondant
  1609. XmlAttribute xId = curConfigTopic.Attributes["id"];
  1610. string sId;
  1611. if (xId != null)
  1612. {
  1613. sId = string.Format("{0}__{1}", vd, xId.Value);
  1614. }
  1615. else
  1616. {
  1617. // pas d'Id il faut en generer un... ou pas
  1618. string type = ((int)Enum.Parse(typeof(TopicImplementation.TopicType), curConfigTopic.GetAttributeValue("type", TopicImplementation.TopicType.standard.ToString()))).ToString();
  1619. sId = string.Format("{2}_{0}_{1}_{3}",
  1620. curConfigTopic.GetAttributeValue("fullName", "").MyGetHashCode(),
  1621. type.MyGetHashCode(),
  1622. curConfigTopic.ParentNode.GetAttributeValue("name", "").MyGetHashCode(),
  1623. curWebSite.GetAttributeValue("id", "").MyGetHashCode()
  1624. );
  1625. }
  1626. if (_VdByTopicId.ContainsKey(sId) == false)
  1627. {
  1628. _VdByTopicId.Add(sId, ((PathAndWCF)_services[vd]).EndPointName);
  1629. }
  1630. else
  1631. {
  1632. if (((string)_VdByTopicId[sId]) != ((PathAndWCF)_services[vd]).EndPointName)
  1633. throw new Exception(string.Format("id for topic must be unique {0} : {1}//{2}", sId, (string)_VdByTopicId["sId"], ((PathAndWCF)_services[vd]).EndPointName));
  1634. }
  1635. XmlNode VirtualGeneratedTopic;
  1636. if (string.IsNullOrEmpty(sId) == false)
  1637. {
  1638. Boolean bSpecialTopics = false; // videorama diaporama etc.
  1639. VirtualGeneratedTopic = GeneratedSites.SelectSingleNode(string.Format("//topic[@id='{0}']", sId));
  1640. if (VirtualGeneratedTopic != null)
  1641. {
  1642. if (((XmlElement)VirtualGeneratedTopic).HasAttribute("type"))
  1643. {
  1644. string ttype = VirtualGeneratedTopic.Attributes["type"].Value;
  1645. if (ttype == "videorama" || ttype == "diaporama" || ttype == "7" || ttype == "8")
  1646. {
  1647. bSpecialTopics = true;
  1648. }
  1649. }
  1650. XmlNode curResTopic;
  1651. if (bSpecialTopics)
  1652. curResTopic = curResTopics.AppendChild(buildedSites.ImportNode(VirtualGeneratedTopic, false));
  1653. // on ne recupere pas la premiere catchLine... est-ce un souci
  1654. else
  1655. curResTopic = curResTopics.AppendChild(buildedSites.ImportNode(VirtualGeneratedTopic, true)); // on passe a true pour recuperer la cachtLine...
  1656. //rajout des icones
  1657. string ConfigIconName = curConfigTopic.GetAttributeValue("icon", "");
  1658. string generatedIconName = VirtualGeneratedTopic.GetAttributeValue("icon", "");
  1659. if (string.IsNullOrEmpty(ConfigIconName))
  1660. {
  1661. // on prend l'icone du topic généree par le service de prod.
  1662. string lIcon = curResTopic.GetAttributeValue("icon", "");
  1663. if (string.IsNullOrEmpty(lIcon) == false)
  1664. {
  1665. XmlNode IconInGeneratedSite = GeneratedSites.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", lIcon, "topic"));
  1666. if (IconInGeneratedSite != null)
  1667. if (xbuildedIcones.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", lIcon, "topic")) == null)
  1668. xbuildedIcones.AppendChild(buildedSites.ImportNode(IconInGeneratedSite, true));
  1669. XmlNode ThumbIconInGeneratedSite = GeneratedSites.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", lIcon, "thumbnail"));
  1670. if (ThumbIconInGeneratedSite != null)
  1671. if (xbuildedIcones.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", lIcon, "thumbnail")) == null)
  1672. xbuildedIcones.AppendChild(buildedSites.ImportNode(ThumbIconInGeneratedSite, true));
  1673. curResTopic.Attributes["icon"].Value = lIcon;
  1674. }
  1675. }
  1676. else
  1677. {
  1678. // on genere nous meme une icone ( surcharge) !!
  1679. XmlNode xNewIcon;
  1680. xNewIcon = CreateNewIcon(xbuildedIcones.OwnerDocument, ConfigIconName, curResTopic, "topic");
  1681. //xNewIcon = xbuildedIcones.OwnerDocument.CreateNode(
  1682. xbuildedIcones.AppendChild(xNewIcon);
  1683. // penser a castrer le path...
  1684. ((XmlElement)curResTopic).SetAttribute("icon", System.IO.Path.GetFileNameWithoutExtension(ConfigIconName.Replace(@"\", "/")));
  1685. }
  1686. //if (curConfigTopic.GetAttributeValue ("icon",""))
  1687. foreach (XmlAttribute xXmlTopicAttribute in curConfigTopic.Attributes)
  1688. {
  1689. if (xXmlTopicAttribute.Name != "icon" && xXmlTopicAttribute.Name != "type")
  1690. {
  1691. ((XmlElement)curResTopic).SetAttribute(xXmlTopicAttribute.Name, xXmlTopicAttribute.Value);
  1692. }
  1693. if (xXmlTopicAttribute.Name == "overrideuno")
  1694. {
  1695. // l'uno est forcé par la config... cas de reprise 1.1 par exemple
  1696. string strUno = curResTopic.Attributes["uno"].Value;
  1697. ((XmlElement)curResTopic).SetAttribute("newuno", strUno);
  1698. ((XmlElement)curResTopic).SetAttribute("uno", curConfigTopic.Attributes["overrideuno"].Value);
  1699. }
  1700. if (xXmlTopicAttribute.Name == "type")
  1701. {
  1702. try
  1703. {
  1704. string iType = ((int)Enum.Parse(typeof(TopicImplementation.TopicType), curConfigTopic.GetAttributeValue("type", TopicImplementation.TopicType.standard.ToString()))).ToString();
  1705. ((XmlElement)curResTopic).SetAttribute(xXmlTopicAttribute.Name, iType);
  1706. }
  1707. catch (Exception parsing)
  1708. {
  1709. Process.Trace(parsing, System.Diagnostics.EventLogEntryType.Warning);
  1710. ((XmlElement)curResTopic).RemoveAttribute(xXmlTopicAttribute.Name);
  1711. }
  1712. }
  1713. }
  1714. if (((XmlElement)curResTopic).HasAttribute("daily"))
  1715. {
  1716. Boolean value;
  1717. ((XmlElement)curResTopic).SetAttribute("daily", (bool.TryParse(curResTopic.GetAttributeValue("daily", "true"), out value)) ? "0" : "1");
  1718. // changement de sens pour aller avec les applications déposées :)
  1719. }
  1720. // Gestion des sous topics;
  1721. string parentType = curConfigTopic.GetAttributeValue("type", "");
  1722. // ici il faut inverser on doit se baser sur la
  1723. if (bSpecialTopics == false)
  1724. {
  1725. foreach (XmlNode curConfigSubTopic in curConfigTopic.SelectNodes("subtopic"))
  1726. {
  1727. string subId = curConfigSubTopic.Attributes["id"].Value;
  1728. XmlNode VirtualGeneratedSubTopic;
  1729. if (string.IsNullOrEmpty(parentType) == false)
  1730. {
  1731. // subId = string.Format("{0}__{1}", vd, subId);
  1732. if (!(parentType == "7" || parentType == "8" || parentType == "diaporama" || parentType == "magazin"))
  1733. {
  1734. subId = string.Format("{0}__{1}", vd, subId);
  1735. }
  1736. else
  1737. { }
  1738. }
  1739. else
  1740. subId = string.Format("{0}__{1}", vd, subId);
  1741. XmlNode SubFromGenerated = GeneratedSites.SelectSingleNode(string.Format("//topic[@id='{0}'] | //subtopic[@id='{0}']", subId));
  1742. if (SubFromGenerated != null)
  1743. {
  1744. VirtualGeneratedSubTopic = buildedSites.ImportNode(curConfigSubTopic, true);
  1745. //recopie des attributs...
  1746. //GeneratedSites.SelectSingleNode(string.Format("//topic[@id='{0}']", subId));
  1747. foreach (XmlAttribute xXmlTopicAttribute in SubFromGenerated.Attributes)
  1748. {
  1749. if (xXmlTopicAttribute.Name != "icon" && xXmlTopicAttribute.Name != "type")
  1750. ((XmlElement)VirtualGeneratedSubTopic).SetAttribute(xXmlTopicAttribute.Name, xXmlTopicAttribute.Value);
  1751. if (xXmlTopicAttribute.Name == "type")
  1752. {
  1753. try
  1754. {
  1755. string iType = ((int)Enum.Parse(typeof(TopicImplementation.TopicType), curConfigTopic.GetAttributeValue("type", TopicImplementation.TopicType.standard.ToString()))).ToString();
  1756. ((XmlElement)VirtualGeneratedSubTopic).SetAttribute(xXmlTopicAttribute.Name, iType);
  1757. }
  1758. catch (Exception parsing)
  1759. {
  1760. Process.Trace(parsing, System.Diagnostics.EventLogEntryType.Warning);
  1761. ((XmlElement)VirtualGeneratedSubTopic).RemoveAttribute(xXmlTopicAttribute.Name);
  1762. }
  1763. }
  1764. if (xXmlTopicAttribute.Name == "icon")
  1765. {
  1766. string lIcon = xXmlTopicAttribute.Value;
  1767. // il faut rajouter un noeud de type Topic sinon le framework de l'Application
  1768. // ne prend pas en compte le thumbnail
  1769. XmlNode IconInGeneratedSite = GeneratedSites.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", lIcon, "topic"));
  1770. if (IconInGeneratedSite != null)
  1771. if (xbuildedIcones.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", lIcon, "topic")) == null)
  1772. xbuildedIcones.AppendChild(buildedSites.ImportNode(IconInGeneratedSite, true));
  1773. XmlNode ThumbIconInGeneratedSite = GeneratedSites.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", lIcon, "thumbnail"));
  1774. if (ThumbIconInGeneratedSite != null)
  1775. if (xbuildedIcones.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", lIcon, "thumbnail")) == null)
  1776. xbuildedIcones.AppendChild(buildedSites.ImportNode(ThumbIconInGeneratedSite, true));
  1777. ((XmlElement)VirtualGeneratedSubTopic).SetAttribute("icon", lIcon);
  1778. //curResTopic.Attributes["icon"].Value = lIcon;
  1779. }
  1780. }
  1781. if (((XmlElement)VirtualGeneratedSubTopic).HasAttribute("href"))
  1782. {
  1783. VirtualGeneratedSubTopic.Attributes["href"].Value = string.Format("{0}&product={1}", VirtualGeneratedSubTopic.Attributes["href"].Value, CurProductId);
  1784. }
  1785. if (((XmlElement)VirtualGeneratedSubTopic).HasAttribute("daily"))
  1786. {
  1787. Boolean value;
  1788. ((XmlElement)VirtualGeneratedSubTopic).SetAttribute("daily", (bool.TryParse(VirtualGeneratedSubTopic.GetAttributeValue("daily", "true"), out value)) ? "0" : "1");
  1789. }
  1790. if (SubFromGenerated.HasChildNodes)
  1791. {
  1792. VirtualGeneratedSubTopic.AppendChild(buildedSites.ImportNode(SubFromGenerated.FirstChild, true));
  1793. }
  1794. if (VirtualGeneratedSubTopic != null)
  1795. curResTopic.AppendChild(VirtualGeneratedSubTopic);
  1796. }//if (SubFromGenerated != null)
  1797. }
  1798. }
  1799. else
  1800. {
  1801. //==>bSpecialTopics = true
  1802. // on est dans le cadre d'un topic special demande IPAD ( topic a tri par table)
  1803. string buildedId = string.Format("{0}__{1}", vd, curConfigTopic.Attributes["id"].Value);
  1804. XmlNode BuildedContainerTopic = GeneratedSites.SelectSingleNode(string.Format("//topic[@id='{0}']", buildedId)); ;
  1805. foreach (XmlNode curBuildedSubTopic in BuildedContainerTopic.SelectNodes("subtopic"))
  1806. {
  1807. Boolean ok = true;
  1808. if (((XmlElement)curBuildedSubTopic).HasAttribute("Serve"))
  1809. if (curBuildedSubTopic.Attributes["Serve"].InnerText == "false")
  1810. ok = false;
  1811. if (ok)
  1812. {
  1813. string configId = curBuildedSubTopic.Attributes["id"].Value;
  1814. XmlNode curConfigSubTopic = curConfigTopic.SelectSingleNode(string.Format("subtopic[@id='{0}']", configId));
  1815. // il ne faut prendre en compte que le virtual ID voulu
  1816. // note ici ce n'est pas bon on duplique les noeuds
  1817. // encours
  1818. if (curConfigSubTopic != null)
  1819. {
  1820. // si il est présentable (filtre du fichier de config du site Web)
  1821. XmlNode VirtualGeneratedSubTopic = null;
  1822. VirtualGeneratedSubTopic = buildedSites.ImportNode(curConfigSubTopic, true);
  1823. // on copie les valeurs remarquables
  1824. foreach (XmlAttribute xXmlTopicAttribute in curBuildedSubTopic.Attributes)
  1825. {
  1826. if (xXmlTopicAttribute.Name != "icon" && xXmlTopicAttribute.Name != "type")
  1827. ((XmlElement)VirtualGeneratedSubTopic).SetAttribute(xXmlTopicAttribute.Name, xXmlTopicAttribute.Value);
  1828. if (xXmlTopicAttribute.Name == "type")
  1829. {
  1830. try
  1831. {
  1832. string iType = ((int)Enum.Parse(typeof(TopicImplementation.TopicType), curConfigTopic.GetAttributeValue("type", TopicImplementation.TopicType.standard.ToString()))).ToString();
  1833. ((XmlElement)VirtualGeneratedSubTopic).SetAttribute(xXmlTopicAttribute.Name, iType);
  1834. }
  1835. catch (Exception parsing)
  1836. {
  1837. Process.Trace(parsing, System.Diagnostics.EventLogEntryType.Warning);
  1838. ((XmlElement)VirtualGeneratedSubTopic).RemoveAttribute(xXmlTopicAttribute.Name);
  1839. }
  1840. }
  1841. if (xXmlTopicAttribute.Name == "icon")
  1842. {
  1843. string lIcon = xXmlTopicAttribute.Value;
  1844. // il faut rajouter une icone de type topic sinon
  1845. // le framework de l'application ne comprend pas qu'on est
  1846. // dans le cadre d'une custom icon
  1847. XmlNode IconInGeneratedSite = GeneratedSites.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", lIcon, "topic"));
  1848. if (IconInGeneratedSite != null)
  1849. if (xbuildedIcones.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", lIcon, "topic")) == null)
  1850. xbuildedIcones.AppendChild(buildedSites.ImportNode(IconInGeneratedSite, true));
  1851. XmlNode ThumbIconInGeneratedSite = GeneratedSites.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", lIcon, "thumbnail"));
  1852. if (ThumbIconInGeneratedSite != null)
  1853. if (xbuildedIcones.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", lIcon, "thumbnail")) == null)
  1854. xbuildedIcones.AppendChild(buildedSites.ImportNode(ThumbIconInGeneratedSite, true));
  1855. ((XmlElement)VirtualGeneratedSubTopic).SetAttribute("icon", lIcon);
  1856. //curResTopic.Attributes["icon"].Value = lIcon;
  1857. }
  1858. }
  1859. // on inverse la logique le Web Est maitre sur le service !!!
  1860. foreach (XmlAttribute xXmlTopicAttribute in curConfigSubTopic.Attributes)
  1861. {
  1862. if (xXmlTopicAttribute.Name == "type")
  1863. {
  1864. try
  1865. {
  1866. string res = xXmlTopicAttribute.Value;
  1867. string iType = ((int)Enum.Parse(typeof(TopicImplementation.TopicType), res)).ToString();
  1868. ((XmlElement)VirtualGeneratedSubTopic).SetAttribute(xXmlTopicAttribute.Name, iType);
  1869. }
  1870. catch (Exception parsing)
  1871. {
  1872. Process.Trace(parsing, System.Diagnostics.EventLogEntryType.Warning);
  1873. ((XmlElement)VirtualGeneratedSubTopic).RemoveAttribute(xXmlTopicAttribute.Name);
  1874. }
  1875. }
  1876. }
  1877. if (((XmlElement)VirtualGeneratedSubTopic).HasAttribute("href"))
  1878. {
  1879. VirtualGeneratedSubTopic.Attributes["href"].Value = string.Format("{0}&product={1}", VirtualGeneratedSubTopic.Attributes["href"].Value, CurProductId);
  1880. }
  1881. if (((XmlElement)VirtualGeneratedSubTopic).HasAttribute("daily"))
  1882. {
  1883. Boolean value;
  1884. ((XmlElement)VirtualGeneratedSubTopic).SetAttribute("daily", (bool.TryParse(VirtualGeneratedSubTopic.GetAttributeValue("daily", "true"), out value)) ? "0" : "1");
  1885. }
  1886. if (curBuildedSubTopic.HasChildNodes)
  1887. {
  1888. VirtualGeneratedSubTopic.AppendChild(buildedSites.ImportNode(curBuildedSubTopic.FirstChild, true));
  1889. }
  1890. // on le rajoute au site
  1891. if (VirtualGeneratedSubTopic != null)
  1892. curResTopic.AppendChild(VirtualGeneratedSubTopic);
  1893. }
  1894. /*
  1895. else
  1896. {
  1897. XmlNode VirtualGeneratedSubTopic = null;
  1898. VirtualGeneratedSubTopic = buildedSites.CreateNode(XmlNodeType.Element, "DEBUG", "");
  1899. VirtualGeneratedSubTopic.InnerText = configId;
  1900. if (VirtualGeneratedSubTopic != null)
  1901. curResTopic.AppendChild(VirtualGeneratedSubTopic);
  1902. }
  1903. */
  1904. } // si on doit l'afficher...
  1905. }
  1906. }
  1907. if (((XmlElement)curResTopic).HasAttribute("href"))
  1908. {
  1909. curResTopic.Attributes["href"].Value = string.Format("{0}&product={1}", curResTopic.Attributes["href"].Value, CurProductId);
  1910. }
  1911. }
  1912. else
  1913. {
  1914. // le topic n'a pas été généré par le service de production...
  1915. if (((XmlElement)curConfigTopic).HasAttribute("type"))
  1916. {
  1917. string topicType = curConfigTopic.Attributes["type"].Value;
  1918. if (topicType == "heart" || topicType == "rated" || topicType == "mostviewed" || topicType == "favorite")
  1919. {
  1920. XmlNode AddedNewTopic = buildedSites.ImportNode(curConfigTopic, false);
  1921. string iType = ((int)Enum.Parse(typeof(TopicImplementation.TopicType), curConfigTopic.GetAttributeValue("type", TopicImplementation.TopicType.standard.ToString()))).ToString();
  1922. ((XmlElement)AddedNewTopic).SetAttribute("type", iType);
  1923. if (((XmlElement)AddedNewTopic).HasAttribute("daily"))
  1924. {
  1925. Boolean value;
  1926. ((XmlElement)AddedNewTopic).SetAttribute("daily", (bool.TryParse(AddedNewTopic.GetAttributeValue("daily", "true"), out value)) ? "0" : "1");
  1927. // changement de sens pour aller avec les applications déposées
  1928. }
  1929. // Gestion de l'uno a faire... ou a revoir...
  1930. ((XmlElement)AddedNewTopic).SetAttribute("uno", sId);
  1931. if (((XmlElement)AddedNewTopic).HasAttribute("overrideuno"))
  1932. {
  1933. // changement de sens pour aller avec les applications déposées
  1934. ((XmlElement)AddedNewTopic).SetAttribute("newuno", sId);
  1935. ((XmlElement)AddedNewTopic).SetAttribute("uno", AddedNewTopic.Attributes["overrideuno"].Value);
  1936. }
  1937. ((XmlElement)AddedNewTopic).SetAttribute("href", string.Format("Topic.ashx?plugin=JI&uno={0}&product={1}&vd={2}", sId, CurProductId, VdG));
  1938. // CC 29/09/2010 on met l'icone...
  1939. if (string.IsNullOrEmpty(AddedNewTopic.GetAttributeValue("icon", "")) == false)
  1940. {
  1941. String ConfigIconName = AddedNewTopic.GetAttributeValue("icon", "");
  1942. ((XmlElement)AddedNewTopic).SetAttribute("icon", System.IO.Path.GetFileNameWithoutExtension(AddedNewTopic.GetAttributeValue("icon", "").Replace(@"\", "/")));
  1943. try
  1944. {
  1945. XmlNode xNewIcon;
  1946. xNewIcon = CreateNewIcon(xbuildedIcones.OwnerDocument, ConfigIconName, curConfigTopic, "topic");
  1947. //xNewIcon = xbuildedIcones.OwnerDocument.CreateNode(
  1948. xbuildedIcones.AppendChild(xNewIcon);
  1949. }
  1950. catch (Exception debe)
  1951. {
  1952. #if DEBUG && DEBUGDEBE
  1953. try
  1954. {
  1955. Process.Trace(debe, System.Diagnostics.EventLogEntryType.Error);
  1956. System.Diagnostics.EventLog.WriteEntry("AFP Iphone", debe.StackTrace, System.Diagnostics.EventLogEntryType.Error);
  1957. }
  1958. catch
  1959. { }
  1960. #endif
  1961. }
  1962. }
  1963. curResTopics.AppendChild(AddedNewTopic);
  1964. }
  1965. }
  1966. else
  1967. { // pas typé... pas généré ca peut être un virtuel pour subTopic
  1968. if (curConfigTopic.SelectNodes(".//subtopic").Count > 0)
  1969. {
  1970. XmlNode curResTopic;
  1971. curResTopic = curResTopics.AppendChild(buildedSites.ImportNode(curConfigTopic, false));
  1972. ((XmlElement)curResTopic).SetAttribute("uno", sId);
  1973. //rajout des icones
  1974. string ConfigIconName = curConfigTopic.GetAttributeValue("icon", "");
  1975. // on genere nous meme une icone ( surcharge) !!
  1976. if (string.IsNullOrEmpty(ConfigIconName) == false)
  1977. {
  1978. XmlNode xNewIcon;
  1979. xNewIcon = CreateNewIcon(xbuildedIcones.OwnerDocument, ConfigIconName, curResTopic, "topic");
  1980. //xNewIcon = xbuildedIcones.OwnerDocument.CreateNode(
  1981. xbuildedIcones.AppendChild(xNewIcon);
  1982. // penser a castrer le path...
  1983. curResTopic.Attributes["icon"].Value = System.IO.Path.GetFileNameWithoutExtension(ConfigIconName.Replace(@"\", "/"));
  1984. }
  1985. foreach (XmlNode curConfigSubTopic in curConfigTopic.SelectNodes("subtopic"))
  1986. {
  1987. string subId = curConfigSubTopic.Attributes["id"].Value;
  1988. XmlNode VirtualGeneratedSubTopic;
  1989. subId = string.Format("{0}__{1}", vd, subId);
  1990. XmlNode SubFromGenerated = GeneratedSites.SelectSingleNode(string.Format("//topic[@id='{0}']", subId));
  1991. if (SubFromGenerated != null)
  1992. {
  1993. VirtualGeneratedSubTopic = buildedSites.ImportNode(curConfigSubTopic, true);
  1994. //recopie des attributs...
  1995. //GeneratedSites.SelectSingleNode(string.Format("//topic[@id='{0}']", subId));
  1996. foreach (XmlAttribute xXmlTopicAttribute in SubFromGenerated.Attributes)
  1997. {
  1998. if (xXmlTopicAttribute.Name != "icon" && xXmlTopicAttribute.Name != "type")
  1999. ((XmlElement)VirtualGeneratedSubTopic).SetAttribute(xXmlTopicAttribute.Name, xXmlTopicAttribute.Value);
  2000. if (xXmlTopicAttribute.Name == "type")
  2001. {
  2002. try
  2003. {
  2004. string iType = ((int)Enum.Parse(typeof(TopicImplementation.TopicType), curConfigTopic.GetAttributeValue("type", TopicImplementation.TopicType.standard.ToString()))).ToString();
  2005. ((XmlElement)VirtualGeneratedSubTopic).SetAttribute(xXmlTopicAttribute.Name, iType);
  2006. }
  2007. catch (Exception parsing)
  2008. {
  2009. Process.Trace(parsing, System.Diagnostics.EventLogEntryType.Warning);
  2010. ((XmlElement)VirtualGeneratedSubTopic).RemoveAttribute(xXmlTopicAttribute.Name);
  2011. }
  2012. }
  2013. }
  2014. if (((XmlElement)VirtualGeneratedSubTopic).HasAttribute("href"))
  2015. {
  2016. VirtualGeneratedSubTopic.Attributes["href"].Value = string.Format("{0}&product={1}", VirtualGeneratedSubTopic.Attributes["href"].Value, CurProductId);
  2017. }
  2018. if (((XmlElement)VirtualGeneratedSubTopic).HasAttribute("daily"))
  2019. {
  2020. Boolean value;
  2021. ((XmlElement)VirtualGeneratedSubTopic).SetAttribute("daily", (bool.TryParse(VirtualGeneratedSubTopic.GetAttributeValue("daily", "true"), out value)) ? "0" : "1");
  2022. }
  2023. if (SubFromGenerated.HasChildNodes)
  2024. {
  2025. VirtualGeneratedSubTopic.AppendChild(buildedSites.ImportNode(SubFromGenerated.FirstChild, true));
  2026. }
  2027. if (VirtualGeneratedSubTopic != null)
  2028. curResTopic.AppendChild(VirtualGeneratedSubTopic);
  2029. }
  2030. }
  2031. }
  2032. }
  2033. }
  2034. }
  2035. } //id service present
  2036. else
  2037. {
  2038. string messageError;
  2039. try
  2040. {
  2041. messageError = string.Format(" Service node is mandatory. Not found for topic {0} ", curConfigTopic.Attributes["id"].Value);
  2042. Process.Trace(messageError, System.Diagnostics.EventLogEntryType.Error);
  2043. }
  2044. catch (Exception e)
  2045. {
  2046. Process.Trace(string.Format("Bad Config. {0}", e.Message), System.Diagnostics.EventLogEntryType.Error);
  2047. }
  2048. }
  2049. }
  2050. // il faut rajouter les advisories
  2051. foreach (XmlNode curConfigTopic in curConfigTopics.SelectNodes("advisories"))
  2052. {
  2053. curResTopics = curResSites.AppendChild(buildedSites.ImportNode(curConfigTopics, true));
  2054. }
  2055. // }
  2056. // a rajouter celle qui viennent de topics( flag) + site (logo);
  2057. string ConfigTopicsIconName = curConfigTopics.GetAttributeValue("icon", "");
  2058. if (string.IsNullOrEmpty(ConfigTopicsIconName) == false)
  2059. {
  2060. XmlNode xIconsTopics = CreateNewIcon(xbuildedIcones.OwnerDocument, ConfigTopicsIconName, curConfigTopics, "flag");
  2061. xbuildedIcones.AppendChild(xIconsTopics);
  2062. }
  2063. else
  2064. {
  2065. // on ne devrait jamais être ici sauf a avoir mis un name sur topics...
  2066. if (((XmlElement)curConfigTopics).HasAttribute("service") && ((XmlElement)curConfigTopics).HasAttribute("name"))
  2067. {
  2068. string topicsName = curConfigTopics.Attributes["name"].Value;
  2069. GeneratedSites = ((PathAndWCF)_services[(string)_idVD[curConfigTopics.Attributes["service"].Value]]).GeneratedSites;
  2070. XmlNode xLogoIcon;
  2071. String LogoName;
  2072. XmlNode xGenereratedtopics = GeneratedSites.SelectSingleNode(string.Format("//topics[@name='{0}'", topicsName));
  2073. LogoName = xGenereratedtopics.GetAttributeValue("icon", "");
  2074. LogoName = System.IO.Path.GetFileNameWithoutExtension(LogoName.Replace(@"\", "/"));
  2075. if (string.IsNullOrEmpty(LogoName) == false)
  2076. {
  2077. xLogoIcon = GeneratedSites.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", LogoName, "logo"));
  2078. if (xLogoIcon != null)
  2079. if (xbuildedIcones.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", LogoName, "topic")) == null)
  2080. xbuildedIcones.AppendChild(buildedSites.ImportNode(xLogoIcon, true));
  2081. }
  2082. }
  2083. //else
  2084. // ni l'un ni l'autre on n'a pas d'icones
  2085. }
  2086. } // curConfigTopics
  2087. // ajout de l'icone propre au site
  2088. string ConfigWebIconName = curWebSite.GetAttributeValue("icon", "");
  2089. string serviceName = curWebSite.GetAttributeValue("service", "");
  2090. XmlNode xFlagIcon;
  2091. if (string.IsNullOrEmpty(ConfigWebIconName) == false)
  2092. {
  2093. XmlNode xIconSite = CreateNewIcon(xbuildedIcones.OwnerDocument, ConfigWebIconName, curWebSite, "logo");
  2094. xbuildedIcones.AppendChild(xIconSite);
  2095. }
  2096. else
  2097. {
  2098. // pas d'icones
  2099. if (string.IsNullOrEmpty(serviceName) == false)
  2100. {
  2101. XmlDocument GeneratedSite = ((PathAndWCF)_services[(string)_idVD[serviceName]]).GeneratedSites;
  2102. xFlagIcon = GeneratedSite.SelectSingleNode(string.Format("//sites/icones/icons[@class='{0}']", "logo"));
  2103. if (xFlagIcon != null)
  2104. {
  2105. if (xbuildedIcones.SelectSingleNode(string.Format("//sites/icones/icons[@class='{0}']", "logo")) == null)
  2106. xbuildedIcones.AppendChild(buildedSites.ImportNode(xFlagIcon, true));
  2107. }
  2108. // mais on a un service on va aller chercher l'icon de celui ci.
  2109. }
  2110. }
  2111. }//curWebSite
  2112. return buildedSites;
  2113. }
  2114. /// <summary>
  2115. /// Cree un noeud contenant l'icone en base 64 en petit et en grand...
  2116. /// </summary>
  2117. /// <param name="xmlDocument"></param>
  2118. /// <param name="ConfigIconName"></param>
  2119. /// <param name="xNode"></param>
  2120. /// <param name="iconClass"></param>
  2121. /// <returns></returns>
  2122. private static XmlNode CreateNewIcon(XmlDocument xmlDocument, string ConfigIconName, XmlNode xNode, string iconClass)
  2123. {
  2124. string smallIconPath = GetLocalOrParentAttribute((XmlElement)xNode, "smallIconsPath", "sites");
  2125. string bigIconPath = GetLocalOrParentAttribute((XmlElement)xNode, "bigIconsPath", "sites");
  2126. XmlNode xNewIcon;
  2127. xNewIcon = xmlDocument.CreateNode(XmlNodeType.Element, "icons", "");
  2128. ((XmlElement)xNewIcon).SetAttribute("name", System.IO.Path.GetFileNameWithoutExtension(ConfigIconName.Replace(@"\", "/")));
  2129. ((XmlElement)xNewIcon).SetAttribute("class", iconClass);
  2130. if (string.IsNullOrEmpty(smallIconPath) == false)
  2131. {
  2132. XmlNode xSmallIcon;
  2133. xSmallIcon = xmlDocument.CreateNode(XmlNodeType.Element, "icon", "");
  2134. ((XmlElement)xSmallIcon).SetAttribute("smallSize", "1");
  2135. string pathFile;
  2136. pathFile = System.IO.Path.Combine(smallIconPath, ConfigIconName);
  2137. if (System.IO.File.Exists(pathFile))
  2138. {
  2139. Stream document = new FileStream(pathFile, FileMode.Open, FileAccess.Read, FileShare.Read);
  2140. xSmallIcon.InnerText = FileToBase64(document);
  2141. }
  2142. xNewIcon.AppendChild(xSmallIcon);
  2143. }
  2144. if (string.IsNullOrEmpty(smallIconPath) == false)
  2145. {
  2146. XmlNode xBigIcon;
  2147. xBigIcon = xmlDocument.CreateNode(XmlNodeType.Element, "icon", "");
  2148. ((XmlElement)xBigIcon).SetAttribute("smallSize", "0");
  2149. string pathFile;
  2150. pathFile = System.IO.Path.Combine(bigIconPath, ConfigIconName);
  2151. if (System.IO.File.Exists(pathFile))
  2152. {
  2153. Stream document = new FileStream(pathFile, FileMode.Open, FileAccess.Read, FileShare.Read);
  2154. xBigIcon.InnerText = FileToBase64(document);
  2155. }
  2156. xNewIcon.AppendChild(xBigIcon);
  2157. }
  2158. return xNewIcon;
  2159. //throw new NotImplementedException();
  2160. }
  2161. // pourquoi se gonfler...
  2162. private static string GetPath(string storePath, string format, string key, string id)
  2163. {
  2164. try
  2165. {
  2166. return Path.Combine(Path.Combine(Path.Combine(Path.Combine(storePath, format), key), GetHashFolder(id)), id);
  2167. }
  2168. catch
  2169. {
  2170. return "";
  2171. }
  2172. }
  2173. public static string GetHashFolder(string id)
  2174. {
  2175. return (Math.Abs(Path.GetFileNameWithoutExtension(id).MyGetHashCode()) % 256).ToString("X2");
  2176. }
  2177. public static string GetLocalOrParentAttribute(XmlElement node, string attributename, string stopCondition)
  2178. {
  2179. XmlElement curNode = node;
  2180. while (curNode is XmlElement && !(curNode.ParentNode is XmlDocument) && curNode.HasAttribute(attributename) == false)
  2181. {
  2182. curNode = (XmlElement)curNode.ParentNode;
  2183. if (!((XmlNode)curNode is XmlDocument) && curNode.Name == stopCondition)
  2184. {
  2185. if (curNode.HasAttribute(attributename))
  2186. return curNode.Attributes[attributename].Value;
  2187. else
  2188. return null;
  2189. }
  2190. }
  2191. if (!((XmlNode)curNode is XmlDocument))
  2192. {
  2193. if (curNode.HasAttribute(attributename))
  2194. return curNode.Attributes[attributename].Value;
  2195. else
  2196. return null;
  2197. }
  2198. return null;
  2199. }
  2200. /// <summary>
  2201. ///
  2202. /// </summary>
  2203. /// <param name="file"></param>
  2204. /// <returns></returns>
  2205. public static string FileToBase64(Stream file)
  2206. {
  2207. byte[] buffer = new byte[file.Length];
  2208. file.Read(buffer, 0, buffer.Length);
  2209. return Convert.ToBase64String(buffer);
  2210. }
  2211. public static string GetDeviceName(HttpContext context)
  2212. {
  2213. string res;
  2214. res = context.Request.UserAgent;
  2215. try
  2216. {
  2217. res = (res.Split("-".ToCharArray()))[1];
  2218. }
  2219. catch
  2220. {
  2221. res = res.Substring(0, 63);
  2222. }
  2223. return res;
  2224. }
  2225. /// <summary>
  2226. ///
  2227. /// </summary>
  2228. /// <param name="context"></param>
  2229. /// <returns></returns>
  2230. public static string GetProductName(HttpContext context, Boolean config)
  2231. {
  2232. string res;
  2233. try
  2234. {
  2235. res = context.Request.QueryString["product"];
  2236. if (string.IsNullOrEmpty(res))
  2237. {
  2238. XmlElement xSites;
  2239. if (config)
  2240. xSites = (XmlElement)Process.Configuration.SelectSingleNode("//sites");
  2241. else
  2242. xSites = (XmlElement)_BuildedSiteConfiguration.SelectSingleNode("//sites");
  2243. string TopicId;
  2244. TopicId = context.Request.QueryString["id"];
  2245. if (string.IsNullOrEmpty(TopicId))
  2246. TopicId = context.Request.QueryString["uno"];
  2247. if (TopicId.IndexOf("__") > -1)
  2248. TopicId = TopicId.Substring(TopicId.IndexOf("__") + 2);
  2249. XmlElement xTopic = (XmlElement)xSites.SelectSingleNode(string.Format("//topic[@id='{0}']", TopicId));
  2250. if (xTopic != null)
  2251. {
  2252. // détermination cascadée inverse...
  2253. res = GetLocalOrParentAttribute(xTopic, "productVote", "sites");
  2254. }
  2255. else
  2256. if (xSites.HasAttribute("productVote"))
  2257. {
  2258. res = xSites.Attributes["productVote"].Value;
  2259. }
  2260. else
  2261. {
  2262. res = xSites.SelectSingleNode("site").Attributes["id"].Value;
  2263. }
  2264. }
  2265. }
  2266. catch
  2267. {
  2268. res = "NO_PRODUCT";
  2269. #if DEBUG
  2270. if (string.IsNullOrEmpty(res))
  2271. res = "AFP";
  2272. #if DEBUGRATING || DEBUGVIEWED
  2273. System.Diagnostics.Debugger.Break();
  2274. #endif
  2275. #endif
  2276. }
  2277. return res;
  2278. }
  2279. /// <summary>
  2280. ///
  2281. /// </summary>
  2282. /// <param name="context"></param>
  2283. /// <returns></returns>
  2284. public static string GetEndPointName(HttpContext context)
  2285. {
  2286. String res;
  2287. string virtualDir;
  2288. try
  2289. {
  2290. virtualDir = context.Request.QueryString["vd"];
  2291. if (string.IsNullOrEmpty(virtualDir))
  2292. {
  2293. string uno;
  2294. uno = context.Request.QueryString["uno"];
  2295. if (string.IsNullOrEmpty(uno) == false && uno.IndexOf("__") != -1)
  2296. {
  2297. virtualDir = uno.Substring(0, uno.IndexOf("__"));
  2298. }
  2299. else
  2300. {
  2301. string id;
  2302. id = context.Request.QueryString["id"];
  2303. if (string.IsNullOrEmpty(id) == false && id.IndexOf("__") != -1)
  2304. {
  2305. virtualDir = id.Substring(0, id.IndexOf("__"));
  2306. }
  2307. else
  2308. {
  2309. // on va prendre le premier ou le defaut;
  2310. XmlElement xServices = (XmlElement)Process.Configuration.SelectSingleNode("//config/services");
  2311. XmlElement xService;
  2312. if (xServices.HasAttribute("defaultService"))
  2313. {
  2314. xService = (XmlElement)xServices.SelectSingleNode(string.Format("service[@id='{0}']", xServices.Attributes["defaultService"].Value));
  2315. }
  2316. else
  2317. {
  2318. // on fait au mieux on prend le premier
  2319. xService = (XmlElement)xServices.ChildNodes[0];
  2320. }
  2321. virtualDir = xService.Attributes["virtualDir"].Value;
  2322. }
  2323. }
  2324. }
  2325. res = ((PathAndWCF)_services[virtualDir]).EndPointName;
  2326. #if DEBUG
  2327. Process.Trace(string.Format("Le EndpointName choisi est : {0}", res), System.Diagnostics.EventLogEntryType.Information);
  2328. #endif
  2329. }
  2330. catch
  2331. {
  2332. res = "";
  2333. }
  2334. #if DEBUG
  2335. if (string.IsNullOrEmpty(res))
  2336. {
  2337. res = "TCPAFP";
  2338. #if DEBUGRATING || DEBUGVIEWED
  2339. System.Diagnostics.Debugger.Break();
  2340. #endif
  2341. }
  2342. #endif
  2343. return res;
  2344. }
  2345. private static void UpdateRating(HttpContext context, XmlNode Article)
  2346. {
  2347. int nbVote;
  2348. double rate;
  2349. string productId = GetProductName(context, true);
  2350. string ItemId;
  2351. //XmlElement bag;
  2352. try
  2353. {
  2354. ItemId = Article.Attributes["uno"].Value;
  2355. string topicId = Article.Attributes["parentId"].Value;
  2356. using (var processorClient = new ProcessorClient(GetEndPointName(context)))
  2357. {
  2358. processorClient.getRated(productId, topicId, ItemId, "", "", out rate, out nbVote);
  2359. ((XmlElement)Article).SetAttribute("globalRate", Convert.ToString(rate));
  2360. ((XmlElement)Article).SetAttribute("numberOfVote", Convert.ToString(nbVote));
  2361. // to do faire les bags
  2362. foreach (XmlNode bag in Article.SelectNodes("Bag"))
  2363. {
  2364. if (((XmlElement)bag).HasAttribute("uno"))
  2365. {
  2366. string mediaid = bag.Attributes["uno"].Value;
  2367. processorClient.getRated(productId, "", "", mediaid, "", out rate, out nbVote);
  2368. ((XmlElement)bag).SetAttribute("globalRate", Convert.ToString(rate));
  2369. ((XmlElement)bag).SetAttribute("numberOfVote", Convert.ToString(nbVote));
  2370. }
  2371. }
  2372. }
  2373. }
  2374. catch
  2375. { }
  2376. }
  2377. }
  2378. }