Exemple #1
0
        /// <summary>
        /// Apply a set of common query filters to the query of people objects.
        /// </summary>
        /// <param name="people">The base query object.</param>
        /// <param name="rockContext">The context the base query object was constructed in.</param>
        private IQueryable <Person> ApplyCommonQueryFilters(IQueryable <Person> people, RockContext rockContext)
        {
            //
            // Filter the results by the dataview selected.
            //
            if (!string.IsNullOrEmpty(GetAttributeValue("FilterResults")))
            {
                var           personService       = new PersonService(rockContext);
                DataView      filterSource        = new DataViewService(rockContext).Get(GetAttributeValue("FilterResults").AsGuid());
                List <string> errorMessages       = new List <string>();
                var           parameterExpression = personService.ParameterExpression;

                var whereExpression = filterSource.GetExpression(personService, parameterExpression, out errorMessages);
                var sourceItems     = personService.Get(parameterExpression, whereExpression).Select(q => q.Id);

                people = people.Where(p => sourceItems.Contains(p.Id));
            }

            //
            // Order and limit the results.
            //
            people = people.OrderBy(p => p.LastName).ThenBy(p => p.FirstName).Take(100);

            return(people);
        }
Exemple #2
0
        /// <summary>
        /// Gets the expression.
        /// </summary>
        /// <param name="entityType"></param>
        /// <param name="serviceInstance">The service instance.</param>
        /// <param name="parameterExpression">The parameter expression.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception">Filter issue(s):  + errorMessages.AsDelimited( ;  )</exception>
        public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection)
        {
            int dataviewId = int.MinValue;

            if (int.TryParse(selection, out dataviewId))
            {
                var dataView = new DataViewService((RockContext)serviceInstance.Context).Get(dataviewId);
                if (dataView != null && dataView.DataViewFilter != null)
                {
                    // Verify that there is not a child filter that uses this view (would result in stack-overflow error)
                    if (!IsViewInFilter(dataView.Id, dataView.DataViewFilter))
                    {
                        // TODO: Should probably verify security again on the selected dataview and it's filters,
                        // as that could be a moving target.
                        var        errorMessages = new List <string>();
                        Expression expression    = dataView.GetExpression(serviceInstance, parameterExpression, out errorMessages);
                        if (errorMessages.Any())
                        {
                            throw new System.Exception("Filter issue(s): " + errorMessages.AsDelimited("; "));
                        }

                        return(expression);
                    }
                }
            }

            return(null);
        }
        /// <summary>
        /// Display a message that shows the number of people who will receive the notification.
        /// </summary>
        /// <param name="count">The number of people to notify.</param>
        protected void UpdateCount()
        {
            int?count = null;

            if (rblSource.SelectedValue == "Manual Selection")
            {
                if (!string.IsNullOrWhiteSpace(PersonList))
                {
                    var people = PersonList.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                    count = people.Count;
                }
            }
            else if (rblSource.SelectedValue == "Group")
            {
                int?groupId = gpGroup.SelectedValueAsId();

                var group = new GroupService(new RockContext()).Get(groupId ?? 0);
                if (groupId.HasValue)
                {
                    count = new GroupMemberService(new RockContext()).Queryable()
                            .Where(m => m.GroupId == groupId.Value && m.GroupMemberStatus == GroupMemberStatus.Active)
                            .Count();
                }
            }
            else if (rblSource.SelectedValue == "Data View")
            {
                int?dataviewId = dvDataView.SelectedValueAsId();

                if (dataviewId.HasValue)
                {
                    using (var rockContext = new RockContext())
                    {
                        var           personService       = new PersonService(rockContext);
                        var           parameterExpression = personService.ParameterExpression;
                        var           dv = new DataViewService(rockContext).Get(dataviewId.Value);
                        List <string> errorMessages;
                        var           whereExpression = dv.GetExpression(personService, parameterExpression, out errorMessages);

                        count = new PersonService(rockContext)
                                .Get(parameterExpression, whereExpression)
                                .Count();
                    }
                }
            }

            if (count.HasValue)
            {
                nbCount.Text = string.Format("Notification will be posted to {0} {1}.", count.Value, "person".PluralizeIf(count != 1));
            }
            else
            {
                nbCount.Text = string.Empty;
            }

            lbSave.Enabled = (count ?? 0) > 0;
        }
        public IQueryable <T> GetDataView(int id)
        {
            var rockContext = new RockContext();
            var dataView    = new DataViewService(rockContext).Get(id);

            ValidateDataView(dataView);

            var paramExpression = Service.ParameterExpression;
            var whereExpression = dataView.GetExpression(Service, paramExpression);

            return(Service.GetNoTracking(paramExpression, whereExpression));
        }
