/*
         *      public void OnBeginRequest(object s, EventArgs e)
         *      {
         *          var app = (HttpApplication)s;
         *          var server = app.Server;
         *          var request = app.Request;
         *          var response = app.Response;
         *
         *
         *          //if (RewriterUtils.OmitFromRewriteProcessing(request.Url.LocalPath))
         *          //{
         *          //    return;
         *          //}
         *
         *
         *          //'Carry out first time initialization tasks
         *          //Initialize.Init(app);
         *
         *          if (request.Url.LocalPath.ToLower().EndsWith("/install/install.aspx")
         || request.Url.LocalPath.ToLower().EndsWith("/install/upgradewizard.aspx")
         || request.Url.LocalPath.ToLower().EndsWith("/install/installwizard.aspx")
         || request.Url.LocalPath.ToLower().EndsWith("captcha.aspx")
         || request.Url.LocalPath.ToLower().EndsWith("scriptresource.axd")
         || request.Url.LocalPath.ToLower().EndsWith("webresource.axd")
         || request.Url.LocalPath.ToLower().EndsWith(".ashx")
         ||             )
         ||         {
         ||             return;
         ||         }
         ||
         ||         var AbsoluteUri = app.Request.Url.AbsoluteUri;
         ||         string portalAlias;
         ||         PortalAliasInfo portal = GetPortalAlias(app, out portalAlias);
         ||         if (portal != null)
         ||         {
         ||             CacheController CacheCtrl = new CacheController(portal.PortalID);
         ||             var CacheItem = CacheCtrl.GetItem(AbsoluteUri);
         ||
         ||             if (CacheItem != null)
         ||             {
         ||                 if (IsCachable(app)){
         ||                     app.Context.Items["OpenOutputCache:CacheKey"] = CacheItem.CacheKey;
         ||                 }
         ||
         ||
         ||                 //string sendToUrl = "~/Portals/0/Cache/Output/55_65E28BECAA964E5BE8F2284FF6380489.data.html";
         ||                 //Satrabel.HttpModules.RewriterUtils.RewriteUrl(app.Context, sendToUrl);
         ||
         ||
         ||                 //var queryString = string.Empty;
         ||                 //string sendToUrlLessQString = sendToUrl;
         ||                 //if ((sendToUrl.IndexOf("?") > 0))
         ||                 //{
         ||                 //    sendToUrlLessQString = sendToUrl.Substring(0, sendToUrl.IndexOf("?"));
         ||                 //    queryString = sendToUrl.Substring(sendToUrl.IndexOf("?") + 1);
         ||                 //}
         ||
         ||                 //grab the file's physical path
         ||                 //string filePath = string.Empty;
         ||                 //filePath = app.Context.Server.MapPath(sendToUrlLessQString);
         ||
         ||                 //rewrite the path..
         ||                 //app.Context.RewritePath(sendToUrlLessQString, String.Empty, queryString);
         ||
         ||             }
         ||         }
         ||     }
         */
        private void OnResolveRequestCache(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;

            if (!IsCachable(app))
            {
                return;
            }
            HttpContext context = app.Context;

            try
            {
                //string CacheKey = app.Context.Items["OpenOutputCache:CacheKey"];
                PortalSettings ps = PortalController.GetCurrentPortalSettings();
                if (ps == null || ps.ActiveTab == null || ps.ActiveTab.TabID == Null.NullInteger)
                {
                    return;
                }
                int       TabId         = ps.ActiveTab.TabID;
                var       tc            = new TabController();
                Hashtable tabSettings   = tc.GetTabSettings(TabId);
                string    CacheProvider = GetTabSettingAsString(tabSettings, "CacheProvider");
                if (string.IsNullOrEmpty(CacheProvider))
                {
                    return;
                }
                OutputCachingProvider provider = OutputCachingProvider.Instance(CacheProvider);
                //string CurrentCulture = Localization.GetPageLocale(ps).Name;
                StringCollection includeVaryByKeys;
                StringCollection excludeVaryByKeys;
                GetVarBy(tabSettings, out includeVaryByKeys, out excludeVaryByKeys, ps.PortalId);
                SortedDictionary <string, string> varyBy = new SortedDictionary <string, string>();
                bool VaryAll = includeVaryByKeys.Count == 0;
                foreach (string key in app.Context.Request.QueryString.Keys)
                {
                    try
                    {
                        // prevent error on invalid querystring eg http://domain.com/?p1=valeu1&value2
                        if (string.IsNullOrWhiteSpace(key))
                        {
                            string referrer = app.Context.Request.UrlReferrer == null ? "none" : app.Context.Request.UrlReferrer.AbsoluteUri;
                            Logger.Warn($"Invalid Querystring in url. Request: {app.Context.Request.Url.AbsoluteUri}.  Referrer: {referrer}");
                            continue;
                        }

                        string qs = app.Context.Request.QueryString[key];
                        // end bughunt
                        varyBy.Add(key.ToLower(), qs);
                        if (VaryAll)
                        {
                            includeVaryByKeys.Add(key.ToLower());
                        }
                        else
                        {
                            if (!includeVaryByKeys.Contains(key) && !excludeVaryByKeys.Contains(key))
                            {
                                return;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception($"Error while processing QueryString. Request: {app.Context.Request.Url.AbsoluteUri}", ex);
                    }
                }
                if (PortalController.GetPortalSettingAsBoolean("OOC_VaryByBrowser", ps.PortalId, false))
                {
                    varyBy.Add("Browser", app.Context.Request.Browser.Browser);
                    includeVaryByKeys.Add("browser");
                }
                //excludeVaryByKeys.Add("returnurl");
                string CacheKey    = provider.GenerateCacheKey(TabId, includeVaryByKeys, excludeVaryByKeys, varyBy);
                string RawCacheKey = GetRawCacheKey(includeVaryByKeys, excludeVaryByKeys, varyBy);
                app.Context.Items["OpenOutputCache:RawCacheKey"] = RawCacheKey;
                app.Context.Items["OpenOutputCache:AbsoluteUri"] = app.Request.Url.AbsoluteUri;
                string CacheMode   = PortalController.GetPortalSetting("OOC_CacheMode", ps.PortalId, "ServerCache");
                int    ExpireDelay = PortalController.GetPortalSettingAsInteger("OOC_ExpireDelay", ps.PortalId, 60);
                if (provider.StreamOutput(TabId, CacheKey, app.Context))
                {
                    app.Context.Response.AddHeader("Content-Type", "text/html; charset=utf-8");
                    SetResponseCache(app.Context.Response, CacheKey, ExpireDelay, CacheMode);
                    app.CompleteRequest();
                }
                else
                {
                    int DefaultCacheDuration = PortalController.GetPortalSettingAsInteger("OOC_CacheDuration", ps.PortalId, 60);
                    int CacheDuration        = GetTabSettingAsInteger(tabSettings, "CacheDuration", DefaultCacheDuration);
                    if (CacheDuration > 0)
                    {
                        int DefaultMaxVaryByCount = PortalController.GetPortalSettingAsInteger("OOC_MaxVaryByCount", ps.PortalId, 0);
                        int MaxVaryByCount        = GetTabSettingAsInteger(tabSettings, "MaxVaryByCount", DefaultMaxVaryByCount);
                        int ItemCount             = 0;
                        if (MaxVaryByCount > 0)
                        {
                            ItemCount = OutputCachingProvider.Instance(CacheProvider).GetItemCount(TabId);
                        }
                        if (MaxVaryByCount <= 0 || ItemCount < MaxVaryByCount)
                        {
                            OutputCacheResponseFilter responseFilter = OutputCachingProvider.Instance(CacheProvider).GetResponseFilter(TabId, MaxVaryByCount, app.Response.Filter, CacheKey, TimeSpan.FromSeconds(CacheDuration));
                            app.Context.Response.Filter = responseFilter;
                            app.Context.Items["OpenOutputCache:Filter"]      = responseFilter;
                            app.Context.Items["OpenOutputCache:CacheMode"]   = CacheMode;
                            app.Context.Items["OpenOutputCache:ExpireDelay"] = ExpireDelay;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }