Пример #1
0
        /// <summary>
        /// Gets the by alias unique identifier.
        /// </summary>
        /// <param name="aliasPersonGuid">The alias person unique identifier.</param>
        /// <returns></returns>
        public virtual PersonAlias GetByAliasGuid( Guid aliasPersonGuid )
        {
            var personAlias = Queryable( "Person" ).Where( a => a.AliasPersonGuid == aliasPersonGuid ).FirstOrDefault();
            if ( personAlias != null )
            {
                return personAlias;
            }
            else
            {
                // If the personId is valid, there should be a personAlias with the AliasPersonID equal
                // to that personId.  If there isn't for some reason, create it now.
                var person = new PersonService( (RockContext)this.Context ).Get( aliasPersonGuid );
                if ( person != null )
                {
                    personAlias = new PersonAlias();
                    personAlias.Guid = Guid.NewGuid();
                    personAlias.AliasPersonId = person.Id;
                    personAlias.AliasPersonGuid = person.Guid;
                    personAlias.PersonId = person.Id;

                    // Use a different context so calling method's changes are not yet saved
                    var rockContext = new RockContext();
                    new PersonAliasService( rockContext ).Add( personAlias );
                    rockContext.SaveChanges();

                    return Get( personAlias.Id );
                }
            }

            return null;
        }
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="itemKey">The item key.</param>
        /// <param name="itemKeyValue">The item key value.</param>
        public void ShowDetail( string itemKey, int itemKeyValue )
        {
            var rockContext = new RockContext();
            pnlDetails.Visible = false;

            if ( !itemKey.Equals( "businessId" ) )
            {
                return;
            }

            bool editAllowed = true;

            Person business = null;     // A business is a person

            if ( !itemKeyValue.Equals( 0 ) )
            {
                business = new PersonService( rockContext ).Get( itemKeyValue );
                editAllowed = business.IsAuthorized( Authorization.EDIT, CurrentPerson );
            }
            else
            {
                business = new Person { Id = 0 };
            }

            if ( business == null )
            {
                return;
            }

            pnlDetails.Visible = true;
            hfBusinessId.Value = business.Id.ToString();

            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;
            if ( !editAllowed || !IsUserAuthorized( Authorization.EDIT ) )
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( Person.FriendlyTypeName );
            }

            if ( readOnly )
            {
                ShowSummary( business );
            }
            else
            {
                if ( business.Id > 0 )
                {
                    ShowSummary( business );
                }
                else
                {
                    ShowEditDetails( business );
                }
            }

            BindContactListGrid( business );
        }
Пример #3
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="businessId">The business identifier.</param>
        public void ShowDetail( int businessId )
        {
            var rockContext = new RockContext();

            // Load the Campus drop down
            ddlCampus.Items.Clear();
            ddlCampus.Items.Add( new ListItem( string.Empty, string.Empty ) );
            foreach ( var campus in CampusCache.All() )
            {
                ListItem li = new ListItem( campus.Name, campus.Id.ToString() );
                ddlCampus.Items.Add( li );
            }

            Person business = null;     // A business is a person

            if ( !businessId.Equals( 0 ) )
            {
                business = new PersonService( rockContext ).Get( businessId );
                pdAuditDetails.SetEntity( business, ResolveRockUrl( "~" ) );
            }

            if ( business == null )
            {
                business = new Person { Id = 0, Guid = Guid.NewGuid() };
                // hide the panel drawer that show created and last modified dates
                pdAuditDetails.Visible = false;
            }

            bool editAllowed = business.IsAuthorized( Authorization.EDIT, CurrentPerson );

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

            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;
            if ( !editAllowed || !IsUserAuthorized( Authorization.EDIT ) )
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( Person.FriendlyTypeName );
            }

            if ( readOnly )
            {
                ShowSummary( businessId );
            }
            else
            {
                if ( business.Id > 0 )
                {
                    ShowSummary( business.Id );
                }
                else
                {
                    ShowEditDetails( business );
                }
            }

            BindContactListGrid( business );
        }
Пример #4
0
        /// <summary>
        /// Returns a list of matching people
        /// </summary>
        /// <param name="searchterm"></param>
        /// <returns></returns>
        public override IQueryable<string> Search( string searchterm )
        {
            var personService = new PersonService( new RockContext() );

            return personService.Queryable().
                Where( p => p.Email.Contains( searchterm ) ).
                OrderBy( p => p.Email ).
                Select( p => p.Email ).Distinct();
        }
Пример #5
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="businessId">The business identifier.</param>
        public void ShowDetail( int businessId )
        {
            var rockContext = new RockContext();

            // Load the Campus drop down
            ddlCampus.Items.Clear();
            ddlCampus.Items.Add( new ListItem( string.Empty, string.Empty ) );
            var campusService = new CampusService( new RockContext() );
            foreach ( Campus campus in campusService.Queryable() )
            {
                ListItem li = new ListItem( campus.Name, campus.Id.ToString() );
                ddlCampus.Items.Add( li );
            }

            Person business = null;     // A business is a person

            if ( !businessId.Equals( 0 ) )
            {
                business = new PersonService( rockContext ).Get( businessId );
            }

            if ( business == null )
            {
                business = new Person { Id = 0, Guid = Guid.NewGuid() };
            }

            bool editAllowed = business.IsAuthorized( Authorization.EDIT, CurrentPerson );

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

            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;
            if ( !editAllowed || !IsUserAuthorized( Authorization.EDIT ) )
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( Person.FriendlyTypeName );
            }

            if ( readOnly )
            {
                ShowSummary( businessId );
            }
            else
            {
                if ( business.Id > 0 )
                {
                    ShowSummary( business.Id );
                }
                else
                {
                    ShowEditDetails( business );
                }
            }

            BindContactListGrid( business );
        }
Пример #6
0
        protected Person GetPersonFromId(string PersonId)
        {
            int intPersonId = Int32.Parse(PersonId);
            PersonService personService = new PersonService(rockContext);

            var person = personService.Queryable().FirstOrDefault(p => p.Id == intPersonId);

            return person;
        }
        /// <summary>
        /// Creates the email communication.
        /// </summary>
        /// <param name="recipientEmails">The recipient emails.</param>
        /// <param name="fromName">From name.</param>
        /// <param name="fromAddress">From address.</param>
        /// <param name="replyTo">The reply to.</param>
        /// <param name="subject">The subject.</param>
        /// <param name="htmlMessage">The HTML message.</param>
        /// <param name="textMessage">The text message.</param>
        /// <param name="bulkCommunication">if set to <c>true</c> [bulk communication].</param>
        /// <param name="recipientStatus">The recipient status.</param>
        /// <param name="senderPersonAliasId">The sender person alias identifier.</param>
        /// <returns></returns>
        public Communication CreateEmailCommunication( 
            List<string> recipientEmails, 
            string fromName,
            string fromAddress,
            string replyTo,
            string subject,
            string htmlMessage,
            string textMessage,
            bool bulkCommunication, 
            CommunicationRecipientStatus recipientStatus = CommunicationRecipientStatus.Delivered, 
            int? senderPersonAliasId = null )
        {
            var recipients = new PersonService( (RockContext)this.Context )
                .Queryable()
                .Where( p => recipientEmails.Contains( p.Email ) )
                .ToList();

            if ( recipients.Any() )
            {
                Rock.Model.Communication communication = new Rock.Model.Communication();
                communication.Status = CommunicationStatus.Approved;
                communication.SenderPersonAliasId = senderPersonAliasId;
                communication.Subject = subject;
                Add( communication );

                communication.IsBulkCommunication = bulkCommunication;
                communication.MediumEntityTypeId = EntityTypeCache.Read( "Rock.Communication.Medium.Email" ).Id;
                communication.FutureSendDateTime = null;

                // add each person as a recipient to the communication
                foreach ( var person in recipients )
                {
                    int? personAliasId = person.PrimaryAliasId;
                    if ( personAliasId.HasValue )
                    {
                        var communicationRecipient = new CommunicationRecipient();
                        communicationRecipient.PersonAliasId = personAliasId.Value;
                        communicationRecipient.Status = recipientStatus;
                        communication.Recipients.Add( communicationRecipient );
                    }
                }

                // add the MediumData to the communication
                communication.MediumData.Clear();
                communication.MediumData.Add( "FromName", fromName );
                communication.MediumData.Add( "FromAddress", fromAddress );
                communication.MediumData.Add( "ReplyTo", replyTo );
                communication.MediumData.Add( "Subject", subject );
                communication.MediumData.Add( "HtmlMessage", htmlMessage );
                communication.MediumData.Add( "TextMessage", textMessage );

                return communication;
            }

            return null;
        }
Пример #8
0
        /// <summary>
        /// Gfs the pledges_ display filter value.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        protected void gfPledges_DisplayFilterValue( object sender, GridFilter.DisplayFilterValueArgs e )
        {
            switch ( e.Key )
            {
                case "Date Range":
                    e.Value = DateRangePicker.FormatDelimitedValues( e.Value );
                    break;

                case "Person":
                    int? personId = e.Value.AsIntegerOrNull();
                    if ( personId != null )
                    {
                        var person = new PersonService( new RockContext() ).Get( personId.Value );
                        if ( person != null )
                        {
                            e.Value = person.ToString();
                        }
                        else
                        {
                            e.Value = string.Empty;
                        }
                    }
                    else
                    {
                        e.Value = string.Empty;
                    }
                    break;

                case "Accounts":

                    var accountIdList = e.Value.Split( ',' ).AsIntegerList();
                    if ( accountIdList.Any() )
                    {
                        var service = new FinancialAccountService( new RockContext() );
                        var accounts = service.GetByIds( accountIdList );
                        if ( accounts != null && accounts.Any() )
                        {
                            e.Value = accounts.Select( a => a.Name ).ToList().AsDelimited( "," );
                        }
                        else
                        {
                            e.Value = string.Empty;
                        }
                    }
                    else
                    {
                        e.Value = string.Empty;
                    }

                    break;

                default:
                    e.Value = string.Empty;
                    break;
            }
        }
        /// <summary>
        /// Handles the Click event of the btnSubmit 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 btnSubmit_Click( object sender, EventArgs e )
        {
            if (_person != null)
            {
                var rockContext = new RockContext();
                var service = new PersonService( rockContext );
                var person = service.Get(_person.Id);
                if ( person != null )
                {
                    switch ( rblEmailPreference.SelectedValue )
                    {
                        case "0":
                            {
                                person.EmailPreference = EmailPreference.EmailAllowed;
                                break;
                            }
                        case "1":
                            {
                                person.EmailPreference = EmailPreference.NoMassEmails;
                                break;
                            }
                        case "2":
                        case "3":
                            {
                                person.EmailPreference = EmailPreference.DoNotEmail;
                                break;
                            }
                    }

                    if (rblEmailPreference.SelectedValue == "3")
                    {
                        person.RecordStatusValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ).Id;
                        person.RecordStatusReasonValueId = ddlInactiveReason.SelectedValue.AsInteger().Value;
                        person.ReviewReasonValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_REVIEW_REASON_SELF_INACTIVATED ).Id;
                        if ( string.IsNullOrWhiteSpace( person.ReviewReasonNote ) )
                        {
                            person.ReviewReasonNote = tbInactiveNote.Text;
                        }
                        else
                        {
                            person.ReviewReasonNote += " " + tbInactiveNote.Text;
                        }
                    }
                    else
                    {
                        person.RecordStatusValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE ).Id;
                        person.RecordStatusReasonValueId = null;
                    }

                    rockContext.SaveChanges();

                    nbMessage.Visible = true;
                    return;
                }
            }
        }
