Esempio n. 1
0
        /// <summary>
        /// Saves an attribute value.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="attribute">The attribute.</param>
        /// <param name="newValue">The new value.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <remarks>
        /// If a rockContext value is included, this method will save any previous changes made to the context
        /// </remarks>
        public static void SaveAttributeValue(IHasAttributes model, Rock.Web.Cache.AttributeCache attribute, string newValue, RockContext rockContext = null)
        {
            if (model != null && attribute != null)
            {
                rockContext = rockContext ?? new RockContext();
                var attributeValueService = new Model.AttributeValueService(rockContext);

                var attributeValue = attributeValueService.GetByAttributeIdAndEntityId(attribute.Id, model.Id);
                if (attributeValue == null)
                {
                    if (newValue == null)
                    {
                        return;
                    }

                    attributeValue             = new Rock.Model.AttributeValue();
                    attributeValue.AttributeId = attribute.Id;
                    attributeValue.EntityId    = model.Id;
                    attributeValueService.Add(attributeValue);
                }

                attributeValue.Value = newValue;

                rockContext.SaveChanges();

                if (model.AttributeValues != null && model.AttributeValues.ContainsKey(attribute.Key))
                {
                    model.AttributeValues[attribute.Key] = attributeValue.Clone(false) as Rock.Model.AttributeValue;
                }
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Saves the attribute value.
        /// </summary>
        /// <param name="entityId">The entity identifier.</param>
        /// <param name="attribute">The attribute.</param>
        /// <param name="newValue">The new value.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <remarks>
        /// If a rockContext value is included, this method will save any previous changes made to the context
        /// </remarks>
        public static void SaveAttributeValue(int entityId, Rock.Web.Cache.AttributeCache attribute, string newValue, RockContext rockContext = null)
        {
            if (attribute != null)
            {
                rockContext = rockContext ?? new RockContext();
                var attributeValueService = new Model.AttributeValueService(rockContext);

                var attributeValue = attributeValueService.GetByAttributeIdAndEntityId(attribute.Id, entityId);
                if (attributeValue == null)
                {
                    if (newValue == null)
                    {
                        return;
                    }

                    attributeValue             = new Rock.Model.AttributeValue();
                    attributeValue.AttributeId = attribute.Id;
                    attributeValue.EntityId    = entityId;
                    attributeValueService.Add(attributeValue);
                }

                attributeValue.Value = newValue;

                rockContext.SaveChanges();
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Saves an attribute value.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="attribute">The attribute.</param>
        /// <param name="newValue">The new value.</param>
        /// <param name="personId">The person id.</param>
        public static void SaveAttributeValue(IHasAttributes model, Rock.Web.Cache.AttributeCache attribute, string newValue, int?personId)
        {
            Model.AttributeValueService attributeValueService = new Model.AttributeValueService();

            var attributeValue = attributeValueService.GetByAttributeIdAndEntityId(attribute.Id, model.Id).FirstOrDefault();

            if (attributeValue == null)
            {
                if (newValue == null)
                {
                    return;
                }

                attributeValue             = new Rock.Model.AttributeValue();
                attributeValue.AttributeId = attribute.Id;
                attributeValue.EntityId    = model.Id;
                attributeValue.Order       = 0;
                attributeValueService.Add(attributeValue, personId);
            }

            attributeValue.Value = newValue;

            attributeValueService.Save(attributeValue, personId);

            model.AttributeValues[attribute.Key] = new List <Rock.Model.AttributeValue>()
            {
                attributeValue.Clone() as Rock.Model.AttributeValue
            };
        }
Esempio n. 4
0
 /// <summary>
 /// Adds the person attribute.
 /// </summary>
 /// <param name="attribute">The attribute.</param>
 /// <param name="person">The person.</param>
 /// <param name="attributeValue">The value.</param>
 private static void AddPersonAttribute( AttributeCache attribute, Person person, string attributeValue )
 {
     if ( !string.IsNullOrWhiteSpace( attributeValue ) )
     {
         person.Attributes.Add( attribute.Key, attribute );
         person.AttributeValues.Add( attribute.Key, new AttributeValueCache()
         {
             AttributeId = attribute.Id,
             Value = attributeValue
         } );
     }
 }
Esempio n. 5
0
 /// <summary>
 /// Adds the person attribute.
 /// </summary>
 /// <param name="attribute">The attribute.</param>
 /// <param name="person">The person.</param>
 /// <param name="value">The value.</param>
 private static void AddPersonAttribute( AttributeCache attribute, Person person, string value, string personRole = "" )
 {
     if ( !string.IsNullOrWhiteSpace( value ) )
     {
         person.Attributes.Add( attribute.Key, attribute );
         person.AttributeValues.Add( attribute.Key, new AttributeValue()
         {
             AttributeId = attribute.Id,
             Value = value,
             ForeignId = personRole  //Attempting to correct the contribution, address, phone # issues where the visitor or child is selected before the adult. Also setting business.
         } );
     }
 }
Esempio n. 6
0
        public virtual HttpResponseMessage SetAttributeValue(int id, string attributeKey, string attributeValue)
        {
            T model;

            if (!Service.TryGet(id, out model))
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            CheckCanEdit(model);

            IHasAttributes modelWithAttributes = model as IHasAttributes;

            if (modelWithAttributes != null)
            {
                using (var rockContext = new RockContext())
                {
                    modelWithAttributes.LoadAttributes(rockContext);
                    Rock.Web.Cache.AttributeCache attributeCache = modelWithAttributes.Attributes.ContainsKey(attributeKey) ? modelWithAttributes.Attributes[attributeKey] : null;

                    if (attributeCache != null)
                    {
                        if (!attributeCache.IsAuthorized(Rock.Security.Authorization.EDIT, this.GetPerson()))
                        {
                            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)
                            {
                                ReasonPhrase = string.Format("Not authorized to edit {0} on {1}", modelWithAttributes.GetType().GetFriendlyTypeName(), attributeKey)
                            });
                        }

                        Rock.Attribute.Helper.SaveAttributeValue(modelWithAttributes, attributeCache, attributeValue, rockContext);
                        var response = ControllerContext.Request.CreateResponse(HttpStatusCode.Accepted, modelWithAttributes.Id);
                        return(response);
                    }
                    else
                    {
                        throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest)
                        {
                            ReasonPhrase = string.Format("{0} does not have a {1} attribute", modelWithAttributes.GetType().GetFriendlyTypeName(), attributeKey)
                        });
                    }
                }
            }
            else
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    ReasonPhrase = "specified item does not have attributes"
                });
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Saves an attribute value.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="attribute">The attribute.</param>
        /// <param name="newValues">The new values.</param>
        /// <param name="personId">The person id.</param>
        public static void SaveAttributeValues(IHasAttributes model, Rock.Web.Cache.AttributeCache attribute, List <Rock.Model.AttributeValue> newValues, int?personId)
        {
            Model.AttributeValueService attributeValueService = new Model.AttributeValueService();

            var attributeValues = attributeValueService.GetByAttributeIdAndEntityId(attribute.Id, model.Id).ToList();
            int i = 0;

            while (i < attributeValues.Count || i < newValues.Count)
            {
                Rock.Model.AttributeValue attributeValue;

                if (i < attributeValues.Count)
                {
                    attributeValue = attributeValues[i];
                }
                else
                {
                    attributeValue             = new Rock.Model.AttributeValue();
                    attributeValue.AttributeId = attribute.Id;
                    attributeValue.EntityId    = model.Id;
                    attributeValue.Order       = i;
                    attributeValueService.Add(attributeValue, personId);
                }

                if (i >= newValues.Count)
                {
                    attributeValueService.Delete(attributeValue, personId);
                }
                else
                {
                    if (attributeValue.Value != newValues[i].Value)
                    {
                        attributeValue.Value = newValues[i].Value;
                    }
                    newValues[i] = attributeValue.Clone() as Rock.Model.AttributeValue;
                }

                attributeValueService.Save(attributeValue, personId);

                i++;
            }

            model.AttributeValues[attribute.Key] = newValues;
        }
