private Template GetTemplate()
        {
            RockMemoryCache cache    = RockMemoryCache.Default;
            Template        template = null;

            if (cache[TemplateCacheKey] != null)
            {
                template = (Template)cache[TemplateCacheKey];
            }
            else
            {
                template = Template.Parse(GetAttributeValue("Template"));
                cache.Set(TemplateCacheKey, template, new CacheItemPolicy());
            }

            return(template);
        }
        public override void Up()
        {
            // Make sure this is unique
            if (DefinedTypeCache.Read(new Guid("0913F7A9-A2BF-479C-96EC-6CDB56310A83")) == null)
            {
                RockMigrationHelper.AddDefinedType("Global", "Hospitals", "Hospital List", "0913F7A9-A2BF-479C-96EC-6CDB56310A83", @"");
                RockMigrationHelper.AddDefinedTypeAttribute("0913F7A9-A2BF-479C-96EC-6CDB56310A83", "9C204CD0-1233-41C5-818A-C5DA439445AA", "City", "Qualifier2", "", 0, "", "CEDC60C1-0F9E-4FE2-BE62-41716813C968");
                RockMigrationHelper.AddDefinedTypeAttribute("0913F7A9-A2BF-479C-96EC-6CDB56310A83", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Notes", "Qualifier8", "", 0, "", "C47A879E-F737-4156-A1FF-B7C465FDB9BC");
                RockMigrationHelper.AddDefinedTypeAttribute("0913F7A9-A2BF-479C-96EC-6CDB56310A83", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Phone", "Qualifier5", "", 0, "", "A4E41679-2CE6-479F-84D4-6821B25E3648");
                RockMigrationHelper.AddDefinedTypeAttribute("0913F7A9-A2BF-479C-96EC-6CDB56310A83", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Speed Dial", "Qualifier6", "", 0, "", "D97EC9DE-5D6A-42FD-B4CE-0516FD5455F6");
                RockMigrationHelper.AddDefinedTypeAttribute("0913F7A9-A2BF-479C-96EC-6CDB56310A83", "9C204CD0-1233-41C5-818A-C5DA439445AA", "State", "Qualifier3", "", 0, "", "239E507C-7C1B-4B4D-84D4-33C368843F04");
                RockMigrationHelper.AddDefinedTypeAttribute("0913F7A9-A2BF-479C-96EC-6CDB56310A83", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Street Address", "Qualifier1", "", 0, "", "73AC0DCE-CE90-4835-AAE7-E98B08F52E9C");
                RockMigrationHelper.AddDefinedTypeAttribute("0913F7A9-A2BF-479C-96EC-6CDB56310A83", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Zip", "Qualifier4", "", 0, "", "46A83E00-D530-48AD-B935-52C015DCA901");
                RockMigrationHelper.AddDefinedValue("0913F7A9-A2BF-479C-96EC-6CDB56310A83", "Sample Hospital", "", "0997ACB6-A4B4-4766-B573-3C44D14DF342", false);
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF342", "239E507C-7C1B-4B4D-84D4-33C368843F04", @"KY");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF342", "46A83E00-D530-48AD-B935-52C015DCA901", @"40023");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF342", "73AC0DCE-CE90-4835-AAE7-E98B08F52E9C", @"1 Main St");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF342", "A4E41679-2CE6-479F-84D4-6821B25E3648", @"(502) 111-1111");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF342", "C47A879E-F737-4156-A1FF-B7C465FDB9BC", @"");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF342", "CEDC60C1-0F9E-4FE2-BE62-41716813C968", @"Louisville");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF342", "D97EC9DE-5D6A-42FD-B4CE-0516FD5455F6", @"");
            }

            // Make sure this is unique
            if (DefinedTypeCache.Read(new Guid("4573E600-4E00-4BE9-BA92-D17093C735D6")) == null)
            {
                RockMigrationHelper.AddDefinedType("Global", "Nursing Homes", "Nursing Home List", "4573E600-4E00-4BE9-BA92-D17093C735D6", @"");
                RockMigrationHelper.AddDefinedTypeAttribute("4573E600-4E00-4BE9-BA92-D17093C735D6", "9C204CD0-1233-41C5-818A-C5DA439445AA", "City", "Qualifier2", "", 0, "", "CEDC60C1-0F9E-4FE2-BE62-41716813C969");
                RockMigrationHelper.AddDefinedTypeAttribute("4573E600-4E00-4BE9-BA92-D17093C735D6", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Notes", "Qualifier8", "", 0, "", "C47A879E-F737-4156-A1FF-B7C465FDB9BD");
                RockMigrationHelper.AddDefinedTypeAttribute("4573E600-4E00-4BE9-BA92-D17093C735D6", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Phone", "Qualifier5", "", 0, "", "A4E41679-2CE6-479F-84D4-6821B25E3649");
                RockMigrationHelper.AddDefinedTypeAttribute("4573E600-4E00-4BE9-BA92-D17093C735D6", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Pastoral Minister", "Qualifier6", "", 0, "", "D97EC9DE-5D6A-42FD-B4CE-0516FD5455F7");
                RockMigrationHelper.AddDefinedTypeAttribute("4573E600-4E00-4BE9-BA92-D17093C735D6", "9C204CD0-1233-41C5-818A-C5DA439445AA", "State", "Qualifier3", "", 0, "", "239E507C-7C1B-4B4D-84D4-33C368843F05");
                RockMigrationHelper.AddDefinedTypeAttribute("4573E600-4E00-4BE9-BA92-D17093C735D6", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Street Address", "Qualifier1", "", 0, "", "73AC0DCE-CE90-4835-AAE7-E98B08F52E9D");
                RockMigrationHelper.AddDefinedTypeAttribute("4573E600-4E00-4BE9-BA92-D17093C735D6", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Zip", "Qualifier4", "", 0, "", "46A83E00-D530-48AD-B935-52C015DCA902");
                RockMigrationHelper.AddDefinedValue("4573E600-4E00-4BE9-BA92-D17093C735D6", "Sample Nursing Home", "", "0997ACB6-A4B4-4766-B573-3C44D14DF343", false);
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF343", "239E507C-7C1B-4B4D-84D4-33C368843F05", @"KY");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF343", "46A83E00-D530-48AD-B935-52C015DCA902", @"40023");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF343", "73AC0DCE-CE90-4835-AAE7-E98B08F52E9D", @"2 Main St");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF343", "A4E41679-2CE6-479F-84D4-6821B25E3649", @"(502) 111-1111");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF343", "C47A879E-F737-4156-A1FF-B7C465FDB9BD", @"");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF343", "CEDC60C1-0F9E-4FE2-BE62-41716813C969", @"Louisville");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF343", "D97EC9DE-5D6A-42FD-B4CE-0516FD5455F7", @"John Adams");
            }
            // Make sure to clear the Rock Cache so the defined type above will be there
            RockMemoryCache.Clear();
        }
        /// <summary>
        /// Gets the or add existing.
        /// </summary>
        /// <param name="factory">The factory.</param>
        /// <returns></returns>
        private static List <ConnectionWorkflow> GetOrAddExisting(Func <List <ConnectionWorkflow> > factory)
        {
            RockMemoryCache cache = RockMemoryCache.Default;

            var value = cache.Get(CACHE_KEY) as List <ConnectionWorkflow>;

            if (value != null)
            {
                return(value);
            }

            value = factory();
            if (value != null)
            {
                cache.Set(CACHE_KEY, value, new CacheItemPolicy());
            }
            return(value);
        }
Beispiel #4
0
        /// <summary>
        /// Gets the or add existing.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="valueFactory">The value factory.</param>
        /// <returns></returns>
        public static Role GetOrAddExisting(string key, Func <Role> valueFactory)
        {
            RockMemoryCache cache = RockMemoryCache.Default;

            object cacheValue = cache.Get(key);

            if (cacheValue != null)
            {
                return((Role)cacheValue);
            }

            Role value = valueFactory();

            if (value != null)
            {
                cache.Set(key, value, new CacheItemPolicy());
            }
            return(value);
        }
Beispiel #5
0
        private Template GetTemplate()
        {
            string cacheKey = CacheKey();

            RockMemoryCache cache    = RockMemoryCache.Default;
            Template        template = cache[cacheKey] as Template;

            if (template != null)
            {
                return(template);
            }
            else
            {
                template = Template.Parse(GetAttributeValue("Template"));

                var cachePolicy = new CacheItemPolicy();
                cache.Set(cacheKey, template, cachePolicy);

                return(template);
            }
        }
        /// <summary>
        /// Flushes the cached triggers.
        /// </summary>
        public static void FlushCachedTriggers()
        {
            RockMemoryCache cache = RockMemoryCache.Default;

            cache.Remove(CACHE_KEY);
        }
        /// <summary>
        /// Handles the Start event of the Application 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 Application_Start(object sender, EventArgs e)
        {
            try
            {
                var stopwatch = System.Diagnostics.Stopwatch.StartNew();
                LogMessage(APP_LOG_FILENAME, "Application Starting...");

                if (System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment)
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("Application_Start: {0}", RockDateTime.Now.ToString("hh:mm:ss.FFF")));
                }

                // Clear all cache
                RockMemoryCache.Clear();

                // Get a db context
                using (var rockContext = new RockContext())
                {
                    if (System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment)
                    {
                        try
                        {
                            // default Initializer is CreateDatabaseIfNotExists, so set it to NULL so that nothing happens if there isn't a database yet
                            Database.SetInitializer <Rock.Data.RockContext>(null);
                            new AttributeService(rockContext).Get(0);
                            System.Diagnostics.Debug.WriteLine(string.Format("ConnectToDatabase {2}/{1} - {0} ms", stopwatch.Elapsed.TotalMilliseconds, rockContext.Database.Connection.Database, rockContext.Database.Connection.DataSource));
                        }
                        catch
                        {
                            // Intentionally Blank
                        }
                    }

                    //// Run any needed Rock and/or plugin migrations
                    //// NOTE: MigrateDatabase must be the first thing that touches the database to help prevent EF from creating empty tables for a new database
                    MigrateDatabase(rockContext);

                    // Preload the commonly used objects
                    stopwatch.Restart();
                    LoadCacheObjects(rockContext);

                    if (System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment)
                    {
                        System.Diagnostics.Debug.WriteLine(string.Format("LoadCacheObjects - {0} ms", stopwatch.Elapsed.TotalMilliseconds));
                    }

                    // Run any plugin migrations
                    MigratePlugins(rockContext);

                    RegisterRoutes(rockContext, RouteTable.Routes);

                    // Configure Rock Rest API
                    stopwatch.Restart();
                    GlobalConfiguration.Configure(Rock.Rest.WebApiConfig.Register);
                    if (System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment)
                    {
                        System.Diagnostics.Debug.WriteLine(string.Format("Configure WebApiConfig - {0} ms", stopwatch.Elapsed.TotalMilliseconds));
                        stopwatch.Restart();
                    }

                    // setup and launch the jobs infrastructure if running under IIS
                    bool runJobsInContext = Convert.ToBoolean(ConfigurationManager.AppSettings["RunJobsInIISContext"]);
                    if (runJobsInContext)
                    {
                        ISchedulerFactory sf;

                        // create scheduler
                        sf    = new StdSchedulerFactory();
                        sched = sf.GetScheduler();

                        // get list of active jobs
                        ServiceJobService jobService = new ServiceJobService(rockContext);
                        foreach (ServiceJob job in jobService.GetActiveJobs().ToList())
                        {
                            const string errorLoadingStatus = "Error Loading Job";
                            try
                            {
                                IJobDetail jobDetail  = jobService.BuildQuartzJob(job);
                                ITrigger   jobTrigger = jobService.BuildQuartzTrigger(job);

                                sched.ScheduleJob(jobDetail, jobTrigger);

                                //// if the last status was an error, but we now loaded successful, clear the error
                                // also, if the last status was 'Running', clear that status because it would have stopped if the app restarted
                                if (job.LastStatus == errorLoadingStatus || job.LastStatus == "Running")
                                {
                                    job.LastStatusMessage = string.Empty;
                                    job.LastStatus        = string.Empty;
                                    rockContext.SaveChanges();
                                }
                            }
                            catch (Exception ex)
                            {
                                // log the error
                                LogError(ex, null);

                                // create a friendly error message
                                string message = string.Format("Error loading the job: {0}.\n\n{2}", job.Name, job.Assembly, ex.Message);
                                job.LastStatusMessage = message;
                                job.LastStatus        = errorLoadingStatus;
                                rockContext.SaveChanges();
                            }
                        }

                        // set up the listener to report back from jobs as they complete
                        sched.ListenerManager.AddJobListener(new RockJobListener(), EverythingMatcher <JobKey> .AllJobs());

                        // start the scheduler
                        sched.Start();
                    }

                    // Force the static Liquid class to get instantiated so that the standard filters are loaded prior
                    // to the custom RockFilter.  This is to allow the custom 'Date' filter to replace the standard
                    // Date filter.
                    Liquid.UseRubyDateFormat = false;

                    //// NOTE: This means that template filters will also use CSharpNamingConvention
                    //// For example the dotliquid documentation says to do this for formatting dates:
                    //// {{ some_date_value | date:"MMM dd, yyyy" }}
                    //// However, if CSharpNamingConvention is enabled, it needs to be:
                    //// {{ some_date_value | Date:"MMM dd, yyyy" }}
                    Template.NamingConvention = new DotLiquid.NamingConventions.CSharpNamingConvention();
                    Template.FileSystem       = new RockWeb.LavaFileSystem();
                    Template.RegisterSafeType(typeof(Enum), o => o.ToString());
                    Template.RegisterFilter(typeof(Rock.Lava.RockFilters));

                    // add call back to keep IIS process awake at night and to provide a timer for the queued transactions
                    AddCallBack();

                    Rock.Security.Authorization.Load();
                }

                EntityTypeService.RegisterEntityTypes(Server.MapPath("~"));
                FieldTypeService.RegisterFieldTypes(Server.MapPath("~"));

                BundleConfig.RegisterBundles(BundleTable.Bundles);

                // mark any user login stored as 'IsOnline' in the database as offline
                MarkOnlineUsersOffline();

                SqlServerTypes.Utilities.LoadNativeAssemblies(Server.MapPath("~"));

                LogMessage(APP_LOG_FILENAME, "Application Started Successfully");
                if (System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment)
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("Application_Started_Successfully: {0}", RockDateTime.Now.ToString("hh:mm:ss.FFF")));
                }
            }
            catch (Exception ex)
            {
                SetError66();
                throw (new Exception("Error occurred during application startup", ex));
            }
        }