Пример #10
0
        protected void btnSend_Click( object sender, EventArgs e )
        {
            var mergeObjects = new Dictionary<string, object>();

            var url = LinkedPageUrl( "ConfirmationPage" );
            if ( string.IsNullOrWhiteSpace( url ) )
            {
                url = ResolveRockUrl( "~/ConfirmAccount" );
            }
            mergeObjects.Add( "ConfirmAccountUrl", RootPath + url.TrimStart( new char[] { '/' } ) );

            var personDictionaries = new List<IDictionary<string, object>>();

            var personService = new PersonService();
            var userLoginService = new UserLoginService();

            foreach ( Person person in personService.GetByEmail( tbEmail.Text ) )
            {
                var users = new List<IDictionary<string,object>>();
                foreach ( UserLogin user in userLoginService.GetByPersonId( person.Id ) )
                {
                    if ( user.EntityType != null )
                    {
                        var component = AuthenticationContainer.GetComponent( user.EntityType.Name );
                        if ( component.ServiceType == AuthenticationServiceType.Internal )
                        {
                            users.Add( user.ToDictionary() );
                        }
                    }
                }

                if (users.Count > 0)
                {
                    IDictionary<string,object> personDictionary = person.ToDictionary();
                    personDictionary.Add("Users", users.ToArray());
                    personDictionaries.Add( personDictionary );
                }
            }

            if ( personDictionaries.Count > 0 )
            {
                mergeObjects.Add( "Persons", personDictionaries.ToArray() );

                var recipients = new Dictionary<string, Dictionary<string, object>>();
                recipients.Add( tbEmail.Text, mergeObjects );

                Email email = new Email( GetAttributeValue( "EmailTemplate" ) );
                email.Send( recipients );

                pnlEntry.Visible = false;
                pnlSuccess.Visible = true;
            }
            else
                pnlWarning.Visible = true;
        }
Пример #11
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void RunCommand()
        {
            gReport.CreatePreviewColumns( typeof( Person ) );

            var service = new PersonService();
            var people = service.Queryable().Where( p => p.LastName == "Turner" );
            var parents = service.Transform( people, new Rock.Reporting.DataTransform.Person.ParentTransform() );

            gReport.DataSource = parents.ToList();
            gReport.DataBind();
        }
Пример #12
0
        protected Person GetPersonFromForm(string formId)
        {
            AttributeValueService attributeValueService = new AttributeValueService(rockContext);
            PersonService personService = new PersonService(rockContext);
            PersonAliasService personAliasService = new PersonAliasService(rockContext);

            var formAttribute = attributeValueService.Queryable().FirstOrDefault(a => a.Value == formId);
            var person = personService.Queryable().FirstOrDefault(p => p.Id == formAttribute.EntityId);

            return person;
        }
        /// <summary>
        /// Handles the Click event of the btnSend 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 btnSend_Click( object sender, EventArgs e )
        {
            var url = LinkedPageUrl( "ConfirmationPage" );
            if ( string.IsNullOrWhiteSpace( url ) )
            {
                url = ResolveRockUrl( "~/ConfirmAccount" );
            }

            var mergeObjects = GlobalAttributesCache.GetMergeFields( CurrentPerson );
            mergeObjects.Add( "ConfirmAccountUrl", RootPath + url.TrimStart( new char[] { '/' } ) );
            var results = new List<IDictionary<string, object>>();

            var rockContext = new RockContext();
            var personService = new PersonService( rockContext );
            var userLoginService = new UserLoginService( rockContext );

            foreach ( Person person in personService.GetByEmail( tbEmail.Text )
                .Where( p => p.Users.Any()))
            {
                var users = new List<UserLogin>();
                foreach ( UserLogin user in userLoginService.GetByPersonId( person.Id ) )
                {
                    if ( user.EntityType != null )
                    {
                        var component = AuthenticationContainer.GetComponent( user.EntityType.Name );
                        if ( !component.RequiresRemoteAuthentication )
                        {
                            users.Add( user );
                        }
                    }
                }

                var resultsDictionary = new Dictionary<string, object>();
                resultsDictionary.Add( "Person", person);
                resultsDictionary.Add( "Users", users );
                results.Add( resultsDictionary );
            }

            if ( results.Count > 0 )
            {
                mergeObjects.Add( "Results", results.ToArray() );
                var recipients = new List<RecipientData>();
                recipients.Add( new RecipientData( tbEmail.Text, mergeObjects ) );

                Email.Send( GetAttributeValue( "EmailTemplate" ).AsGuid(), recipients, ResolveRockUrlIncludeRoot( "~/" ), ResolveRockUrlIncludeRoot( "~~/" ) );

                pnlEntry.Visible = false;
                pnlSuccess.Visible = true;
            }
            else
            {
                pnlWarning.Visible = true;
            }
        }
        /// <summary>
        /// Handles the Delete event of the gBusinessList control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rock.Web.UI.Controls.RowEventArgs"/> instance containing the event data.</param>
        protected void gBusinessList_Delete( object sender, Rock.Web.UI.Controls.RowEventArgs e )
        {
            var rockContext = new RockContext();
            PersonService service = new PersonService( rockContext );
            Person business = service.Get( e.RowKeyId );
            if ( business != null )
            {
                business.RecordStatusValueId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ) ).Id;
                rockContext.SaveChanges();
            }

            BindGrid();
        }
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit( EventArgs e )
        {
            base.OnInit( e );

            try
            {
                var groupGuid = GetAttributeValue( "Group" ).AsGuidOrNull();
                string personKey = PageParameter( "Person" );

                if ( !groupGuid.HasValue )
                {
                    ShowConfigError( "The 'Group' configuration for this block has not been set." );
                }
                else if ( string.IsNullOrWhiteSpace( personKey ) )
                {
                    ShowError( "Missing Parameter Value" );
                }
                else
                {
                    RockContext rockContext = new RockContext();
                    Person targetPerson = null;
                    targetPerson = new PersonService( rockContext ).GetByUrlEncodedKey( personKey );

                    if ( targetPerson == null )
                    {
                        ShowError( "We can't find a record in our system for you." );
                    }
                    else
                    {
                        GroupService groupService = new GroupService( rockContext );
                        Group group = groupService.Get( groupGuid.Value );
                        if ( group == null )
                        {
                            ShowConfigError( "The 'Group' configuration for this block is incorrect." );
                        }
                        else
                        {
                            AddOrUpdatePersonInGroup( targetPerson, group, rockContext );
                        }
                    }
                }
            }
            catch ( System.FormatException )
            {
                ShowError( "Something is wrong with that link.  Are you sure you copied it correctly?" );
            }
            catch ( SystemException ex )
            {
                ShowError( ex.Message );
            }
        }
Пример #16
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override bool Execute( Model.WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            var checkInState = GetCheckInState( entity, out errorMessages );
            if (checkInState != null)
            {
                using ( new Rock.Data.UnitOfWorkScope() )
                {
                    var personService = new PersonService();
                    var memberService = new GroupMemberService();
                    IQueryable<Person> people = null;

                    if ( checkInState.CheckIn.SearchType.Guid.Equals( new Guid( SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_PHONE_NUMBER ) ) )
                    {
                        people = personService.GetByPhonePartial( checkInState.CheckIn.SearchValue );
                    }
                    else if ( checkInState.CheckIn.SearchType.Guid.Equals( new Guid( SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_NAME ) ) )
                    {
                        people = personService.GetByFullName( checkInState.CheckIn.SearchValue );
                    }
                    else
                    {
                        errorMessages.Add( "Invalid Search Type" );
                        return false;
                    }

                    foreach ( var person in people.ToList() )
                    {
                        foreach ( var group in person.Members.Where( m => m.Group.GroupType.Guid == new Guid( SystemGuid.GroupType.GROUPTYPE_FAMILY ) ).Select( m => m.Group ).ToList() )
                        {
                            var family = checkInState.CheckIn.Families.Where( f => f.Group.Id == group.Id ).FirstOrDefault();
                            if ( family == null )
                            {
                                family = new CheckInFamily();
                                family.Group = group.Clone( false );
                                family.Group.LoadAttributes();
                                family.Caption = group.ToString();
                                family.SubCaption = memberService.GetFirstNames( group.Id ).ToList().AsDelimited( ", " );
                                checkInState.CheckIn.Families.Add( family );
                            }
                        }
                    }

                    return true;
                }
            }

            errorMessages.Add( "Invalid Check-in State" );
            return false;
        }
Пример #17
0
        private void BindGrid()
        {
            var HtmlService = new HtmlContentService();
            var content     = HtmlService.GetContent(CurrentBlock.Id, EntityValue());

            var personService   = new Rock.Model.PersonService();
            var versionAudits   = new Dictionary <int, Rock.Model.Audit>();
            var modifiedPersons = new Dictionary <int, string>();

            foreach (var version in content)
            {
                var lastAudit = HtmlService.Audits(version)
                                .Where(a => a.AuditType == Rock.Model.AuditType.Add ||
                                       a.AuditType == Rock.Model.AuditType.Modify)
                                .OrderByDescending(h => h.DateTime)
                                .FirstOrDefault();
                if (lastAudit != null)
                {
                    versionAudits.Add(version.Id, lastAudit);
                }
            }

            foreach (var audit in versionAudits.Values)
            {
                if (audit.PersonId.HasValue && !modifiedPersons.ContainsKey(audit.PersonId.Value))
                {
                    var modifiedPerson = personService.Get(audit.PersonId.Value, true);
                    modifiedPersons.Add(audit.PersonId.Value, modifiedPerson != null ? modifiedPerson.FullName : string.Empty);
                }
            }

            var versions = content.
                           Select(v => new
            {
                v.Id,
                v.Version,
                v.Content,
                ModifiedDateTime = versionAudits.ContainsKey(v.Id) ? versionAudits[v.Id].DateTime.ToElapsedString() : string.Empty,
                ModifiedByPerson = versionAudits.ContainsKey(v.Id) && versionAudits[v.Id].PersonId.HasValue ? modifiedPersons[versionAudits[v.Id].PersonId.Value] : string.Empty,
                Approved         = v.IsApproved,
                ApprovedByPerson = v.ApprovedByPerson != null ? v.ApprovedByPerson.FullName : "",
                v.StartDateTime,
                v.ExpireDateTime
            }).ToList();

            rGrid.DataSource = versions;
            rGrid.DataBind();
        }
Пример #18
0
        /// <summary>
        /// Returns the field's current value(s)
        /// </summary>
        /// <param name="parentControl">The parent control.</param>
        /// <param name="value">Information about the value</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param>
        /// <returns></returns>
        public override string FormatValue( System.Web.UI.Control parentControl, string value, Dictionary<string, ConfigurationValue> configurationValues, bool condensed )
        {
            string formattedValue = string.Empty;

            if ( !string.IsNullOrWhiteSpace( value ) )
            {
                var service = new PersonService();
                var person = service.Get( new Guid( value ) );
                if ( person != null )
                {
                    formattedValue = person.FullName;
                }
            }

            return base.FormatValue( parentControl, formattedValue, null, condensed );
        }