Exemple #5
0
        /// <summary>
        /// Gets the data view expression.
        /// </summary>
        /// <param name="dataViewId">The data view identifier.</param>
        /// <param name="service">The service.</param>
        /// <param name="parmExpression">The parm expression.</param>
        /// <param name="entityTypeCache">The entity type cache.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        private Expression GetDataViewExpression(int dataViewId, IService service, ParameterExpression parmExpression, EntityTypeCache entityTypeCache)
        {
            var  dataViewSource    = new DataViewService(_rockContext).Get(dataViewId);
            bool isCorrectDataType = dataViewSource.EntityTypeId == entityTypeCache.Id;

            if (isCorrectDataType)
            {
                List <string> errorMessages   = new List <string>();
                var           whereExpression = dataViewSource.GetExpression(service, parmExpression, out errorMessages);
                return(whereExpression);
            }
            else
            {
                throw new Exception(string.Format("The DataView provided is not of type {0}.", entityTypeCache.FriendlyName));
            }
        }
Exemple #6
0
        public IQueryable <T> GetDataView(int id)
        {
            var dataView = new DataViewService().Get(id);

            if (dataView != null && dataView.EntityType.Name == typeof(T).FullName)
            {
                var errorMessages = new List <string>();

                var paramExpression = _service.ParameterExpression;
                var whereExpression = dataView.GetExpression(_service, paramExpression, out errorMessages);

                if (paramExpression != null && whereExpression != null)
                {
                    return(_service.Get(paramExpression, whereExpression));
                }
            }

            return(null);
        }
Exemple #7
0
        /// <summary>
        /// Gets the data view expression.
        /// </summary>
        /// <param name="dataViewId">The data view identifier.</param>
        /// <param name="service">The service.</param>
        /// <param name="parmExpression">The parm expression.</param>
        /// <param name="entityTypeCache">The entity type cache.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        private Expression GetDataViewExpression(int dataViewId, IService service, ParameterExpression parmExpression, EntityTypeCache entityTypeCache)
        {
            if (service.Context is RockContext)
            {
                var  dataViewSource    = new DataViewService(service.Context as RockContext).Get(dataViewId);
                bool isCorrectDataType = dataViewSource.EntityTypeId == entityTypeCache.Id;

                if (isCorrectDataType)
                {
                    var whereExpression = dataViewSource.GetExpression(service, parmExpression);
                    return(whereExpression);
                }
                else
                {
                    throw new Exception(string.Format("The DataView provided is not of type {0}.", entityTypeCache.FriendlyName));
                }
            }
            else
            {
                throw new Exception(string.Format("The database context for type {0} does not support RockContext dataviews.", entityTypeCache.FriendlyName));
            }
        }
        public IQueryable <T> GetDataView(int id)
        {
            var dataView = new DataViewService(new RockContext()).Get(id);

            CheckCanEdit(dataView);
            SetProxyCreation(false);

            if (dataView != null && dataView.EntityType.Name == typeof(T).FullName)
            {
                var errorMessages = new List <string>();

                var paramExpression = Service.ParameterExpression;
                var whereExpression = dataView.GetExpression(Service, paramExpression, out errorMessages);

                if (paramExpression != null)
                {
                    return(Service.Get(paramExpression, whereExpression));
                }
            }

            return(null);
        }
Exemple #9
0
        public IQueryable <T> GetDataView(int id)
        {
            var dataView = new DataViewService(new RockContext()).Get(id);

            // since DataViews can be secured at the Dataview or Category level, specifically check for CanView
            CheckCanView(dataView, GetPerson());

            SetProxyCreation(false);

            if (dataView != null && dataView.EntityType.Name == typeof(T).FullName)
            {
                var errorMessages = new List <string>();

                var paramExpression = Service.ParameterExpression;
                var whereExpression = dataView.GetExpression(Service, paramExpression, out errorMessages);

                if (paramExpression != null)
                {
                    return(Service.Get(paramExpression, whereExpression));
                }
            }

            return(null);
        }
