Service/Data Access class for Rock.Model.DefinedValue entity objects.
        /// <summary>
        /// Binds the package grid.
        /// </summary>
        public void BindPackageGrid()
        {
            using ( var rockContext = new RockContext() )
            {
                var definedValues = new DefinedValueService( rockContext )
                    .GetByDefinedTypeGuid( Rock.SystemGuid.DefinedType.PROTECT_MY_MINISTRY_PACKAGES.AsGuid() )
                    .ToList();

                foreach( var definedValue in definedValues )
                {
                    definedValue.LoadAttributes( rockContext );
                }

                gDefinedValues.DataSource = definedValues.Select( v => new
                {
                    v.Id,
                    v.Value,
                    v.Description,
                    PackageName = v.GetAttributeValue( "PMMPackageName" ),
                    DefaultCounty = v.GetAttributeValue( "DefaultCounty" ),
                    SendAddressCounty = v.GetAttributeValue( "SendHomeCounty" ).AsBoolean(),
                    DefaultState = v.GetAttributeValue( "DefaultState" ),
                    SendAddressState = v.GetAttributeValue( "SendHomeState" ).AsBoolean(),
                    MVRJurisdication = v.GetAttributeValue("MVRJurisdiction"),
                    SendAddressStateMVR = v.GetAttributeValue( "SendHomeStateMVR" ).AsBoolean()
                } )
                .ToList();
                gDefinedValues.DataBind();
            }
        }
Пример #2
0
        protected void btnSaveStars_OnClick(object sender, EventArgs e)
        {
            // ddl
            var x = Convert.ToInt32(ddlStars.SelectedItem.Value);

            DefinedValueService definedValueService = new DefinedValueService(rockContext);

            var definedValue = definedValueService.Queryable().FirstOrDefault(a => a.Id == x);
            definedValue.LoadAttributes();
            var attributeValue = definedValue.GetAttributeValue("StarValue");
            var starsValue = Convert.ToDecimal(attributeValue);

            var pa = Person.PrimaryAliasId;
            //var pa = ppPerson.PersonAliasId;
            //var value = Decimal.Parse(tbValue.Text);

            StarsService starsService = new StarsService(starsProjectContext);

            org.newpointe.Stars.Model.Stars stars = new org.newpointe.Stars.Model.Stars();

            stars.PersonAliasId = pa.GetValueOrDefault();
            stars.CampusId = 1;
            stars.TransactionDateTime = DateTime.Now;
            stars.Value = starsValue;
            stars.Note = ddlStars.SelectedItem.Text + ". Manually added by " + CurrentPerson.FullName;

            starsService.Add(stars);

            starsProjectContext.SaveChanges();

            //Refresh Page to update grids
            Response.Redirect(Request.RawUrl);
        }
Пример #3
0
        /// <summary>
        /// Loads the drop downs.
        /// </summary>
        private void LoadDropDowns()
        {
            var list = new Rock.Model.DefinedValueService().GetByDefinedTypeGuid(new Guid(com.ccvonline.SystemGuid.DefinedType.RESIDENCY_POINT_OF_ASSESSMENT_TYPE))
                       .OrderBy(a => a.Name).ToList();

            list.Insert(0, new DefinedValue {
                Id = Rock.Constants.None.Id, Name = Rock.Constants.None.Text
            });

            ddlPointOfAssessmentTypeValue.DataSource = list;
            ddlPointOfAssessmentTypeValue.DataBind();
        }
Пример #4
0
        /// <summary>
        /// Loads the cache objects.
        /// </summary>
        private void LoadCacheObjects()
        {
            using (new Rock.Data.UnitOfWorkScope())
            {
                // Cache all the Field Types
                var fieldTypeService = new Rock.Model.FieldTypeService();
                foreach (var fieldType in fieldTypeService.Queryable().ToList())
                {
                    Rock.Web.Cache.FieldTypeCache.Read(fieldType);
                }

                // Cache all tha Defined Types
                var definedTypeService = new Rock.Model.DefinedTypeService();
                foreach (var definedType in definedTypeService.Queryable().ToList())
                {
                    Rock.Web.Cache.DefinedTypeCache.Read(definedType);
                }

                // Cache all the Defined Values
                var definedValueService = new Rock.Model.DefinedValueService();
                foreach (var definedValue in definedValueService.Queryable().ToList())
                {
                    Rock.Web.Cache.DefinedValueCache.Read(definedValue);
                }

                // Read all the qualifiers first so that EF doesn't perform a query for each attribute when it's cached
                var qualifiers = new Dictionary <int, Dictionary <string, string> >();
                foreach (var attributeQualifier in new Rock.Model.AttributeQualifierService().Queryable())
                {
                    if (!qualifiers.ContainsKey(attributeQualifier.AttributeId))
                    {
                        qualifiers.Add(attributeQualifier.AttributeId, new Dictionary <string, string>());
                    }
                    qualifiers[attributeQualifier.AttributeId].Add(attributeQualifier.Key, attributeQualifier.Value);
                }

                // Cache all the attributes.
                foreach (var attribute in new Rock.Model.AttributeService().Queryable().ToList())
                {
                    if (qualifiers.ContainsKey(attribute.Id))
                    {
                        Rock.Web.Cache.AttributeCache.Read(attribute, qualifiers[attribute.Id]);
                    }
                    else
                    {
                        Rock.Web.Cache.AttributeCache.Read(attribute, new Dictionary <string, string>());
                    }
                }
            }
        }
Пример #5
0
        /// <summary>
        /// Loads the cache objects.
        /// </summary>
        private void LoadCacheObjects(RockContext rockContext)
        {
            // Read all the qualifiers first so that EF doesn't perform a query for each attribute when it's cached
            var qualifiers = new Dictionary <int, Dictionary <string, string> >();

            foreach (var attributeQualifier in new Rock.Model.AttributeQualifierService(rockContext).Queryable())
            {
                if (!qualifiers.ContainsKey(attributeQualifier.AttributeId))
                {
                    qualifiers.Add(attributeQualifier.AttributeId, new Dictionary <string, string>());
                }
                qualifiers[attributeQualifier.AttributeId].Add(attributeQualifier.Key, attributeQualifier.Value);
            }

            // Cache all the attributes.
            foreach (var attribute in new Rock.Model.AttributeService(rockContext).Queryable("Categories").ToList())
            {
                if (qualifiers.ContainsKey(attribute.Id))
                {
                    Rock.Web.Cache.AttributeCache.Read(attribute, qualifiers[attribute.Id]);
                }
                else
                {
                    Rock.Web.Cache.AttributeCache.Read(attribute, new Dictionary <string, string>());
                }
            }

            // Cache all the Field Types
            var all = Rock.Web.Cache.FieldTypeCache.All();

            // DT: When running with production CCV Data, this is taking a considerable amount of time

            // Cache all tha Defined Types
            var definedTypeService = new Rock.Model.DefinedTypeService(rockContext);

            foreach (var definedType in definedTypeService.Queryable().ToList())
            {
                Rock.Web.Cache.DefinedTypeCache.Read(definedType);
            }

            // Cache all the Defined Values
            var definedValueService = new Rock.Model.DefinedValueService(rockContext);

            foreach (var definedValue in definedValueService.Queryable().ToList())
            {
                Rock.Web.Cache.DefinedValueCache.Read(definedValue);
            }
        }
Пример #6
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad( EventArgs e )
        {
            base.OnLoad( e );

            if ( Page.IsPostBack )
            {
                var rockContext = new RockContext();
                var definedValueService = new DefinedValueService(rockContext);

                foreach ( RepeaterItem item in rptrValues.Items )
                {
                    var hfValue = item.FindControl( "hfValue" ) as HiddenField;
                    var cbValue = item.FindControl( "cbValue" ) as CheckBox;

                    if ( hfValue != null && cbValue != null )
                    {
                        var value = definedValueService.Get( hfValue.ValueAsInt() );
                        if ( value != null )
                        {
                            Helper.LoadAttributes( value );
                            if ( value.GetAttributeValue( attributeKey ) != cbValue.Checked.ToString() )
                            {
                                value.SetAttributeValue( attributeKey, cbValue.Checked.ToString() );
                                value.SaveAttributeValues();
                                DefinedValueCache.Flush( value.Id );
                            }
                        }
                    }
                }
            }

            bool wasVisible = this.Visible;

            ShowList();

            if ( Page.IsPostBack && wasVisible && this.Visible == false )
            {
                // If last item was just checked do a redirect back to the same page.  
                // This is needed to hide the control since content is inside an update 
                // panel
                Response.Redirect( CurrentPageReference.BuildUrl(), false );
            }
        }
        /// <summary>
        /// Handles the Delete event of the gDefinedType control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void gDefinedType_Delete( object sender, RowEventArgs e )
        {
            var rockContext = new RockContext();
            var definedValueService = new DefinedValueService( rockContext );
            var definedTypeService = new DefinedTypeService( rockContext );

            DefinedType type = definedTypeService.Get( e.RowKeyId );

            if ( type != null )
            {
                string errorMessage;
                if ( !definedTypeService.CanDelete( type, out errorMessage ) )
                {
                    mdGridWarning.Show( errorMessage, ModalAlertType.Information );
                    return;
                }

                // if this DefinedType has DefinedValues, see if they can be deleted
                var definedValues = definedValueService.GetByDefinedTypeId( type.Id ).ToList();

                foreach ( var value in definedValues )
                {
                    if ( !definedValueService.CanDelete( value, out errorMessage ) )
                    {
                        mdGridWarning.Show( errorMessage, ModalAlertType.Information );
                        return;
                    }
                }

                foreach ( var value in definedValues )
                {
                    definedValueService.Delete( value );
                }

                definedTypeService.Delete( type );

                rockContext.SaveChanges();
            }

            gDefinedType_Bind();
        }
Пример #8
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad( EventArgs e )
        {
            base.OnLoad( e );

            if ( Page.IsPostBack )
            {
                var definedValueService = new DefinedValueService();

                foreach ( RepeaterItem item in rptrValues.Items )
                {
                    var hfValue = item.FindControl( "hfValue" ) as HiddenField;
                    var cbValue = item.FindControl( "cbValue" ) as CheckBox;

                    if ( hfValue != null && cbValue != null )
                    {
                        var value = definedValueService.Get( hfValue.ValueAsInt() );
                        if ( value != null )
                        {
                            Helper.LoadAttributes( value );
                            value.SetAttributeValue( attributeKey, cbValue.Checked.ToString() );
                            Helper.SaveAttributeValues( value, CurrentPersonId );
                            DefinedValueCache.Flush( value.Id );
                        }
                    }
                }
            }

            ShowList();

            if (Page.IsPostBack && pnlContent.Visible == false)
            {
                // If last item was just checked (postback and visible == false), 
                // do a redirect back to the same page.  This is needed to hide 
                // the pre/post content which is outside of this controls update panel.
                Response.Redirect( CurrentPageReference.BuildUrl(), false );
            }

        }