Esempio n. 8
0
 private string GetValue( string key, AttributeCache attributeCache, RockContext rockContext )
 {
     var attributeValue = new AttributeValueService( rockContext ).GetByAttributeIdAndEntityId( attributeCache.Id, null );
     string value = ( attributeValue != null && !string.IsNullOrEmpty( attributeValue.Value ) ) ? attributeValue.Value : attributeCache.DefaultValue;
     AttributeValues.AddOrUpdate( key, value, ( k, v ) => value );
     return value;
 }
Esempio n. 9
0
        /// <summary>
        /// Adds Attribute model to cache, and returns cached object.  
        /// </summary>
        /// <param name="attributeModel">The attribute model.</param>
        /// <param name="qualifiers">The qualifiers.</param>
        /// <returns></returns>
        public static AttributeCache Read( Rock.Model.Attribute attributeModel, Dictionary<string, string> qualifiers )
        {
            AttributeCache attribute = new AttributeCache( attributeModel, qualifiers );

            string cacheKey = AttributeCache.CacheKey( attributeModel.Id );

            ObjectCache cache = MemoryCache.Default;
            cache.Set( cacheKey, attribute, new CacheItemPolicy() );

            return attribute;
        }
Esempio n. 10
0
 /// <summary>
 /// Adds the person attribute.
 /// </summary>
 /// <param name="attribute">The attribute.</param>
 /// <param name="person">The person.</param>
 /// <param name="value">The value.</param>
 protected static void AddPersonAttribute( AttributeCache attribute, Person person, string value )
 {
     if ( attribute != null && !string.IsNullOrWhiteSpace( value ) )
     {
         person.Attributes.Add( attribute.Key, attribute );
         person.AttributeValues.Add( attribute.Key, new AttributeValueCache()
         {
             AttributeId = attribute.Id,
             Value = value
         } );
     }
 }
