Exemple #1
0
    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            // Set form action to pass XSS test
            form1.Action = "/";

            // try to get site's 404 page
            var       host = WebRequestHelper.GetHostNameFromRequest(HttpContext.Current);
            SiteCache site = SiteCache.GetSiteByDomain(host);
            if (site != null && site.PageNotFoundPageId.HasValue)
            {
                site.RedirectToPageNotFoundPage();
            }
            else
            {
                Response.StatusCode = 404;
                lLogoSvg.Text       = System.IO.File.ReadAllText(HttpContext.Current.Request.MapPath("~/Assets/Images/rock-logo-sm.svg"));
            }
        }
        catch
        {
            Response.StatusCode = 404;
            lLogoSvg.Text       = System.IO.File.ReadAllText(HttpContext.Current.Request.MapPath("~/Assets/Images/rock-logo-sm.svg"));
        }
    }
Exemple #2
0
        /// <summary>
        /// Handles the Click event of the btnLoadBlockTypesAndPages control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnLoadBlockTypesAndPages_Click(object sender, EventArgs e)
        {
            var rockContext = new RockContext();

            // ensure update attributes is called on every blocktype
            foreach (var blockType in new BlockTypeService(rockContext).Queryable().AsNoTracking().ToList())
            {
                System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();
                var blockTypeCache = BlockTypeCache.Get(blockType.Guid);
                if (!blockTypeCache.IsInstancePropertiesVerified)
                {
                    try
                    {
                        var blockControl      = this.Page.LoadControl(blockTypeCache.Path) as RockBlock;
                        int?blockEntityTypeId = EntityTypeCache.Get(typeof(Block)).Id;
                        Rock.Attribute.Helper.UpdateAttributes(blockControl.GetType(), blockEntityTypeId, "BlockTypeId", blockType.Id.ToString(), rockContext);
                        blockTypeCache.MarkInstancePropertiesVerified(true);
                        System.Diagnostics.Debug.WriteLine(string.Format("[{1}ms] BlockType {0}", blockTypeCache.Path, stopwatch.Elapsed.TotalMilliseconds));
                    }
                    catch (Exception ex)
                    {
                        ExceptionLogService.LogException(ex);
                    }
                }

                stopwatch.Stop();
            }

            foreach (var page in new PageService(rockContext).Queryable())
            {
                string url = string.Empty;
                try
                {
                    System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();
                    var proxySafeUri = Request.UrlProxySafe();
                    url = $"{proxySafeUri.Scheme}://{WebRequestHelper.GetHostNameFromRequest( HttpContext.Current )}:{proxySafeUri.Port}{ResolveRockUrl( new PageReference( page.Id ).BuildUrl() )}";

                    //url = string.Format( "http{0}://{1}:{2}{3}",
                    //    ( Request.IsSecureConnection ) ? "s" : "",
                    //    WebRequestHelper.GetHostNameFromRequest( HttpContext.Current ),
                    //    Request.UrlProxySafe().Port,
                    //    ResolveRockUrl( new PageReference( page.Id ).BuildUrl() ) );

                    WebRequest request = WebRequest.Create(url);
                    request.Timeout = 10000;
                    WebResponse response = request.GetResponse();
                    stopwatch.Stop();
                    System.Diagnostics.Debug.WriteLine(string.Format("[{2}ms] Loaded {0} {1} ", page.InternalName, url, stopwatch.Elapsed.TotalMilliseconds));
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("Exception Loading {0} {1}, {2}", page.InternalName, url, ex));
                }
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            request  = context.Request;
            response = context.Response;

            RockContext rockContext = new RockContext();

            if (request.HttpMethod != "GET" && request.HttpMethod != "HEAD")
            {
                response.TrySkipIisCustomErrors = true;
                response.StatusCode             = 405;
                response.Headers.Add("Allow", "GET");
                response.Write("Invalid request method.");
                return;
            }

            if (request.QueryString["ChannelId"] == null)
            {
                response.TrySkipIisCustomErrors = true;
                response.StatusCode             = 400;
                response.Write("A ChannelId is required.");
                return;
            }

            int?channelId = request.QueryString["ChannelId"].AsIntegerOrNull();

            if (channelId == null)
            {
                response.TrySkipIisCustomErrors = true;
                response.StatusCode             = 400;
                response.Write("Invalid channel id.");
                return;
            }

            ContentChannel channel = new ContentChannelService(rockContext).Queryable("ContentChannelType").FirstOrDefault(c => c.Id == channelId.Value);

            if (channel == null)
            {
                response.TrySkipIisCustomErrors = true;
                response.StatusCode             = 404;
                response.Write("Channel does not exist.");
                return;
            }

            if (!channel.EnableRss)
            {
                response.TrySkipIisCustomErrors = true;
                response.StatusCode             = 403;
                response.Write("RSS is not enabled for this channel.");
                return;
            }

            DefinedValueCache dvRssTemplate = null;

            if (request.QueryString["TemplateId"] != null)
            {
                int?templateDefinedValueId = request.QueryString["TemplateId"].AsIntegerOrNull();

                if (templateDefinedValueId == null)
                {
                    response.TrySkipIisCustomErrors = true;
                    response.StatusCode             = 400;
                    response.Write("Invalid template id.");
                    return;
                }

                dvRssTemplate = DefinedValueCache.Get(templateDefinedValueId.Value);
            }

            if (dvRssTemplate == null)
            {
                dvRssTemplate = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.DEFAULT_RSS_CHANNEL);
            }

            if (dvRssTemplate.DefinedType.Guid != new Guid(Rock.SystemGuid.DefinedType.LAVA_TEMPLATES))
            {
                response.TrySkipIisCustomErrors = true;
                response.StatusCode             = 400;
                response.Write("Invalid template id.");
                return;
            }

            string rssTemplate = dvRssTemplate.GetAttributeValue("Template");

            if (string.IsNullOrWhiteSpace(dvRssTemplate.GetAttributeValue("MimeType")))
            {
                response.ContentType = "application/rss+xml";
            }
            else
            {
                response.ContentType = dvRssTemplate.GetAttributeValue("MimeType");
            }

            if (request.HttpMethod == "HEAD")
            {
                response.StatusCode = 200;
                return;
            }

            // load merge fields
            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);

            mergeFields.Add("Channel", channel);

            Dictionary <string, object> requestObjects = new Dictionary <string, object>();

            requestObjects.Add("Scheme", request.Url.Scheme);
            requestObjects.Add("Host", WebRequestHelper.GetHostNameFromRequest(context));
            requestObjects.Add("Authority", request.Url.Authority);
            requestObjects.Add("LocalPath", request.Url.LocalPath);
            requestObjects.Add("AbsoluteUri", request.Url.AbsoluteUri);
            requestObjects.Add("AbsolutePath", request.Url.AbsolutePath);
            requestObjects.Add("Port", request.Url.Port);
            requestObjects.Add("Query", request.Url.Query);
            requestObjects.Add("OriginalString", request.Url.OriginalString);

            mergeFields.Add("Request", requestObjects);

            // check for new rss item limit
            if (request.QueryString["Count"] != null)
            {
                int.TryParse(request.QueryString["Count"], out rssItemLimit);
            }

            // get channel items
            ContentChannelItemService contentService = new ContentChannelItemService(rockContext);

            var content = contentService.Queryable("ContentChannelType")
                          .Where(c =>
                                 c.ContentChannelId == channel.Id &&
                                 (c.Status == ContentChannelItemStatus.Approved || c.ContentChannel.ContentChannelType.DisableStatus || c.ContentChannel.RequiresApproval == false) &&
                                 c.StartDateTime <= RockDateTime.Now);

            if (channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange)
            {
                if (channel.ContentChannelType.IncludeTime)
                {
                    content = content.Where(c => !c.ExpireDateTime.HasValue || c.ExpireDateTime >= RockDateTime.Now);
                }
                else
                {
                    content = content.Where(c => !c.ExpireDateTime.HasValue || c.ExpireDateTime > RockDateTime.Today);
                }
            }

            if (channel.ItemsManuallyOrdered)
            {
                content = content.OrderBy(c => c.Order);
            }
            else
            {
                content = content.OrderByDescending(c => c.StartDateTime);
            }

            content = content.Take(rssItemLimit);

            content.LoadAttributes();

            foreach (var item in content)
            {
                item.Content = item.Content.ResolveMergeFields(mergeFields);

                // resolve any relative links
                var    globalAttributes = GlobalAttributesCache.Get();
                string publicAppRoot    = globalAttributes.GetValue("PublicApplicationRoot").EnsureTrailingForwardslash();
                item.Content = item.Content.Replace(@" src=""/", @" src=""" + publicAppRoot);
                item.Content = item.Content.Replace(@" href=""/", @" href=""" + publicAppRoot);

                // get item attributes and add them as elements to the feed
                foreach (var attributeValue in item.AttributeValues)
                {
                    attributeValue.Value.Value = attributeValue.Value.Value.ResolveMergeFields(mergeFields);
                }
            }

            mergeFields.Add("Items", content);

            mergeFields.Add("RockVersion", Rock.VersionInfo.VersionInfo.GetRockProductVersionNumber());

            response.Write(rssTemplate.ResolveMergeFields(mergeFields));
        }