Пример #19
0
        protected void btnUpdate_Click( object sender, EventArgs e )
        {
            if ( Page.IsValid && person != null)
            {
                PersonService personService = new PersonService();

                person.GivenName = txtFirstName.Text;
                person.NickName = txtNickName.Text;
                person.LastName = txtLastName.Text;

                if ( person.Guid == Guid.Empty )
                    personService.Add( person, CurrentPersonId );

                personService.Save( person, CurrentPersonId );
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //Set the person picker to the currently logged in person.
            PersonService personService = new PersonService(rockContext);
            var personObject = personService.Get(CurrentPerson.Guid);

            //Get the person from the URL
            string qsPersonId = PageParameter("PersonId");
            int iPersonId = Int32.Parse(qsPersonId);

            var thePerson = personService.Get(iPersonId);

            //Get the URL encoded key from the person object
            var urlEncodedKey = thePerson.UrlEncodedKey;
            PageViewHistoryUrl = ResolveUrl("~/page/279?Person=" + urlEncodedKey);
        }
Пример #21
0
        public void DeleteKnownRelationship( int personId, int relatedPersonId, int relationshipRoleId )
        {
            SetProxyCreation( true );
            var rockContext = this.Service.Context as RockContext;
            var personService = new PersonService( rockContext );
            var person = personService.Get( personId );
            var relatedPerson = personService.Get( relatedPersonId );

            CheckCanEdit( person );
            CheckCanEdit( relatedPerson );

            System.Web.HttpContext.Current.Items.Add( "CurrentPerson", GetPerson() );

            var groupMemberService = new GroupMemberService( rockContext );
            groupMemberService.DeleteKnownRelationship( personId, relatedPersonId, relationshipRoleId );
        }
Пример #22
0
        protected void btnSubmit_OnClick(object sender, EventArgs e)
        {
            pnlOpportunities.Visible = true;
            pnlSignature.Visible = false;
            pnlSuccess.Visible = true;

            AttributeValueService attributeValueService = new AttributeValueService(rockContext);
            PersonService personService = new PersonService(rockContext);

            List<Guid> personGuidList = new List<Guid>();
            personGuidList.Add(_targetPerson.Guid);

            var p = attributeValueService.GetByAttributeIdAndEntityId(906, _targetPerson.Id);
            var p2 = attributeValueService.GetByAttributeIdAndEntityId(1434, _targetPerson.Id);

            var personFromService = personService.GetByGuids(personGuidList).FirstOrDefault();

            DateTime dateToSave = DateTime.Now.AddYears(CurrentYearAdd);

            p.Value = dateToSave.ToString();

            if (p2.Value.IsNullOrWhiteSpace())
            {
                p2.Value = dateToSave.Year.ToString();
            }
            else
            {
                if (!p2.Value.Contains(dateToSave.Year.ToString()))
                {
                    p2.Value = p2.Value + "," + dateToSave.Year.ToString();
                }

            }

            personFromService.ConnectionStatusValue.Value = "Partner";
            personFromService.ConnectionStatusValueId = 65;

            rockContext.SaveChanges();

            LoadOpportunities();

            if (GetAttributeValue("SendConfirmationEmail") == "True")
            {
                SendEmail(personFromService.Email, CurrentDateTime.Year.ToString() + " Partnership Covenant", rockContext);
            }
        }
Пример #23
0
        protected void Page_Load( object sender, EventArgs e )
        {
            person = CurrentPage.GetCurrentContext( "Rock.Model.Person" ) as Rock.Model.Person;
            if (person == null)
            {
                PersonService personService = new PersonService();
                person = new Person();
                personService.Add( person, CurrentPersonId );
            }

            if ( !IsPostBack )
            {
                txtFirstName.Text = person.FirstName;
                txtNickName.Text = person.NickName;
                txtLastName.Text = person.LastName;
            }
        }
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="restUserId">The rest user identifier.</param>
        public void ShowDetail( int restUserId )
        {
            var rockContext = new RockContext();

            Person restUser = null;

            if ( !restUserId.Equals( 0 ) )
            {
                restUser = new PersonService( rockContext ).Get( restUserId );
            }

            if ( restUser == null )
            {
                restUser = new Person { Id = 0 };
            }

            bool editAllowed = restUser.IsAuthorized( Authorization.EDIT, CurrentPerson );

            hfRestUserId.Value = restUser.Id.ToString();
            lTitle.Text = ActionTitle.Edit( "REST Key" ).FormatAsHtmlTitle();
            if ( restUser.Id > 0 )
            {
                tbName.Text = restUser.LastName;
                cbActive.Checked = false;
                var activeStatusId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid() ).Id;
                if ( restUser.RecordStatusValueId == activeStatusId )
                {
                    cbActive.Checked = true;
                }

                var noteService = new NoteService( rockContext );
                var description = noteService.Queryable().Where( a => a.EntityId == restUser.Id ).FirstOrDefault();
                if ( description != null )
                {
                    tbDescription.Text = description.Text;
                }

                var userLoginService = new UserLoginService( rockContext );
                var userLogin = userLoginService.Queryable().Where( a => a.PersonId == restUser.Id ).FirstOrDefault();
                if ( userLogin != null )
                {
                    tbKey.Text = userLogin.ApiKey;
                }
            }
        }
        public GroupOfTypeResult GetInGroupOfType(int personId, Guid groupTypeId)
        {
            GroupOfTypeResult result = new GroupOfTypeResult();
            result.PersonId = personId;
            result.PersonInGroup = false;
            result.GroupList = new List<GroupSummary>();

            // get person info
            Person person = new PersonService( (Rock.Data.RockContext)Service.Context ).Get( personId );

            if (person != null)
            {
                result.NickName = person.NickName;
                result.LastName = person.LastName;
            }

            // get group type info
            GroupType groupType = new GroupTypeService( (Rock.Data.RockContext)Service.Context ).Get( groupTypeId );

            if (groupType != null)
            {
                result.GroupTypeName = groupType.Name;
                result.GroupTypeIconCss = groupType.IconCssClass;
                result.GroupTypeId = groupType.Id;
            }

            // determine if person is in this type of group
            GroupMemberService groupMemberService = new GroupMemberService( (Rock.Data.RockContext)Service.Context );
            IQueryable<GroupMember> groupMembershipsQuery = groupMemberService.Queryable("Person,GroupRole,Group")
                                        .Where(t => t.Group.GroupType.Guid == groupTypeId && t.PersonId == personId )
                                        .OrderBy(g => g.GroupRole.Order);

            foreach (GroupMember member in groupMembershipsQuery)
            {
                result.PersonInGroup = true;
                GroupSummary group = new GroupSummary();
                group.GroupName = member.Group.Name;
                group.GroupId = member.Group.Id;
                group.RoleName = member.GroupRole.Name;

                result.GroupList.Add(group);
            }

            return result;
        }
Пример #26
0
        public System.Net.Http.HttpResponseMessage CreateKnownRelationship( int personId, int relatedPersonId, int relationshipRoleId )
        {
            SetProxyCreation( true );
            var rockContext = this.Service.Context as RockContext;
            var personService = new PersonService(rockContext);
            var person = personService.Get(personId);
            var relatedPerson = personService.Get(relatedPersonId);

            CheckCanEdit( person );
            CheckCanEdit( relatedPerson );

            System.Web.HttpContext.Current.Items.Add( "CurrentPerson", GetPerson() );

            var groupMemberService = new GroupMemberService(rockContext);
            groupMemberService.CreateKnownRelationship( personId, relatedPersonId, relationshipRoleId );

            return ControllerContext.Request.CreateResponse( HttpStatusCode.Created );
        }
Пример #27
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit( EventArgs e )
        {
            base.OnInit( e );

            var mergeObjects = GlobalAttributesCache.GetMergeFields( CurrentPerson );
            LoadDropdowns( mergeObjects );

            var key = PageParameter( "Person" );
            if ( !string.IsNullOrWhiteSpace( key ) )
            {
                var service = new PersonService( new RockContext() );
                _person = service.GetByUrlEncodedKey( key );
            }

            if ( _person == null && CurrentPerson != null )
            {
                _person = CurrentPerson;
            }

            if (_person != null)
            {
                nbMessage.NotificationBoxType = NotificationBoxType.Success;
                nbMessage.Text = GetAttributeValue( "SuccessText" ).ResolveMergeFields( mergeObjects );
            }
            else
            {
                nbMessage.NotificationBoxType = NotificationBoxType.Danger;
                nbMessage.Text = "Unfortunately, we're unable to update your email preference, as we're not sure who you are.";
                nbMessage.Visible = true;
                btnSubmit.Visible = false;
            }

            string script = string.Format( @"
    $(""input[id^='{0}'"").click(function () {{
        if ($(this).val() == '3') {{
            $('#{1}').slideDown('fast');
        }} else {{
            $('#{1}').slideUp('fast');
        }}
    }});    
", rblEmailPreference.ClientID, divNotInvolved.ClientID );

            ScriptManager.RegisterStartupScript( rblEmailPreference, rblEmailPreference.GetType(), "toggle-preference" + this.BlockId.ToString(), script, true );
        }
Пример #28
0
        /// <summary>
        /// Handles the Delete event of the gRestKeyList 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 gRestKeyList_Delete( object sender, RowEventArgs e )
        {
            var rockContext = new RockContext();
            var personService = new PersonService( rockContext );
            var userLoginService = new UserLoginService( rockContext );
            var restUser = personService.Get( e.RowKeyId );
            if ( restUser != null )
            {
                restUser.RecordStatusValueId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ) ).Id;

                // remove all user logins for key
                foreach ( var login in restUser.Users.ToList() )
                {
                    userLoginService.Delete( login );
                }
                rockContext.SaveChanges();
            }

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

            ddlTitle.BindToDefinedType( DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_TITLE ) ), true );
            ddlSuffix.BindToDefinedType( DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_SUFFIX ) ), true );
            rblMaritalStatus.BindToDefinedType( DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS ) ) );
            rblStatus.BindToDefinedType( DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS ) ) );
            ddlRecordStatus.BindToDefinedType( DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_RECORD_STATUS ) ) );
            ddlReason.BindToDefinedType( DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_RECORD_STATUS_REASON ) ), true );

            ddlGivingGroup.Items.Clear();
            ddlGivingGroup.Items.Add( new ListItem( None.Text, None.IdValue ) );
            if ( Person != null )
            {
                var personService = new PersonService();
                foreach ( var family in personService.GetFamilies( Person ) )
                {
                    ddlGivingGroup.Items.Add( new ListItem( family.Name, family.Id.ToString() ) );
                }
            }
        }
