/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
- 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"))
- 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") && topic != null)
- if (topic.LastModified.ToUniversalTime().Subtract(DateTime.Parse(context.Request.Headers["If-Modified-Since"])).TotalSeconds <= 1)
- {
-
- context.Response.AddHeader("cache-control", "public");
- context.Response.StatusCode = 304;
- return;
- }
-
- #if DEBUG && TRACE_LASTMODIFIEDTOPIC
- StringBuilder text;
- text = new StringBuilder();
- text.AppendLine(string.Format ("Topic Local ID {0} lastmodified {1} " , LocalId , topic.LastModified.ToUniversalTime()) );
-
- Process.Trace(text.ToString(),"LastModified topic",System.Diagnostics.EventLogEntryType.Information );
- #endif
- // Préparation Http
- WebApplication.PageSetHeaders(new Dictionary<string, string>
- {
- { "##LM##", topic.LastModified.ToUniversalTime ().ToHTTPHeaderString () } ,
- { "##ET##", topic.Checksum } ,
- { "##EXP##", DateTime.UtcNow.ToUniversalTime ().AddSeconds (WebApplication.GetExpires()).ToHTTPHeaderString()}
- });
- context.Response.Buffer = true;
- context.Response.BufferOutput = true;
- context.Response.ContentType = "text/xml";
-
- // Ecriture du topic
- context.Response.BinaryWrite(topic.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, string.Format("error {0}. Requested uno {1}", e.ToString(), uno), System.Diagnostics.EventLogEntryType.FailureAudit);
- Process.Set(WebApplication.PageName, e.Message, System.Diagnostics.EventLogEntryType.FailureAudit);
-
- // Préparation Http
- context.Response.Buffer = true;
- context.Response.BufferOutput = true;
- context.Response.ContentType = "text/xml";
- context.Response.ClearContent();
-
- // XAfp par défaut
- var defaultXml = XmlWriter.Create(context.Response.OutputStream);
-
-
- defaultXml.WriteStartElement("Xafp");
- {
- // Xafp
- defaultXml.WriteAttributeString("type", "collection");
- defaultXml.WriteAttributeString("uno", context.Request.QueryString["uno"]);
-
- defaultXml.WriteStartElement("Head");
- {
- // Xafp/Head
- defaultXml.WriteElementString("Name", "-");
- defaultXml.WriteElementString("DateCreated", DateTime.UtcNow.ToXmlElementString());
- defaultXml.WriteElementString("DateUpdated", DateTime.UtcNow.ToXmlElementString());
- defaultXml.WriteElementString("NumberOfItems", "0");
- }
- defaultXml.WriteEndElement();
- // /Xafp/Head
- defaultXml.WriteElementString("Bag", string.Empty);
- }
- defaultXml.WriteEndElement();
- // /Xafp
- #if DEBUG
- defaultXml.WriteComment(string.Format("e : {0} \n Stack trace {3} e2 :{1} debug : {2}", e.Message, mes, dmes, e.StackTrace));
- #endif
- defaultXml.Flush();
- }
- }
-
- /// <summary>
- /// construit les topics des plus votés...
- /// </summary>
- /// <param name="context"></param>
- /// <param name="topic"></param>
- private static XmlDocument BuildRateTopic(HttpContext context, String topicType, int MaxEntries, TimeSpan TimeCacheVote ,string lang )
- {
- // on va chercher la liste sur les differents serveurs.. .
- XmlDocument xRes = null;
-
- string lEndPointName = "";
- ProcessorClient processorRated;
- String DocFromService = "";
- foreach (string Vd in _services.Keys)
- {
- try
- {
- XmlDocument xDocFromService = new XmlDocument();
- DocFromService = "";
- int type = 1;
- //lEndPointName = ((PathAndWCF)_services[Vd]).EndPointName ;
- lEndPointName = GetEndPointName(context);
- processorRated = new ProcessorClient(lEndPointName);
-
-
- #if DEBUG && DEBUG_VOTE
- Process.Trace(string.Format("on incorpore {0} : ", lEndPointName), System.Diagnostics.EventLogEntryType.Information);
- #endif
-
- // on a le lien vers le serveur
- switch (topicType)
- {
- case "heart":
- DocFromService = processorRated.GetHeartRatedList("", GetProductName(context, false), context.Request.QueryString["uno"], TimeCacheVote, MaxEntries,lang);
- type = 0;
- break;
- case "rated":
-
- DocFromService = processorRated.GetArticleRatedList("", GetProductName(context, false), context.Request.QueryString["uno"], TimeCacheVote, MaxEntries, lang);
- type = 1;
- break;
-
- case "mostviewed":
- DocFromService = processorRated.GetMostViewed("", GetProductName(context, false), context.Request.QueryString["uno"], TimeCacheVote, MaxEntries);
- type = 2;
- break;
- }
- #if DEBUG && DEBUGTRACERATING
- Process.Trace(string.Format(" DocFromService{0} <==> {1}", DocFromService, lEndPointName ), System.Diagnostics.EventLogEntryType.Information);
-
- #endif
- if (string.IsNullOrEmpty(DocFromService) == false)
- {
- #if DEBUG && DEBUG_VOTE
- Process.Trace(string.Format("on incorpore {0} : ", lEndPointName), System.Diagnostics.EventLogEntryType.Information);
- #endif
-
- if (xRes == null)
- {
- // on est sur le premier
- xRes = new XmlDocument();
- xRes.LoadXml(DocFromService);
- }
- else
- { // on incorpore
-
- xDocFromService.LoadXml(DocFromService);
- xRes = Mixte(xRes, xDocFromService, MaxEntries, type);
- }
- }
-
- processorRated.Dispose();
-
- }
- catch (Exception debe)
- {
- // on prend le topic généré?
- Process.Trace(debe, System.Diagnostics.EventLogEntryType.Error);
-
- #if DEBUG
- try
- {
- Process.Trace(debe, System.Diagnostics.EventLogEntryType.Error);
- System.Diagnostics.EventLog.WriteEntry("AFP Iphone", debe.StackTrace, System.Diagnostics.EventLogEntryType.Error);
- }
- catch
- { }
- xRes = new XmlDocument();
- 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);
- xRes.LoadXml(string.Format("{0}<!-- on va chercher sur : {3} topicType {4}--> <!-- DocFromService {5} --> <!--{1}-->{2}", "<ERROR>", debe.ToString(), "</ERROR>", lEndPointName, topicType, DocFromService));
- #endif
-
- }
- }
- return xRes;
- }
-
- // string.Format("{0}{1}", (((double)row["averageRating"] * 1000) / (1 + (Math.Truncate(DateTime.Now.Subtract(newsDate).TotalDays) * 10))).ToString("0000"), ((int)row["votes"]).ToString("0000000000"));
-
-
-
- /// <summary>
- /// Fusionne deux resultats de vote venant de deux services différents !!!
- /// </summary>
- /// <param name="BuildedRes"></param>
- /// <param name="xDocFromService"></param>
- /// <param name="MaxEntries"></param>
- /// <param name="topicType"></param>
- /// <returns></returns>
- private static XmlDocument Mixte(XmlDocument BuildedRes, XmlDocument xDocFromService, int MaxEntries, int topicType)
- {
- XmlDocument xRes = new XmlDocument();
- xRes.LoadXml("<Xafp><Bag/></Xafp>");
- XmlNode Xbag = xRes.SelectSingleNode("//Xafp/Bag");
- XmlNode SourceItem;
- XmlNode NewItem;
- int nbItem;
- Boolean Exit = false;
- XmlNode lastInserted = null;
-
- xRes.SelectSingleNode("//Xafp").InsertBefore(xRes.ImportNode(BuildedRes.SelectSingleNode("//Xafp/Head"), true), Xbag);
- nbItem = BuildedRes.DocumentElement.SelectSingleNode("//Xafp/Head/NumberOfItems").Value.toInt();
- SourceItem = BuildedRes.SelectSingleNode("//Xafp/Bag/Item");
- NewItem = xDocFromService.SelectSingleNode("//Xafp/Bag/Item");
- if (NewItem == null) Exit = true; // si pas de resultat on sort de suite...
- while (Exit == false)
- {
-
- if (nbItem <= MaxEntries)
- {
- if (SourceItem == null)
- {
- // recopie de tous les noeuds restant dans le source
- while (nbItem <= MaxEntries && Exit == false)
- {
- if (NewItem != null)
- {
- XmlNode ImportedNode;
- if (lastInserted == null)
- {
- ImportedNode = xRes.ImportNode(NewItem, true);
- if (ImportedNode == null)
- Exit = true;
- lastInserted = Xbag.AppendChild(ImportedNode);
- }
- else
- {
- ImportedNode = xRes.ImportNode(NewItem, true);
- if (ImportedNode == null)
- Exit = true;
- else
- {
- try
- {
- lastInserted = Xbag.InsertAfter(ImportedNode, lastInserted);
- }
- catch
- {
- Process.Trace(string.Format("ImporteNode {0}", ImportedNode.InnerXml), System.Diagnostics.EventLogEntryType.Information);
- Process.Trace(string.Format("lastInserted {0}", lastInserted.InnerXml), System.Diagnostics.EventLogEntryType.Information);
- Process.Trace(string.Format("Xbag {0}", Xbag.InnerXml), System.Diagnostics.EventLogEntryType.Information);
-
- }
- }
- }
- NewItem = NewItem.NextSibling;
- }
- if (NewItem == null) Exit = true;
- nbItem++;
- }
- Exit = true;
- }
- if (NewItem == null && SourceItem != null)
- {
- //recopie de tous les noeuds restant dans le New
- while (nbItem <= MaxEntries && Exit == false)
- {
- if (lastInserted == null)
- {
- lastInserted = Xbag.AppendChild(xRes.ImportNode(SourceItem, true));
- }
- else
- {
- lastInserted = Xbag.InsertAfter(xRes.ImportNode(SourceItem, true), lastInserted);
- }
- SourceItem = SourceItem.NextSibling;
- if (SourceItem == null) Exit = true;
- nbItem++;
- }
-
- Exit = true;
-
- }
- if (Exit != true)
- {
- nbItem += 1;
- double averageratingFromSource = getGlobalRate(SourceItem, topicType);
- double averageratingFromNew = getGlobalRate(NewItem, topicType);
- DateTime DtFromSource = getDate(SourceItem, topicType);
- DateTime DtFromNew = getDate(NewItem, topicType);
- int voteFromSource = getVote(SourceItem, topicType);
- int voteFromNew = getVote(NewItem, topicType);
-
- string ratefromsource = string.Format("{0}{1}", ((averageratingFromSource * 1000) / (1 + (Math.Truncate(DateTime.Now.Subtract(DtFromSource).TotalDays) * 10))).ToString("0000"), voteFromSource.ToString("0000000000"));
- string ratefromNEw = string.Format("{0}{1}", ((averageratingFromNew * 1000) / (1 + (Math.Truncate(DateTime.Now.Subtract(DtFromNew).TotalDays) * 10))).ToString("0000"), (voteFromNew).ToString("0000000000"));
-
- if (ratefromsource.CompareTo(ratefromNEw) > 0)
- {
- if (nbItem == 1)
- {
- lastInserted = Xbag.AppendChild(xRes.ImportNode(SourceItem, true));
- }
- else
- {
- lastInserted = Xbag.InsertAfter(xRes.ImportNode(SourceItem, true), lastInserted);
- }
- }
- else
- {
- if (nbItem == 1)
- {
- lastInserted = Xbag.AppendChild(xRes.ImportNode(NewItem, true));
- }
- else
- {
- lastInserted = Xbag.InsertAfter(xRes.ImportNode(SourceItem, true), lastInserted);
- }
-
- }
- SourceItem = SourceItem.NextSibling;
- NewItem = NewItem.NextSibling;
- //if( SourceItem.Attributes[""]
- }
- }
- else
- { Exit = true; }
- }
- xRes.DocumentElement.SelectSingleNode("//Xafp/Head/NumberOfItems").InnerText = nbItem.ToString();
- return xRes;
- }
-
- private static int getVote(XmlNode SourceItem, int topicType)
- {
- try
- {
- if (topicType != 0)
- {
- return SourceItem.Attributes["numberOfVote"].Value.toInt();
- }
- else
- {
- return SourceItem.SelectSingleNode("Bag").Attributes["numberOfVote"].Value.toInt();
- }
- }
- catch (Exception ex)
- {
- #if DEBUG
- Process.Trace(string.Format("{0} {1} ", ex.ToString(), SourceItem.InnerXml), System.Diagnostics.EventLogEntryType.Warning);
- #endif
- return 0;
-
- }
-
- }
-
- private static DateTime getDate(XmlNode SourceItem, int topicType)
- {
- String articledate;
- articledate = SourceItem.SelectSingleNode("//DatePublished").InnerText;
- return DateTime.ParseExact(articledate, "yyyyMMddTHHmmssZ", System.Globalization.CultureInfo.InvariantCulture);
-
- }
-
- private static double getGlobalRate(XmlNode SourceItem, int topicType)
- {
- try
- {
- if (topicType != 0)
- {
- return SourceItem.Attributes["globalRate"].Value.toInt();
- }
- else
- {
- return SourceItem.SelectSingleNode("Bag").Attributes["globalRate"].Value.toInt();
- }
- }
- catch (Exception ex)
- {
- #if DEBUG
- Process.Trace(string.Format("{0} {1} ", ex.ToString(), SourceItem.InnerXml), System.Diagnostics.EventLogEntryType.Warning);
- #endif
- return 0;
- }
- }
-
- private static string GetLang(string uno)
- {
- XmlElement xTopic = (XmlElement)_BuildedSiteConfiguration.SelectSingleNode(string.Format("//topic[@uno='{0}']", uno));
- string reslang ="";
- try
- {
- reslang = GetLocalOrParentAttribute(xTopic, "lang", "sites");
- }catch
- {}
-
- return reslang ;
- }
- /// <summary>
- /// int --> (string) TopicImplementation.TopicType
- /// </summary>
- /// <param name="uno"></param>
- /// <returns></returns>
- private static string GetType(string uno)
- {
- XmlElement xTopic = (XmlElement)_BuildedSiteConfiguration.SelectSingleNode(string.Format("//topic[@uno='{0}']", uno));
- if (xTopic != null && xTopic.HasAttribute("type"))
- {
- int type;
- if (int.TryParse(xTopic.Attributes["type"].Value, out type))
- {
-
- #if DEBUG && DEBUGDEBE
- try
- {
- System.Diagnostics.EventLog.WriteEntry("AFP Iphone",
- string.Format(" UNO {0} --> type {1} --> {2}", uno, type.ToString() , Enum.GetName(typeof(TopicImplementation.TopicType), type))
- ,System.Diagnostics.EventLogEntryType.Error);
- }
- catch
- { }
- #endif
- return Enum.GetName(typeof(TopicImplementation.TopicType), type);
- }
-
- }
-
- #if DEBUG && DEBUGDEBE
- try
- {
- System.Diagnostics.EventLog.WriteEntry("AFP Iphone",
- string.Format(" UNO {0} --> type {1} --> standard", uno, xTopic.Attributes["type"].Value )
- ,System.Diagnostics.EventLogEntryType.Error);
- }
- catch
- { }
- #endif
- return Enum.GetName(typeof(TopicImplementation.TopicType), 0); //standard
- }
-
-
- /// <summary>
- /// enregistre les pages lues en DB...
- /// </summary>
- /// <param name="context"></param>
- private static void RequestViewed(HttpContext context)
- {
- #if DEBUG && DEBUGVIEWED
- System.Diagnostics.Debugger.Break();
- #endif
- context.Response.Buffer = true;
- context.Response.BufferOutput = true;
- context.Response.ContentType = "text/xml";
-
- context.Response.ClearContent();
- var defaultXml = XmlWriter.Create(context.Response.OutputStream);
-
- defaultXml.WriteStartElement("Ok");
- defaultXml.WriteEndElement();
- defaultXml.Flush();
-
- try
- {
- // connexion au service de production...
- string productId = GetProductName(context, false);
-
-
- string device = GetDeviceName(context);
-
- using (var processorClient = new ProcessorClient(GetEndPointName(context)))
- {
- processorClient.InsertViewed(
- productId,
- context.Request.QueryString["uno"],
- context.Request.QueryString["item"],
- context.Request.QueryString["mediaId"],
- device)
- ;
- }
-
-
- }
- catch (Exception e)
- {
- Process.Trace(e, System.Diagnostics.EventLogEntryType.Error);
- }
-
- }
- private static void RequestNeutral(HttpContext context)
- {
- context.Response.Buffer = true;
- context.Response.BufferOutput = true;
- context.Response.ContentType = "text/xml";
-
-
- context.Response.ClearContent();
- var defaultXml = XmlWriter.Create(context.Response.OutputStream);
-
- defaultXml.WriteStartElement("Ok");
- defaultXml.WriteEndElement();
- defaultXml.Flush();
-
-
- }
-
-
- public void ProcessRequest(HttpContext context)
- {
- // Bufferisation
- #if DEBUG && TRACE_CONTEXT
-
- int loop1, loop2;
- System.Collections.Specialized.NameValueCollection coll;
-
- // Load Header collection into NameValueCollection object.
- coll = context.Request.Headers;
- StringBuilder text;
- text = new StringBuilder();
- //text.AppendLine(message.Message);
-
- // Put the names of all keys into a string array.
- String[] arr1 = coll.AllKeys;
- for (loop1 = 0; loop1 < arr1.Length; loop1++)
- {
- text.AppendLine("");
- text.AppendLine(string.Format("Key {0}",arr1[loop1]));
-
- // Get all values under this key.
- String[] arr2=coll.GetValues(arr1[loop1]);
- for (loop2 = 0; loop2 < arr2.Length; loop2++)
- {
- text.AppendLine(string.Format(" Value {0}", arr2[loop2]));
- }
-
- }
-
- Process.Trace(text.ToString(), "TraceRequest", System.Diagnostics.EventLogEntryType.Information);
-
- #endif
- context.Response.Buffer = true;
- context.Response.BufferOutput = true;
- List<String> StringsCachedDepency = null;
- DateTime CachedDate = System.DateTime.MinValue;
- Boolean reDoSites = false;
- String page = Path.GetFileNameWithoutExtension(context.Request.Url.Segments[context.Request.Url.Segments.Length - 1]).ToLower();
- if (_services == null && page != "sites")
- {
- try
- {
- Monitor.Enter(_lockRootCache);
- _BuildedSiteConfiguration = BuildSites(out StringsCachedDepency, out CachedDate);
- }
- finally
- {
- Monitor.Exit(_lockRootCache);
- }
- reDoSites = true;
- }
-
- if (string.IsNullOrEmpty(context.Request.QueryString["rebuild"]) == false)
- {
- reDoSites = true;
- }
- switch (page)
- {
- case "about":
- RequestAbout(context);
- break;
-
- case "check":
- RequestCheck(context);
- break;
-
- case "description":
- RequestDescription(context);
- break;
-
- case "disclaimer":
- RequestDisclaimer(context);
- break;
-
- case "products":
- RequestProducts(context, StringsCachedDepency, CachedDate);
- break;
-
- case "rating":
- RequestRating(context);
- break;
-
- case "sites":
- RequestSites(context, reDoSites);
- break;
-
- case "topic":
- RequestTopic(context);
- break;
-
- case "mostviewed":
- RequestMostViewed(context);
- break;
-
- /* case "view":
- RequestView(context);
- break;
- */
- case "viewed":
- RequestViewed(context);
- break;
- case "emailed":
- case "saved":
- RequestNeutral(context);
- break;
- case "location":
- RequestAround(context);
- break;
- default:
-
- context.Response.StatusCode = 404;
- break;
- }
-
- // Fin de traitement
- context.Response.End();
- }
-
- private void RequestAround(HttpContext context)
- {
- // on va chercher toutes les dépeches avoisinant le point donné
- // par latitude longitude
- // limité par distance
-
- // 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);
-
- string longitude = context.Request.QueryString["longitude"];
- string latitude = context.Request.QueryString["latitude"];
- string range = context.Request.QueryString["range"];
-
- string lang = context.Request.QueryString["lang"];
-
- if (string.IsNullOrEmpty(range))
- {
- range = "30"; //TO DO configurer par le fichier XML
-
- }
- /*
- lEndPointName = GetEndPointName(context);
- processorRated = new ProcessorClient(lEndPointName);
- DocFromService = processorRated.GetHeartRatedList("", GetProductName(context, false), context.Request.QueryString["uno"], TimeCacheVote, MaxEntries);
- */
- try
- {
- Process.Trace(string.Format("AroundMe endpoint Name {0}", endPointName), System.Diagnostics.EventLogEntryType.Information);
- var processorClient = new ProcessorClient(endPointName);
-
-
- string reponse = processorClient.GetAroundMe(latitude, longitude, range, 40, lang);
- Process.Trace(string.Format("AroundMe retour du server {0}", reponse), System.Diagnostics.EventLogEntryType.Information);
- context.Response.Write(reponse );
-
- }
- 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 void RequestMostViewed(HttpContext context)
- {
- throw new NotImplementedException();
- }
-
-
-
- static XmlDocument BuildSites(out List<String> sitesPath, out DateTime CachedDate)
- {
-
-
- XmlDocument WebConfig = Process.Configuration;
- string VdG = "";
-
- //Process.FileConfigurationPath
- Process.ReloadConfiguration(); // il faudrait le faire uniquement pour le changement du fichier de config...
-
- try
- {
- XmlElement xCache = (XmlElement)Process.Configuration.SelectSingleNode("//config/rated");
- if (xCache != null)
- {
- if (xCache.HasAttribute("expiration"))
- {
- _ExpireCacheVote = xCache.Attributes["expiration"].Value.DurationToTimeSpan();
- }
-
- if (xCache.HasAttribute("buildedWithXDay"))
- {
- _BuildWithXDay = xCache.Attributes["buildedWithXDay"].Value.DurationToTimeSpan();
- }
-
- }
-
- XmlElement xDir = (XmlElement)Process.Configuration.SelectSingleNode("//*[@virtualDir]");
- if (xDir != null)
- VdG = xDir.Attributes["virtualDir"].Value;
-
- }
- catch
- {
- _ExpireCacheVote = null; // 20 mn
- _BuildWithXDay = null; //30 jours
- }
-
- sitesPath = new List<string>();
- CachedDate = System.DateTime.MinValue;
- XmlDocument buildedSites = new XmlDocument();
- XmlNode xbuildedIcones;
- String FilePathConfig = Process.FileConfigurationPath;
-
- if (_VdByTopicId == null)
- {
- _VdByTopicId = new System.Collections.Hashtable();
- }
- else
- {
- _VdByTopicId.Clear();
- }
- if (string.IsNullOrEmpty(FilePathConfig) == false)
- {
- sitesPath.Add(FilePathConfig);
- Process.Trace(string.Format("Added {0} in sitesPath ", FilePathConfig), System.Diagnostics.EventLogEntryType.Information);
- }
-
- // le generated XMl n'est pas bon...
- if (_services == null)
- {
- #if DEBUG
- Process.Trace(WebApplication.PageName, "Build Sites start", System.Diagnostics.EventLogEntryType.Information);
- #endif
-
- _services = new System.Collections.Hashtable();
- _idVD = new System.Collections.Hashtable();
- // lecture de la configuration des parametres WCF
- foreach (XmlElement xService in WebConfig.SelectSingleNode("//config/services").ChildNodes)
- {
- PathAndWCF newconfig = new PathAndWCF();
- if (xService.HasAttribute("endpoint"))
- {
- newconfig.EndPointName = xService.Attributes["endpoint"].Value;
- }
- // mandatory...
-
-
- XmlDocument XConfigServices = new XmlDocument();
- XConfigServices.Load(xService.Attributes["serviceConfigPath"].Value);
-
-
- string BuildedStoragePath;
- BuildedStoragePath = XConfigServices.SelectSingleNode("//config/storage").Attributes["storePath"].Value;
- newconfig.RootPath = BuildedStoragePath;
-
- string PathGeneratedXml = GetPath(BuildedStoragePath, Constants._storageSitesFormatName, Constants._storageSitesKey, Constants._storageSitesFileId);
- if (string.IsNullOrEmpty(PathGeneratedXml) == false)
- {
-
- DateTime fd = System.IO.File.GetLastWriteTimeUtc(PathGeneratedXml);
- if (CachedDate < fd)
- CachedDate = fd;
- sitesPath.Add(PathGeneratedXml);
- XmlDocument loadX = new XmlDocument();
- loadX.Load(PathGeneratedXml);
- newconfig.GeneratedSites = new XmlDocument();
- newconfig.GeneratedSites.LoadXml(loadX.OuterXml);
-
- }
-
- _services.Add(xService.Attributes["virtualDir"].Value, newconfig);
- _idVD.Add(xService.Attributes["id"].Value, xService.Attributes["virtualDir"].Value);
- }
-
- }// if (_services == null )
-
-
- buildedSites.LoadXml("<sites dataCenter='1'><icones/></sites>");
- foreach (XmlAttribute xatt in WebConfig.SelectSingleNode("//config/sites").Attributes)
- {
- ((XmlElement)(buildedSites.SelectSingleNode("//sites"))).SetAttribute(xatt.Name, xatt.Value);
- }
- xbuildedIcones = buildedSites.SelectSingleNode("//icones");
-
-
- foreach (XmlNode curWebSite in WebConfig.SelectNodes("//config/sites/site"))
- {
- XmlNode curResSites;
- String ProductVoteName = "";
- String CurProductId = "";
-
- if (((XmlElement)curWebSite).HasAttribute("productVote"))
- {
- ProductVoteName = curWebSite.Attributes["productVote"].Value;
- }
- else
- {
- //TODO trace
- }
- if (((XmlElement)curWebSite).HasAttribute("id"))
- {
- CurProductId = curWebSite.Attributes["id"].Value;
- }
- else
- {
- //TODO trace
- }
-
- curResSites = buildedSites.DocumentElement.AppendChild(buildedSites.ImportNode(curWebSite, false));
- if (((XmlElement)curResSites).HasAttribute("icon"))
- {
- curResSites.Attributes["icon"].Value = System.IO.Path.GetFileNameWithoutExtension(curResSites.Attributes["icon"].Value.Replace(@"\", "/"));
- }
- foreach (XmlNode curAdv in curWebSite.SelectNodes("advisories"))
- {
- curResSites.AppendChild(buildedSites.ImportNode(curAdv, true));
- }
-
- foreach (XmlNode curConfigTopics in curWebSite.SelectNodes("./topics"))
- {
- XmlNode curResTopics;
- XmlDocument GeneratedSites;
- curResTopics = curResSites.AppendChild(buildedSites.ImportNode(curConfigTopics, false));
-
- foreach (XmlAttribute xXmlTopicAttribute in curConfigTopics.Attributes)
- {
- if (xXmlTopicAttribute.Name == "icon")
- ((XmlElement)curResTopics).SetAttribute(xXmlTopicAttribute.Name, System.IO.Path.GetFileNameWithoutExtension(xXmlTopicAttribute.Value.Replace(@"\", "/")));
- else
- ((XmlElement)curResTopics).SetAttribute(xXmlTopicAttribute.Name, xXmlTopicAttribute.Value);
-
- }
-
- /* List<string> icons;
- icons = new List<string>();
- */
-
- //GeneratedSites = new XmlDocument();
- // partie de fusion des Documents sites filtré par le WebConfig...
- foreach (XmlNode curConfigTopic in curConfigTopics.SelectNodes("topic"))
- {
- // il faut remplire le Generated Sites
- string idVD = GetLocalOrParentAttribute((XmlElement)curConfigTopic, "service", "site");
- if (string.IsNullOrEmpty(idVD) == false)
- {
- string vd = (string)_idVD[idVD];
-
- // note determination storagepath
- GeneratedSites = ((PathAndWCF)_services[vd]).GeneratedSites;
- // on va aller chercher dans le site generé le topic correspondant
-
- XmlAttribute xId = curConfigTopic.Attributes["id"];
- string sId;
-
- if (xId != null)
- {
- sId = string.Format("{0}__{1}", vd, xId.Value);
- }
- else
- {
- // pas d'Id il faut en generer un... ou pas
- string type = ((int)Enum.Parse(typeof(TopicImplementation.TopicType), curConfigTopic.GetAttributeValue("type", TopicImplementation.TopicType.standard.ToString()))).ToString();
-
-
- sId = string.Format("{2}_{0}_{1}_{3}",
- curConfigTopic.GetAttributeValue("fullName", "").MyGetHashCode(),
- type.MyGetHashCode(),
- curConfigTopic.ParentNode.GetAttributeValue("name", "").MyGetHashCode(),
- curWebSite.GetAttributeValue("id", "").MyGetHashCode()
- );
-
-
- }
- if (_VdByTopicId.ContainsKey(sId) == false)
- {
- _VdByTopicId.Add(sId, ((PathAndWCF)_services[vd]).EndPointName);
- }
- else
- {
- if (((string)_VdByTopicId[sId]) != ((PathAndWCF)_services[vd]).EndPointName)
- throw new Exception(string.Format("id for topic must be unique {0} : {1}//{2}", sId, (string)_VdByTopicId["sId"], ((PathAndWCF)_services[vd]).EndPointName));
- }
-
- XmlNode VirtualGeneratedTopic;
- if (string.IsNullOrEmpty(sId) == false)
- {
-
- Boolean bSpecialTopics = false; // videorama diaporama etc.
- VirtualGeneratedTopic = GeneratedSites.SelectSingleNode(string.Format("//topic[@id='{0}']", sId));
- if (VirtualGeneratedTopic != null)
- {
-
- if (((XmlElement)VirtualGeneratedTopic).HasAttribute("type"))
- {
-
- string ttype = VirtualGeneratedTopic.Attributes["type"].Value;
- if (ttype == "videorama" || ttype == "diaporama" || ttype == "7" || ttype == "8")
- {
- bSpecialTopics = true;
- }
- }
-
- XmlNode curResTopic;
- if (bSpecialTopics)
- curResTopic = curResTopics.AppendChild(buildedSites.ImportNode(VirtualGeneratedTopic, false));
- // on ne recupere pas la premiere catchLine... est-ce un souci
- else
- curResTopic = curResTopics.AppendChild(buildedSites.ImportNode(VirtualGeneratedTopic, true)); // on passe a true pour recuperer la cachtLine...
- //rajout des icones
- string ConfigIconName = curConfigTopic.GetAttributeValue("icon", "");
- string generatedIconName = VirtualGeneratedTopic.GetAttributeValue("icon", "");
- if (string.IsNullOrEmpty(ConfigIconName))
- {
- // on prend l'icone du topic généree par le service de prod.
- string lIcon = curResTopic.GetAttributeValue("icon", "");
- if (string.IsNullOrEmpty(lIcon) == false)
- {
- XmlNode IconInGeneratedSite = GeneratedSites.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", lIcon, "topic"));
- if (IconInGeneratedSite != null)
- if (xbuildedIcones.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", lIcon, "topic")) == null)
- xbuildedIcones.AppendChild(buildedSites.ImportNode(IconInGeneratedSite, true));
-
-
- XmlNode ThumbIconInGeneratedSite = GeneratedSites.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", lIcon, "thumbnail"));
- if (ThumbIconInGeneratedSite != null)
- if (xbuildedIcones.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", lIcon, "thumbnail")) == null)
- xbuildedIcones.AppendChild(buildedSites.ImportNode(ThumbIconInGeneratedSite, true));
-
- curResTopic.Attributes["icon"].Value = lIcon;
- }
- }
- else
- {
- // on genere nous meme une icone ( surcharge) !!
- XmlNode xNewIcon;
- xNewIcon = CreateNewIcon(xbuildedIcones.OwnerDocument, ConfigIconName, curResTopic, "topic");
- //xNewIcon = xbuildedIcones.OwnerDocument.CreateNode(
- xbuildedIcones.AppendChild(xNewIcon);
- // penser a castrer le path...
- ((XmlElement)curResTopic).SetAttribute("icon", System.IO.Path.GetFileNameWithoutExtension(ConfigIconName.Replace(@"\", "/")));
-
- }
- //if (curConfigTopic.GetAttributeValue ("icon",""))
-
- foreach (XmlAttribute xXmlTopicAttribute in curConfigTopic.Attributes)
- {
- if (xXmlTopicAttribute.Name != "icon" && xXmlTopicAttribute.Name != "type")
- {
- ((XmlElement)curResTopic).SetAttribute(xXmlTopicAttribute.Name, xXmlTopicAttribute.Value);
- }
- if (xXmlTopicAttribute.Name == "overrideuno")
- {
- // l'uno est forcé par la config... cas de reprise 1.1 par exemple
- string strUno = curResTopic.Attributes["uno"].Value;
- ((XmlElement)curResTopic).SetAttribute("newuno", strUno);
- ((XmlElement)curResTopic).SetAttribute("uno", curConfigTopic.Attributes["overrideuno"].Value);
-
- }
- if (xXmlTopicAttribute.Name == "type")
- {
- try
- {
- string iType = ((int)Enum.Parse(typeof(TopicImplementation.TopicType), curConfigTopic.GetAttributeValue("type", TopicImplementation.TopicType.standard.ToString()))).ToString();
- ((XmlElement)curResTopic).SetAttribute(xXmlTopicAttribute.Name, iType);
- }
- catch (Exception parsing)
- {
- Process.Trace(parsing, System.Diagnostics.EventLogEntryType.Warning);
- ((XmlElement)curResTopic).RemoveAttribute(xXmlTopicAttribute.Name);
- }
- }
- }
-
- if (((XmlElement)curResTopic).HasAttribute("daily"))
- {
- Boolean value;
- ((XmlElement)curResTopic).SetAttribute("daily", (bool.TryParse(curResTopic.GetAttributeValue("daily", "true"), out value)) ? "0" : "1");
- // changement de sens pour aller avec les applications déposées :)
- }
- // Gestion des sous topics;
-
- string parentType = curConfigTopic.GetAttributeValue("type", "");
-
-
- // ici il faut inverser on doit se baser sur la
- if (bSpecialTopics == false)
- {
- foreach (XmlNode curConfigSubTopic in curConfigTopic.SelectNodes("subtopic"))
- {
- string subId = curConfigSubTopic.Attributes["id"].Value;
- XmlNode VirtualGeneratedSubTopic;
- if (string.IsNullOrEmpty(parentType) == false)
- {
- // subId = string.Format("{0}__{1}", vd, subId);
- if (!(parentType == "7" || parentType == "8" || parentType == "diaporama" || parentType == "magazin"))
- {
- subId = string.Format("{0}__{1}", vd, subId);
- }
- else
- { }
-
-
- }
- else
- subId = string.Format("{0}__{1}", vd, subId);
- XmlNode SubFromGenerated = GeneratedSites.SelectSingleNode(string.Format("//topic[@id='{0}'] | //subtopic[@id='{0}']", subId));
- if (SubFromGenerated != null)
- {
- VirtualGeneratedSubTopic = buildedSites.ImportNode(curConfigSubTopic, true);
-
- //recopie des attributs...
- //GeneratedSites.SelectSingleNode(string.Format("//topic[@id='{0}']", subId));
- foreach (XmlAttribute xXmlTopicAttribute in SubFromGenerated.Attributes)
- {
- if (xXmlTopicAttribute.Name != "icon" && xXmlTopicAttribute.Name != "type")
- ((XmlElement)VirtualGeneratedSubTopic).SetAttribute(xXmlTopicAttribute.Name, xXmlTopicAttribute.Value);
- if (xXmlTopicAttribute.Name == "type")
- {
- try
- {
- string iType = ((int)Enum.Parse(typeof(TopicImplementation.TopicType), curConfigTopic.GetAttributeValue("type", TopicImplementation.TopicType.standard.ToString()))).ToString();
- ((XmlElement)VirtualGeneratedSubTopic).SetAttribute(xXmlTopicAttribute.Name, iType);
- }
- catch (Exception parsing)
- {
- Process.Trace(parsing, System.Diagnostics.EventLogEntryType.Warning);
- ((XmlElement)VirtualGeneratedSubTopic).RemoveAttribute(xXmlTopicAttribute.Name);
- }
- }
-
- if (xXmlTopicAttribute.Name == "icon")
- {
- string lIcon = xXmlTopicAttribute.Value;
- // il faut rajouter un noeud de type Topic sinon le framework de l'Application
- // ne prend pas en compte le thumbnail
- XmlNode IconInGeneratedSite = GeneratedSites.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", lIcon, "topic"));
- if (IconInGeneratedSite != null)
- if (xbuildedIcones.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", lIcon, "topic")) == null)
- xbuildedIcones.AppendChild(buildedSites.ImportNode(IconInGeneratedSite, true));
-
- XmlNode ThumbIconInGeneratedSite = GeneratedSites.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", lIcon, "thumbnail"));
- if (ThumbIconInGeneratedSite != null)
- if (xbuildedIcones.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", lIcon, "thumbnail")) == null)
- xbuildedIcones.AppendChild(buildedSites.ImportNode(ThumbIconInGeneratedSite, true));
- ((XmlElement)VirtualGeneratedSubTopic).SetAttribute("icon", lIcon);
- //curResTopic.Attributes["icon"].Value = lIcon;
- }
- }
-
- if (((XmlElement)VirtualGeneratedSubTopic).HasAttribute("href"))
- {
- VirtualGeneratedSubTopic.Attributes["href"].Value = string.Format("{0}&product={1}", VirtualGeneratedSubTopic.Attributes["href"].Value, CurProductId);
- }
- if (((XmlElement)VirtualGeneratedSubTopic).HasAttribute("daily"))
- {
- Boolean value;
- ((XmlElement)VirtualGeneratedSubTopic).SetAttribute("daily", (bool.TryParse(VirtualGeneratedSubTopic.GetAttributeValue("daily", "true"), out value)) ? "0" : "1");
- }
-
- if (SubFromGenerated.HasChildNodes)
- {
- VirtualGeneratedSubTopic.AppendChild(buildedSites.ImportNode(SubFromGenerated.FirstChild, true));
- }
-
- if (VirtualGeneratedSubTopic != null)
- curResTopic.AppendChild(VirtualGeneratedSubTopic);
-
-
- }//if (SubFromGenerated != null)
- }
- }
- else
- {
- //==>bSpecialTopics = true
- // on est dans le cadre d'un topic special demande IPAD ( topic a tri par table)
-
- string buildedId = string.Format("{0}__{1}", vd, curConfigTopic.Attributes["id"].Value);
-
- XmlNode BuildedContainerTopic = GeneratedSites.SelectSingleNode(string.Format("//topic[@id='{0}']", buildedId)); ;
- foreach (XmlNode curBuildedSubTopic in BuildedContainerTopic.SelectNodes("subtopic"))
- {
- Boolean ok = true;
-
- if (((XmlElement)curBuildedSubTopic).HasAttribute("Serve"))
- if (curBuildedSubTopic.Attributes["Serve"].InnerText == "false")
- ok = false;
- if (ok)
- {
- string configId = curBuildedSubTopic.Attributes["id"].Value;
- XmlNode curConfigSubTopic = curConfigTopic.SelectSingleNode(string.Format("subtopic[@id='{0}']", configId));
- // il ne faut prendre en compte que le virtual ID voulu
- // note ici ce n'est pas bon on duplique les noeuds
- // encours
- if (curConfigSubTopic != null)
- {
- // si il est présentable (filtre du fichier de config du site Web)
- XmlNode VirtualGeneratedSubTopic = null;
- VirtualGeneratedSubTopic = buildedSites.ImportNode(curConfigSubTopic, true);
-
- // on copie les valeurs remarquables
- foreach (XmlAttribute xXmlTopicAttribute in curBuildedSubTopic.Attributes)
- {
- if (xXmlTopicAttribute.Name != "icon" && xXmlTopicAttribute.Name != "type")
- ((XmlElement)VirtualGeneratedSubTopic).SetAttribute(xXmlTopicAttribute.Name, xXmlTopicAttribute.Value);
- if (xXmlTopicAttribute.Name == "type")
- {
- try
- {
- string iType = ((int)Enum.Parse(typeof(TopicImplementation.TopicType), curConfigTopic.GetAttributeValue("type", TopicImplementation.TopicType.standard.ToString()))).ToString();
- ((XmlElement)VirtualGeneratedSubTopic).SetAttribute(xXmlTopicAttribute.Name, iType);
- }
- catch (Exception parsing)
- {
- Process.Trace(parsing, System.Diagnostics.EventLogEntryType.Warning);
- ((XmlElement)VirtualGeneratedSubTopic).RemoveAttribute(xXmlTopicAttribute.Name);
- }
- }
-
- if (xXmlTopicAttribute.Name == "icon")
- {
- string lIcon = xXmlTopicAttribute.Value;
- // il faut rajouter une icone de type topic sinon
- // le framework de l'application ne comprend pas qu'on est
- // dans le cadre d'une custom icon
- XmlNode IconInGeneratedSite = GeneratedSites.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", lIcon, "topic"));
- if (IconInGeneratedSite != null)
- if (xbuildedIcones.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", lIcon, "topic")) == null)
- xbuildedIcones.AppendChild(buildedSites.ImportNode(IconInGeneratedSite, true));
-
- XmlNode ThumbIconInGeneratedSite = GeneratedSites.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", lIcon, "thumbnail"));
- if (ThumbIconInGeneratedSite != null)
- if (xbuildedIcones.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", lIcon, "thumbnail")) == null)
- xbuildedIcones.AppendChild(buildedSites.ImportNode(ThumbIconInGeneratedSite, true));
- ((XmlElement)VirtualGeneratedSubTopic).SetAttribute("icon", lIcon);
- //curResTopic.Attributes["icon"].Value = lIcon;
- }
- }
- // on inverse la logique le Web Est maitre sur le service !!!
- foreach (XmlAttribute xXmlTopicAttribute in curConfigSubTopic.Attributes)
- {
- if (xXmlTopicAttribute.Name == "type")
- {
- try
- {
- string res = xXmlTopicAttribute.Value;
-
- string iType = ((int)Enum.Parse(typeof(TopicImplementation.TopicType), res)).ToString();
- ((XmlElement)VirtualGeneratedSubTopic).SetAttribute(xXmlTopicAttribute.Name, iType);
- }
- catch (Exception parsing)
- {
- Process.Trace(parsing, System.Diagnostics.EventLogEntryType.Warning);
- ((XmlElement)VirtualGeneratedSubTopic).RemoveAttribute(xXmlTopicAttribute.Name);
- }
-
- }
- }
- if (((XmlElement)VirtualGeneratedSubTopic).HasAttribute("href"))
- {
- VirtualGeneratedSubTopic.Attributes["href"].Value = string.Format("{0}&product={1}", VirtualGeneratedSubTopic.Attributes["href"].Value, CurProductId);
- }
-
- if (((XmlElement)VirtualGeneratedSubTopic).HasAttribute("daily"))
- {
- Boolean value;
- ((XmlElement)VirtualGeneratedSubTopic).SetAttribute("daily", (bool.TryParse(VirtualGeneratedSubTopic.GetAttributeValue("daily", "true"), out value)) ? "0" : "1");
- }
-
- if (curBuildedSubTopic.HasChildNodes)
- {
- VirtualGeneratedSubTopic.AppendChild(buildedSites.ImportNode(curBuildedSubTopic.FirstChild, true));
- }
-
- // on le rajoute au site
- if (VirtualGeneratedSubTopic != null)
- curResTopic.AppendChild(VirtualGeneratedSubTopic);
- }
- /*
- else
- {
- XmlNode VirtualGeneratedSubTopic = null;
- VirtualGeneratedSubTopic = buildedSites.CreateNode(XmlNodeType.Element, "DEBUG", "");
- VirtualGeneratedSubTopic.InnerText = configId;
-
- if (VirtualGeneratedSubTopic != null)
- curResTopic.AppendChild(VirtualGeneratedSubTopic);
-
- }
- */
- } // si on doit l'afficher...
- }
-
- }
- if (((XmlElement)curResTopic).HasAttribute("href"))
- {
- curResTopic.Attributes["href"].Value = string.Format("{0}&product={1}", curResTopic.Attributes["href"].Value, CurProductId);
-
- }
-
- }
- else
- {
- // le topic n'a pas été généré par le service de production...
- if (((XmlElement)curConfigTopic).HasAttribute("type"))
- {
- string topicType = curConfigTopic.Attributes["type"].Value;
- if (topicType == "heart" || topicType == "rated" || topicType == "mostviewed" || topicType == "favorite")
- {
- XmlNode AddedNewTopic = buildedSites.ImportNode(curConfigTopic, false);
-
- string iType = ((int)Enum.Parse(typeof(TopicImplementation.TopicType), curConfigTopic.GetAttributeValue("type", TopicImplementation.TopicType.standard.ToString()))).ToString();
- ((XmlElement)AddedNewTopic).SetAttribute("type", iType);
-
- if (((XmlElement)AddedNewTopic).HasAttribute("daily"))
- {
- Boolean value;
- ((XmlElement)AddedNewTopic).SetAttribute("daily", (bool.TryParse(AddedNewTopic.GetAttributeValue("daily", "true"), out value)) ? "0" : "1");
- // changement de sens pour aller avec les applications déposées
- }
- // Gestion de l'uno a faire... ou a revoir...
- ((XmlElement)AddedNewTopic).SetAttribute("uno", sId);
- if (((XmlElement)AddedNewTopic).HasAttribute("overrideuno"))
- {
- // changement de sens pour aller avec les applications déposées
- ((XmlElement)AddedNewTopic).SetAttribute("newuno", sId);
- ((XmlElement)AddedNewTopic).SetAttribute("uno", AddedNewTopic.Attributes["overrideuno"].Value);
- }
-
- ((XmlElement)AddedNewTopic).SetAttribute("href", string.Format("Topic.ashx?plugin=JI&uno={0}&product={1}&vd={2}", sId, CurProductId, VdG));
-
- // CC 29/09/2010 on met l'icone...
- if (string.IsNullOrEmpty(AddedNewTopic.GetAttributeValue("icon", "")) == false)
- {
- String ConfigIconName = AddedNewTopic.GetAttributeValue("icon", "");
-
- ((XmlElement)AddedNewTopic).SetAttribute("icon", System.IO.Path.GetFileNameWithoutExtension(AddedNewTopic.GetAttributeValue("icon", "").Replace(@"\", "/")));
- try
- {
- XmlNode xNewIcon;
- xNewIcon = CreateNewIcon(xbuildedIcones.OwnerDocument, ConfigIconName, curConfigTopic, "topic");
- //xNewIcon = xbuildedIcones.OwnerDocument.CreateNode(
- xbuildedIcones.AppendChild(xNewIcon);
- }
- catch (Exception debe)
- {
- #if DEBUG && DEBUGDEBE
- try
- {
- Process.Trace(debe, System.Diagnostics.EventLogEntryType.Error);
- System.Diagnostics.EventLog.WriteEntry("AFP Iphone", debe.StackTrace, System.Diagnostics.EventLogEntryType.Error);
- }
- catch
- { }
- #endif
- }
- }
-
- curResTopics.AppendChild(AddedNewTopic);
- }
- }
- else
- { // pas typé... pas généré ca peut être un virtuel pour subTopic
- if (curConfigTopic.SelectNodes(".//subtopic").Count > 0)
- {
- XmlNode curResTopic;
- curResTopic = curResTopics.AppendChild(buildedSites.ImportNode(curConfigTopic, false));
- ((XmlElement)curResTopic).SetAttribute("uno", sId);
- //rajout des icones
- string ConfigIconName = curConfigTopic.GetAttributeValue("icon", "");
-
- // on genere nous meme une icone ( surcharge) !!
- if (string.IsNullOrEmpty(ConfigIconName) == false)
- {
- XmlNode xNewIcon;
- xNewIcon = CreateNewIcon(xbuildedIcones.OwnerDocument, ConfigIconName, curResTopic, "topic");
- //xNewIcon = xbuildedIcones.OwnerDocument.CreateNode(
- xbuildedIcones.AppendChild(xNewIcon);
- // penser a castrer le path...
- curResTopic.Attributes["icon"].Value = System.IO.Path.GetFileNameWithoutExtension(ConfigIconName.Replace(@"\", "/"));
- }
- foreach (XmlNode curConfigSubTopic in curConfigTopic.SelectNodes("subtopic"))
- {
- string subId = curConfigSubTopic.Attributes["id"].Value;
- XmlNode VirtualGeneratedSubTopic;
- subId = string.Format("{0}__{1}", vd, subId);
- XmlNode SubFromGenerated = GeneratedSites.SelectSingleNode(string.Format("//topic[@id='{0}']", subId));
- if (SubFromGenerated != null)
- {
- VirtualGeneratedSubTopic = buildedSites.ImportNode(curConfigSubTopic, true);
-
- //recopie des attributs...
- //GeneratedSites.SelectSingleNode(string.Format("//topic[@id='{0}']", subId));
- foreach (XmlAttribute xXmlTopicAttribute in SubFromGenerated.Attributes)
- {
- if (xXmlTopicAttribute.Name != "icon" && xXmlTopicAttribute.Name != "type")
- ((XmlElement)VirtualGeneratedSubTopic).SetAttribute(xXmlTopicAttribute.Name, xXmlTopicAttribute.Value);
- if (xXmlTopicAttribute.Name == "type")
- {
- try
- {
- string iType = ((int)Enum.Parse(typeof(TopicImplementation.TopicType), curConfigTopic.GetAttributeValue("type", TopicImplementation.TopicType.standard.ToString()))).ToString();
- ((XmlElement)VirtualGeneratedSubTopic).SetAttribute(xXmlTopicAttribute.Name, iType);
- }
- catch (Exception parsing)
- {
- Process.Trace(parsing, System.Diagnostics.EventLogEntryType.Warning);
- ((XmlElement)VirtualGeneratedSubTopic).RemoveAttribute(xXmlTopicAttribute.Name);
- }
- }
- }
-
- if (((XmlElement)VirtualGeneratedSubTopic).HasAttribute("href"))
- {
- VirtualGeneratedSubTopic.Attributes["href"].Value = string.Format("{0}&product={1}", VirtualGeneratedSubTopic.Attributes["href"].Value, CurProductId);
- }
- if (((XmlElement)VirtualGeneratedSubTopic).HasAttribute("daily"))
- {
- Boolean value;
- ((XmlElement)VirtualGeneratedSubTopic).SetAttribute("daily", (bool.TryParse(VirtualGeneratedSubTopic.GetAttributeValue("daily", "true"), out value)) ? "0" : "1");
- }
-
- if (SubFromGenerated.HasChildNodes)
- {
- VirtualGeneratedSubTopic.AppendChild(buildedSites.ImportNode(SubFromGenerated.FirstChild, true));
- }
-
- if (VirtualGeneratedSubTopic != null)
- curResTopic.AppendChild(VirtualGeneratedSubTopic);
- }
- }
- }
-
- }
- }
- }
- } //id service present
- else
- {
- string messageError;
- try
- {
- messageError = string.Format(" Service node is mandatory. Not found for topic {0} ", curConfigTopic.Attributes["id"].Value);
- Process.Trace(messageError, System.Diagnostics.EventLogEntryType.Error);
- }
- catch (Exception e)
- {
- Process.Trace(string.Format("Bad Config. {0}", e.Message), System.Diagnostics.EventLogEntryType.Error);
- }
- }
- }
- // il faut rajouter les advisories
- foreach (XmlNode curConfigTopic in curConfigTopics.SelectNodes("advisories"))
- {
- curResTopics = curResSites.AppendChild(buildedSites.ImportNode(curConfigTopics, true));
- }
- // }
-
- // a rajouter celle qui viennent de topics( flag) + site (logo);
- string ConfigTopicsIconName = curConfigTopics.GetAttributeValue("icon", "");
- if (string.IsNullOrEmpty(ConfigTopicsIconName) == false)
- {
- XmlNode xIconsTopics = CreateNewIcon(xbuildedIcones.OwnerDocument, ConfigTopicsIconName, curConfigTopics, "flag");
- xbuildedIcones.AppendChild(xIconsTopics);
- }
- else
- {
- // on ne devrait jamais être ici sauf a avoir mis un name sur topics...
- if (((XmlElement)curConfigTopics).HasAttribute("service") && ((XmlElement)curConfigTopics).HasAttribute("name"))
- {
- string topicsName = curConfigTopics.Attributes["name"].Value;
- GeneratedSites = ((PathAndWCF)_services[(string)_idVD[curConfigTopics.Attributes["service"].Value]]).GeneratedSites;
- XmlNode xLogoIcon;
- String LogoName;
- XmlNode xGenereratedtopics = GeneratedSites.SelectSingleNode(string.Format("//topics[@name='{0}'", topicsName));
- LogoName = xGenereratedtopics.GetAttributeValue("icon", "");
- LogoName = System.IO.Path.GetFileNameWithoutExtension(LogoName.Replace(@"\", "/"));
-
- if (string.IsNullOrEmpty(LogoName) == false)
- {
- xLogoIcon = GeneratedSites.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", LogoName, "logo"));
- if (xLogoIcon != null)
- if (xbuildedIcones.SelectSingleNode(string.Format("//sites/icones/icons[@name='{0}' and @class='{1}']", LogoName, "topic")) == null)
- xbuildedIcones.AppendChild(buildedSites.ImportNode(xLogoIcon, true));
- }
-
- }
- //else
- // ni l'un ni l'autre on n'a pas d'icones
- }
-
- } // curConfigTopics
- // ajout de l'icone propre au site
-
- string ConfigWebIconName = curWebSite.GetAttributeValue("icon", "");
- string serviceName = curWebSite.GetAttributeValue("service", "");
- XmlNode xFlagIcon;
-
- if (string.IsNullOrEmpty(ConfigWebIconName) == false)
- {
- XmlNode xIconSite = CreateNewIcon(xbuildedIcones.OwnerDocument, ConfigWebIconName, curWebSite, "logo");
- xbuildedIcones.AppendChild(xIconSite);
- }
- else
- {
- // pas d'icones
- if (string.IsNullOrEmpty(serviceName) == false)
- {
- XmlDocument GeneratedSite = ((PathAndWCF)_services[(string)_idVD[serviceName]]).GeneratedSites;
-
- xFlagIcon = GeneratedSite.SelectSingleNode(string.Format("//sites/icones/icons[@class='{0}']", "logo"));
- if (xFlagIcon != null)
- {
- if (xbuildedIcones.SelectSingleNode(string.Format("//sites/icones/icons[@class='{0}']", "logo")) == null)
- xbuildedIcones.AppendChild(buildedSites.ImportNode(xFlagIcon, true));
- }
- // mais on a un service on va aller chercher l'icon de celui ci.
- }
- }
-
-
-
- }//curWebSite
-
-
-
- return buildedSites;
-
- }
-
- /// <summary>
- /// Cree un noeud contenant l'icone en base 64 en petit et en grand...
- /// </summary>
- /// <param name="xmlDocument"></param>
- /// <param name="ConfigIconName"></param>
- /// <param name="xNode"></param>
- /// <param name="iconClass"></param>
- /// <returns></returns>
- private static XmlNode CreateNewIcon(XmlDocument xmlDocument, string ConfigIconName, XmlNode xNode, string iconClass)
- {
- string smallIconPath = GetLocalOrParentAttribute((XmlElement)xNode, "smallIconsPath", "sites");
- string bigIconPath = GetLocalOrParentAttribute((XmlElement)xNode, "bigIconsPath", "sites");
-
- XmlNode xNewIcon;
- xNewIcon = xmlDocument.CreateNode(XmlNodeType.Element, "icons", "");
- ((XmlElement)xNewIcon).SetAttribute("name", System.IO.Path.GetFileNameWithoutExtension(ConfigIconName.Replace(@"\", "/")));
- ((XmlElement)xNewIcon).SetAttribute("class", iconClass);
-
-
- if (string.IsNullOrEmpty(smallIconPath) == false)
- {
- XmlNode xSmallIcon;
- xSmallIcon = xmlDocument.CreateNode(XmlNodeType.Element, "icon", "");
- ((XmlElement)xSmallIcon).SetAttribute("smallSize", "1");
- string pathFile;
- pathFile = System.IO.Path.Combine(smallIconPath, ConfigIconName);
- if (System.IO.File.Exists(pathFile))
- {
- Stream document = new FileStream(pathFile, FileMode.Open, FileAccess.Read, FileShare.Read);
- xSmallIcon.InnerText = FileToBase64(document);
- }
- xNewIcon.AppendChild(xSmallIcon);
- }
- if (string.IsNullOrEmpty(smallIconPath) == false)
- {
- XmlNode xBigIcon;
- xBigIcon = xmlDocument.CreateNode(XmlNodeType.Element, "icon", "");
- ((XmlElement)xBigIcon).SetAttribute("smallSize", "0");
- string pathFile;
- pathFile = System.IO.Path.Combine(bigIconPath, ConfigIconName);
- if (System.IO.File.Exists(pathFile))
- {
- Stream document = new FileStream(pathFile, FileMode.Open, FileAccess.Read, FileShare.Read);
- xBigIcon.InnerText = FileToBase64(document);
- }
- xNewIcon.AppendChild(xBigIcon);
- }
-
- return xNewIcon;
- //throw new NotImplementedException();
- }
-
-
-
- // pourquoi se gonfler...
- private static string GetPath(string storePath, string format, string key, string id)
- {
- try
- {
- return Path.Combine(Path.Combine(Path.Combine(Path.Combine(storePath, format), key), GetHashFolder(id)), id);
- }
- catch
- {
- return "";
- }
- }
-
- public static string GetHashFolder(string id)
- {
- return (Math.Abs(Path.GetFileNameWithoutExtension(id).MyGetHashCode()) % 256).ToString("X2");
- }
-
- public static string GetLocalOrParentAttribute(XmlElement node, string attributename, string stopCondition)
- {
-
- XmlElement curNode = node;
- while (curNode is XmlElement && !(curNode.ParentNode is XmlDocument) && curNode.HasAttribute(attributename) == false)
- {
- curNode = (XmlElement)curNode.ParentNode;
- if (!((XmlNode)curNode is XmlDocument) && curNode.Name == stopCondition)
- {
- if (curNode.HasAttribute(attributename))
- return curNode.Attributes[attributename].Value;
- else
- return null;
- }
-
- }
- if (!((XmlNode)curNode is XmlDocument))
- {
- if (curNode.HasAttribute(attributename))
- return curNode.Attributes[attributename].Value;
- else
- return null;
- }
-
- return null;
-
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="file"></param>
- /// <returns></returns>
- public static string FileToBase64(Stream file)
- {
- byte[] buffer = new byte[file.Length];
-
- file.Read(buffer, 0, buffer.Length);
-
- return Convert.ToBase64String(buffer);
- }
-
- public static string GetDeviceName(HttpContext context)
- {
- string res;
- res = context.Request.UserAgent;
-
- try
- {
-
- res = (res.Split("-".ToCharArray()))[1];
- }
- catch
- {
- res = res.Substring(0, 63);
- }
- return res;
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="context"></param>
- /// <returns></returns>
- public static string GetProductName(HttpContext context, Boolean config)
- {
- string res;
-
-
- try
- {
- res = context.Request.QueryString["product"];
- if (string.IsNullOrEmpty(res))
- {
- XmlElement xSites;
- if (config)
- xSites = (XmlElement)Process.Configuration.SelectSingleNode("//sites");
- else
- xSites = (XmlElement)_BuildedSiteConfiguration.SelectSingleNode("//sites");
-
- string TopicId;
- TopicId = context.Request.QueryString["id"];
- if (string.IsNullOrEmpty(TopicId))
- TopicId = context.Request.QueryString["uno"];
- if (TopicId.IndexOf("__") > -1)
- TopicId = TopicId.Substring(TopicId.IndexOf("__") + 2);
- XmlElement xTopic = (XmlElement)xSites.SelectSingleNode(string.Format("//topic[@id='{0}']", TopicId));
- if (xTopic != null)
- {
- // détermination cascadée inverse...
- res = GetLocalOrParentAttribute(xTopic, "productVote", "sites");
-
-
-
- }
- else
- if (xSites.HasAttribute("productVote"))
- {
- res = xSites.Attributes["productVote"].Value;
- }
- else
- {
- res = xSites.SelectSingleNode("site").Attributes["id"].Value;
-
- }
- }
-
- }
- catch
- {
- res = "NO_PRODUCT";
- #if DEBUG
- if (string.IsNullOrEmpty(res))
- res = "AFP";
- #if DEBUGRATING || DEBUGVIEWED
- System.Diagnostics.Debugger.Break();
- #endif
- #endif
- }
- return res;
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="context"></param>
- /// <returns></returns>
- public static string GetEndPointName(HttpContext context)
- {
- String res;
- string virtualDir;
- try
- {
- virtualDir = context.Request.QueryString["vd"];
-
- if (string.IsNullOrEmpty(virtualDir))
- {
- string uno;
- uno = context.Request.QueryString["uno"];
-
- if (string.IsNullOrEmpty(uno) == false && uno.IndexOf("__") != -1)
- {
- virtualDir = uno.Substring(0, uno.IndexOf("__"));
- }
- else
- {
- string id;
- id = context.Request.QueryString["id"];
-
- if (string.IsNullOrEmpty(id) == false && id.IndexOf("__") != -1)
- {
- virtualDir = id.Substring(0, id.IndexOf("__"));
- }
- else
- {
- // on va prendre le premier ou le defaut;
- XmlElement xServices = (XmlElement)Process.Configuration.SelectSingleNode("//config/services");
- XmlElement xService;
- if (xServices.HasAttribute("defaultService"))
- {
- xService = (XmlElement)xServices.SelectSingleNode(string.Format("service[@id='{0}']", xServices.Attributes["defaultService"].Value));
- }
- else
- {
- // on fait au mieux on prend le premier
- xService = (XmlElement)xServices.ChildNodes[0];
- }
- virtualDir = xService.Attributes["virtualDir"].Value;
- }
- }
- }
- res = ((PathAndWCF)_services[virtualDir]).EndPointName;
- #if DEBUG
- Process.Trace(string.Format("Le EndpointName choisi est : {0}", res), System.Diagnostics.EventLogEntryType.Information);
- #endif
-
- }
- catch
- {
- res = "";
- }
- #if DEBUG
- if (string.IsNullOrEmpty(res))
- {
- res = "TCPAFP";
- #if DEBUGRATING || DEBUGVIEWED
- System.Diagnostics.Debugger.Break();
- #endif
- }
- #endif
-
- return res;
- }
-
-
- private static void UpdateRating(HttpContext context, XmlNode Article)
- {
- int nbVote;
- double rate;
-
- string productId = GetProductName(context, true);
- string ItemId;
- //XmlElement bag;
- try
- {
- ItemId = Article.Attributes["uno"].Value;
- string topicId = Article.Attributes["parentId"].Value;
-
- using (var processorClient = new ProcessorClient(GetEndPointName(context)))
- {
-
- processorClient.getRated(productId, topicId, ItemId, "", "", out rate, out nbVote);
- ((XmlElement)Article).SetAttribute("globalRate", Convert.ToString(rate));
- ((XmlElement)Article).SetAttribute("numberOfVote", Convert.ToString(nbVote));
- // to do faire les bags
-
- foreach (XmlNode bag in Article.SelectNodes("Bag"))
- {
-
- if (((XmlElement)bag).HasAttribute("uno"))
- {
- string mediaid = bag.Attributes["uno"].Value;
-
- processorClient.getRated(productId, "", "", mediaid, "", out rate, out nbVote);
- ((XmlElement)bag).SetAttribute("globalRate", Convert.ToString(rate));
- ((XmlElement)bag).SetAttribute("numberOfVote", Convert.ToString(nbVote));
- }
- }
-
- }
- }
- catch
- { }
- }
-
-
-
-
- }
-
-
-
- }