Пример #9
0
        /// <summary>
        /// Handles the Delete event of the gDefinedValues control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void gDefinedValues_Delete( object sender, RowEventArgs e )
        {
            var valueService = new DefinedValueService();

            DefinedValue value = valueService.Get( (int)e.RowKeyValue );

            DefinedTypeCache.Flush(value.DefinedTypeId);
            DefinedValueCache.Flush(value.Id);

            if ( value != null )
            {
                valueService.Delete( value, CurrentPersonId );
                valueService.Save( value, CurrentPersonId );
            }

            BindDefinedValuesGrid();
        }
        /// <summary>
        /// Handles the Click event of the lbSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbSave_Click( object sender, EventArgs e )
        {
            var rockContext = new RockContext();
            rockContext.WrapTransaction( () =>
            {
                var personService = new PersonService( rockContext );
                var changes = new List<string>();
                Person business = null;

                if ( int.Parse( hfBusinessId.Value ) != 0 )
                {
                    business = personService.Get( int.Parse( hfBusinessId.Value ) );
                }

                if ( business == null )
                {
                    business = new Person();
                    personService.Add( business );
                }

                // Business Name
                History.EvaluateChange( changes, "Last Name", business.LastName, tbBusinessName.Text );
                business.LastName = tbBusinessName.Text;

                // Phone Number
                var businessPhoneTypeId = new DefinedValueService( rockContext ).GetByGuid( new Guid( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK ) ).Id;

                string oldPhoneNumber = string.Empty;
                string newPhoneNumber = string.Empty;

                var phoneNumber = business.PhoneNumbers.FirstOrDefault( n => n.NumberTypeValueId == businessPhoneTypeId );
                if ( phoneNumber != null )
                {
                    oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                }

                if ( !string.IsNullOrWhiteSpace( PhoneNumber.CleanNumber( pnbPhone.Number ) ) )
                {
                    if ( phoneNumber == null )
                    {
                        phoneNumber = new PhoneNumber { NumberTypeValueId = businessPhoneTypeId };
                        business.PhoneNumbers.Add( phoneNumber );
                    }
                    phoneNumber.CountryCode = PhoneNumber.CleanNumber( pnbPhone.CountryCode );
                    phoneNumber.Number = PhoneNumber.CleanNumber( pnbPhone.Number );
                    phoneNumber.IsMessagingEnabled = cbSms.Checked;
                    phoneNumber.IsUnlisted = cbUnlisted.Checked;

                    newPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                }
                else
                {
                    if ( phoneNumber != null )
                    {
                        business.PhoneNumbers.Remove( phoneNumber );
                        new PhoneNumberService( rockContext ).Delete( phoneNumber );
                    }
                }

                History.EvaluateChange(
                    changes,
                    string.Format( "{0} Phone", DefinedValueCache.GetName( businessPhoneTypeId ) ),
                    oldPhoneNumber,
                    newPhoneNumber );

                // Record Type - this is always "business". it will never change.
                business.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid() ).Id;

                // Record Status
                int? newRecordStatusId = ddlRecordStatus.SelectedValueAsInt();
                History.EvaluateChange( changes, "Record Status", DefinedValueCache.GetName( business.RecordStatusValueId ), DefinedValueCache.GetName( newRecordStatusId ) );
                business.RecordStatusValueId = newRecordStatusId;

                // Record Status Reason
                int? newRecordStatusReasonId = null;
                if ( business.RecordStatusValueId.HasValue && business.RecordStatusValueId.Value == DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ) ).Id )
                {
                    newRecordStatusReasonId = ddlReason.SelectedValueAsInt();
                }

                History.EvaluateChange( changes, "Record Status Reason", DefinedValueCache.GetName( business.RecordStatusReasonValueId ), DefinedValueCache.GetName( newRecordStatusReasonId ) );
                business.RecordStatusReasonValueId = newRecordStatusReasonId;

                // Email
                business.IsEmailActive = true;
                History.EvaluateChange( changes, "Email", business.Email, tbEmail.Text );
                business.Email = tbEmail.Text.Trim();

                var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum<EmailPreference>();
                History.EvaluateChange( changes, "EmailPreference", business.EmailPreference, newEmailPreference );
                business.EmailPreference = newEmailPreference;

                if ( business.IsValid )
                {
                    if ( rockContext.SaveChanges() > 0 )
                    {
                        if ( changes.Any() )
                        {
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof( Person ),
                                Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                business.Id,
                                changes );
                        }
                    }
                }

                // Add/Update Family Group
                var familyGroupType = GroupTypeCache.GetFamilyGroupType();
                int adultRoleId = familyGroupType.Roles
                    .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid() ) )
                    .Select( r => r.Id )
                    .FirstOrDefault();
                var adultFamilyMember = UpdateGroupMember( business.Id, familyGroupType, business.LastName + " Business", ddlCampus.SelectedValueAsInt(), adultRoleId, rockContext );
                business.GivingGroup = adultFamilyMember.Group;

                // Add/Update Known Relationship Group Type
                var knownRelationshipGroupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid() );
                int knownRelationshipOwnerRoleId = knownRelationshipGroupType.Roles
                    .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid() ) )
                    .Select( r => r.Id )
                    .FirstOrDefault();
                var knownRelationshipOwner = UpdateGroupMember( business.Id, knownRelationshipGroupType, "Known Relationship", null, knownRelationshipOwnerRoleId, rockContext );

                // Add/Update Implied Relationship Group Type
                var impliedRelationshipGroupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_IMPLIED_RELATIONSHIPS.AsGuid() );
                int impliedRelationshipOwnerRoleId = impliedRelationshipGroupType.Roles
                    .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_IMPLIED_RELATIONSHIPS_OWNER.AsGuid() ) )
                    .Select( r => r.Id )
                    .FirstOrDefault();
                var impliedRelationshipOwner = UpdateGroupMember( business.Id, impliedRelationshipGroupType, "Implied Relationship", null, impliedRelationshipOwnerRoleId, rockContext );

                rockContext.SaveChanges();

                // Every business should have an alias record with same id.  If it's missing, create it
                if ( !business.Aliases.Any( a => a.AliasPersonId == business.Id ) )
                {
                    // refetch the business to make sure we have an Id
                    business = personService.Get( business.Id );
                    if ( business != null )
                    {
                        business.Aliases.Add( new PersonAlias { AliasPersonId = business.Id, AliasPersonGuid = business.Guid } );
                        rockContext.SaveChanges();
                    }
                }

                // Location
                int workLocationTypeId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK ).Id;

                var groupLocationService = new GroupLocationService( rockContext );
                var workLocation = groupLocationService.Queryable( "Location" )
                    .Where( gl =>
                        gl.GroupId == adultFamilyMember.Group.Id &&
                        gl.GroupLocationTypeValueId == workLocationTypeId )
                    .FirstOrDefault();

                if ( string.IsNullOrWhiteSpace( acAddress.Street1 ) )
                {
                    if ( workLocation != null )
                    {
                        groupLocationService.Delete( workLocation );
                        History.EvaluateChange( changes, "Address", workLocation.Location.ToString(), string.Empty );
                    }
                }
                else
                {
                    var oldValue = string.Empty;

                    var newLocation = new LocationService( rockContext ).Get(
                        acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country );

                    if ( workLocation != null )
                    {
                        oldValue = workLocation.Location.ToString();
                    }
                    else
                    {
                        workLocation = new GroupLocation();
                        groupLocationService.Add( workLocation );
                        workLocation.GroupId = adultFamilyMember.Group.Id;
                        workLocation.GroupLocationTypeValueId = workLocationTypeId;
                    }
                    workLocation.Location = newLocation;

                    History.EvaluateChange( changes, "Address", oldValue, newLocation.ToString() );
                }

                rockContext.SaveChanges();

                hfBusinessId.Value = business.Id.ToString();
            } );

            ShowSummary( hfBusinessId.Value.AsInteger() );
        }
        protected void dlgPackage_SaveClick( object sender, EventArgs e )
        {
            int definedValueId = hfDefinedValueId.Value.AsInteger();

            var definedType = DefinedTypeCache.Read( Rock.SystemGuid.DefinedType.PROTECT_MY_MINISTRY_PACKAGES.AsGuid() );
            if ( definedType != null )
            {
                using ( var rockContext = new RockContext() )
                {
                    var service = new DefinedValueService( rockContext );

                    DefinedValue definedValue = null;
                    if ( !definedValueId.Equals( 0 ) )
                    {
                        definedValue = service.Get( definedValueId );
                    }

                    if ( definedValue == null )
                    {
                        definedValue = new DefinedValue();
                        definedValue.DefinedTypeId = definedType.Id;
                        service.Add( definedValue );
                    }

                    definedValue.Value = tbTitle.Text;
                    definedValue.Description = tbDescription.Text;
                    rockContext.SaveChanges();

                    definedValue.LoadAttributes( rockContext );

                    Guid? dvJurisdicationCodeGuid = null;
                    int? dvJurisdictionCodeId = ddlMVRJurisdication.SelectedValueAsInt();
                    if ( dvJurisdictionCodeId.HasValue && dvJurisdictionCodeId.Value > 0 )
                    {
                        var dvJurisdicationCode = DefinedValueCache.Read( dvJurisdictionCodeId.Value );
                        if ( dvJurisdicationCode != null )
                        {
                            dvJurisdicationCodeGuid = dvJurisdicationCode.Guid;
                        }
                    }

                    definedValue.SetAttributeValue( "PMMPackageName", tbPackageName.Text );
                    definedValue.SetAttributeValue( "DefaultCounty", tbDefaultCounty.Text );
                    definedValue.SetAttributeValue( "SendHomeCounty", cbSendCounty.Checked.ToString() );
                    definedValue.SetAttributeValue( "DefaultState", tbDefaultState.Text );
                    definedValue.SetAttributeValue( "SendHomeState", cbSendState.Checked.ToString() );
                    definedValue.SetAttributeValue( "MVRJurisdiction", dvJurisdicationCodeGuid.HasValue ? dvJurisdicationCodeGuid.Value.ToString() : string.Empty );
                    definedValue.SetAttributeValue( "SendHomeStateMVR", cbSendStateMVR.Checked.ToString() );
                    definedValue.SaveAttributeValues( rockContext );

                    DefinedTypeCache.Flush( definedType.Id );
                    DefinedValueCache.Flush( definedValue.Id );
                }
            }

            BindPackageGrid();

            HideDialog();
        }