Пример #30
0
        /// <summary>
        /// Returns a list of each person and their GroupRequiremnt status for this group requirement
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="personQry">The person qry.</param>
        /// <param name="groupId">The group identifier.</param>
        /// <param name="groupRoleId">The group role identifier.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception">No dataview assigned to Group Requirement Type: " + this.GroupRequirementType.Name</exception>
        public IEnumerable <PersonGroupRequirementStatus> PersonQueryableMeetsGroupRequirement(RockContext rockContext, IQueryable <Person> personQry, int groupId, int?groupRoleId)
        {
            if ((this.GroupRoleId != null) && (groupRoleId != null) && (this.GroupRoleId != groupRoleId))
            {
                // if this GroupRequirement is for a specific role, the groupRole we are checking for is something different
                var result = personQry.ToList().Select(a =>
                                                       new PersonGroupRequirementStatus
                {
                    PersonId              = a.Id,
                    GroupRequirement      = this,
                    MeetsGroupRequirement = MeetsGroupRequirement.NotApplicable
                });

                return(result);
            }

            if (this.GroupRequirementType.RequirementCheckType == RequirementCheckType.Dataview)
            {
                if (this.GroupRequirementType.DataViewId.HasValue)
                {
                    var errorMessages           = new List <string>();
                    var personService           = new PersonService(rockContext);
                    var paramExpression         = personService.ParameterExpression;
                    var dataViewWhereExpression = this.GroupRequirementType.DataView.GetExpression(personService, paramExpression, out errorMessages);
                    var dataViewQry             = personService.Get(paramExpression, dataViewWhereExpression);

                    IQueryable <Person> warningDataViewQry = null;
                    if (this.GroupRequirementType.WarningDataViewId.HasValue)
                    {
                        var warningDataViewWhereExpression = this.GroupRequirementType.WarningDataView.GetExpression(personService, paramExpression, out errorMessages);
                        warningDataViewQry = personService.Get(paramExpression, warningDataViewWhereExpression);
                    }

                    if (dataViewQry != null)
                    {
                        var personWithRequirements = from p in personQry
                                                     join d in dataViewQry on p equals d into oj
                                                     from d in oj.DefaultIfEmpty()
                                                     select new { PersonId = p.Id, Included = d != null, WarningIncluded = false };

                        // if a Warning Database was specified, set the WarningIncluded flag to true if they are included in the Warning Dataview
                        if (warningDataViewQry != null)
                        {
                            personWithRequirements = personWithRequirements.Select(a => new
                            {
                                a.PersonId,
                                a.Included,
                                WarningIncluded = warningDataViewQry.Any(w => w.Id == a.PersonId)
                            });
                        }

                        var result = personWithRequirements.ToList().Select(a =>
                                                                            new PersonGroupRequirementStatus
                        {
                            PersonId              = a.PersonId,
                            GroupRequirement      = this,
                            MeetsGroupRequirement = a.Included
                                    ? (a.WarningIncluded ? MeetsGroupRequirement.MeetsWithWarning : MeetsGroupRequirement.Meets)
                                    : MeetsGroupRequirement.NotMet
                        });

                        return(result);
                    }
                }
                else
                {
                    throw new Exception("No dataview assigned to Group Requirement Type: " + this.GroupRequirementType.Name);
                }
            }
            else if (this.GroupRequirementType.RequirementCheckType == RequirementCheckType.Sql)
            {
                // if requirement set on GroupType, this.Group is null
                var targetGroup = this.Group ?? new GroupService(rockContext).Get(groupId);

                string formattedSql        = this.GroupRequirementType.SqlExpression.ResolveMergeFields(this.GroupRequirementType.GetMergeObjects(targetGroup));
                string warningFormattedSql = this.GroupRequirementType.WarningSqlExpression.ResolveMergeFields(this.GroupRequirementType.GetMergeObjects(targetGroup));
                try
                {
                    var tableResult = DbService.GetDataTable(formattedSql, System.Data.CommandType.Text, null);
                    if (tableResult.Columns.Count > 0)
                    {
                        IEnumerable <int> personIds        = tableResult.Rows.OfType <System.Data.DataRow>().Select(r => Convert.ToInt32(r[0]));
                        IEnumerable <int> warningPersonIds = null;

                        // if a Warning SQL was specified, get a list of PersonIds that should have a warning with their status
                        if (!string.IsNullOrWhiteSpace(warningFormattedSql))
                        {
                            var warningTableResult = DbService.GetDataTable(warningFormattedSql, System.Data.CommandType.Text, null);
                            if (warningTableResult.Columns.Count > 0)
                            {
                                warningPersonIds = warningTableResult.Rows.OfType <System.Data.DataRow>().Select(r => Convert.ToInt32(r[0]));
                            }
                        }

                        var result = personQry.Select(a => a.Id).ToList().Select(a => new PersonGroupRequirementStatus
                        {
                            PersonId              = a,
                            GroupRequirement      = this,
                            MeetsGroupRequirement = personIds.Contains(a)
                                    ? ((warningPersonIds != null && warningPersonIds.Contains(a))
                                        ? MeetsGroupRequirement.MeetsWithWarning
                                        : MeetsGroupRequirement.Meets
                                       )
                                    : MeetsGroupRequirement.NotMet,
                        });

                        return(result);
                    }
                }
                catch (Exception ex)
                {
                    // Exception occurred (probably due to bad SQL)
                    ExceptionLogService.LogException(ex, System.Web.HttpContext.Current);

                    var result = personQry.Select(a => a.Id).ToList().Select(a => new PersonGroupRequirementStatus
                    {
                        PersonId              = a,
                        GroupRequirement      = this,
                        MeetsGroupRequirement = MeetsGroupRequirement.Error
                    });

                    return(result);
                }
            }
            else
            {
                // manual
                var groupMemberRequirementQry = new GroupMemberRequirementService(rockContext).Queryable().Where(a => a.GroupMember.GroupId == groupId && a.GroupRequirementId == this.Id && a.RequirementMetDateTime.HasValue);

                var result = personQry.ToList().Select(a =>
                                                       new PersonGroupRequirementStatus
                {
                    PersonId              = a.Id,
                    GroupRequirement      = this,
                    MeetsGroupRequirement = groupMemberRequirementQry.Any(r => r.GroupMember.PersonId == a.Id) ? MeetsGroupRequirement.Meets : MeetsGroupRequirement.NotMet
                });

                return(result);
            }

            // shouldn't happen
            return(null);
        }
Пример #31
0
        /// <summary>
        /// Gets the existing value for a specific field for the given registrant.
        /// </summary>
        /// <param name="registrant">The registrant.</param>
        /// <param name="person">The person.</param>
        /// <param name="family">The family.</param>
        /// <param name="Field">The field.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        public object GetRegistrantValue(RegistrationRegistrant registrant, Person person, Group family,
                                         RegistrationTemplateFormField Field, RockContext rockContext)
        {
            if (Field.FieldSource == RegistrationFieldSource.PersonField)
            {
                if (person != null)
                {
                    DefinedValueCache dvPhone = null;

                    switch (Field.PersonFieldType)
                    {
                    case RegistrationPersonFieldType.FirstName: return(person.NickName);

                    case RegistrationPersonFieldType.LastName: return(person.LastName);

                    case RegistrationPersonFieldType.Campus:
                    {
                        if (family != null)
                        {
                            return(family.CampusId);
                        }
                        break;
                    }

                    case RegistrationPersonFieldType.Address:
                    {
                        var location = person.GetHomeLocation(rockContext);
                        if (location != null)
                        {
                            return(location.Clone());
                        }
                        break;
                    }

                    case RegistrationPersonFieldType.Email: return(person.Email);

                    case RegistrationPersonFieldType.Birthdate: return(person.BirthDate);

                    case RegistrationPersonFieldType.Gender: return(person.Gender);

                    case RegistrationPersonFieldType.MaritalStatus: return(person.MaritalStatusValueId);

                    case RegistrationPersonFieldType.MobilePhone:
                    {
                        dvPhone = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE);
                        break;
                    }

                    case RegistrationPersonFieldType.HomePhone:
                    {
                        dvPhone = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME);
                        break;
                    }

                    case RegistrationPersonFieldType.WorkPhone:
                    {
                        dvPhone = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK);
                        break;
                    }
                    }

                    if (dvPhone != null)
                    {
                        var phoneNumber = new PersonService(rockContext).GetPhoneNumber(person, dvPhone);
                        if (phoneNumber != null)
                        {
                            return(phoneNumber.Clone());
                        }
                    }
                }
            }
            else
            {
                var attribute = AttributeCache.Read(Field.AttributeId ?? 0);
                if (attribute != null)
                {
                    switch (Field.FieldSource)
                    {
                    case RegistrationFieldSource.PersonAttribute:
                    {
                        if (person != null)
                        {
                            if (person.Attributes == null)
                            {
                                person.LoadAttributes();
                            }
                            return(person.GetAttributeValue(attribute.Key));
                        }
                        break;
                    }

                    case RegistrationFieldSource.GroupMemberAttribute:
                    {
                        if (registrant.GroupMember != null)
                        {
                            if (registrant.GroupMember.Attributes == null)
                            {
                                registrant.GroupMember.LoadAttributes();
                            }
                            return(registrant.GroupMember.GetAttributeValue(attribute.Key));
                        }
                        break;
                    }

                    case RegistrationFieldSource.RegistrationAttribute:
                    {
                        if (registrant.Attributes == null)
                        {
                            registrant.LoadAttributes();
                        }
                        return(registrant.GetAttributeValue(attribute.Key));
                    }
                    }
                }
            }

            return(null);
        }
Пример #32
0
        /// <summary>
        /// Sends the specified recipients.
        /// </summary>
        /// <param name="recipients">The recipients.</param>
        /// <param name="from">From.</param>
        /// <param name="fromName">From name.</param>
        /// <param name="subject">The subject.</param>
        /// <param name="body">The body.</param>
        /// <param name="appRoot">The application root.</param>
        /// <param name="themeRoot">The theme root.</param>
        /// <param name="attachments">Attachments.</param>
        /// <param name="createCommunicationHistory">if set to <c>true</c> [create communication history].</param>
        public void Send(List<string> recipients, string from, string fromName, string subject, string body, string appRoot, string themeRoot, List<Attachment> attachments, bool createCommunicationHistory )
        {
            try
            {
                var globalAttributes = GlobalAttributesCache.Read();

                if ( string.IsNullOrWhiteSpace( from ) )
                {
                    from = globalAttributes.GetValue( "OrganizationEmail" );
                }

                if ( !string.IsNullOrWhiteSpace( from ) )
                {
                    // Resolve any possible merge fields in the from address
                    var globalConfigValues = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields( null );
                    string msgFrom = from.ResolveMergeFields( globalConfigValues );

                    string msgSubject = subject;
                    string msgBody = body;
                    if ( !string.IsNullOrWhiteSpace( themeRoot ) )
                    {
                        msgSubject = msgSubject.Replace( "~~/", themeRoot );
                        msgBody = msgBody.Replace( "~~/", themeRoot );
                    }

                    if ( !string.IsNullOrWhiteSpace( appRoot ) )
                    {
                        msgSubject = msgSubject.Replace( "~/", appRoot );
                        msgBody = msgBody.Replace( "~/", appRoot );
                        msgBody = msgBody.Replace( @" src=""/", @" src=""" + appRoot );
                        msgBody = msgBody.Replace( @" href=""/", @" href=""" + appRoot );
                    }

                    MailMessage message = new MailMessage();

                    // set from
                    if ( !string.IsNullOrWhiteSpace( fromName ) )
                    {
                        message.From = new MailAddress( msgFrom, fromName );
                    }
                    else
                    {
                        message.From = new MailAddress( msgFrom );
                    }

                    CheckSafeSender( message, globalAttributes );

                    message.IsBodyHtml = true;
                    message.Priority = MailPriority.Normal;

                    message.To.Clear();
                    recipients.ForEach( r => message.To.Add( r ) );

                    message.Subject = msgSubject;

                    // strip out any unsubscribe links since we don't know the person
                    msgBody = Regex.Replace( msgBody, @"\[\[\s*UnsubscribeOption\s*\]\]", string.Empty );

                    message.Body = msgBody;

                    // add attachments
                    if ( attachments != null )
                    {
                        foreach ( var attachment in attachments )
                        {
                            message.Attachments.Add(attachment);
                        }
                    }

                    using ( var smtpClient = GetSmtpClient() )
                    {
                        smtpClient.Send( message );
                    }

                    if ( createCommunicationHistory )
                    {
                        using ( var rockContext = new RockContext() )
                        {
                            int? senderPersonAliasId = null;
                            if ( createCommunicationHistory )
                            {
                                var sender = new PersonService( rockContext )
                                    .Queryable().AsNoTracking()
                                    .Where( p => p.Email == from )
                                    .FirstOrDefault();
                                senderPersonAliasId = sender != null ? sender.PrimaryAliasId : (int?)null;
                            }

                            new CommunicationService( rockContext ).CreateEmailCommunication(
                                recipients, fromName, from, from, subject, body, string.Empty, false,
                                CommunicationRecipientStatus.Delivered, senderPersonAliasId );

                            rockContext.SaveChanges();
                        }
                    }
                }
            }
            catch ( Exception ex )
            {
                ExceptionLogService.LogException( ex, null );
            }
        }
