Esempio n. 1
1
        /// <summary>
        /// Gets the parents of the person
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="input">The input.</param>
        /// <returns></returns>
        public static List<Person> Parents( DotLiquid.Context context, object input )
        {
            var person = GetPerson( input );

            if ( person != null )
            {
                Guid adultGuid = Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid();
                var parents = new PersonService( new RockContext() ).GetFamilyMembers( person.Id ).Where( m => m.GroupRole.Guid == adultGuid ).Select( a => a.Person );
                return parents.ToList();
            }

            return new List<Person>();
        }
Esempio n. 2
1
        /// <summary>
        /// Gets the current person.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        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. 3
0
 public string ReadTemplateFile(DotLiquid.Context context, string templateName)
 {
     var include = Path.Combine(Root, "_includes", templateName);
     if (_fileSystem.File.Exists(include))
         return _fileSystem.File.ReadAllText(include);
     return string.Empty;
 }
Esempio n. 4
0
 private LiquidTemplateRenderer(DotLiquid.Template liquidTemplate, string template, IEnumerable<string> dependencies)
 {
     _template = liquidTemplate;
     Raw = template;
     Dependencies = dependencies;
 }
 partial void RenderTemplateOverride(T4MVC_System_Web_Mvc_ActionResult callInfo, DotLiquid.Template layout, string templateHtml);
Esempio n. 6
0
 /// <summary>
 /// Gets the rock context.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <returns></returns>
 private static RockContext GetRockContext( DotLiquid.Context context)
 {
     if ( context.Registers.ContainsKey("rock_context"))
     {
         return context.Registers["rock_context"] as RockContext;
     }
     else
     {
         var rockContext = new RockContext();
         context.Registers.Add( "rock_context", rockContext );
         return rockContext;
     }
 }
Esempio n. 7
0
 /// <summary>
 /// Properties the specified context.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="input">The input.</param>
 /// <param name="propertyKey">The property key.</param>
 /// <param name="qualifier">The qualifier.</param>
 /// <returns></returns>
 public static object Property( DotLiquid.Context context, object input, string propertyKey, string qualifier = "" )
 {
     if ( input != null )
     {
         return input.GetPropertyValue(propertyKey);
     }
     return string.Empty;
 }
