Пример #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"));
        }
    }
        public static async Task <ValidationResponse> ValidateAsync(LoginModel login, Cache cache)
        {
            try
            {
                var client = new SigRClient(Settings.AdminSiteUrl, Settings.STSApiKey, "SiteHub");

                var domainName = login.UserName.Split('@')[1].ToLower();

                var site = await SiteCache.GetSiteByDomain(cache, domainName);

                var cred = new STSCredential
                {
                    Domain       = site.OnPremDomainName,
                    UserName     = login.UserName,
                    Password     = login.Password,
                    RemoteSiteId = site.Id
                };

                await client.StartAsync();

                ValidationResponse res = await client.ProcessSTSValidationRequest(cred);

                return(res);
            }
            catch (Exception ex)
            {
                Utils.AddLogEntry("Error during user validation", System.Diagnostics.EventLogEntryType.Error, 0, ex);
                return(new ValidationResponse
                {
                    IsValid = false
                });
            }
        }
Пример #3
0
        /// <summary>
        /// Gets the site from the site cache in the following order:
        /// 1. check the query string and try to get the site
        /// 2. Get the site using the domain of the current request
        /// 3. Get the last site from the site cookie
        /// </summary>
        /// <returns></returns>
        private SiteCache GetSite(HttpContext context)
        {
            SiteCache site       = null;
            string    siteCookie = context.Request.Cookies[SITE_COOKIE_NAME];
            string    host       = context.Request.Host.Host;

            // First check to see if site was specified in querystring
            int?siteId = context.Request.Query["SiteId"].ToString().AsIntegerOrNull();

            if (siteId.HasValue)
            {
                site = SiteCache.Get(siteId.Value);
            }

            // Then check to see if site can be determined by domain
            if (site == null)
            {
                site = SiteCache.GetSiteByDomain(host);
            }

            // Then check the last site
            if (site == null)
            {
                if (siteCookie != null)
                {
                    site = SiteCache.Get(siteCookie.AsInteger());
                }
            }

            return(site);
        }
Пример #4
0
        /// <summary>
        /// Gets the site from the site cache in the following order:
        /// 1. check the query string and try to get the site
        /// 2. Get the site using the domain of the current request
        /// 3. Get the last site from the site cookie
        /// </summary>
        /// <returns></returns>
        private SiteCache GetSite(HttpRequestBase routeHttpRequest, string host, HttpCookie siteCookie)
        {
            SiteCache site = null;

            // First check to see if site was specified in querystring
            int?siteId = routeHttpRequest.QueryString["SiteId"].AsIntegerOrNull();

            if (siteId.HasValue)
            {
                site = SiteCache.Get(siteId.Value);
            }

            // Then check to see if site can be determined by domain
            if (site == null)
            {
                site = SiteCache.GetSiteByDomain(host);
            }

            // Then check the last site
            if (site == null)
            {
                if (siteCookie != null && siteCookie.Value != null)
                {
                    site = SiteCache.Get(siteCookie.Value.AsInteger());
                }
            }

            return(site);
        }
Пример #5
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
                SiteCache site = SiteCache.GetSiteByDomain(Request.Url.Host);
                if (site != null && site.PageNotFoundPageId.HasValue)
                {
                    //site.RedirectToPageNotFoundPage();
                    PageReference redirectRef = site.PageNotFoundPageReference;

                    if (redirectRef.QueryString == null)
                    {
                        redirectRef.QueryString = new System.Collections.Specialized.NameValueCollection();
                    }
                    string orignalUrl = Request.RawUrl.IndexOf('/') == 0 ? Request.RawUrl.Substring(1) : Request.RawUrl;
                    redirectRef.QueryString.Add("originalUrl", orignalUrl);

                    Response.Redirect(redirectRef.BuildUrl(), false);
                }
                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"));
            }
        }
