/// <summary>
        /// Gets the people a person is related to
        /// </summary>
        /// <param name="context"></param>
        /// <param name="input"></param>
        /// <param name="relationshipTypeName">The relationship name you're search for</param>
        /// <returns></returns>
        public static List <Person> Relationship(DotLiquid.Context context, object input, string relationshipTypeName)
        {
            Person person      = null;
            var    rockContext = new RockContext();

            if (input is int)
            {
                person = new PersonService(rockContext).Get(( int )input);
            }
            else if (input is Person)
            {
                person = ( Person )input;
            }

            if (person != null)
            {
                var relationshipType = new GroupTypeRoleService(rockContext).GetByGroupTypeId(GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid()).Id).FirstOrDefault(r => relationshipTypeName == r.Name);
                if (relationshipType != null)
                {
                    var relatedPersons = new GroupMemberService(rockContext).GetKnownRelationship(person.Id, relationshipType.Id);
                    return(relatedPersons.Select(p => p.Person).ToList());
                }
            }

            return(new List <Person>());
        }
Esempio n. 2
0
        /// <summary>
        /// Gets the current person.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns>The current person or null if not found.</returns>
        /// <exception cref="ArgumentNullException">context</exception>
        public static Person GetCurrentPerson(DotLiquid.Context context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            string currentPersonKey = "CurrentPerson";
            Person currentPerson    = null;

            // First, check for a person override value included in the lava context.
            if (context.Scopes != null)
            {
                foreach (var scope in context.Scopes)
                {
                    if (scope.ContainsKey(currentPersonKey))
                    {
                        currentPerson = scope[currentPersonKey] as Person;
                    }
                }
            }

            if (currentPerson == null)
            {
                var httpContext = HttpContext.Current;
                if (httpContext != null && httpContext.Items.Contains(currentPersonKey))
                {
                    currentPerson = httpContext.Items[currentPersonKey] as Person;
                }
            }

            return(currentPerson);
        }