Exemple #10
0
        /// <summary>
        /// Binds the attendees grid.
        /// </summary>
        private void BindGiversGrid()
        {
            // Get all the selected criteria values
            var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(drpSlidingDateRange.DelimitedValues);
            var start     = dateRange.Start;
            var end       = dateRange.End;

            var minAmount = nreAmount.LowerValue;
            var maxAmount = nreAmount.UpperValue;

            var currencyTypeIds = new List <int>();

            cblCurrencyTypes.SelectedValues.ForEach(i => currencyTypeIds.Add(i.AsInteger()));

            var sourceTypeIds = new List <int>();

            cblTransactionSource.SelectedValues.ForEach(i => sourceTypeIds.Add(i.AsInteger()));

            var accountIds = new List <int>();

            foreach (var cblAccounts in phAccounts.Controls.OfType <RockCheckBoxList>())
            {
                accountIds.AddRange(cblAccounts.SelectedValuesAsInt);
            }

            var dataViewId = dvpDataView.SelectedValueAsInt();

            GiversViewBy viewBy = GiversViewBy.Giver;

            if (!HideViewByOption)
            {
                viewBy = hfViewBy.Value.ConvertToEnumOrNull <GiversViewBy>() ?? GiversViewBy.Giver;
            }

            // Clear all the existing grid columns
            var selectField    = new SelectField();
            var oldSelectField = gGiversGifts.ColumnsOfType <SelectField>().FirstOrDefault();

            if (oldSelectField != null)
            {
                selectField.SelectedKeys.AddRange(oldSelectField.SelectedKeys);
            }

            gGiversGifts.Columns.Clear();

            // Add a column for selecting rows
            gGiversGifts.Columns.Add(selectField);

            // Add a column for the person's name
            gGiversGifts.Columns.Add(
                new RockBoundField
            {
                DataField      = "PersonName",
                HeaderText     = "Person",
                SortExpression = "LastName,NickName"
            });

            // add a column for email (but is only included on excel export)
            gGiversGifts.Columns.Add(
                new RockBoundField
            {
                DataField           = "Email",
                HeaderText          = "Email",
                SortExpression      = "Email",
                Visible             = false,
                ExcelExportBehavior = ExcelExportBehavior.AlwaysInclude
            });

            // Add a column for total amount
            gGiversGifts.Columns.Add(
                new CurrencyField
            {
                DataField      = "TotalAmount",
                HeaderText     = "Total",
                SortExpression = "TotalAmount"
            });


            // Add columns for the selected account totals
            if (accountIds.Any())
            {
                var accounts = new FinancialAccountService(_rockContext)
                               .Queryable().AsNoTracking()
                               .Where(a => accountIds.Contains(a.Id))
                               .ToList();

                foreach (int accountId in accountIds)
                {
                    var account = accounts.FirstOrDefault(a => a.Id == accountId);
                    if (account != null)
                    {
                        gGiversGifts.Columns.Add(
                            new CurrencyField
                        {
                            DataField      = account.Id.ToString(),
                            HeaderText     = account.Name,
                            SortExpression = account.Id.ToString()
                        });
                    }
                }
            }

            // Add a column for the number of gifts
            var numberGiftsField = new RockBoundField
            {
                DataField        = "NumberGifts",
                HeaderText       = "Number of Gifts",
                SortExpression   = "NumberGifts",
                DataFormatString = "{0:N0}",
            };

            numberGiftsField.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
            gGiversGifts.Columns.Add(numberGiftsField);

            // Add a column to indicate if this is a first time giver
            gGiversGifts.Columns.Add(
                new BoolField
            {
                DataField      = "IsFirstEverGift",
                HeaderText     = "Is First Gift",
                SortExpression = "IsFirstEverGift"
            });

            // Add a column for the first gift date ( that matches criteria )
            gGiversGifts.Columns.Add(
                new DateField
            {
                DataField      = "FirstGift",
                HeaderText     = "First Gift",
                SortExpression = "FirstGift"
            });

            // Add a column for the first-ever gift date ( to any tax-deductible account )
            gGiversGifts.Columns.Add(
                new DateField
            {
                DataField      = "FirstEverGift",
                HeaderText     = "First Gift Ever",
                SortExpression = "FirstEverGift"
            });


            var transactionDetailService = new FinancialTransactionDetailService(_rockContext);
            var personService            = new PersonService(_rockContext);

            // If dataview was selected get the person id's returned by the dataview
            var dataViewPersonIds = new List <int>();

            if (dataViewId.HasValue)
            {
                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          dataViewPersonIdQry = personService
                                                       .Queryable().AsNoTracking()
                                                       .Where(paramExpression, whereExpression, sortProperty)
                                                       .Select(p => p.Id);
                    dataViewPersonIds = dataViewPersonIdQry.ToList();
                }
            }

            // Check to see if grid should display only people who gave a certain number of times and if so
            // set the min value
            int minCount          = 0;
            var previousPersonIds = new List <int>();

            if (radByPattern.Checked)
            {
                minCount = tbPatternXTimes.Text.AsInteger();
                var missedStart = drpPatternDateRange.LowerValue;
                var missedEnd   = drpPatternDateRange.UpperValue;
                if (missedStart.HasValue && missedEnd.HasValue)
                {
                    // Get the givingids that gave any amount during the pattern's date range. These
                    // are needed so that we know who to exclude from the result set
                    var previousGivingIds = transactionDetailService
                                            .Queryable().AsNoTracking()
                                            .Where(d =>
                                                   d.Transaction.TransactionDateTime.HasValue &&
                                                   d.Transaction.TransactionDateTime.Value >= missedStart.Value &&
                                                   d.Transaction.TransactionDateTime.Value < missedEnd.Value &&
                                                   accountIds.Contains(d.AccountId) &&
                                                   d.Amount != 0.0M)
                                            .Select(d => d.Transaction.AuthorizedPersonAlias.Person.GivingId);

                    // Now get the person ids from the givingids
                    previousPersonIds = personService
                                        .Queryable().AsNoTracking()
                                        .Where(p => previousGivingIds.Contains(p.GivingId))
                                        .Select(p => p.Id)
                                        .ToList();
                }
            }

            // Call the stored procedure to get all the giving data that matches the selected criteria.
            // The stored procedure returns two tables. First is a list of all matching transaction summary
            // information and the second table is each giving leader's first-ever gift date to a tax-deductible account
            DataSet ds = FinancialTransactionDetailService.GetGivingAnalytics(start, end, minAmount, maxAmount,
                                                                              accountIds, currencyTypeIds, sourceTypeIds, dataViewId, viewBy);

            // Get the results table
            DataTable dtResults = ds.Tables[0];

            // Get the first-ever gift dates and load them into a dictionary for faster matching
            DataTable dtFirstEver   = ds.Tables[1];
            var       firstEverVals = new Dictionary <int, DateTime>();

            foreach (DataRow row in ds.Tables[1].Rows)
            {
                if (!DBNull.Value.Equals(row["FirstEverGift"]))
                {
                    firstEverVals.Add((int)row["PersonId"], (DateTime)row["FirstEverGift"]);
                }
            }

            // Add columns to the result set for the first-ever data
            dtResults.Columns.Add(new DataColumn("IsFirstEverGift", typeof(bool)));
            dtResults.Columns.Add(new DataColumn("FirstEverGift", typeof(DateTime)));

            foreach (DataRow row in dtResults.Rows)
            {
                bool rowValid = true;

                // Get the person id
                int personId = (int)row["Id"];

                if (radByPattern.Checked)
                {
                    // If pattern was specified check minimum gifts and other date range
                    int numberGifts = (int)row["NumberGifts"];
                    if (numberGifts < minCount)
                    {
                        rowValid = false;
                    }
                    else
                    {
                        // If this giving leader gave during the pattern date, remove the row since we
                        // only want those who did not
                        if (previousPersonIds.Contains(personId))
                        {
                            rowValid = false;
                        }
                    }
                }

                if (dataViewId.HasValue)
                {
                    // If a dataview filter was specified, and this row is not part of dataview,
                    // remove it
                    if (!dataViewPersonIds.Contains(personId))
                    {
                        rowValid = false;

                        // Remove person id from list so that list can be used later to optionally
                        // add rows for remaining people who were in the dataview, but not in the
                        // result set
                        dataViewPersonIds.Remove(personId);
                    }
                }

                if (rowValid)
                {
                    // Set the first ever information for each row
                    bool     isFirstEverGift = false;
                    DateTime firstGift       = (DateTime)row["FirstGift"];
                    if (firstEverVals.ContainsKey(personId))
                    {
                        DateTime firstEverGift = firstEverVals[personId];
                        isFirstEverGift = firstEverGift.Equals(firstGift);

                        row["FirstEverGift"] = firstEverGift;
                    }

                    // If only first time givers should be included, remove any that are not
                    if (radFirstTime.Checked && !isFirstEverGift)
                    {
                        rowValid = false;
                    }
                    else
                    {
                        row["IsFirstEverGift"] = isFirstEverGift;
                    }
                }

                if (!rowValid)
                {
                    row.Delete();
                }
            }

            // if dataview was selected and it includes people not in the result set,
            if (dataViewId.HasValue && rblDataViewAction.SelectedValue == "All" && dataViewPersonIds.Any())
            {
                // Query for the names of each of these people
                foreach (var person in personService
                         .Queryable().AsNoTracking()
                         .Select(p => new {
                    p.Id,
                    p.Guid,
                    p.NickName,
                    p.LastName,
                    p.Email
                }))
                {
                    // Check for a first ever gift date
                    var firstEverGiftDate = firstEverVals
                                            .Where(f => f.Key == person.Id)
                                            .Select(f => f.Value)
                                            .FirstOrDefault();

                    DataRow row = dtResults.NewRow();
                    row["Id"]              = person.Id;
                    row["Guid"]            = person.Guid;
                    row["NickName"]        = person.NickName;
                    row["LastName"]        = person.LastName;
                    row["PersonName"]      = person.NickName + " " + person.LastName;
                    row["Email"]           = person.Email;
                    row["IsFirstEverGift"] = false;
                    row["FirstEverGift"]   = firstEverGiftDate;
                    dtResults.Rows.Add(row);
                }
            }

            // Update the changes (deletes) in the datatable
            dtResults.AcceptChanges();

            // Calculate Total
            if (viewBy == GiversViewBy.Giver)
            {
                pnlTotal.Visible = true;
                object amountTotalObj = dtResults.Compute("Sum(TotalAmount)", null);
                if (amountTotalObj != null)
                {
                    decimal amountTotal = amountTotalObj.ToString().AsDecimal();
                    lTotal.Text = amountTotal.FormatAsCurrency();
                }
                else
                {
                    lTotal.Text = string.Empty;
                }
            }
            else
            {
                pnlTotal.Visible = false;
            }

            // Sort the results
            System.Data.DataView dv = dtResults.DefaultView;
            if (gGiversGifts.SortProperty != null)
            {
                try
                {
                    var sortProperties = new List <string>();
                    foreach (string prop in gGiversGifts.SortProperty.Property.SplitDelimitedValues(false))
                    {
                        sortProperties.Add(string.Format("[{0}] {1}", prop, gGiversGifts.SortProperty.DirectionString));
                    }
                    dv.Sort = sortProperties.AsDelimited(", ");
                }
                catch
                {
                    dv.Sort = "[LastName] ASC, [NickName] ASC";
                }
            }
            else
            {
                dv.Sort = "[LastName] ASC, [NickName] ASC";
            }

            gGiversGifts.DataSource = dv;
            gGiversGifts.DataBind();
        }
        private void BindData()
        {
            using (var rockContext = new RockContext())
            {
                var dataView = new DataViewService(rockContext).Get(_dataViewGuid ?? Guid.Empty);
                if (dataView != null)
                {
                    var personService = new PersonService(rockContext);

                    // Filter people by dataview
                    var errorMessages   = new List <string>();
                    var paramExpression = personService.ParameterExpression;
                    var whereExpression = dataView.GetExpression(personService, paramExpression, out errorMessages);
                    var personQry       = personService
                                          .Queryable(false, false).AsNoTracking()
                                          .Where(paramExpression, whereExpression, null);

                    var dvPersonIdQry = personQry.Select(p => p.Id);

                    bool filteredQry = false;

                    // Filter by first name
                    string firstName = tbFirstName.Text.Trim();
                    if (!string.IsNullOrWhiteSpace(firstName))
                    {
                        personQry = personQry.Where(p =>
                                                    p.FirstName.StartsWith(firstName) ||
                                                    p.NickName.StartsWith(firstName));
                        filteredQry = true;
                    }

                    // Filter by last name
                    string lastName = tbLastName.Text.Trim();
                    if (!string.IsNullOrWhiteSpace(lastName))
                    {
                        personQry = personQry.Where(p =>
                                                    p.LastName.StartsWith(lastName));
                        filteredQry = true;
                    }


                    if (filteredQry || _showAllPeople)
                    {
                        if (_optOutGroupGuid.HasValue)
                        {
                            var optOutPersonIdQry = new GroupMemberService(rockContext)
                                                    .Queryable().AsNoTracking()
                                                    .Where(g => g.Group.Guid.Equals(_optOutGroupGuid.Value))
                                                    .Select(g => g.PersonId);

                            personQry = personQry.Where(p =>
                                                        !optOutPersonIdQry.Contains(p.Id));
                        }

                        if (_showFamily)
                        {
                            BindFamilies(rockContext, personQry, dvPersonIdQry);
                        }
                        else
                        {
                            BindPeople(rockContext, personQry);
                        }
                    }
                    else
                    {
                        rptPeople.Visible   = false;
                        rptFamilies.Visible = false;
                    }
                }
                else
                {
                    rptPeople.Visible   = false;
                    rptFamilies.Visible = false;
                    ShowMessages(new List <string> {
                        "This block requires a valid Data View setting."
                    });
                }

                if (CurrentPerson != null && _optOutGroupGuid.HasValue)
                {
                    bool optedOut = new GroupMemberService(rockContext)
                                    .Queryable().AsNoTracking()
                                    .Any(m =>
                                         m.PersonId == CurrentPerson.Id &&
                                         m.Group.Guid.Equals(_optOutGroupGuid.Value));
                    lbOptInOut.Text = optedOut ? "Opt in to the Directory" : "Opt Out of the Directory";
                }
            }
        }