Пример #6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            this.RockPage.AddScriptLink(ResolveUrl("../Scripts/jquery.autocomplete.min.js"));
            this.RockPage.AddScriptLink(ResolveUrl("../Scripts/underscore.min.js"));
            this.RockPage.AddScriptLink(ResolveUrl("../Scripts/jstz.min.js"));
            this.RockPage.AddScriptLink(ResolveUrl("../Scripts/calendar.js"));
            this.RockPage.AddScriptLink(ResolveUrl("../Scripts/ServiceUEvents.js"));

            this.RockPage.AddCSSLink(ResolveUrl("../Styles/autocomplete-styles.css"));
            this.RockPage.AddCSSLink(ResolveUrl("../Styles/ServiceUEvents.css"));
            this.RockPage.AddCSSLink(ResolveUrl("../Styles/calendar.min.css"));
            var eventtitleroute = PageParameter("eventcalendarroute");

            GetCampus();

            if (!Page.IsPostBack)
            {
                //i'm filtering out those axd calls becuase they are shwoing up for some reson as a valid valud of eventcalendarroute.
                if (!string.IsNullOrEmpty(eventtitleroute) && eventtitleroute != "WebResource.axd" && eventtitleroute != "ScriptResource.axd")
                {
                    var rc = new Rock.Data.RockContext();
                    // int eventid = 0;
                    string eventId = string.Empty;
                    using ( rc )
                    {
                        eventId = rc.Database.SqlQuery <string>("exec newpointe_getEventIDbyUrl @url", new SqlParameter("url", eventtitleroute)).ToList <string>()[0];
                    }
                    if (string.IsNullOrEmpty(eventId))
                    {
                        SiteCache site = SiteCache.GetSiteByDomain(Request.Url.Host);

                        //site.RedirectToPageNotFoundPage();
                    }
                    else
                    {
                        hdnEventId.Value = eventId;
                    }
                }
                else if (!string.IsNullOrEmpty(eventtitleroute))
                {
                    //Response.Redirect( eventtitleroute );
                }

                CampusService campusService = new CampusService(new Rock.Data.RockContext());

                var qry = campusService.Queryable().Where(c => !c.Name.Contains("Central Services") && !c.Name.Contains("Online") && !c.Name.Contains("Future") && (c.IsActive ?? false)).Select(p => new { Name = p.Name.Replace("Campus", "").Trim(), ShortCode = p.ShortCode }).OrderBy(c => c.Name).ToList();

                rptCampuses.DataSource = qry;
                rptCampuses.DataBind();

                qry.Insert(0, new { Name = "ALL", ShortCode = "ALL" });
                ddlCampusDropdown.DataSource     = qry;
                ddlCampusDropdown.DataValueField = "ShortCode";
                ddlCampusDropdown.DataTextField  = "Name";
                ddlCampusDropdown.DataBind();
            }
        }
Пример #7
0
            public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
            {
                var site = SiteCache.GetSiteByDomain(httpContext.Request.Host.Host);

                if (site != null)
                {
                    return(site.Id == _siteId);
                }

                return(false);
            }
Пример #8
0
        /// <summary>
        /// Gets the site from the site cache in the following order:
        /// 1. Get the site using the domain of the current request
        /// 2. Get the last site from the site cookie
        /// </summary>
        /// <param name="host">The host.</param>
        /// <param name="siteCookie">The site cookie.</param>
        /// <returns></returns>
        private SiteCache GetSite(string host, HttpCookie siteCookie)
        {
            // Check to see if site can be determined by domain
            SiteCache site = SiteCache.GetSiteByDomain(host);

            // Then check the last site
            if (site == null && siteCookie != null && siteCookie.Value != null)
            {
                site = SiteCache.Get(siteCookie.Value.AsInteger());
            }

            return(site);
        }