Esempio n. 8
0
            public string ReadTemplateFile(DotLiquid.Context context, string templateName)
            {
                if (_resourceProvider == null) return null;

                return _templateCache.GetOrAdd(templateName, s =>
                {
                    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. 9
0
        /// <summary>
        /// Gets the profile photo for a person object in a string that zebra printers can use.
        /// If the person has no photo, a default silhouette photo (adult/child, male/female)
        /// photo is used.
        /// See http://www.rockrms.com/lava/person#ZebraPhoto for details.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="input">The input, which is the person.</param>
        /// <param name="size">The size.</param>
        /// <param name="brightness">The brightness adjustment (-1.0 to 1.0).</param>
        /// <param name="contrast">The contrast adjustment (-1.0 to 1.0).</param>
        /// <returns>A ZPL field containing the photo data with a label of LOGO (^FS ~DYE:LOGO,P,P,{0},,{1} ^FD").</returns>
        public static string ZebraPhoto( DotLiquid.Context context, object input, string size, double brightness = 1.0, double contrast = 1.0 )
        {
            var person = GetPerson( input );
            try
            {
                if ( person != null )
                {
                    Stream initialPhotoStream;
                    if ( person.PhotoId.HasValue )
                    {
                        initialPhotoStream = new BinaryFileService( GetRockContext( context ) ).Get( person.PhotoId.Value ).ContentStream;
                    }
                    else
                    {
                        var photoUrl = new StringBuilder();
                        photoUrl.Append( HttpContext.Current.Server.MapPath( "~/" ) );

                        if ( person.Age.HasValue && person.Age.Value < 18 )
                        {
                            // it's a child
                            if ( person.Gender == Gender.Female )
                            {
                                photoUrl.Append( "Assets/FamilyManagerThemes/RockDefault/photo-child-female.png" );
                            }
                            else
                            {
                                photoUrl.Append( "Assets/FamilyManagerThemes/RockDefault/photo-child-male.png" );
                            }
                        }
                        else
                        {
                            // it's an adult
                            if ( person.Gender == Gender.Female )
                            {
                                photoUrl.Append( "Assets/FamilyManagerThemes/RockDefault/photo-adult-female.png" );
                            }
                            else
                            {
                                photoUrl.Append( "Assets/FamilyManagerThemes/RockDefault/photo-adult-male.png" );
                            }
                        }

                        initialPhotoStream = File.Open( photoUrl.ToString(), FileMode.Open );
                    }

                    Bitmap initialBitmap = new Bitmap( initialPhotoStream );

                    // Adjust the image if any of the parameters not default
                    if ( brightness != 1.0 || contrast != 1.0 )
                    {
                        initialBitmap = ImageAdjust( initialBitmap, (float)brightness, (float)contrast );
                    }

                    // Calculate rectangle to crop image into
                    int height = initialBitmap.Height;
                    int width = initialBitmap.Width;
                    Rectangle cropSection = new Rectangle( 0, 0, height, width );
                    if ( height < width )
                    {
                        cropSection = new Rectangle( ( width - height ) / 2, 0, ( width + height ) / 2, height ); // (width + height)/2 is a simplified version of the (width - height)/2 + height function
                    }
                    else if ( height > width )
                    {
                        cropSection = new Rectangle( 0, ( height - width ) / 2, width, ( height + width ) / 2 );
                    }

                    // Crop and resize image
                    int pixelSize = size.AsIntegerOrNull() ?? 395;
                    Bitmap resizedBitmap = new Bitmap( pixelSize, pixelSize );
                    using ( Graphics g = Graphics.FromImage( resizedBitmap ) )
                    {
                        g.DrawImage( initialBitmap, new Rectangle( 0, 0, resizedBitmap.Width, resizedBitmap.Height ), cropSection, GraphicsUnit.Pixel );
                    }

                    // Grayscale Image
                    var masks = new byte[] { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };
                    var outputBitmap = new Bitmap( resizedBitmap.Width, resizedBitmap.Height, PixelFormat.Format1bppIndexed );
                    var data = new sbyte[resizedBitmap.Width, resizedBitmap.Height];
                    var inputData = resizedBitmap.LockBits( new Rectangle( 0, 0, resizedBitmap.Width, resizedBitmap.Height ), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb );
                    try
                    {
                        var scanLine = inputData.Scan0;
                        var line = new byte[inputData.Stride];
                        for ( var y = 0; y < inputData.Height; y++, scanLine += inputData.Stride )
                        {
                            Marshal.Copy( scanLine, line, 0, line.Length );
                            for ( var x = 0; x < resizedBitmap.Width; x++ )
                            {
                                // Change to greyscale
                                data[x, y] = (sbyte)( 64 * ( ( ( line[x * 3 + 2] * 0.299 + line[x * 3 + 1] * 0.587 + line[x * 3 + 0] * 0.114 ) / 255 ) - 0.4 ) );
                            }
                        }
                    }
                    finally
                    {
                        resizedBitmap.UnlockBits( inputData );
                    }

                    //Dither Image
                    var outputData = outputBitmap.LockBits( new Rectangle( 0, 0, outputBitmap.Width, outputBitmap.Height ), ImageLockMode.WriteOnly, PixelFormat.Format1bppIndexed );
                    try
                    {
                        var scanLine = outputData.Scan0;
                        for ( var y = 0; y < outputData.Height; y++, scanLine += outputData.Stride )
                        {
                            var line = new byte[outputData.Stride];
                            for ( var x = 0; x < resizedBitmap.Width; x++ )
                            {
                                var j = data[x, y] > 0;
                                if ( j ) line[x / 8] |= masks[x % 8];
                                var error = (sbyte)( data[x, y] - ( j ? 32 : -32 ) );
                                if ( x < resizedBitmap.Width - 1 ) data[x + 1, y] += (sbyte)( 7 * error / 16 );
                                if ( y < resizedBitmap.Height - 1 )
                                {
                                    if ( x > 0 ) data[x - 1, y + 1] += (sbyte)( 3 * error / 16 );
                                    data[x, y + 1] += (sbyte)( 5 * error / 16 );
                                    if ( x < resizedBitmap.Width - 1 ) data[x + 1, y + 1] += (sbyte)( 1 * error / 16 );
                                }
                            }

                            Marshal.Copy( line, 0, scanLine, outputData.Stride );
                        }
                    }
                    finally
                    {
                        outputBitmap.UnlockBits( outputData );
                    }

                    // Convert from x to .png
                    MemoryStream convertedStream = new MemoryStream();
                    outputBitmap.Save( convertedStream, System.Drawing.Imaging.ImageFormat.Png );
                    convertedStream.Seek( 0, SeekOrigin.Begin );

                    // Convert the .png stream into a ZPL-readable Hex format
                    var content = convertedStream.ReadBytesToEnd();
                    StringBuilder zplImageData = new StringBuilder();

                    foreach ( Byte b in content )
                    {
                        string hexRep = string.Format( "{0:X}", b );
                        if ( hexRep.Length == 1 )
                            hexRep = "0" + hexRep;
                        zplImageData.Append( hexRep );
                    }

                    convertedStream.Dispose();
                    initialPhotoStream.Dispose();

                    return string.Format( "^FS ~DYE:LOGO,P,P,{0},,{1} ^FD", content.Length, zplImageData.ToString() );
                }
            }
            catch
            {
                // intentially blank
            }

            return string.Empty;
        }
Esempio n. 10
0
        /// <summary>
        /// Sorts the list of items by the specified attribute's value
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="input">The input.</param>
        /// <param name="attributeKey">The attribute key.</param>
        /// <returns></returns>
        public static object SortByAttribute( DotLiquid.Context context, object input, string attributeKey )
        {
            if ( input is IEnumerable )
            {
                var rockContext = GetRockContext( context );
                var inputList = ( input as IEnumerable ).OfType<Rock.Attribute.IHasAttributes>().ToList();
                foreach ( var item in inputList )
                {
                    if ( item.Attributes == null )
                    {
                        item.LoadAttributes( rockContext );
                    }
                }

                if ( inputList.Count > 1 && inputList[0].Attributes.ContainsKey( attributeKey ) )
                {
                    var attributeCache = inputList[0].Attributes[attributeKey];

                    inputList.Sort( ( item1, item2 ) =>
                    {
                        var item1AttributeValue = item1.AttributeValues.Where( a => a.Key == attributeKey ).FirstOrDefault().Value.SortValue;
                        var item2AttributeValue = item2.AttributeValues.Where( a => a.Key == attributeKey ).FirstOrDefault().Value.SortValue;
                        if ( item1AttributeValue is IComparable && item2AttributeValue is IComparable )
                        {
                            return ( item1AttributeValue as IComparable ).CompareTo( item2AttributeValue as IComparable );
                        }
                        else
                        {
                            return 0;
                        }
                    } );
                }

                return inputList;
            }
            else
            {
                return input;
            }
        }
Esempio n. 11
0
 /// <summary>
 /// Gets the profile photo for a person object in a string that zebra printers can use.
 /// If the person has no photo, a default silhouette photo (adult/child, male/female)
 /// photo is used.
 /// See http://www.rockrms.com/lava/person#ZebraPhoto for details.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="input">The input, which is the person.</param>
 /// <param name="size">The size.</param>
 /// <returns>A ZPL field containing the photo data with a label of LOGO (^FS ~DYE:LOGO,P,P,{0},,{1} ^FD").</returns>
 public static string ZebraPhoto( DotLiquid.Context context, object input, string size )
 {
     return ZebraPhoto( context, input, size, 1.0, 1.0 );
 }
Esempio n. 12
0
        /// <summary>
        /// Gets an number for a person object
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="input">The input.</param>
        /// <param name="phoneType">Type of the phone number.</param>
        /// <param name="countryCode">Whether or not there should be a country code returned</param>
        /// <returns></returns>
        public static string PhoneNumber( DotLiquid.Context context, object input, string phoneType = "Home", bool countryCode = false )
        {
            var person = GetPerson( input );
            string phoneNumber = null;

            if ( person != null )
            {
                var phoneNumberQuery = new PhoneNumberService( GetRockContext( context ) )
                            .Queryable()
                            .AsNoTracking()
                            .Where( p =>
                               p.PersonId == person.Id )
                            .Where( a => a.NumberTypeValue.Value == phoneType )
                            .FirstOrDefault();

                if ( phoneNumberQuery != null )
                {
                    if ( countryCode && !string.IsNullOrEmpty( phoneNumberQuery.CountryCode ) )
                    {
                        phoneNumber = phoneNumberQuery.NumberFormattedWithCountryCode;
                    }
                    else
                    {
                        phoneNumber = phoneNumberQuery.NumberFormatted;
                    }
                }
            }

            return phoneNumber;
        }
Esempio n. 13
0
        /// <summary>
        /// Persons the by identifier.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="input">The input.</param>
        /// <returns></returns>
        public static Person PersonById( DotLiquid.Context context, object input )
        {
            if ( input == null )
            {
                return null;
            }

            int personId = -1;

            if ( !Int32.TryParse( input.ToString(), out personId ) )
            {
                return null;
            }

            var rockContext = new RockContext();

            return new PersonService( rockContext ).Get( personId );
        }
Esempio n. 14
0
        /// <summary>
        /// Persons the by unique identifier.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="input">The input.</param>
        /// <returns></returns>
        public static Person PersonByGuid( DotLiquid.Context context, object input )
        {
            if ( input == null )
            {
                return null;
            }

            Guid? personGuid = input.ToString().AsGuidOrNull();

            if ( personGuid.HasValue )
            {
                var rockContext = new RockContext();

                return new PersonService( rockContext ).Get( personGuid.Value );
            }
            else
            {
                return null;
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Gets the last attendance item for a given person in a group of type provided
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="input">The input.</param>
        /// <param name="groupTypeId">The group type identifier.</param>
        /// <returns></returns>
        public static Attendance LastAttendedGroupOfType( DotLiquid.Context context, object input, string groupTypeId )
        {
            var person = GetPerson( input );
            int? numericalGroupTypeId = groupTypeId.AsIntegerOrNull();

            if ( person != null && numericalGroupTypeId.HasValue )
            {
                var attendance =  new AttendanceService( GetRockContext( context ) ).Queryable("Group").AsNoTracking()
                    .Where( a => a.Group.GroupTypeId == numericalGroupTypeId && a.PersonAlias.PersonId == person.Id && a.DidAttend == true )
                    .OrderByDescending( a => a.StartDateTime ).FirstOrDefault();

                return attendance;
            }

            return new Attendance();
        }
Esempio n. 16
0
        /// <summary>
        /// DotLiquid Attribute Filter
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="input">The input.</param>
        /// <param name="attributeKey">The attribute key.</param>
        /// <param name="qualifier">The qualifier.</param>
        /// <returns></returns>
        public static object Attribute( DotLiquid.Context context, object input, string attributeKey, string qualifier = "" )
        {
            IHasAttributes item = null;

            if ( input == null || attributeKey == null )
            {
                return string.Empty;
            }

            // Try to get RockContext from the dotLiquid context
            var rockContext = GetRockContext( context );

            AttributeCache attribute = null;
            string rawValue = string.Empty;

            // If Input is "Global" then look for a global attribute with key
            if ( input.ToString().Equals( "Global", StringComparison.OrdinalIgnoreCase ) )
            {
                var globalAttributeCache = Rock.Web.Cache.GlobalAttributesCache.Read( rockContext );
                attribute = globalAttributeCache.Attributes
                    .FirstOrDefault( a => a.Key.Equals( attributeKey, StringComparison.OrdinalIgnoreCase ) );
                if ( attribute != null )
                {
                    // Get the value
                    string theValue = globalAttributeCache.GetValue( attributeKey );
                    if ( theValue.HasMergeFields() )
                    {
                        // Global attributes may reference other global attributes, so try to resolve this value again
                        rawValue = theValue.ResolveMergeFields( new Dictionary<string, object>() );
                    }
                    else
                    {
                        rawValue = theValue;
                    }
                }
            }

            // If input is an object that has attributes, find its attribute value
            else
            {
                if ( input is IHasAttributes )
                {
                    item = (IHasAttributes)input;
                }
                else if ( input is IHasAttributesWrapper )
                {
                    item = ( (IHasAttributesWrapper)input ).HasAttributesEntity;
                }

                if ( item != null )
                {
                    if ( item.Attributes == null )
                    {
                        item.LoadAttributes( rockContext );
                    }

                    if ( item.Attributes.ContainsKey( attributeKey ) )
                    {
                        attribute = item.Attributes[attributeKey];
                        rawValue = item.AttributeValues[attributeKey].Value;
                    }
                }
            }

            // If valid attribute and value were found
            if ( attribute != null && !string.IsNullOrWhiteSpace( rawValue ) )
            {
                Person currentPerson = GetCurrentPerson( context );

                if ( attribute.IsAuthorized( Authorization.VIEW, currentPerson ) )
                {
                    // Check qualifier for 'Raw' if present, just return the raw unformatted value
                    if ( qualifier.Equals( "RawValue", StringComparison.OrdinalIgnoreCase ) )
                    {
                        return rawValue;
                    }

                    // Check qualifier for 'Url' and if present and attribute's field type is a ILinkableFieldType, then return the formatted url value
                    var field = attribute.FieldType.Field;
                    if ( qualifier.Equals( "Url", StringComparison.OrdinalIgnoreCase ) && field is Rock.Field.ILinkableFieldType )
                    {
                        return ( (Rock.Field.ILinkableFieldType)field ).UrlLink( rawValue, attribute.QualifierValues );
                    }

                    // check if attribute is a key value list and return a collection of key/value pairs
                    if ( field is Rock.Field.Types.KeyValueListFieldType )
                    {
                        var keyValueField = (Rock.Field.Types.KeyValueListFieldType)field;

                        return keyValueField.GetValuesFromString( null, rawValue, attribute.QualifierValues, false );
                    }

                    // If qualifier was specified, and the attribute field type is an IEntityFieldType, try to find a property on the entity
                    if ( !string.IsNullOrWhiteSpace( qualifier ) && field is Rock.Field.IEntityFieldType )
                    {
                        IEntity entity = ( (Rock.Field.IEntityFieldType)field ).GetEntity( rawValue );
                        if ( entity != null )
                        {
                            if ( qualifier.Equals( "object", StringComparison.OrdinalIgnoreCase ) )
                            {
                                return entity;
                            }
                            else
                            {
                                return entity.GetPropertyValue( qualifier ).ToStringSafe();
                            }
                        }
                    }

                    // Otherwise return the formatted value
                    return field.FormatValue( null, rawValue, attribute.QualifierValues, false );
                }
            }

            return string.Empty;
        }
Esempio n. 17
0
        /// <summary>
        /// Returnes the nearest group of a specific type.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="input">The input.</param>
        /// <param name="groupTypeId">The group type identifier.</param>
        /// <returns></returns>
        public static Rock.Model.Group NearestGroup( DotLiquid.Context context, object input, string groupTypeId )
        {
            var person = GetPerson( input );
            int? numericalGroupTypeId = groupTypeId.AsIntegerOrNull();

            if ( person != null && numericalGroupTypeId.HasValue )
            {
                return new GroupService( GetRockContext( context ) )
                    .GetNearestGroup( person.Id, numericalGroupTypeId.Value );
            }

            return null;
        }
Esempio n. 18
0
        /// <summary>
        /// Returns the Campus (or Campuses) that the Person belongs to
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="input">The input.</param>
        /// <param name="option">The option.</param>
        /// <returns></returns>
        public static object Campus( DotLiquid.Context context, object input, object option = null )
        {
            var person = GetPerson( input );

            bool getAll = false;
            if ( option != null && option.GetType() == typeof( string ) )
            {
                // if a string of "all" is specified for the option, return all of the campuses (if they are part of multiple families from different campuses)
                if ( string.Equals( (string)option, "all", StringComparison.OrdinalIgnoreCase ) )
                {
                    getAll = true;
                }
            }

            if ( getAll )
            {
                return person.GetFamilies().Select( a => a.Campus ).OrderBy( a => a.Name );
            }
            else
            {
                return person.GetCampus();
            }
        }
Esempio n. 19
0
 public string ReadTemplateFile(DotLiquid.Context context, string templateName)
 {
     return LoadEmbeddedResource("NServiceMVC.Views." + templateName);
 }
Esempio n. 20
0
        /// <summary>
        /// Gets the children of the person
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="input">The input.</param>
        /// <returns></returns>
        public static List<Person> Children( DotLiquid.Context context, object input )
        {
            var person = GetPerson( input );

            if ( person != null )
            {
                Guid childGuid = Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid();
                var children = new PersonService( new RockContext() ).GetFamilyMembers( person.Id ).Where( m => m.GroupRole.Guid == childGuid ).Select( a => a.Person );
                return children.ToList();
            }

            return new List<Person>();
        }
Esempio n. 21
0
        /// <summary>
        /// DotLiquid Attribute Filter
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="input">The input.</param>
        /// <param name="attributeKey">The attribute key.</param>
        /// <param name="qualifier">The qualifier.</param>
        /// <returns></returns>
        public static object Attribute( DotLiquid.Context context, object input, string attributeKey, string qualifier = "" )
        {
            if ( input == null || attributeKey == null )
            {
                return string.Empty;
            }

            // Try to get RockContext from the dotLiquid context
            var rockContext = GetRockContext(context);

            AttributeCache attribute = null;
            string rawValue = string.Empty;

            // If Input is "Global" then look for a global attribute with key
            if (input.ToString().Equals( "Global", StringComparison.OrdinalIgnoreCase ) )
            {
                var globalAttributeCache = Rock.Web.Cache.GlobalAttributesCache.Read( rockContext );
                attribute = globalAttributeCache.Attributes
                    .FirstOrDefault( a => a.Key.Equals(attributeKey, StringComparison.OrdinalIgnoreCase));
                if (attribute != null )
                {
                    // Get the value
                    string theValue = globalAttributeCache.GetValue( attributeKey );

                    // Global attributes may reference other global attributes, so try to resolve this value again
                    rawValue = theValue.ResolveMergeFields( new Dictionary<string, object>() );
                }
            }

            // If input is an object that has attributes, find it's attribute value
            else if ( input is IHasAttributes)
            {
                var item = (IHasAttributes)input;
                if ( item.Attributes == null)
                {
                    item.LoadAttributes( rockContext );
                }

                if ( item.Attributes.ContainsKey(attributeKey))
                {
                    attribute = item.Attributes[attributeKey];
                    rawValue = item.AttributeValues[attributeKey].Value;
                }
            }

            // If valid attribute and value were found
            if ( attribute != null && !string.IsNullOrWhiteSpace( rawValue ) )
            {
                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;
                    }
                }

                if ( attribute.IsAuthorized( Authorization.VIEW, currentPerson ) )
                {
                    // Check qualifier for 'Raw' if present, just return the raw unformatted value
                    if ( qualifier.Equals( "RawValue", StringComparison.OrdinalIgnoreCase ) )
                    {
                        return rawValue;
                    }

                    // Check qualifier for 'Url' and if present and attribute's field type is a ILinkableFieldType, then return the formatted url value
                    var field = attribute.FieldType.Field;
                    if ( qualifier.Equals( "Url", StringComparison.OrdinalIgnoreCase ) && field is Rock.Field.ILinkableFieldType )
                    {
                        return ( (Rock.Field.ILinkableFieldType)field ).UrlLink( rawValue, attribute.QualifierValues );
                    }

                    // If qualifier was specified, and the attribute field type is an IEntityFieldType, try to find a property on the entity
                    if ( !string.IsNullOrWhiteSpace( qualifier ) && field is Rock.Field.IEntityFieldType )
                    {
                        IEntity entity = ( (Rock.Field.IEntityFieldType)field ).GetEntity( rawValue );
                        if ( entity != null )
                        {
                            if ( qualifier.Equals( "object", StringComparison.OrdinalIgnoreCase ) )
                            {
                                return entity;
                            }
                            else
                            {
                                return entity.GetPropertyValue( qualifier ).ToStringSafe();
                            }
                        }
                    }

                    // Otherwise return the formatted value
                    return field.FormatValue( null, rawValue, attribute.QualifierValues, false );
                }
            }

            return string.Empty;
        }
Esempio n. 22
0
        /// <summary>
        /// Gets the groups of selected type that geofence the selected person 
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="input">The input.</param>
        /// <param name="groupTypeId">The group type identifier.</param>
        /// <param name="groupTypeRoleId">The group type role identifier.</param>
        /// <returns></returns>
        public static List<Rock.Model.Person> GeofencingGroupMembers( DotLiquid.Context context, object input, string groupTypeId, string groupTypeRoleId )
        {
            var person = GetPerson( input );
            int? numericalGroupTypeId = groupTypeId.AsIntegerOrNull();
            int? numericalGroupTypeRoleId = groupTypeRoleId.AsIntegerOrNull();

            if ( person != null && numericalGroupTypeId.HasValue && numericalGroupTypeRoleId.HasValue )
            {
                return new GroupService( GetRockContext( context ) )
                    .GetGeofencingGroups( person.Id, numericalGroupTypeId.Value )
                    .SelectMany( g => g.Members.Where( m => m.GroupRole.Id == numericalGroupTypeRoleId ) )
                    .Select( m => m.Person )
                    .ToList();
            }

            return new List<Model.Person>();
        }
Esempio n. 23
0
        /// <summary>
        /// Addresses the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="input">The input.</param>
        /// <param name="addressType">Type of the address.</param>
        /// <param name="qualifier">The qualifier.</param>
        /// <returns></returns>
        public static string Address( DotLiquid.Context context, object input, string addressType, string qualifier = "" )
        {
            if ( input != null && input is Person )
            {
                var person = (Person)input;
               
                Guid familyGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid();
                var location = new GroupMemberService( GetRockContext(context) )
                    .Queryable( "GroupLocations.Location" )
                    .Where( m => 
                        m.PersonId == person.Id && 
                        m.Group.GroupType.Guid == familyGuid )
                    .SelectMany( m => m.Group.GroupLocations )
                    .Where( gl => 
                        gl.GroupLocationTypeValue.Value == addressType )
                    .Select( gl => gl.Location )
                    .FirstOrDefault();

                if (location != null)
                {
                    if ( qualifier == "" )
                    {
                        return location.GetFullStreetAddress();
                    }
                    else
                    {
                        var matches = Regex.Matches(qualifier, @"\[\[([^\]]+)\]\]");
                        foreach ( var match in matches )
                        {
                            string propertyKey = match.ToString().Replace("[", "");
                            propertyKey = propertyKey.ToString().Replace( "]", "" );
                            propertyKey = propertyKey.ToString().Replace( " ", "" );

                            switch ( propertyKey )
                            {
                                case "Street1":
                                    qualifier = qualifier.Replace( match.ToString(), location.Street1 );
                                    break;
                                case "Street2":
                                    qualifier = qualifier.Replace( match.ToString(), location.Street2 );
                                    break;
                                case "City":
                                    qualifier = qualifier.Replace( match.ToString(), location.City );
                                    break;
                                case "State":
                                    qualifier = qualifier.Replace( match.ToString(), location.State );
                                    break;
                                case "PostalCode":
                                case "Zip":
                                    qualifier = qualifier.Replace( match.ToString(), location.PostalCode );
                                    break;
                                case "Country":
                                    qualifier = qualifier.Replace( match.ToString(), location.Country );
                                    break;
                                case "GeoPoint":
                                    if ( location.GeoPoint != null )
                                    {
                                        qualifier = qualifier.Replace( match.ToString(), string.Format("{0},{1}", location.GeoPoint.Latitude.ToString(), location.GeoPoint.Longitude.ToString()) );
                                    }
                                    else
                                    {
                                        qualifier = qualifier.Replace( match.ToString(), "" );
                                    }
                                    break;
                                case "Latitude":
                                    if ( location.GeoPoint != null )
                                    {
                                        qualifier = qualifier.Replace( match.ToString(), location.GeoPoint.Latitude.ToString() );
                                    }
                                    else
                                    {
                                        qualifier = qualifier.Replace( match.ToString(), "" );
                                    }
                                    break;
                                case "Longitude":
                                    if ( location.GeoPoint != null )
                                    {
                                        qualifier = qualifier.Replace( match.ToString(), location.GeoPoint.Longitude.ToString() );
                                    }
                                    else
                                    {
                                        qualifier = qualifier.Replace( match.ToString(), "" );
                                    }
                                    break;
                                case "FormattedAddress":
                                    qualifier = qualifier.Replace( match.ToString(), location.FormattedAddress );
                                    break;
                                case "FormattedHtmlAddress":
                                    qualifier = qualifier.Replace( match.ToString(), location.FormattedHtmlAddress );
                                    break;
                                default:
                                    qualifier = qualifier.Replace( match.ToString(), "" );
                                    break;
                            }
                        }

                        return qualifier;
                    }
                }
            }

            return string.Empty;
        }
Esempio n. 24
0
        /// <summary>
        /// Gets the groups of selected type that geofence the selected person
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="input">The input.</param>
        /// <param name="groupTypeId">The group type identifier.</param>
        /// <returns></returns>
        public static List<Rock.Model.Group> GeofencingGroups( DotLiquid.Context context, object input, string groupTypeId )
        {
            var person = GetPerson( input );
            int? numericalGroupTypeId = groupTypeId.AsIntegerOrNull();

            if ( person != null && numericalGroupTypeId.HasValue )
            {
                return new GroupService( GetRockContext( context ) )
                    .GetGeofencingGroups( person.Id, numericalGroupTypeId.Value )
                    .ToList();
            }

            return new List<Model.Group>();
        }
Esempio n. 25
0
 public override void Render(DL.Context context, System.IO.TextWriter result)
 {
     if (null != m_Content)
         result.Write(m_Content);
     else
         result.Write("(null)");
 }
Esempio n. 26
0
        /// <summary>
        /// Gets the groups of selected type that person is a member of
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="input">The input.</param>
        /// <param name="groupTypeId">The group type identifier.</param>
        /// <param name="status">The status.</param>
        /// <returns></returns>
        public static List<Rock.Model.GroupMember> Groups( DotLiquid.Context context, object input, string groupTypeId, string status = "Active" )
        {
            var person = GetPerson( input );
            int? numericalGroupTypeId = groupTypeId.AsIntegerOrNull();

            if ( person != null && numericalGroupTypeId.HasValue )
            {
                var groupQuery =  new GroupMemberService( GetRockContext( context ) )
                    .Queryable("Group, GroupRole").AsNoTracking()
                    .Where( m =>
                        m.PersonId == person.Id &&
                        m.Group.GroupTypeId == numericalGroupTypeId.Value &&
                        m.Group.IsActive );

                if ( status != "All" )
                {
                    GroupMemberStatus queryStatus = GroupMemberStatus.Active;
                    queryStatus = (GroupMemberStatus)Enum.Parse( typeof( GroupMemberStatus ), status, true );

                    groupQuery = groupQuery.Where( m => m.GroupMemberStatus == queryStatus );
                }

                return groupQuery.ToList();
            }

            return new List<Model.GroupMember>();
        }
 public override System.Web.Mvc.ActionResult RenderTemplate(DotLiquid.Template layout, string templateHtml)
 {
     var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.RenderTemplate);
     ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "layout", layout);
     ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "templateHtml", templateHtml);
     RenderTemplateOverride(callInfo, layout, templateHtml);
     return callInfo;
 }