Beispiel #8
0
        /// <summary>
        /// Flushes this instance.
        /// </summary>
        public static void Flush()
        {
            RockMemoryCache cache = RockMemoryCache.Default;

            cache.Remove(SystemSettings.CacheKey());
        }
Beispiel #9
0
        /// <summary>
        /// Handles the BlockUpdated event of the PageMenu 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 PageMenu_BlockUpdated(object sender, EventArgs e)
        {
            RockMemoryCache cache = RockMemoryCache.Default;

            cache.Remove(CacheKey());
        }
        /// <summary>
        /// Writes the <see cref="T:System.Web.UI.WebControls.CompositeControl" /> content to the specified <see cref="T:System.Web.UI.HtmlTextWriter" /> object, for display on the client.
        /// </summary>
        /// <param name="writer">An <see cref="T:System.Web.UI.HtmlTextWriter" /> that represents the output stream to render HTML content on the client.</param>
        protected override void Render(HtmlTextWriter writer)
        {
            var blockCache = _rockBlock.BlockCache;

            string preHtml   = string.Empty;
            string postHtml  = string.Empty;
            string appRoot   = _rockBlock.ResolveRockUrl("~/");
            string themeRoot = _rockBlock.ResolveRockUrl("~~/");

            if (_rockBlock.Visible)
            {
                if (!string.IsNullOrWhiteSpace(blockCache.PreHtml))
                {
                    preHtml = blockCache.PreHtml.Replace("~~/", themeRoot).Replace("~/", appRoot);
                }

                if (!string.IsNullOrWhiteSpace(blockCache.PostHtml))
                {
                    postHtml = blockCache.PostHtml.Replace("~~/", themeRoot).Replace("~/", appRoot);
                }

                if (preHtml.HasMergeFields() || postHtml.HasMergeFields())
                {
                    var mergeFields = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields(_rockBlock.CurrentPerson);
                    mergeFields.Add("CurrentPerson", _rockBlock.CurrentPerson);
                    mergeFields.Add("Campuses", CampusCache.All());
                    mergeFields.Add("PageParameter", _rockBlock.PageParameters());

                    var contextObjects = new Dictionary <string, object>();
                    foreach (var contextEntityType in _rockBlock.RockPage.GetContextEntityTypes())
                    {
                        var contextEntity = _rockBlock.RockPage.GetCurrentContext(contextEntityType);
                        if (contextEntity != null && contextEntity is DotLiquid.ILiquidizable)
                        {
                            var type = Type.GetType(contextEntityType.AssemblyName ?? contextEntityType.Name);
                            if (type != null)
                            {
                                contextObjects.Add(type.Name, contextEntity);
                            }
                        }
                    }

                    if (contextObjects.Any())
                    {
                        mergeFields.Add("Context", contextObjects);
                    }

                    preHtml  = preHtml.ResolveMergeFields(mergeFields);
                    postHtml = postHtml.ResolveMergeFields(mergeFields);
                }
            }

            StringBuilder  sbOutput = null;
            StringWriter   swOutput = null;
            HtmlTextWriter twOutput = null;

            if (_rockBlock.BlockCache.OutputCacheDuration > 0)
            {
                sbOutput = new StringBuilder();
                swOutput = new StringWriter(sbOutput);
                twOutput = new HtmlTextWriter(swOutput);
            }

            // Create block wrapper
            string blockTypeCss = blockCache.BlockType != null ? blockCache.BlockType.Name : "";
            var    parts        = blockTypeCss.Split(new char[] { '>' });

            if (parts.Length > 1)
            {
                blockTypeCss = parts[parts.Length - 1].Trim();
            }
            blockTypeCss = blockTypeCss.Replace(' ', '-').ToLower();
            string blockInstanceCss = "block-instance " +
                                      blockTypeCss +
                                      (string.IsNullOrWhiteSpace(blockCache.CssClass) ? "" : " " + blockCache.CssClass.Trim()) +
                                      (_rockBlock.UserCanEdit || _rockBlock.UserCanAdministrate ? " can-configure " : "");

            writer.Write(preHtml);
            writer.AddAttribute(HtmlTextWriterAttribute.Id, string.Format("bid_{0}", blockCache.Id));
            writer.AddAttribute("data-zone-location", blockCache.BlockLocation.ToString());
            writer.AddAttribute(HtmlTextWriterAttribute.Class, blockInstanceCss);
            writer.RenderBeginTag(HtmlTextWriterTag.Div);

            writer.AddAttribute(HtmlTextWriterAttribute.Class, "block-content");
            writer.RenderBeginTag(HtmlTextWriterTag.Div);

            if (blockCache.OutputCacheDuration > 0)
            {
                twOutput.Write(preHtml);
                twOutput.AddAttribute(HtmlTextWriterAttribute.Id, string.Format("bid_{0}", blockCache.Id));
                twOutput.AddAttribute("data-zone-location", blockCache.BlockLocation.ToString());
                twOutput.AddAttribute(HtmlTextWriterAttribute.Class, blockInstanceCss);
                twOutput.RenderBeginTag(HtmlTextWriterTag.Div);

                twOutput.AddAttribute(HtmlTextWriterAttribute.Class, "block-content");
                twOutput.RenderBeginTag(HtmlTextWriterTag.Div);
            }

            if (_rockBlock.PageCache.IncludeAdminFooter && _adminControls.Any())
            {
                // Add the config buttons
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "block-configuration config-bar");
                writer.RenderBeginTag(HtmlTextWriterTag.Div);

                writer.AddAttribute(HtmlTextWriterAttribute.Href, "#");
                writer.RenderBeginTag(HtmlTextWriterTag.A);
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "fa fa-arrow-circle-right");
                writer.RenderBeginTag(HtmlTextWriterTag.I);
                writer.RenderEndTag();
                writer.RenderEndTag();

                writer.AddAttribute(HtmlTextWriterAttribute.Class, "block-configuration-bar");
                writer.RenderBeginTag(HtmlTextWriterTag.Div);

                writer.RenderBeginTag(HtmlTextWriterTag.Span);
                writer.Write(string.IsNullOrWhiteSpace(blockCache.Name) ? blockCache.BlockType.Name : blockCache.Name);
                writer.RenderEndTag();

                foreach (Control configControl in _adminControls)
                {
                    configControl.RenderControl(writer);
                }

                writer.RenderEndTag();  // block-configuration-bar
                writer.RenderEndTag();  // config-bar
            }

            _rockBlock.RenderControl(writer);

            writer.RenderEndTag();  // block-content
            writer.RenderEndTag();  // block-instance
            writer.Write(postHtml);

            if (blockCache.OutputCacheDuration > 0)
            {
                base.Render(twOutput);

                twOutput.RenderEndTag();  // block-content
                twOutput.RenderEndTag();  // block-instance
                twOutput.Write(postHtml);

                CacheItemPolicy cacheDuration = new CacheItemPolicy();
                cacheDuration.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(blockCache.OutputCacheDuration);

                RockMemoryCache cache          = RockMemoryCache.Default;
                string          _blockCacheKey = string.Format("Rock:BlockOutput:{0}", blockCache.Id);
                cache.Set(_blockCacheKey, sbOutput.ToString(), cacheDuration);
            }
        }