Пример #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PageReference"/> class from a url.
        /// </summary>
        /// <param name="uri">The URI e.g.: new Uri( ResolveRockUrlIncludeRoot("~/Person/5")</param>
        /// <param name="applicationPath">The application path e.g.: HttpContext.Current.Request.ApplicationPath</param>
        public PageReference(Uri uri, string applicationPath)
        {
            Parameters = new Dictionary <string, string>();

            var routeInfo = new Rock.Web.RouteInfo(uri, applicationPath);

            if (routeInfo != null)
            {
                if (routeInfo.RouteData.Values["PageId"] != null)
                {
                    PageId = routeInfo.RouteData.Values["PageId"].ToString().AsInteger();
                }

                else if (routeInfo.RouteData.DataTokens["PageRoutes"] != null)
                {
                    var pages = routeInfo.RouteData.DataTokens["PageRoutes"] as List <PageAndRouteId>;
                    if (pages != null && pages.Count > 0)
                    {
                        if (pages.Count == 1)
                        {
                            var pageAndRouteId = pages.First();
                            PageId  = pageAndRouteId.PageId;
                            RouteId = pageAndRouteId.RouteId;
                        }
                        else
                        {
                            SiteCache site = SiteCache.GetSiteByDomain(uri.Host);
                            if (site != null)
                            {
                                foreach (var pageAndRouteId in pages)
                                {
                                    var pageCache = PageCache.Get(pageAndRouteId.PageId);
                                    if (pageCache != null && pageCache.Layout != null && pageCache.Layout.SiteId == site.Id)
                                    {
                                        PageId  = pageAndRouteId.PageId;
                                        RouteId = pageAndRouteId.RouteId;
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    foreach (var routeParm in routeInfo.RouteData.Values)
                    {
                        Parameters.Add(routeParm.Key, (string)routeParm.Value);
                    }
                }
            }
        }
Пример #10
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
            SiteCache site = SiteCache.GetSiteByDomain(Request.Url.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"));

                // Jeremy Weatherford [email protected]
                // use BRShortLinks table to redirect to a matching Url
                // see BRShortLinks.aspx.cs for where they come from

                string search = Request.RawUrl.ToLower();
                int    idx    = search.IndexOf("?");
                if (idx != -1)
                {
                    search = search.Substring(0, idx);            // stop at ?
                }
                var p = new Dictionary <string, object>();
                p.Add("@link", search);
                var res = DbService.ExecuteScaler("SELECT [url] FROM BRShortLinks WHERE [link]=@link",
                                                  CommandType.Text, p);
                if (res != null)
                {
                    string link = (string)res;
                    // shortlink success
                    Response.Redirect(link, false);
                    return;
                }
            }

            // really 404 -- todo, log it
            Response.Redirect("/page/504", false);
        }
        catch (Exception e2)
        {
            Response.Redirect("/page/504", false);
            //lLogoSvg.Text = e2.Message;
        }
    }
Пример #11
0
        private SiteCache GetSite(HttpRequestBase routeHttpRequest, string host, HttpCookie siteCookie)
        {
            /*
             * 2020-02-27 edrotning
             * Keeping this version of the GetSite method in case it is needed later.
             * Removed the option to use the SiteId parameter to determine what site the route belongs to.
             * The intent of the parameter was to specify a site to use if multiple Rock sites are sharing a domain and route.
             * This was removed because many blocks use the parameter name "SiteId" to specify the site the block should be using and not where the route should directed to (e.g. SiteDetails.ascx).
             * It is believed this was put into place for debugging purposes where one domain name (localhost:6229) is the norm.
             */

            SiteCache site = null;

            // First check to see if site was specified in querystring
            int?siteId = routeHttpRequest.QueryString["SiteId"].AsIntegerOrNull();

            if (siteId.HasValue)
            {
                site = SiteCache.Get(siteId.Value);
            }

            // Then check to see if site can be determined by domain
            if (site == null)
            {
                site = SiteCache.GetSiteByDomain(host);
            }

            // Then check the last site
            if (site == null)
            {
                if (siteCookie != null && siteCookie.Value != null)
                {
                    site = SiteCache.Get(siteCookie.Value.AsInteger());
                }
            }

            return(site);
        }
Пример #12
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            // Check to see if exception should be logged
            if (Convert.ToBoolean(GlobalAttributesCache.Read().GetValue("Log404AsException")))
            {
                ExceptionLogService.LogException(new Exception(string.Format("404 Error: {0}", Request.Url.AbsoluteUri)), Context);
            }

            // If this is an API call, set status code and exit
            if (Request.Url.Query.Contains(Request.Url.Authority + ResolveUrl("~/api/")))
            {
                Response.StatusCode = 404;
                Response.Flush();
                Response.End();
                return;
            }


            // try to get site's 404 page
            SiteCache site = SiteCache.GetSiteByDomain(Request.Url.Host);
            if (site != null && site.PageNotFoundPageId.HasValue)
            {
                site.RedirectToPageNotFoundPage();
            }
            else
            {
                Response.StatusCode = 404;
                logoImg.Src         = ResolveUrl("~/Assets/Images/rock-logo.svg");
            }
        }
        catch
        {
            Response.StatusCode = 404;
            logoImg.Src         = ResolveUrl("~/Assets/Images/rock-logo.svg");
        }
    }
Пример #13
0
        /// <summary>
        /// Determine the logical page being requested by evaluating the routedata, or querystring and
        /// then loading the appropriate layout (ASPX) page
        /// </summary>
        /// <param name="requestContext"></param>
        /// <returns></returns>
        System.Web.IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
        {
            if (requestContext == null)
            {
                throw new ArgumentNullException("requestContext");
            }

            try
            {
                string pageId  = "";
                int    routeId = 0;

                var parms = new Dictionary <string, string>();

                // Pages using the default routing URL will have the page id in the RouteData.Values collection
                if (requestContext.RouteData.Values["PageId"] != null)
                {
                    pageId = (string)requestContext.RouteData.Values["PageId"];
                }
                // Pages that use a custom URL route will have the page id in the RouteDate.DataTokens collection
                else if (requestContext.RouteData.DataTokens["PageId"] != null)
                {
                    pageId  = (string)requestContext.RouteData.DataTokens["PageId"];
                    routeId = Int32.Parse((string)requestContext.RouteData.DataTokens["RouteId"]);

                    foreach (var routeParm in requestContext.RouteData.Values)
                    {
                        parms.Add(routeParm.Key, (string)routeParm.Value);
                    }
                }
                // If page has not been specified get the site by the domain and use the site's default page
                else
                {
                    SiteCache site = SiteCache.GetSiteByDomain(requestContext.HttpContext.Request.Url.Host);

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

                    if (site != 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)
                        {
                            bool redirect = false;

                            // get the device type
                            string u = requestContext.HttpContext.Request.UserAgent;

                            var clientType = PageViewUserAgent.GetClientType(u);

                            // 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)
                            {
                                if (clientType == "Tablet")
                                {
                                    redirect = true;
                                }
                            }

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

                        if (string.IsNullOrWhiteSpace(pageId))
                        {
                            if (site.DefaultPageId.HasValue)
                            {
                                pageId = site.DefaultPageId.Value.ToString();
                            }

                            if (site.DefaultPageRouteId.HasValue)
                            {
                                routeId = site.DefaultPageRouteId.Value;
                            }
                        }
                    }

                    if (string.IsNullOrEmpty(pageId))
                    {
                        throw new SystemException("Invalid Site Configuration");
                    }
                }

                PageCache page = null;

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

                if (page == null)
                {
                    // try to get site's 404 page
                    SiteCache site = SiteCache.GetSiteByDomain(requestContext.HttpContext.Request.Url.Host);
                    if (site != null && site.PageNotFoundPageId != null)
                    {
                        if (Convert.ToBoolean(GlobalAttributesCache.Read().GetValue("Log404AsException")))
                        {
                            Rock.Model.ExceptionLogService.LogException(
                                new Exception(string.Format("404 Error: {0}", requestContext.HttpContext.Request.Url.AbsoluteUri)),
                                requestContext.HttpContext.ApplicationInstance.Context);
                        }

                        page = PageCache.Read(site.PageNotFoundPageId ?? 0);
                    }
                    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)));
                    }
                }

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

                try
                {
                    // Return the page for the selected theme and layout
                    Rock.Web.UI.RockPage cmsPage = (Rock.Web.UI.RockPage)BuildManager.CreateInstanceFromVirtualPath(layoutPath, typeof(Rock.Web.UI.RockPage));
                    cmsPage.SetPage(page);
                    cmsPage.PageReference = new PageReference(page.Id, routeId, parms, requestContext.HttpContext.Request.QueryString);
                    return(cmsPage);
                }
                catch (System.Web.HttpException)
                {
                    // The Selected theme and/or layout didn't exist, attempt first to use the layout in the default theme.
                    theme = "Rock";

                    // If not using the default layout, verify that Layout exists in the default theme directory
                    if (layout != "FullWidth" &&
                        !File.Exists(requestContext.HttpContext.Server.MapPath(string.Format("~/Themes/Rock/Layouts/{0}.aspx", layout))))
                    {
                        // If selected layout doesn't exist in the default theme, switch to the Default layout
                        layout = "FullWidth";
                    }

                    // Build the path to the aspx file to
                    layoutPath = PageCache.FormatPath(theme, layout);

                    // Return the default layout and/or theme
                    Rock.Web.UI.RockPage cmsPage = (Rock.Web.UI.RockPage)BuildManager.CreateInstanceFromVirtualPath(layoutPath, typeof(Rock.Web.UI.RockPage));
                    cmsPage.SetPage(page);
                    cmsPage.PageReference = new PageReference(page.Id, routeId, parms, requestContext.HttpContext.Request.QueryString);
                    return(cmsPage);
                }
            }
            catch (Exception ex)
            {
                if (requestContext.HttpContext != null)
                {
                    requestContext.HttpContext.Cache["RockExceptionOrder"] = "66";
                    requestContext.HttpContext.Cache["RockLastException"]  = ex;
                }

                System.Web.UI.Page errorPage = (System.Web.UI.Page)BuildManager.CreateInstanceFromVirtualPath("~/Error.aspx", typeof(System.Web.UI.Page));
                return(errorPage);
            }
        }
