public void AddRange_ShouldWork()
        {
            var iplist = new IPList();

            iplist.AddRange("0.0.0.5", "0.0.0.20");
            for (uint ip = 0; ip < 5; ip++)
            {
                iplist.CheckNumber(ip).ShouldBeFalse();
            }
            for (uint ip = 5; ip < 21; ip++)
            {
                iplist.CheckNumber(ip).ShouldBeTrue();
            }
            for (uint ip = 21; ip < 32; ip++)
            {
                iplist.CheckNumber(ip).ShouldBeFalse();
            }
        }
Beispiel #2
0
        public JsonResult AddIPMasks(string Single_IP, string Cidr_IP, string Sub_IP, string Sub_Subnet, string Start_IP, string End_IP, bool IP_Allowed)
        {
            ExceptionsML bizEx;
            var          client = SvcBldr.Company();

            IPList l = new IPList();

            if (!String.IsNullOrEmpty(Single_IP))
            {
                l.Add(Single_IP);
            }
            if (!String.IsNullOrEmpty(Cidr_IP))
            {
                var parts = Cidr_IP.Split(new char[] { '/' });
                l.Add(parts[0], int.Parse(parts[1]));
            }
            if (!String.IsNullOrEmpty(Sub_IP) && !String.IsNullOrEmpty(Sub_Subnet))
            {
                l.Add(Sub_IP, Sub_Subnet);
            }
            if (!String.IsNullOrEmpty(Start_IP) && !String.IsNullOrEmpty(End_IP))
            {
                l.AddRange(Start_IP, End_IP);
            }

            foreach (var item in l.GetRanges())
            {
                var mask = new CompanyIPMaskDTO()
                {
                    IPMask = item.Key, SubnetMask = item.Value, Allowed = IP_Allowed
                };
                client.SetIPMask(mask, out bizEx);
                if (bizEx != null)
                {
                    return(Result(null, bizEx));
                }
            }
            return(GetIPMasks());
        }
        /// <summary>
        /// Handles OnLoad event at Page level<br/>
        /// Performs OnLoad actions that are common to all Pages.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad (e);

            // load the dedicated CSS
            if ( !this.IsCssFileRegistered("SmartError") )
                this.RegisterCssFile("Mod_SmartError");

            ArrayList storedError = null;
            StringBuilder sb = new StringBuilder(); // to build response text
            int _httpStatusCode = (int)HttpStatusCode.InternalServerError; // default value
            string _renderedEvent = string.Empty;
            string validStatus = "301;307;403;404;410;500;501;502;503;504";

            if ( Request.QueryString[0] != null )
            {
                // is this a "MagicUrl" request
                if ( Request.QueryString[0].StartsWith("404;http://") )
                {
                    Hashtable magicUrlList = null;
                    string redirectUrl = string.Empty;
                    string qPart = string.Empty;
                    int qPartPos = Request.QueryString[0].LastIndexOf("/") + 1 ;
                    qPart = qPartPos < Request.QueryString[0].Length ? Request.QueryString[0].Substring(qPartPos) : string.Empty;
                    if ( qPart.Length > 0 )
                    {
                        if ( Utils.IsInteger(qPart) )
                            redirectUrl = HttpUrlBuilder.BuildUrl(Int32.Parse(qPart));
                        else
                        {
                            magicUrlList = GetMagicUrlList(Portal.UniqueID);
                            if ( magicUrlList != null && magicUrlList.ContainsKey(HttpUtility.HtmlEncode(qPart)) )
                            {
                                redirectUrl = HttpUtility.HtmlDecode(magicUrlList[HttpUtility.HtmlEncode(qPart)].ToString());
                                if ( Utils.IsInteger(redirectUrl) )
                                    redirectUrl = HttpUrlBuilder.BuildUrl(Int32.Parse(redirectUrl));
                            }
                        }
                        if ( redirectUrl.Length != 0 )
                            Response.Redirect(redirectUrl, true);
                        else
                            _httpStatusCode = (int)HttpStatusCode.NotFound;
                    }

                }
                // get status code from querystring
                else if ( Utils.IsInteger(Request.QueryString[0]) && validStatus.IndexOf(Request.QueryString[0]) > -1 )
                {
                    _httpStatusCode = int.Parse(Request.QueryString[0]);
                }
            }

            // get stored error
            if (Request.QueryString["eid"] != null && Request.QueryString["eid"].Length > 0)
            {
                storedError = (ArrayList)CurrentCache.Get(Request.QueryString["eid"]);
            }
            if ( storedError != null && storedError[_RENDEREDEVENT_] != null )
                _renderedEvent = storedError[_RENDEREDEVENT_].ToString();
            else
                _renderedEvent = @"<p>No exception event stored or cache has expired.</p>";

            // get home link
            string homeUrl = HttpUrlBuilder.BuildUrl();

            // try localizing message
            try
            {
                switch ( _httpStatusCode )
                {
                    case (int)HttpStatusCode.NotFound : // 404
                    case (int)HttpStatusCode.Gone : // 410
                    case (int)HttpStatusCode.MovedPermanently : // 301
                    case (int)HttpStatusCode.TemporaryRedirect : // 307
                        sb.AppendFormat("<h3>{0}</h3>",General.GetString("SMARTERROR_404HEADING","Page Not Found", null));
                        sb.AppendFormat("<p>{0}</p>",General.GetString("SMARTERROR_404TEXT","We're sorry, but there is no page that matches your entry. It is possible you typed the address incorrectly, or the page may no longer exist. You may wish to try another entry or choose from the links below, which we hope will help you find what you’re looking for.", null));
                        break;
                    case (int)HttpStatusCode.Forbidden : // 403
                        sb.AppendFormat("<h3>{0}</h3>",General.GetString("SMARTERROR_403HEADING","Not Authorised", null));
                        sb.AppendFormat("<p>{0}</p>",General.GetString("SMARTERROR_403TEXT","You do not have the required authority for the requested page or action.", null));
                        break;
                    default :
                        sb.AppendFormat("<h3>{0}</h3>",General.GetString("SMARTERROR_500HEADING","Our Apologies", null));
                        sb.AppendFormat("<p>{0}</p>",General.GetString("SMARTERROR_500TEXT","We're sorry, but we were unable to service your request. It's possible that the problem is a temporary condition.", null));
                        break;
                }
                sb.AppendFormat("<p><a href=\"{0}\">{1}</a></p>", homeUrl,General.GetString("HOME","Home Page",null));
            }
            catch // default to english message
            {
                switch ( _httpStatusCode )
                {
                    case (int)HttpStatusCode.NotFound :
                        sb.Append("<h3>Page Not Found</h3>");
                        sb.Append("<p>We're sorry, but there is no page that matches your entry. It is possible you typed the address incorrectly, or the page may no longer exist. You may wish to try another entry or choose from the links below, which we hope will help you find what you’re looking for.</p>");
                        break;
                    case (int)HttpStatusCode.Forbidden :
                        sb.Append("<h3>Not Authorised</h3>");
                        sb.Append("<p>You do not have the required authority for the requested page or action.</p>");
                        break;
                    default :
                        sb.Append("<h3>Our Apologies</h3>");
                        sb.AppendFormat("<p>We're sorry, but we were unable to service your request. It's possible that the problem is a temporary condition.</p>");
                        break;
                }
                sb.AppendFormat("<p><a href=\"{0}\">{1}</a></p>",homeUrl, "Home Page");
            }

            // find out if user is on allowed IP Address
            if ( Request.UserHostAddress != null
                && Request.UserHostAddress.Length > 0 )
            {
                // construct IPList
                string[] lockKeyHolders = Config.LockKeyHolders.Split(new char[]{';'}); //ConfigurationSettings.AppSettings["LockKeyHolders"].Split(new char[]{';'});
                IPList ipList = new IPList();
                try
                {
                    foreach ( string lockKeyHolder in lockKeyHolders )
                    {
                        if ( lockKeyHolder.IndexOf("-") > -1 )
                            ipList.AddRange(lockKeyHolder.Substring(0, lockKeyHolder.IndexOf("-")), lockKeyHolder.Substring(lockKeyHolder.IndexOf("-") + 1));
                        else
                            ipList.Add(lockKeyHolder);
                    }

                    // check if requestor's IP address is in allowed list
                    if ( ipList.CheckNumber(Request.UserHostAddress) )
                    {
                        // we can show error details
                        sb.AppendFormat("<h3>{0} - {1}</h3>",General.GetString("SMARTERROR_SUPPORTDETAILS_HEADING","Support Details", null), _httpStatusCode.ToString());
                        sb.Append(_renderedEvent);
                    }
                }
                catch
                {
                    // if there was a problem, let's assume that user is not authorised
                }
            }
            PageContent.Controls.Add(new LiteralControl(sb.ToString()));
            Response.StatusCode = _httpStatusCode;
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
        }