Пример #33
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>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            var rockContext = new RockContext();
            rockContext.WrapTransaction( () =>
            {
                var personService = new PersonService( rockContext );

                var changes = new List<string>();

                var person = personService.Get( CurrentPersonId ?? 0 );
                if ( person != null )
                {
                    int? orphanedPhotoId = null;
                    if ( person.PhotoId != imgPhoto.BinaryFileId )
                    {
                        orphanedPhotoId = person.PhotoId;
                        person.PhotoId = imgPhoto.BinaryFileId;

                        if ( orphanedPhotoId.HasValue )
                        {
                            if ( person.PhotoId.HasValue )
                            {
                                changes.Add( "Modified the photo." );
                            }
                            else
                            {
                                changes.Add( "Deleted the photo." );
                            }
                        }
                        else if ( person.PhotoId.HasValue )
                        {
                            changes.Add( "Added a photo." );
                        }
                    }

                    int? newTitleId = ddlTitle.SelectedValueAsInt();
                    History.EvaluateChange( changes, "Title", DefinedValueCache.GetName( person.TitleValueId ), DefinedValueCache.GetName( newTitleId ) );
                    person.TitleValueId = newTitleId;

                    History.EvaluateChange( changes, "First Name", person.FirstName, tbFirstName.Text );
                    person.FirstName = tbFirstName.Text;

                    History.EvaluateChange(changes, "Nick Name", person.NickName, tbNickName.Text);
                    person.NickName = tbNickName.Text;

                    History.EvaluateChange( changes, "Last Name", person.LastName, tbLastName.Text );
                    person.LastName = tbLastName.Text;

                    int? newSuffixId = ddlSuffix.SelectedValueAsInt();
                    History.EvaluateChange( changes, "Suffix", DefinedValueCache.GetName( person.SuffixValueId ), DefinedValueCache.GetName( newSuffixId ) );
                    person.SuffixValueId = newSuffixId;

                    var birthMonth = person.BirthMonth;
                    var birthDay = person.BirthDay;
                    var birthYear = person.BirthYear;

                    var birthday = bpBirthDay.SelectedDate;
                    if ( birthday.HasValue )
                    {
                        // If setting a future birthdate, subtract a century until birthdate is not greater than today.
                        var today = RockDateTime.Today;
                        while ( birthday.Value.CompareTo( today ) > 0 )
                        {
                            birthday = birthday.Value.AddYears( -100 );
                        }

                        person.BirthMonth = birthday.Value.Month;
                        person.BirthDay = birthday.Value.Day;
                        if ( birthday.Value.Year != DateTime.MinValue.Year )
                        {
                            person.BirthYear = birthday.Value.Year;
                        }
                        else
                        {
                            person.BirthYear = null;
                        }
                    }
                    else
                    {
                        person.SetBirthDate( null );
                    }

                    History.EvaluateChange( changes, "Birth Month", birthMonth, person.BirthMonth );
                    History.EvaluateChange( changes, "Birth Day", birthDay, person.BirthDay );
                    History.EvaluateChange( changes, "Birth Year", birthYear, person.BirthYear );

                    var newGender = rblGender.SelectedValue.ConvertToEnum<Gender>();
                    History.EvaluateChange( changes, "Gender", person.Gender, newGender );
                    person.Gender = newGender;

                    var phoneNumberTypeIds = new List<int>();

                    bool smsSelected = false;

                    foreach ( RepeaterItem item in rContactInfo.Items )
                    {
                        HiddenField hfPhoneType = item.FindControl( "hfPhoneType" ) as HiddenField;
                        PhoneNumberBox pnbPhone = item.FindControl( "pnbPhone" ) as PhoneNumberBox;
                        CheckBox cbUnlisted = item.FindControl( "cbUnlisted" ) as CheckBox;
                        CheckBox cbSms = item.FindControl( "cbSms" ) as CheckBox;

                        if ( hfPhoneType != null &&
                            pnbPhone != null &&
                            cbSms != null &&
                            cbUnlisted != null )
                        {
                            if ( !string.IsNullOrWhiteSpace( PhoneNumber.CleanNumber( pnbPhone.Number ) ) )
                            {
                                int phoneNumberTypeId;
                                if ( int.TryParse( hfPhoneType.Value, out phoneNumberTypeId ) )
                                {
                                    var phoneNumber = person.PhoneNumbers.FirstOrDefault( n => n.NumberTypeValueId == phoneNumberTypeId );
                                    string oldPhoneNumber = string.Empty;
                                    if ( phoneNumber == null )
                                    {
                                        phoneNumber = new PhoneNumber { NumberTypeValueId = phoneNumberTypeId };
                                        person.PhoneNumbers.Add( phoneNumber );
                                    }
                                    else
                                    {
                                        oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                                    }

                                    phoneNumber.CountryCode = PhoneNumber.CleanNumber( pnbPhone.CountryCode );
                                    phoneNumber.Number = PhoneNumber.CleanNumber( pnbPhone.Number );

                                    // Only allow one number to have SMS selected
                                    if ( smsSelected )
                                    {
                                        phoneNumber.IsMessagingEnabled = false;
                                    }
                                    else
                                    {
                                        phoneNumber.IsMessagingEnabled = cbSms.Checked;
                                        smsSelected = cbSms.Checked;
                                    }

                                    phoneNumber.IsUnlisted = cbUnlisted.Checked;
                                    phoneNumberTypeIds.Add( phoneNumberTypeId );

                                    History.EvaluateChange(
                                        changes,
                                        string.Format( "{0} Phone", DefinedValueCache.GetName( phoneNumberTypeId ) ),
                                        oldPhoneNumber,
                                        phoneNumber.NumberFormattedWithCountryCode );
                                }
                            }
                        }
                    }

                    // Remove any blank numbers
                    var phoneNumberService = new PhoneNumberService( rockContext );
                    foreach ( var phoneNumber in person.PhoneNumbers
                        .Where( n => n.NumberTypeValueId.HasValue && !phoneNumberTypeIds.Contains( n.NumberTypeValueId.Value ) )
                        .ToList() )
                    {
                        History.EvaluateChange(
                            changes,
                            string.Format( "{0} Phone", DefinedValueCache.GetName( phoneNumber.NumberTypeValueId ) ),
                            phoneNumber.ToString(),
                            string.Empty );

                        person.PhoneNumbers.Remove( phoneNumber );
                        phoneNumberService.Delete( phoneNumber );
                    }

                    History.EvaluateChange( changes, "Email", person.Email, tbEmail.Text );
                    person.Email = tbEmail.Text.Trim();

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

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

                            if ( orphanedPhotoId.HasValue )
                            {
                                BinaryFileService binaryFileService = new BinaryFileService( rockContext );
                                var binaryFile = binaryFileService.Get( orphanedPhotoId.Value );
                                if ( binaryFile != null )
                                {
                                    // marked the old images as IsTemporary so they will get cleaned up later
                                    binaryFile.IsTemporary = true;
                                    rockContext.SaveChanges();
                                }
                            }

                            // if they used the ImageEditor, and cropped it, the uncropped file is still in BinaryFile. So clean it up
                            if ( imgPhoto.CropBinaryFileId.HasValue )
                            {
                                if ( imgPhoto.CropBinaryFileId != person.PhotoId )
                                {
                                    BinaryFileService binaryFileService = new BinaryFileService( rockContext );
                                    var binaryFile = binaryFileService.Get( imgPhoto.CropBinaryFileId.Value );
                                    if ( binaryFile != null && binaryFile.IsTemporary )
                                    {
                                        string errorMessage;
                                        if ( binaryFileService.CanDelete( binaryFile, out errorMessage ) )
                                        {
                                            binaryFileService.Delete( binaryFile );
                                            rockContext.SaveChanges();
                                        }
                                    }
                                }
                            }
                        }

                        // save address
                        if ( pnlAddress.Visible )
                        {
                            Guid? familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuidOrNull();
                            if ( familyGroupTypeGuid.HasValue )
                            {
                                var familyGroup = new GroupService( rockContext ).Queryable()
                                                .Where( f => f.GroupType.Guid == familyGroupTypeGuid.Value
                                                    && f.Members.Any( m => m.PersonId == person.Id ) )
                                                .FirstOrDefault();
                                if ( familyGroup != null )
                                {
                                    Guid? addressTypeGuid = GetAttributeValue("LocationType").AsGuidOrNull();
                                    if ( addressTypeGuid.HasValue )
                                    {
                                        var groupLocationService = new GroupLocationService( rockContext );

                                        var dvHomeAddressType = DefinedValueCache.Read( addressTypeGuid.Value );
                                        var familyAddress = groupLocationService.Queryable().Where( l => l.GroupId == familyGroup.Id && l.GroupLocationTypeValueId == dvHomeAddressType.Id ).FirstOrDefault();
                                        if ( familyAddress != null && string.IsNullOrWhiteSpace( acAddress.Street1 ) )
                                        {
                                            // delete the current address
                                            History.EvaluateChange( changes, familyAddress.GroupLocationTypeValue.Value + " Location", familyAddress.Location.ToString(), string.Empty );
                                            groupLocationService.Delete( familyAddress );
                                            rockContext.SaveChanges();
                                        }
                                        else
                                        {
                                            if ( !string.IsNullOrWhiteSpace( acAddress.Street1 ) )
                                            {
                                                if ( familyAddress == null )
                                                {
                                                    familyAddress = new GroupLocation();
                                                    groupLocationService.Add( familyAddress );
                                                    familyAddress.GroupLocationTypeValueId = dvHomeAddressType.Id;
                                                    familyAddress.GroupId = familyGroup.Id;
                                                    familyAddress.IsMailingLocation = true;
                                                    familyAddress.IsMappedLocation = true;
                                                }
                                                else if ( hfStreet1.Value != string.Empty ) {

                                                    // user clicked move so create a previous address
                                                    var previousAddress = new GroupLocation();
                                                    groupLocationService.Add( previousAddress );

                                                    var previousAddressValue = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid() );
                                                    if ( previousAddressValue  != null )
                                                    {
                                                        previousAddress.GroupLocationTypeValueId = previousAddressValue.Id;
                                                        previousAddress.GroupId = familyGroup.Id;

                                                        Location previousAddressLocation = new Location();
                                                        previousAddressLocation.Street1 = hfStreet1.Value;
                                                        previousAddressLocation.Street2 = hfStreet2.Value;
                                                        previousAddressLocation.City = hfCity.Value;
                                                        previousAddressLocation.State = hfState.Value;
                                                        previousAddressLocation.PostalCode = hfPostalCode.Value;
                                                        previousAddressLocation.Country = hfCountry.Value;

                                                        previousAddress.Location = previousAddressLocation;
                                                    }
                                                }

                                                familyAddress.IsMailingLocation = cbIsMailingAddress.Checked;
                                                familyAddress.IsMappedLocation = cbIsPhysicalAddress.Checked;

                                                var updatedHomeAddress = new Location();
                                                acAddress.GetValues( updatedHomeAddress );

                                                History.EvaluateChange( changes, dvHomeAddressType.Value + " Location", familyAddress.Location != null ? familyAddress.Location.ToString() : string.Empty, updatedHomeAddress.ToString() );

                                                familyAddress.Location = updatedHomeAddress;
                                                rockContext.SaveChanges();
                                            }
                                        }

                                        HistoryService.SaveChanges(
                                            rockContext,
                                            typeof( Person ),
                                            Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                            person.Id,
                                            changes );
                                    }
                                }
                            }
                        }

                        NavigateToParentPage();
                    }
                }
            } );
        }
