/// <summary> /// Loads the drop downs. /// </summary> private void LoadDropDowns() { ddlLayout.Items.Clear(); ddlLayout.Items.Add(new ListItem(string.Empty, None.IdValue)); var site = SiteCache.Read(hfSiteId.ValueAsInt()); if (site != null) { string virtualFolder = string.Format("~/Themes/{0}/Layouts", site.Theme); string physicalFolder = Request.MapPath(virtualFolder); // search for all layouts (aspx files) under the physical path var layoutFiles = new List <string>(); DirectoryInfo di = new DirectoryInfo(physicalFolder); if (di.Exists) { foreach (var file in di.GetFiles("*.aspx", SearchOption.AllDirectories)) { ddlLayout.Items.Add(new ListItem(file.FullName.Replace(physicalFolder, virtualFolder).Replace(@"\", "/"), Path.GetFileNameWithoutExtension(file.Name))); } } } ddlLayout.Required = true; }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad(EventArgs e) { if (!Page.IsPostBack && _pageId.HasValue) { var rockContext = new RockContext(); LoadSites(rockContext); PageService pageService = new PageService(rockContext); Rock.Model.Page page = pageService.Queryable("Layout,PageRoutes") .Where(p => p.Id == _pageId.Value) .FirstOrDefault(); if (page.Layout != null) { ddlSite.SelectedValue = page.Layout.SiteId.ToString(); LoadLayouts(rockContext, SiteCache.Read(page.Layout.SiteId)); ddlLayout.SelectedValue = page.Layout.Id.ToString(); } rptProperties.DataSource = _tabs; rptProperties.DataBind(); tbPageName.Text = page.InternalName; tbPageTitle.Text = page.PageTitle; tbBrowserTitle.Text = page.BrowserTitle; tbBodyCssClass.Text = page.BodyCssClass; ppParentPage.SetValue(pageService.Get(page.ParentPageId ?? 0)); tbIconCssClass.Text = page.IconCssClass; cbPageTitle.Checked = page.PageDisplayTitle; cbPageBreadCrumb.Checked = page.PageDisplayBreadCrumb; cbPageIcon.Checked = page.PageDisplayIcon; cbPageDescription.Checked = page.PageDisplayDescription; ddlMenuWhen.SelectedValue = ((int)page.DisplayInNavWhen).ToString(); cbMenuDescription.Checked = page.MenuDisplayDescription; cbMenuIcon.Checked = page.MenuDisplayIcon; cbMenuChildPages.Checked = page.MenuDisplayChildPages; cbBreadCrumbIcon.Checked = page.BreadCrumbDisplayIcon; cbBreadCrumbName.Checked = page.BreadCrumbDisplayName; cbRequiresEncryption.Checked = page.RequiresEncryption; cbEnableViewState.Checked = page.EnableViewState; cbIncludeAdminFooter.Checked = page.IncludeAdminFooter; cbAllowIndexing.Checked = page.AllowIndexing; tbCacheDuration.Text = page.OutputCacheDuration.ToString(); tbDescription.Text = page.Description; ceHeaderContent.Text = page.HeaderContent; tbPageRoute.Text = string.Join(",", page.PageRoutes.Select(route => route.Route).ToArray()); // Add enctype attribute to page's <form> tag to allow file upload control to function Page.Form.Attributes.Add("enctype", "multipart/form-data"); } base.OnLoad(e); }
/// <summary> /// Build filter values/summary with user friendly data from filters /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The e.</param> protected void fExceptionList_DisplayFilterValue(object sender, GridFilter.DisplayFilterValueArgs e) { switch (e.Key) { case "Site": int siteId; if (int.TryParse(e.Value, out siteId)) { var site = SiteCache.Read(siteId); if (site != null) { e.Value = site.Name; } } break; case "Page": int pageId; if (int.TryParse(e.Value, out pageId)) { var page = PageCache.Read(pageId); if (page != null) { e.Value = page.InternalName; } } break; case "User": int userPersonId; if (int.TryParse(e.Value, out userPersonId)) { PersonService personService = new PersonService(new RockContext()); var user = personService.Get(userPersonId); if (user != null) { e.Value = user.FullName; } } break; // ignore old filter parameters case "Start Date": case "End Date": e.Value = null; break; case "Date Range": e.Value = SlidingDateRangePicker.FormatDelimitedValues(e.Value); break; } }
/// <summary> /// Loads the sites. /// </summary> /// <param name="rockContext">The rock context.</param> private void LoadSites(RockContext rockContext) { ddlSite.Items.Clear(); foreach (SiteCache site in new SiteService(rockContext) .Queryable().AsNoTracking() .Where(s => s.EnabledForShortening) .OrderBy(s => s.Name) .Select(a => a.Id) .ToList() .Select(a => SiteCache.Read(a))) { ddlSite.Items.Add(new ListItem(site.Name, site.Id.ToString())); } }
/// <summary> /// Binds the pages grid. /// </summary> protected void BindPagesGrid() { pnlPages.Visible = false; int siteId = PageParameter("siteId").AsInteger() ?? 0; if (siteId == 0) { // quit if the siteId can't be determined return; } hfSiteId.SetValue(siteId); pnlPages.Visible = true; LayoutService layoutService = new LayoutService(); layoutService.RegisterLayouts(Request.MapPath("~"), SiteCache.Read(siteId), CurrentPersonId); var layouts = layoutService.Queryable().Where(a => a.SiteId.Equals(siteId)).Select(a => a.Id).ToList(); var siteService = new SiteService(); var pageId = siteService.Get(siteId).DefaultPageId; var pageService = new PageService(); var qry = pageService.GetAllDescendents((int)pageId).AsQueryable().Where(a => layouts.Contains(a.LayoutId)); string layoutFilter = gPagesFilter.GetUserPreference("Layout"); if (!string.IsNullOrWhiteSpace(layoutFilter) && layoutFilter != Rock.Constants.All.Text) { qry = qry.Where(a => a.Layout.ToString() == layoutFilter); } SortProperty sortProperty = gPages.SortProperty; if (sortProperty != null) { qry = qry.Sort(sortProperty); } else { qry = qry.OrderBy(q => q.Id); } gPages.DataSource = qry.ToList(); gPages.DataBind(); }
protected string GetFilePath(string fileName) { string virtualPath = fileName; var siteCache = SiteCache.Read(hfSiteId.ValueAsInt()); if (siteCache != null) { virtualPath = string.Format("~/Themes/{0}/Layouts/{1}.aspx", siteCache.Theme, fileName); if (!File.Exists(Request.MapPath(virtualPath))) { virtualPath = virtualPath += " <span class='label label-danger'>Missing</span>"; } } return(virtualPath); }
/// <summary> /// Binds the group members grid. /// </summary> protected void BindLayoutsGrid() { pnlLayouts.Visible = false; int siteId = PageParameter("siteId").AsInteger(); if (siteId == 0) { // quit if the siteId can't be determined return; } var rockContext = new RockContext(); var site = SiteCache.Read(siteId, rockContext); if (site == null) { return; } hfSiteId.SetValue(siteId); pnlLayouts.Visible = true; // Add any missing layouts LayoutService.RegisterLayouts(Request.MapPath("~"), site); LayoutService layoutService = new LayoutService(new RockContext()); var qry = layoutService.Queryable().Where(a => a.SiteId.Equals(siteId)); SortProperty sortProperty = gLayouts.SortProperty; if (sortProperty != null) { gLayouts.DataSource = qry.Sort(sortProperty).ToList(); } else { gLayouts.DataSource = qry.OrderBy(l => l.Name).ToList(); } gLayouts.DataBind(); }
/// <summary> /// Binds the filter. /// </summary> private void BindFilter() { int siteId = PageParameter("siteId").AsInteger(); if (siteId == 0) { // quit if the siteId can't be determined return; } LayoutService.RegisterLayouts(Request.MapPath("~"), SiteCache.Read(siteId)); LayoutService layoutService = new LayoutService(new RockContext()); var layouts = layoutService.Queryable().Where(a => a.SiteId.Equals(siteId)).ToList(); ddlLayoutFilter.DataSource = layouts; ddlLayoutFilter.DataBind(); ddlLayoutFilter.Items.Insert(0, Rock.Constants.All.ListItem); ddlLayoutFilter.Visible = layouts.Any(); ddlLayoutFilter.SetValue(gPagesFilter.GetUserPreference("Layout")); }
/// <summary> /// Build filter values/summary with user friendly data from filters /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The e.</param> protected void fExceptionList_DisplayFilterValue(object sender, GridFilter.DisplayFilterValueArgs e) { switch (e.Key) { case "Site": int siteId; if (int.TryParse(e.Value, out siteId)) { var site = SiteCache.Read(siteId); if (site != null) { e.Value = site.Name; } } break; case "Page": int pageId; if (int.TryParse(e.Value, out pageId)) { var page = PageCache.Read(pageId); if (page != null) { e.Value = page.InternalName; } } break; case "User": int userPersonId; if (int.TryParse(e.Value, out userPersonId)) { PersonService personService = new PersonService(new RockContext()); var user = personService.Get(userPersonId); if (user != null) { e.Value = user.FullName; } } break; } }
/// <summary> /// Shows the readonly details. /// </summary> /// <param name="page">The page.</param> private void ShowReadonlyDetails(Rock.Model.Page page) { SetEditMode(false); string pageIconHtml = !string.IsNullOrWhiteSpace(page.IconCssClass) ? pageIconHtml = string.Format("<i class='{0} fa-2x' ></i>", page.IconCssClass) : string.Empty; lTitle.Text = page.InternalName.FormatAsHtmlTitle(); if (!string.IsNullOrEmpty(page.IconCssClass)) { lIcon.Text = string.Format("<i class='{0}'></i>", page.IconCssClass); } else { lIcon.Text = "<i class='fa fa-file-text-o'></i>"; } var site = SiteCache.Read(page.Layout.SiteId); hlblSiteName.Text = "Site: " + site.Name; lblMainDetailsCol1.Text = new DescriptionList() .Add("Internal Name", page.InternalName) .Add("Page Title", page.PageTitle) .Add("Browser Title", page.BrowserTitle) .Add("Description", page.Description) .Html; var pageReference = new PageReference(page.Id); var pageUrl = pageReference.BuildUrl(); var pageLink = string.Format("<a href='{0}'>{0}</a>", pageUrl); lblMainDetailsCol2.Text = new DescriptionList() .Add("Layout", page.Layout) .Add("Url", pageLink) .Html; }
/// <summary> /// Handles the Pre Send Request event of the Application control. /// </summary> protected void Application_PreSendRequestHeaders() { Response.Headers.Remove("Server"); Response.Headers.Remove("X-AspNet-Version"); bool useFrameDomains = false; string allowedDomains = string.Empty; int?siteId = (Context.Items["Rock:SiteId"] ?? "").ToString().AsIntegerOrNull(); try { if (siteId.HasValue) { var site = SiteCache.Read(siteId.Value); if (site != null && !String.IsNullOrWhiteSpace(site.AllowedFrameDomains)) { useFrameDomains = true; allowedDomains = site.AllowedFrameDomains; } } } catch { } if (useFrameDomains) { // string concat is 5x faster than String.Format in this senario Response.AddHeader("Content-Security-Policy", "frame-ancestors " + allowedDomains); } else { Response.AddHeader("X-Frame-Options", "SAMEORIGIN"); Response.AddHeader("Content-Security-Policy", "frame-ancestors 'self'"); } }
/// <summary> /// Shows the edit details. /// </summary> /// <param name="page">The page.</param> private void ShowEditDetails(Rock.Model.Page page) { if (page.Id > 0) { lTitle.Text = ActionTitle.Edit(Rock.Model.Page.FriendlyTypeName).FormatAsHtmlTitle(); lIcon.Text = "<i class='fa fa-square-o'></i>"; } else { lTitle.Text = ActionTitle.Add(Rock.Model.Page.FriendlyTypeName).FormatAsHtmlTitle(); if (!string.IsNullOrEmpty(page.IconCssClass)) { lIcon.Text = string.Format("<i class='{0}'></i>", page.IconCssClass); } else { lIcon.Text = "<i class='fa fa-file-text-o'></i>"; } } SetEditMode(true); var rockContext = new RockContext(); PageService pageService = new PageService(rockContext); if (page.Layout != null) { ddlSite.SetValue(page.Layout.SiteId); } else if (page.ParentPageId.HasValue) { var parentPageCache = PageCache.Read(page.ParentPageId.Value); if (parentPageCache != null && parentPageCache.Layout != null) { ddlSite.SetValue(parentPageCache.Layout.SiteId); } } LoadLayouts(rockContext, SiteCache.Read(ddlSite.SelectedValue.AsInteger())); if (page.LayoutId == 0) { // default a new page's layout to whatever the parent page's layout is if (page.ParentPage != null) { page.LayoutId = page.ParentPage.LayoutId; } } ddlLayout.SetValue(page.LayoutId); phPageAttributes.Controls.Clear(); page.LoadAttributes(); if (page.Attributes != null && page.Attributes.Any()) { wpPageAttributes.Visible = true; Rock.Attribute.Helper.AddEditControls(page, phPageAttributes, true, BlockValidationGroup); } else { wpPageAttributes.Visible = false; } rptProperties.DataSource = _tabs; rptProperties.DataBind(); tbPageName.Text = page.InternalName; tbPageTitle.Text = page.PageTitle; tbBrowserTitle.Text = page.BrowserTitle; tbBodyCssClass.Text = page.BodyCssClass; ppParentPage.SetValue(pageService.Get(page.ParentPageId ?? 0)); tbIconCssClass.Text = page.IconCssClass; cbPageTitle.Checked = page.PageDisplayTitle; cbPageBreadCrumb.Checked = page.PageDisplayBreadCrumb; cbPageIcon.Checked = page.PageDisplayIcon; cbPageDescription.Checked = page.PageDisplayDescription; ddlMenuWhen.SelectedValue = (( int )page.DisplayInNavWhen).ToString(); cbMenuDescription.Checked = page.MenuDisplayDescription; cbMenuIcon.Checked = page.MenuDisplayIcon; cbMenuChildPages.Checked = page.MenuDisplayChildPages; cbBreadCrumbIcon.Checked = page.BreadCrumbDisplayIcon; cbBreadCrumbName.Checked = page.BreadCrumbDisplayName; cbRequiresEncryption.Checked = page.RequiresEncryption; cbEnableViewState.Checked = page.EnableViewState; cbIncludeAdminFooter.Checked = page.IncludeAdminFooter; cbAllowIndexing.Checked = page.AllowIndexing; tbCacheDuration.Text = page.OutputCacheDuration.ToString(); tbDescription.Text = page.Description; ceHeaderContent.Text = page.HeaderContent; tbPageRoute.Text = string.Join(",", page.PageRoutes.Select(route => route.Route).ToArray()); // Add enctype attribute to page's <form> tag to allow file upload control to function Page.Form.Attributes.Add("enctype", "multipart/form-data"); }
/// <summary> /// Sends the notification. /// </summary> /// <param name="ex">The ex.</param> private void SendNotification(Exception ex) { int? pageId = (Context.Items["Rock:PageId"] ?? "").ToString().AsIntegerOrNull();; int? siteId = (Context.Items["Rock:SiteId"] ?? "").ToString().AsIntegerOrNull();; PersonAlias personAlias = null; Person person = null; try { var user = UserLoginService.GetCurrentUser(); if (user != null && user.Person != null) { person = user.Person; personAlias = user.Person.PrimaryAlias; } } catch { } try { ExceptionLogService.LogException(ex, Context, pageId, siteId, personAlias); } catch { } try { string siteName = "Rock"; if (siteId.HasValue) { var site = SiteCache.Read(siteId.Value); if (site != null) { siteName = site.Name; } } // setup merge codes for email var mergeObjects = GlobalAttributesCache.GetMergeFields(null); mergeObjects.Add("ExceptionDetails", string.Format("An error occurred{0} on the {1} site on page: <br>{2}<p>{3}</p>", person != null ? " for " + person.FullName : "", siteName, Context.Request.Url.OriginalString, FormatException(ex, ""))); mergeObjects.Add("Person", person); // get email addresses to send to var globalAttributesCache = GlobalAttributesCache.Read(); string emailAddressesList = globalAttributesCache.GetValue("EmailExceptionsList"); if (!string.IsNullOrWhiteSpace(emailAddressesList)) { string[] emailAddresses = emailAddressesList.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var recipients = new List <RecipientData>(); foreach (string emailAddress in emailAddresses) { recipients.Add(new RecipientData(emailAddress, mergeObjects)); } if (recipients.Any()) { bool sendNotification = true; string filterSettings = globalAttributesCache.GetValue("EmailExceptionsFilter"); var serverVarList = Context.Request.ServerVariables; if (!string.IsNullOrWhiteSpace(filterSettings) && serverVarList.Count > 0) { string[] nameValues = filterSettings.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); foreach (string nameValue in nameValues) { string[] nameAndValue = nameValue.Split(new char[] { '^' }, StringSplitOptions.RemoveEmptyEntries); { if (nameAndValue.Length == 2) { var serverValue = serverVarList[nameAndValue[0]]; if (serverValue != null && serverValue.ToUpper().Contains(nameAndValue[1].ToUpper().Trim())) { sendNotification = false; break; } } } } } if (sendNotification) { Email.Send(Rock.SystemGuid.SystemEmail.CONFIG_EXCEPTION_NOTIFICATION.AsGuid(), recipients, string.Empty, string.Empty, false); } } } } catch { } }
/// <summary> /// Handles the Click event of the btnSave 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 btnSave_Click(object sender, EventArgs e) { Site site; if (Page.IsValid) { var rockContext = new RockContext(); SiteService siteService = new SiteService(rockContext); SiteDomainService siteDomainService = new SiteDomainService(rockContext); bool newSite = false; int siteId = hfSiteId.Value.AsInteger(); if (siteId == 0) { newSite = true; site = new Rock.Model.Site(); siteService.Add(site); } else { site = siteService.Get(siteId); } site.Name = tbSiteName.Text; site.Description = tbDescription.Text; site.Theme = ddlTheme.Text; site.DefaultPageId = ppDefaultPage.PageId; site.DefaultPageRouteId = ppDefaultPage.PageRouteId; site.LoginPageId = ppLoginPage.PageId; site.LoginPageRouteId = ppLoginPage.PageRouteId; site.ChangePasswordPageId = ppChangePasswordPage.PageId; site.ChangePasswordPageRouteId = ppChangePasswordPage.PageRouteId; site.CommunicationPageId = ppCommunicationPage.PageId; site.CommunicationPageRouteId = ppCommunicationPage.PageRouteId; site.RegistrationPageId = ppRegistrationPage.PageId; site.RegistrationPageRouteId = ppRegistrationPage.PageRouteId; site.PageNotFoundPageId = ppPageNotFoundPage.PageId; site.PageNotFoundPageRouteId = ppPageNotFoundPage.PageRouteId; site.ErrorPage = tbErrorPage.Text; site.GoogleAnalyticsCode = tbGoogleAnalytics.Text; site.RequiresEncryption = cbRequireEncryption.Checked; site.EnableMobileRedirect = cbEnableMobileRedirect.Checked; site.MobilePageId = ppMobilePage.PageId; site.ExternalUrl = tbExternalURL.Text; site.AllowedFrameDomains = tbAllowedFrameDomains.Text; site.RedirectTablets = cbRedirectTablets.Checked; site.EnablePageViews = cbEnablePageViews.Checked; site.PageViewRetentionPeriodDays = nbPageViewRetentionPeriodDays.Text.AsIntegerOrNull(); site.AllowIndexing = cbAllowIndexing.Checked; site.PageHeaderContent = cePageHeaderContent.Text; var currentDomains = tbSiteDomains.Text.SplitDelimitedValues().ToList <string>(); site.SiteDomains = site.SiteDomains ?? new List <SiteDomain>(); // Remove any deleted domains foreach (var domain in site.SiteDomains.Where(w => !currentDomains.Contains(w.Domain)).ToList()) { site.SiteDomains.Remove(domain); siteDomainService.Delete(domain); } foreach (string domain in currentDomains) { SiteDomain sd = site.SiteDomains.Where(d => d.Domain == domain).FirstOrDefault(); if (sd == null) { sd = new SiteDomain(); sd.Domain = domain; sd.Guid = Guid.NewGuid(); site.SiteDomains.Add(sd); } } if (!site.DefaultPageId.HasValue && !newSite) { ppDefaultPage.ShowErrorMessage("Default Page is required."); return; } if (!site.IsValid) { // Controls will render the error messages return; } rockContext.WrapTransaction(() => { rockContext.SaveChanges(); if (newSite) { Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.EDIT); Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.ADMINISTRATE); Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.APPROVE); } }); SiteCache.Flush(site.Id); // Create the default page is this is a new site if (!site.DefaultPageId.HasValue && newSite) { var siteCache = SiteCache.Read(site.Id); // Create the layouts for the site, and find the first one LayoutService.RegisterLayouts(Request.MapPath("~"), siteCache); var layoutService = new LayoutService(rockContext); var layouts = layoutService.GetBySiteId(siteCache.Id); Layout layout = layouts.FirstOrDefault(l => l.FileName.Equals("FullWidth", StringComparison.OrdinalIgnoreCase)); if (layout == null) { layout = layouts.FirstOrDefault(); } if (layout != null) { var pageService = new PageService(rockContext); var page = new Page(); page.LayoutId = layout.Id; page.PageTitle = siteCache.Name + " Home Page"; page.InternalName = page.PageTitle; page.BrowserTitle = page.PageTitle; page.EnableViewState = true; page.IncludeAdminFooter = true; page.MenuDisplayChildPages = true; var lastPage = pageService.GetByParentPageId(null).OrderByDescending(b => b.Order).FirstOrDefault(); page.Order = lastPage != null ? lastPage.Order + 1 : 0; pageService.Add(page); rockContext.SaveChanges(); site = siteService.Get(siteCache.Id); site.DefaultPageId = page.Id; rockContext.SaveChanges(); SiteCache.Flush(site.Id); } } var qryParams = new Dictionary <string, string>(); qryParams["siteId"] = site.Id.ToString(); NavigateToPage(RockPage.Guid, qryParams); } }
protected void ddlSite_SelectedIndexChanged(object sender, EventArgs e) { LoadLayouts(new RockContext(), SiteCache.Read(ddlSite.SelectedValueAsInt().Value)); }
/// <summary> /// Shows the exception. /// </summary> private void ShowException() { Exception ex = GetSavedValue("RockLastException") as Exception; if (ex != null) { int?siteId = (GetSavedValue("Rock:SiteId") ?? string.Empty).ToString().AsIntegerOrNull(); if (siteId.HasValue) { var site = SiteCache.Read(siteId.Value); if (site != null && !string.IsNullOrWhiteSpace(site.ErrorPage)) { Context.Response.Redirect(site.ErrorPage, false); Context.ApplicationInstance.CompleteRequest(); return; } } pnlSecurity.Visible = false; pnlException.Visible = true; int?errorLevel = (GetSavedValue("RockExceptionOrder") ?? string.Empty).ToString().AsIntegerOrNull(); ClearSavedValue("RockExceptionOrder"); ClearSavedValue("RockLastException"); bool showDetails = errorLevel.HasValue && errorLevel.Value == 66; if (!showDetails) { try { // check to see if the user is an admin, if so allow them to view the error details var userLogin = Rock.Model.UserLoginService.GetCurrentUser(); GroupService service = new GroupService(new RockContext()); Group adminGroup = service.GetByGuid(new Guid(Rock.SystemGuid.Group.GROUP_ADMINISTRATORS)); showDetails = userLogin != null && adminGroup.Members.Where(m => m.PersonId == userLogin.PersonId).Count() > 0; } catch { // ignore } } if (ex is HttpRequestValidationException) { lErrorInfo.Text = "<h3>Exception Log:</h3>"; lErrorInfo.Text += "<div class=\"alert alert-danger\">"; lErrorInfo.Text += "<h4>Invalid Content</h4>"; lErrorInfo.Text += "<p>One or more of the fields contained invalid characters. Please make sure that your entries do not contain any angle brackets like < or >."; lErrorInfo.Text += "</div>"; } else { if (showDetails) { lErrorInfo.Text = "<h3>Exception Log:</h3>"; ProcessException(ex, " "); } } if (Request.Headers["X-Requested-With"] == "XMLHttpRequest") { Response.StatusCode = 500; Response.Clear(); if (ex is HttpRequestValidationException) { Response.Write("One or more of the fields contains invalid characters. Please make sure that your entries do not contain any angle brackets like < or >."); } else { if (showDetails) { var stackTrace = HttpUtility.HtmlEncode(ex.StackTrace); // go get the important exception while (ex.InnerException != null) { ex = ex.InnerException; if (ex != null) { stackTrace = HttpUtility.HtmlEncode(ex.StackTrace) + "<br/>" + stackTrace; } } Response.Write(string.Format("{0}<p><pre>{1}</pre>", HttpUtility.HtmlEncode(ex.Message), stackTrace)); } else { Response.Write("An error has occurred while processing your request. Your organization's administrators have been notified of this problem."); } } Response.Flush(); Response.End(); return; } } }
/// <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); } }
/// <summary> /// Handles the Click event of the btnSave 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 btnSave_Click(object sender, EventArgs e) { Site site; if (Page.IsValid) { var rockContext = new RockContext(); PageService pageService = new PageService(rockContext); SiteService siteService = new SiteService(rockContext); SiteDomainService siteDomainService = new SiteDomainService(rockContext); bool newSite = false; int siteId = hfSiteId.Value.AsInteger(); if (siteId == 0) { newSite = true; site = new Rock.Model.Site(); siteService.Add(site); } else { site = siteService.Get(siteId); } site.Name = tbSiteName.Text; site.Description = tbDescription.Text; site.Theme = ddlTheme.Text; site.DefaultPageId = ppDefaultPage.PageId; site.DefaultPageRouteId = ppDefaultPage.PageRouteId; site.LoginPageId = ppLoginPage.PageId; site.LoginPageRouteId = ppLoginPage.PageRouteId; site.ChangePasswordPageId = ppChangePasswordPage.PageId; site.ChangePasswordPageRouteId = ppChangePasswordPage.PageRouteId; site.CommunicationPageId = ppCommunicationPage.PageId; site.CommunicationPageRouteId = ppCommunicationPage.PageRouteId; site.RegistrationPageId = ppRegistrationPage.PageId; site.RegistrationPageRouteId = ppRegistrationPage.PageRouteId; site.PageNotFoundPageId = ppPageNotFoundPage.PageId; site.PageNotFoundPageRouteId = ppPageNotFoundPage.PageRouteId; site.ErrorPage = tbErrorPage.Text; site.GoogleAnalyticsCode = tbGoogleAnalytics.Text; site.RequiresEncryption = cbRequireEncryption.Checked; site.EnabledForShortening = cbEnableForShortening.Checked; site.EnableMobileRedirect = cbEnableMobileRedirect.Checked; site.MobilePageId = ppMobilePage.PageId; site.ExternalUrl = tbExternalURL.Text; site.AllowedFrameDomains = tbAllowedFrameDomains.Text; site.RedirectTablets = cbRedirectTablets.Checked; site.EnablePageViews = cbEnablePageViews.Checked; site.AllowIndexing = cbAllowIndexing.Checked; site.IsIndexEnabled = cbEnableIndexing.Checked; site.IndexStartingLocation = tbIndexStartingLocation.Text; site.PageHeaderContent = cePageHeaderContent.Text; int?existingIconId = null; if (site.FavIconBinaryFileId != imgSiteIcon.BinaryFileId) { existingIconId = site.FavIconBinaryFileId; site.FavIconBinaryFileId = imgSiteIcon.BinaryFileId; } var currentDomains = tbSiteDomains.Text.SplitDelimitedValues().ToList <string>(); site.SiteDomains = site.SiteDomains ?? new List <SiteDomain>(); // Remove any deleted domains foreach (var domain in site.SiteDomains.Where(w => !currentDomains.Contains(w.Domain)).ToList()) { site.SiteDomains.Remove(domain); siteDomainService.Delete(domain); } int order = 0; foreach (string domain in currentDomains) { SiteDomain sd = site.SiteDomains.Where(d => d.Domain == domain).FirstOrDefault(); if (sd == null) { sd = new SiteDomain(); sd.Domain = domain; sd.Guid = Guid.NewGuid(); site.SiteDomains.Add(sd); } sd.Order = order++; } if (!site.DefaultPageId.HasValue && !newSite) { ppDefaultPage.ShowErrorMessage("Default Page is required."); return; } if (!site.IsValid) { // Controls will render the error messages return; } rockContext.WrapTransaction(() => { rockContext.SaveChanges(); SaveAttributes(new Page().TypeId, "SiteId", site.Id.ToString(), PageAttributesState, rockContext); if (existingIconId.HasValue) { BinaryFileService binaryFileService = new BinaryFileService(rockContext); var binaryFile = binaryFileService.Get(existingIconId.Value); if (binaryFile != null) { // marked the old images as IsTemporary so they will get cleaned up later binaryFile.IsTemporary = true; rockContext.SaveChanges(); } } if (newSite) { Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.EDIT); Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.ADMINISTRATE); Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.APPROVE); } }); // add/update for the InteractionChannel for this site and set the RetentionPeriod var interactionChannelService = new InteractionChannelService(rockContext); int channelMediumWebsiteValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid()).Id; var interactionChannelForSite = interactionChannelService.Queryable() .Where(a => a.ChannelTypeMediumValueId == channelMediumWebsiteValueId && a.ChannelEntityId == site.Id).FirstOrDefault(); if (interactionChannelForSite == null) { interactionChannelForSite = new InteractionChannel(); interactionChannelForSite.ChannelTypeMediumValueId = channelMediumWebsiteValueId; interactionChannelForSite.ChannelEntityId = site.Id; interactionChannelService.Add(interactionChannelForSite); } interactionChannelForSite.Name = site.Name; interactionChannelForSite.RetentionDuration = nbPageViewRetentionPeriodDays.Text.AsIntegerOrNull(); interactionChannelForSite.ComponentEntityTypeId = EntityTypeCache.Read <Rock.Model.Page>().Id; rockContext.SaveChanges(); foreach (int pageId in pageService.GetBySiteId(site.Id) .Select(p => p.Id) .ToList()) { PageCache.Flush(pageId); } SiteCache.Flush(site.Id); AttributeCache.FlushEntityAttributes(); // Create the default page is this is a new site if (!site.DefaultPageId.HasValue && newSite) { var siteCache = SiteCache.Read(site.Id); // Create the layouts for the site, and find the first one LayoutService.RegisterLayouts(Request.MapPath("~"), siteCache); var layoutService = new LayoutService(rockContext); var layouts = layoutService.GetBySiteId(siteCache.Id); Layout layout = layouts.FirstOrDefault(l => l.FileName.Equals("FullWidth", StringComparison.OrdinalIgnoreCase)); if (layout == null) { layout = layouts.FirstOrDefault(); } if (layout != null) { var page = new Page(); page.LayoutId = layout.Id; page.PageTitle = siteCache.Name + " Home Page"; page.InternalName = page.PageTitle; page.BrowserTitle = page.PageTitle; page.EnableViewState = true; page.IncludeAdminFooter = true; page.MenuDisplayChildPages = true; var lastPage = pageService.GetByParentPageId(null).OrderByDescending(b => b.Order).FirstOrDefault(); page.Order = lastPage != null ? lastPage.Order + 1 : 0; pageService.Add(page); rockContext.SaveChanges(); site = siteService.Get(siteCache.Id); site.DefaultPageId = page.Id; rockContext.SaveChanges(); SiteCache.Flush(site.Id); } } var qryParams = new Dictionary <string, string>(); qryParams["siteId"] = site.Id.ToString(); NavigateToPage(RockPage.Guid, qryParams); } }
/// <summary> /// Handles the Click event of the btnSave 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 btnSave_Click(object sender, EventArgs e) { Site site; if (Page.IsValid) { using (new Rock.Data.UnitOfWorkScope()) { SiteService siteService = new SiteService(); SiteDomainService siteDomainService = new SiteDomainService(); bool newSite = false; int siteId = int.Parse(hfSiteId.Value); if (siteId == 0) { newSite = true; site = new Rock.Model.Site(); siteService.Add(site, CurrentPersonId); } else { site = siteService.Get(siteId); } site.Name = tbSiteName.Text; site.Description = tbDescription.Text; site.Theme = ddlTheme.Text; site.DefaultPageId = ppDefaultPage.PageId; site.DefaultPageRouteId = ppDefaultPage.PageRouteId; site.LoginPageId = ppLoginPage.PageId; site.LoginPageRouteId = ppLoginPage.PageRouteId; site.RegistrationPageId = ppRegistrationPage.PageId; site.RegistrationPageRouteId = ppRegistrationPage.PageRouteId; site.PageNotFoundPageId = ppPageNotFoundPage.PageId; site.PageNotFoundPageRouteId = ppPageNotFoundPage.PageRouteId; site.ErrorPage = tbErrorPage.Text; site.GoogleAnalyticsCode = tbGoogleAnalytics.Text; site.FacebookAppId = tbFacebookAppId.Text; site.FacebookAppSecret = tbFacebookAppSecret.Text; var currentDomains = tbSiteDomains.Text.SplitDelimitedValues().ToList <string>(); site.SiteDomains = site.SiteDomains ?? new List <SiteDomain>(); // Remove any deleted domains foreach (var domain in site.SiteDomains.Where(w => !currentDomains.Contains(w.Domain)).ToList()) { site.SiteDomains.Remove(domain); siteDomainService.Delete(domain, CurrentPersonId); } foreach (string domain in currentDomains) { SiteDomain sd = site.SiteDomains.Where(d => d.Domain == domain).FirstOrDefault(); if (sd == null) { sd = new SiteDomain(); sd.Domain = domain; sd.Guid = Guid.NewGuid(); site.SiteDomains.Add(sd); } } if (!site.DefaultPageId.HasValue && !newSite) { ppDefaultPage.ShowErrorMessage("Default Page is required."); return; } if (!site.IsValid) { // Controls will render the error messages return; } RockTransactionScope.WrapTransaction(() => { siteService.Save(site, CurrentPersonId); if (newSite) { Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, CurrentPersonId); } }); SiteCache.Flush(site.Id); // Create the default page is this is a new site if (!site.DefaultPageId.HasValue && newSite) { var siteCache = SiteCache.Read(site.Id); // Create the layouts for the site, and find the first one var layoutService = new LayoutService(); layoutService.RegisterLayouts(Request.MapPath("~"), siteCache, CurrentPersonId); var layouts = layoutService.GetBySiteId(siteCache.Id); Layout layout = layouts.FirstOrDefault(l => l.FileName.Equals("FullWidth", StringComparison.OrdinalIgnoreCase)); if (layout == null) { layout = layouts.FirstOrDefault(); } if (layout != null) { var pageService = new PageService(); var page = new Page(); page.LayoutId = layout.Id; page.PageTitle = siteCache.Name + " Home Page"; page.InternalName = page.PageTitle; page.BrowserTitle = page.PageTitle; page.EnableViewState = true; page.IncludeAdminFooter = true; page.MenuDisplayChildPages = true; var lastPage = pageService.GetByParentPageId(null). OrderByDescending(b => b.Order).FirstOrDefault(); page.Order = lastPage != null ? lastPage.Order + 1 : 0; pageService.Add(page, CurrentPersonId); pageService.Save(page, CurrentPersonId); site = siteService.Get(siteCache.Id); site.DefaultPageId = page.Id; siteService.Save(site, CurrentPersonId); SiteCache.Flush(site.Id); } } } var qryParams = new Dictionary <string, string>(); qryParams["siteId"] = site.Id.ToString(); NavigateToPage(RockPage.Guid, qryParams); } }
/// <summary> /// Shows the detail. /// </summary> /// <param name="layoutId">The layout identifier.</param> /// <param name="siteId">The group id.</param> public void ShowDetail(int layoutId, int?siteId) { Layout layout = null; if (!layoutId.Equals(0)) { layout = new LayoutService(new RockContext()).Get(layoutId); } if (layout == null && siteId.HasValue) { var site = SiteCache.Read(siteId.Value); if (site != null) { layout = new Layout { Id = 0 }; layout.SiteId = siteId.Value; } } if (layout == null) { pnlDetails.Visible = false; return; } hfSiteId.Value = layout.SiteId.ToString(); hfLayoutId.Value = layout.Id.ToString(); bool readOnly = false; nbEditModeMessage.Text = string.Empty; if (!IsUserAuthorized(Authorization.EDIT)) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(Rock.Model.Layout.FriendlyTypeName); } if (layout.IsSystem) { nbEditModeMessage.Text = EditModeMessage.System(Rock.Model.Layout.FriendlyTypeName); } if (readOnly) { btnEdit.Visible = false; //btnDelete.Visible = false; ShowReadonlyDetails(layout); } else { btnEdit.Visible = true; //btnDelete.Visible = !layout.IsSystem; if (layout.Id > 0) { ShowReadonlyDetails(layout); } else { ShowEditDetails(layout); } } }
/// <summary> /// Shows the list. /// </summary> public void ShowList() { var rockContext = new RockContext(); int sessionCount = GetAttributeValue("SessionCount").AsInteger(); int skipCount = pageNumber * sessionCount; Person person = null; Guid? personGuid = PageParameter("PersonGuid").AsGuidOrNull(); // NOTE: Since this block shows a history of sites a person visited in Rock, require Person.Guid instead of Person.Id to reduce the risk of somebody manually editing the URL to see somebody else pageview history if (personGuid.HasValue) { person = new PersonService(rockContext).Get(personGuid.Value); } else if (!string.IsNullOrEmpty(PageParameter("Person"))) { // Just in case Person (Person Token) was used, look up by Impersonation Token person = new PersonService(rockContext).GetByImpersonationToken(PageParameter("Person"), false, this.PageCache.Id); } if (person != null) { lPersonName.Text = person.FullName; InteractionService interactionService = new InteractionService(rockContext); var pageViews = interactionService.Queryable(); var sessionInfo = interactionService.Queryable() .Where(s => s.PersonAlias.PersonId == person.Id); if (startDate != DateTime.MinValue) { sessionInfo = sessionInfo.Where(s => s.InteractionDateTime > drpDateFilter.LowerValue); } if (endDate != DateTime.MaxValue) { sessionInfo = sessionInfo.Where(s => s.InteractionDateTime < drpDateFilter.UpperValue); } if (siteId != -1) { var site = SiteCache.Read(siteId); string siteName = string.Empty; if (site != null) { siteName = site.Name; } // lookup the interactionDeviceType, and create it if it doesn't exist int channelMediumValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid()).Id; var interactionChannelId = new InteractionChannelService(rockContext).Queryable() .Where(a => a.ChannelTypeMediumValueId == channelMediumValueId && a.ChannelEntityId == siteId) .Select(a => a.Id) .FirstOrDefault(); sessionInfo = sessionInfo.Where(p => p.InteractionComponent.ChannelId == interactionChannelId); } var pageviewInfo = sessionInfo.GroupBy(s => new { s.InteractionSession, s.InteractionComponent.Channel, }) .Select(s => new WebSession { PageViewSession = s.Key.InteractionSession, StartDateTime = s.Min(x => x.InteractionDateTime), EndDateTime = s.Max(x => x.InteractionDateTime), SiteId = siteId, Site = s.Key.Channel.Name, PageViews = pageViews.Where(p => p.InteractionSessionId == s.Key.InteractionSession.Id && p.InteractionComponent.ChannelId == s.Key.Channel.Id).OrderBy(p => p.InteractionDateTime).ToList() }); pageviewInfo = pageviewInfo.OrderByDescending(p => p.StartDateTime) .Skip(skipCount) .Take(sessionCount + 1); rptSessions.DataSource = pageviewInfo.ToList().Take(sessionCount); rptSessions.DataBind(); // set next button if (pageviewInfo.Count() > sessionCount) { hlNext.Visible = hlNext.Enabled = true; Dictionary <string, string> queryStringNext = new Dictionary <string, string>(); queryStringNext.Add("Page", (pageNumber + 1).ToString()); queryStringNext.Add("Person", person.UrlEncodedKey); if (siteId != -1) { queryStringNext.Add("SiteId", siteId.ToString()); } if (startDate != DateTime.MinValue) { queryStringNext.Add("StartDate", startDate.ToShortDateString()); } if (endDate != DateTime.MaxValue) { queryStringNext.Add("EndDate", endDate.ToShortDateString()); } var pageReferenceNext = new Rock.Web.PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringNext); hlNext.NavigateUrl = pageReferenceNext.BuildUrl(); } else { hlNext.Visible = hlNext.Enabled = false; } // set prev button if (pageNumber == 0) { hlPrev.Visible = hlPrev.Enabled = false; } else { hlPrev.Visible = hlPrev.Enabled = true; Dictionary <string, string> queryStringPrev = new Dictionary <string, string>(); queryStringPrev.Add("Page", (pageNumber - 1).ToString()); queryStringPrev.Add("Person", person.UrlEncodedKey); if (siteId != -1) { queryStringPrev.Add("SiteId", siteId.ToString()); } if (startDate != DateTime.MinValue) { queryStringPrev.Add("StartDate", startDate.ToShortDateString()); } if (endDate != DateTime.MaxValue) { queryStringPrev.Add("EndDate", endDate.ToShortDateString()); } var pageReferencePrev = new Rock.Web.PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringPrev); hlPrev.NavigateUrl = pageReferencePrev.BuildUrl(); } } else { lMessages.Text = "<div class='alert alert-warning'>No person provided to show results for.</div>"; } }
public void Execute() { if (PageId.HasValue || !string.IsNullOrWhiteSpace(ComponentName)) { using (var rockContext = new RockContext()) { int channelMediumTypeValueId = DefinedValueCache.Read(AvalancheUtilities.AppMediumValue.AsGuid()).Id; var interactionChannelService = new InteractionChannelService(rockContext); var interactionService = new InteractionService(rockContext); var interactionChannel = interactionChannelService.Queryable() .Where(a => a.ChannelTypeMediumValueId == channelMediumTypeValueId && a.ChannelEntityId == this.SiteId) .FirstOrDefault(); if (interactionChannel == null) { interactionChannel = new InteractionChannel(); interactionChannel.Name = SiteCache.Read(SiteId ?? 1).Name; interactionChannel.ChannelTypeMediumValueId = channelMediumTypeValueId; interactionChannel.ChannelEntityId = this.SiteId; interactionChannel.ComponentEntityTypeId = EntityTypeCache.Read <Rock.Model.Page>().Id; interactionChannelService.Add(interactionChannel); rockContext.SaveChanges(); } InteractionComponent interactionComponent = null; var interactionComponentService = new InteractionComponentService(rockContext); if (PageId.HasValue) { interactionComponent = interactionComponentService.GetComponentByEntityId(interactionChannel.Id, PageId.Value, PageTitle); } else { interactionComponent = interactionComponentService.GetComponentByComponentName(interactionChannel.Id, ComponentName); } rockContext.SaveChanges(); // Add the interaction if (interactionComponent != null) { var deviceId = Regex.Match(UserAgent, "(?<=-).+(?=\\))").Value.Trim().Substring(0, 20); var deviceApplication = Regex.Match(UserAgent, "^[\\S]{0,}").Value.Trim() + " " + deviceId; var clientOs = Regex.Match(UserAgent, "(?<=;).+(?=-)").Value.Trim(); var clientType = Regex.Match(UserAgent, "(?<=\\().+(?=;)").Value.Trim(); var deviceType = interactionService.GetInteractionDeviceType(deviceApplication, clientOs, clientType, UserAgent); var interactionSessionService = new InteractionSessionService(rockContext); var interactionSession = interactionSessionService.Queryable().Where(s => s.IpAddress == IPAddress && s.DeviceTypeId == deviceType.Id).FirstOrDefault(); if (interactionSession == null) { interactionSession = new InteractionSession() { DeviceTypeId = deviceType.Id, IpAddress = IPAddress }; interactionSessionService.Add(interactionSession); rockContext.SaveChanges(); } var interaction = new InteractionService(rockContext).AddInteraction(interactionComponent.Id, null, Operation, InteractionData, PersonAliasId, DateViewed, deviceApplication, clientOs, clientType, UserAgent, IPAddress, interactionSession.Guid); interaction.InteractionSummary = InteractionSummary; PersonalDevice personalDevice = GetPersonalDevice(deviceId, rockContext); if (personalDevice != null) { interaction.PersonalDeviceId = personalDevice.Id; } rockContext.SaveChanges(); } } } }
/// <summary> /// Shows the active users. /// </summary> private void ShowActiveUsers() { int?siteId = GetAttributeValue("Site").AsIntegerOrNull(); if (!siteId.HasValue) { lMessages.Text = "<div class='alert alert-warning'>No site is currently configured.</div>"; return; } else { int pageViewCount = GetAttributeValue("PageViewCount").AsIntegerOrNull() ?? 0; StringBuilder sbUsers = new StringBuilder(); var site = SiteCache.Read(siteId.Value); lSiteName.Text = "<h4>" + site.Name + "</h4>"; lSiteName.Visible = GetAttributeValue("ShowSiteNameAsTitle").AsBoolean(); lMessages.Text = string.Empty; using (var rockContext = new RockContext()) { var qryPageViews = new PageViewService(rockContext).Queryable(); var qryPersonAlias = new PersonAliasService(rockContext).Queryable(); var pageViewQry = qryPageViews.Join( qryPersonAlias, pv => pv.PersonAliasId, pa => pa.Id, (pv, pa) => new { PersonAliasPersonId = pa.PersonId, pv.DateTimeViewed, pv.SiteId, pv.SessionId, PagePageTitle = pv.Page.PageTitle }); var last24Hours = RockDateTime.Now.AddDays(-1); int pageViewTakeCount = pageViewCount; if (pageViewTakeCount == 0) { pageViewTakeCount = 1; } // Query to get who is logged in and last visit was to selected site var activeLogins = new UserLoginService(rockContext).Queryable("Person") .Where(l => l.PersonId.HasValue && l.IsOnLine == true) .OrderByDescending(l => l.LastActivityDateTime) .Select(l => new { login = l, pageViews = pageViewQry .Where(v => v.PersonAliasPersonId == l.PersonId) .Where(v => v.DateTimeViewed > last24Hours) .OrderByDescending(v => v.DateTimeViewed) .Take(pageViewTakeCount) }) .Where(a => a.pageViews.Any() && a.pageViews.FirstOrDefault().SiteId == site.Id) .Select(a => new { a.login, pageViews = a.pageViews, LatestSessionId = a.pageViews.FirstOrDefault().SessionId }); if (CurrentUser != null) { activeLogins = activeLogins.Where(m => m.login.UserName != CurrentUser.UserName); } foreach (var activeLogin in activeLogins) { var login = activeLogin.login; Guid?latestSession = activeLogin.LatestSessionId; TimeSpan tsLastActivity = login.LastActivityDateTime.HasValue ? RockDateTime.Now.Subtract(login.LastActivityDateTime.Value) : TimeSpan.MaxValue; string className = tsLastActivity.Minutes <= 5 ? "recent" : "not-recent"; // create link to the person string personLink = login.Person.FullName; if (GetAttributeValue("PersonProfilePage") != null) { string personProfilePage = GetAttributeValue("PersonProfilePage"); var pageParams = new Dictionary <string, string>(); pageParams.Add("PersonId", login.Person.Id.ToString()); var pageReference = new Rock.Web.PageReference(personProfilePage, pageParams); personLink = string.Format(@"<a href='{0}'>{1}</a>", pageReference.BuildUrl(), login.Person.FullName); } // determine whether to show last page views if (GetAttributeValue("PageViewCount").AsInteger() > 0) { string format = @" <li class='active-user {0}' data-toggle='tooltip' data-placement='top' title='{2}'> <i class='fa-li fa fa-circle'></i> {1} </li>"; if (activeLogin.pageViews != null) { var pageViews = activeLogin.pageViews.ToList(); string pageViewsHtml = activeLogin.pageViews.ToList() .Where(v => v.SessionId == latestSession) .Select(v => HttpUtility.HtmlEncode(v.PagePageTitle)).ToList().AsDelimited("<br> "); sbUsers.Append(string.Format(format, className, personLink, pageViewsHtml)); } } else { string format = @" <li class='active-user {0}'> <i class='fa-li fa fa-circle'></i> {1} </li>"; sbUsers.Append(string.Format(format, className, personLink)); } } } if (sbUsers.Length > 0) { lUsers.Text = string.Format(@"<ul class='activeusers fa-ul'>{0}</ul>", sbUsers.ToString()); } else { lMessages.Text = string.Format("There are no logged in users on the {0} site.", site.Name); } } }
/// <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); } }
/// <summary> /// Binds the pages grid. /// </summary> protected void BindPagesGrid() { pnlPages.Visible = false; int siteId = PageParameter("siteId").AsInteger(); if (siteId == 0) { // quit if the siteId can't be determined return; } hfSiteId.SetValue(siteId); pnlPages.Visible = true; // Question: Is this RegisterLayouts necessary here? Since if it's a new layout // there would not be any pages on them (which is our concern here). // It seems like it should be the concern of some other part of the puzzle. LayoutService.RegisterLayouts(Request.MapPath("~"), SiteCache.Read(siteId)); //var layouts = layoutService.Queryable().Where( a => a.SiteId.Equals( siteId ) ).Select( a => a.Id ).ToList(); // Find all the pages that are related to this site... // 1) pages used by one of this site's layouts and // 2) the site's 'special' pages used directly by the site. var rockContext = new RockContext(); var siteService = new SiteService(rockContext); var pageService = new PageService(rockContext); var site = siteService.Get(siteId); if (site != null) { var sitePages = new List <int> { site.DefaultPageId ?? -1, site.LoginPageId ?? -1, site.RegistrationPageId ?? -1, site.PageNotFoundPageId ?? -1 }; var qry = pageService.Queryable("Layout") .Where(t => t.Layout.SiteId == siteId || sitePages.Contains(t.Id)); string layoutFilter = gPagesFilter.GetUserPreference("Layout"); if (!string.IsNullOrWhiteSpace(layoutFilter) && layoutFilter != Rock.Constants.All.Text) { qry = qry.Where(a => a.Layout.ToString() == layoutFilter); } SortProperty sortProperty = gPages.SortProperty; if (sortProperty != null) { qry = qry.Sort(sortProperty); } else { qry = qry .OrderBy(t => t.Layout.Name) .ThenBy(t => t.InternalName); } gPages.DataSource = qry.ToList(); gPages.DataBind(); } }
/// <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); } }
/// <summary> /// Shows the active users. /// </summary> private void ShowActiveUsers() { int?siteId = GetAttributeValue("Site").AsIntegerOrNull(); if (!siteId.HasValue || SiteCache.Read(siteId.Value) == null) { lMessages.Text = "<div class='alert alert-warning'>No site is currently configured.</div>"; return; } else { int pageViewCount = GetAttributeValue("PageViewCount").AsIntegerOrNull() ?? 0; StringBuilder sbUsers = new StringBuilder(); var site = SiteCache.Read(siteId.Value); lSiteName.Text = "<h4>" + site.Name + "</h4>"; lSiteName.Visible = GetAttributeValue("ShowSiteNameAsTitle").AsBoolean(); if (!site.EnablePageViews) { lMessages.Text = "<div class='alert alert-warning'>Active " + site.Name + " users not available because page views are not enabled for site.</div>"; return; } lMessages.Text = string.Empty; string guestVisitorsStr = string.Empty; using (var rockContext = new RockContext()) { var qryPageViews = new InteractionService(rockContext).Queryable(); var qryPersonAlias = new PersonAliasService(rockContext).Queryable(); var pageViewQry = qryPageViews.Join( qryPersonAlias, pv => pv.PersonAliasId, pa => pa.Id, (pv, pa) => new { PersonAliasPersonId = pa.PersonId, pv.InteractionDateTime, pv.InteractionComponent.Channel.ChannelEntityId, pv.InteractionSessionId, PagePageTitle = pv.InteractionComponent.Name }); var last24Hours = RockDateTime.Now.AddDays(-1); int pageViewTakeCount = pageViewCount; if (pageViewTakeCount == 0) { pageViewTakeCount = 1; } // Query to get who is logged in and last visit was to selected site var activeLogins = new UserLoginService(rockContext).Queryable() .Where(l => l.PersonId.HasValue && l.IsOnLine == true) .OrderByDescending(l => l.LastActivityDateTime) .Select(l => new { login = new { l.UserName, l.LastActivityDateTime, l.PersonId, Person = new { l.Person.NickName, l.Person.LastName, l.Person.SuffixValueId } }, pageViews = pageViewQry .Where(v => v.PersonAliasPersonId == l.PersonId) .Where(v => v.InteractionDateTime > last24Hours) .OrderByDescending(v => v.InteractionDateTime) .Take(pageViewTakeCount) }) .Select(a => new { a.login, pageViews = a.pageViews.ToList() }); if (CurrentUser != null) { activeLogins = activeLogins.Where(m => m.login.UserName != CurrentUser.UserName); } foreach (var activeLogin in activeLogins) { var login = activeLogin.login; if (!activeLogin.pageViews.Any() || activeLogin.pageViews.FirstOrDefault().ChannelEntityId != site.Id) { // only show active logins with PageViews and the most recent pageview is for the specified site continue; } var latestPageViewSessionId = activeLogin.pageViews.FirstOrDefault().InteractionSessionId; TimeSpan tsLastActivity = login.LastActivityDateTime.HasValue ? RockDateTime.Now.Subtract(login.LastActivityDateTime.Value) : TimeSpan.MaxValue; string className = tsLastActivity.Minutes <= 5 ? "recent" : "not-recent"; // create link to the person string personFullName = Person.FormatFullName(login.Person.NickName, login.Person.LastName, login.Person.SuffixValueId); string personLink = personFullName; if (GetAttributeValue("PersonProfilePage") != null) { string personProfilePage = GetAttributeValue("PersonProfilePage"); var pageParams = new Dictionary <string, string>(); pageParams.Add("PersonId", login.PersonId.ToString()); var pageReference = new Rock.Web.PageReference(personProfilePage, pageParams); personLink = string.Format(@"<a href='{0}'>{1}</a>", pageReference.BuildUrl(), personFullName); } // determine whether to show last page views if (GetAttributeValue("PageViewCount").AsInteger() > 0) { string activeLoginFormat = @" <li class='active-user {0}' data-toggle='tooltip' data-placement='top' title='{2}'> <i class='fa-li fa fa-circle'></i> {1} </li>"; // define the formatting for each user entry if (activeLogin.pageViews != null) { string pageViewsHtml = activeLogin.pageViews .Where(v => v.InteractionSessionId == latestPageViewSessionId) .Select(v => HttpUtility.HtmlEncode(v.PagePageTitle)).ToList().AsDelimited("<br> "); sbUsers.Append(string.Format(activeLoginFormat, className, personLink, pageViewsHtml)); } } else { string inactiveLoginFormat = @" <li class='active-user {0}'> <i class='fa-li fa fa-circle'></i> {1} </li>"; sbUsers.Append(string.Format(inactiveLoginFormat, className, personLink)); } } // get the 'show guests' attribute and if it's true, determine how many guests there are. bool showGuestVisitors = GetAttributeValue("ShowGuestVisitors").AsBoolean(); if (showGuestVisitors) { // build a list of unique sessions views in the past 15 minutes. // We'll only take entries with a null personAliasID, which means they're not logged in, // and thus ARE guests. var last5Minutes = RockDateTime.Now.AddMinutes(-5); var last15Minutes = RockDateTime.Now.AddMinutes(-15); var qryGuests = new InteractionService(rockContext).Queryable().AsNoTracking() .Where( i => i.InteractionComponent.Channel.ChannelEntityId == site.Id && i.InteractionDateTime > last15Minutes && i.PersonAliasId == null && i.InteractionSession.DeviceType.ClientType != "Other" && i.InteractionSession.DeviceType.ClientType != "Crawler") .GroupBy(i => i.InteractionSessionId) .Select(g => new { SessionId = g.Key, LastVisit = g.Max(i => i.InteractionDateTime) }) .ToList(); var numRecentGuests = qryGuests.Where(g => g.LastVisit >= last5Minutes).Count(); var numInactiveGuests = qryGuests.Where(g => g.LastVisit < last5Minutes).Count(); // now build the formatted entry, which is "Current Guests (0) (1)" where the first is a green badge, and the second yellow. if (numRecentGuests > 0 || numInactiveGuests > 0) { guestVisitorsStr = "Current Guests:"; if (numRecentGuests > 0) { guestVisitorsStr += string.Format(" <span class=\"badge badge-success\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"Users active in the past 5 minutes.\">{0}</span>", numRecentGuests); } if (numInactiveGuests > 0) { guestVisitorsStr += string.Format(" <span class=\"badge badge-warning\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"Users active in the past 15 minutes.\">{0}</span>", numInactiveGuests); } } } } if (sbUsers.Length > 0) { lUsers.Text = string.Format(@"<ul class='activeusers fa-ul'>{0}</ul>", sbUsers.ToString()); lUsers.Text += string.Format(@"<p class='margin-l-sm js-current-guests'>{0}</p>", guestVisitorsStr); } else { lMessages.Text = string.Format("There are no logged in users on the {0} site.", site.Name); lMessages.Text += "<br /><br />" + guestVisitorsStr; } } }
/// <summary> /// Execute method to write transaction to the database. /// </summary> public void Execute() { if (PageId.HasValue) { using (var rockContext = new RockContext()) { var userAgent = (this.UserAgent ?? string.Empty).Trim(); if (userAgent.Length > 450) { userAgent = userAgent.Substring(0, 450); // trim super long useragents to fit in pageViewUserAgent.UserAgent } // get user agent info var clientType = InteractionDeviceType.GetClientType(userAgent); // don't log visits from crawlers if (clientType != "Crawler") { // lookup the interaction channel, and create it if it doesn't exist int channelMediumTypeValueId = DefinedValueCache.Read(SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid()).Id; var interactionChannelService = new InteractionChannelService(rockContext); var interactionChannel = interactionChannelService.Queryable() .Where(a => a.ChannelTypeMediumValueId == channelMediumTypeValueId && a.ChannelEntityId == this.SiteId) .FirstOrDefault(); if (interactionChannel == null) { interactionChannel = new InteractionChannel(); interactionChannel.Name = SiteCache.Read(SiteId ?? 1).Name; interactionChannel.ChannelTypeMediumValueId = channelMediumTypeValueId; interactionChannel.ChannelEntityId = this.SiteId; interactionChannel.ComponentEntityTypeId = EntityTypeCache.Read <Rock.Model.Page>().Id; interactionChannelService.Add(interactionChannel); rockContext.SaveChanges(); } // check that the page exists as a component var interactionComponent = new InteractionComponentService(rockContext).GetComponentByEntityId(interactionChannel.Id, PageId.Value, PageTitle); rockContext.SaveChanges(); // Add the interaction if (interactionComponent != null) { ClientInfo client = uaParser.Parse(userAgent); var clientOs = client.OS.ToString(); var clientBrowser = client.UserAgent.ToString(); var interaction = new InteractionService(rockContext).AddInteraction(interactionComponent.Id, null, "View", Url, PersonAliasId, DateViewed, clientBrowser, clientOs, clientType, userAgent, IPAddress, this.SessionId?.AsGuidOrNull()); if (Url.IsNotNullOrWhitespace() && Url.IndexOf("utm_", StringComparison.OrdinalIgnoreCase) >= 0) { var urlParams = HttpUtility.ParseQueryString(Url); interaction.Source = urlParams.Get("utm_source").Truncate(25); interaction.Medium = urlParams.Get("utm_medium").Truncate(25); interaction.Campaign = urlParams.Get("utm_campaign").Truncate(50); interaction.Content = urlParams.Get("utm_content").Truncate(50); } rockContext.SaveChanges(); } } } } }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages) { errorMessages = new List <string>(); var service = new PageShortLinkService(rockContext); // Get the merge fields var mergeFields = GetMergeFields(action); // Get the site int siteId = GetAttributeValue(action, "Site", true).AsInteger(); SiteCache site = SiteCache.Read(siteId); if (site == null) { errorMessages.Add(string.Format("Invalid Site Value")); return(false); } // Get the token string token = GetAttributeValue(action, "Token", true).ResolveMergeFields(mergeFields); if (token.IsNullOrWhiteSpace()) { int tokenLen = GetAttributeValue(action, "RandomTokenLength").AsIntegerOrNull() ?? 7; token = service.GetUniqueToken(site.Id, tokenLen); } // Get the target url string url = GetAttributeValue(action, "Url", true).ResolveMergeFields(mergeFields).RemoveCrLf().Trim(); if (url.IsNullOrWhiteSpace()) { errorMessages.Add("A valid Target Url was not specified."); return(false); } // Save the short link var link = service.GetByToken(token, site.Id); if (link != null) { if (!GetAttributeValue(action, "Overwrite").AsBoolean()) { errorMessages.Add(string.Format("The selected token ('{0}') already exists. Please specify a unique token, or configure action to allow token re-use.", token)); return(false); } else { link.Url = url; } } else { link = new PageShortLink(); link.SiteId = site.Id; link.Token = token; link.Url = url; service.Add(link); } rockContext.SaveChanges(); // Save the resulting short link url var attribute = AttributeCache.Read(GetAttributeValue(action, "Attribute").AsGuid(), rockContext); if (attribute != null) { string domain = new SiteService(rockContext).GetDefaultDomainUri(site.Id).ToString(); string shortLink = domain.EnsureTrailingForwardslash() + token; SetWorkflowAttributeValue(action, attribute.Guid, shortLink); action.AddLogEntry(string.Format("Set '{0}' attribute to '{1}'.", attribute.Name, shortLink)); } return(true); }