Пример #12
0
        /// <summary>
        /// Maps the attendance.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <returns></returns>
        //private DateTime? StartDateTime { get; set;}
        private void MapAttendance( IQueryable<Row> tableData )
        {
            var lookupContext = new RockContext();
            int completed = 0;
            int totalRows = tableData.Count();
            int percentage = ( totalRows - 1 ) / 100 + 1;
            ReportProgress( 0, string.Format( "Verifying Attendance import ({0:N0} found).", totalRows ) );

            var attendanceList = new List<Rock.Model.Attendance>();
            var groupService = new GroupService( lookupContext );
            var existingGroupList = new List<Group>();
            existingGroupList = groupService.Queryable().ToList();

            foreach ( var row in tableData )
            {

                   DateTime? startTime = row["Start_Date_Time"] as DateTime?;
                if ( startTime != null && startTime != DateTime.MinValue)
                {
                    DateTime startDateTime = (DateTime)startTime;
                    if ( startDateTime.Year == 2014 && startDateTime.Month >= 1 && startDateTime.Month <= 8 )
                    {

                    //startDateTime = BruteForceDateTime(startTime);

                    var attendance = new Rock.Model.Attendance();
                    attendance.CreatedByPersonAliasId = ImportPersonAlias.Id;
                    attendance.ModifiedByPersonAliasId = ImportPersonAlias.Id;
                    attendance.CreatedDateTime = DateTime.Today;
                    attendance.ModifiedDateTime = DateTime.Today;
                    attendance.StartDateTime = startDateTime; //(DateTime)startTime;
                    attendance.DidAttend = true;
                    attendance.CampusId = 1; //Campus is needed for attendance to show in attendance analysis.

                    //string position = row["CheckedInAs"] as string;
                    //string jobTitle = row["Job_Title"] as string;
                    //string machineName = row["Checkin_Machine_Name"] as string;
                    int? rlcId = row["RLC_ID"] as int?;

                    int? individualId = row["Individual_ID"] as int?;

                        if ( individualId != null )
                        {
                            attendance.PersonAliasId = GetPersonAliasId( individualId );
                        }

                        DateTime? checkInTime = row["Check_In_Time"] as DateTime?;
                        if ( checkInTime != null )
                        {
                            // set the start time to the time they actually checked in. If null it maintains Start_Date_Time
                            attendance.StartDateTime = (DateTime)checkInTime; //BruteForceDateTime( checkInTime );
                        }

                        DateTime? checkOutTime = row["Check_Out_Time"] as DateTime?;
                        if ( checkOutTime != null )
                        {
                            attendance.EndDateTime = (DateTime)checkOutTime; //BruteForceDateTime( checkOutTime );
                        }

                        //string f1AttendanceCode = row["Tag_Code"] as string;
                        //if ( f1AttendanceCode != null )
                        //{
                        //    attendance.AttendanceCode = new Rock.Model.AttendanceCode();
                        //    attendance.AttendanceCode.Code = f1AttendanceCode;
                        //}
                        string f1AttendanceCheckedInAs = row["CheckedInAs"] as string;
                        if ( f1AttendanceCheckedInAs != null )
                        {
                            attendance.Note = f1AttendanceCheckedInAs;
                        }

                        // look up location, schedule, and device -- all of these fields can be null if need be
                        attendance.LocationId = GetLocationId( Convert.ToInt32( rlcId ) );

                        //look up Group
                        Group rlcGroup = existingGroupList.Where( g => g.ForeignId == ( rlcId.ToString() ) ).FirstOrDefault();
                        if ( rlcGroup != null )
                        {
                            attendance.GroupId = rlcGroup.Id;
                        }

                        var dvService = new DefinedValueService( lookupContext );

                        attendance.SearchTypeValueId = dvService.Queryable().Where( dv => dv.Value == "Phone Number" ).FirstOrDefault().Id;

                        //ReportProgress( 0, string.Format( "{0},{1},{2},{3},{4},{5},{6},{7},{8}", individualId,rlcId,rlcGroup.Name,attendance.CreatedByPersonAliasId,attendance.ModifiedByPersonAliasId,attendance.StartDateTime,attendance.DidAttend,attendance.AttendanceCode,attendance.LocationId ) );

                        //look into creating DeviceIds and Locations (Generic)

                        // Other Attributes to create:
                        // Tag_Comment
                        // BreakoutGroup_Name
                        // Pager_Code

                        //attendanceList.Add( attendance );

                        completed++;
                        if ( completed % percentage < 1 )
                        {
                            int percentComplete = completed / percentage;
                            ReportProgress( percentComplete, string.Format( "Completed: {0:N0} Percent Completed: {0:N0} ", completed, percentComplete ) );
                        }
                    //    else if ( completed % ReportingNumber < 1 )
                    //    {
                    //        var rockContext = new RockContext();
                    //        rockContext.WrapTransaction( () =>
                    //{
                    //    rockContext.Configuration.AutoDetectChangesEnabled = false;
                    //    rockContext.Attendances.AddRange( attendanceList );
                    //    rockContext.SaveChanges( DisableAudit );
                    //} );

                    //        ReportPartialProgress();
                    //    }

                        var rockContext = new RockContext();
                        rockContext.WrapTransaction( () =>
                        {
                            rockContext.Configuration.AutoDetectChangesEnabled = false;

                            rockContext.Attendances.Add( attendance );
                            rockContext.SaveChanges( DisableAudit );
                        } );

                        ReportPartialProgress();
                }
              }
               }
        }
        /// <summary>
        /// Loads the drop downs.
        /// </summary>
        private void LoadDropDowns( int? groupTypeId )
        {
            ddlAttendanceRule.BindToEnum<Rock.Model.AttendanceRule>();

            cblScheduleTypes.Items.Clear();
            cblScheduleTypes.Items.Add( new ListItem( "Weekly", "1" ) );
            cblScheduleTypes.Items.Add( new ListItem( "Custom", "2" ) );
            cblScheduleTypes.Items.Add( new ListItem( "Named", "4" ) );

            cblLocationSelectionModes.Items.Clear();
            cblLocationSelectionModes.Items.Add( new ListItem( "Named", "2" ) );
            cblLocationSelectionModes.Items.Add( new ListItem( "Address", "1" ) );
            cblLocationSelectionModes.Items.Add( new ListItem( "Point", "4" ) );
            cblLocationSelectionModes.Items.Add( new ListItem( "Geo-fence", "8" ) );
            cblLocationSelectionModes.Items.Add( new ListItem( "Group Member Address", "16" ) );

            var rockContext = new RockContext();
            gtpInheritedGroupType.GroupTypes = new GroupTypeService( rockContext ).Queryable()
                .Where( g => g.Id != groupTypeId )
                .ToList();

            var groupTypePurposeList = new DefinedValueService( rockContext ).GetByDefinedTypeGuid( new Guid( Rock.SystemGuid.DefinedType.GROUPTYPE_PURPOSE ) ).OrderBy( a => a.Value ).ToList();

            ddlGroupTypePurpose.Items.Clear();
            ddlGroupTypePurpose.Items.Add( Rock.Constants.None.ListItem );
            foreach ( var item in groupTypePurposeList )
            {
                ddlGroupTypePurpose.Items.Add( new ListItem( item.Value, item.Id.ToString() ) );
            }
        }
Пример #14
0
        /// <summary>
        /// Creates the control(s) neccessary for prompting user for a new value
        /// </summary>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="id"></param>
        /// <returns>
        /// The control
        /// </returns>
        public override Control EditControl( Dictionary<string, ConfigurationValue> configurationValues, string id )
        {
            ListControl editControl;

            if ( configurationValues != null && configurationValues.ContainsKey( ALLOW_MULTIPLE_KEY ) && configurationValues[ ALLOW_MULTIPLE_KEY ].Value.AsBoolean() )
            {
                editControl = new Rock.Web.UI.Controls.RockCheckBoxList { ID = id }; 
                editControl.AddCssClass( "checkboxlist-group" );
            }
            else
            {
                editControl = new Rock.Web.UI.Controls.RockDropDownList { ID = id }; 
                editControl.Items.Add( new ListItem() );
            }

            if ( configurationValues != null && configurationValues.ContainsKey( DEFINED_TYPE_KEY ) )
            {
                int definedTypeId = 0;
                if ( Int32.TryParse( configurationValues[DEFINED_TYPE_KEY].Value, out definedTypeId ) )
                {
                    Rock.Model.DefinedValueService definedValueService = new Model.DefinedValueService();
                    foreach ( var definedValue in definedValueService.GetByDefinedTypeId( definedTypeId ) )
                    {
                        editControl.Items.Add( new ListItem( definedValue.Name, definedValue.Id.ToString() ) );
                    }
                }
            }
            
            return editControl;
        }
Пример #15
0
        /// <summary>
        /// Binds the defined values grid.
        /// </summary>
        protected void BindDefinedValuesGrid()
        {
            AttributeService attributeService = new AttributeService();

            int definedTypeId = hfDefinedTypeId.ValueAsInt();
            
            // add attributes with IsGridColumn to grid
            string qualifierValue = hfDefinedTypeId.Value;
            var qryDefinedTypeAttributes = attributeService.GetByEntityTypeId( new DefinedValue().TypeId ).AsQueryable()
                .Where( a => a.EntityTypeQualifierColumn.Equals( "DefinedTypeId", StringComparison.OrdinalIgnoreCase )
                && a.EntityTypeQualifierValue.Equals( qualifierValue ) );

            qryDefinedTypeAttributes = qryDefinedTypeAttributes.Where( a => a.IsGridColumn );

            List<Attribute> gridItems = qryDefinedTypeAttributes.ToList();

            foreach ( var item in gDefinedValues.Columns.OfType<AttributeField>().ToList() )
            {
                gDefinedValues.Columns.Remove( item );
            }

            foreach ( var item in gridItems.OrderBy( a => a.Order ).ThenBy( a => a.Name ) )
            {
                string dataFieldExpression = item.Key;
                bool columnExists = gDefinedValues.Columns.OfType<AttributeField>().FirstOrDefault( a => a.DataField.Equals( dataFieldExpression ) ) != null;
                if ( !columnExists )
                {
                    AttributeField boundField = new AttributeField();
                    boundField.DataField = dataFieldExpression;
                    boundField.HeaderText = item.Name;
                    boundField.SortExpression = string.Empty;
                    int insertPos = gDefinedValues.Columns.IndexOf( gDefinedValues.Columns.OfType<DeleteField>().First());
                    gDefinedValues.Columns.Insert(insertPos, boundField );
                }
            }

            var queryable = new DefinedValueService().Queryable().Where( a => a.DefinedTypeId == definedTypeId ).OrderBy( a => a.Order );
            var result = queryable.ToList();

            gDefinedValues.DataSource = result;
            gDefinedValues.DataBind();
        }