Beispiel #4
0
        /// <summary>
        /// Handles the BeginRequest event of the AppleseedApplication control.
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// The <see cref="System.EventArgs"/> instance containing the event data.
        /// </param>
        protected void AppleseedApplication_BeginRequest(object sender, EventArgs e)
        {
            string rawUrlLower = Request.RawUrl.ToLower();

            if (rawUrlLower != "/" && !rawUrlLower.Contains("/installer") && !rawUrlLower.Contains("/webresource.axd") && !File.Exists(Server.MapPath(rawUrlLower.Split('?')[0])))
            {
                Appleseed.Framework.Site.Data.PagesDB pagedb = new Framework.Site.Data.PagesDB();
                string redirectToUrl = pagedb.GetDynamicPageUrl(rawUrlLower);
                if (!string.IsNullOrEmpty(redirectToUrl))
                {
                    Response.Redirect(redirectToUrl, true);
                    return;
                }
            }
            //Appleseed.Framework.Site.Data.PagesDB pagedb = new Framework.Site.Data.PagesDB();
            //string redirectToUrl = pagedb.GetDynamicPageUrl(Request.RawUrl);
            //if (!string.IsNullOrEmpty(redirectToUrl))
            //{
            //    Response.Redirect(redirectToUrl, true);
            //    return;
            //}
            string Addwww = System.Configuration.ConfigurationManager.AppSettings.Get("AddWwwToRequest");

            if (Addwww != null && Addwww.Equals("true"))
            {
                if (!Request.IsSecureConnection)
                {
                    if (!Request.Url.AbsoluteUri.ToLower().Contains("www"))
                    {
                        var newUrl = Request.Url.AbsoluteUri.Replace("http://", "http://www.");
                        Response.Redirect(newUrl, true);
                    }
                }
            }

            /*Send a signal to allow custom js registration (not enabled yet)*/
            Bus.Send(new JSRegisterDescriptor()
            {
                Scripts = new List <string>()
            });

            var contextReader = new Reader(new WebContextReader());
            var context       = contextReader.Current;

            var currentUrl = context.Request.Path.ToLower();

            if (Debugger.IsAttached && currentUrl.Contains("trace.axd"))
            {
                return;
            }

            context.Trace.Warn("Application_BeginRequest :: " + currentUrl);
            if (Portal.PageID > 0)
            {
                var physicalPath = context.Server.MapPath(currentUrl.Substring(currentUrl.LastIndexOf("/") + 1));

                if (!File.Exists(physicalPath))
                {
                    // Rewrites the path
                    context.RewritePath("~/default.aspx?" + context.Request.ServerVariables["QUERY_STRING"]);
                }
            }
            else
            {
                var pname = currentUrl.Substring(currentUrl.LastIndexOf("/") + 1);

                // if the request was not caused by an MS Ajax Client script invoking a WS.
                if (!currentUrl.ToLower().EndsWith(".asmx/js"))
                {
                    if (!String.IsNullOrEmpty(pname) && pname.Length > 5)
                    {
                        pname = pname.Substring(0, pname.Length - 5);
                    }

                    if (Regex.IsMatch(pname, @"^\d+$"))
                    {
                        context.RewritePath(
                            string.Format(
                                "~/default.aspx?pageid={0}&{1}", pname, context.Request.ServerVariables["QUERY_STRING"]));
                    }
                }
            }

            // 1st Check: is it a dangerously malformed request?
            #region
            // Important patch http://support.microsoft.com/?kbid=887459
            if (context.Request.Path.IndexOf('\\') >= 0 ||
                Path.GetFullPath(context.Request.PhysicalPath) != context.Request.PhysicalPath)
            {
                throw new AppleseedRedirect(LogLevel.Warn, HttpStatusCode.NotFound, "Malformed request", null);
            }

            #endregion

            // 2nd Check: is the AllPortals Lock switched on?
            // let the user through if client IP address is in LockExceptions list, otherwise throw...
            #region
            if (Config.LockAllPortals)
            {
                var rawUrl       = context.Request.RawUrl.ToLower(CultureInfo.InvariantCulture);
                var lockRedirect = Config.LockRedirect;
                if (!rawUrl.EndsWith(lockRedirect))
                {
                    // construct IPList
                    var lockKeyHolders = Config.LockKeyHolders.Split(new[] { ';' });
                    var ipList         = new IPList();
                    foreach (var lockKeyHolder in lockKeyHolders)
                    {
                        if (lockKeyHolder.IndexOf("-") > -1)
                        {
                            ipList.AddRange(
                                lockKeyHolder.Substring(0, lockKeyHolder.IndexOf("-")),
                                lockKeyHolder.Substring(lockKeyHolder.IndexOf("-") + 1));
                        }
                        else
                        {
                            ipList.Add(lockKeyHolder);
                        }
                    }

                    // check if requestor's IP address is in allowed list
                    if (!ipList.CheckNumber(context.Request.UserHostAddress))
                    {
                        throw new PortalsLockedException();
                    }
                }
            }
            #endregion

            // 3rd Check: is database/code version correct?
            var requestUri      = context.Request.Url;
            var requestPath     = requestUri.AbsolutePath.ToLower(CultureInfo.InvariantCulture);
            var returnToRequest = CheckAndUpdateDB(context, requestPath);


            if (returnToRequest)
            {
                return;
            }

            // Get portalsettings and add both key "PortalSettings","PortalID" into the Context.Item if not exisit
            // All neccessory checks and oprations are managed by this method
            //[email protected] - 2014/12/16 - Get portalsettings by pageid and portal id
            PortalSettings portalSettings = PortalSettings.GetPortalSettingsbyPageID(Portal.PageID, Portal.UniqueID);

            Membership.Provider.ApplicationName     = portalSettings.PortalAlias;
            ProfileManager.Provider.ApplicationName = portalSettings.PortalAlias;
            Roles.ApplicationName = portalSettings.PortalAlias;

            var smartErrorRedirect = Config.SmartErrorRedirect;
            if (smartErrorRedirect.StartsWith("~/"))
            {
                smartErrorRedirect = smartErrorRedirect.TrimStart(new[] { '~' });
            }

            if (requestPath.EndsWith(smartErrorRedirect.ToLower(CultureInfo.InvariantCulture)))
            {
                return; // this is SmartError page... so continue
            }

            // WLF: This was backwards before so it would always set refreshSite true because the cookie was changed before it was checked.
            // WLF: REVIEW: This whole section needs a code review.
            // Try to get alias from cookie to determine if alias has been changed
            var refreshSite       = false;
            var portalAliasCookie = context.Request.Cookies["PortalAlias"];
            if (portalAliasCookie != null && portalAliasCookie.Value.ToLower() != Portal.UniqueID)
            {
                refreshSite = true; // Portal has changed since last page request
            }

            if (portalSettings != null)
            {
                portalAliasCookie = new HttpCookie("PortalAlias")
                {
                    Path = "/", Value = portalSettings.PortalAlias
                };
                if (context.Response.Cookies["PortalAlias"] == null)
                {
                    context.Response.Cookies.Add(portalAliasCookie);
                }
                else
                {
                    context.Response.Cookies.Set(portalAliasCookie);
                }
            }

            // if switching portals then clean parameters [TipTopWeb]
            // Must be the last instruction in this method
            var refreshedCookie = context.Request.Cookies["refreshed"];

            // 5/7/2006 Ed Daniel
            // Added hack for Http 302 by extending condition below to check for more than 3 cookies
            if (refreshSite && context.Request.Cookies.Keys.Count > 3)
            {
                // Sign out and force the browser to refresh only once to avoid any dead-lock
                if (refreshedCookie == null || refreshedCookie.Value == "false")
                {
                    var rawUrl             = context.Request.RawUrl;
                    var newRefreshedCookie = new HttpCookie("refreshed", "true")
                    {
                        Path    = "/",
                        Expires = DateTime.Now.AddMinutes(1)
                    };
                    if (refreshedCookie == null)
                    {
                        context.Response.Cookies.Add(newRefreshedCookie);
                    }
                    else
                    {
                        context.Response.Cookies.Set(newRefreshedCookie);
                    }

                    var msg =
                        string.Format(
                            "User logged out on global.asax line 423. Values -> refreshsite: {0}, context.Request.Cookies.Keys.count: {1}, rawurl: {2}",
                            refreshSite,
                            context.Request.Cookies.Keys.Count,
                            rawUrl);

                    ErrorHandler.Publish(
                        LogLevel.Warn,
                        msg);

                    // sign-out, if refreshed parameter on the command line we will not call it again
                    PortalSecurity.SignOut(rawUrl, false);
                }
            }

            // invalidate cookie, so the page can be refreshed when needed
            refreshedCookie = context.Request.Cookies["refreshed"];
            if (refreshedCookie != null && context.Request.Cookies.Keys.Count > 3)
            {
                var newRefreshedCookie = new HttpCookie("refreshed", "false")
                {
                    Path    = "/",
                    Expires = DateTime.Now.AddMinutes(1)
                };
                context.Response.Cookies.Set(newRefreshedCookie);
            }

            // This is done in order to allow the sitemap to reference a page that is outside this website.
            var targetPage = this.Request.Params["sitemapTargetPage"];
            if (!string.IsNullOrEmpty(targetPage))
            {
                int mvcPageId;
                if (int.TryParse(targetPage, out mvcPageId))
                {
                    var url = HttpUrlBuilder.BuildUrl(mvcPageId);
                    this.Response.Redirect(url);
                }
            }
        }
