/Server/IServV2/IPhone/Sites/IPWS/PageHandler.cs
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
Large files files are truncated, but you can click here to view the full file
- using System.Collections.Generic;
- using System.Web.Caching;
- using AFP.IPhone.Application;
- using AFP.IPhone.Extensions;
- using AFP.IPhone.Processor;
- using AFP.IPhone.Storage;
-
- using System;
- using System.IO;
- using System.IO.Compression;
- using System.Linq;
- using System.Threading;
- using System.Web;
- using System.Xml;
- using System.Security.Cryptography;
- using System.Text;
-
-
- namespace AFP.IPhone.Web
- {
- public class PageHandler : IHttpHandler
- {
- private class CachedDocument
- {
- private string GetChecksum(byte[] document)
- {
- MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();
- Byte[] ba = MD5.ComputeHash(document);
-
- StringBuilder hex = new StringBuilder(ba.Length * 2);
- foreach (byte b in ba)
- hex.AppendFormat("{0:x2}", b);
- return hex.ToString();
- }
-
-
-
- public CachedDocument(byte[] document, DateTime lastModified)
- {
- Document = document;
- LastModified = lastModified;
- Checksum = GetChecksum(document);
- }
-
- public string Checksum { get; private set; }
-
- public byte[] Document { get; private set; }
-
- public DateTime LastModified { get; private set; }
- }
-
- private static readonly object _lockRootCache = new object();
- private static readonly object _lockTopicCache = new object();
- private struct PathAndWCF
- {
- public string RootPath;
- public string EndPointName;
- public XmlDocument GeneratedSites;
- }
-
- private static System.Collections.Hashtable _services; // virtualdir ---> PathAndWCF config;
- private static System.Collections.Hashtable _idVD; // id service ---> virtualdir;
- private static System.Collections.Hashtable _VdByTopicId; // topicid ---> EndPointName;
- private static XmlDocument _BuildedSiteConfiguration;
-
- private static TimeSpan? _ExpireCacheVote = null;
- private static TimeSpan? _BuildWithXDay = null;
-
- public bool IsReusable
- {
- get { return false; }
- }
-
- private static FileInfo GetMediaInfo(string virtualdir, string format, string plugin, string mediaId)
- {
-
- return new System.IO.FileInfo(GetPath((string)(((PathAndWCF)_services[virtualdir]).RootPath), format, plugin, mediaId));
- //return new StorageServer().Info(format, plugin, mediaId);
- }
-
- private static void GetMedia(Stream output, string virtualdir, string format, string plugin, string mediaId)
- {
- var buffer = new byte[16384];
- int read;
-
-
- /* using (Stream document = new StorageServer().Restore(format, plugin, mediaId))
- {}
- */
- Stream document = new FileStream(GetPath(((PathAndWCF)_services[virtualdir]).RootPath, format, plugin, mediaId), FileMode.Open, FileAccess.Read, FileShare.Read);
- do
- {
- if ((read = document.Read(buffer, 0, buffer.Length)) > 0)
- output.Write(buffer, 0, read);
- } while (read > 0);
- document.Close();
-
- }
-
- private static void RequestAbout(HttpContext context)
- {
- // Préparation Http
- WebApplication.PageSetHeaders();
- context.Response.Charset = "utf-8";
- context.Response.ContentType = "text/html";
-
- // Compression Gzip
- if (context.Request.ServerVariables.AllKeys.Contains("HTTP_ACCEPT_ENCODING") && Convert.ToString(context.Request.ServerVariables["HTTP_ACCEPT_ENCODING"]).IndexOf("gzip") > -1)
- {
- context.Response.AddHeader("Content-Encoding", "gzip");
- context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
- }
-
- try
- {
- if (string.IsNullOrEmpty(context.Request.QueryString["site"]))
- {
- 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)));
- }
- else
- {
- // plusieurs produits...
- 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"]);
-
- if (System.IO.File.Exists(fPath))
- {
- context.Response.TransmitFile(fPath);
- }
- else
- {
- 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)));
- }
-
- }
-
- }
- catch (Exception e)
- {
- try
- {
- context.Response.TransmitFile(string.Format(@"{0}about\about-en.html", context.Request.PhysicalApplicationPath));
- }
- catch
- {
- // Reporting
- Process.Trace(WebApplication.PageName, e.ToString(), System.Diagnostics.EventLogEntryType.Error);
- Process.Set(WebApplication.PageName, e.Message, System.Diagnostics.EventLogEntryType.Error);
-
- // Erreur de traitement
- context.Response.ContentType = "text/xml";
- context.Response.ClearContent();
- context.Response.Write(new ExceptionDocument(e, "About error"));
- }
- }
- }
-
- private static void RequestCheck(HttpContext context)
- {
- try
- {
- // Préparation Http
- WebApplication.PageSetHeaders();
- context.Response.ContentType = "text/html";
-
- if (context.Request.QueryString.Get("deep") == "1")
- try
- {
- using (var processorClient = new ProcessorClient(Process.Configuration.DocumentElement.GetAttribute("processorEndpointName")))
- {
- var processorServiceStatus = processorClient.Status();
-
- // Ecriture du tag ok
- switch (processorServiceStatus)
- {
- case System.Diagnostics.EventLogEntryType.Error:
- context.Response.Write("STATUS_ERROR");
- break;
-
- case System.Diagnostics.EventLogEntryType.Warning:
- context.Response.Write("STATUS_WARNING");
- break;
- default:
-
- context.Response.Write("STATUS_OK");
- break;
- }
- }
- }
- catch (Exception e)
- {
- // Reporting
- Process.Set(WebApplication.PageName, e.Message, System.Diagnostics.EventLogEntryType.Error);
-
- // Ecriture du tag error
- context.Response.Write("STATUS_ERROR");
- }
- else
- context.Response.Write("STATUS_OK");
- }
- catch (Exception e)
- {
- // Reporting
- Process.Set(WebApplication.PageName, e.Message, System.Diagnostics.EventLogEntryType.Error);
-
- // Ecriture de l'erreur sur la sortie
- context.Response.Write(e.ToString());
- }
- }
-
- private static void RequestDescription(HttpContext context)
- {
- // Préparation Http
- WebApplication.PageSetHeaders();
- context.Response.ContentType = "text/html";
-
- // Compression Gzip
- if (context.Request.ServerVariables.AllKeys.Contains("HTTP_ACCEPT_ENCODING") && Convert.ToString(context.Request.ServerVariables["HTTP_ACCEPT_ENCODING"]).IndexOf("gzip") > -1)
- {
- context.Response.AddHeader("Content-Encoding", "gzip");
- context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
- }
-
- try
- {
- 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)));
- }
- catch (Exception e)
- {
- try
- {
- context.Response.TransmitFile(string.Format(@"{0}description\{1}-en.html", context.Request.PhysicalApplicationPath, context.Request.QueryString["product"]));
- }
- catch (Exception e2)
- {
- // Reporting
- Process.Trace(WebApplication.PageName, string.Format("{0},{1}", e.ToString(), e2.ToString()), System.Diagnostics.EventLogEntryType.Error);
- Process.Set(WebApplication.PageName, string.Format("{0},{1}", e.Message, e2.Message), System.Diagnostics.EventLogEntryType.Error);
-
- // Erreur de traitement
- context.Response.ContentType = "text/xml";
- context.Response.ClearContent();
- context.Response.Write(new ExceptionDocument(e, "About error"));
- }
- }
- }
-
- private static void RequestDisclaimer(HttpContext context)
- {
- // Préparation Http
- WebApplication.PageSetHeaders();
- context.Response.Charset = "utf-8";
- context.Response.ContentType = "text/html";
-
- // Compression Gzip
- if (context.Request.ServerVariables.AllKeys.Contains("HTTP_ACCEPT_ENCODING") && Convert.ToString(context.Request.ServerVariables["HTTP_ACCEPT_ENCODING"]).IndexOf("gzip") > -1)
- {
- context.Response.AddHeader("Content-Encoding", "gzip");
- context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
- }
-
- try
- {
- 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)));
- }
- catch (Exception e)
- {
- try
- {
- context.Response.TransmitFile(string.Format(@"{0}disclaimers\{1}\disclaimer-en.html", context.Request.PhysicalApplicationPath, context.Request.QueryString["SC"]));
- }
- catch
- {
- // Reporting
- Process.Trace(WebApplication.PageName, e.ToString(), System.Diagnostics.EventLogEntryType.Error);
- Process.Set(WebApplication.PageName, e.Message, System.Diagnostics.EventLogEntryType.Error);
-
- // Erreur de traitement
- context.Response.ContentType = "text/xml";
- context.Response.ClearContent();
- context.Response.Write(new ExceptionDocument(e, "About error"));
- }
- }
- }
-
- private static void RequestProducts(HttpContext context, List<String> StringsCachedDepency, DateTime? CachedDate)
- {
- try
- {
- #if DEBUG && DEBUGPRODUCT
- System.Diagnostics.Debugger.Break();
- #endif
- String FilePathConfig = Process.FileConfigurationPath;
- FileInfo info = null;
- if (string.IsNullOrEmpty(FilePathConfig) == false)
- {
- info = new FileInfo(FilePathConfig);
- }
-
- if (string.IsNullOrEmpty(FilePathConfig) == false)
- {
- if (StringsCachedDepency == null)
- {
- StringsCachedDepency = new List<string>();
- }
- StringsCachedDepency.Add(FilePathConfig);
- }
-
- CachedDocument products;
-
- try
- {
- Monitor.Enter(_lockRootCache);
-
- products = (CachedDocument)context.Cache[Constants._storageProductsFileId];
-
- // Products présent dans le cache ?
- if (products == null)
- {
- // Récupération des informations
- var productsDocument = new XmlDocument();
-
- productsDocument.LoadXml("<sites/>");
-
- foreach (XmlNode site in _BuildedSiteConfiguration.SelectNodes("//site"))
- {
- if (site is XmlElement)
- productsDocument.DocumentElement.AppendChild(productsDocument.ImportNode(site, false));
- }
- // Suppression des sites non requis
- if (Process.Configuration.DocumentElement.HasAttribute("sitesIdList"))
- {
- var allowedIds = Process.Configuration.DocumentElement.GetAttribute("sitesIdList").Split(';');
- var removedSites = new List<XmlElement>();
-
- // Recherche des sites non requis
- foreach (XmlElement site in _BuildedSiteConfiguration.SelectNodes("//site"))
- if (site.HasAttribute("id") && !allowedIds.Contains(site.GetAttribute("id")))
- removedSites.Add(site);
-
- // Suppression des sites non requis
- foreach (var site in removedSites)
- productsDocument.DocumentElement.RemoveChild(site);
- }
-
-
-
- // Mise en mémoire du document sites
- using (var buffer = new MemoryStream())
- {
- productsDocument.Save(buffer);
- if (info != null)
- products = new CachedDocument(buffer.ToArray(), info.LastWriteTimeUtc);
- }
-
- // Mise en cache
- if (info != null)
- context.Cache.Insert(Constants._storageProductsFileId, products, new CacheDependency(info.FullName));
- }
- }
- catch (Exception e3)
- {
- string Message = e3.ToString();
- products = null;
- }
- finally
- {
- Monitor.Exit(_lockRootCache);
- }
-
- // Vérification du cache
- Boolean bCache = true;
-
- if (context.Request.Headers.AllKeys.Contains("Cache-Control"))
- if (context.Request.Headers["Cache-Control"].ToLower() == "no-cache")
- bCache = false;
- if (context.Request.Headers.AllKeys.Contains("Pragma"))
- {
- // doit-on faire une boucle?
- if (context.Request.Headers["Pragma"].ToLower() == "no-cache")
- bCache = false;
- }
-
- if (bCache)
- if (context.Request.Headers.AllKeys.Contains("If-Modified-Since"))
- if (products.LastModified.ToUniversalTime().Subtract(DateTime.Parse(context.Request.Headers["If-Modified-Since"])).TotalSeconds <= 1)
- {
- context.Response.AddHeader("cache-control", "public");
- context.Response.StatusCode = 304;
- return;
- }
-
- // Préparation Http
- WebApplication.PageSetHeaders
- (
- new Dictionary<string, string>
- {
- { "##LM##", products.LastModified.ToUniversalTime ().ToHTTPHeaderString () } ,
- { "##ET##", products.Checksum },
- { "##EXP##", DateTime.Now.ToUniversalTime().AddSeconds (WebApplication.GetExpires()).ToHTTPHeaderString()}
- }
- );
- context.Response.Buffer = true;
- context.Response.BufferOutput = true;
- context.Response.ContentType = "text/xml";
-
- // Ecriture du document Sites
- context.Response.BinaryWrite(products.Document);
-
- // Compression Gzip
- if (context.Request.ServerVariables.AllKeys.Contains("HTTP_ACCEPT_ENCODING") && Convert.ToString(context.Request.ServerVariables["HTTP_ACCEPT_ENCODING"]).IndexOf("gzip") > -1)
- {
- context.Response.AddHeader("Content-Encoding", "gzip");
- context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
- }
-
- // Reporting
- Process.Set(WebApplication.PageName, "Hits", System.Diagnostics.EventLogEntryType.Information);
- }
- catch (Exception e)
- {
- // Reporting
- Process.Trace(WebApplication.PageName, e.ToString(), System.Diagnostics.EventLogEntryType.Error);
- Process.Set(WebApplication.PageName, e.Message, System.Diagnostics.EventLogEntryType.Error);
-
- // Erreur de traitement
- context.Response.ContentType = "text/xml";
- context.Response.ClearContent();
- context.Response.Write(new ExceptionDocument(e, "Products error"));
- }
- }
-
- private static void RequestRating(HttpContext context)
- {
- #if DEBUG && DEBUGRATING
- System.Diagnostics.Debugger.Break();
- #endif
- // Préparation Http
- WebApplication.PageSetHeaders();
-
- context.Response.ContentType = "text/xml";
- // Récupération des informations
- string productId = GetProductName(context, true);
- string device = GetDeviceName(context);
- string endPointName = GetEndPointName(context);
- // Vote selon type
- try
- {
- using (var processorClient = new ProcessorClient(endPointName))
- {
- // Vote
- switch (context.Request.QueryString["type"])
- {
- case "0":
- 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));
- break;
-
- case "1":
- 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));
- break;
- default:
-
- throw new Exception("Invalid type value.");
- }
- }
- }
- catch (Exception e)
- {
- // Reporting
- Process.Trace(WebApplication.PageName, string.Format(" endpointName {0} error {1} ", endPointName, e.ToString()), System.Diagnostics.EventLogEntryType.Error);
- Process.Set(WebApplication.PageName, string.Format(" endpointName {0} error {1} ", endPointName, e.Message), System.Diagnostics.EventLogEntryType.Error);
-
- // Réponse
- context.Response.ClearContent();
- context.Response.Write(new ExceptionDocument(e, string.Format(" {1} on endpointName {0} ProductId {2}", endPointName, "Rating error", productId)));
- }
-
- }
-
- private static void RequestSites(HttpContext context, Boolean rebuildSites)
- {
- #if DEBUG && DEBUG_SITE
- System.Diagnostics.Debugger.Break();
- #endif
-
- Process.Start();
-
- // on a reconstruit le document... sans les favoris toutefois a faire plus tard
-
-
- try
- {
- CachedDocument sites;
- /*
- * Raccourci de debuggage en prod...
- */
- /*
- List<string> StringsCachedDepency1;
- DateTime CachedDate1;
-
- var sitesDocument1 = BuildSites(out StringsCachedDepency1, out CachedDate1);
- */
- try
- {
- Monitor.Enter(_lockRootCache);
- // Vérification du cache
- sites = (CachedDocument)context.Cache[Constants._storageSitesFileId];
- // Sites présent dans le cache ?
- if (sites == null || rebuildSites)
- {
- _services = null; // on force la reconstruction totale... evitera le bug du cache pour la partie Ipad...
-
- // Récupération des informations
- var sitesDocument = new XmlDocument();
-
- context.Cache.Remove(Constants._storageSitesFileId);
-
- List<string> StringsCachedDepency;
- DateTime CachedDate;
-
- sitesDocument = BuildSites(out StringsCachedDepency, out CachedDate);
-
- //StringsCachedDepency.Add(Process.FileConfigurationPath); // Si la config change il faut que l'on s'adapte. déjà fait dans buildSites...
- // si le document sites.xml change il faut aussi se mettre à jour
- //StringsCachedDepency.Add(Process.FileConfigurationPath); // Si la config change il faut que l'on s'adapte.
-
- _BuildedSiteConfiguration = sitesDocument;
-
- // Site par défaut
- if (Process.Configuration.DocumentElement.HasAttribute("defaultSite"))
- sitesDocument.DocumentElement.SetAttribute("defaultSite", Process.Configuration.DocumentElement.GetAttribute("defaultSite"));
-
- // Suppression des attributs inutiles
- foreach (XmlElement item in sitesDocument.SelectNodes("//topic[@id]|//subtopic[@id]"))
- item.RemoveAttribute("id");
- foreach (XmlElement item in sitesDocument.SelectNodes("//topic[@product]|//subtopic[@product]"))
- item.RemoveAttribute("product");
-
- foreach (XmlElement item in sitesDocument.SelectNodes("//topic[@showcatchline]|//subtopic[@showcatchline]"))
- item.RemoveAttribute("showcatchline");
-
- foreach (XmlElement item in sitesDocument.SelectNodes("//site[@smallIconsPath]"))
- item.RemoveAttribute("smallIconsPath");
- foreach (XmlElement item in sitesDocument.SelectNodes("//site[@bigIconsPath]"))
- item.RemoveAttribute("bigIconsPath");
- foreach (XmlElement item in sitesDocument.SelectNodes("//topic[@maxAge]"))
- item.RemoveAttribute("maxAge");
- foreach (XmlElement item in sitesDocument.SelectNodes("//topic[@overrideuno]"))
- item.RemoveAttribute("overrideuno");
- // foreach (XmlElement item in sitesDocument.SelectNodes("//topic[@newuno]"))
- // item.RemoveAttribute("newuno");
-
- foreach (XmlElement item in sitesDocument.SelectNodes("//subtopic[@maxAge]"))
- item.RemoveAttribute("maxAge");
- foreach (XmlElement item in sitesDocument.SelectNodes("//site[@defaultIcon]"))
- item.RemoveAttribute("defaultIcon");
-
- foreach (XmlElement item in sitesDocument.SelectNodes("//topic[@announce]"))
- item.RemoveAttribute("announce");
-
- foreach (XmlElement item in sitesDocument.SelectNodes("//topic[@Serve]|//subtopic[@Serve]"))
- item.RemoveAttribute("Serve");
-
- foreach (XmlElement item in sitesDocument.SelectNodes("//site[@maxNumberOfItems]"))
- item.RemoveAttribute("maxNumberOfItems");
- foreach (XmlElement item in sitesDocument.SelectNodes("//site[@productVote]"))
- item.RemoveAttribute("productVote");
-
- /* foreach (XmlElement item in sitesDocument.SelectNodes("//site"))
- item.RemoveAttribute("maxNumberOfItems");
- */
- foreach (XmlElement item in sitesDocument.SelectNodes("//topic|//subtopic|//topics"))
- {
- item.RemoveAttribute("path");
- item.RemoveAttribute("file");
- item.RemoveAttribute("htmlModel");
- item.RemoveAttribute("serviceCongigPath");
- item.RemoveAttribute("virtualDir");
- item.RemoveAttribute("siteId");
- item.RemoveAttribute("service");
- if (item.HasAttribute("shortName") == false)
- {
- item.SetAttribute("shortName", item.GetAttributeValue("fullName", ""));
- }
- }
- sitesDocument.DocumentElement.SetAttribute("updateDate", DateTime.UtcNow.ToXmlElementString());
-
- // Mise en mémoire du document sites
- using (var buffer = new MemoryStream())
- {
- sitesDocument.Save(buffer);
- sites = new CachedDocument(buffer.ToArray(), CachedDate);
- Process.Trace(string.Format("Cached document {0}", CachedDate), System.Diagnostics.EventLogEntryType.Information);
- }
-
- // Mise en cache
- context.Cache.Remove(Constants._storageSitesFileId);
- context.Cache.Insert(Constants._storageSitesFileId, sites, new CacheDependency(StringsCachedDepency.ToArray()));
-
-
- }
- }
- catch (Exception e3)
- {
- throw e3;
- }
- finally
- {
- Monitor.Exit(_lockRootCache);
- }
-
- // Vérification du cache
- Boolean bCache = true;
-
- if (context.Request.Headers.AllKeys.Contains("Cache-Control"))
- if (context.Request.Headers["Cache-Control"].ToLower() == "no-cache")
- bCache = false;
- if (context.Request.Headers.AllKeys.Contains("Pragma"))
- {
- // doit-on faire une boucle?
- if (context.Request.Headers["Pragma"].ToLower() == "no-cache")
- bCache = false;
- }
-
- if (bCache)
- if (context.Request.Headers.AllKeys.Contains("If-Modified-Since"))
- if (sites.LastModified.ToUniversalTime().Subtract(DateTime.Parse(context.Request.Headers["If-Modified-Since"])).TotalSeconds <= 1)
- {
- context.Response.AddHeader("cache-control", "public");
- context.Response.StatusCode = 304;
- return;
- }
-
- // Préparation Http
- WebApplication.PageSetHeaders(
- new Dictionary<string, string>
- {
- { "##LM##", sites.LastModified.ToUniversalTime ().ToHTTPHeaderString () } ,
- { "##ET##", sites.Checksum} ,
- { "##EXP##", DateTime.UtcNow.ToUniversalTime().AddSeconds (WebApplication.GetExpires()).ToHTTPHeaderString()}
- });
- context.Response.Buffer = true;
- context.Response.BufferOutput = true;
- context.Response.ContentType = "text/xml";
-
-
- // Ecriture du document Sites
- context.Response.BinaryWrite(sites.Document);
-
- // Compression Gzip
- if (context.Request.ServerVariables.AllKeys.Contains("HTTP_ACCEPT_ENCODING") && Convert.ToString(context.Request.ServerVariables["HTTP_ACCEPT_ENCODING"]).IndexOf("gzip") > -1)
- {
- context.Response.AddHeader("Content-Encoding", "gzip");
- context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
- }
-
- // Reporting
- Process.Set(WebApplication.PageName, "Hits", System.Diagnostics.EventLogEntryType.Information);
- }
- catch (Exception e)
- {
- // Reporting
- Process.Trace(WebApplication.PageName, e.ToString(), System.Diagnostics.EventLogEntryType.Error);
- Process.Set(WebApplication.PageName, e.Message, System.Diagnostics.EventLogEntryType.Error);
-
- // Erreur de traitement
- context.Response.ContentType = "text/xml";
- context.Response.ClearContent();
- context.Response.Write(new ExceptionDocument(e, "Sites error"));
- }
- }
-
- private static void RequestTopic(HttpContext context)
- {
-
- String FilePathConfig = Process.FileConfigurationPath;
- List<string> StringsCachedDepency = null;
- int startAt = 0;
- string mes = "";
- string dmes = " start";
- String uno = "";
-
- if (string.IsNullOrEmpty(FilePathConfig) == false)
- {
- if (StringsCachedDepency == null)
- {
- StringsCachedDepency = new List<string>();
- }
- StringsCachedDepency.Add(FilePathConfig);
- }
- try
- {
-
- CachedDocument topic = null;
- String VirtualDirectory;
- String ProductID;
- XmlElement SelectedSite;
- String sCacheReference = "";
- uno = context.Request.QueryString["uno"];
- XmlDocument sitesDocument = new XmlDocument();
- XmlDocument xapplicationConfiguration = Process.Configuration;
- string overtype = "";
-
- ProductID = context.Request.QueryString["product"];
- if (string.IsNullOrEmpty(ProductID))
- {
- //TODO il faut mettre le DefaultSiteName dans SiteName
- }
- VirtualDirectory = context.Request.QueryString["vd"];
- if (string.IsNullOrEmpty(VirtualDirectory))
- {
- VirtualDirectory = context.Request.QueryString["product"];
- }
- dmes += " 1 ";
- using (var buffer = new MemoryStream())
- {
- GetMedia(buffer, VirtualDirectory, Constants._storageSitesFormatName, Constants._storageSitesKey, Constants._storageSitesFileId);
- buffer.Position = 0;
- sitesDocument.Load(buffer);
- }
- // Récupération de l'id topic
- // ici il faudrait faire le calcul du maxEntries??
-
- dmes += " on cherche avec le uno " + uno;
- dmes += "\n" + string.Format("//*[@uno='{0}']", uno);
-
- XmlNode topicElement = sitesDocument.SelectSingleNode(string.Format("//*[@uno='{0}']", uno));
- TopicDeclaration topicDeclaration;
-
- if (topicElement == null)
- {
- //cas des votes !!!
- if (uno.IndexOf("__") > -1)
- uno = uno.Substring(uno.IndexOf("__") + 2);
- dmes += " on re cherche avec le uno " + uno;
- dmes += "Process configuration \n" + Process.Configuration.OuterXml;
- topicElement = Process.Configuration.SelectSingleNode(string.Format("//*[@uno='{0}']", uno));
- if (((XmlElement)topicElement).HasAttribute("type"))
- {
- overtype = topicElement.Attributes["type"].Value.ToLower();
-
- }
- dmes += "Process configuration \n" + Process.Configuration.OuterXml;
- }
- dmes += "\n topicElement " + topicElement.OuterXml;
- topicDeclaration = new TopicDeclaration((XmlElement)topicElement);
-
-
- // Récupération des informations sur le topic source
- string idTopic = "";
- if (((XmlElement)topicElement).HasAttribute("id"))
- idTopic = topicElement.Attributes["id"].Value;
- else
- idTopic = " __" + uno;
- string nameMedia = idTopic;
- dmes += " et on a trouvé";
-
- if (topicElement.Name == "subtopic")
- {
- if (((XmlElement)topicElement).HasAttribute("type"))
- {
- if ((topicElement.Attributes["type"].Value == "diaporama") || (topicElement.Attributes["type"].Value == "magazin") || (topicElement.Attributes["type"].Value == "7") || (topicElement.Attributes["type"].Value == "8"))
- {
- nameMedia = string.Format("{0}__{1}", VirtualDirectory, nameMedia);
- }
- }
- }
-
-
-
-
- SelectedSite = (XmlElement)_BuildedSiteConfiguration.SelectSingleNode(string.Format("//site[@id='{0}']", ProductID));
- if (SelectedSite == null)
- {
- throw new Exception(string.Format("Configuration Error no product with id {0}", ProductID));
- }
- /******************************************************************************************************************************************/
- /******************************************************************************************************************************************/
- /******************************************************************************************************************************************/
- /******************************************************************************************************************************************/
- /******************************************************************************************************************************************/
- /******************************************************************************************************************************************/
- XmlElement curNode;
- String LocalId = idTopic.Substring(idTopic.IndexOf("__") + 2);
- XmlElement ConfigSiteNode = null;
-
-
- ConfigSiteNode = (XmlElement)Process.Configuration.SelectSingleNode(string.Format(".//site[@id='{0}']", ProductID));
- curNode = (XmlElement)ConfigSiteNode.SelectSingleNode(string.Format(".//*[@id='{0}']", LocalId));
- // et evidement ce n'est pas bon...
- // dans le cadre d'un Free/payant...
- int maxEntries;
- try
- {
- while (curNode is XmlElement && !(curNode.ParentNode is XmlDocument) && curNode.HasAttribute("maxNumberOfItems") == false)
- {
- curNode = (XmlElement)curNode.ParentNode;
- }
- if (curNode.HasAttribute("maxNumberOfItems"))
- maxEntries = int.Parse(curNode.GetAttribute("maxNumberOfItems"));
- else
- maxEntries = 30;
- }
- catch (Exception e)
- {
- string a = e.Message;
- maxEntries = 30;
- #if DEBUG && toto
- 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);
- //Process.Set(WebApplication.PageName, string.Format(" Determination maxNumber {0}", e.ToString()), System.Diagnostics.EventLogEntryType.Error);
- #endif
-
- }
-
- //int maxEntries;
- //curNode = (XmlElement)sitesDocument.SelectSingleNode(string.Format(".//*[@uno='{0}']", uno));
- curNode = (XmlElement)ConfigSiteNode.SelectSingleNode(string.Format(".//*[@id='{0}']", LocalId));
- try
- {
- while (curNode is XmlElement && !(curNode.ParentNode is XmlDocument) && curNode.HasAttribute("startat") == false)
- {
- curNode = (XmlElement)curNode.ParentNode;
- }
- if (curNode.HasAttribute("startat"))
- startAt = int.Parse(curNode.GetAttribute("startat"));
- else
- startAt = 0;
- }
- catch (Exception e)
- {
- string a = e.Message;
- startAt = 0;
- }
-
- #if DEBUG_TOPIC
- System.Diagnostics.Debugger.Break();
- #endif
- try
- {
- Monitor.Enter(_lockTopicCache);
-
- // Vérification du cache
- sCacheReference = string.Format("{0}_{1}", uno, ProductID);
- topic = (CachedDocument)context.Cache[sCacheReference];
-
-
- // Topic présent dans le cache ?
- if (topic == null)
- {
-
- String topicType = GetType(uno);
- string lang = GetLang(uno);
- if (string.IsNullOrEmpty(overtype) == false)
- {
- topicType = overtype;
- }
- dmes += "\n" + overtype + "\n";
- var topicDocument = new XmlDocument();
-
- if (topicType == "heart" || topicType == "rated" || topicType == "mostviewed")
- {
- dmes += "\n on a bien un Rated\n";
- XmlDocument btopic = BuildRateTopic(context, topicType, 50, (TimeSpan)_BuildWithXDay, lang );
- dmes += "\n buildrated done \n";
-
- using (var buffer = new MemoryStream())
- {
- btopic.Save(buffer);
- topic = new CachedDocument(buffer.ToArray(), System.DateTime.UtcNow);
- }
- dmes += "\n " + btopic.OuterXml + "\n";
- #if DEBUG && DEBUGTRACERATING
- Process.Trace(WebApplication.PageName, string.Format(" Build Rated Topic {0}", dmes), System.Diagnostics.EventLogEntryType.Error);
- //Process.Set(WebApplication.PageName, string.Format(" Build Rated Topic {0}", dmes), System.Diagnostics.EventLogEntryType.Error);
- #endif
- if (_ExpireCacheVote != null)
- context.Cache.Insert(sCacheReference, topic, null, System.Web.Caching.Cache.NoAbsoluteExpiration, (TimeSpan)_ExpireCacheVote);
- else
- context.Cache.Insert(sCacheReference, topic, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromHours(2));
-
- }
- else
- {
-
- // Chargement du document sites
-
- dmes += " non Rated";
- var topicInfo = GetMediaInfo(VirtualDirectory, Constants._storageTopicFormatName, context.Request.QueryString["plugin"], string.Format("{0}.xml", nameMedia));
-
- // Chargement du document topic XAfp
- //TODO du ou des topics
- using (var buffer = new MemoryStream())
- {
- GetMedia(buffer, VirtualDirectory, Constants._storageTopicFormatName, context.Request.QueryString["plugin"], string.Format("{0}.xml", nameMedia));
- buffer.Position = 0;
- topicDocument.Load(buffer);
- }
-
- // Suppression des éléments en excédent et ajout du parentUno
-
-
- var bag = topicDocument.DocumentElement.SelectSingleNode("Bag");
- var rmv = 0;
- int currentI = 0;
-
- foreach (XmlNode item in bag.SelectNodes("Item"))
- {
- // présence de topicId ?
- //UpdateRating(context, item);
-
- if (((XmlElement)item).HasAttribute("topicId"))
- {
- if (topicDeclaration.Topics.SelectSingleNode(string.Format("*[@id='{0}']", ((XmlElement)item).GetAttribute("topicId"))) == null)
- {
- bag.RemoveChild(((XmlElement)item));
- rmv++;
- }
- else
- {
- ((XmlElement)item).RemoveAttribute("topicId");
-
- if (int.Parse(((XmlElement)item).GetAttributeValue("index", "0")) < maxEntries + rmv)
- {
- if (currentI < startAt)
- {
- bag.RemoveChild(((XmlElement)item));
- //currentI++;
- }
- else
- {
- ((XmlElement)item).RemoveAttribute("index");
- }
- currentI++;
- }
- else
- {
- bag.RemoveChild(((XmlElement)item));
- }
- }
- }
- else if (int.Parse(((XmlElement)item).GetAttributeValue("index", "0")) < maxEntries + rmv)
- {
- if (currentI < startAt)
- {
- bag.RemoveChild(((XmlElement)item));
- // rmv++;
- }
- else
- {
- ((XmlElement)item).RemoveAttribute("index");
- }
- currentI++;
- }
- else
- bag.RemoveChild(((XmlElement)item));
- }
- // Modification NumberOfItems
-
-
- var nbi = topicDocument.DocumentElement.SelectSingleNode("Head/NumberOfItems");
- if (nbi != null)
- nbi.InnerText = bag.SelectNodes("Item").Count.ToString();
-
- if (topicDocument.DocumentElement.SelectSingleNode("Xafp/CatchLine") != null)
- {
- topicDocument.DocumentElement.RemoveChild(topicDocument.DocumentElement.SelectSingleNode("Xafp/CatchLine"));
- }
-
- // Ajout namespace xml
- var topicDocumentNavigator = topicDocument.CreateNavigator();
- var topicDocumentManager = new XmlNamespaceManager(topicDocumentNavigator.NameTable);
-
- topicDocumentManager.AddNamespace("xml", "http://www.w3.org/XML/1998/namespace");
-
- // Attributs obligatoires
- if (topicDocument.DocumentElement.SelectSingleNode("@lang", topicDocumentManager) == null)
- topicDocument.DocumentElement.SetAttribute("xml:lang", topicDeclaration.Topics.GetAttribute("lang"));
-
- // Mise en mémoire
- using (var buffer = new MemoryStream())
- {
- topicDocument.Save(buffer);
- topic = new CachedDocument(buffer.ToArray(), topicInfo.LastWriteTimeUtc);
- #if DEBUG && TRACE_LASTMODIFIEDTOPIC
- StringBuilder text2;
- text2 = new StringBuilder();
- text2.AppendLine(string.Format("Topic Local ID {0} lastmodified {1} lastAccessTime {2} ", LocalId, topicInfo.LastWriteTimeUtc, topicInfo.LastAccessTimeUtc ));
-
- Process.Trace(text2.ToString(), "LastModified topic", System.Diagnostics.EventLogEntryType.Information);
- #endif
- }
-
- // Mise en cache
- // il faut aussi faire une dépendance selon le site...
- // doit on le cacher?
- StringsCachedDepency.Add(topicInfo.FullName);
- if (_ExpireCacheVote != null)
- context.Cache.Insert(sCacheReference, topic, new CacheDependency(StringsCachedDepency.ToArray()), System.Web.Caching.Cache.NoAbsoluteExpiration, (TimeSpan)_ExpireCacheVote);
- else
- context.Cache.Insert(sCacheReference, topic, new CacheDependency(StringsCachedDepency.ToArray()));
- }// topic == rated etc.
- }
- }
- catch (Exception e2)
- {
- mes = e2.Message;
- Process.Trace(e2, System.Diagnostics.EventLogEntryType.Error);
- #if DEBUG && DEBUGDEBE
- try
- {
- Process.Trace(e2, System.Diagnostics.EventLogEntryType.Error);
- System.Diagnostics.EventLog.WriteEntry("AFP Iphone", e2.StackTrace, System.Diagnostics.EventLogEntryType.Error);
- }
- catch
- { }
- #endif
- }
- finally
- {
- Monitor.Exit(_lockTopicCache);
- }
-
- // Vérification du cache
- Boolean bCache = true;
-
- if (context.Request.Headers.AllKeys.Contains("Cache-Control"))
- …
Large files files are truncated, but you can click here to view the full file