Пример #16
0
        /// <summary>
        /// Handles the SaveClick event of the dlgLocations control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void dlgLocations_SaveClick( object sender, EventArgs e )
        {
            Location location = null;
            int? memberPersonId = null;
            RockContext rockContext = new RockContext();

            if ( LocationTypeTab.Equals( MEMBER_LOCATION_TAB_TITLE ) )
            {
                if ( ddlMember.SelectedValue != null )
                {
                    var ids = ddlMember.SelectedValue.Split( new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries );
                    if ( ids.Length == 2 )
                    {
                        var dbLocation = new LocationService( rockContext ).Get( int.Parse( ids[0] ) );
                        if ( dbLocation != null )
                        {
                            location = new Location();
                            location.CopyPropertiesFrom( dbLocation );
                        }

                        memberPersonId = int.Parse( ids[1] );
                    }
                }
            }
            else
            {
                if ( locpGroupLocation.Location != null )
                {
                    location = new Location();
                    location.CopyPropertiesFrom( locpGroupLocation.Location );
                }
            }

            if ( location != null )
            {
                GroupLocation groupLocation = null;

                Guid guid = hfAddLocationGroupGuid.Value.AsGuid();
                if ( !guid.IsEmpty() )
                {
                    groupLocation = GroupLocationsState.FirstOrDefault( l => l.Guid.Equals( guid ) );
                }

                if ( groupLocation == null )
                {
                    groupLocation = new GroupLocation();
                    GroupLocationsState.Add( groupLocation );
                }

                groupLocation.GroupMemberPersonId = memberPersonId;
                groupLocation.Location = location;
                groupLocation.LocationId = groupLocation.Location.Id;
                groupLocation.GroupLocationTypeValueId = ddlLocationType.SelectedValueAsId();

                if ( groupLocation.GroupLocationTypeValueId.HasValue )
                {
                    groupLocation.GroupLocationTypeValue = new DefinedValue();
                    var definedValue = new DefinedValueService( rockContext ).Get( groupLocation.GroupLocationTypeValueId.Value );
                    if ( definedValue != null )
                    {
                        groupLocation.GroupLocationTypeValue.CopyPropertiesFrom( definedValue );
                    }
                }
            }

            BindLocationsGrid();

            HideDialog();
        }
Пример #17
0
        /// <summary>
        /// Gets the <see cref="Rock.Model.Person"/> entity of the provided Person's spouse.
        /// </summary>
        /// <param name="person">The <see cref="Rock.Model.Person"/> entity of the Person to retrieve the spouse of.</param>
        /// <returns>The <see cref="Rock.Model.Person"/> entity containing the provided Person's spouse. If the provided Person's spouse is not found, this value will be null.</returns>
        public Person GetSpouse( Person person )
        {
            // Spouse is determined if all these conditions are met
            // 1) Adult in the same family as Person (GroupType = Family, GroupRole = Adult, and in same Group)
            // 2) Opposite Gender as Person
            // 3) Both Persons are Married
            
            Guid adultGuid = new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT );
            Guid marriedGuid = new Guid(Rock.SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_MARRIED);
            int marriedDefinedValueId = new DefinedValueService().Queryable().First(a => a.Guid == marriedGuid).Id;

            if ( person.MaritalStatusValueId != marriedDefinedValueId )
            {
                return null;
            }

            return GetFamilyMembers(person)
                .Where( m => m.GroupRole.Guid == adultGuid)
                .Where( m => m.Person.Gender != person.Gender )
                .Where( m => m.Person.MaritalStatusValueId == marriedDefinedValueId)
                .Select( m => m.Person )
                .FirstOrDefault();
        }
        /// <summary>
        /// Adds a new defined value to a given DefinedType.
        /// </summary>
        /// <param name="topic">the string value of the new defined value</param>
        /// <param name="definedTypeCache">a defined type cache to which the defined value will be added.</param>
        /// <param name="rockContext"></param>
        /// <returns></returns>
        private DefinedValueCache AddDefinedTypeValue( string topic, DefinedTypeCache definedTypeCache, RockContext rockContext )
        {
            DefinedValueService definedValueService = new DefinedValueService( rockContext );

            DefinedValue definedValue = new DefinedValue {
                Id = 0,
                IsSystem = false,
                Value = topic,
                Description = "",
                CreatedDateTime = RockDateTime.Now,
                DefinedTypeId = definedTypeCache.Id
            };
            definedValueService.Add( definedValue );
            rockContext.SaveChanges();

            Rock.Web.Cache.DefinedValueCache.Flush( definedValue.Id );
            Rock.Web.Cache.DefinedTypeCache.Flush( definedTypeCache.Id );

            return DefinedValueCache.Read( definedValue.Id, rockContext );
        }
        /// <summary>
        /// Handles the GridReorder event of the gDefinedValues control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="GridReorderEventArgs"/> instance containing the event data.</param>
        protected void gDefinedValues_GridReorder( object sender, GridReorderEventArgs e )
        {
            var definedType = DefinedTypeCache.Read( Rock.SystemGuid.DefinedType.PROTECT_MY_MINISTRY_PACKAGES.AsGuid() );
            if ( definedType != null )
            {
                var changedIds = new List<int>();

                using ( var rockContext = new RockContext() )
                {
                    var definedValueService = new DefinedValueService( rockContext );
                    var definedValues = definedValueService.Queryable().Where( a => a.DefinedTypeId == definedType.Id ).OrderBy( a => a.Order ).ThenBy( a => a.Value );
                    changedIds = definedValueService.Reorder( definedValues.ToList(), e.OldIndex, e.NewIndex );
                    rockContext.SaveChanges();
                }

                DefinedTypeCache.Flush( definedType.Id );
                foreach ( int id in changedIds )
                {
                    Rock.Web.Cache.DefinedValueCache.Flush( id );
                }
            }

            BindPackageGrid();
        }
        /// <summary>
        /// Handles the Delete event of the gDefinedValues control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param>
        protected void gDefinedValues_Delete( object sender, RowEventArgs e )
        {
            using ( var rockContext = new RockContext() )
            {
                var definedValueService = new DefinedValueService( rockContext );
                var value = definedValueService.Get( e.RowKeyId );
                if ( value != null )
                {
                    string errorMessage;
                    if ( !definedValueService.CanDelete( value, out errorMessage ) )
                    {
                        mdGridWarningValues.Show( errorMessage, ModalAlertType.Information );
                        return;
                    }

                    definedValueService.Delete( value );
                    rockContext.SaveChanges();

                    DefinedTypeCache.Flush( value.DefinedTypeId );
                    DefinedValueCache.Flush( value.Id );
                }

                BindPackageGrid();
            }
        }
Пример #21
0
        /// <summary>
        /// Handles the Click event of the btnSaveDefinedValue control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSaveValue_Click( object sender, EventArgs e )
        {
            DefinedValue definedValue;
            DefinedValueService definedValueService = new DefinedValueService();

            int definedValueId = hfDefinedValueId.ValueAsInt();

            if ( definedValueId.Equals( 0 ) )
            {
                int definedTypeId = hfDefinedTypeId.ValueAsInt();
                definedValue = new DefinedValue { Id = 0 };
                definedValue.DefinedTypeId = definedTypeId;
                definedValue.IsSystem = false;

                var orders = definedValueService.Queryable()
                    .Where( d => d.DefinedTypeId == definedTypeId )
                    .Select( d => d.Order)
                    .ToList();
                
                definedValue.Order = orders.Any() ? orders.Max() + 1 : 0;
            }
            else
            {
                definedValue = definedValueService.Get( definedValueId );
            }

            definedValue.Name = tbValueName.Text;
            definedValue.Description = tbValueDescription.Text;
            definedValue.LoadAttributes();
            Rock.Attribute.Helper.GetEditValues( phDefinedValueAttributes, definedValue );

            if ( !Page.IsValid )
            {
                return;
            }

            if ( !definedValue.IsValid )
            {
                // Controls will render the error messages                    
                return;
            }

            RockTransactionScope.WrapTransaction( () =>
            {
                if ( definedValue.Id.Equals( 0 ) )
                {
                    definedValueService.Add( definedValue, CurrentPersonId );
                }

                definedValueService.Save( definedValue, CurrentPersonId );
                Rock.Attribute.Helper.SaveAttributeValues( definedValue, CurrentPersonId );

                Rock.Web.Cache.DefinedTypeCache.Flush( definedValue.DefinedTypeId );
                Rock.Web.Cache.DefinedValueCache.Flush( definedValue.Id );
            } );
                        
            BindDefinedValuesGrid();

            hfDefinedValueId.Value = string.Empty;
            modalValue.Hide();
        }
Пример #22
0
        /// <summary>
        /// Handles the GridReorder event of the gDefinedValues control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="GridReorderEventArgs"/> instance containing the event data.</param>
        private void gDefinedValues_GridReorder( object sender, GridReorderEventArgs e )
        {
            int definedTypeId = hfDefinedTypeId.ValueAsInt();
            DefinedTypeCache.Flush( definedTypeId );

            using ( new UnitOfWorkScope() )
            {
                var definedValueService = new DefinedValueService();               
                var definedValues = definedValueService.Queryable().Where( a => a.DefinedTypeId == definedTypeId ).OrderBy( a => a.Order );
                definedValueService.Reorder( definedValues.ToList(), e.OldIndex, e.NewIndex, CurrentPersonId );
                BindDefinedValuesGrid();
            }
        }