Пример #34
0
        /// <summary>
        /// Updates the last login and writes to the person's history log
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        public static void UpdateLastLogin(string userName)
        {
            if (!string.IsNullOrWhiteSpace(userName))
            {
                using (var rockContext = new RockContext())
                {
                    int? personId     = null;
                    bool impersonated = userName.StartsWith("rckipid=");

                    if (!impersonated)
                    {
                        var userLogin = new UserLoginService(rockContext).GetByUserName(userName);
                        if (userLogin != null)
                        {
                            userLogin.LastLoginDateTime = RockDateTime.Now;
                            personId = userLogin.PersonId;
                        }
                    }
                    else
                    {
                        var impersonationToken = userName.Substring(8);
                        personId = new PersonService(rockContext).GetByImpersonationToken(impersonationToken, false, null)?.Id;
                    }

                    if (personId.HasValue)
                    {
                        var relatedDataBuilder  = new System.Text.StringBuilder();
                        int?relatedEntityTypeId = null;
                        int?relatedEntityId     = null;

                        if (impersonated)
                        {
                            var impersonatedByUser = HttpContext.Current?.Session["ImpersonatedByUser"] as UserLogin;

                            relatedEntityTypeId = EntityTypeCache.GetId <Rock.Model.Person>();
                            relatedEntityId     = impersonatedByUser?.PersonId;

                            if (impersonatedByUser != null)
                            {
                                relatedDataBuilder.Append($" impersonated by { impersonatedByUser.Person.FullName }");
                            }
                        }

                        if (HttpContext.Current != null && HttpContext.Current.Request != null)
                        {
                            string cleanUrl = PersonToken.ObfuscateRockMagicToken(HttpContext.Current.Request.Url.AbsoluteUri);

                            // obfuscate the url specified in the returnurl, just in case it contains any sensitive information (like a rckipid)
                            Regex returnurlRegEx = new Regex(@"returnurl=([^&]*)");
                            cleanUrl = returnurlRegEx.Replace(cleanUrl, "returnurl=XXXXXXXXXXXXXXXXXXXXXXXXXXXX");

                            relatedDataBuilder.AppendFormat(" to <span class='field-value'>{0}</span>, from <span class='field-value'>{1}</span>",
                                                            cleanUrl, HttpContext.Current.Request.UserHostAddress);
                        }

                        var historyChangeList = new History.HistoryChangeList();
                        var historyChange     = historyChangeList.AddChange(History.HistoryVerb.Login, History.HistoryChangeType.Record, userName);

                        if (relatedDataBuilder.Length > 0)
                        {
                            historyChange.SetRelatedData(relatedDataBuilder.ToString(), null, null);
                        }

                        HistoryService.SaveChanges(rockContext, typeof(Rock.Model.Person), Rock.SystemGuid.Category.HISTORY_PERSON_ACTIVITY.AsGuid(), personId.Value, historyChangeList, true);
                    }
                }
            }
        }
Пример #35
0
        /// <summary>
        /// Creates and stores a new PersonToken for a person using the specified ExpireDateTime, UsageLimit, and Page
        /// Returns the encrypted URLEncoded Token which can be used as a rckipid
        /// </summary>
        /// <param name="personAlias">The person alias.</param>
        /// <param name="expireDateTime">The expire date time.</param>
        /// <param name="usageLimit">The usage limit.</param>
        /// <param name="pageId">The page identifier.</param>
        /// <returns></returns>
        public static string CreateNew(PersonAlias personAlias, DateTime?expireDateTime, int?usageLimit, int?pageId)
        {
            if (personAlias == null)
            {
                return(null);
            }

            using (var rockContext = new RockContext())
            {
                var person = personAlias.Person;
                if (person == null)
                {
                    person = new PersonService(rockContext).Get(personAlias.PersonId);
                }

                if (person == null)
                {
                    return(null);
                }
                // If a token is disallowed by security settings, return an error message.
                if (!person.IsPersonTokenUsageAllowed())
                {
                    return("TokenProhibited");
                }

                var token = Rock.Security.Encryption.GenerateUniqueToken();

                PersonToken personToken = new PersonToken();
                personToken.PersonAliasId = personAlias.Id;
                personToken.Token         = token;
                if (expireDateTime != null)
                {
                    personToken.ExpireDateTime = expireDateTime;
                }
                else
                {
                    int?tokenExpireMinutes = GlobalAttributesCache.Get().GetValue("core.PersonTokenExpireMinutes").AsIntegerOrNull();
                    if (tokenExpireMinutes.HasValue)
                    {
                        personToken.ExpireDateTime = RockDateTime.Now.AddMinutes(tokenExpireMinutes.Value);
                    }
                    else
                    {
                        personToken.ExpireDateTime = null;
                    }
                }

                personToken.TimesUsed  = 0;
                personToken.UsageLimit = usageLimit ?? GlobalAttributesCache.Get().GetValue("core.PersonTokenUsageLimit").AsIntegerOrNull();

                personToken.PageId = pageId;

                var personTokenService = new PersonTokenService(rockContext);
                personTokenService.Add(personToken);
                rockContext.SaveChanges(true);

                var encryptedToken = Rock.Security.Encryption.EncryptString(token);

                // do a Replace('%', '!') after we UrlEncode it (to make it more safely embeddable in HTML and cross browser compatible)
                return(System.Web.HttpUtility.UrlEncode(encryptedToken).Replace('%', '!'));
            }
        }
Пример #36
0
        /// <summary>
        /// Gets the chart data.
        /// </summary>
        /// <param name="groupBy">The group by.</param>
        /// <param name="graphBy">The graph by.</param>
        /// <param name="startDate">The start date.</param>
        /// <param name="endDate">The end date.</param>
        /// <param name="groupIds">The group ids.</param>
        /// <param name="campusIds">The campus ids. Include the keyword 'null' in the list to include CampusId is null</param>
        /// <param name="scheduleIds">The schedule ids.</param>
        /// <param name="dataViewId">The data view identifier.</param>
        /// <returns></returns>
        public IEnumerable <IChartData> GetChartData(ChartGroupBy groupBy = ChartGroupBy.Week, AttendanceGraphBy graphBy = AttendanceGraphBy.Total, DateTime?startDate = null, DateTime?endDate = null, string groupIds = null, string campusIds = null, int?dataViewId = null, string scheduleIds = null)
        {
            var qryAttendance = Queryable().AsNoTracking()
                                .Where(a =>
                                       a.DidAttend.HasValue &&
                                       a.DidAttend.Value &&
                                       a.PersonAlias != null);

            if (startDate.HasValue)
            {
                startDate     = startDate.Value.Date;
                qryAttendance = qryAttendance.Where(a => a.Occurrence.OccurrenceDate >= startDate.Value);
            }

            if (endDate.HasValue)
            {
                qryAttendance = qryAttendance.Where(a => a.Occurrence.OccurrenceDate < endDate.Value);
            }

            if (dataViewId.HasValue)
            {
                var rockContext = (RockContext)this.Context;

                var dataView = new DataViewService(rockContext).Get(dataViewId.Value);
                if (dataView != null)
                {
                    var personService = new PersonService(rockContext);

                    var errorMessages   = new List <string>();
                    var paramExpression = personService.ParameterExpression;
                    var whereExpression = dataView.GetExpression(personService, paramExpression, out errorMessages);

                    Rock.Web.UI.Controls.SortProperty sort = null;
                    var dataViewPersonIdQry = personService
                                              .Queryable().AsNoTracking()
                                              .Where(paramExpression, whereExpression, sort)
                                              .Select(p => p.Id);

                    qryAttendance = qryAttendance.Where(a => dataViewPersonIdQry.Contains(a.PersonAlias.PersonId));
                }
            }

            if (!string.IsNullOrWhiteSpace(groupIds))
            {
                var groupIdList = groupIds.Split(',').AsIntegerList();
                qryAttendance = qryAttendance
                                .Where(a =>
                                       a.Occurrence.GroupId.HasValue &&
                                       groupIdList.Contains(a.Occurrence.GroupId.Value));
            }

            // If campuses were included, filter attendances by those that have selected campuses
            // if 'null' is one of the campuses, treat that as a 'CampusId is Null'
            var includeNullCampus = (campusIds ?? "").Split(',').ToList().Any(a => a.Equals("null", StringComparison.OrdinalIgnoreCase));
            var campusIdList      = (campusIds ?? "").Split(',').AsIntegerList();

            // remove 0 from the list, just in case it is there
            campusIdList.Remove(0);

            if (campusIdList.Any())
            {
                if (includeNullCampus)
                {
                    // show records that have a campusId in the campusIdsList + records that have a null campusId
                    qryAttendance = qryAttendance.Where(a => (a.CampusId.HasValue && campusIdList.Contains(a.CampusId.Value)) || !a.CampusId.HasValue);
                }
                else
                {
                    // only show records that have a campusId in the campusIdList
                    qryAttendance = qryAttendance.Where(a => a.CampusId.HasValue && campusIdList.Contains(a.CampusId.Value));
                }
            }
            else if (includeNullCampus)
            {
                // 'null' was the only campusId in the campusIds parameter, so only show records that have a null CampusId
                qryAttendance = qryAttendance.Where(a => !a.CampusId.HasValue);
            }

            // If schedules were included, filter attendances by those that have selected schedules
            var scheduleIdList = (scheduleIds ?? "").Split(',').AsIntegerList();

            scheduleIdList.Remove(0);
            if (scheduleIdList.Any())
            {
                qryAttendance = qryAttendance.Where(a => a.Occurrence.ScheduleId.HasValue && scheduleIdList.Contains(a.Occurrence.ScheduleId.Value));
            }

            var qryAttendanceWithSummaryDateTime = qryAttendance.GetAttendanceWithSummaryDateTime(groupBy);

            var summaryQry = qryAttendanceWithSummaryDateTime.Select(a => new
            {
                a.SummaryDateTime,
                Campus = new
                {
                    Id   = a.Attendance.CampusId,
                    Name = a.Attendance.Campus.Name
                },
                Group = new
                {
                    Id   = a.Attendance.Occurrence.GroupId,
                    Name = a.Attendance.Occurrence.Group.Name
                },
                Schedule = new
                {
                    Id   = a.Attendance.Occurrence.ScheduleId,
                    Name = a.Attendance.Occurrence.Schedule.Name
                },
                Location = new
                {
                    Id   = a.Attendance.Occurrence.LocationId,
                    Name = a.Attendance.Occurrence.Location.Name
                }
            });

            List <SummaryData> result = null;

            if (graphBy == AttendanceGraphBy.Total)
            {
                var groupByQry = summaryQry.GroupBy(a => new { a.SummaryDateTime }).Select(s => new { s.Key, Count = s.Count() }).OrderBy(o => o.Key);

                result = groupByQry.ToList().Select(a => new SummaryData
                {
                    DateTimeStamp = a.Key.SummaryDateTime.ToJavascriptMilliseconds(),
                    DateTime      = a.Key.SummaryDateTime,
                    SeriesName    = "Total",
                    YValue        = a.Count
                }).ToList();
            }
            else if (graphBy == AttendanceGraphBy.Campus)
            {
                var groupByQry = summaryQry.GroupBy(a => new { a.SummaryDateTime, Series = a.Campus }).Select(s => new { s.Key, Count = s.Count() }).OrderBy(o => o.Key);

                result = groupByQry.ToList().Select(a => new SummaryData
                {
                    DateTimeStamp = a.Key.SummaryDateTime.ToJavascriptMilliseconds(),
                    DateTime      = a.Key.SummaryDateTime,
                    SeriesName    = a.Key.Series.Name,
                    YValue        = a.Count
                }).ToList();
            }
            else if (graphBy == AttendanceGraphBy.Group)
            {
                var groupByQry = summaryQry.GroupBy(a => new { a.SummaryDateTime, Series = a.Group }).Select(s => new { s.Key, Count = s.Count() }).OrderBy(o => o.Key);

                result = groupByQry.ToList().Select(a => new SummaryData
                {
                    DateTimeStamp = a.Key.SummaryDateTime.ToJavascriptMilliseconds(),
                    DateTime      = a.Key.SummaryDateTime,
                    SeriesName    = a.Key.Series.Name,
                    YValue        = a.Count
                }).ToList();
            }
            else if (graphBy == AttendanceGraphBy.Schedule)
            {
                var groupByQry = summaryQry.GroupBy(a => new { a.SummaryDateTime, Series = a.Schedule }).Select(s => new { s.Key, Count = s.Count() }).OrderBy(o => o.Key);

                result = groupByQry.ToList().Select(a => new SummaryData
                {
                    DateTimeStamp = a.Key.SummaryDateTime.ToJavascriptMilliseconds(),
                    DateTime      = a.Key.SummaryDateTime,
                    SeriesName    = a.Key.Series.Name,
                    YValue        = a.Count
                }).ToList();
            }
            else if (graphBy == AttendanceGraphBy.Location)
            {
                var groupByQry = summaryQry.GroupBy(a => new { a.SummaryDateTime, Series = a.Location }).Select(s => new { s.Key, Count = s.Count() }).OrderBy(o => o.Key);

                result = groupByQry.ToList().Select(a => new SummaryData
                {
                    DateTimeStamp = a.Key.SummaryDateTime.ToJavascriptMilliseconds(),
                    DateTime      = a.Key.SummaryDateTime,
                    SeriesName    = a.Key.Series.Name,
                    YValue        = a.Count
                }).ToList();
            }

            return(result);
        }