Esempio n. 28
0
        /// <summary>
        /// Gets the groups of selected type that person is a member of which they have attended at least once
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="input">The input.</param>
        /// <param name="groupTypeId">The group type identifier.</param>
        /// <returns></returns>
        public static List<Rock.Model.Group> GroupsAttended( DotLiquid.Context context, object input, string groupTypeId )
        {
            var person = GetPerson( input );
            int? numericalGroupTypeId = groupTypeId.AsIntegerOrNull();

            if ( person != null && numericalGroupTypeId.HasValue )
            {
                return new AttendanceService( GetRockContext( context ) ).Queryable().AsNoTracking()
                    .Where(a => a.Group.GroupTypeId == numericalGroupTypeId && a.PersonAlias.PersonId == person.Id && a.DidAttend == true)
                    .Select(a => a.Group).Distinct().ToList();
            }

            return new List<Model.Group>();
        }
Esempio n. 29
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. 30
0
        /// <summary>
        /// Determines whether [has rights to] [the specified context].
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="input">The input.</param>
        /// <param name="verb">The verb.</param>
        /// <param name="typeName">Name of the type.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception">Could not determine type for the input provided. Consider passing it in (e.g. 'Rock.Model.Person')</exception>
        public static bool HasRightsTo( DotLiquid.Context context, object input, string verb, string typeName = "" )
        {
            if (string.IsNullOrWhiteSpace( verb ) )
            {
                throw new Exception( "Could not determine the verd to check against (e.g. 'View', 'Edit'...)" );
            }

            if ( input == null )
            {
                return false;
            }
            else
            {
                var type = input.GetType();

                // if the input is a model call IsAuthorized and get out of here
                if ( type.IsAssignableFrom( typeof( ISecured ) ) )
                {
                    var model = (ISecured)input;
                    return model.IsAuthorized( verb, GetCurrentPerson( context ) );
                }

                // not so easy then...
                if ( string.IsNullOrWhiteSpace( typeName ) )
                {
                    // attempt to read it from the input object
                    var propertyInfo = type.GetProperty( "TypeName" );

                    if ( propertyInfo != null )
                    {
                        typeName = propertyInfo.GetValue( input, null ).ToString();
                    }

                    if ( string.IsNullOrWhiteSpace( typeName ) )
                    {
                        throw new Exception( "Could not determine type for the input provided. Consider passing it in (e.g. 'Rock.Model.Person')" );
                    }
                }

                int? id = null;

                if ( type == typeof( int ) )
                {
                    id = (int)input;
                }
                else if ( type == typeof( string ) )
                {
                    id = input.ToString().AsIntegerOrNull();
                }
                else
                {
                    // check if it has an id property
                    var propertyInfo = type.GetProperty( "Id" );

                    if ( propertyInfo != null )
                    {
                        id = (int)propertyInfo.GetValue( input, null );
                    }
                }

                if ( id.HasValue )
                {
                    var entityTypes = EntityTypeCache.All();
                    var entityTypeCache = entityTypes.Where( e => String.Equals( e.Name, typeName, StringComparison.OrdinalIgnoreCase ) ).FirstOrDefault();

                    if ( entityTypeCache != null )
                    {
                        RockContext _rockContext = new RockContext();

                        Type entityType = entityTypeCache.GetEntityType();
                        if ( entityType != null )
                        {
                            Type[] modelType = { entityType };
                            Type genericServiceType = typeof( Rock.Data.Service<> );
                            Type modelServiceType = genericServiceType.MakeGenericType( modelType );
                            Rock.Data.IService serviceInstance = Activator.CreateInstance( modelServiceType, new object[] { _rockContext } ) as IService;

                            MethodInfo getMethod = serviceInstance.GetType().GetMethod( "Get", new Type[] { typeof( int ) } );

                            if ( getMethod != null )
                            {
                                var model = getMethod.Invoke( serviceInstance, new object[] { id.Value } ) as ISecured;

                                if ( model != null )
                                {
                                    return model.IsAuthorized( verb, GetCurrentPerson( context ) );
                                }
                            }
                        }
                    }
                }
                else
                {
                    throw new Exception( "Could not determine the id of the entity." );
                }
            }

            return false;
        }