Esempio n. 3
0
        public string ReadTemplateFile(DotLiquid.Context context, string templateName)
        {
            try {
                templateName = templateName.Trim('\'', '"');

                context.GetTracer().Info("Loading template: " + templateName);

                var res = TemplateResolver.GetTemplateContents(templateName);

                if (string.IsNullOrEmpty(res))
                {
                    if (!string.IsNullOrEmpty(LocalPath))
                    {
                        templateName = Path.Combine(LocalPath, templateName);

                        if (File.Exists(templateName))
                        {
                            res = File.ReadAllText(templateName);
                        }
                        else
                        {
                            throw new WhamTemplateException("[FKASIHQJWKTP] Template not found: " + templateName);
                        }
                    }
                    else
                    {
                        throw new WhamTemplateException($"[FHBAOUTOPQA] Template not loaded: '{templateName}'");
                    }
                }

                return(res);
            } catch (Exception x) {
                throw new WhamTemplateException($"[FKJJAHQROIZ] Template error accessing '{templateName}': {x.Message}", x);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// 获取模块的Html
        /// </summary>
        /// <param name="url">模块所在的Url地址</param>
        /// <param name="path">模块的路径</param>
        /// <param name="args">模块的参数</param>
        /// <returns></returns>
        public virtual string GetWidgetHtml(string url, string path, IDictionary <string, object> args)
        {
            // 获取模块的Html之前首先要获取到所在Url的TemplateResult, 模块有可能需要用到返回的变量
            var uri            = new Uri(url);
            var pageManager    = Application.Ioc.Resolve <VisualPageManager>();
            var templateResult = pageManager.GetPageResult(uri.PathAndQuery) as TemplateResult;

            // 过滤空参数, 无参数时应该等于null
            args = args.Where(x => x.Value != null && x.Value as string != "")
                   .ToDictionary(x => x.Key, x => x.Value);
            if (args.Count == 0)
            {
                args = null;
            }
            // 获取模块的Html
            // 通过渲染器获取避免读取和写入区域管理器的缓存
            var templateManager = Application.Ioc.Resolve <TemplateManager>();
            var renderer        = Application.Ioc.Resolve <ITemplateWidgetRenderer>();
            var context         = new DotLiquid.Context();
            var widget          = new TemplateWidget(path, args);

            if (templateResult?.TemplateArgument != null)
            {
                var arguments = templateResult.TemplateArgument;
                context.Push(templateManager.CreateHash(arguments));
            }
            var widgetHtml = renderer.Render(context, widget);

            return(widgetHtml);
        }
Esempio n. 5
0
            public string ReadTemplateFile(DotLiquid.Context context, string templateName)
            {
                if (_resourceProvider == null)
                {
                    return(null);
                }
                string template;

                if (!_templateCache.TryGetValue(templateName, out template))
                {
                    string resourceName;
                    var    slashIndex = templateName.LastIndexOf('/');
                    if (slashIndex > -1)
                    {
                        var fileName = templateName.Substring(slashIndex + 1);
                        resourceName = $"{templateName.Substring(0, slashIndex)}/_{fileName}.liquid";
                    }
                    else
                    {
                        resourceName = $"_{templateName}.liquid";
                    }

                    template = _resourceProvider.GetResource(resourceName);
                    _templateCache[templateName] = template;
                }

                return(template);
            }
Esempio n. 6
0
        //Stolen from Rock filters...why you not helper method?
        private static Person GetCurrentPerson(DotLiquid.Context context)
        {
            Person currentPerson = null;

            // First check for a person override value included in lava context
            if (context.Scopes != null)
            {
                foreach (var scopeHash in context.Scopes)
                {
                    if (scopeHash.ContainsKey("CurrentPerson"))
                    {
                        currentPerson = scopeHash["CurrentPerson"] as Person;
                    }
                }
            }

            if (currentPerson == null)
            {
                var httpContext = System.Web.HttpContext.Current;
                if (httpContext != null && httpContext.Items.Contains("CurrentPerson"))
                {
                    currentPerson = httpContext.Items["CurrentPerson"] as Person;
                }
            }

            return(currentPerson);
        }
Esempio n. 7
0
        public string ReadTemplateFile(DotLiquid.Context context, string templateName)
        {
            var include = Path.Combine(Root, "_includes", templateName);

            if (File.Exists(include))
            {
                return(File.ReadAllText(include));
            }
            return(string.Empty);
        }
Esempio n. 8
0
        /// <summary>
        /// Determines whether the specified command is authorized within the context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="command">The command.</param>
        /// <returns>
        ///   <c>true</c> if the specified command is authorized; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsAuthorized(DotLiquid.Context context, string command)
        {
            if (context?.Registers?.ContainsKey("EnabledCommands") == true && command.IsNotNullOrWhiteSpace())
            {
                var enabledCommands = context.Registers["EnabledCommands"].ToString().Split(',').ToList();

                if (enabledCommands.Contains("All") || enabledCommands.Contains(command))
                {
                    return(true);
                }
            }

            return(false);
        }
Esempio n. 9
0
        public static List <PersonCourseInfo> PersonCourseInfo(DotLiquid.Context context, object personObj, string categoryIds)
        {
            if (personObj != null && personObj is Person)
            {
                var courseEntityType = EntityTypeCache.Get(typeof(Course));
                var validCategoryIds = CategoryCache.All()
                                       .Where(c => c.EntityTypeId == courseEntityType.Id)
                                       .Where(c => categoryIds.Split().Select(i => i.AsInteger()).ToList().Contains(c.Id))
                                       .Select(c => c.Id).ToList();

                return(PersonCourseInfo(context, personObj as Person, validCategoryIds));
            }

            return(null);
        }
Esempio n. 10
0
        public static List <PersonCourseInfo> PersonCourseInfo(DotLiquid.Context context, object personObj)
        {
            var courseEntityType = EntityTypeCache.Get(typeof(Course));
            var categories       = CategoryCache.All().Where(c => c.EntityTypeId == courseEntityType.Id);
            var categoryIds      = categories
                                   .Select(c => c.Id)
                                   .ToList();

            if (personObj != null && personObj is Person)
            {
                return(PersonCourseInfo(context, personObj as Person, categoryIds));
            }

            return(null);
        }
            public string ReadTemplateFile(DotLiquid.Context context, string templateName)
            {
                if (_resourceProvider == null)
                {
                    return(null);
                }
                string resourceName;
                var    slashIndex = templateName.LastIndexOf('/');

                if (slashIndex > -1)
                {
                    var fileName = templateName.Substring(slashIndex + 1);
                    resourceName = $"{templateName.Substring(0, slashIndex)}/_{fileName}.liquid";
                }
                else
                {
                    resourceName = $"_{templateName}.liquid";
                }

                return(_resourceProvider.GetResource(resourceName));
            }
Esempio n. 12
0
        public static string TwoPass(DotLiquid.Context context, object input)
        {
            var lava         = input.ToString();
            var mergeObjects = new Dictionary <string, object>();

            if (context.Environments.Count > 0)
            {
                foreach (var keyVal in context.Environments[0])
                {
                    mergeObjects.Add(keyVal.Key, keyVal.Value);
                }
            }

            string enabledCommands = null;

            if (context.Registers.ContainsKey("EnabledCommands"))
            {
                enabledCommands = context.Registers["EnabledCommands"].ToString();
            }

            return(lava.ResolveMergeFields(mergeObjects, enabledCommands));
        }
Esempio n. 13
0
        /// <summary>
        /// Parses the Lava Command markup, first resolving merge fields and then harvesting any provided parameters.
        /// </summary>
        /// <param name="markup">The Lava Command markup.</param>
        /// <param name="context">The DotLiquid context.</param>
        /// <param name="parms">
        /// A dictionary into which any parameters discovered within the <paramref name="markup"/> will be added or replaced.
        /// Default values may be pre-loaded into this collection, and will be overwritten if a matching key is present within the <paramref name="markup"/>.
        /// Note that parameter keys should be added in lower case.
        /// <para>
        /// When searching the <paramref name="markup"/> for key/value parameter pairs, the following <see cref="Regex"/> pattern will be used: @"\S+:('[^']+'|\d+)".
        /// This means that the following patterns will be matched: "key:'value'" OR "key:integer". While this should work for most - if not all - Lava Command parameters,
        /// you can always choose to not use this helper method and instead roll your own implementation.
        /// </para>
        /// </param>
        public static void ParseCommandMarkup(string markup, DotLiquid.Context context, Dictionary <string, string> parms)
        {
            if (markup.IsNull())
            {
                return;
            }

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (parms == null)
            {
                throw new ArgumentNullException(nameof(parms));
            }

            var mergeFields = new Dictionary <string, object>();

            // Get variables defined in the lava context.
            foreach (var scope in context.Scopes)
            {
                foreach (var item in scope)
                {
                    mergeFields.AddOrReplace(item.Key, item.Value);
                }
            }

            // Get merge fields loaded by the block or container.
            foreach (var environment in context.Environments)
            {
                foreach (var item in environment)
                {
                    mergeFields.AddOrReplace(item.Key, item.Value);
                }
            }

            // Resolve merge fields.
            var resolvedMarkup = markup.ResolveMergeFields(mergeFields);

            // Harvest parameters.
            var markupParms = Regex.Matches(resolvedMarkup, @"\S+:('[^']+'|\d+)")
                              .Cast <Match>()
                              .Select(m => m.Value)
                              .ToList();

            foreach (var parm in markupParms)
            {
                var itemParts = parm.ToString().Split(new char[] { ':' }, 2);
                if (itemParts.Length > 1)
                {
                    var key   = itemParts[0].Trim().ToLower();
                    var value = itemParts[1].Trim();

                    if (value[0] == '\'')
                    {
                        // key:'value'
                        parms.AddOrReplace(key, value.Substring(1, value.Length - 2));
                    }
                    else
                    {
                        // key:integer
                        parms.AddOrReplace(key, value);
                    }
                }
            }
        }
Esempio n. 14
0
 public override void Render(DotLiquid.Context context, TextWriter result)
 {
     result.WriteLine(Custom());
 }
Esempio n. 15
0
 public string ReadTemplateFile(DotLiquid.Context context, string templateName)
 {
     return(File.ReadAllText(Path.Combine(_path, templateName)));
 }
Esempio n. 16
0
        private static List <PersonCourseInfo> PersonCourseInfo(DotLiquid.Context context, Person person, List <int> categoryIds)
        {
            var currentPerson = GetCurrentPerson(context);

            RockContext         rockContext         = new RockContext();
            CourseService       courseService       = new CourseService(rockContext);
            CourseRecordService courseRecordService = new CourseRecordService(rockContext);
            var courseRecordQry = courseRecordService.Queryable().Where(r => r.PersonAlias.PersonId == person.Id);

            var courseItems = new List <PersonCourseInfo>();

            CourseRequirementStatusService courseRequirementStatusService = new CourseRequirementStatusService(rockContext);
            var statusQry = courseRequirementStatusService.Queryable()
                            .Where(s => s.PersonAlias.PersonId == person.Id);

            var recordQueryable = courseRecordService.Queryable()
                                  .GroupJoin(statusQry,
                                             r => r.CourseId,
                                             s => s.CourseRequirement.CourseId,
                                             (r, s) => new { Record = r, Statuses = s }
                                             )
                                  .Where(r => r.Record.PersonAlias.PersonId == person.Id)
                                  .OrderByDescending(r => r.Record.CompletionDateTime);

            var courses = courseService.Queryable()
                          .Where(c => c.IsActive)
                          .Where(c => categoryIds.Contains(c.CategoryId ?? 0))
                          .GroupJoin(recordQueryable,
                                     c => c.Id,
                                     r => r.Record.CourseId,
                                     (c, r) => new
            {
                Course   = c,
                Records  = r,
                Category = c.Category
            })
                          .ToList();

            foreach (var course in courses)
            {
                if (course.Course.IsAuthorized(Rock.Security.Authorization.VIEW, currentPerson))
                {
                    var courseItem = new PersonCourseInfo()
                    {
                        Course     = course.Course,
                        Category   = course.Category,
                        IsComplete = false
                    };

                    var completedRecords = course.Records.Where(r => r.Record.Passed).ToList();
                    if (completedRecords.Any())
                    {
                        var completedCourse = completedRecords.First();
                        courseItem.IsComplete        = true;
                        courseItem.CompletedDateTime = completedCourse.Record.CompletionDateTime;
                        var expired = completedCourse.Statuses
                                      .Where(s => s.State == CourseRequirementState.Expired).Any();
                        if (expired)
                        {
                            courseItem.IsExpired = true;
                        }
                    }
                    courseItems.Add(courseItem);
                }
            }


            return(courseItems);
        }