Beispiel #5
0
 public static void CreateTestList()
 {
     iplist = new IPList();
     iplist.AddRange("192.168.0.1", "192.168.0.156");
 }
Beispiel #6
0
        /// <summary>
        /// Handles the BeginRequest event of the Application control.
        /// The Application_BeginRequest method is an ASP.NET event that executes
        /// on each web request into the portal application.  The below method
        /// obtains the current pageIndex and PageID from the querystring of the
        /// request -- and then obtains the configuration necessary to process
        /// and render the request.
        /// This portal configuration is stored within the application's "Context"
        /// object -- which is available to all pages, controls and components
        /// during the processing of a single request.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            Reader      contextReader = new Reader(new WebContextReader());
            HttpContext context       = contextReader.Current;

            // TODO: Move all URL handling to URLHandler.cs in core
            // TODO: Need to support page name with no id, search db for match
            // TODO: If not, return page with recomended matches..

            /*
             * QUERY FOR MATCHERS
             *          int pageID = Portal.PageID; // Get PageID from QueryString
             *                      string portalAlias = Portal.UniqueID;
             * Portal alias =
             * page name = currentURL.Substring(currentURL.LastIndexOf("/") + 1)
             * DECLARE @portalAlias varchar(20)
             * DECLARE @PageName varchar(20)
             *
             * SET @portalAlias = 'rainbow'
             * SET @PageName = 'Manage'
             *
             * SELECT     rb_Tabs.TabID, rb_Tabs.TabName
             * FROM         rb_Portals INNER JOIN
             *        rb_Tabs ON rb_Portals.PortalID = rb_Tabs.PortalID
             * WHERE     (rb_Portals.PortalAlias LIKE '%' + @portalAlias + '%') AND (rb_Tabs.TabName LIKE N'%' + @PageName + N'%')
             */
            string currentURL = context.Request.Path.ToLower();