Exemple #4
0
        /// <summary>
        /// Determine the logical page being requested by evaluating the routedata, or querystring and
        /// then loading the appropriate layout (ASPX) page
        ///
        /// Pick url on the following priority order:
        /// 1. PageId
        /// 2. Route match and site match
        /// 3. ShortLink match and site match
        /// 4. Route and no site match
        /// 5. ShortLink with no site match
        /// 6. If there is no routing info in the request then set to default page
        /// 7. 404 if route does not exist
        ///
        /// </summary>
        /// <param name="requestContext"></param>
        /// <returns></returns>
        System.Web.IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
        {
            string pageId      = string.Empty;
            int    routeId     = 0;
            bool   isSiteMatch = false;
            Dictionary <string, string> parms;
            string          host;
            HttpRequestBase routeHttpRequest;
            HttpCookie      siteCookie;

            // Context cannot be null
            if (requestContext == null)
            {
                throw new ArgumentNullException("requestContext");
            }

            try
            {
                routeHttpRequest = requestContext.HttpContext.Request;
                siteCookie       = routeHttpRequest.Cookies["last_site"];
                parms            = new Dictionary <string, string>();
                host             = WebRequestHelper.GetHostNameFromRequest(HttpContext.Current);

                if (requestContext.RouteData.Values["PageId"] != null)
                {
                    // Pages using the default routing URL will have the page id in the RouteData.Values collection
                    pageId      = ( string )requestContext.RouteData.Values["PageId"];
                    isSiteMatch = true;
                }
                else if (requestContext.RouteData.DataTokens["PageRoutes"] != null)
                {
                    SiteCache site = GetSite(routeHttpRequest, host, siteCookie);
                    // Pages that use a custom URL route will have the page id in the RouteData.DataTokens collection
                    GetPageIdFromDataTokens(requestContext, site, out pageId, out routeId, out isSiteMatch);

                    foreach (var routeParm in requestContext.RouteData.Values)
                    {
                        parms.Add(routeParm.Key, ( string )routeParm.Value);
                    }
                }
                else if (((System.Web.Routing.Route)requestContext.RouteData.Route).Url.IsNullOrWhiteSpace())
                {
                    // if we don't have routing info then set the page ID to the default page for the site.

                    // Get the site, if not found use the default site
                    SiteCache site = GetSite(routeHttpRequest, host, siteCookie);
                    if (site == null)
                    {
                        site = SiteCache.Get(SystemGuid.Site.SITE_ROCK_INTERNAL.AsGuid());
                    }

                    if (site.DefaultPageId.HasValue)
                    {
                        pageId      = site.DefaultPageId.Value.ToString();
                        isSiteMatch = true;
                    }
                    else
                    {
                        throw new SystemException("Invalid Site Configuration");
                    }
                }

                // If the the page ID and site has not yet been matched
                if (string.IsNullOrEmpty(pageId) || !isSiteMatch)
                {
                    SiteCache site = GetSite(routeHttpRequest, host, siteCookie);

                    // if not found use the default site
                    if (site == null)
                    {
                        site = SiteCache.Get(SystemGuid.Site.SITE_ROCK_INTERNAL.AsGuid());
                    }

                    if (site != null)
                    {
                        // Check to see if this is a short link route
                        string shortlink = null;
                        if (requestContext.RouteData.Values.ContainsKey("shortlink"))
                        {
                            shortlink = requestContext.RouteData.Values["shortlink"].ToString();
                        }

                        // If shortlink have the same name as route and route's site did not match, then check if shortlink site match.
                        if (shortlink.IsNullOrWhiteSpace() && requestContext.RouteData.DataTokens["RouteName"] != null)
                        {
                            shortlink = requestContext.RouteData.DataTokens["RouteName"].ToString();
                        }

                        if (shortlink.IsNotNullOrWhiteSpace())
                        {
                            using (var rockContext = new Rock.Data.RockContext())
                            {
                                var pageShortLink = new PageShortLinkService(rockContext).GetByToken(shortlink, site.Id);

                                if (pageShortLink != null && (pageShortLink.SiteId == site.Id || requestContext.RouteData.DataTokens["RouteName"] == null))
                                {
                                    pageId  = string.Empty;
                                    routeId = 0;

                                    string trimmedUrl = pageShortLink.Url.RemoveCrLf().Trim();

                                    var transaction = new ShortLinkTransaction();
                                    transaction.PageShortLinkId = pageShortLink.Id;
                                    transaction.Token           = pageShortLink.Token;
                                    transaction.Url             = trimmedUrl;
                                    if (requestContext.HttpContext.User != null)
                                    {
                                        transaction.UserName = requestContext.HttpContext.User.Identity.Name;
                                    }

                                    transaction.DateViewed = RockDateTime.Now;
                                    transaction.IPAddress  = WebRequestHelper.GetClientIpAddress(routeHttpRequest);
                                    transaction.UserAgent  = routeHttpRequest.UserAgent ?? string.Empty;
                                    RockQueue.TransactionQueue.Enqueue(transaction);

                                    requestContext.HttpContext.Response.Redirect(trimmedUrl);
                                    return(null);
                                }
                            }
                        }

                        // If site has has been enabled for mobile redirect, then we'll need to check what type of device is being used
                        if (site.EnableMobileRedirect)
                        {
                            // get the device type
                            string u = routeHttpRequest.UserAgent;

                            var clientType = InteractionDeviceType.GetClientType(u);

                            bool redirect = false;

                            // first check if device is a mobile device
                            if (clientType == "Mobile")
                            {
                                redirect = true;
                            }

                            // if not, mobile device and tables should be redirected also, check if device is a tablet
                            if (!redirect && site.RedirectTablets && clientType == "Tablet")
                            {
                                redirect = true;
                            }

                            if (redirect)
                            {
                                if (site.MobilePageId.HasValue)
                                {
                                    pageId  = site.MobilePageId.Value.ToString();
                                    routeId = 0;
                                }
                                else if (!string.IsNullOrWhiteSpace(site.ExternalUrl))
                                {
                                    requestContext.HttpContext.Response.Redirect(site.ExternalUrl);
                                    return(null);
                                }
                            }
                        }
                    }
                }

                PageCache page = null;
                if (!string.IsNullOrEmpty(pageId))
                {
                    int pageIdNumber = 0;
                    if (int.TryParse(pageId, out pageIdNumber))
                    {
                        page = PageCache.Get(pageIdNumber);
                    }
                }

                if (page == null)
                {
                    // try to get site's 404 page
                    SiteCache site = GetSite(routeHttpRequest, host, siteCookie);
                    if (site != null && site.PageNotFoundPageId != null)
                    {
                        if (Convert.ToBoolean(GlobalAttributesCache.Get().GetValue("Log404AsException")))
                        {
                            Rock.Model.ExceptionLogService.LogException(
                                new Exception($"404 Error: {routeHttpRequest.Url.AbsoluteUri}"),
                                requestContext.HttpContext.ApplicationInstance.Context);
                        }

                        page = PageCache.Get(site.PageNotFoundPageId ?? 0);
                        requestContext.HttpContext.Response.StatusCode             = 404;
                        requestContext.HttpContext.Response.TrySkipIisCustomErrors = true;
                    }
                    else
                    {
                        // no 404 page found for the site, return the default 404 error page
                        return((System.Web.UI.Page)BuildManager.CreateInstanceFromVirtualPath("~/Http404Error.aspx", typeof(System.Web.UI.Page)));
                    }
                }

                CreateOrUpdateSiteCookie(siteCookie, requestContext, page);

                string theme      = page.Layout.Site.Theme;
                string layout     = page.Layout.FileName;
                string layoutPath = PageCache.FormatPath(theme, layout);

                try
                {
                    return(CreateRockPage(page, layoutPath, routeId, parms, routeHttpRequest));
                }
                catch (System.Web.HttpException)
                {
                    // The Selected theme and/or layout didn't exist so try to use the layout in the default theme.
                    theme = "Rock";

                    // Verify that Layout exists in the default theme directory and if not try use the default layout of the default theme
                    string layoutPagePath = string.Format("~/Themes/Rock/Layouts/{0}.aspx", layout);
                    if (!File.Exists(requestContext.HttpContext.Server.MapPath(layoutPagePath)))
                    {
                        layout = "FullWidth";
                    }

                    layoutPath = PageCache.FormatPath(theme, layout);

                    return(CreateRockPage(page, layoutPath, routeId, parms, routeHttpRequest));
                }
            }
            catch (Exception ex)
            {
                if (requestContext.HttpContext != null)
                {
                    requestContext.HttpContext.Cache["RockExceptionOrder"] = "66";
                    requestContext.HttpContext.Cache["RockLastException"]  = ex;
                }

                return((System.Web.UI.Page)BuildManager.CreateInstanceFromVirtualPath("~/Error.aspx", typeof(System.Web.UI.Page)));
            }
        }