Esempio n. 11
0
        /// <summary>
        /// Returns Attribute object from cache.  If attribute does not already exist in cache, it
        /// will be read and added to cache
        /// </summary>
        /// <param name="id">The id of the Attribute to read</param>
        /// <returns></returns>
        public static AttributeCache Read( int id )
        {
            string cacheKey = AttributeCache.CacheKey( id );

            ObjectCache cache = MemoryCache.Default;
            AttributeCache attribute = cache[cacheKey] as AttributeCache;

            if ( attribute != null )
            {
                return attribute;
            }
            else
            {
                var attributeService = new Rock.Model.AttributeService();
                var attributeModel = attributeService.Get( id );
                if ( attributeModel != null )
                {
                    attribute = new AttributeCache( attributeModel );
                    cache.Set( cacheKey, attribute, new CacheItemPolicy() );
                    return attribute;
                }
                else
                {
                    return null;
                }
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Adds Attribute model to cache, and returns cached object
        /// </summary>
        /// <param name="attributeModel">The attributeModel to cache</param>
        /// <returns></returns>
        public static AttributeCache Read( Rock.Model.Attribute attributeModel )
        {
            string cacheKey = AttributeCache.CacheKey( attributeModel.Id );

            ObjectCache cache = MemoryCache.Default;
            AttributeCache attribute = cache[cacheKey] as AttributeCache;

            if ( attribute != null )
            {
                return attribute;
            }
            else
            {
                attribute = new AttributeCache( attributeModel );
                cache.Set( cacheKey, attribute, new CacheItemPolicy() );
                return attribute;
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Adds the entity field for attribute.
        /// </summary>
        /// <param name="entityFields">The entity fields.</param>
        /// <param name="attribute">The attribute.</param>
        public static void AddEntityFieldForAttribute( List<EntityField> entityFields, AttributeCache attribute )
        {
            // Ensure prop name is unique
            string propName = attribute.Name;
            int i = 1;
            while ( entityFields.Any( p => p.Name.Equals( propName, StringComparison.CurrentCultureIgnoreCase ) ) )
            {
                propName = attribute.Name + ( i++ ).ToString();
            }

            EntityField entityProperty = null;

            var fieldType = FieldTypeCache.Read( attribute.FieldTypeId );
            string fieldTypeUpperGuid = fieldType.Guid.ToString().ToUpper();

            switch ( fieldTypeUpperGuid )
            {
                case SystemGuid.FieldType.BOOLEAN:
                    entityProperty = new EntityField( attribute.Name, FieldKind.Attribute, null, 1, attribute.Guid );
                    entityProperty.FilterFieldType = SystemGuid.FieldType.SINGLE_SELECT;
                    break;

                case SystemGuid.FieldType.DATE:
                    entityProperty = new EntityField( attribute.Name, FieldKind.Attribute, null, 2, attribute.Guid );
                    entityProperty.FilterFieldType = SystemGuid.FieldType.DATE;
                    break;

                case SystemGuid.FieldType.TIME:
                    entityProperty = new EntityField( attribute.Name, FieldKind.Attribute, null, 2, attribute.Guid );
                    entityProperty.FilterFieldType = SystemGuid.FieldType.TIME;
                    break;

                case SystemGuid.FieldType.INTEGER:
                    entityProperty = new EntityField( attribute.Name, FieldKind.Attribute, null, 2, attribute.Guid );
                    entityProperty.FilterFieldType = SystemGuid.FieldType.INTEGER;
                    break;

                case SystemGuid.FieldType.DECIMAL:
                    entityProperty = new EntityField( attribute.Name, FieldKind.Attribute, null, 2, attribute.Guid );
                    entityProperty.FilterFieldType = SystemGuid.FieldType.DECIMAL;
                    break;

                case SystemGuid.FieldType.DAY_OF_WEEK:
                    entityProperty = new EntityField( attribute.Name, FieldKind.Attribute, null, 1, attribute.Guid );
                    entityProperty.FilterFieldType = SystemGuid.FieldType.DAY_OF_WEEK;
                    break;

                case SystemGuid.FieldType.MULTI_SELECT:
                    entityProperty = new EntityField( attribute.Name, FieldKind.Attribute, null, 1, attribute.Guid );
                    entityProperty.FilterFieldType = SystemGuid.FieldType.MULTI_SELECT;
                    break;

                case SystemGuid.FieldType.SINGLE_SELECT:
                    entityProperty = new EntityField( attribute.Name, FieldKind.Attribute, null, 1, attribute.Guid );
                    entityProperty.FilterFieldType = SystemGuid.FieldType.MULTI_SELECT;
                    break;

                case SystemGuid.FieldType.TEXT:
                    entityProperty = new EntityField( attribute.Name, FieldKind.Attribute, null, 2, attribute.Guid );
                    entityProperty.FilterFieldType = SystemGuid.FieldType.TEXT;
                    break;
            }

            if ( entityProperty != null )
            {
                if ( attribute.EntityTypeId == EntityTypeCache.GetId( typeof( Group ) ) && attribute.EntityTypeQualifierColumn == "GroupTypeId" )
                {
                    var groupType = new GroupTypeService( new RockContext() ).Get( attribute.EntityTypeQualifierValue.AsInteger() );
                    if ( groupType != null )
                    {
                        entityProperty.Title = string.Format( "{0} ({1})", attribute.Name.SplitCase(), groupType.Name );
                    }
                }

                entityFields.Add( entityProperty );
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Adds the entity field for attribute.
        /// </summary>
        /// <param name="entityFields">The entity fields.</param>
        /// <param name="attribute">The attribute.</param>
        public static void AddEntityFieldForAttribute( List<EntityField> entityFields, AttributeCache attribute )
        {
            // Ensure prop name is unique
            string propName = attribute.Key;
            int i = 1;
            while ( entityFields.Any( p => p.Name.Equals( propName, StringComparison.CurrentCultureIgnoreCase ) ) )
            {
                propName = attribute.Key + ( i++ ).ToString();
            }

            // Make sure that the attributes field type actually renders a filter control
            var fieldType = FieldTypeCache.Read( attribute.FieldTypeId );
            if ( fieldType != null && fieldType.Field.FilterControl( attribute.QualifierValues, propName, true ) != null )
            {
                var entityField = new EntityField();
                entityField.Name = propName;
                entityField.Title = attribute.Name.SplitCase();
                entityField.FieldKind = FieldKind.Attribute;
                entityField.PropertyType = typeof( string );
                entityField.AttributeGuid = attribute.Guid;
                entityField.FieldType = fieldType;
                foreach ( var config in attribute.QualifierValues )
                {
                    entityField.FieldConfig.Add( config.Key, config.Value );
                }

                if ( attribute.EntityTypeId == EntityTypeCache.GetId( typeof( Group ) ) && attribute.EntityTypeQualifierColumn == "GroupTypeId" )
                {
                    using ( var rockContext = new RockContext() )
                    {
                        var groupType = new GroupTypeService( rockContext ).Get( attribute.EntityTypeQualifierValue.AsInteger() );
                        if ( groupType != null )
                        {
                            entityField.Title = string.Format( "{0} ({1})", attribute.Name, groupType.Name );
                        }
                    }
                }

                entityFields.Add( entityField );
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Adds the entity field for attribute.
        /// </summary>
        /// <param name="entityFields">The entity fields.</param>
        /// <param name="attribute">The attribute.</param>
        /// <param name="limitToFilterableAttributes">if set to <c>true</c> [limit to filterable attributes].</param>
        public static void AddEntityFieldForAttribute( List<EntityField> entityFields, AttributeCache attribute, bool limitToFilterableAttributes = true )
        {
            var entityField = GetEntityFieldForAttribute( attribute, limitToFilterableAttributes );

            // If the field could not be created, we are done.
            if (entityField == null)
                return;

            // Ensure that the field name is unique.
            string fieldName = entityField.Name;

            int i = 1;
            while ( entityFields.Any( p => p.Name.Equals( fieldName, StringComparison.CurrentCultureIgnoreCase ) ) )
            {
                fieldName = entityField.Name + ( i++ ).ToString();
            }

            entityField.Name = fieldName;

            entityFields.Add( entityField );
        }
Esempio n. 16
0
 /// <summary>
 /// Removes attribute from cache
 /// </summary>
 /// <param name="id">The id of the attribute to remove from cache</param>
 public static void Flush(int id)
 {
     FlushCache(AttributeCache.CacheKey(id));
 }
Esempio n. 17
0
        /// <summary>
        /// Adds Attribute model to cache, and returns cached object
        /// </summary>
        /// <param name="attributeModel">The attributeModel to cache</param>
        /// <returns></returns>
        public static AttributeCache Read( Rock.Model.Attribute attributeModel )
        {
            string cacheKey = AttributeCache.CacheKey( attributeModel.Id );

            ObjectCache cache = MemoryCache.Default;
            AttributeCache attribute = cache[cacheKey] as AttributeCache;

            if ( attribute != null )
            {
                attribute.CopyFromModel( attributeModel );
            }
            else
            {
                attribute = new AttributeCache( attributeModel );
                var cachePolicy = new CacheItemPolicy();
                cache.Set( cacheKey, attribute, cachePolicy );
                cache.Set( attribute.Guid.ToString(), attribute.Id, cachePolicy );
            }

            return attribute;
        }
        /// <summary>
        /// Sends a background request to Protect My Ministry
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="workflow">The Workflow initiating the request.</param>
        /// <param name="personAttribute">The person attribute.</param>
        /// <param name="ssnAttribute">The SSN attribute.</param>
        /// <param name="requestTypeAttribute">The request type attribute.</param>
        /// <param name="billingCodeAttribute">The billing code attribute.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns>
        /// True/False value of whether the request was successfully sent or not
        /// </returns>
        /// <exception cref="System.NotImplementedException"></exception>
        /// <remarks>
        /// Note: If the associated workflow type does not have attributes with the following keys, they
        /// will automatically be added to the workflow type configuration in order to store the results
        /// of the PMM background check request
        ///     ReportStatus:           The status returned by PMM
        ///     ReportLink:             The location of the background report on PMM server
        ///     ReportRecommendation:   PMM's recomendataion
        ///     Report (BinaryFile):    The downloaded background report
        /// </remarks>
        public override bool SendRequest( RockContext rockContext, Model.Workflow workflow,
            AttributeCache personAttribute, AttributeCache ssnAttribute, AttributeCache requestTypeAttribute,
            AttributeCache billingCodeAttribute, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            try
            {
                // Check to make sure workflow is not null
                if ( workflow == null )
                {
                    errorMessages.Add( "The 'ProtectMyMinistry' requires a valid workflow." );
                    return false;
                }

                // Get the person that the request is for
                Person person = null;
                if ( personAttribute != null )
                {
                    Guid? personAliasGuid = workflow.GetAttributeValue( personAttribute.Key ).AsGuidOrNull();
                    if ( personAliasGuid.HasValue )
                    {
                        person = new PersonAliasService( rockContext ).Queryable()
                            .Where( p => p.Guid.Equals( personAliasGuid.Value ) )
                            .Select( p => p.Person )
                            .FirstOrDefault();
                    }
                }

                if ( person == null )
                {
                    errorMessages.Add( "The 'ProtectMyMinistry' background check requires the workflow to have a 'Person' attribute that contains the person who the background check is for." );
                    return false;
                }

                string password = Encryption.DecryptString( GetAttributeValue( "Password" ) );

                XElement rootElement = new XElement( "OrderXML",
                    new XElement( "Method", "SEND ORDER" ),
                    new XElement( "Authentication",
                        new XElement( "Username", GetAttributeValue( "UserName" ) ),
                        new XElement( "Password", password )
                    )
                );

                if ( GetAttributeValue( "TestMode" ).AsBoolean() )
                {
                    rootElement.Add( new XElement( "TestMode", "YES" ) );
                }

                rootElement.Add( new XElement( "ReturnResultURL", GetAttributeValue( "ReturnURL" ) ) );

                XElement orderElement = new XElement( "Order" );
                rootElement.Add( orderElement );

                if ( billingCodeAttribute != null )
                {
                    Guid? campusGuid = workflow.GetAttributeValue( billingCodeAttribute.Key ).AsGuidOrNull();
                    if ( campusGuid.HasValue )
                    {
                        var campus = CampusCache.Read( campusGuid.Value );
                        if ( campus != null )
                        {
                            orderElement.Add( new XElement( "BillingReferenceCode", campus.Name ) );
                        }
                    }
                }

                XElement subjectElement = new XElement( "Subject",
                    new XElement( "FirstName", person.FirstName ),
                    new XElement( "MiddleName", person.MiddleName ),
                    new XElement( "LastName", person.LastName )
                );
                orderElement.Add( subjectElement );

                if ( person.BirthDate.HasValue )
                {
                    subjectElement.Add( new XElement( "DOB", person.BirthDate.Value.ToString( "MM/dd/yyyy" ) ) );
                }

                if ( ssnAttribute != null )
                {
                    string ssn = Encryption.DecryptString( workflow.GetAttributeValue( ssnAttribute.Key ) ).AsNumeric();
                    if ( !string.IsNullOrWhiteSpace( ssn ) && ssn.Length == 9 )
                    {
                        subjectElement.Add( new XElement( "SSN", ssn.Insert( 5, "-" ).Insert( 3, "-" ) ) );
                    }
                }

                if ( person.Gender == Gender.Male )
                {
                    subjectElement.Add( new XElement( "Gender", "Male" ) );
                }
                if ( person.Gender == Gender.Female )
                {
                    subjectElement.Add( new XElement( "Gender", "Female" ) );
                }

                var homelocation = person.GetHomeLocation();
                if ( homelocation != null)
                {
                    subjectElement.Add( new XElement( "CurrentAddress",
                        new XElement( "StreetAddress", homelocation.Street1 ),
                        new XElement( "City", homelocation.City ),
                        new XElement( "State", homelocation.State ),
                        new XElement( "Zipcode", homelocation.PostalCode )
                    ) );
                }

                XElement aliasesElement = new XElement( "Aliases" );
                if ( person.NickName != person.FirstName )
                {
                    aliasesElement.Add( new XElement( "Alias", new XElement( "FirstName", person.NickName ) ) );
                }
                // foreach ( string lastName in [previous last names] )
                //{
                //    aliasesElement.Add( new XElement( "Alias", new XElement( "LastName", lastName ) ) );
                //}
                if ( aliasesElement.HasElements )
                {
                    subjectElement.Add( aliasesElement );
                }

                string packageType = requestTypeAttribute != null ? workflow.GetAttributeValue( requestTypeAttribute.Key ) : string.Empty;
                if ( string.IsNullOrWhiteSpace(packageType) )
                {
                    packageType = "Basic";
                }
                orderElement.Add( new XElement( "PackageServiceCode", packageType,
                    new XAttribute( "OrderId", workflow.Id.ToString() ) ) );
                orderElement.Add( new XElement( "OrderDetail",
                    new XAttribute( "OrderId", workflow.Id.ToString() ),
                    new XAttribute( "ServiceCode", "combo" ) ) );

                XDocument xdoc = new XDocument( new XDeclaration( "1.0", "UTF-8", "yes" ), rootElement );

                XDocument xResult = PostToWebService( xdoc, GetAttributeValue("RequestURL") );

                if ( _HTTPStatusCode == HttpStatusCode.OK )
                {
                    if ( xResult.Root.Descendants().Count() > 0 )
                    {
                        SaveResults( xResult, workflow, rockContext );
                    }
                    return true;
                }
                else
                {
                    errorMessages.Add( "Invalid HttpStatusCode: " + _HTTPStatusCode.ToString() );
                }

                return false;

            }
            catch( Exception ex )
            {
                ExceptionLogService.LogException( ex, null );
                errorMessages.Add( ex.Message );
                return false;
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Reads the specified GUID.
        /// </summary>
        /// <param name="guid">The GUID.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        public static AttributeCache Read( Guid guid, RockContext rockContext = null )
        {
            ObjectCache cache = MemoryCache.Default;
            object cacheObj = cache[guid.ToString()];

            AttributeCache attribute = null;
            if ( cacheObj != null )
            {
                attribute = Read( (int)cacheObj );
            }

            if ( attribute == null )
            {
                rockContext = rockContext ?? new RockContext();
                var attributeService = new AttributeService( rockContext );
                var attributeModel = attributeService.Get( guid );
                if ( attributeModel != null )
                {
                    attribute = new AttributeCache( attributeModel );

                    var cachePolicy = new CacheItemPolicy();
                    cache.Set( AttributeCache.CacheKey( attribute.Id ), attribute, cachePolicy );
                    cache.Set( attribute.Guid.ToString(), attribute.Id, cachePolicy );
                }
            }

            return attribute;
        }
Esempio n. 20
0
        /// <summary>
        /// Returns Attribute object from cache.  If attribute does not already exist in cache, it
        /// will be read and added to cache
        /// </summary>
        /// <param name="id">The id of the Attribute to read</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        public static AttributeCache Read( int id, RockContext rockContext = null )
        {
            string cacheKey = AttributeCache.CacheKey( id );

            ObjectCache cache = MemoryCache.Default;
            AttributeCache attribute = cache[cacheKey] as AttributeCache;

            if ( attribute == null )
            {
                rockContext = rockContext ?? new RockContext();
                var attributeService = new Rock.Model.AttributeService( rockContext );
                var attributeModel = attributeService.Get( id );
                if ( attributeModel != null )
                {
                    attribute = new AttributeCache( attributeModel );

                    var cachePolicy = new CacheItemPolicy();
                    cache.Set( cacheKey, attribute, cachePolicy );
                    cache.Set( attribute.Guid.ToString(), attribute.Id, cachePolicy );
                }
            }

            return attribute;
        }
Esempio n. 21
0
        /// <summary>
        /// Removes attribute from cache
        /// </summary>
        /// <param name="id">The id of the attribute to remove from cache</param>
        public static void Flush(int id)
        {
            ObjectCache cache = MemoryCache.Default;

            cache.Remove(AttributeCache.CacheKey(id));
        }
Esempio n. 22
0
        /// <summary>
        /// Adds the entity field for attribute.
        /// </summary>
        /// <param name="entityFields">The entity fields.</param>
        /// <param name="attribute">The attribute.</param>
        /// <param name="limitToFilterableAttributes">if set to <c>true</c> [limit to filterable attributes].</param>
        public static void AddEntityFieldForAttribute( List<EntityField> entityFields, AttributeCache attribute, bool limitToFilterableAttributes = true )
        {
            // Ensure prop name only has Alpha, Numeric and underscore chars
            string propName = attribute.Key.RemoveSpecialCharacters().Replace( ".", "" );

            // Ensure prop name is unique
            int i = 1;
            while ( entityFields.Any( p => p.Name.Equals( propName, StringComparison.CurrentCultureIgnoreCase ) ) )
            {
                propName = attribute.Key + ( i++ ).ToString();
            }

            // Make sure that the attributes field type actually renders a filter control if limitToFilterableAttributes
            var fieldType = FieldTypeCache.Read( attribute.FieldTypeId );
            if ( fieldType != null && ( !limitToFilterableAttributes || fieldType.Field.HasFilterControl() ) )
            {
                var entityField = new EntityField( propName, FieldKind.Attribute, typeof( string ), attribute.Guid, fieldType );
                entityField.Title = attribute.Name.SplitCase();

                foreach ( var config in attribute.QualifierValues )
                {
                    entityField.FieldConfig.Add( config.Key, config.Value );
                }

                if ( attribute.EntityTypeId == EntityTypeCache.GetId( typeof( Group ) ) && attribute.EntityTypeQualifierColumn == "GroupTypeId" )
                {
                    using ( var rockContext = new RockContext() )
                    {
                        var groupType = new GroupTypeService( rockContext ).Get( attribute.EntityTypeQualifierValue.AsInteger() );
                        if ( groupType != null )
                        {
                            entityField.Title = string.Format( "{0} ({1})", attribute.Name, groupType.Name );
                        }
                    }
                }

                entityFields.Add( entityField );
            }
        }
Esempio n. 23
0
 /// <summary>
 /// Adds Attribute model to cache, and returns cached object
 /// </summary>
 /// <param name="attributeModel">The attributeModel to cache</param>
 /// <returns></returns>
 public static AttributeCache Read(Rock.Model.Attribute attributeModel)
 {
     return(GetOrAddExisting(AttributeCache.CacheKey(attributeModel.Id),
                             () => LoadByModel(attributeModel)));
 }
 /// <summary>
 /// Abstract method for sending a background request. Derived classes should implement
 /// this method to initiate a background request. Because requests will be made through a
 /// workflow, the workflow is passed to this method. It is up to the derived class to
 /// evaluate/update any workflow attributes it needs
 /// </summary>
 /// <param name="rockContext">The rock context.</param>
 /// <param name="workflow">The Workflow initiating the request.</param>
 /// <param name="personAttribute">The person attribute.</param>
 /// <param name="ssnAttribute">The SSN attribute.</param>
 /// <param name="requestTypeAttribute">The request type attribute.</param>
 /// <param name="billingCodeAttribute">The billing code attribute.</param>
 /// <param name="errorMessages">The error messages.</param>
 /// <returns>
 /// True/False value of whether the request was successfully sent or not
 /// </returns>
 public abstract bool SendRequest( RockContext rockContext, Rock.Model.Workflow workflow, 
     AttributeCache personAttribute, AttributeCache ssnAttribute, AttributeCache requestTypeAttribute, 
     AttributeCache billingCodeAttribute, out List<string> errorMessages );
Esempio n. 25
0
 /// <summary>
 /// Returns Attribute object from cache.  If attribute does not already exist in cache, it
 /// will be read and added to cache
 /// </summary>
 /// <param name="id">The id of the Attribute to read</param>
 /// <param name="rockContext">The rock context.</param>
 /// <returns></returns>
 public static AttributeCache Read(int id, RockContext rockContext = null)
 {
     return(GetOrAddExisting(AttributeCache.CacheKey(id),
                             () => LoadById(id, rockContext)));
 }
Esempio n. 26
0
 /// <summary>
 /// Adds Attribute model to cache, and returns cached object.
 /// </summary>
 /// <param name="attributeModel">The attribute model.</param>
 /// <param name="qualifiers">The qualifiers.</param>
 /// <returns></returns>
 public static AttributeCache Read(Rock.Model.Attribute attributeModel, Dictionary <string, string> qualifiers)
 {
     return(GetOrAddExisting(AttributeCache.CacheKey(attributeModel.Id),
                             () => LoadByModel(attributeModel, qualifiers)));
 }
Esempio n. 27
0
        /// <summary>
        /// Sends a background request to Protect My Ministry
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="workflow">The Workflow initiating the request.</param>
        /// <param name="personAttribute">The person attribute.</param>
        /// <param name="ssnAttribute">The SSN attribute.</param>
        /// <param name="requestTypeAttribute">The request type attribute.</param>
        /// <param name="billingCodeAttribute">The billing code attribute.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns>
        /// True/False value of whether the request was successfully sent or not
        /// </returns>
        /// <exception cref="System.NotImplementedException"></exception>
        /// <remarks>
        /// Note: If the associated workflow type does not have attributes with the following keys, they
        /// will automatically be added to the workflow type configuration in order to store the results
        /// of the PMM background check request
        ///     RequestStatus:          The request status returned by PMM request
        ///     RequestMessage:         Any error messages returned by PMM request
        ///     ReportStatus:           The report status returned by PMM
        ///     ReportLink:             The location of the background report on PMM server
        ///     ReportRecommendation:   PMM's recomendataion
        ///     Report (BinaryFile):    The downloaded background report
        /// </remarks>
        public override bool SendRequest( RockContext rockContext, Model.Workflow workflow,
            AttributeCache personAttribute, AttributeCache ssnAttribute, AttributeCache requestTypeAttribute,
            AttributeCache billingCodeAttribute, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            try
            {
                // Check to make sure workflow is not null
                if ( workflow == null )
                {
                    errorMessages.Add( "The 'Protect My Ministry' background check provider requires a valid workflow." );
                    return false;
                }

                // Get the person that the request is for
                Person person = null;
                if ( personAttribute != null )
                {
                    Guid? personAliasGuid = workflow.GetAttributeValue( personAttribute.Key ).AsGuidOrNull();
                    if ( personAliasGuid.HasValue )
                    {
                        person = new PersonAliasService( rockContext ).Queryable()
                            .Where( p => p.Guid.Equals( personAliasGuid.Value ) )
                            .Select( p => p.Person )
                            .FirstOrDefault();
                        person.LoadAttributes( rockContext );
                    }
                }

                if ( person == null )
                {
                    errorMessages.Add( "The 'Protect My Ministry' background check provider requires the workflow to have a 'Person' attribute that contains the person who the background check is for." );
                    return false;
                }

                string password = Encryption.DecryptString( GetAttributeValue( "Password" ) );

                XElement rootElement = new XElement( "OrderXML",
                    new XElement( "Method", "SEND ORDER" ),
                    new XElement( "Authentication",
                        new XElement( "Username", GetAttributeValue( "UserName" ) ),
                        new XElement( "Password", password )
                    )
                );

                if ( GetAttributeValue( "TestMode" ).AsBoolean() )
                {
                    rootElement.Add( new XElement( "TestMode", "YES" ) );
                }

                rootElement.Add( new XElement( "ReturnResultURL", GetAttributeValue( "ReturnURL" ) ) );

                XElement orderElement = new XElement( "Order" );
                rootElement.Add( orderElement );

                if ( billingCodeAttribute != null )
                {
                    string billingCode = workflow.GetAttributeValue( billingCodeAttribute.Key );
                    Guid? campusGuid = billingCode.AsGuidOrNull();
                    if ( campusGuid.HasValue )
                    {
                        var campus = CampusCache.Read( campusGuid.Value );
                        if ( campus != null )
                        {
                            billingCode = campus.Name;
                        }
                    }
                    orderElement.Add( new XElement( "BillingReferenceCode", billingCode ) );
                }

                XElement subjectElement = new XElement( "Subject",
                    new XElement( "FirstName", person.FirstName ),
                    new XElement( "MiddleName", person.MiddleName ),
                    new XElement( "LastName", person.LastName )
                );
                orderElement.Add( subjectElement );

                if ( person.SuffixValue != null )
                {
                    subjectElement.Add( new XElement( "Generation", person.SuffixValue.Value ) );
                }
                if ( person.BirthDate.HasValue )
                {
                    subjectElement.Add( new XElement( "DOB", person.BirthDate.Value.ToString( "MM/dd/yyyy" ) ) );
                }

                if ( ssnAttribute != null )
                {
                    string ssn = Encryption.DecryptString( workflow.GetAttributeValue( ssnAttribute.Key ) ).AsNumeric();
                    if ( !string.IsNullOrWhiteSpace( ssn ) && ssn.Length == 9 )
                    {
                        subjectElement.Add( new XElement( "SSN", ssn.Insert( 5, "-" ).Insert( 3, "-" ) ) );
                    }
                }

                if ( person.Gender == Gender.Male )
                {
                    subjectElement.Add( new XElement( "Gender", "Male" ) );
                }
                if ( person.Gender == Gender.Female )
                {
                    subjectElement.Add( new XElement( "Gender", "Female" ) );
                }

                string dlNumber = person.GetAttributeValue( "com.sparkdevnetwork.DLNumber" );
                if ( !string.IsNullOrWhiteSpace( dlNumber ) )
                {
                    subjectElement.Add( new XElement( "DLNumber", dlNumber ) );
                }

                var homelocation = person.GetHomeLocation();
                if ( homelocation != null)
                {
                    subjectElement.Add( new XElement( "CurrentAddress",
                        new XElement( "StreetAddress", homelocation.Street1 ),
                        new XElement( "City", homelocation.City ),
                        new XElement( "State", homelocation.State ),
                        new XElement( "Zipcode", homelocation.PostalCode )
                    ) );
                }

                XElement aliasesElement = new XElement( "Aliases" );
                if ( person.NickName != person.FirstName )
                {
                    aliasesElement.Add( new XElement( "Alias", new XElement( "FirstName", person.NickName ) ) );
                }

                foreach ( var previousName in person.GetPreviousNames() )
                {
                    aliasesElement.Add( new XElement( "Alias", new XElement( "LastName", previousName.LastName ) ) );
                }

                if ( aliasesElement.HasElements )
                {
                    subjectElement.Add( aliasesElement );
                }

                DefinedValueCache pkgTypeDefinedValue = null;
                string packageName = "BASIC";
                string county = string.Empty;
                string state = string.Empty;
                string mvrJurisdiction = string.Empty;
                string mvrState = string.Empty;

                if ( requestTypeAttribute != null )
                {
                    pkgTypeDefinedValue = DefinedValueCache.Read( workflow.GetAttributeValue( requestTypeAttribute.Key ).AsGuid() );
                    if ( pkgTypeDefinedValue != null )
                    {
                        if ( pkgTypeDefinedValue.Attributes == null )
                        {
                            pkgTypeDefinedValue.LoadAttributes( rockContext );
                        }

                        packageName = pkgTypeDefinedValue.GetAttributeValue("PMMPackageName");
                        county = pkgTypeDefinedValue.GetAttributeValue( "DefaultCounty" );
                        state = pkgTypeDefinedValue.GetAttributeValue( "DefaultState" );
                        Guid? mvrJurisdictionGuid = pkgTypeDefinedValue.GetAttributeValue( "MVRJurisdiction" ).AsGuidOrNull();
                        if ( mvrJurisdictionGuid.HasValue )
                        {
                            var mvrJurisdictionDv = DefinedValueCache.Read( mvrJurisdictionGuid.Value );
                            if ( mvrJurisdictionDv != null )
                            {
                                mvrJurisdiction = mvrJurisdictionDv.Value;
                                if ( mvrJurisdiction.Length >= 2 )
                                {
                                    mvrState = mvrJurisdiction.Left( 2 );
                                }
                            }
                        }

                        if ( homelocation != null )
                        {
                            if ( !string.IsNullOrWhiteSpace( homelocation.County ) &&
                                pkgTypeDefinedValue.GetAttributeValue("SendHomeCounty").AsBoolean() )
                            {
                                county = homelocation.County;
                            }

                            if ( !string.IsNullOrWhiteSpace( homelocation.State ) )
                            {
                                if ( pkgTypeDefinedValue.GetAttributeValue( "SendHomeState" ).AsBoolean() )
                                {
                                    state = homelocation.State;
                                }
                                if ( pkgTypeDefinedValue.GetAttributeValue( "SendHomeStateMVR" ).AsBoolean() )
                                {
                                    mvrState = homelocation.State;
                                }
                            }
                        }
                    }
                }

                if ( !string.IsNullOrWhiteSpace( packageName ) )
                {
                    orderElement.Add( new XElement( "PackageServiceCode", packageName,
                        new XAttribute( "OrderId", workflow.Id.ToString() ) ) );

                    if ( packageName.Trim().Equals( "BASIC", StringComparison.OrdinalIgnoreCase ) ||
                        packageName.Trim().Equals( "PLUS", StringComparison.OrdinalIgnoreCase ) )
                    {
                        orderElement.Add( new XElement( "OrderDetail",
                            new XAttribute( "OrderId", workflow.Id.ToString() ),
                            new XAttribute( "ServiceCode", "combo" ) ) );
                    }
                }

                if ( !string.IsNullOrWhiteSpace( county ) ||
                    !string.IsNullOrWhiteSpace( state ) )
                {
                    orderElement.Add( new XElement( "OrderDetail",
                        new XAttribute( "OrderId", workflow.Id.ToString() ),
                        new XAttribute( "ServiceCode", string.IsNullOrWhiteSpace(county) ? "StateCriminal" : "CountyCrim" ),
                        new XElement( "County", county ),
                        new XElement( "State", state ),
                        new XElement( "YearsToSearch", 7 ),
                        new XElement( "CourtDocsRequested", "NO" ),
                        new XElement( "RushRequested", "NO" ),
                        new XElement( "SpecialInstructions", "" ) )
                    );
                }

                if ( !string.IsNullOrWhiteSpace( mvrJurisdiction ) && !string.IsNullOrWhiteSpace( mvrState ) )
                {
                    orderElement.Add( new XElement( "OrderDetail",
                        new XAttribute( "OrderId", workflow.Id.ToString() ),
                        new XAttribute( "ServiceCode", "MVR" ),
                        new XElement( "JurisdictionCode", mvrJurisdiction ),
                        new XElement( "State", mvrState ) )
                    );
                }

                XDocument xdoc = new XDocument( new XDeclaration( "1.0", "UTF-8", "yes" ), rootElement );
                var requestDateTime = RockDateTime.Now;

                XDocument xResult = PostToWebService( xdoc, GetAttributeValue("RequestURL") );
                var responseDateTime = RockDateTime.Now;

                int? personAliasId = person.PrimaryAliasId;
                if ( personAliasId.HasValue )
                {
                    // Create a background check file
                    using ( var newRockContext = new RockContext() )
                    {
                        var backgroundCheckService = new BackgroundCheckService( newRockContext );
                        var backgroundCheck = backgroundCheckService.Queryable()
                            .Where( c =>
                                c.WorkflowId.HasValue &&
                                c.WorkflowId.Value == workflow.Id )
                            .FirstOrDefault();

                        if ( backgroundCheck == null )
                        {
                            backgroundCheck = new Rock.Model.BackgroundCheck();
                            backgroundCheck.PersonAliasId = personAliasId.Value;
                            backgroundCheck.WorkflowId = workflow.Id;
                            backgroundCheckService.Add( backgroundCheck );
                        }

                        backgroundCheck.RequestDate = RockDateTime.Now;

                        // Clear any SSN nodes before saving XML to record
                        foreach ( var xSSNElement in xdoc.Descendants( "SSN" ) )
                        {
                            xSSNElement.Value = "XXX-XX-XXXX";
                        }
                        foreach ( var xSSNElement in xResult.Descendants( "SSN" ) )
                        {
                            xSSNElement.Value = "XXX-XX-XXXX";
                        }

                        backgroundCheck.ResponseXml = string.Format( @"
            Request XML ({0}):
            ------------------------
            {1}

            Response XML ({2}):
            ------------------------
            {3}

            ", requestDateTime, xdoc.ToString(), responseDateTime, xResult.ToString() );
                        newRockContext.SaveChanges();
                    }
                }

                if ( _HTTPStatusCode == HttpStatusCode.OK )
                {
                    using ( var newRockContext = new RockContext() )
                    {
                        bool createdNewAttribute = false;
                        var xOrderXML = xResult.Elements( "OrderXML" ).FirstOrDefault();
                        if ( xOrderXML != null )
                        {
                            var xStatus = xOrderXML.Elements( "Status" ).FirstOrDefault();
                            if ( xStatus != null )
                            {
                                if ( SaveAttributeValue( workflow, "RequestStatus", xStatus.Value,
                                    FieldTypeCache.Read( Rock.SystemGuid.FieldType.TEXT.AsGuid() ), newRockContext, null ) )
                                {
                                    createdNewAttribute = true;
                                }
                            }

                            var xErrors = xOrderXML.Elements( "Errors" ).FirstOrDefault();
                            if ( xErrors != null )
                            {
                                string errorMsg = xErrors.Elements( "Message" ).Select( x => x.Value ).ToList().AsDelimited( Environment.NewLine );
                                if ( SaveAttributeValue( workflow, "RequestMessage", errorMsg,
                                    FieldTypeCache.Read( Rock.SystemGuid.FieldType.TEXT.AsGuid() ), newRockContext, null ) )
                                {
                                    createdNewAttribute = true;
                                }
                            }

                            if ( xResult.Root.Descendants().Count() > 0 )
                            {
                                SaveResults( xResult, workflow, rockContext, false );
                            }
                        }
                        else
                        {
                            if ( SaveAttributeValue( workflow, "RequestMessage", errorMessages.AsDelimited( Environment.NewLine ),
                                FieldTypeCache.Read( Rock.SystemGuid.FieldType.TEXT.AsGuid() ), newRockContext, null ) )
                            {
                                createdNewAttribute = true;
                            }

                        }

                        newRockContext.SaveChanges();

                        if ( createdNewAttribute )
                        {
                            AttributeCache.FlushEntityAttributes();
                        }
                    }
                    return true;
                }
                else
                {
                    errorMessages.Add( "Invalid HttpStatusCode: " + _HTTPStatusCode.ToString() );
                    return false;
                }
            }

            catch ( Exception ex )
            {
                ExceptionLogService.LogException( ex, null );
                errorMessages.Add( ex.Message );
                return false;
            }
        }
        private static Guid? SaveFile( AttributeCache binaryFileAttribute, string url, string fileName )
        {
            // get BinaryFileType info
            if ( binaryFileAttribute != null &&
                binaryFileAttribute.QualifierValues != null &&
                binaryFileAttribute.QualifierValues.ContainsKey( "binaryFileType" ) )
            {
                Guid? fileTypeGuid = binaryFileAttribute.QualifierValues["binaryFileType"].Value.AsGuidOrNull();
                if ( fileTypeGuid.HasValue )
                {
                    RockContext rockContext = new RockContext();
                    BinaryFileType binaryFileType = new BinaryFileTypeService( rockContext ).Get( fileTypeGuid.Value );

                    if ( binaryFileType != null )
                    {
                        byte[] data = null;

                        using ( WebClient wc = new WebClient() )
                        {
                            data = wc.DownloadData( url );
                        }

                        BinaryFile binaryFile = new BinaryFile();
                        binaryFile.Guid = Guid.NewGuid();
                        binaryFile.IsTemporary = true;
                        binaryFile.BinaryFileTypeId = binaryFileType.Id;
                        binaryFile.MimeType = "application/pdf";
                        binaryFile.FileName = fileName;
                        binaryFile.ContentStream = new MemoryStream( data );

                        var binaryFileService = new BinaryFileService( rockContext );
                        binaryFileService.Add( binaryFile );

                        rockContext.SaveChanges();

                        return binaryFile.Guid;
                    }
                }
            }

            return null;
        }
Esempio n. 29
0
        /// <summary>
        /// Loads Rock data that's used globally by the transform
        /// </summary>
        private void LoadExistingRockData()
        {
            var lookupContext = new RockContext();
            var attributeValueService = new AttributeValueService( lookupContext );
            var attributeService = new AttributeService( lookupContext );

            IntegerFieldTypeId = FieldTypeCache.Read( new Guid( Rock.SystemGuid.FieldType.INTEGER ) ).Id;
            TextFieldTypeId = FieldTypeCache.Read( new Guid( Rock.SystemGuid.FieldType.TEXT ) ).Id;
            PersonEntityTypeId = EntityTypeCache.Read( "Rock.Model.Person" ).Id;
            CampusList = CampusCache.All();

            int attributeEntityTypeId = EntityTypeCache.Read( "Rock.Model.Attribute" ).Id;
            int batchEntityTypeId = EntityTypeCache.Read( "Rock.Model.FinancialBatch" ).Id;
            int userLoginTypeId = EntityTypeCache.Read( "Rock.Model.UserLogin" ).Id;

            int visitInfoCategoryId = new CategoryService( lookupContext ).GetByEntityTypeId( attributeEntityTypeId )
                .Where( c => c.Name == "Visit Information" ).Select( c => c.Id ).FirstOrDefault();

            // Look up and create attributes for F1 unique identifiers if they don't exist
            var personAttributes = attributeService.GetByEntityTypeId( PersonEntityTypeId ).AsNoTracking().ToList();

            var householdAttribute = personAttributes.FirstOrDefault( a => a.Key.Equals( "F1HouseholdId", StringComparison.InvariantCultureIgnoreCase ) );
            if ( householdAttribute == null )
            {
                householdAttribute = new Rock.Model.Attribute();
                householdAttribute.Key = "F1HouseholdId";
                householdAttribute.Name = "F1 Household Id";
                householdAttribute.FieldTypeId = IntegerFieldTypeId;
                householdAttribute.EntityTypeId = PersonEntityTypeId;
                householdAttribute.EntityTypeQualifierValue = string.Empty;
                householdAttribute.EntityTypeQualifierColumn = string.Empty;
                householdAttribute.Description = "The FellowshipOne household identifier for the person that was imported";
                householdAttribute.DefaultValue = string.Empty;
                householdAttribute.IsMultiValue = false;
                householdAttribute.IsRequired = false;
                householdAttribute.Order = 0;

                lookupContext.Attributes.Add( householdAttribute );
                lookupContext.SaveChanges( DisableAuditing );
                personAttributes.Add( householdAttribute );
            }

            var individualAttribute = personAttributes.FirstOrDefault( a => a.Key.Equals( "F1IndividualId", StringComparison.InvariantCultureIgnoreCase ) );
            if ( individualAttribute == null )
            {
                individualAttribute = new Rock.Model.Attribute();
                individualAttribute.Key = "F1IndividualId";
                individualAttribute.Name = "F1 Individual Id";
                individualAttribute.FieldTypeId = IntegerFieldTypeId;
                individualAttribute.EntityTypeId = PersonEntityTypeId;
                individualAttribute.EntityTypeQualifierValue = string.Empty;
                individualAttribute.EntityTypeQualifierColumn = string.Empty;
                individualAttribute.Description = "The FellowshipOne individual identifier for the person that was imported";
                individualAttribute.DefaultValue = string.Empty;
                individualAttribute.IsMultiValue = false;
                individualAttribute.IsRequired = false;
                individualAttribute.Order = 0;

                lookupContext.Attributes.Add( individualAttribute );
                lookupContext.SaveChanges( DisableAuditing );
                personAttributes.Add( individualAttribute );
            }

            var secondaryEmailAttribute = personAttributes.FirstOrDefault( a => a.Key.Equals( "SecondaryEmail", StringComparison.InvariantCultureIgnoreCase ) );
            if ( secondaryEmailAttribute == null )
            {
                secondaryEmailAttribute = new Rock.Model.Attribute();
                secondaryEmailAttribute.Key = "SecondaryEmail";
                secondaryEmailAttribute.Name = "Secondary Email";
                secondaryEmailAttribute.FieldTypeId = TextFieldTypeId;
                secondaryEmailAttribute.EntityTypeId = PersonEntityTypeId;
                secondaryEmailAttribute.EntityTypeQualifierValue = string.Empty;
                secondaryEmailAttribute.EntityTypeQualifierColumn = string.Empty;
                secondaryEmailAttribute.Description = "The secondary email for this person";
                secondaryEmailAttribute.DefaultValue = string.Empty;
                secondaryEmailAttribute.IsMultiValue = false;
                secondaryEmailAttribute.IsRequired = false;
                secondaryEmailAttribute.Order = 0;

                lookupContext.Attributes.Add( secondaryEmailAttribute );
                var visitInfoCategory = new CategoryService( lookupContext ).Get( visitInfoCategoryId );
                secondaryEmailAttribute.Categories.Add( visitInfoCategory );
                lookupContext.SaveChanges( DisableAuditing );
            }

            var infellowshipLoginAttribute = personAttributes.FirstOrDefault( a => a.Key.Equals( "InFellowshipLogin", StringComparison.InvariantCultureIgnoreCase ) );
            if ( infellowshipLoginAttribute == null )
            {
                infellowshipLoginAttribute = new Rock.Model.Attribute();
                infellowshipLoginAttribute.Key = "InFellowshipLogin";
                infellowshipLoginAttribute.Name = "InFellowship Login";
                infellowshipLoginAttribute.FieldTypeId = TextFieldTypeId;
                infellowshipLoginAttribute.EntityTypeId = PersonEntityTypeId;
                infellowshipLoginAttribute.EntityTypeQualifierValue = string.Empty;
                infellowshipLoginAttribute.EntityTypeQualifierColumn = string.Empty;
                infellowshipLoginAttribute.Description = "The InFellowship login for this person";
                infellowshipLoginAttribute.DefaultValue = string.Empty;
                infellowshipLoginAttribute.IsMultiValue = false;
                infellowshipLoginAttribute.IsRequired = false;
                infellowshipLoginAttribute.Order = 0;

                // don't add a category as this attribute is only used via the API
                lookupContext.Attributes.Add( infellowshipLoginAttribute );
                lookupContext.SaveChanges( DisableAuditing );
            }

            IndividualIdAttribute = AttributeCache.Read( individualAttribute.Id );
            HouseholdIdAttribute = AttributeCache.Read( householdAttribute.Id );
            InFellowshipLoginAttribute = AttributeCache.Read( infellowshipLoginAttribute.Id );
            SecondaryEmailAttribute = AttributeCache.Read( secondaryEmailAttribute.Id );

            // Set AuthProviderEntityTypeId if Apollos/Infellowship provider exists
            var f1AuthProvider = "cc.newspring.F1.Security.Authentication.F1Migrator";
            var cache = EntityTypeCache.Read( f1AuthProvider );
            AuthProviderEntityTypeId = cache == null ? (int?)null : cache.Id;

            var aliasIdList = new PersonAliasService( lookupContext ).Queryable().AsNoTracking()
                .Select( pa => new
                {
                    PersonAliasId = pa.Id,
                    PersonId = pa.PersonId,
                    IndividualId = pa.ForeignId,
                    FamilyRole = pa.Person.ReviewReasonNote
                } ).ToList();
            var householdIdList = attributeValueService.GetByAttributeId( householdAttribute.Id ).AsNoTracking()
                .Select( av => new
                {
                    PersonId = (int)av.EntityId,
                    HouseholdId = av.Value
                } ).ToList();

            ImportedPeople = householdIdList.GroupJoin( aliasIdList,
                household => household.PersonId,
                aliases => aliases.PersonId,
                ( household, aliases ) => new PersonKeys
                    {
                        PersonAliasId = aliases.Select( a => a.PersonAliasId ).FirstOrDefault(),
                        PersonId = household.PersonId,
                        IndividualId = aliases.Select( a => a.IndividualId ).FirstOrDefault(),
                        HouseholdId = household.HouseholdId.AsType<int?>(),
                        FamilyRoleId = aliases.Select( a => a.FamilyRole.ConvertToEnum<FamilyRole>( 0 ) ).FirstOrDefault()
                    }
                ).ToList();

            ImportedBatches = new FinancialBatchService( lookupContext ).Queryable().AsNoTracking()
                .Where( b => b.ForeignId != null )
                .ToDictionary( t => (int)t.ForeignId, t => (int?)t.Id );
        }
Esempio n. 30
0
        /// <summary>
        /// Create an EntityField for an Attribute.
        /// </summary>
        /// <param name="attribute">The attribute.</param>
        /// <param name="limitToFilterableAttributes"></param>
        public static EntityField GetEntityFieldForAttribute( AttributeCache attribute, bool limitToFilterableAttributes = true )
        {
            // Ensure field name only has Alpha, Numeric and underscore chars
            string fieldName = attribute.Key.RemoveSpecialCharacters().Replace( ".", "" );

            EntityField entityField = null;

            // Make sure that the attributes field type actually renders a filter control if limitToFilterableAttributes
            var fieldType = FieldTypeCache.Read( attribute.FieldTypeId );
            if ( fieldType != null && ( !limitToFilterableAttributes || fieldType.Field.HasFilterControl() ) )
            {
                entityField = new EntityField( fieldName, FieldKind.Attribute, typeof( string ), attribute.Guid, fieldType );
                entityField.Title = attribute.Name.SplitCase();
                entityField.TitleWithoutQualifier = entityField.Title;

                foreach ( var config in attribute.QualifierValues )
                {
                    entityField.FieldConfig.Add( config.Key, config.Value );
                }

                // Special processing for Entity Type "Group" to handle sub-types that are distinguished by GroupTypeId.
                if ( attribute.EntityTypeId == EntityTypeCache.GetId( typeof( Group ) ) && attribute.EntityTypeQualifierColumn == "GroupTypeId" )
                {
                    using ( var rockContext = new RockContext() )
                    {
                        var groupType = GroupTypeCache.Read( attribute.EntityTypeQualifierValue.AsInteger(), rockContext );
                        if ( groupType != null )
                        {
                            // Append the Qualifier to the title
                            entityField.AttributeEntityTypeQualifierName = groupType.Name;
                            entityField.Title = string.Format( "{0} ({1})", attribute.Name, groupType.Name );
                        }
                    }
                }

                // Special processing for Entity Type "ContentChannelItem" to handle sub-types that are distinguished by ContentChannelTypeId.
                if ( attribute.EntityTypeId == EntityTypeCache.GetId( typeof( ContentChannelItem ) ) && attribute.EntityTypeQualifierColumn == "ContentChannelTypeId" )
                {
                    using ( var rockContext = new RockContext() )
                    {
                        var contentChannelType = new ContentChannelTypeService( rockContext ).Get( attribute.EntityTypeQualifierValue.AsInteger() );
                        if ( contentChannelType != null )
                        {
                            // Append the Qualifier to the title
                            entityField.AttributeEntityTypeQualifierName = contentChannelType.Name;
                            entityField.Title = string.Format( "{0} ({1})", attribute.Name, contentChannelType.Name );
                        }
                    }
                }

                // Special processing for Entity Type "Workflow" to handle sub-types that are distinguished by WorkflowTypeId.
                if ( attribute.EntityTypeId == EntityTypeCache.GetId( typeof( Rock.Model.Workflow ) ) && attribute.EntityTypeQualifierColumn == "WorkflowTypeId" )
                {
                    using ( var rockContext = new RockContext() )
                    {
                        int workflowTypeId = attribute.EntityTypeQualifierValue.AsInteger();
                        if (_workflowTypeNameLookup == null)
                        {
                            _workflowTypeNameLookup = new WorkflowTypeService( rockContext ).Queryable().ToDictionary( k => k.Id, v => v.Name );
                        }

                        var workflowTypeName = _workflowTypeNameLookup.ContainsKey( workflowTypeId ) ? _workflowTypeNameLookup[workflowTypeId] : null;
                        if ( workflowTypeName != null )
                        {
                            // Append the Qualifier to the title for Workflow Attributes
                            entityField.AttributeEntityTypeQualifierName = workflowTypeName;
                            entityField.Title = string.Format( "({1}) {0} ", attribute.Name, workflowTypeName );
                        }
                    }
                }
            }

            return entityField;
        }
Esempio n. 31
0
        private static void AddAttributeCategory(List <AttributeCategory> attributeCategories, Rock.Web.Cache.CategoryCache category, Rock.Web.Cache.AttributeCache attribute)
        {
            AttributeCategory attributeCategory = null;

            if (category != null)
            {
                attributeCategory = attributeCategories.Where(g => g.Category != null && g.Category.Id == category.Id).FirstOrDefault();
            }
            else
            {
                attributeCategory = attributeCategories.Where(g => g.Category == null).FirstOrDefault();
            }

            if (attributeCategory == null)
            {
                attributeCategory            = new AttributeCategory();
                attributeCategory.Category   = category;
                attributeCategory.Attributes = new List <Web.Cache.AttributeCache>();
                attributeCategories.Add(attributeCategory);
            }

            attributeCategory.Attributes.Add(attribute);
        }