Пример #23
0
        /// <summary>
        /// Adds a new defined value to a given DefinedType.
        /// </summary>
        /// <param name="stringValue">the string value of the new defined value</param>
        /// <param name="definedType">a defined type to which the defined value will be added.</param>
        /// <param name="rockContext"></param>
        /// <returns></returns>
        private DefinedValue AddDefinedTypeValue( string stringValue, DefinedType definedType, RockContext rockContext )
        {
            DefinedValueService definedValueService = new DefinedValueService( rockContext );
            DefinedTypeService definedTypeService = new DefinedTypeService( rockContext );

            DefinedValue definedValue = new DefinedValue {
                Id = 0,
                IsSystem = false,
                Value = stringValue,
                Description = string.Empty,
                CreatedDateTime = RockDateTime.Now,
                DefinedTypeId = definedType.Id
            };

            definedValueService.Add( definedValue );
            rockContext.ChangeTracker.DetectChanges();
            rockContext.SaveChanges( disablePrePostProcessing: true );

            return definedValue;
        }
Пример #24
0
        private void ShowAttributeValueEdit(int valueId, bool setValues)
        {
            var definedType = DefinedTypeCache.Read( hfDefinedTypeId.ValueAsInt() );
            DefinedValue definedValue;
            if ( !valueId.Equals( 0 ) )
            {
                definedValue = new DefinedValueService().Get( valueId );
                if ( definedType != null )
                {
                    lActionTitleDefinedValue.Text = ActionTitle.Edit( "defined value for " + definedType.Name );
                }
            }
            else
            {
                definedValue = new DefinedValue { Id = 0 };
                definedValue.DefinedTypeId = hfDefinedTypeId.ValueAsInt();
                if ( definedType != null )
                {
                    lActionTitleDefinedValue.Text = ActionTitle.Add( "defined value for " + definedType.Name );
                }
            }

            if ( setValues )
            {
                hfDefinedValueId.SetValue( definedValue.Id );
                tbValueName.Text = definedValue.Name;
                tbValueDescription.Text = definedValue.Description;
            }

            definedValue.LoadAttributes();
            phDefinedValueAttributes.Controls.Clear();
            Rock.Attribute.Helper.AddEditControls( definedValue, phDefinedValueAttributes, setValues );

            SetValidationGroup( phDefinedValueAttributes.Controls, modalValue.ValidationGroup );

            modalValue.Show();
        }
Пример #25
0
        /// <summary>
        /// Gs the marketing campaign audiences add.
        /// </summary>
        /// <param name="primaryAudience">if set to <c>true</c> [is primary].</param>
        private void gMarketingCampaignAudiencesAdd( bool primaryAudience )
        {
            DefinedValueService definedValueService = new DefinedValueService( new RockContext() );

            // populate dropdown with all MarketingCampaignAudiences that aren't already MarketingCampaignAudiences
            var guid = Rock.SystemGuid.DefinedType.MARKETING_CAMPAIGN_AUDIENCE_TYPE.AsGuid();
            var existingAudiences = MarketingCampaignAudiencesState.Select( s => s.AudienceTypeValueId ).ToList();
            var qry = definedValueService.GetByDefinedTypeGuid( guid )
                .Where( v => !existingAudiences.Contains( v.Id ) );

            List<DefinedValue> list = qry.ToList();
            if ( list.Count == 0 )
            {
                list.Add( new DefinedValue { Id = None.Id, Value = None.Text } );
                btnAddMarketingCampaignAudience.Enabled = false;
                btnAddMarketingCampaignAudience.CssClass = "btn btn-primary disabled";
            }
            else
            {
                btnAddMarketingCampaignAudience.Enabled = true;
                btnAddMarketingCampaignAudience.CssClass = "btn btn-primary";
            }

            ddlMarketingCampaignAudiences.DataSource = list;
            ddlMarketingCampaignAudiences.DataBind();
            hfMarketingCampaignAudienceIsPrimary.Value = primaryAudience.ToTrueFalse();
            pnlMarketingCampaignAudiencePicker.Visible = true;
            pnlDetails.Visible = false;
        }
        /// <summary>
        /// Handles the Add event of the gLocationTypes control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void gLocationTypes_Add( object sender, EventArgs e )
        {
            DefinedValueService definedValueService = new DefinedValueService( new RockContext() );

            // populate dropdown with all locationtypes that aren't already locationtypes
            var qry = from dlt in definedValueService.GetByDefinedTypeGuid( new Guid( Rock.SystemGuid.DefinedType.GROUP_LOCATION_TYPE ) )
                      where !( from lt in LocationTypesDictionary.Keys
                               select lt ).Contains( dlt.Id )
                      select dlt;

            List<DefinedValue> list = qry.ToList();
            if ( list.Count == 0 )
            {
                modalAlert.Show( "There are not any location types defined.  Before you can add location types to a group type, you will first need to add them using Defined Type/Values", ModalAlertType.Warning );
            }
            else
            {
                ddlLocationType.DataSource = list;
                ddlLocationType.DataBind();
                ShowDialog( "LocationType" );
            }
        }