Exemple #12
0
        private List <object> GetMergeObjectList(RockContext rockContext)
        {
            List <GroupMember> records = new List <GroupMember>();

            if (rblSource.SelectedValue == "Group")
            {
                int groupId = gpGroup.SelectedValueAsId().Value;

                var groupIds = new GroupService(rockContext).GetAllDescendents(groupId)
                               .Select(g => g.Id)
                               .ToList();
                groupIds.Add(groupId);

                records = new GroupMemberService(new RockContext()).Queryable()
                          .Where(m => groupIds.Contains(m.GroupId) && m.GroupMemberStatus == GroupMemberStatus.Active)
                          .ToList();
            }
            else if (rblSource.SelectedValue == "Data View")
            {
                int dataviewId = dvDataView.SelectedValueAsId().Value;

                var           groupService        = new GroupService(rockContext);
                var           parameterExpression = groupService.ParameterExpression;
                var           dv = new DataViewService(rockContext).Get(dataviewId);
                List <string> errorMessages;
                var           whereExpression = dv.GetExpression(groupService, parameterExpression, out errorMessages);

                records = groupService
                          .Get(parameterExpression, whereExpression)
                          .SelectMany(g => g.Members)
                          .Where(m => m.GroupMemberStatus == GroupMemberStatus.Active)
                          .ToList();
            }

            switch (rblSortBy.SelectedValue)
            {
            case "Group":
                records = records.OrderBy(m => m.Group.Name)
                          .ThenBy(m => m.Person.FirstName)
                          .ThenBy(m => m.Person.LastName)
                          .ToList();
                break;

            case "Last":
                records = records.OrderBy(m => m.Person.LastName)
                          .ThenBy(m => m.Person.FirstName)
                          .ThenBy(m => m.Group.Name)
                          .ToList();
                break;

            case "First":
            default:
                records = records.OrderBy(m => m.Person.FirstName)
                          .ThenBy(m => m.Person.LastName)
                          .ThenBy(m => m.Group.Name)
                          .ToList();
                break;
            }

            return(records.Cast <object>().ToList());
        }
        /// <summary>
        /// Handles the Click event of the lbSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbSave_Click(object sender, EventArgs e)
        {
            List <int> personAliasIds = null;

            if (rblSource.SelectedValue == "Manual Selection")
            {
                personAliasIds = PersonList.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries)
                                 .Select(p => p.Split('^')[0].AsInteger())
                                 .ToList();
            }
            else if (rblSource.SelectedValue == "Group")
            {
                int?groupId = gpGroup.SelectedValueAsId();

                var group = new GroupService(new RockContext()).Get(groupId ?? 0);
                if (groupId.HasValue)
                {
                    personAliasIds = new GroupMemberService(new RockContext()).Queryable()
                                     .Where(m => m.GroupId == groupId.Value && m.GroupMemberStatus == GroupMemberStatus.Active)
                                     .Select(m => m.Person)
                                     .ToList()
                                     .Select(p => p.PrimaryAliasId.Value)
                                     .ToList();
                }
            }
            else if (rblSource.SelectedValue == "Data View")
            {
                int?dataviewId = dvDataView.SelectedValueAsId();

                if (dataviewId.HasValue)
                {
                    using (var rockContext = new RockContext())
                    {
                        var           personService       = new PersonService(rockContext);
                        var           parameterExpression = personService.ParameterExpression;
                        var           dv = new DataViewService(rockContext).Get(dataviewId.Value);
                        List <string> errorMessages;
                        var           whereExpression = dv.GetExpression(personService, parameterExpression, out errorMessages);

                        personAliasIds = new PersonService(rockContext)
                                         .Get(parameterExpression, whereExpression)
                                         .ToList()
                                         .Select(p => p.PrimaryAliasId.Value)
                                         .ToList();
                    }
                }
            }

            using (var rockContext = new RockContext())
            {
                var notificationService          = new NotificationService(rockContext);
                var notificationRecipientService = new NotificationRecipientService(rockContext);

                var notification = new Notification();

                notification.Title          = tbTitle.Text;
                notification.Message        = ceMessage.Text;
                notification.SentDateTime   = RockDateTime.Now;
                notification.IconCssClass   = tbIconCssClass.Text;
                notification.Classification = ddlClassification.SelectedValueAsEnum <NotificationClassification>();
                notificationService.Add(notification);

                foreach (var aliasId in personAliasIds)
                {
                    notification.Recipients.Add(new NotificationRecipient {
                        PersonAliasId = aliasId
                    });
                }

                rockContext.SaveChanges();
            }

            pnlPost.Visible    = false;
            pnlResults.Visible = true;
        }