Пример #37
0
        /// <summary>
        /// Gets the group placement registrants.
        /// </summary>
        /// <param name="options">The options.</param>
        /// <param name="currentPerson">The current person.</param>
        /// <returns></returns>
        public List <GroupPlacementRegistrant> GetGroupPlacementRegistrants(GetGroupPlacementRegistrantsParameters options, Person currentPerson)
        {
            var rockContext = this.Context as RockContext;

            var registrationRegistrantService = new RegistrationRegistrantService(rockContext);
            var registrationRegistrantQuery   = registrationRegistrantService.Queryable();

            registrationRegistrantQuery = registrationRegistrantQuery
                                          .Where(a => a.Registration.RegistrationInstance.RegistrationTemplateId == options.RegistrationTemplateId);

            if (options.RegistrationInstanceId.HasValue)
            {
                registrationRegistrantQuery = registrationRegistrantQuery.Where(a => a.Registration.RegistrationInstanceId == options.RegistrationInstanceId.Value);
            }
            else if (options.RegistrationTemplateInstanceIds?.Any() == true)
            {
                registrationRegistrantQuery = registrationRegistrantQuery.Where(a => options.RegistrationTemplateInstanceIds.Contains(a.Registration.RegistrationInstanceId));
            }

            if (options.RegistrantPersonDataViewFilterId.HasValue)
            {
                var dataFilter      = new DataViewFilterService(rockContext).Get(options.RegistrantPersonDataViewFilterId.Value);
                var personService   = new PersonService(rockContext);
                var paramExpression = personService.ParameterExpression;

                var personWhereExpression = dataFilter?.GetExpression(typeof(Person), personService, paramExpression);
                if (personWhereExpression != null)
                {
                    var personIdQry = personService.Queryable().Where(paramExpression, personWhereExpression, null).Select(x => x.Id);
                    registrationRegistrantQuery = registrationRegistrantQuery.Where(a => personIdQry.Contains(a.PersonAlias.PersonId));
                }
            }

            if (options.RegistrantId.HasValue)
            {
                registrationRegistrantQuery = registrationRegistrantQuery.Where(a => a.Id == options.RegistrantId.Value);
            }

            Block registrationInstanceGroupPlacementBlock = new BlockService(rockContext).Get(options.BlockId);

            if (registrationInstanceGroupPlacementBlock != null && currentPerson != null)
            {
                const string RegistrantAttributeFilter_RegistrationInstanceId = "RegistrantAttributeFilter_RegistrationInstanceId_{0}";
                const string RegistrantAttributeFilter_RegistrationTemplateId = "RegistrantAttributeFilter_RegistrationTemplateId_{0}";
                string       userPreferenceKey;
                if (options.RegistrationInstanceId.HasValue)
                {
                    userPreferenceKey = PersonService.GetBlockUserPreferenceKeyPrefix(options.BlockId) + string.Format(RegistrantAttributeFilter_RegistrationInstanceId, options.RegistrationInstanceId);
                }
                else
                {
                    userPreferenceKey = PersonService.GetBlockUserPreferenceKeyPrefix(options.BlockId) + string.Format(RegistrantAttributeFilter_RegistrationTemplateId, options.RegistrationTemplateId);
                }

                var        attributeFilters          = PersonService.GetUserPreference(currentPerson, userPreferenceKey).FromJsonOrNull <Dictionary <int, string> >() ?? new Dictionary <int, string>();
                var        parameterExpression       = registrationRegistrantService.ParameterExpression;
                Expression registrantWhereExpression = null;
                foreach (var attributeFilter in attributeFilters)
                {
                    var attribute             = AttributeCache.Get(attributeFilter.Key);
                    var attributeFilterValues = attributeFilter.Value.FromJsonOrNull <List <string> >();
                    var entityField           = EntityHelper.GetEntityFieldForAttribute(attribute);
                    if (entityField != null && attributeFilterValues != null)
                    {
                        var attributeWhereExpression = ExpressionHelper.GetAttributeExpression(registrationRegistrantService, parameterExpression, entityField, attributeFilterValues);
                        if (registrantWhereExpression == null)
                        {
                            registrantWhereExpression = attributeWhereExpression;
                        }
                        else
                        {
                            registrantWhereExpression = Expression.AndAlso(registrantWhereExpression, attributeWhereExpression);
                        }
                    }
                }

                if (registrantWhereExpression != null)
                {
                    registrationRegistrantQuery = registrationRegistrantQuery.Where(parameterExpression, registrantWhereExpression);
                }
            }

            var registrationTemplatePlacement = new RegistrationTemplatePlacementService(rockContext).Get(options.RegistrationTemplatePlacementId);

            if (options.FilterFeeId.HasValue)
            {
                registrationRegistrantQuery = registrationRegistrantQuery.Where(a => a.Fees.Any(f => f.RegistrationTemplateFeeId == options.FilterFeeId.Value));
            }

            if (options.FilterFeeOptionIds?.Any() == true)
            {
                registrationRegistrantQuery = registrationRegistrantQuery.Where(a => a.Fees.Any(f => f.RegistrationTemplateFeeItemId.HasValue && options.FilterFeeOptionIds.Contains(f.RegistrationTemplateFeeItemId.Value)));
            }

            // don't include registrants that are on the waiting list
            registrationRegistrantQuery = registrationRegistrantQuery.Where(a => a.OnWaitList == false);

            registrationRegistrantQuery = registrationRegistrantQuery.OrderBy(a => a.PersonAlias.Person.LastName).ThenBy(a => a.PersonAlias.Person.NickName);

            var registrationTemplatePlacementService = new RegistrationTemplatePlacementService(rockContext);
            var registrationInstanceService          = new RegistrationInstanceService(rockContext);

            // get a queryable of PersonIds for the registration template shared groups so we can determine if the registrant has been placed
            var registrationTemplatePlacementGroupsPersonIdQuery = registrationTemplatePlacementService.GetRegistrationTemplatePlacementPlacementGroups(registrationTemplatePlacement).SelectMany(a => a.Members).Select(a => a.PersonId);

            // and also get a queryable of PersonIds for the registration instance placement groups so we can determine if the registrant has been placed
            IQueryable <InstancePlacementGroupPersonId> allInstancesPlacementGroupInfoQuery = null;

            if (!options.RegistrationInstanceId.HasValue && (options.RegistrationTemplateInstanceIds == null || !options.RegistrationTemplateInstanceIds.Any()))
            {
                // if neither RegistrationInstanceId or RegistrationTemplateInstanceIds was specified, use all of the RegistrationTemplates instances
                options.RegistrationTemplateInstanceIds = new RegistrationTemplateService(rockContext).GetSelect(options.RegistrationTemplateId, s => s.Instances.Select(i => i.Id)).ToArray();
            }

            if (options.RegistrationInstanceId.HasValue)
            {
                allInstancesPlacementGroupInfoQuery =
                    registrationInstanceService.GetRegistrationInstancePlacementGroups(registrationInstanceService.Get(options.RegistrationInstanceId.Value))
                    .Where(a => a.GroupTypeId == registrationTemplatePlacement.GroupTypeId)
                    .SelectMany(a => a.Members).Select(a => a.PersonId)
                    .Select(s => new InstancePlacementGroupPersonId
                {
                    PersonId = s,
                    RegistrationInstanceId = options.RegistrationInstanceId.Value
                });
            }
            else if (options.RegistrationTemplateInstanceIds?.Any() == true)
            {
                foreach (var registrationInstanceId in options.RegistrationTemplateInstanceIds)
                {
                    var instancePlacementGroupInfoQuery = registrationInstanceService.GetRegistrationInstancePlacementGroups(registrationInstanceService.Get(registrationInstanceId))
                                                          .Where(a => a.GroupTypeId == registrationTemplatePlacement.GroupTypeId)
                                                          .SelectMany(a => a.Members).Select(a => a.PersonId)
                                                          .Select(s => new InstancePlacementGroupPersonId
                    {
                        PersonId = s,
                        RegistrationInstanceId = registrationInstanceId
                    });

                    if (allInstancesPlacementGroupInfoQuery == null)
                    {
                        allInstancesPlacementGroupInfoQuery = instancePlacementGroupInfoQuery;
                    }
                    else
                    {
                        allInstancesPlacementGroupInfoQuery = allInstancesPlacementGroupInfoQuery.Union(instancePlacementGroupInfoQuery);
                    }
                }
            }

            if (allInstancesPlacementGroupInfoQuery == null)
            {
                throw new ArgumentNullException("Registration Instance(s) must be specified");
            }

            // select in a way to avoid lazy loading
            var registrationRegistrantPlacementQuery = registrationRegistrantQuery.Select(r => new
            {
                Registrant = r,
                r.PersonAlias.Person,
                r.Registration.RegistrationInstance,

                // marked as AlreadyPlacedInGroup if the Registrant is a member of any of the registrant template placement group or the registration instance placement groups
                AlreadyPlacedInGroup =
                    registrationTemplatePlacementGroupsPersonIdQuery.Contains(r.PersonAlias.PersonId) ||
                    allInstancesPlacementGroupInfoQuery.Any(x => x.RegistrationInstanceId == r.Registration.RegistrationInstanceId && x.PersonId == r.PersonAlias.PersonId)
            });

            var registrationRegistrantPlacementList = registrationRegistrantPlacementQuery.AsNoTracking().ToList();

            var groupPlacementRegistrantList = registrationRegistrantPlacementList
                                               .Select(x => new GroupPlacementRegistrant(x.Registrant, x.Person, x.AlreadyPlacedInGroup, x.RegistrationInstance, options))
                                               .ToList();

            return(groupPlacementRegistrantList.ToList());
        }