Пример #27
0
        /// <summary>
        /// Executes this instance.
        /// </summary>
        public void Execute()
        {
            using ( var rockContext = new RockContext() )
            {
                var communication = new CommunicationService( rockContext ).Get( CommunicationId );

                if ( communication != null && communication.Status == CommunicationStatus.PendingApproval )
                {
                    // get notification group
                    var approvers = new GroupService( rockContext ).Get(SystemGuid.Group.GROUP_COMMUNICATION_APPROVERS.AsGuid());

                    if ( approvers != null )
                    {
                        var mergeFields = new Dictionary<string, object>();

                        var globalAttributeFields = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields( null );
                        globalAttributeFields.ToList().ForEach( d => mergeFields.Add( d.Key, d.Value ) );

                        string fromName = Rock.Web.Cache.GlobalAttributesCache.Value("OrganizationName");
                        string fromEmail = Rock.Web.Cache.GlobalAttributesCache.Value( "OrganizationEmail" );
                        string subject = "Pending Communication Requires Approval";
                        var appRoot = Rock.Web.Cache.GlobalAttributesCache.Read( rockContext ).GetValue( "ExternalApplicationRoot" );
                        string communicationDetails = string.Empty;
                        string typeName = string.Empty;

                        // get custom details by type
                        switch ( communication.Medium.TypeName )
                        {
                            case "Rock.Communication.Medium.Email":
                                string emailFromName = communication.GetMediumDataValue( "FromName" );
                                string emailFromAddress = communication.GetMediumDataValue( "FromAddress" );
                                communicationDetails = string.Format( @"
                                        <strong>From Name:</strong> {0}<br/>
                                        <strong>From Address:</strong> {1}<br/>
                                        <strong>Subject:</strong> {2}<br/>"
                                            , emailFromName
                                            , emailFromAddress
                                            , communication.Subject );
                                typeName = "Email";
                                break;
                            case "Rock.Communication.Medium.Sms":
                                int fromValueId = communication.GetMediumDataValue( "FromValue" ).AsInteger();
                                var fromValue = new DefinedValueService( rockContext ).Get( fromValueId );
                                typeName = "SMS";

                                if ( fromValue != null )
                                {
                                    communicationDetails = string.Format( "<strong>SMS Number:</strong> {0} ({1})<br/>", fromValue.Description, fromValue.Value );
                                }
                                break;
                        }

                        // create approval link if one was not provided
                        if ( ApprovalPageUrl == null )
                        {
                            ApprovalPageUrl = string.Format( "{0}Communication/{1}", Rock.Web.Cache.GlobalAttributesCache.Read( rockContext ).GetValue( "InternalApplicationRoot" ), communication.Id );
                        }

                        foreach ( var approver in approvers.Members )
                        {
                            string message = string.Format( @"
                                    {{{{ 'Global' | Attribute:'EmailHeader' }}}}

                                    <p>{0}:</p>

                                    <p>A new communication requires approval. Information about this communication can be found below.</p>

                                    <p>
                                        <strong>From:</strong> {1}<br />
                                        <strong>Type:</strong> {2}<br />
                                        {3}
                                        <strong>Recipient Count:</strong> {4}<br />
                                    </p>

                                    <p>
                                        <a href='{5}'>View Communication</a>
                                    </p>

                                    {{{{ 'Global' | Attribute:'EmailFooter' }}}}",
                                                    approver.Person.NickName,
                                                    communication.SenderPersonAlias.Person.FullName,
                                                    typeName,
                                                    communicationDetails,
                                                    communication.Recipients.Count(),
                                                    ApprovalPageUrl);

                            var recipients = new List<string>();
                            recipients.Add( approver.Person.Email );

                            Email.Send( fromEmail, fromName, subject, recipients, message.ResolveMergeFields( mergeFields ), appRoot, string.Empty, null, false );
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            GroupType groupType;
            var rockContext = new RockContext();
            GroupTypeService groupTypeService = new GroupTypeService( rockContext );
            GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService( rockContext );
            AttributeService attributeService = new AttributeService( rockContext );
            AttributeQualifierService qualifierService = new AttributeQualifierService( rockContext );
            CategoryService categoryService = new CategoryService( rockContext );
            GroupScheduleExclusionService scheduleExclusionService = new GroupScheduleExclusionService( rockContext );

            int groupTypeId = int.Parse( hfGroupTypeId.Value );

            if ( groupTypeId == 0 )
            {
                groupType = new GroupType();
                groupTypeService.Add( groupType );
            }
            else
            {
                groupType = groupTypeService.Get( groupTypeId );

                // selected roles
                var selectedRoleGuids = GroupTypeRolesState.Select( r => r.Guid );
                foreach ( var role in groupType.Roles.Where( r => !selectedRoleGuids.Contains( r.Guid ) ).ToList() )
                {
                    groupType.Roles.Remove( role );
                    groupTypeRoleService.Delete( role );
                }
            }

            foreach ( var roleState in GroupTypeRolesState )
            {
                GroupTypeRole role = groupType.Roles.Where( r => r.Guid == roleState.Guid ).FirstOrDefault();
                if ( role == null )
                {
                    role = new GroupTypeRole();
                    groupType.Roles.Add( role );
                }
                else
                {
                    roleState.Id = role.Id;
                    roleState.Guid = role.Guid;
                }

                role.CopyPropertiesFrom( roleState );
            }

            ScheduleType allowedScheduleTypes = ScheduleType.None;
            foreach( ListItem li in cblScheduleTypes.Items )
            {
                if ( li.Selected )
                {
                    allowedScheduleTypes = allowedScheduleTypes | (ScheduleType)li.Value.AsInteger();
                }
            }

            GroupLocationPickerMode locationSelectionMode = GroupLocationPickerMode.None;
            foreach ( ListItem li in cblLocationSelectionModes.Items )
            {
                if ( li.Selected )
                {
                    locationSelectionMode = locationSelectionMode | (GroupLocationPickerMode)li.Value.AsInteger();
                }
            }

            groupType.Name = tbName.Text;
            groupType.Description = tbDescription.Text;
            groupType.GroupTerm = tbGroupTerm.Text;
            groupType.GroupMemberTerm = tbGroupMemberTerm.Text;
            groupType.ShowInGroupList = cbShowInGroupList.Checked;
            groupType.ShowInNavigation = cbShowInNavigation.Checked;
            groupType.IconCssClass = tbIconCssClass.Text;
            groupType.TakesAttendance = cbTakesAttendance.Checked;
            groupType.SendAttendanceReminder = cbSendAttendanceReminder.Checked;
            groupType.AttendanceRule = ddlAttendanceRule.SelectedValueAsEnum<AttendanceRule>();
            groupType.AttendancePrintTo = ddlPrintTo.SelectedValueAsEnum<PrintTo>();
            groupType.AllowedScheduleTypes = allowedScheduleTypes;
            groupType.LocationSelectionMode = locationSelectionMode;
            groupType.GroupTypePurposeValueId = ddlGroupTypePurpose.SelectedValueAsInt();
            groupType.AllowMultipleLocations = cbAllowMultipleLocations.Checked;
            groupType.InheritedGroupTypeId = gtpInheritedGroupType.SelectedGroupTypeId;
            groupType.EnableLocationSchedules = cbEnableLocationSchedules.Checked;

            groupType.ChildGroupTypes = new List<GroupType>();
            groupType.ChildGroupTypes.Clear();
            foreach ( var item in ChildGroupTypesDictionary )
            {
                var childGroupType = groupTypeService.Get( item.Key );
                if ( childGroupType != null )
                {
                    groupType.ChildGroupTypes.Add( childGroupType );
                }
            }

            // Delete any removed exclusions
            foreach ( var exclusion in groupType.GroupScheduleExclusions.Where( s => !ScheduleExclusionDictionary.Keys.Contains( s.Guid ) ).ToList() )
            {
                groupType.GroupScheduleExclusions.Remove( exclusion );
                scheduleExclusionService.Delete( exclusion );
            }

            // Update exclusions
            foreach( var keyVal in ScheduleExclusionDictionary )
            {
                var scheduleExclusion = groupType.GroupScheduleExclusions
                    .FirstOrDefault( s => s.Guid.Equals( keyVal.Key));
                if ( scheduleExclusion == null )
                {
                    scheduleExclusion = new GroupScheduleExclusion();
                    groupType.GroupScheduleExclusions.Add( scheduleExclusion);
                }

                scheduleExclusion.StartDate = keyVal.Value.Start;
                scheduleExclusion.EndDate = keyVal.Value.End;
            }

            DefinedValueService definedValueService = new DefinedValueService( rockContext );

            groupType.LocationTypes = new List<GroupTypeLocationType>();
            groupType.LocationTypes.Clear();
            foreach ( var item in LocationTypesDictionary )
            {
                var locationType = definedValueService.Get( item.Key );
                if ( locationType != null )
                {
                    groupType.LocationTypes.Add( new GroupTypeLocationType { LocationTypeValueId = locationType.Id } );
                }
            }

            if ( !groupType.IsValid )
            {
                // Controls will render the error messages
                return;
            }

            // need WrapTransaction due to Attribute saves
            rockContext.WrapTransaction( () =>
            {
                rockContext.SaveChanges();

                /* Save Attributes */
                string qualifierValue = groupType.Id.ToString();
                SaveAttributes( new GroupType().TypeId, "Id", qualifierValue, GroupTypeAttributesState, rockContext );
                SaveAttributes( new Group().TypeId, "GroupTypeId", qualifierValue, GroupAttributesState, rockContext );
                SaveAttributes( new GroupMember().TypeId, "GroupTypeId", qualifierValue, GroupMemberAttributesState, rockContext );

                // Reload to save default role
                groupType = groupTypeService.Get( groupType.Id );
                groupType.DefaultGroupRole = groupType.Roles.FirstOrDefault( r => r.Guid.Equals( DefaultRoleGuid ) );
                if ( groupType.DefaultGroupRole == null )
                {
                    groupType.DefaultGroupRole = groupType.Roles.FirstOrDefault();
                }

                rockContext.SaveChanges();

                // Reload the roles and apply their attribute values
                foreach ( var role in groupTypeRoleService.GetByGroupTypeId( groupType.Id ).ToList() )
                {
                    role.LoadAttributes( rockContext );
                    var roleState = GroupTypeRolesState.Where( r => r.Guid.Equals( role.Guid ) ).FirstOrDefault();
                    if ( roleState != null && roleState.AttributeValues != null )
                    {
                        foreach ( var attributeValue in roleState.AttributeValues )
                        {
                            role.SetAttributeValue( attributeValue.Key, roleState.GetAttributeValue( attributeValue.Key ) );
                        }

                        role.SaveAttributeValues( rockContext );
                    }
                }
            } );

            GroupTypeCache.Flush( groupType.Id );

            NavigateToParentPage();
        }
Пример #29
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            var rockContext = new RockContext();
            var financialPledgeService = new FinancialPledgeService( rockContext );
            var financialAccountService = new FinancialAccountService( rockContext );
            var definedValueService = new DefinedValueService( rockContext );
            var person = FindPerson( rockContext );

            FinancialPledge financialPledge = new FinancialPledge();

            financialPledge.PersonAliasId = person.PrimaryAliasId;
            var financialAccount = financialAccountService.Get( GetAttributeValue( "Account" ).AsGuid() );
            if ( financialAccount != null )
            {
                financialPledge.AccountId = financialAccount.Id;
            }

            financialPledge.TotalAmount = tbTotalAmount.Text.AsDecimal();

            var pledgeFrequencySelection = DefinedValueCache.Read( bddlFrequency.SelectedValue.AsInteger() );
            if ( pledgeFrequencySelection != null )
            {
                financialPledge.PledgeFrequencyValueId = pledgeFrequencySelection.Id;
            }

            financialPledge.StartDate = drpDateRange.LowerValue ?? DateTime.MinValue;
            financialPledge.EndDate = drpDateRange.UpperValue ?? DateTime.MaxValue;

            if ( sender != btnConfirm )
            {
                var duplicatePledges = financialPledgeService.Queryable()
                    .Where( a => a.PersonAlias.PersonId == person.Id )
                    .Where( a => a.AccountId == financialPledge.AccountId )
                    .Where( a => a.StartDate == financialPledge.StartDate )
                    .Where( a => a.EndDate == financialPledge.EndDate ).ToList();

                if ( duplicatePledges.Any() )
                {
                    pnlAddPledge.Visible = false;
                    pnlConfirm.Visible = true;
                    nbDuplicatePledgeWarning.Text = "The following pledges have already been entered for you:";
                    nbDuplicatePledgeWarning.Text += "<ul>";
                    foreach ( var pledge in duplicatePledges.OrderBy( a => a.StartDate ).ThenBy( a => a.Account.Name ) )
                    {
                        nbDuplicatePledgeWarning.Text += string.Format( "<li>{0} {1} {2}</li>", pledge.Account, pledge.PledgeFrequencyValue, pledge.TotalAmount );
                    }

                    nbDuplicatePledgeWarning.Text += "</ul>";

                    return;
                }
            }

            financialPledgeService.Add( financialPledge );

            rockContext.SaveChanges();

            // populate account so that Liquid can access it
            financialPledge.Account = financialAccount;

            // populate PledgeFrequencyValue so that Liquid can access it
            financialPledge.PledgeFrequencyValue = definedValueService.Get( financialPledge.PledgeFrequencyValueId ?? 0 );

            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( this.RockPage, this.CurrentPerson );
            mergeFields.Add( "Person", person );
            mergeFields.Add( "FinancialPledge", financialPledge );
            mergeFields.Add( "PledgeFrequency", pledgeFrequencySelection );
            mergeFields.Add( "Account", financialAccount );
            lReceipt.Text = GetAttributeValue( "ReceiptText" ).ResolveMergeFields( mergeFields );

            // Resolve any dynamic url references
            string appRoot = ResolveRockUrl( "~/" );
            string themeRoot = ResolveRockUrl( "~~/" );
            lReceipt.Text = lReceipt.Text.Replace( "~~/", themeRoot ).Replace( "~/", appRoot );

            // show liquid help for debug
            if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) )
            {
                lReceipt.Text += mergeFields.lavaDebugInfo();
            }

            lReceipt.Visible = true;
            pnlAddPledge.Visible = false;
            pnlConfirm.Visible = false;

            // if a ConfirmationEmailTemplate is configured, send an email
            var confirmationEmailTemplateGuid = GetAttributeValue( "ConfirmationEmailTemplate" ).AsGuidOrNull();
            if ( confirmationEmailTemplateGuid.HasValue )
            {
                var recipients = new List<Rock.Communication.RecipientData>();

                // add person and the mergeObjects (same mergeobjects as receipt)
                recipients.Add( new Rock.Communication.RecipientData( person.Email, mergeFields ) );

                Rock.Communication.Email.Send( confirmationEmailTemplateGuid.Value, recipients, ResolveRockUrl( "~/" ), ResolveRockUrl( "~~/" ) );
            }
        }
Пример #30
0
        /// <summary>
        /// Loads the cache objects.
        /// </summary>
        private void LoadCacheObjects()
        {
            using ( new Rock.Data.UnitOfWorkScope() )
            {
                // Cache all the Field Types
                var fieldTypeService = new Rock.Model.FieldTypeService();
                foreach ( var fieldType in fieldTypeService.Queryable().ToList() )
                    Rock.Web.Cache.FieldTypeCache.Read( fieldType );

                // Cache all tha Defined Types
                var definedTypeService = new Rock.Model.DefinedTypeService();
                foreach ( var definedType in definedTypeService.Queryable().ToList() )
                    Rock.Web.Cache.DefinedTypeCache.Read( definedType );

                // Cache all the Defined Values
                var definedValueService = new Rock.Model.DefinedValueService();
                foreach ( var definedValue in definedValueService.Queryable().ToList() )
                    Rock.Web.Cache.DefinedValueCache.Read( definedValue );

                // Read all the qualifiers first so that EF doesn't perform a query for each attribute when it's cached
                var qualifiers = new Dictionary<int, Dictionary<string, string>>();
                foreach ( var attributeQualifier in new Rock.Model.AttributeQualifierService().Queryable() )
                {
                    if ( !qualifiers.ContainsKey( attributeQualifier.AttributeId ) )
                        qualifiers.Add( attributeQualifier.AttributeId, new Dictionary<string, string>() );
                    qualifiers[attributeQualifier.AttributeId].Add( attributeQualifier.Key, attributeQualifier.Value );
                }

                // Cache all the attributes.
                foreach ( var attribute in new Rock.Model.AttributeService().Queryable().ToList() )
                {
                    if ( qualifiers.ContainsKey( attribute.Id ) )
                        Rock.Web.Cache.AttributeCache.Read( attribute, qualifiers[attribute.Id] );
                    else
                        Rock.Web.Cache.AttributeCache.Read( attribute, new Dictionary<string, string>() );
                }
            }
        }
        /// <summary>
        /// Shows the view.
        /// </summary>
        /// <param name="settings">The settings.</param>
        public void ShowView( List<AttributeValue> settings )
        {
            ShowHighlightLabels( settings );

            lUserName.Text = GetSettingValue( settings, "UserName" );
            lPassword.Text = "********";

            using ( var rockContext = new RockContext() )
            {
                var packages = new DefinedValueService( rockContext )
                    .GetByDefinedTypeGuid( Rock.SystemGuid.DefinedType.PROTECT_MY_MINISTRY_PACKAGES.AsGuid() )
                    .Select( v => v.Value )
                    .ToList();
                lPackages.Text = packages.AsDelimited( "<br/>" );
            }

            pnlNew.Visible = false;
            pnlViewDetails.Visible = true;
            pnlEditDetails.Visible = false;
            pnlPackages.Visible = false;

            HideSecondaryBlocks( false );
        }
Пример #32
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var shapePageReference = new Rock.Web.PageReference(GetAttributeValue("SHAPEAssessmentPage"));
            var discPageReference = new Rock.Web.PageReference(GetAttributeValue("DISCAssessmentPage"));

            if (!string.IsNullOrWhiteSpace(PageParameter("FormId")))
                {
                    //Load the person based on the FormId
                    var personInUrl = PageParameter("FormId");
                    SelectedPerson = GetPersonFromForm(personInUrl);
                    PersonEncodedKey = SelectedPerson.UrlEncodedKey;
                }

                else if (!string.IsNullOrWhiteSpace(PageParameter("PersonId")))
                {
                    //Load the person based on the PersonId
                    SelectedPerson = GetPersonFromId(PageParameter("PersonId"));
                    PersonEncodedKey = SelectedPerson.UrlEncodedKey;
                 }

                else if (CurrentPerson != null)
                {
                    //Load the person based on the currently logged in person
                    SelectedPerson = CurrentPerson;
                    PersonEncodedKey = SelectedPerson.UrlEncodedKey;
                }

                else
                {
                    //Show Error Message
                    nbNoPerson.Visible = true;
                    Response.Redirect(shapePageReference.BuildUrl(), true);
                    return;
                }

            // Load the attributes

            AttributeValueService attributeValueService = new AttributeValueService(rockContext);
            DefinedValueService definedValueService = new DefinedValueService(rockContext);

            string spiritualGift1 = "";
            string spiritualGift2 = "";
            string spiritualGift3 = "";
            string spiritualGift4 = "";
            string heartCategories = "";
            string heartCauses = "";
            string heartPassion = "";
            string ability1 = "";
            string ability2 = "";
            string people = "";
            string places = "";
            string events = "";

            var spiritualGift1AttributeValue =
                attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift1" && a.EntityId == SelectedPerson.Id);

            // Redirect if they haven't taken the Assessment
            if (spiritualGift1AttributeValue == null)
            {
                Response.Redirect(shapePageReference.BuildUrl(), true);
            }

            else
            {
                var spiritualGift2AttributeValue =
              attributeValueService
                  .Queryable()
                  .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift2" && a.EntityId == SelectedPerson.Id);

                var spiritualGift3AttributeValue =
              attributeValueService
                  .Queryable()
                  .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift3" && a.EntityId == SelectedPerson.Id);

                var spiritualGift4AttributeValue =
              attributeValueService
                  .Queryable()
                  .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift4" && a.EntityId == SelectedPerson.Id);

                var ability1AttributeValue =
                    attributeValueService
                        .Queryable().FirstOrDefault(a => a.Attribute.Key == "Ability1" && a.EntityId == SelectedPerson.Id);

                var ability2AttributeValue =
                    attributeValueService
                        .Queryable().FirstOrDefault(a => a.Attribute.Key == "Ability2" && a.EntityId == SelectedPerson.Id);

                var peopleAttributeValue = attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "SHAPEPeople" && a.EntityId == SelectedPerson.Id);

                var placesAttributeValue = attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "SHAPEPlaces" && a.EntityId == SelectedPerson.Id);

                var eventsAttributeValue = attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "SHAPEEvents" && a.EntityId == SelectedPerson.Id);

                var heartCategoriesAttributeValue = attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "HeartCategories" && a.EntityId == SelectedPerson.Id);

                var heartCausesAttributeValue = attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "HeartCauses" && a.EntityId == SelectedPerson.Id);

                var heartPassionAttributeValue = attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "HeartPassion" && a.EntityId == SelectedPerson.Id);

                if (spiritualGift1AttributeValue.Value != null) spiritualGift1 = spiritualGift1AttributeValue.Value;
                if (spiritualGift2AttributeValue.Value != null) spiritualGift2 = spiritualGift2AttributeValue.Value;
                if (spiritualGift3AttributeValue.Value != null) spiritualGift3 = spiritualGift3AttributeValue.Value;
                if (spiritualGift4AttributeValue.Value != null) spiritualGift4 = spiritualGift4AttributeValue.Value;
                if (heartCategoriesAttributeValue.Value != null) heartCategories = heartCategoriesAttributeValue.Value;
                if (heartCausesAttributeValue.Value != null) heartCauses = heartCausesAttributeValue.Value;
                if (heartPassionAttributeValue.Value != null) heartPassion = heartPassionAttributeValue.Value;
                if (ability1AttributeValue.Value != null) ability1 = ability1AttributeValue.Value;
                if (ability2AttributeValue.Value != null) ability2 = ability2AttributeValue.Value;
                if (peopleAttributeValue.Value != null) people = peopleAttributeValue.Value;
                if (placesAttributeValue.Value != null) places = placesAttributeValue.Value;
                if (eventsAttributeValue.Value != null) events = eventsAttributeValue.Value;

                string spiritualGift1Guid;
                string spiritualGift2Guid;
                string spiritualGift3Guid;
                string spiritualGift4Guid;
                string ability1Guid;
                string ability2Guid;

                // Check to see if there are already values saved as an ID.  If so, convert them to GUID
                if (spiritualGift1.ToString().Length < 5)
                {
                    if (spiritualGift1 != null) SpiritualGift1 = Int32.Parse(spiritualGift1);
                    if (spiritualGift2 != null) SpiritualGift2 = Int32.Parse(spiritualGift2);
                    if (spiritualGift3 != null) SpiritualGift3 = Int32.Parse(spiritualGift3);
                    if (spiritualGift4 != null) SpiritualGift4 = Int32.Parse(spiritualGift4);
                    if (ability1 != null) Ability1 = Int32.Parse(ability1);
                    if (ability2 != null) Ability2 = Int32.Parse(ability2);

                    var intsOfGifts =
                        definedValueService.GetByIds(new List<int>
                        {
                            SpiritualGift1,
                            SpiritualGift2,
                            SpiritualGift3,
                            SpiritualGift4,
                            Ability1,
                            Ability2
                        });

                    spiritualGift1Guid = intsOfGifts.ToList()[SpiritualGift1].Guid.ToString();
                    spiritualGift2Guid = intsOfGifts.ToList()[SpiritualGift2].Guid.ToString();
                    spiritualGift3Guid = intsOfGifts.ToList()[SpiritualGift3].Guid.ToString();
                    spiritualGift4Guid = intsOfGifts.ToList()[SpiritualGift4].Guid.ToString();
                    ability1Guid = intsOfGifts.ToList()[Ability1].Guid.ToString();
                    ability2Guid = intsOfGifts.ToList()[Ability2].Guid.ToString();
                }
                else
                {
                    spiritualGift1Guid = spiritualGift1;
                    spiritualGift2Guid = spiritualGift2;
                    spiritualGift3Guid = spiritualGift3;
                    spiritualGift4Guid = spiritualGift4;
                    ability1Guid = ability1;
                    ability2Guid = ability2;
                }

                // Get all of the data about the assiciated gifts and ability categories
                var shapeGift1Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(spiritualGift1Guid) }).FirstOrDefault();
                var shapeGift2Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(spiritualGift2Guid) }).FirstOrDefault();
                var shapeGift3Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(spiritualGift3Guid) }).FirstOrDefault();
                var shapeGift4Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(spiritualGift4Guid) }).FirstOrDefault();
                var ability1Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(ability1Guid) }).FirstOrDefault();
                var ability2Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(ability2Guid) }).FirstOrDefault();

                shapeGift1Object.LoadAttributes();
                shapeGift2Object.LoadAttributes();
                shapeGift3Object.LoadAttributes();
                shapeGift4Object.LoadAttributes();
                ability1Object.LoadAttributes();
                ability2Object.LoadAttributes();

                // Get heart choices Values from Guids
                string heartCategoriesString = "";
                if (!heartCategories.IsNullOrWhiteSpace())
                {
                    string[] heartCategoryArray = heartCategories.Split(',');
                    foreach (string category in heartCategoryArray)
                    {
                        var definedValueObject =
                            definedValueService.Queryable().FirstOrDefault(a => a.Guid == new Guid(category));

                        if (category.Equals(heartCategoryArray.Last()))
                        {
                            heartCategoriesString += definedValueObject.Value;
                        }
                        else
                        {
                            heartCategoriesString += definedValueObject.Value + ", ";
                        }
                    }

                }

                // Get Volunteer Opportunities

                string gift1AssociatedVolunteerOpportunities =
                    shapeGift1Object.GetAttributeValue("AssociatedVolunteerOpportunities");
                string gift2AssociatedVolunteerOpportunities =
                    shapeGift2Object.GetAttributeValue("AssociatedVolunteerOpportunities");
                string gift3AssociatedVolunteerOpportunities =
                    shapeGift3Object.GetAttributeValue("AssociatedVolunteerOpportunities");
                string gift4AssociatedVolunteerOpportunities =
                    shapeGift4Object.GetAttributeValue("AssociatedVolunteerOpportunities");

                string allAssociatedVolunteerOpportunities = gift1AssociatedVolunteerOpportunities + "," +
                                                             gift2AssociatedVolunteerOpportunities + "," +
                                                             gift3AssociatedVolunteerOpportunities + "," +
                                                             gift4AssociatedVolunteerOpportunities;

                if (allAssociatedVolunteerOpportunities != ",,,")
                {
                    List<int> associatedVolunteerOpportunitiesList =
                        allAssociatedVolunteerOpportunities.Split(',').Select(t => int.Parse(t)).ToList();
                    Dictionary<int, int> VolunteerOpportunities = new Dictionary<int, int>();

                    var i = 0;
                    var q = from x in associatedVolunteerOpportunitiesList
                            group x by x
                        into g
                            let count = g.Count()
                            orderby count descending
                            select new { Value = g.Key, Count = count };
                    foreach (var x in q)
                    {
                        VolunteerOpportunities.Add(i, x.Value);
                        i++;
                    }

                    ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService(rockContext);
                    List<ConnectionOpportunity> connectionOpportunityList = new List<ConnectionOpportunity>();

                    foreach (KeyValuePair<int, int> entry in VolunteerOpportunities.Take(4))
                    {
                        var connection = connectionOpportunityService.GetByIds(new List<int> { entry.Value }).FirstOrDefault();

                        // Only display connection if it is marked Active
                        if (connection.IsActive == true)
                        {
                            connectionOpportunityList.Add(connection);
                        }

                    }

                    rpVolunteerOpportunities.DataSource = connectionOpportunityList;
                    rpVolunteerOpportunities.DataBind();
                }

                //Get DISC Info

                DiscService.AssessmentResults savedScores = DiscService.LoadSavedAssessmentResults(SelectedPerson);

                if (!string.IsNullOrWhiteSpace(savedScores.PersonalityType))
                {
                    ShowResults(savedScores);
                    DISCResults.Visible = true;
                    NoDISCResults.Visible = false;

                }
                else
                {
                    discPageReference.Parameters = new System.Collections.Generic.Dictionary<string, string>();
                    discPageReference.Parameters.Add("rckipid", SelectedPerson.UrlEncodedKey);
                    Response.Redirect(discPageReference.BuildUrl(), true);
                }

                // Build the UI

                lbPersonName.Text = SelectedPerson.FullName;

                lbGift1Title.Text = shapeGift1Object.Value;
                lbGift1BodyHTML.Text = shapeGift1Object.GetAttributeValue("HTMLDescription");

                lbGift2Title.Text = shapeGift2Object.Value;
                lbGift2BodyHTML.Text = shapeGift2Object.GetAttributeValue("HTMLDescription");

                lbGift3Title.Text = shapeGift3Object.Value;
                lbGift3BodyHTML.Text = shapeGift3Object.GetAttributeValue("HTMLDescription");

                lbGift4Title.Text = shapeGift4Object.Value;
                lbGift4BodyHTML.Text = shapeGift4Object.GetAttributeValue("HTMLDescription");

                lbAbility1Title.Text = ability1Object.Value;
                lbAbility1BodyHTML.Text = ability1Object.GetAttributeValue("HTMLDescription");

                lbAbility2Title.Text = ability2Object.Value;
                lbAbility2BodyHTML.Text = ability2Object.GetAttributeValue("HTMLDescription");

                lbPeople.Text = people;
                lbPlaces.Text = places;
                lbEvents.Text = events;

                lbHeartCategories.Text = heartCategoriesString;
                lbHeartCauses.Text = heartCauses;
                lbHeartPassion.Text = heartPassion;

                if (spiritualGift1AttributeValue.ModifiedDateTime != null)
                {
                    lbAssessmentDate.Text = spiritualGift1AttributeValue.ModifiedDateTime.Value.ToShortDateString();
                }
                else
                {
                    lbAssessmentDate.Text = spiritualGift1AttributeValue.CreatedDateTime.Value.ToShortDateString();
                }

                // Show create account panel if this person doesn't have an account
                if (SelectedPerson.Users.Count == 0)
                {
                    pnlAccount.Visible = true;
                }

            }
        }