Beispiel #11
0
        /// <summary>
        /// Flushes the cached HTML for a specific blockId or, if specified, a specific entityValue (Entity Context)
        /// </summary>
        /// <param name="blockId">The block identifier.</param>
        /// <param name="entityValue">The entity value.</param>
        public static void FlushCachedContent(int blockId, string entityValue)
        {
            RockMemoryCache cache = RockMemoryCache.Default;

            cache.Remove(HtmlContentCacheKey(blockId, entityValue));
        }
Beispiel #12
0
        /// <summary>
        /// Renders the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="result">The result.</param>
        public override void Render(Context context, TextWriter result)
        {
            RockPage page = HttpContext.Current.Handler as RockPage;

            var parms = ParseMarkup(_markup, context);

            using (TextWriter twStylesheet = new StringWriter())
            {
                base.Render(context, twStylesheet);

                var stylesheet = twStylesheet.ToString();

                if (parms.ContainsKey("compile"))
                {
                    if (parms["compile"] == "less")
                    {
                        DotlessConfiguration dotLessConfiguration = new DotlessConfiguration();
                        dotLessConfiguration.MinifyOutput = true;

                        if (parms.ContainsKey("import"))
                        {
                            // import statements should go at the end to allow for default variable assignment in the beginning
                            // to help reduce the number of Less errors we automatically add the bootstrap and core rock variables files
                            var importStatements = string.Empty;

                            var importSource = "~/Styles/Bootstrap/variables.less,~/Styles/_rock-variables.less," + parms["import"];

                            var importFiles = importSource.Split(',');
                            foreach (var importFile in importFiles)
                            {
                                var filePath = string.Empty;
                                if (!importFile.StartsWith("~"))
                                {
                                    filePath = $"~~/Styles/{importFile}";
                                }
                                else
                                {
                                    filePath = importFile;
                                }

                                filePath = page.ResolveRockUrl(filePath);

                                var fullPath = page.MapPath("~/") + filePath;

                                if (File.Exists(fullPath))
                                {
                                    importStatements = $"{importStatements}{Environment.NewLine}@import \"{fullPath}\";";
                                }
                            }

                            stylesheet = $"{stylesheet}{Environment.NewLine}{importStatements}";
                        }

                        // ok we have our less stylesheet let's see if it's been cached (less can take ~100ms to compile so let's try not to do that if necessary)
                        if (parms.ContainsKey("cacheduration"))
                        {
                            var             cacheKey         = stylesheet.GetHashCode().ToString();
                            RockMemoryCache cache            = RockMemoryCache.Default;
                            var             cachedStylesheet = cache[cacheKey] as string;

                            if (cachedStylesheet.IsNotNullOrWhitespace())
                            {
                                stylesheet = cachedStylesheet;
                            }
                            else
                            {
                                stylesheet = LessWeb.Parse(stylesheet, dotLessConfiguration);

                                // check if we should cache this
                                if (parms.ContainsKey("cacheduration") && stylesheet.IsNotNullOrWhitespace())
                                {
                                    int cacheDuration = 0;
                                    Int32.TryParse(parms["cacheduration"], out cacheDuration);

                                    if (cacheDuration > 0)
                                    {
                                        cache.Set(cacheKey, stylesheet, new CacheItemPolicy {
                                            AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(cacheDuration)
                                        });
                                    }
                                }
                            }
                        }
                        else
                        {
                            stylesheet = LessWeb.Parse(stylesheet, dotLessConfiguration);
                        }
                    }

                    if (stylesheet == string.Empty)
                    {
                        if (parms.ContainsKey("id"))
                        {
                            result.Write($"An error occurred compiling the Less for this stylesheet (id: {parms["id"]}).");
                        }
                        else
                        {
                            result.Write("An error occurred compiling the Less for this stylesheet.");
                        }
                        return;
                    }
                }

                if (parms.ContainsKey("id"))
                {
                    var identifier = parms["id"];
                    if (identifier.IsNotNullOrWhitespace())
                    {
                        var controlId = "css-" + identifier;

                        var cssControl = page.Header.FindControl(controlId);
                        if (cssControl == null)
                        {
                            cssControl    = new System.Web.UI.LiteralControl($"{Environment.NewLine}<style>{stylesheet}</style>{Environment.NewLine}");
                            cssControl.ID = controlId;
                            page.Header.Controls.Add(cssControl);
                        }
                    }
                }
                else
                {
                    page.Header.Controls.Add(new System.Web.UI.LiteralControl($"{Environment.NewLine}<style>{stylesheet}</style>{Environment.NewLine}"));
                }
            }
        }