Exemple #14
0
        /// <summary>
        /// Initialize basic information about the page structure and setup the default content.
        /// </summary>
        /// <param name="sender">Object that is generating this event.</param>
        /// <param name="e">Arguments that describe this event.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!Page.IsPostBack)
            {
                if (string.IsNullOrWhiteSpace(GetAttributeValue("GroupTypes")))
                {
                    nbConfigError.Text = "Block has not been configured yet. Please edit the block settings.";
                    pnlEdit.Visible    = false;

                    return;
                }

                //
                // Find and verify we have a real person.
                //
                var rockContext   = new RockContext();
                var personService = new PersonService(rockContext);
                TargetPersonId = PageParameter("PersonId").AsInteger();
                var person = personService.Get(TargetPersonId);
                if (person == null || person.Id == 0)
                {
                    nbInvalidPerson.Text = "The requested person could not be found.";
                    pnlEdit.Visible      = false;

                    return;
                }

                //
                // Check if the user is either a group leader or an administrator.
                //
                if (!IsGroupLeaderFor(person) && !UserCanAdministrate)
                {
                    nbInvalidPerson.Text = "You are not a group leader for this person.";
                    pnlEdit.Visible      = false;

                    return;
                }

                //
                // Verify if this person is in the "do not edit" list.
                //
                if (!string.IsNullOrWhiteSpace(GetAttributeValue("DisableEditingPeopleInView")))
                {
                    var dataView            = new DataViewService(rockContext).Get(GetAttributeValue("DisableEditingPeopleInView").AsGuid());
                    var errorMessages       = new List <string>();
                    var parameterExpression = personService.ParameterExpression;

                    var whereExpression = dataView.GetExpression(personService, parameterExpression, out errorMessages);
                    var list            = personService.Get(parameterExpression, whereExpression).ToList();
                    if (personService.Get(parameterExpression, whereExpression).Where(p => p.Id == person.Id).Any())
                    {
                        nbInvalidPerson.Text = "The requested person can not be edited by this page.";
                        pnlEdit.Visible      = false;

                        return;
                    }
                }

                ShowDetails(true);
            }
        }
