public LegaueTableResults() { var cache = new SiteCache(); this.resultTypes = cache.GetLeageResultTypes(); this.LeagueType = this.resultTypes[0]; this.SelectedResultTypeID = 2; }
/// <summary> /// Registers any layouts in a particular site's theme folder that do not currently have any layouts registered in Rock. /// </summary> /// <param name="physWebAppPath">A <see cref="System.String" /> containing the physical path to Rock on the server.</param> /// <param name="site">The site.</param> public static void RegisterLayouts( string physWebAppPath, SiteCache site ) { // Dictionary for block types. Key is path, value is friendly name var list = new Dictionary<string, string>(); // Find all the layouts in theme layout folder... string layoutFolder = Path.Combine(physWebAppPath, string.Format("Themes\\{0}\\Layouts", site.Theme)); // search for all layouts (aspx files) under the physical path var layoutFiles = new List<string>(); DirectoryInfo di = new DirectoryInfo( layoutFolder ); if ( di.Exists ) { foreach(var file in di.GetFiles( "*.aspx", SearchOption.AllDirectories )) { layoutFiles.Add( Path.GetFileNameWithoutExtension( file.Name ) ); } } var rockContext = new RockContext(); var layoutService = new LayoutService( rockContext ); // Get a list of the layout filenames already registered var registered = layoutService.GetBySiteId( site.Id ).Select( l => l.FileName ).Distinct().ToList(); // for each unregistered layout foreach ( string layoutFile in layoutFiles.Except( registered, StringComparer.CurrentCultureIgnoreCase ) ) { // Create new layout record and save it Layout layout = new Layout(); layout.SiteId = site.Id; layout.FileName = layoutFile; layout.Name = layoutFile.SplitCase(); layout.Guid = new Guid(); layoutService.Add( layout ); } rockContext.SaveChanges(); }
public UserManagementController(ApplicationSettings settings, UserServiceBase userManager, SettingsService settingsService, PageService pageService, SearchService searchService, IUserContext context, ListCache listCache, PageViewModelCache pageViewModelCache, SiteCache siteCache, IWikiImporter wikiImporter, IRepository repository, IPluginFactory pluginFactory) : base(settings, userManager, context, settingsService) { _settingsService = settingsService; _pageService = pageService; _searchService = searchService; _listCache = listCache; _pageViewModelCache = pageViewModelCache; _siteCache = siteCache; _wikiImporter = wikiImporter; _repository = repository; _pluginFactory = pluginFactory; }
internal TextPlugin(ISettingsRepository repository, SiteCache siteCache) : this() { Repository = repository; PluginCache = siteCache; }
/// <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> /// 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.Get(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.ToList().Where(a => a.Layout.ToString() == layoutFilter).AsQueryable(); } 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"); } 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> /// Shows the list. /// </summary> public void ShowList() { var rockContext = new RockContext(); int sessionCount = GetAttributeValue(AttributeKey.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.Get(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.Get(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.InteractionChannelId == interactionChannelId); } var pageviewInfo = sessionInfo.GroupBy(s => new { s.InteractionSession, s.InteractionComponent.InteractionChannel, }) .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.InteractionChannel.Name, PageViews = pageViews.Where(p => p.InteractionSessionId == s.Key.InteractionSession.Id && p.InteractionComponent.InteractionChannelId == s.Key.InteractionChannel.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>"; } }
/// <summary> /// Gets the cache object associated with this Entity /// </summary> /// <returns></returns> public IEntityCache GetCacheObject() { return(SiteCache.Get(this.Id)); }
/// <summary> /// Sends the notification. /// </summary> /// <param name="ex">The ex.</param> private void SendNotification(Exception ex) { int?pageId = (Context.Items["Rock:PageId"] ?? string.Empty).ToString().AsIntegerOrNull(); int?siteId = (Context.Items["Rock:SiteId"] ?? string.Empty).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 { // ignore exception } try { ExceptionLogService.LogException(ex, Context, pageId, siteId, personAlias); } catch { // ignore exception } try { bool sendNotification = true; var globalAttributesCache = GlobalAttributesCache.Get(); string filterSettings = globalAttributesCache.GetValue("EmailExceptionsFilter"); if (!string.IsNullOrWhiteSpace(filterSettings)) { // Get the current request's list of server variables var serverVarList = Context.Request.ServerVariables; 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) { switch (nameAndValue[0].ToLower()) { case "type": { if (ex.GetType().Name.ToLower().Contains(nameAndValue[1].ToLower())) { sendNotification = false; } break; } case "source": { if (ex.Source.ToLower().Contains(nameAndValue[1].ToLower())) { sendNotification = false; } break; } case "message": { if (ex.Message.ToLower().Contains(nameAndValue[1].ToLower())) { sendNotification = false; } break; } case "stacktrace": { if (ex.StackTrace.ToLower().Contains(nameAndValue[1].ToLower())) { sendNotification = false; } break; } default: { var serverValue = serverVarList[nameAndValue[0]]; if (serverValue != null && serverValue.ToUpper().Contains(nameAndValue[1].ToUpper().Trim())) { sendNotification = false; } break; } } } } if (!sendNotification) { break; } } } if (!sendNotification) { return; } // get email addresses to send to string emailAddressesList = globalAttributesCache.GetValue("EmailExceptionsList"); if (!string.IsNullOrWhiteSpace(emailAddressesList)) { string[] emailAddresses = emailAddressesList.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (emailAddresses.Length > 0) { string siteName = "Rock"; if (siteId.HasValue) { var site = SiteCache.Get(siteId.Value); if (site != null) { siteName = site.Name; } } var exceptionDetails = string.Format( "An error occurred{0} on the {1} site on page: <br>{2}<p>{3}</p>", person != null ? " for " + person.FullName : string.Empty, siteName, Context.Request.UrlProxySafe().OriginalString, FormatException(ex, string.Empty)); // setup merge codes for email var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null); mergeFields.Add("ExceptionDetails", exceptionDetails); try { mergeFields.Add("Exception", ex); } catch { // ignore } mergeFields.Add("Person", person); var recipients = new List <RockEmailMessageRecipient>(); foreach (string emailAddress in emailAddresses) { recipients.Add(RockEmailMessageRecipient.CreateAnonymous(emailAddress, mergeFields)); } if (recipients.Any()) { var message = new RockEmailMessage(Rock.SystemGuid.SystemCommunication.CONFIG_EXCEPTION_NOTIFICATION.AsGuid()); message.SetRecipients(recipients); message.Send(); } } } } catch { // ignore exception } }
/// <summary> /// Builds the mobile package that can be archived for deployment. /// </summary> /// <param name="applicationId">The application identifier.</param> /// <param name="deviceType">The type of device to build for.</param> /// <param name="versionId">The version identifier to use on this package.</param> /// <returns>An update package for the specified application and device type.</returns> public static UpdatePackage BuildMobilePackage(int applicationId, DeviceType deviceType, int versionId) { var site = SiteCache.Get(applicationId); string applicationRoot = GlobalAttributesCache.Value("PublicApplicationRoot"); var additionalSettings = site.AdditionalSettings.FromJsonOrNull <AdditionalSiteSettings>(); if (additionalSettings.IsNull()) { throw new Exception("Invalid or non-existing AdditionalSettings property on site."); } // // Get all the system phone formats. // var phoneFormats = DefinedTypeCache.Get(SystemGuid.DefinedType.COMMUNICATION_PHONE_COUNTRY_CODE) .DefinedValues .Select(dv => new MobilePhoneFormat { CountryCode = dv.Value, MatchExpression = dv.GetAttributeValue("MatchRegEx"), FormatExpression = dv.GetAttributeValue("FormatRegEx") }) .ToList(); // // Get all the defined values. // var definedTypeGuids = new[] { SystemGuid.DefinedType.LOCATION_COUNTRIES, SystemGuid.DefinedType.LOCATION_ADDRESS_STATE, SystemGuid.DefinedType.PERSON_MARITAL_STATUS }; var definedValues = new List <MobileDefinedValue>(); foreach (var definedTypeGuid in definedTypeGuids) { var definedType = DefinedTypeCache.Get(definedTypeGuid); definedValues.AddRange(definedType.DefinedValues .Select(a => new MobileDefinedValue { Guid = a.Guid, DefinedTypeGuid = a.DefinedType.Guid, Value = a.Value, Description = a.Description, Attributes = GetMobileAttributeValues(a, a.Attributes.Select(b => b.Value)) })); } // // Build CSS Styles // var settings = additionalSettings.DownhillSettings; settings.Platform = DownhillPlatform.Mobile; // ensure the settings are set to mobile var cssStyles = CssUtilities.BuildFramework(settings); // append custom css but parse it for downhill variables if (additionalSettings.CssStyle.IsNotNullOrWhiteSpace()) { cssStyles += CssUtilities.ParseCss(additionalSettings.CssStyle, settings); } // Run Lava on CSS to enable color utilities cssStyles = cssStyles.ResolveMergeFields(Lava.LavaHelper.GetCommonMergeFields(null, null, new Lava.CommonMergeFieldsOptions { GetLegacyGlobalMergeFields = false })); // Get the Rock organization time zone. If not found back to the // OS time zone. If not found just use Greenwich. var timeZoneMapping = NodaTime.TimeZones.TzdbDateTimeZoneSource.Default.WindowsMapping.PrimaryMapping; var timeZoneName = timeZoneMapping.GetValueOrNull(RockDateTime.OrgTimeZoneInfo.Id) ?? timeZoneMapping.GetValueOrNull(TimeZoneInfo.Local.Id) ?? "GMT"; // // Initialize the base update package settings. // var package = new UpdatePackage { ApplicationType = additionalSettings.ShellType ?? ShellType.Blank, ApplicationVersionId = versionId, CssStyles = cssStyles, LoginPageGuid = site.LoginPageId.HasValue ? PageCache.Get(site.LoginPageId.Value)?.Guid : null, ProfileDetailsPageGuid = additionalSettings.ProfilePageId.HasValue ? PageCache.Get(additionalSettings.ProfilePageId.Value)?.Guid : null, PhoneFormats = phoneFormats, DefinedValues = definedValues, TabsOnBottomOnAndroid = additionalSettings.TabLocation == TabLocation.Bottom, HomepageRoutingLogic = additionalSettings.HomepageRoutingLogic, DoNotEnableNotificationsAtLaunch = !additionalSettings.EnableNotificationsAutomatically, TimeZone = timeZoneName, PushTokenUpdateValue = additionalSettings.PushTokenUpdateValue }; // // Setup the appearance settings. // package.AppearanceSettings.BarBackgroundColor = additionalSettings.BarBackgroundColor; package.AppearanceSettings.MenuButtonColor = additionalSettings.MenuButtonColor; package.AppearanceSettings.ActivityIndicatorColor = additionalSettings.ActivityIndicatorColor; package.AppearanceSettings.FlyoutXaml = additionalSettings.FlyoutXaml; package.AppearanceSettings.NavigationBarActionsXaml = additionalSettings.NavigationBarActionXaml; package.AppearanceSettings.LockedPhoneOrientation = additionalSettings.LockedPhoneOrientation; package.AppearanceSettings.LockedTabletOrientation = additionalSettings.LockedTabletOrientation; package.AppearanceSettings.PaletteColors.Add("text-color", additionalSettings.DownhillSettings.TextColor); package.AppearanceSettings.PaletteColors.Add("heading-color", additionalSettings.DownhillSettings.HeadingColor); package.AppearanceSettings.PaletteColors.Add("background-color", additionalSettings.DownhillSettings.BackgroundColor); package.AppearanceSettings.PaletteColors.Add("app-primary", additionalSettings.DownhillSettings.ApplicationColors.Primary); package.AppearanceSettings.PaletteColors.Add("app-secondary", additionalSettings.DownhillSettings.ApplicationColors.Secondary); package.AppearanceSettings.PaletteColors.Add("app-success", additionalSettings.DownhillSettings.ApplicationColors.Success); package.AppearanceSettings.PaletteColors.Add("app-info", additionalSettings.DownhillSettings.ApplicationColors.Info); package.AppearanceSettings.PaletteColors.Add("app-danger", additionalSettings.DownhillSettings.ApplicationColors.Danger); package.AppearanceSettings.PaletteColors.Add("app-warning", additionalSettings.DownhillSettings.ApplicationColors.Warning); package.AppearanceSettings.PaletteColors.Add("app-light", additionalSettings.DownhillSettings.ApplicationColors.Light); package.AppearanceSettings.PaletteColors.Add("app-dark", additionalSettings.DownhillSettings.ApplicationColors.Dark); package.AppearanceSettings.PaletteColors.Add("app-brand", additionalSettings.DownhillSettings.ApplicationColors.Brand); if (site.FavIconBinaryFileId.HasValue) { package.AppearanceSettings.LogoUrl = $"{applicationRoot}/GetImage.ashx?Id={site.FavIconBinaryFileId.Value}"; } // // Load all the layouts. // foreach (var layout in LayoutCache.All().Where(l => l.SiteId == site.Id)) { var mobileLayout = new MobileLayout { LayoutGuid = layout.Guid, Name = layout.Name, LayoutXaml = deviceType == DeviceType.Tablet ? layout.LayoutMobileTablet : layout.LayoutMobilePhone }; package.Layouts.Add(mobileLayout); } // // Load all the pages. // var blockIds = new List <int>(); using (var rockContext = new RockContext()) { AddPagesToUpdatePackage(package, applicationRoot, rockContext, new[] { PageCache.Get(site.DefaultPageId.Value) }); blockIds = new BlockService(rockContext).Queryable() .Where(b => b.Page != null && b.Page.Layout.SiteId == site.Id && b.BlockType.EntityTypeId.HasValue) .OrderBy(b => b.Order) .Select(b => b.Id) .ToList(); } // // Load all the blocks. // foreach (var blockId in blockIds) { var block = BlockCache.Get(blockId); var blockEntityType = block?.BlockType.EntityType.GetEntityType(); if (blockEntityType != null && typeof(Rock.Blocks.IRockMobileBlockType).IsAssignableFrom(blockEntityType)) { var additionalBlockSettings = block.AdditionalSettings.FromJsonOrNull <AdditionalBlockSettings>() ?? new AdditionalBlockSettings(); var mobileBlockEntity = (Rock.Blocks.IRockMobileBlockType)Activator.CreateInstance(blockEntityType); mobileBlockEntity.BlockCache = block; mobileBlockEntity.PageCache = block.Page; mobileBlockEntity.RequestContext = new Net.RockRequestContext(); var attributes = block.Attributes .Select(a => a.Value) .Where(a => a.Categories.Any(c => c.Name == "custommobile")); var mobileBlock = new MobileBlock { PageGuid = block.Page.Guid, Zone = block.Zone, BlockGuid = block.Guid, RequiredAbiVersion = mobileBlockEntity.RequiredMobileAbiVersion, BlockType = mobileBlockEntity.MobileBlockType, ConfigurationValues = mobileBlockEntity.GetBlockInitialization(Blocks.RockClientType.Mobile), Order = block.Order, AttributeValues = GetMobileAttributeValues(block, attributes), PreXaml = block.PreHtml, PostXaml = block.PostHtml, CssClasses = block.CssClass, CssStyles = additionalBlockSettings.CssStyles, ShowOnTablet = additionalBlockSettings.ShowOnTablet, ShowOnPhone = additionalBlockSettings.ShowOnPhone, RequiresNetwork = additionalBlockSettings.RequiresNetwork, NoNetworkContent = additionalBlockSettings.NoNetworkContent, AuthorizationRules = string.Join(",", GetOrderedExplicitAuthorizationRules(block)) }; package.Blocks.Add(mobileBlock); } } // // Load all the campuses. // foreach (var campus in CampusCache.All().Where(c => c.IsActive ?? true)) { var mobileCampus = new MobileCampus { Guid = campus.Guid, Name = campus.Name }; if (campus.Location != null) { if (campus.Location.Latitude.HasValue && campus.Location.Longitude.HasValue) { mobileCampus.Latitude = campus.Location.Latitude; mobileCampus.Longitude = campus.Location.Longitude; } if (!string.IsNullOrWhiteSpace(campus.Location.Street1)) { mobileCampus.Street1 = campus.Location.Street1; mobileCampus.City = campus.Location.City; mobileCampus.State = campus.Location.State; mobileCampus.PostalCode = campus.Location.PostalCode; } } // Get the campus time zone, If not found try the Rock // organization time zone. If not found back to the // OS time zone. If not found just use Greenwich. mobileCampus.TimeZone = timeZoneMapping.GetValueOrNull(campus.TimeZoneId ?? string.Empty) ?? timeZoneMapping.GetValueOrNull(RockDateTime.OrgTimeZoneInfo.Id) ?? timeZoneMapping.GetValueOrNull(TimeZoneInfo.Local.Id) ?? "GMT"; package.Campuses.Add(mobileCampus); } return(package); }
/// <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> /// Gets the site *PageId properties. /// </summary> /// <param name="site">The site.</param> /// <returns>A dictionary of various page ids for the site.</returns> private Dictionary<string, object> GetSiteProperties( SiteCache site ) { var properties = new Dictionary<string, object>(); properties.Add( "DefaultPageId", site.DefaultPageId ); properties.Add( "LoginPageId", site.LoginPageId ); properties.Add( "PageNotFoundPageId", site.PageNotFoundPageId ); properties.Add( "CommunicationPageId", site.CommunicationPageId ); properties.Add( "RegistrationPageId ", site.RegistrationPageId ); properties.Add( "MobilePageId", site.MobilePageId ); return properties; }
/// <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().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> /// Handles the SelectedIndexChanged event of the ddlSite 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 ddlSite_SelectedIndexChanged(object sender, EventArgs e) { LoadLayouts(new RockContext(), SiteCache.Read(ddlSite.SelectedValueAsInt().Value)); }
public Head2Head() { var cache = new SiteCache(); this.players = cache.GetPlayers(); this.Games = new List<GameResult>(); }
/// <summary> /// Uses the DataTokens to contstruct a list of PageAndRouteIds /// If any exist then set page and route ID to the first one found. /// Then loop through the collection looking for a site match, if one is found then set the page and route ID to that /// and the IsSiteMatch property to true. /// </summary> private void GetPageIdFromDataTokens(RequestContext routeRequestContext, SiteCache site, out string pageId, out int routeId, out bool isSiteMatch) { pageId = string.Empty; routeId = 0; isSiteMatch = false; // Pages that use a custom URL route will have the page id in the RouteData.DataTokens collection var pageAndRouteIds = (List <PageAndRouteId>)routeRequestContext.RouteData.DataTokens["PageRoutes"]; if (pageAndRouteIds == null && !pageAndRouteIds.Any()) { return; } // First try to find a match for the site if (site != null) { // See if this is a possible shortlink if (routeRequestContext.RouteData.DataTokens["RouteName"] != null && routeRequestContext.RouteData.DataTokens["RouteName"].ToStringSafe().StartsWith("{")) { // Get the route value string routeValue = routeRequestContext.RouteData.Values.Values.FirstOrDefault().ToStringSafe(); // See if the route value string matches a shortlink for this site. var pageShortLink = new PageShortLinkService(new Rock.Data.RockContext()).GetByToken(routeValue, site.Id); if (pageShortLink != null && pageShortLink.SiteId == site.Id) { // The route entered matches a shortlink for the site, so lets NOT set the page ID for a catch-all route and let the shortlink logic take over. return; } } // Not a short link so cycle through the pages and routes to find a match for the site. foreach (var pageAndRouteId in pageAndRouteIds) { var pageCache = PageCache.Get(pageAndRouteId.PageId); if (pageCache != null && pageCache.Layout != null && pageCache.Layout.SiteId == site.Id) { pageId = pageAndRouteId.PageId.ToStringSafe(); routeId = pageAndRouteId.RouteId; isSiteMatch = true; return; } } } // If the requesting site uses exclusive routes and we didn't find anything for the site then just return if (site.EnableExclusiveRoutes) { return; } // Default to first site/page that is not Exclusive foreach (var pageAndRouteId in pageAndRouteIds) { if (!IsPageExclusiveToAnotherSite(site, pageAndRouteId.PageId)) { // These are safe to assign as defaults pageId = pageAndRouteId.PageId.ToStringSafe(); routeId = pageAndRouteId.RouteId; return; } } }
private void LoadLayouts(SiteCache Site) { ddlLayout.Items.Clear(); var layoutService = new LayoutService(); layoutService.RegisterLayouts( Request.MapPath( "~" ), Site, CurrentPersonId ); foreach ( var layout in layoutService.GetBySiteId( Site.Id ) ) { ddlLayout.Items.Add( new ListItem( layout.Name, layout.Id.ToString() ) ); } }
/// <summary> /// Shows the active users. /// </summary> private void ShowActiveUsers() { int?siteId = GetAttributeValue(AttributeKey.Site).AsIntegerOrNull(); if (!siteId.HasValue || SiteCache.Get(siteId.Value) == null) { lMessages.Text = "<div class='alert alert-warning'>No site is currently configured.</div>"; return; } else { int pageViewCount = GetAttributeValue(AttributeKey.PageViewCount).AsIntegerOrNull() ?? 0; StringBuilder sbUsers = new StringBuilder(); var site = SiteCache.Get(siteId.Value); lSiteName.Text = "<h4>" + site.Name + "</h4>"; lSiteName.Visible = GetAttributeValue(AttributeKey.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.InteractionChannel.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(AttributeKey.PersonProfilePage) != null) { string personProfilePage = GetAttributeValue(AttributeKey.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(AttributeKey.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(AttributeKey.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.InteractionChannel.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> /// Redirects to communication page. /// </summary> /// <param name="site">The site.</param> /// <returns></returns> public static IActionResult RedirectToCommunicationPageResult(this SiteCache site) { return(new RedirectResult(site.CommunicationPageReference.BuildUrl(), false)); }
public IHttpActionResult PostInteractions([FromBody] List <MobileInteractionSession> sessions, Guid?personalDeviceGuid = null) { var person = GetPerson(); var ipAddress = System.Web.HttpContext.Current?.Request?.UserHostAddress; using (var rockContext = new Data.RockContext()) { var interactionChannelService = new InteractionChannelService(rockContext); var interactionComponentService = new InteractionComponentService(rockContext); var interactionSessionService = new InteractionSessionService(rockContext); var interactionService = new InteractionService(rockContext); var userLoginService = new UserLoginService(rockContext); var channelMediumTypeValue = DefinedValueCache.Get(SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE); var pageEntityTypeId = EntityTypeCache.Get(typeof(Model.Page)).Id; // // Check to see if we have a site and the API key is valid. // if (MobileHelper.GetCurrentApplicationSite() == null) { return(StatusCode(System.Net.HttpStatusCode.Forbidden)); } // // Get the personal device identifier if they provided it's unique identifier. // int?personalDeviceId = null; if (personalDeviceGuid.HasValue) { personalDeviceId = new PersonalDeviceService(rockContext).GetId(personalDeviceGuid.Value); } // // Create a quick way to cache data since we have to loop twice. // var interactionComponentLookup = new Dictionary <string, int>(); // // Helper method to get a cache key for looking up the component Id. // string GetComponentCacheKey(MobileInteraction mi) { return($"{mi.AppId}:{mi.PageGuid}:{mi.ChannelGuid}:{mi.ChannelId}:{mi.ComponentId}:{mi.ComponentName}"); } // // Interactions Components will now try to load from cache which // causes problems if we are inside a transaction. So first loop through // everything and make sure all our components and channels exist. // var prePassInteractions = sessions.SelectMany(a => a.Interactions) .DistinctBy(a => GetComponentCacheKey(a)); // // It's safe to do this pre-pass outside the transaction since we are just creating // the channels and components (if necessary), which is going to have to be done at // at some point no matter what. // foreach (var mobileInteraction in prePassInteractions) { // // Lookup the interaction channel, and create it if it doesn't exist // if (mobileInteraction.AppId.HasValue && mobileInteraction.PageGuid.HasValue) { var site = SiteCache.Get(mobileInteraction.AppId.Value); var page = PageCache.Get(mobileInteraction.PageGuid.Value); if (site == null || page == null) { continue; } // // Try to find an existing interaction channel. // var interactionChannelId = InteractionChannelCache.GetChannelIdByTypeIdAndEntityId(channelMediumTypeValue.Id, site.Id, site.Name, pageEntityTypeId, null); // // Get an existing or create a new component. // var interactionComponentId = InteractionComponentCache.GetComponentIdByChannelIdAndEntityId(interactionChannelId, page.Id, page.InternalName); interactionComponentLookup.AddOrReplace(GetComponentCacheKey(mobileInteraction), interactionComponentId); } else if (mobileInteraction.ChannelId.HasValue || mobileInteraction.ChannelGuid.HasValue) { int?interactionChannelId = null; if (mobileInteraction.ChannelId.HasValue) { interactionChannelId = mobileInteraction.ChannelId.Value; } else if (mobileInteraction.ChannelGuid.HasValue) { interactionChannelId = InteractionChannelCache.Get(mobileInteraction.ChannelGuid.Value)?.Id; } if (interactionChannelId.HasValue) { if (mobileInteraction.ComponentId.HasValue) { // Use the provided component identifier. interactionComponentLookup.AddOrReplace(GetComponentCacheKey(mobileInteraction), mobileInteraction.ComponentId.Value); } else if (mobileInteraction.ComponentName.IsNotNullOrWhiteSpace()) { int interactionComponentId; // Get or create a new component with the details we have. if (mobileInteraction.ComponentEntityId.HasValue) { interactionComponentId = InteractionComponentCache.GetComponentIdByChannelIdAndEntityId(interactionChannelId.Value, mobileInteraction.ComponentEntityId, mobileInteraction.ComponentName); } else { var interactionComponent = interactionComponentService.GetComponentByComponentName(interactionChannelId.Value, mobileInteraction.ComponentName); rockContext.SaveChanges(); interactionComponentId = interactionComponent.Id; } interactionComponentLookup.AddOrReplace(GetComponentCacheKey(mobileInteraction), interactionComponentId); } } } } // // Now wrap the actual interaction creation inside a transaction. We should // probably move this so it uses the InteractionTransaction class for better // performance. This is so we can inform the client that either everything // saved or that nothing saved. No partial saves here. // rockContext.WrapTransaction(() => { foreach (var mobileSession in sessions) { var interactionGuids = mobileSession.Interactions.Select(i => i.Guid).ToList(); var existingInteractionGuids = interactionService.Queryable() .Where(i => interactionGuids.Contains(i.Guid)) .Select(i => i.Guid) .ToList(); // // Loop through all interactions that don't already exist and add each one. // foreach (var mobileInteraction in mobileSession.Interactions.Where(i => !existingInteractionGuids.Contains(i.Guid))) { string cacheKey = GetComponentCacheKey(mobileInteraction); if (!interactionComponentLookup.ContainsKey(cacheKey)) { // Shouldn't happen, but just in case. continue; } var interactionComponentId = interactionComponentLookup[cacheKey]; // // Add the interaction // var interaction = interactionService.CreateInteraction(interactionComponentId, mobileInteraction.EntityId, mobileInteraction.Operation, mobileInteraction.Summary, mobileInteraction.Data, person?.PrimaryAliasId, RockDateTime.ConvertLocalDateTimeToRockDateTime(mobileInteraction.DateTime.LocalDateTime), mobileSession.Application, mobileSession.OperatingSystem, mobileSession.ClientType, null, ipAddress, mobileSession.Guid); interaction.Guid = mobileInteraction.Guid; interaction.PersonalDeviceId = personalDeviceId; interaction.RelatedEntityTypeId = mobileInteraction.RelatedEntityTypeId; interaction.RelatedEntityId = mobileInteraction.RelatedEntityId; interaction.ChannelCustom1 = mobileInteraction.ChannelCustom1; interaction.ChannelCustom2 = mobileInteraction.ChannelCustom2; interaction.ChannelCustomIndexed1 = mobileInteraction.ChannelCustomIndexed1; interactionService.Add(interaction); // Attempt to process this as a communication interaction. ProcessCommunicationInteraction(mobileSession, mobileInteraction, rockContext); } } rockContext.SaveChanges(); }); } return(Ok()); }
/// <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) { 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.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); } }
public static void RemoveCache() { SiteCache.RemoveByPattern(@"CK_CommonModel_\S*"); }
/// <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) { Rock.Web.UI.DialogPage dialogPage = this.Page as Rock.Web.UI.DialogPage; if (dialogPage != null) { dialogPage.ValidationGroup = this.BlockValidationGroup; } valSummaryTop.ValidationGroup = this.BlockValidationGroup; // Set the validation group on any custom settings providers. SetValidationGroup(CustomSettingsProviders.Values.ToArray(), this.BlockValidationGroup); int?blockId = PageParameter("BlockId").AsIntegerOrNull(); if (!blockId.HasValue) { return; } var _block = BlockCache.Get(blockId.Value); SiteCache _site = null; // Get site info from Page -> Layout -> Site if (_block.Page != null) { _site = SiteCache.Get(_block.Page.SiteId); } else if (_block.Layout != null) { _site = SiteCache.Get(_block.Layout.SiteId); } else if (_block.SiteId.HasValue) { _site = SiteCache.Get(_block.SiteId.Value); } // Change Pre/Post text labels if this is a mobile block if (_site != null && _site.SiteType == SiteType.Mobile) { cePostHtml.Label = "Post-XAML"; cePreHtml.Label = "Pre-XAML"; } var blockControlType = _block.BlockType.GetCompiledType(); this.ShowCustomGridColumns = typeof(Rock.Web.UI.ICustomGridColumns).IsAssignableFrom(blockControlType); this.ShowCustomGridOptions = typeof(Rock.Web.UI.ICustomGridOptions).IsAssignableFrom(blockControlType); this.ShowMobileOptions = _block.Attributes.Any(a => a.Value.Categories.Any(c => c.Name == "custommobile")); if (!Page.IsPostBack && _block.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson)) { if (_block.Attributes != null) { avcAdvancedAttributes.IncludedCategoryNames = new string[] { "advanced" }; avcAdvancedAttributes.AddEditControls(_block); avcMobileAttributes.IncludedCategoryNames = new string[] { "custommobile" }; avcMobileAttributes.AddEditControls(_block); avcAttributes.ExcludedCategoryNames = new string[] { "advanced", "customsetting", "custommobile" }; avcAttributes.AddEditControls(_block); } foreach (var kvp in CustomSettingsProviders) { kvp.Key.ReadSettingsFromEntity(_block, kvp.Value); } rptProperties.DataSource = GetTabs(_block.BlockType); rptProperties.DataBind(); tbBlockName.Text = _block.Name; tbCssClass.Text = _block.CssClass; cePreHtml.Text = _block.PreHtml; cePostHtml.Text = _block.PostHtml; // Hide the Cache duration block for now; tbCacheDuration.Visible = false; //tbCacheDuration.Text = _block.OutputCacheDuration.ToString(); pwCustomGridColumns.Visible = this.ShowCustomGridColumns; tglEnableStickyHeader.Visible = this.ShowCustomGridOptions; if (this.ShowCustomGridColumns) { CustomGridColumnsConfigState = _block.GetAttributeValue(CustomGridColumnsConfig.AttributeKey).FromJsonOrNull <CustomGridColumnsConfig>() ?? new CustomGridColumnsConfig(); BindCustomColumnsConfig(); } else { CustomGridColumnsConfigState = null; } if (this.ShowCustomGridOptions) { tglEnableStickyHeader.Checked = _block.GetAttributeValue(CustomGridOptionsConfig.EnableStickyHeadersAttributeKey).AsBoolean(); tglEnableDefaultWorkflowLauncher.Checked = _block.GetAttributeValue(CustomGridOptionsConfig.EnableDefaultWorkflowLauncherAttributeKey).AsBoolean(); CustomActionsConfigState = _block.GetAttributeValue(CustomGridOptionsConfig.CustomActionsConfigsAttributeKey).FromJsonOrNull <List <CustomActionConfig> >(); BindCustomActionsConfig(); } else { CustomActionsConfigState = null; } ShowSelectedPane(); } base.OnLoad(e); }
/// <summary> /// Handles the Click event of the btnDeleteConfirm 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 btnDeleteConfirm_Click(object sender, EventArgs e) { bool canDelete = false; var rockContext = new RockContext(); SiteService siteService = new SiteService(rockContext); Site site = siteService.Get(hfSiteId.Value.AsInteger()); LayoutService layoutService = new LayoutService(rockContext); PageService pageService = new PageService(rockContext); PageViewService pageViewService = new PageViewService(rockContext); if (site != null) { var sitePages = new List <int> { site.DefaultPageId ?? -1, site.LoginPageId ?? -1, site.RegistrationPageId ?? -1, site.PageNotFoundPageId ?? -1 }; foreach (var pageView in pageViewService .Queryable() .Where(t => t.Page != null && t.Page.Layout != null && t.Page.Layout.SiteId == site.Id)) { pageView.Page = null; pageView.PageId = null; } var pageQry = pageService.Queryable("Layout") .Where(t => t.Layout.SiteId == site.Id || sitePages.Contains(t.Id)); pageService.DeleteRange(pageQry); var layoutQry = layoutService.Queryable() .Where(l => l.SiteId == site.Id); layoutService.DeleteRange(layoutQry); rockContext.SaveChanges(true); string errorMessage; canDelete = siteService.CanDelete(site, out errorMessage, includeSecondLvl: true); if (!canDelete) { mdDeleteWarning.Show(errorMessage, ModalAlertType.Alert); return; } siteService.Delete(site); rockContext.SaveChanges(); SiteCache.Flush(site.Id); } NavigateToParentPage(); }
/// <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); pdAuditDetails.SetEntity(layout, ResolveRockUrl("~")); } if (layout == null && siteId.HasValue) { var site = SiteCache.Get(siteId.Value); if (site != null) { layout = new Layout { Id = 0 }; layout.SiteId = siteId.Value; } // hide the panel drawer that show created and last modified dates pdAuditDetails.Visible = false; } 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> /// 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); } }
public void Setup() { _siteCache = new SiteCache(ApplicationSettings, CacheMock.RoadkillCache); }
/// <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 siteCookie = requestContext.HttpContext.Request.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 = SiteCache.GetSiteByDomain(requestContext.HttpContext.Request.Url.Host); if (site == null) { // Use last site 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(requestContext.HttpContext.Request.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) { // 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) { // 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}", 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); 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, 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> /// Determine the logical page being requested by evaluating the RouteData, or QueryString and /// then loading the appropriate layout (ASPX) page /// /// Pick URL on the following priority order: /// 1. PageId /// 2. Route match and site match /// 3. ShortLink match and site match /// 4. Route and no site match /// 5. ShortLink with no site match /// 6. If there is no routing info in the request then set to default page /// 7. 404 if route does not exist /// /// </summary> /// <param name="requestContext"></param> /// <returns></returns> System.Web.IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext) { string pageId = string.Empty; int routeId = 0; bool isSiteMatch = false; Dictionary <string, string> parms; string host; HttpRequestBase routeHttpRequest; HttpCookie siteCookie; // Context cannot be null if (requestContext == null) { throw new ArgumentNullException("requestContext"); } try { routeHttpRequest = requestContext.HttpContext.Request; siteCookie = routeHttpRequest.Cookies["last_site"]; parms = new Dictionary <string, string>(); host = WebRequestHelper.GetHostNameFromRequest(HttpContext.Current); if (requestContext.RouteData.Values["PageId"] != null) { // Pages using the default routing URL will have the page id in the RouteData.Values collection pageId = ( string )requestContext.RouteData.Values["PageId"]; isSiteMatch = true; } else if (requestContext.RouteData.DataTokens["PageRoutes"] != null) { SiteCache site = GetSite(routeHttpRequest, host, siteCookie); // Pages that use a custom URL route will have the page id in the RouteData.DataTokens collection GetPageIdFromDataTokens(requestContext, site, out pageId, out routeId, out isSiteMatch); foreach (var routeParm in requestContext.RouteData.Values) { parms.Add(routeParm.Key, ( string )routeParm.Value); } } else if (((System.Web.Routing.Route)requestContext.RouteData.Route).Url.IsNullOrWhiteSpace()) { // if we don't have routing info then set the page ID to the default page for the site. // Get the site, if not found use the default site SiteCache site = GetSite(routeHttpRequest, host, siteCookie); if (site == null) { site = SiteCache.Get(SystemGuid.Site.SITE_ROCK_INTERNAL.AsGuid()); } if (site.DefaultPageId.HasValue) { pageId = site.DefaultPageId.Value.ToString(); isSiteMatch = true; } else { throw new SystemException("Invalid Site Configuration"); } } // If the page ID and site has not yet been matched if (string.IsNullOrEmpty(pageId) || !isSiteMatch) { SiteCache site = GetSite(routeHttpRequest, host, siteCookie); // if not found use the default site if (site == null) { site = SiteCache.Get(SystemGuid.Site.SITE_ROCK_INTERNAL.AsGuid()); } // Are shortlinks enabled for this site? If so, check for a matching shortlink route. if (site != null && site.EnabledForShortening) { // Check to see if this is a short link route string shortlink = null; if (requestContext.RouteData.Values.ContainsKey("shortlink")) { shortlink = requestContext.RouteData.Values["shortlink"].ToString(); } else { // Because we implemented shortlinks using a {shortlink} (catchall) route, it's // possible the organization added a custom {catchall} route (at root level; no slashes) // and it is overriding our shortlink route. If they did, use it for a possible 'shortlink' // route match. if (requestContext.RouteData.DataTokens["RouteName"] != null && requestContext.RouteData.DataTokens["RouteName"].ToStringSafe().StartsWith("{")) { var routeName = requestContext.RouteData.DataTokens["RouteName"].ToStringSafe().Trim(new Char[] { '{', '}' }); shortlink = requestContext.RouteData.Values[routeName].ToStringSafe(); } } // If shortlink have the same name as route and route's site did not match, then check if shortlink site match. if (shortlink.IsNullOrWhiteSpace() && requestContext.RouteData.DataTokens["RouteName"] != null) { shortlink = requestContext.RouteData.DataTokens["RouteName"].ToString(); } if (shortlink.IsNotNullOrWhiteSpace()) { using (var rockContext = new Rock.Data.RockContext()) { var pageShortLink = new PageShortLinkService(rockContext).GetByToken(shortlink, site.Id); if (pageShortLink != null && (pageShortLink.SiteId == site.Id || requestContext.RouteData.DataTokens["RouteName"] == null)) { pageId = string.Empty; routeId = 0; string trimmedUrl = pageShortLink.Url.RemoveCrLf().Trim(); var transaction = new ShortLinkTransaction(); transaction.PageShortLinkId = pageShortLink.Id; transaction.Token = pageShortLink.Token; transaction.Url = trimmedUrl; if (requestContext.HttpContext.User != null) { transaction.UserName = requestContext.HttpContext.User.Identity.Name; } transaction.DateViewed = RockDateTime.Now; transaction.IPAddress = WebRequestHelper.GetClientIpAddress(routeHttpRequest); transaction.UserAgent = routeHttpRequest.UserAgent ?? string.Empty; RockQueue.TransactionQueue.Enqueue(transaction); requestContext.HttpContext.Response.Redirect(trimmedUrl); return(null); } } } // If site has been enabled for mobile redirect, then we'll need to check what type of device is being used if (site.EnableMobileRedirect) { // get the device type string u = routeHttpRequest.UserAgent; var clientType = InteractionDeviceType.GetClientType(u); bool redirect = false; // first check if device is a mobile device if (clientType == "Mobile") { redirect = true; } // if not, mobile device and tables should be redirected also, check if device is a tablet if (!redirect && site.RedirectTablets && clientType == "Tablet") { redirect = true; } if (redirect) { if (site.MobilePageId.HasValue) { pageId = site.MobilePageId.Value.ToString(); routeId = 0; } else if (!string.IsNullOrWhiteSpace(site.ExternalUrl)) { requestContext.HttpContext.Response.Redirect(site.ExternalUrl); return(null); } } } } } PageCache page = null; if (!string.IsNullOrEmpty(pageId)) { int pageIdNumber = 0; if (int.TryParse(pageId, out pageIdNumber)) { page = PageCache.Get(pageIdNumber); // If it was not a siteMatch and the page is not a system page // and 'Enable Route Domain Matching' is true, then we can't // match the page and therefore must set it back to null // for 404 handling. if (page != null && !isSiteMatch && !page.IsSystem && GlobalAttributesCache.Get().GetValue("core_EnableRouteDomainMatching").AsBoolean()) { page = null; } } } if (page == null) { // try to get site's 404 page SiteCache site = GetSite(routeHttpRequest, host, siteCookie); if (site != null && site.PageNotFoundPageId != null) { if (Convert.ToBoolean(GlobalAttributesCache.Get().GetValue("Log404AsException"))) { Rock.Model.ExceptionLogService.LogException( new Exception($"404 Error: {routeHttpRequest.Url.AbsoluteUri}"), requestContext.HttpContext.ApplicationInstance.Context); } page = PageCache.Get(site.PageNotFoundPageId ?? 0); requestContext.HttpContext.Response.StatusCode = 404; requestContext.HttpContext.Response.TrySkipIisCustomErrors = true; } else { // no 404 page found for the site, return the default 404 error page return((System.Web.UI.Page)BuildManager.CreateInstanceFromVirtualPath("~/Http404Error.aspx", typeof(System.Web.UI.Page))); } } CreateOrUpdateSiteCookie(siteCookie, requestContext, page); string theme = page.Layout.Site.Theme; string layout = page.Layout.FileName; string layoutPath = PageCache.FormatPath(theme, layout); try { return(CreateRockPage(page, layoutPath, routeId, parms, routeHttpRequest)); } catch (System.Web.HttpException) { // The Selected theme and/or layout didn't exist so try to use the layout in the default theme. theme = "Rock"; // Verify that Layout exists in the default theme directory and if not try use the default layout of the default theme string layoutPagePath = string.Format("~/Themes/Rock/Layouts/{0}.aspx", layout); if (!File.Exists(requestContext.HttpContext.Server.MapPath(layoutPagePath))) { layout = "FullWidth"; } layoutPath = PageCache.FormatPath(theme, layout); return(CreateRockPage(page, layoutPath, routeId, parms, routeHttpRequest)); } } catch (Exception ex) { if (requestContext.HttpContext != null) { requestContext.HttpContext.Cache["RockExceptionOrder"] = "66"; requestContext.HttpContext.Cache["RockLastException"] = ex; } return((System.Web.UI.Page)BuildManager.CreateInstanceFromVirtualPath("~/Error.aspx", typeof(System.Web.UI.Page))); } }
public PageService(ApplicationSettings settings, IRepository repository, SearchService searchService, PageHistoryService historyService, IUserContext context, ListCache listCache, ModelCache modelCache, PageViewModelCache pageViewModelCache, SiteCache sitecache, IPluginFactory pluginFactory) : base(settings, repository) { _searchService = searchService; _markupConverter = new MarkupConverter(settings, repository, pluginFactory); _historyService = historyService; _context = context; _listCache = listCache; _modelCache = modelCache; _pageViewModelCache = pageViewModelCache; _siteCache = sitecache; _pluginFactory = pluginFactory; _markupLinkUpdater = new MarkupLinkUpdater(_markupConverter.Parser); }
public MenuParser(MarkupConverter markupConverter, ISettingsRepository settingsRepository, SiteCache siteCache, IUserContext userContext) { _markupConverter = markupConverter; _settingsRepository = settingsRepository; _siteCache = siteCache; _userContext = userContext; }
/// <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; try { var user = UserLoginService.GetCurrentUser(); if (user != null && user.Person != null) { 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", "An error occurred on the " + siteName + " site on page: <br>" + Context.Request.Url.OriginalString + "<p>" + FormatException(ex, "")); // 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); } } } } catch { } }
public CacheController(ApplicationSettings settings, UserServiceBase userService, SettingsService settingsService, IUserContext context, ListCache listCache, PageViewModelCache pageViewModelCache, SiteCache siteCache) : base(settings, userService, context, settingsService) { _settingsService = settingsService; _listCache = listCache; _pageViewModelCache = pageViewModelCache; _siteCache = siteCache; }
/// <summary> /// Loads the layouts. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="site">The site.</param> private void LoadLayouts( RockContext rockContext, SiteCache site ) { LayoutService.RegisterLayouts( Request.MapPath( "~" ), site ); ddlLayout.Items.Clear(); var layoutService = new LayoutService( rockContext ); foreach ( var layout in layoutService.GetBySiteId( site.Id ) ) { ddlLayout.Items.Add( new ListItem( layout.Name, layout.Id.ToString() ) ); } }
public Game() { var cache = new SiteCache(); this.players = cache.GetPlayers(); }