Пример #38
0
 public static Group SaveNewFamily(RockContext rockContext, Person person, int?campusId, bool savePersonAttributes)
 {
     return(PersonService.SaveNewPerson(person, rockContext, campusId, savePersonAttributes));
 }
Пример #39
0
        /// <summary>
        /// Saves the new family.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="familyMembers">The family members.</param>
        /// <param name="campusId">The campus identifier.</param>
        /// <param name="savePersonAttributes">if set to <c>true</c> [save person attributes].</param>
        /// <returns></returns>
        public static Group SaveNewFamily(RockContext rockContext, List <GroupMember> familyMembers, int?campusId, bool savePersonAttributes)
        {
            var familyGroupType = GroupTypeCache.GetFamilyGroupType();

            var familyChanges            = new List <string>();
            var familyMemberChanges      = new Dictionary <Guid, List <string> >();
            var familyDemographicChanges = new Dictionary <Guid, List <string> >();

            if (familyGroupType != null)
            {
                var groupService = new GroupService(rockContext);

                var familyGroup = new Group();

                familyGroup.GroupTypeId = familyGroupType.Id;

                familyGroup.Name = familyMembers.FirstOrDefault().Person.LastName + " Family";
                History.EvaluateChange(familyChanges, "Family", string.Empty, familyGroup.Name);

                if (campusId.HasValue)
                {
                    History.EvaluateChange(familyChanges, "Campus", string.Empty, CampusCache.Read(campusId.Value).Name);
                }
                familyGroup.CampusId = campusId;

                int?childRoleId = null;
                var childRole   = new GroupTypeRoleService(rockContext).Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD));
                if (childRole != null)
                {
                    childRoleId = childRole.Id;
                }

                foreach (var familyMember in familyMembers)
                {
                    var person = familyMember.Person;
                    if (person != null)
                    {
                        familyGroup.Members.Add(familyMember);

                        var demographicChanges = new List <string>();
                        demographicChanges.Add("Created");

                        History.EvaluateChange(demographicChanges, "Record Type", string.Empty, person.RecordTypeValueId.HasValue ? DefinedValueCache.GetName(person.RecordTypeValueId.Value) : string.Empty);
                        History.EvaluateChange(demographicChanges, "Record Status", string.Empty, person.RecordStatusValueId.HasValue ? DefinedValueCache.GetName(person.RecordStatusValueId.Value) : string.Empty);
                        History.EvaluateChange(demographicChanges, "Record Status Reason", string.Empty, person.RecordStatusReasonValueId.HasValue ? DefinedValueCache.GetName(person.RecordStatusReasonValueId.Value) : string.Empty);
                        History.EvaluateChange(demographicChanges, "Connection Status", string.Empty, person.ConnectionStatusValueId.HasValue ? DefinedValueCache.GetName(person.ConnectionStatusValueId) : string.Empty);
                        History.EvaluateChange(demographicChanges, "Deceased", false.ToString(), (person.IsDeceased).ToString());
                        History.EvaluateChange(demographicChanges, "Title", string.Empty, person.TitleValueId.HasValue ? DefinedValueCache.GetName(person.TitleValueId) : string.Empty);
                        History.EvaluateChange(demographicChanges, "First Name", string.Empty, person.FirstName);
                        History.EvaluateChange(demographicChanges, "Nick Name", string.Empty, person.NickName);
                        History.EvaluateChange(demographicChanges, "Middle Name", string.Empty, person.MiddleName);
                        History.EvaluateChange(demographicChanges, "Last Name", string.Empty, person.LastName);
                        History.EvaluateChange(demographicChanges, "Suffix", string.Empty, person.SuffixValueId.HasValue ? DefinedValueCache.GetName(person.SuffixValueId) : string.Empty);
                        History.EvaluateChange(demographicChanges, "Birth Date", null, person.BirthDate);
                        History.EvaluateChange(demographicChanges, "Gender", null, person.Gender);
                        History.EvaluateChange(demographicChanges, "Marital Status", string.Empty, person.MaritalStatusValueId.HasValue ? DefinedValueCache.GetName(person.MaritalStatusValueId) : string.Empty);
                        History.EvaluateChange(demographicChanges, "Anniversary Date", null, person.AnniversaryDate);
                        History.EvaluateChange(demographicChanges, "Graduation Year", null, person.GraduationYear);
                        History.EvaluateChange(demographicChanges, "Email", string.Empty, person.Email);
                        History.EvaluateChange(demographicChanges, "Email Active", false.ToString(), person.IsEmailActive.ToString());
                        History.EvaluateChange(demographicChanges, "Email Note", string.Empty, person.EmailNote);
                        History.EvaluateChange(demographicChanges, "Email Preference", null, person.EmailPreference);
                        History.EvaluateChange(demographicChanges, "Inactive Reason Note", string.Empty, person.InactiveReasonNote);
                        History.EvaluateChange(demographicChanges, "System Note", string.Empty, person.SystemNote);

                        familyDemographicChanges.Add(person.Guid, demographicChanges);

                        var memberChanges = new List <string>();

                        string roleName = familyGroupType.Roles
                                          .Where(r => r.Id == familyMember.GroupRoleId)
                                          .Select(r => r.Name)
                                          .FirstOrDefault();

                        History.EvaluateChange(memberChanges, "Role", string.Empty, roleName);
                        familyMemberChanges.Add(person.Guid, memberChanges);
                    }
                }

                groupService.Add(familyGroup);
                rockContext.SaveChanges();

                var personService = new PersonService(rockContext);

                foreach (var groupMember in familyMembers)
                {
                    var person = groupMember.Person;

                    if (savePersonAttributes)
                    {
                        var newValues = person.AttributeValues;

                        person.LoadAttributes();
                        foreach (var attributeCache in person.Attributes.Select(a => a.Value))
                        {
                            string oldValue = person.GetAttributeValue(attributeCache.Key) ?? string.Empty;
                            string newValue = string.Empty;
                            if (newValues != null &&
                                newValues.ContainsKey(attributeCache.Key) &&
                                newValues[attributeCache.Key] != null)
                            {
                                newValue = newValues[attributeCache.Key].Value ?? string.Empty;
                            }

                            if (!oldValue.Equals(newValue))
                            {
                                History.EvaluateChange(familyDemographicChanges[person.Guid], attributeCache.Name,
                                                       attributeCache.FieldType.Field.FormatValue(null, oldValue, attributeCache.QualifierValues, false),
                                                       attributeCache.FieldType.Field.FormatValue(null, newValue, attributeCache.QualifierValues, false));
                                Rock.Attribute.Helper.SaveAttributeValue(person, attributeCache, newValue);
                            }
                        }
                    }

                    person = personService.Get(groupMember.PersonId);
                    if (person != null)
                    {
                        bool updateRequired = false;
                        var  changes        = familyDemographicChanges[person.Guid];
                        if (groupMember.GroupRoleId != childRoleId)
                        {
                            person.GivingGroupId = familyGroup.Id;
                            updateRequired       = true;
                            History.EvaluateChange(changes, "Giving Group", string.Empty, familyGroup.Name);
                        }

                        if (updateRequired)
                        {
                            rockContext.SaveChanges();
                        }

                        HistoryService.SaveChanges(rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                                   person.Id, changes);

                        HistoryService.SaveChanges(rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                                                   person.Id, familyMemberChanges[person.Guid], familyGroup.Name, typeof(Group), familyGroup.Id);

                        HistoryService.SaveChanges(rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                                                   person.Id, familyChanges, familyGroup.Name, typeof(Group), familyGroup.Id);
                    }
                }

                return(familyGroup);
            }

            return(null);
        }
        /// <summary>
        /// Gets financial transaction details based on selected filter values.
        /// </summary>
        /// <param name="start">The start.</param>
        /// <param name="end">The end.</param>
        /// <param name="minAmount">The minimum amount.</param>
        /// <param name="maxAmount">The maximum amount.</param>
        /// <param name="currencyTypeIds">The currency type ids.</param>
        /// <param name="sourceTypeIds">The source type ids.</param>
        /// <param name="accountIds">The account ids.</param>
        /// <param name="dataViewId">The data view identifier.</param>
        /// <returns></returns>
        public IQueryable <FinancialTransactionDetail> GetGifts(
            DateTime?start, DateTime?end, decimal?minAmount, decimal?maxAmount,
            List <int> currencyTypeIds, List <int> sourceTypeIds, List <int> accountIds, int?dataViewId)
        {
            // Base Transaction Detail query
            var qry = GetGifts();

            // Start Date Filter
            if (start.HasValue)
            {
                qry = qry.Where(t => t.Transaction.TransactionDateTime >= start.Value);
            }

            // End Date Filter
            if (end.HasValue)
            {
                qry = qry.Where(t => t.Transaction.TransactionDateTime < end.Value);
            }

            // Account Id Filter
            var distictAccountIds = accountIds.Where(i => i != 0).Distinct().ToList();

            if (distictAccountIds.Any())
            {
                qry = qry
                      .Where(t =>
                             distictAccountIds.Contains(t.AccountId));
            }


            // Currency Type Filter
            var distictCurrencyTypeIds = currencyTypeIds.Where(i => i != 0).Distinct().ToList();

            if (distictCurrencyTypeIds.Any())
            {
                qry = qry
                      .Where(t =>
                             t.Transaction.FinancialPaymentDetail != null &&
                             t.Transaction.FinancialPaymentDetail.CurrencyTypeValueId.HasValue &&
                             distictCurrencyTypeIds.Contains(t.Transaction.FinancialPaymentDetail.CurrencyTypeValueId.Value));
            }

            // Source Type Filter
            var distictSourceTypeIds = sourceTypeIds.Where(i => i != 0).Distinct().ToList();

            if (distictSourceTypeIds.Any())
            {
                qry = qry
                      .Where(t =>
                             t.Transaction.SourceTypeValueId.HasValue &&
                             distictSourceTypeIds.Contains(t.Transaction.SourceTypeValueId.Value));
            }

            // Amount Range Filter
            if (minAmount.HasValue || maxAmount.HasValue)
            {
                var givingIdQry = qry
                                  .GroupBy(d => d.Transaction.AuthorizedPersonAlias.Person.GivingId)
                                  .Select(d => new { d.Key, Total = d.Sum(t => t.Amount) })
                                  .Where(s =>
                                         (!minAmount.HasValue || s.Total >= minAmount.Value) &&
                                         (!maxAmount.HasValue || s.Total <= maxAmount.Value))
                                  .Select(s => s.Key);

                // put all the givingIds into a List instead of a subquery to prevent a timeout issue
                var givingIdList = givingIdQry.ToList();

                qry = qry
                      .Where(d =>
                             givingIdList.Contains(d.Transaction.AuthorizedPersonAlias.Person.GivingId));
            }

            // Data View Filter
            if (dataViewId.HasValue)
            {
                var rockContext = (RockContext)this.Context;
                if (rockContext != null)
                {
                    var personService = new PersonService(rockContext);
                    var dataView      = new DataViewService(rockContext).Get(dataViewId.Value);
                    if (dataView != null)
                    {
                        var errorMessages = new List <string>();
                        ParameterExpression paramExpression = personService.ParameterExpression;
                        Expression          whereExpression = dataView.GetExpression(personService, paramExpression, out errorMessages);

                        SortProperty sortProperty        = null;
                        var          dataViewGivingIdQry = personService
                                                           .Queryable().AsNoTracking()
                                                           .Where(paramExpression, whereExpression, sortProperty)
                                                           .Select(p => p.GivingId);

                        qry = qry
                              .Where(t =>
                                     dataViewGivingIdQry.Contains(t.Transaction.AuthorizedPersonAlias.Person.GivingId));
                    }
                }
            }

            return(qry);
        }