#if DEBUG
            if (currentURL.Contains("trace.axd"))
            {
                return;
            }
#endif
            context.Trace.Warn("Application_BeginRequest :: " + currentURL);
            if (Portal.PageID > 0)
            {
                //Creates the physical path on the server
                string physicalPath = context.Server.MapPath(currentURL.Substring(currentURL.LastIndexOf("/") + 1));

                // TODO: Can we enhance performance here by checking to see if it is a friedly url page
                // name instead of doing an IO check for exists?
                // checks to see if the file does not exsists.
                if (!File.Exists(physicalPath)) // Rewrites the path
                {
                    context.RewritePath("~/default.aspx?" + context.Request.ServerVariables["QUERY_STRING"]);
                }
            }
            else
            {
                string pname = currentURL.Substring(currentURL.LastIndexOf("/") + 1);
                pname = pname.Substring(0, (pname.Length - 5));
                if (Regex.IsMatch(pname, @"^\d+$"))
                {
                    context.RewritePath("~/default.aspx?pageid=" + pname +
                                        context.Request.ServerVariables["QUERY_STRING"]);
                }
            }


            // 1st Check: is it a dangerously malformed request?
            //Important patch http://support.microsoft.com/?kbid=887459
            if (context.Request.Path.IndexOf('\\') >= 0 ||
                Path.GetFullPath(context.Request.PhysicalPath) != context.Request.PhysicalPath)
            {
                throw new RainbowRedirect(LogLevel.Warn, HttpStatusCode.NotFound, "Malformed request", null);
            }

            #region 2nd Check: is the AllPortals Lock switched on?

            // 2nd Check: is the AllPortals Lock switched on?
            // let the user through if client IP address is in LockExceptions list, otherwise throw...
            if (Config.LockAllPortals)
            {
                string _rawUrl       = context.Request.RawUrl.ToLower(CultureInfo.InvariantCulture);
                string _lockRedirect = Config.LockRedirect;
                if (!_rawUrl.EndsWith(_lockRedirect))
                {
                    // construct IPList
                    string[] lockKeyHolders = Config.LockKeyHolders.Split(new char[] { ';' });
                    IPList   ipList         = new IPList();
                    foreach (string lockKeyHolder in lockKeyHolders)
                    {
                        if (lockKeyHolder.IndexOf("-") > -1)
                        {
                            ipList.AddRange(lockKeyHolder.Substring(0, lockKeyHolder.IndexOf("-")),
                                            lockKeyHolder.Substring(lockKeyHolder.IndexOf("-") + 1));
                        }
                        else
                        {
                            ipList.Add(lockKeyHolder);
                        }
                    }
                    // check if requestor's IP address is in allowed list
                    if (!ipList.CheckNumber(context.Request.UserHostAddress))
                    {
                        throw new PortalsLockedException();
                    }
                }
            }

            #endregion

            #region 3rd Check: is database/code version correct?

            // 3rd Check: is database/code version correct?
            // don't check database when installer is running
            if (Request.AppRelativeCurrentExecutionFilePath.ToLower() != Config.InstallerRedirect.ToLower() &&
                Request.AppRelativeCurrentExecutionFilePath.ToLower() != "~/webresource.axd")
            {
                int versionDelta = Database.DatabaseVersion.CompareTo(Portal.CodeVersion);
                // if DB and code versions do not match
                if (versionDelta != 0)
                {
                    Uri    _requestUri             = context.Request.Url;
                    string _databaseUpdateRedirect = Config.DatabaseUpdateRedirect;
                    if (_databaseUpdateRedirect.StartsWith("~/"))
                    {
                        _databaseUpdateRedirect = _databaseUpdateRedirect.TrimStart(new char[] { '~' });
                    }

                    if (
                        !
                        _requestUri.AbsolutePath.ToLower(CultureInfo.InvariantCulture).EndsWith(
                            _databaseUpdateRedirect.ToLower(CultureInfo.InvariantCulture)))
                    {
                        // ...and this is not DB Update page
                        string errorMessage = "Database version: " + Database.DatabaseVersion.ToString() + " Code version: " +
                                              Portal.CodeVersion.ToString();
                        if (versionDelta < 0) // DB Version is behind Code Version
                        {
                            // Jonathan : WHy wouldnt we redirect to update page?
                            // TODO : Check with people why this was like this....
                            Response.Redirect(Framework.Settings.Path.ApplicationRoot + _databaseUpdateRedirect, true);
                            // so update?
                            ErrorHandler.Publish(LogLevel.Warn, errorMessage);
                            // throw new DatabaseVersionException(errorMessage);
                        }
                        else // DB version is ahead of Code Version
                        {
                            ErrorHandler.Publish(LogLevel.Warn, errorMessage);
                            // Jonathan : WHy wouldnt we redirect to update page?
                            // TODO : Check with people why this was like this....
                            // Who cares ?
                            // throw new CodeVersionException(errorMessage);
                        }
                    }
                    else // this is already DB Update page...
                    {
                        return; // so skip creation of PortalSettings
                    }
                }

                #endregion

                // ************ 'calculate' response to this request ************
                //
                // Test 1 - try requested Alias and requested PageID
                // Test 2 - try requested Alias and PageID 0
                // Test 3 - try default Alias and requested PageID
                // Test 4 - try default Alias and PageID 0
                //
                // The UrlToleranceLevel determines how many times the test is allowed to fail before the request is considered
                // to be "an error" and is therefore redirected:
                //
                // UrlToleranceLevel 1
                //		- requested Alias must be valid - if invalid, InvalidAliasRedirect page on default portal will be shown
                //		- if requested PageID is found, it is shown
                //		- if requested PageID is not found, InvalidPageIdRedirect page is shown
                //
                // UrlToleranceLevel 2
                //		- requested Alias must be valid - if invalid, InvalidAliasRedirect page on default portal will be shown
                //		- if requested PageID is found, it is shown
                //		- if requested PageID is not found, PageID 0 (Home page) is shown
                //
                // UrlToleranceLevel 3 - <<<<<< not working?
                //		- if requested Alias is invalid, default Alias will be used
                //		- if requested PageID is found, it is shown
                //		- if requested PageID is not found, InvalidPageIdRedirect page is shown
                //
                // UrlToleranceLevel 4 -
                //		- if requested Alias is invalid, default Alias will be used
                //		- if requested PageID is found, it is shown
                //		- if requested PageID is not found, PageID 0 (Home page) is shown

                PortalSettings portalSettings = null;
                int            pageID         = Portal.PageID;        // Get PageID from QueryString
                string         portalAlias    = Portal.UniqueID;      // Get requested alias from querystring, cookies or hostname
                string         defaultAlias   = Config.DefaultPortal; // get default portal from config

                // load arrays with values to test
                string[] testAlias = new string[4] {
                    portalAlias, portalAlias, defaultAlias, defaultAlias
                };
                int[] testPageID = new int[4] {
                    pageID, 0, pageID, 0
                };

                int testsAllowed = Config.UrlToleranceLevel;
                int testsToRun   = testsAllowed > 2 ? 4 : 2;
                // if requested alias is default alias, limit UrlToleranceLevel to max value of 2 and limit tests to 2
                if (portalAlias == defaultAlias)
                {
                    testsAllowed = testsAllowed % 2;
                    testsToRun   = 2;
                }

                int testsCounter = 1;
                while (testsCounter <= testsToRun)
                {
                    //try with current values from arrays
                    portalSettings = new PortalSettings(testPageID[testsCounter - 1], testAlias[testsCounter - 1]);

                    // test returned result
                    if (portalSettings.PortalAlias != null)
                    {
                        break; // successful hit
                    }
                    else
                    {
                        testsCounter++; // increment the test counter and continue
                    }
                }

                if (portalSettings.PortalAlias == null)
                {
                    // critical error - neither requested alias nor default alias could be found in DB
                    throw new RainbowRedirect(
                              Config.NoPortalErrorRedirect,
                              LogLevel.Fatal,
                              Config.NoPortalErrorResponse,
                              "Unable to load any portal - redirecting request to ErrorNoPortal page.",
                              null);
                }

                if (testsCounter <= testsAllowed) // success
                {
                    // Portal Settings has passed the test so add it to Context
                    context.Items.Add("PortalSettings", portalSettings);
                    context.Items.Add("PortalID", portalSettings.PortalID); // jes1111
                }
                else // need to redirect
                {
                    if (portalSettings.PortalAlias != portalAlias) // we didn't get the portal we asked for
                    {
                        throw new RainbowRedirect(
                                  Config.InvalidAliasRedirect,
                                  LogLevel.Info,
                                  HttpStatusCode.NotFound,
                                  "Invalid Alias specified in request URL - redirecting (404) to InvalidAliasRedirect page.",
                                  null);
                    }

                    if (portalSettings.ActivePage.PageID != pageID) // we didn't get the page we asked for
                    {
                        throw new RainbowRedirect(
                                  Config.InvalidPageIdRedirect,
                                  LogLevel.Info,
                                  HttpStatusCode.NotFound,
                                  "Invalid PageID specified in request URL - redirecting (404) to InvalidPageIdRedirect page.",
                                  null);
                    }
                }

                // Save cookies
                //saveCookie = true; // Jes1111 - why is this always set to true? is it needed?
                //ExtendCookie(settings);
                //if (saveCookie) // Jes1111 - why is this always set to true? is it needed?
                //{
                context.Response.Cookies["PortalAlias"].Path  = "/";
                context.Response.Cookies["PortalAlias"].Value = portalSettings.PortalAlias;
                //}

                //Try to get alias from cookie to determine if alias has been changed
                bool refreshSite = false;
                if (context.Request.Cookies["PortalAlias"] != null &&
                    context.Request.Cookies["PortalAlias"].Value.ToLower() != Portal.UniqueID)
                {
                    refreshSite = true; //Portal has changed since last page request
                }
                // if switching portals then clean parameters [TipTopWeb]
                // Must be the last instruction in this method

                // 5/7/2006 Ed Daniel
                // Added hack for Http 302 by extending condition below to check for more than 3 cookies
                if (refreshSite && context.Request.Cookies.Keys.Count > 3)
                {
                    // Signout and force the browser to refresh only once to avoid any dead-lock
                    if (context.Request.Cookies["refreshed"] == null ||
                        (context.Request.Cookies["refreshed"] != null &&
                         context.Response.Cookies["refreshed"].Value == "false"))
                    {
                        string rawUrl = context.Request.RawUrl;

                        // jes1111 - not needed now
                        //					//by Manu avoid endless loop when portal does not exists
                        //					if (rawUrl.EndsWith("init")) // jes1111: is this still valid/needed?
                        //						context.Response.Redirect("~/app_support/ErrorNoPortal.html", true);
                        //
                        //					// add parameter at the end of the command line to detect the dead-lock
                        //					if (rawUrl.LastIndexOf(@"?") > 0)
                        //						rawUrl += "&init";
                        //					else rawUrl += "?init";

                        context.Response.Cookies["refreshed"].Value   = "true";
                        context.Response.Cookies["refreshed"].Path    = "/";
                        context.Response.Cookies["refreshed"].Expires = DateTime.Now.AddMinutes(1);

                        // sign-out, if refreshed param on the command line we will not call it again
                        PortalSecurity.SignOut(rawUrl, false);
                    }
                }

                // invalidate cookie, so the page can be refreshed when needed
                if (context.Request.Cookies["refreshed"] != null && context.Request.Cookies.Keys.Count > 3)
                {
                    context.Response.Cookies["refreshed"].Path    = "/";
                    context.Response.Cookies["refreshed"].Value   = "false";
                    context.Response.Cookies["refreshed"].Expires = DateTime.Now.AddMinutes(1);
                }
            }
        } // end of Application_BeginRequest