Beispiel #13
0
        /// <summary>
        /// Reads the specified label by guid.
        /// </summary>
        /// <param name="guid">The unique identifier.</param>
        /// <returns></returns>
        public static KioskLabel Read(Guid guid)
        {
            string cacheKey = KioskLabel.CacheKey(guid);

            RockMemoryCache cache = RockMemoryCache.Default;
            KioskLabel      label = cache[cacheKey] as KioskLabel;

            if (label != null)
            {
                return(label);
            }
            else
            {
                using (var rockContext = new RockContext())
                {
                    var file = new BinaryFileService(rockContext).Get(guid);
                    if (file != null)
                    {
                        label = new KioskLabel();

                        label.Guid        = file.Guid;
                        label.Url         = string.Format("{0}GetFile.ashx?id={1}", System.Web.VirtualPathUtility.ToAbsolute("~"), file.Id);
                        label.MergeFields = new Dictionary <string, string>();
                        label.FileContent = file.ContentsToString();

                        file.LoadAttributes(rockContext);
                        string attributeValue = file.GetAttributeValue("MergeCodes");
                        if (!string.IsNullOrWhiteSpace(attributeValue))
                        {
                            string[] nameValues = attributeValue.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                            foreach (string nameValue in nameValues)
                            {
                                string[] nameAndValue = nameValue.Split(new char[] { '^' }, StringSplitOptions.RemoveEmptyEntries);
                                if (nameAndValue.Length == 2 && !label.MergeFields.ContainsKey(nameAndValue[0]))
                                {
                                    label.MergeFields.Add(nameAndValue[0], nameAndValue[1]);

                                    int definedValueId = int.MinValue;
                                    if (int.TryParse(nameAndValue[1], out definedValueId))
                                    {
                                        var definedValue = DefinedValueCache.Read(definedValueId);
                                        if (definedValue != null)
                                        {
                                            string mergeField = definedValue.GetAttributeValue("MergeField");
                                            if (mergeField != null)
                                            {
                                                label.MergeFields[nameAndValue[0]] = mergeField;
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        cache.Set(cacheKey, label, new CacheItemPolicy {
                            AbsoluteExpiration = DateTimeOffset.Now.Date.AddDays(1)
                        });

                        return(label);
                    }
                }
            }

            return(null);
        }
Beispiel #14
0
        /// <summary>
        /// Flushes the specified guid.
        /// </summary>
        /// <param name="guid">The unique identifier.</param>
        public static void Flush(Guid guid)
        {
            RockMemoryCache cache = RockMemoryCache.Default;

            cache.Remove(KioskLabel.CacheKey(guid));
        }