Exemple #15
0
        /// <summary>
        /// Job that will sync groups.
        ///
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            bool requirePasswordReset = dataMap.GetBoolean("RequirePasswordReset");

            int groupsSynced  = 0;
            int groupsChanged = 0;

            try
            {
                // get groups set to sync
                GroupService groupService     = new GroupService(new RockContext());
                var          groupIdsThatSync = groupService.Queryable().Where(g => g.SyncDataViewId != null).Select(a => a.Id).ToList();

                foreach (var syncGroupId in groupIdsThatSync)
                {
                    bool hasGroupChanged = false;

                    // use a fresh rockContext per group so that ChangeTracker doesn't get bogged down
                    using (var rockContext = new RockContext())
                    {
                        var syncGroup = new GroupService(rockContext).Get(syncGroupId);
                        GroupMemberService groupMemberService = new GroupMemberService(rockContext);

                        // increase the timeout just in case the dataview source is slow
                        rockContext.Database.CommandTimeout = 180;

                        var syncSource = new DataViewService(rockContext).Get(syncGroup.SyncDataViewId.Value);

                        // ensure this is a person dataview
                        bool isPersonDataSet = syncSource.EntityTypeId == EntityTypeCache.Read(typeof(Rock.Model.Person)).Id;

                        if (isPersonDataSet)
                        {
                            SortProperty sortById = new SortProperty();
                            sortById.Property  = "Id";
                            sortById.Direction = System.Web.UI.WebControls.SortDirection.Ascending;
                            List <string> errorMessages = new List <string>();

                            var personService       = new PersonService(rockContext);
                            var parameterExpression = personService.ParameterExpression;
                            var whereExpression     = syncSource.GetExpression(personService, parameterExpression, out errorMessages);
                            var sourceItems         = personService.Get(parameterExpression, whereExpression).Select(q => q.Id).ToList();
                            var targetItems         = groupMemberService.Queryable().Where(gm => gm.GroupId == syncGroup.Id).ToList();

                            // delete items from the target not in the source
                            foreach (var targetItem in targetItems.Where(t => !sourceItems.Contains(t.PersonId)))
                            {
                                // made a clone of the person as it will be detached when the group member is deleted. Also
                                // saving the delete before the email is sent in case an exception occurs so the user doesn't
                                // get an email everytime the agent runs.
                                Person recipient = (Person)targetItem.Person.Clone();
                                groupMemberService.Delete(targetItem);

                                rockContext.SaveChanges();

                                hasGroupChanged = true;

                                if (syncGroup.ExitSystemEmailId.HasValue)
                                {
                                    SendExitEmail(syncGroup.ExitSystemEmailId.Value, recipient, syncGroup);
                                }
                            }

                            // add items not in target but in the source
                            foreach (var sourceItem in sourceItems.Where(s => !targetItems.Select(t => t.PersonId).Contains(s)))
                            {
                                // add source to target
                                var newGroupMember = new GroupMember {
                                    Id = 0
                                };
                                newGroupMember.PersonId          = sourceItem;
                                newGroupMember.Group             = syncGroup;
                                newGroupMember.GroupMemberStatus = GroupMemberStatus.Active;
                                newGroupMember.GroupRoleId       = syncGroup.GroupType.DefaultGroupRoleId ?? syncGroup.GroupType.Roles.FirstOrDefault().Id;
                                groupMemberService.Add(newGroupMember);

                                hasGroupChanged = true;

                                if (syncGroup.WelcomeSystemEmailId.HasValue)
                                {
                                    SendWelcomeEmail(syncGroup.WelcomeSystemEmailId.Value, sourceItem, syncGroup, syncGroup.AddUserAccountsDuringSync ?? false, requirePasswordReset);
                                }
                            }

                            if (hasGroupChanged)
                            {
                                groupsChanged++;
                            }

                            groupsSynced++;

                            rockContext.SaveChanges();

                            if (hasGroupChanged && (syncGroup.IsSecurityRole || syncGroup.GroupType.Guid.Equals(Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid())))
                            {
                                Rock.Security.Role.Flush(syncGroup.Id);
                            }
                        }
                    }
                }

                var resultMessage = string.Empty;
                if (groupsSynced == 0)
                {
                    resultMessage = "No groups to sync";
                }
                else if (groupsSynced == 1)
                {
                    resultMessage = "1 group was sync'ed";
                }
                else
                {
                    resultMessage = string.Format("{0} groups were sync'ed", groupsSynced);
                }

                resultMessage += string.Format(" and {0} groups where changed", groupsChanged);

                context.Result = resultMessage;
            }
            catch (System.Exception ex)
            {
                HttpContext context2 = HttpContext.Current;
                ExceptionLogService.LogException(ex, context2);
                throw;
            }
        }