Exemple #5
0
        /// <summary>
        /// Determine the logical page being requested by evaluating the routedata, or querystring and
        /// then loading the appropriate layout (ASPX) page
        ///
        /// Pick url on the following priority order:
        /// 1. PageId
        /// 2. Route match and site match
        /// 3. ShortLink match and site match
        /// 4. Route and no site match
        /// 5. ShortLink with no site match
        /// 6. If there is no routing info in the request then set to default page
        /// 7. 404 if route does not exist
        ///
        /// </summary>
        /// <param name="requestContext"></param>
        /// <returns></returns>
        System.Web.IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
        {
            string pageId      = string.Empty;
            int    routeId     = 0;
            bool   isSiteMatch = false;
            Dictionary <string, string> parms;
            string          host;
            HttpRequestBase routeHttpRequest;
            HttpCookie      siteCookie;
            SiteCache       site;

            // Context cannot be null
            if (requestContext == null)
            {
                throw new ArgumentNullException("requestContext");
            }

            try
            {
                routeHttpRequest = requestContext.HttpContext.Request;
                siteCookie       = routeHttpRequest.Cookies["last_site"];
                parms            = new Dictionary <string, string>();
                host             = WebRequestHelper.GetHostNameFromRequest(HttpContext.Current);
                site             = GetSite(host, siteCookie);

                if (requestContext.RouteData.Values["PageId"] != null)
                {
                    // Pages using the default routing URL will have the page id in the RouteData.Values collection
                    pageId = ( string )requestContext.RouteData.Values["PageId"];

                    // Does the page ID exist on the requesting site
                    isSiteMatch = IsSiteMatch(site, pageId.AsIntegerOrNull());

                    if (site != null && site.EnableExclusiveRoutes && !isSiteMatch)
                    {
                        // If the site has to match and does not then don't use the page ID. Set it to empty so the 404 can be returned.
                        pageId = string.Empty;
                    }
                    else if (!isSiteMatch)
                    {
                        // This page belongs to another site, make sure it is allowed to be loaded.
                        if (IsPageExclusiveToAnotherSite(site, pageId.AsIntegerOrNull(), null))
                        {
                            // If the page has to match the site and does not then don't use the page ID. Set it to empty so the 404 can be returned.
                            pageId = string.Empty;
                        }
                    }
                }
                else if (requestContext.RouteData.DataTokens["PageRoutes"] != null)
                {
                    // Pages that use a custom URL route will have the page id in the RouteData.DataTokens collection
                    GetPageIdFromDataTokens(requestContext, site, out pageId, out routeId, out isSiteMatch);

                    foreach (var routeParm in requestContext.RouteData.Values)
                    {
                        parms.Add(routeParm.Key, ( string )routeParm.Value);
                    }
                }
                else if (((System.Web.Routing.Route)requestContext.RouteData.Route).Url.IsNullOrWhiteSpace())
                {
                    // if we don't have routing info then set the page ID to the default page for the site.

                    // Get the site, if not found use the default site
                    if (site == null)
                    {
                        site = SiteCache.Get(SystemGuid.Site.SITE_ROCK_INTERNAL.AsGuid());
                    }

                    if (site.DefaultPageId.HasValue)
                    {
                        pageId      = site.DefaultPageId.Value.ToString();
                        isSiteMatch = true;
                    }
                    else
                    {
                        throw new SystemException("Invalid Site Configuration");
                    }
                }

                // If the the page ID and site has not yet been matched
                if (string.IsNullOrEmpty(pageId) || !isSiteMatch)
                {
                    // if not found use the default site
                    if (site == null)
                    {
                        site = SiteCache.Get(SystemGuid.Site.SITE_ROCK_INTERNAL.AsGuid());
                    }

                    // Are shortlinks enabled for this site? If so, check for a matching shortlink route.
                    if (site != null)
                    {
                        if (site.EnabledForShortening)
                        {
                            // Check to see if this is a short link route
                            string shortlink = null;
                            if (requestContext.RouteData.Values.ContainsKey("shortlink"))
                            {
                                shortlink = requestContext.RouteData.Values["shortlink"].ToString();
                            }
                            else
                            {
                                // Because we implemented shortlinks using a {shortlink} (catchall) route, it's
                                // possible the organization added a custom {catchall} route (at root level; no slashes)
                                // and it is overriding our shortlink route.  If they did, use it for a possible 'shortlink'
                                // route match.
                                if (requestContext.RouteData.DataTokens["RouteName"] != null && requestContext.RouteData.DataTokens["RouteName"].ToStringSafe().StartsWith("{"))
                                {
                                    var routeName = requestContext.RouteData.DataTokens["RouteName"].ToStringSafe().Trim(new Char[] { '{', '}' });
                                    shortlink = requestContext.RouteData.Values[routeName].ToStringSafe();
                                }
                            }

                            if (shortlink.IsNullOrWhiteSpace() && requestContext.RouteData.DataTokens["RouteName"] != null)
                            {
                                shortlink = requestContext.RouteData.DataTokens["RouteName"].ToString();
                            }

                            if (shortlink.IsNotNullOrWhiteSpace())
                            {
                                using (var rockContext = new Rock.Data.RockContext())
                                {
                                    var pageShortLink = new PageShortLinkService(rockContext).GetByToken(shortlink, site.Id);

                                    // Use the short link if the site IDs match or the current site and shortlink site are not exclusive.
                                    // Note: this is only a restriction based on the site chosen as the owner of the shortlink, the acutal URL can go anywhere.
                                    if (pageShortLink != null && (pageShortLink.SiteId == site.Id || (!site.EnableExclusiveRoutes && !pageShortLink.Site.EnableExclusiveRoutes)))
                                    {
                                        if (pageShortLink.SiteId == site.Id || requestContext.RouteData.DataTokens["RouteName"] == null)
                                        {
                                            pageId  = string.Empty;
                                            routeId = 0;

                                            string trimmedUrl = pageShortLink.Url.RemoveCrLf().Trim();

                                            var transaction = new ShortLinkTransaction
                                            {
                                                PageShortLinkId = pageShortLink.Id,
                                                Token           = pageShortLink.Token,
                                                Url             = trimmedUrl,
                                                DateViewed      = RockDateTime.Now,
                                                IPAddress       = WebRequestHelper.GetClientIpAddress(routeHttpRequest),
                                                UserAgent       = routeHttpRequest.UserAgent ?? string.Empty,
                                                UserName        = requestContext.HttpContext.User?.Identity.Name
                                            };

                                            RockQueue.TransactionQueue.Enqueue(transaction);

                                            requestContext.HttpContext.Response.Redirect(trimmedUrl, false);
                                            requestContext.HttpContext.ApplicationInstance.CompleteRequest();

                                            // Global.asax.cs will throw and log an exception if null is returned, so just return a new page.
                                            return(new System.Web.UI.Page());
                                        }
                                    }
                                }
                            }
                        }

                        // If site has has been enabled for mobile redirect, then we'll need to check what type of device is being used
                        if (site.EnableMobileRedirect)
                        {
                            // get the device type
                            string u = routeHttpRequest.UserAgent;

                            var clientType = InteractionDeviceType.GetClientType(u);

                            bool redirect = false;

                            // first check if device is a mobile device
                            if (clientType == "Mobile")
                            {
                                redirect = true;
                            }

                            // if not, mobile device and tables should be redirected also, check if device is a tablet
                            if (!redirect && site.RedirectTablets && clientType == "Tablet")
                            {
                                redirect = true;
                            }

                            if (redirect)
                            {
                                if (site.MobilePageId.HasValue)
                                {
                                    pageId  = site.MobilePageId.Value.ToString();
                                    routeId = 0;
                                }
                                else if (!string.IsNullOrWhiteSpace(site.ExternalUrl))
                                {
                                    requestContext.HttpContext.Response.Redirect(site.ExternalUrl, false);
                                    requestContext.HttpContext.ApplicationInstance.CompleteRequest();

                                    // Global.asax.cs will throw and log an exception if null is returned, so just return a new page.
                                    return(new System.Web.UI.Page());
                                }
                            }
                        }
                    }
                }

                PageCache page = null;
                if (!string.IsNullOrEmpty(pageId))
                {
                    int pageIdNumber = 0;
                    if (int.TryParse(pageId, out pageIdNumber))
                    {
                        page = PageCache.Get(pageIdNumber);
                    }
                }

                if (page == null)
                {
                    // try to get site's 404 page
                    if (site != null && site.PageNotFoundPageId != null)
                    {
                        if (Convert.ToBoolean(GlobalAttributesCache.Get().GetValue("Log404AsException")))
                        {
                            Rock.Model.ExceptionLogService.LogException(
                                new Exception($"404 Error: {routeHttpRequest.Url.AbsoluteUri}"),
                                requestContext.HttpContext.ApplicationInstance.Context);
                        }

                        page = PageCache.Get(site.PageNotFoundPageId ?? 0);
                        requestContext.HttpContext.Response.StatusCode             = 404;
                        requestContext.HttpContext.Response.TrySkipIisCustomErrors = true;
                    }
                    else
                    {
                        // no 404 page found for the site, return the default 404 error page
                        return((System.Web.UI.Page)BuildManager.CreateInstanceFromVirtualPath("~/Http404Error.aspx", typeof(System.Web.UI.Page)));
                    }
                }

                CreateOrUpdateSiteCookie(siteCookie, requestContext, page);

                string theme      = page.Layout.Site.Theme;
                string layout     = page.Layout.FileName;
                string layoutPath = PageCache.FormatPath(theme, layout);

                try
                {
                    return(CreateRockPage(page, layoutPath, routeId, parms, routeHttpRequest));
                }
                catch (System.Web.HttpException)
                {
                    // The Selected theme and/or layout didn't exist so try to use the layout in the default theme.
                    theme = "Rock";

                    // Verify that Layout exists in the default theme directory and if not try use the default layout of the default theme
                    string layoutPagePath = string.Format("~/Themes/Rock/Layouts/{0}.aspx", layout);
                    if (!File.Exists(requestContext.HttpContext.Server.MapPath(layoutPagePath)))
                    {
                        layout = "FullWidth";
                    }

                    layoutPath = PageCache.FormatPath(theme, layout);

                    return(CreateRockPage(page, layoutPath, routeId, parms, routeHttpRequest));
                }
            }
            catch (Exception ex)
            {
                if (requestContext.HttpContext != null)
                {
                    requestContext.HttpContext.Cache["RockExceptionOrder"] = "66";
                    requestContext.HttpContext.Cache["RockLastException"]  = ex;
                }

                return((System.Web.UI.Page)BuildManager.CreateInstanceFromVirtualPath("~/Error.aspx", typeof(System.Web.UI.Page)));
            }
        }
 private SiteCache GetSiteByDomainName(RequestContext requestContext)
 {
     return(SiteCache.GetSiteByDomain(WebRequestHelper.GetHostNameFromRequest(HttpContext.Current)));
 }