Пример #14
0
        /// <summary>
        /// Determine the logical page being requested by evaluating the routedata, or querystring and
        /// then loading the appropriate layout (ASPX) page
        /// </summary>
        /// <param name="requestContext"></param>
        /// <returns></returns>
        System.Web.IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
        {
            if (requestContext == null)
            {
                throw new ArgumentNullException("requestContext");
            }

            try
            {
                var httpRequest = requestContext.HttpContext.Request;

                var siteCookie = httpRequest.Cookies["last_site"];

                string pageId  = "";
                int    routeId = 0;

                var parms = new Dictionary <string, string>();

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

                // Pages that use a custom URL route will have the page id in the RouteDate.DataTokens collection
                else if (requestContext.RouteData.DataTokens["PageRoutes"] != null)
                {
                    var pageAndRouteIds = requestContext.RouteData.DataTokens["PageRoutes"] as List <PageAndRouteId>;
                    if (pageAndRouteIds != null && pageAndRouteIds.Count > 0)
                    {
                        // Default to first site/page
                        if (pageAndRouteIds.Count >= 1)
                        {
                            var pageAndRouteId = pageAndRouteIds.First();
                            pageId  = pageAndRouteId.PageId.ToJson();
                            routeId = pageAndRouteId.RouteId;
                        }

                        // Then check to see if any can be matched by site
                        if (pageAndRouteIds.Count > 1)
                        {
                            SiteCache site = null;

                            // First check to see if site was specified in querystring
                            int?siteId = httpRequest.QueryString["SiteId"].AsIntegerOrNull();
                            if (siteId.HasValue)
                            {
                                site = SiteCache.Read(siteId.Value);
                            }

                            // Then check to see if site can be determined by domain
                            if (site == null)
                            {
                                site = SiteCache.GetSiteByDomain(httpRequest.Url.Host);
                            }

                            // Then check the last site
                            if (site == null)
                            {
                                if (siteCookie != null && siteCookie.Value != null)
                                {
                                    site = SiteCache.Read(siteCookie.Value.AsInteger());
                                }
                            }

                            if (site != null)
                            {
                                foreach (var pageAndRouteId in pageAndRouteIds)
                                {
                                    var pageCache = PageCache.Read(pageAndRouteId.PageId);
                                    if (pageCache != null && pageCache.Layout != null && pageCache.Layout.SiteId == site.Id)
                                    {
                                        pageId  = pageAndRouteId.PageId.ToJson();
                                        routeId = pageAndRouteId.RouteId;
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    foreach (var routeParm in requestContext.RouteData.Values)
                    {
                        parms.Add(routeParm.Key, (string)routeParm.Value);
                    }
                }

                // If page has not been specified get the site by the domain and use the site's default page
                if (string.IsNullOrEmpty(pageId))
                {
                    SiteCache site = SiteCache.GetSiteByDomain(httpRequest.Url.Host);
                    if (site == null)
                    {
                        // Use last site
                        if (siteCookie != null && siteCookie.Value != null)
                        {
                            site = SiteCache.Read(siteCookie.Value.AsInteger());
                        }
                    }

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

                    if (site != null)
                    {
                        // Check to see if this is a short link route
                        if (requestContext.RouteData.Values.ContainsKey("shortlink"))
                        {
                            string shortlink = requestContext.RouteData.Values["shortlink"].ToString();
                            using (var rockContext = new Rock.Data.RockContext())
                            {
                                var pageShortLink = new PageShortLinkService(rockContext).GetByToken(shortlink, site.Id);
                                if (pageShortLink != null)
                                {
                                    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  = UI.RockPage.GetClientIpAddress(httpRequest);
                                    transaction.UserAgent  = httpRequest.UserAgent ?? "";
                                    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 = httpRequest.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)
                            {
                                if (clientType == "Tablet")
                                {
                                    redirect = true;
                                }
                            }

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

                        if (string.IsNullOrWhiteSpace(pageId))
                        {
                            if (site.DefaultPageId.HasValue)
                            {
                                pageId = site.DefaultPageId.Value.ToString();
                            }

                            if (site.DefaultPageRouteId.HasValue)
                            {
                                routeId = site.DefaultPageRouteId.Value;
                            }
                        }
                    }

                    if (string.IsNullOrEmpty(pageId))
                    {
                        throw new SystemException("Invalid Site Configuration");
                    }
                }

                PageCache page = null;

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

                if (page == null)
                {
                    // try to get site's 404 page
                    SiteCache site = SiteCache.GetSiteByDomain(httpRequest.Url.Host);
                    if (site == null)
                    {
                        // Use last site
                        if (siteCookie != null && siteCookie.Value != null)
                        {
                            site = SiteCache.Read(siteCookie.Value.AsInteger());
                        }
                    }

                    if (site != null && site.PageNotFoundPageId != null)
                    {
                        if (Convert.ToBoolean(GlobalAttributesCache.Read().GetValue("Log404AsException")))
                        {
                            Rock.Model.ExceptionLogService.LogException(
                                new Exception(string.Format("404 Error: {0}", httpRequest.Url.AbsoluteUri)),
                                requestContext.HttpContext.ApplicationInstance.Context);
                        }

                        page = PageCache.Read(site.PageNotFoundPageId ?? 0);
                    }
                    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)));
                    }
                }

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

                if (siteCookie == null)
                {
                    siteCookie = new System.Web.HttpCookie("last_site", page.Layout.SiteId.ToString());
                }
                else
                {
                    siteCookie.Value = page.Layout.SiteId.ToString();
                }
                requestContext.HttpContext.Response.SetCookie(siteCookie);

                try
                {
                    // Return the page for the selected theme and layout
                    Rock.Web.UI.RockPage cmsPage = (Rock.Web.UI.RockPage)BuildManager.CreateInstanceFromVirtualPath(layoutPath, typeof(Rock.Web.UI.RockPage));
                    cmsPage.SetPage(page);
                    cmsPage.PageReference = new PageReference(page.Id, routeId, parms, httpRequest.QueryString);
                    return(cmsPage);
                }
                catch (System.Web.HttpException)
                {
                    // The Selected theme and/or layout didn't exist, attempt first to use the layout in the default theme.
                    theme = "Rock";

                    // If not using the default layout, verify that Layout exists in the default theme directory
                    if (layout != "FullWidth" &&
                        !File.Exists(requestContext.HttpContext.Server.MapPath(string.Format("~/Themes/Rock/Layouts/{0}.aspx", layout))))
                    {
                        // If selected layout doesn't exist in the default theme, switch to the Default layout
                        layout = "FullWidth";
                    }

                    // Build the path to the aspx file to
                    layoutPath = PageCache.FormatPath(theme, layout);

                    // Return the default layout and/or theme
                    Rock.Web.UI.RockPage cmsPage = (Rock.Web.UI.RockPage)BuildManager.CreateInstanceFromVirtualPath(layoutPath, typeof(Rock.Web.UI.RockPage));
                    cmsPage.SetPage(page);
                    cmsPage.PageReference = new PageReference(page.Id, routeId, parms, httpRequest.QueryString);
                    return(cmsPage);
                }
            }
            catch (Exception ex)
            {
                if (requestContext.HttpContext != null)
                {
                    requestContext.HttpContext.Cache["RockExceptionOrder"] = "66";
                    requestContext.HttpContext.Cache["RockLastException"]  = ex;
                }

                System.Web.UI.Page errorPage = (System.Web.UI.Page)BuildManager.CreateInstanceFromVirtualPath("~/Error.aspx", typeof(System.Web.UI.Page));
                return(errorPage);
            }
        }
Пример #15
0
        /// <summary>
        /// Determine the logical page being requested by evaluating the routedata, or querystring and
        /// then loading the appropriate layout (ASPX) page
        /// </summary>
        /// <param name="requestContext"></param>
        /// <returns></returns>
        System.Web.IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
        {
            if (requestContext == null)
            {
                throw new ArgumentNullException("requestContext");
            }

            string pageId  = "";
            int    routeId = 0;

            var parms = new Dictionary <string, string>();

            // Pages using the default routing URL will have the page id in the RouteData.Values collection
            if (requestContext.RouteData.Values["PageId"] != null)
            {
                pageId = (string)requestContext.RouteData.Values["PageId"];
            }
            // Pages that use a custom URL route will have the page id in the RouteDate.DataTokens collection
            else if (requestContext.RouteData.DataTokens["PageId"] != null)
            {
                pageId  = (string)requestContext.RouteData.DataTokens["PageId"];
                routeId = Int32.Parse((string)requestContext.RouteData.DataTokens["RouteId"]);

                foreach (var routeParm in requestContext.RouteData.Values)
                {
                    parms.Add(routeParm.Key, (string)routeParm.Value);
                }
            }
            // If page has not been specified get the site by the domain and use the site's default page
            else
            {
                SiteCache site = SiteCache.GetSiteByDomain(requestContext.HttpContext.Request.Url.Host);

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

                if (site != null)
                {
                    if (site.DefaultPageId.HasValue)
                    {
                        pageId = site.DefaultPageId.Value.ToString();
                    }

                    if (site.DefaultPageRouteId.HasValue)
                    {
                        routeId = site.DefaultPageRouteId.Value;
                    }
                }

                if (string.IsNullOrEmpty(pageId))
                {
                    throw new SystemException("Invalid Site Configuration");
                }
            }

            PageCache page = null;

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

            if (page == null)
            {
                // try to get site's 404 page
                SiteCache site = SiteCache.GetSiteByDomain(requestContext.HttpContext.Request.Url.Host);
                if (site != null && site.PageNotFoundPageId != null)
                {
                    page = PageCache.Read(site.PageNotFoundPageId ?? 0);
                }
                else
                {
                    // no 404 page found for the site
                    return(new HttpHandlerError(404));
                }
            }

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

            try
            {
                // Return the page for the selected theme and layout
                Rock.Web.UI.RockPage cmsPage = (Rock.Web.UI.RockPage)BuildManager.CreateInstanceFromVirtualPath(layoutPath, typeof(Rock.Web.UI.RockPage));
                cmsPage.SetPage(page);
                cmsPage.PageReference = new PageReference(page.Id, routeId, parms, requestContext.HttpContext.Request.QueryString);
                return(cmsPage);
            }
            catch (System.Web.HttpException)
            {
                // The Selected theme and/or layout didn't exist, attempt first to use the layout in the default theme.
                theme = "Rock";

                // If not using the default layout, verify that Layout exists in the default theme directory
                if (layout != "Default" &&
                    !File.Exists(requestContext.HttpContext.Server.MapPath(string.Format("~/Themes/Rock/Layouts/{0}.aspx", layout))))
                {
                    // If selected layout doesn't exist in the default theme, switch to the Default layout
                    layout = "Default";
                }

                // Build the path to the aspx file to
                layoutPath = PageCache.FormatPath(theme, layout);

                // Return the default layout and/or theme
                Rock.Web.UI.RockPage cmsPage = (Rock.Web.UI.RockPage)BuildManager.CreateInstanceFromVirtualPath(layoutPath, typeof(Rock.Web.UI.RockPage));
                cmsPage.SetPage(page);
                cmsPage.PageReference = new PageReference(page.Id, routeId, parms, requestContext.HttpContext.Request.QueryString);
                return(cmsPage);
            }
        }
 private SiteCache GetSiteByDomainName(RequestContext requestContext)
 {
     return(SiteCache.GetSiteByDomain(WebRequestHelper.GetHostNameFromRequest(HttpContext.Current)));
 }