Пример #33
0
        /// <summary>
        /// Builds an expression for a property field
        /// </summary>
        /// <param name="serviceInstance">The service instance.</param>
        /// <param name="parameterExpression">The parameter expression.</param>
        /// <param name="entityField">The property.</param>
        /// <param name="values">The values.</param>
        /// <returns></returns>
        private Expression GetPropertyExpression( IService serviceInstance, ParameterExpression parameterExpression, EntityField entityField, List<string> values )
        {
            Expression trueValue = Expression.Constant( true );
            MemberExpression propertyExpression = Expression.Property( parameterExpression, entityField.Name );

            switch ( entityField.FilterFieldType )
            {
                // Date Properties
                case SystemGuid.FieldType.DATE:

                    if ( values.Count == 2 )
                    {
                        ComparisonType comparisonType = values[0].ConvertToEnum<ComparisonType>( ComparisonType.EqualTo );
                        DateTime dateValue = values[1].AsDateTime() ?? DateTime.MinValue;
                        ConstantExpression constantExpression = Expression.Constant( dateValue );

                        if ( !( ComparisonType.IsBlank | ComparisonType.IsNotBlank ).HasFlag( comparisonType ) )
                        {
                            if ( entityField.PropertyType == typeof( DateTime? ) )
                            {
                                // special case for Nullable Type
                                MemberExpression hasValue = Expression.Property( propertyExpression, "HasValue" );
                                MemberExpression valueExpression = Expression.Property( propertyExpression, "Value" );
                                Expression comparisonExpression = ComparisonExpression( comparisonType, valueExpression, constantExpression );
                                return Expression.AndAlso( hasValue, comparisonExpression );
                            }
                        }

                        return ComparisonExpression( comparisonType, propertyExpression, constantExpression );
                    }

                    break;

                // Number properties
                case SystemGuid.FieldType.INTEGER:

                    if ( values.Count == 2 )
                    {
                        ComparisonType comparisonType = values[0].ConvertToEnum<ComparisonType>( ComparisonType.EqualTo );
                        int intValue = values[1].AsIntegerOrNull() ?? int.MinValue;
                        ConstantExpression constantExpression = Expression.Constant( intValue );

                        if ( !( ComparisonType.IsBlank | ComparisonType.IsNotBlank ).HasFlag( comparisonType ) )
                        {
                            if ( entityField.PropertyType == typeof( int? ) )
                            {
                                // special case for Nullable Type
                                MemberExpression hasValue = Expression.Property( propertyExpression, "HasValue" );
                                MemberExpression valueExpression = Expression.Property( propertyExpression, "Value" );
                                Expression comparisonExpression = ComparisonExpression( comparisonType, valueExpression, constantExpression );
                                return Expression.AndAlso( hasValue, comparisonExpression );
                            }
                        }

                        return ComparisonExpression( comparisonType, propertyExpression, constantExpression );
                    }

                    break;

                // Enumerations and Defined Value properties
                case SystemGuid.FieldType.MULTI_SELECT:

                    if ( values.Count == 1 )
                    {
                        List<string> selectedValues = JsonConvert.DeserializeObject<List<string>>( values[0] );
                        if ( selectedValues.Any() )
                        {
                            if ( entityField.PropertyType.IsEnum )
                            {
                                ConstantExpression constantExpression = Expression.Constant( Enum.Parse( entityField.PropertyType, selectedValues[0].Replace( " ", string.Empty ) ) );
                                Expression comparison = Expression.Equal( propertyExpression, constantExpression );

                                foreach ( string selectedValue in selectedValues.Skip( 1 ) )
                                {
                                    constantExpression = Expression.Constant( Enum.Parse( entityField.PropertyType, selectedValue.Replace( " ", string.Empty ) ) );
                                    comparison = Expression.Or( comparison, Expression.Equal( propertyExpression, constantExpression ) );
                                }

                                return comparison;
                            }
                            else if ( entityField.DefinedTypeGuid.HasValue )
                            {
                                List<Guid> selectedValueGuids = selectedValues.Select( v => v.AsGuid() ).ToList();
                                List<int> selectedIds = new DefinedValueService( serviceInstance.Context as RockContext ).GetByGuids( selectedValueGuids ).Select( a => a.Id ).ToList();
                                ConstantExpression constantExpression = Expression.Constant( selectedIds, typeof( List<int> ) );

                                if ( entityField.PropertyType == typeof( int? ) )
                                {
                                    // special case for Nullable Type
                                    MemberExpression hasValue = Expression.Property( propertyExpression, "HasValue" );
                                    MemberExpression valueExpression = Expression.Property( propertyExpression, "Value" );
                                    MethodCallExpression containsExpression = Expression.Call( constantExpression, "Contains", new Type[] { }, valueExpression );
                                    return Expression.AndAlso( hasValue, containsExpression );
                                }
                                else
                                {
                                    return Expression.Call( constantExpression, "Contains", new Type[] { }, propertyExpression );
                                }
                            }
                        }
                    }

                    break;

                // Boolean Properties
                case SystemGuid.FieldType.SINGLE_SELECT:

                    if ( values.Count == 1 )
                    {
                        if ( entityField.PropertyType == typeof( bool ) || entityField.PropertyType == typeof( bool? ) )
                        {
                            ConstantExpression constantExpression = Expression.Constant( bool.Parse( values[0] ) );
                            ComparisonType comparisonType = ComparisonType.EqualTo;

                            if ( entityField.PropertyType == typeof( bool? ) )
                            {
                                // special case for Nullable Type
                                MemberExpression hasValue = Expression.Property( propertyExpression, "HasValue" );
                                MemberExpression valueExpression = Expression.Property( propertyExpression, "Value" );
                                Expression compareExpression = ComparisonExpression( comparisonType, valueExpression, constantExpression );
                                return Expression.AndAlso( hasValue, compareExpression );
                            }
                            else
                            {
                                return ComparisonExpression( comparisonType, propertyExpression, constantExpression );
                            }
                        }
                    }

                    break;

                // String Properties
                case SystemGuid.FieldType.TEXT:

                    if ( values.Count == 2 )
                    {
                        ComparisonType comparisonType = values[0].ConvertToEnum<ComparisonType>( ComparisonType.EqualTo );
                        ConstantExpression constantExpression = Expression.Constant( values[1] );

                        return ComparisonExpression( comparisonType, propertyExpression, constantExpression );
                    }

                    break;
            }

            return null;
        }