private void LoadContent() { var eventItemGuid = GetAttributeValue("EventItem").AsGuid(); if (eventItemGuid != Guid.Empty) { lMessages.Text = string.Empty; RockContext rockContext = new RockContext(); // get event occurrences var qry = new EventItemOccurrenceService(rockContext).Queryable() .Where(e => e.EventItem.Guid == eventItemGuid); // filter occurrences for campus if (GetAttributeValue("UseCampusContext").AsBoolean()) { var campusEntityType = EntityTypeCache.Read("Rock.Model.Campus"); var contextCampus = RockPage.GetCurrentContext(campusEntityType) as Campus; if (contextCampus != null) { qry = qry.Where(e => e.CampusId == contextCampus.Id); } } else { if (!string.IsNullOrWhiteSpace(GetAttributeValue("Campuses"))) { var selectedCampuses = Array.ConvertAll(GetAttributeValue("Campuses").Split(','), s => new Guid(s)).ToList(); qry = qry.Where(e => selectedCampuses.Contains(e.Campus.Guid)); } } // retrieve occurrences var itemOccurrences = qry.ToList(); // filter by date range var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(GetAttributeValue("DateRange")); if (dateRange.Start != null && dateRange.End != null) { itemOccurrences.RemoveAll(o => o.GetStartTimes(dateRange.Start.Value, dateRange.End.Value).Count() == 0); } else { // default show all future (max 1 year) itemOccurrences.RemoveAll(o => o.GetStartTimes(RockDateTime.Now, RockDateTime.Now.AddDays(365)).Count() == 0); } // limit results int maxItems = GetAttributeValue("MaxOccurrences").AsInteger(); itemOccurrences = itemOccurrences.OrderBy(i => i.NextStartDateTime).Take(maxItems).ToList(); // load event item var eventItem = new EventItemService(rockContext).Get(eventItemGuid); // make lava merge fields var mergeFields = new Dictionary <string, object>(); mergeFields.Add("RegistrationPage", LinkedPageRoute("RegistrationPage")); mergeFields.Add("EventItem", eventItem); mergeFields.Add("EventItemOccurrences", itemOccurrences); // add context to merge fields var contextEntityTypes = RockPage.GetContextEntityTypes(); var contextObjects = new Dictionary <string, object>(); foreach (var conextEntityType in contextEntityTypes) { var contextObject = RockPage.GetCurrentContext(conextEntityType); contextObjects.Add(conextEntityType.FriendlyName, contextObject); } mergeFields.Add("Context", contextObjects); lContent.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields); } else { lMessages.Text = "<div class='alert alert-warning'>No event item is configured for this block.</div>"; } }
/// <summary> /// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering. /// </summary> protected override void CreateChildControls() { Controls.Clear(); _hfActionTypeGuid = new HiddenField(); _hfActionTypeGuid.ID = this.ID + "_hfActionTypeGuid"; _lblActionTypeName = new Label(); _lblActionTypeName.ClientIDMode = ClientIDMode.Static; _lblActionTypeName.ID = this.ID + "_lblActionTypeName"; _lbDeleteActionType = new LinkButton(); _lbDeleteActionType.CausesValidation = false; _lbDeleteActionType.ID = this.ID + "_lbDeleteActionType"; _lbDeleteActionType.CssClass = "btn btn-xs btn-danger"; _lbDeleteActionType.Click += lbDeleteActionType_Click; var iDelete = new HtmlGenericControl("i"); _lbDeleteActionType.Controls.Add(iDelete); iDelete.AddCssClass("fa fa-times"); _tbActionTypeName = new DataTextBox(); _tbActionTypeName.ID = this.ID + "_tbActionTypeName"; _tbActionTypeName.Label = "Name"; _ddlEntityType = new RockDropDownList(); _ddlEntityType.ID = this.ID + "_ddlEntityType"; _ddlEntityType.Label = "Action Type"; // make it autopostback since Attributes are dependant on which EntityType is selected _ddlEntityType.AutoPostBack = true; _ddlEntityType.SelectedIndexChanged += ddlEntityType_SelectedIndexChanged; foreach (var item in WorkflowActionContainer.Instance.Components.Values.OrderBy(a => a.Value.EntityType.FriendlyName)) { var type = item.Value.GetType(); if (type != null) { var entityType = EntityTypeCache.Read(type); var li = new ListItem(entityType.FriendlyName, entityType.Id.ToString()); // Get description string description = string.Empty; var descAttributes = type.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false); if (descAttributes != null) { foreach (System.ComponentModel.DescriptionAttribute descAttribute in descAttributes) { description = descAttribute.Description; } } if (!string.IsNullOrWhiteSpace(description)) { li.Attributes.Add("title", description); } _ddlEntityType.Items.Add(li); } } // set label when they exit the edit field _tbActionTypeName.Attributes["onblur"] = string.Format("javascript: $('#{0}').text($(this).val());", _lblActionTypeName.ID); _tbActionTypeName.SourceTypeName = "Rock.Model.WorkflowActionType, Rock"; _tbActionTypeName.PropertyName = "Name"; _cbIsActionCompletedOnSuccess = new RockCheckBox { Label = "Action is Completed on Success" }; _cbIsActionCompletedOnSuccess.ID = this.ID + "_cbIsActionCompletedOnSuccess"; _cbIsActivityCompletedOnSuccess = new RockCheckBox { Label = "Activity is Completed on Success" }; _cbIsActivityCompletedOnSuccess.ID = this.ID + "_cbIsActivityCompletedOnSuccess"; _phActionAttributes = new PlaceHolder(); _phActionAttributes.ID = this.ID + "_phActionAttributes"; Controls.Add(_hfActionTypeGuid); Controls.Add(_lblActionTypeName); Controls.Add(_tbActionTypeName); Controls.Add(_ddlEntityType); Controls.Add(_cbIsActionCompletedOnSuccess); Controls.Add(_cbIsActivityCompletedOnSuccess); Controls.Add(_phActionAttributes); Controls.Add(_lbDeleteActionType); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { var deviceService = new DeviceService(new RockContext()); var sortProperty = gDevice.SortProperty; gDevice.EntityTypeId = EntityTypeCache.Read <Device>().Id; var queryable = deviceService.Queryable().Select(a => new { a.Id, a.Name, DeviceTypeName = a.DeviceType.Value, a.IPAddress, a.PrintToOverride, a.PrintFrom, PrinterDeviceName = a.PrinterDevice.Name, a.PrinterDeviceId, a.DeviceTypeValueId }); string name = fDevice.GetUserPreference("Name"); if (!string.IsNullOrWhiteSpace(name)) { queryable = queryable.Where(d => d.Name.Contains(name)); } int?deviceTypeId = fDevice.GetUserPreference("Device Type").AsIntegerOrNull(); if (deviceTypeId.HasValue) { queryable = queryable.Where(d => d.DeviceTypeValueId == deviceTypeId.Value); } string ipAddress = fDevice.GetUserPreference("IP Address"); if (!string.IsNullOrWhiteSpace(ipAddress)) { queryable = queryable.Where(d => d.IPAddress.Contains(ipAddress)); } if (!string.IsNullOrWhiteSpace(fDevice.GetUserPreference("Print To"))) { PrintTo printTo = (PrintTo)System.Enum.Parse(typeof(PrintTo), fDevice.GetUserPreference("Print To"));; queryable = queryable.Where(d => d.PrintToOverride == printTo); } int?printerId = fDevice.GetUserPreference("Printer").AsIntegerOrNull(); if (printerId.HasValue) { queryable = queryable.Where(d => d.PrinterDeviceId == printerId); } if (!string.IsNullOrWhiteSpace(fDevice.GetUserPreference("Print From"))) { PrintFrom printFrom = (PrintFrom)System.Enum.Parse(typeof(PrintFrom), fDevice.GetUserPreference("Print From"));; queryable = queryable.Where(d => d.PrintFrom == printFrom); } if (sortProperty != null) { gDevice.DataSource = queryable.Sort(sortProperty).ToList(); } else { gDevice.DataSource = queryable.OrderBy(d => d.Name).ToList(); } gDevice.EntityTypeId = EntityTypeCache.Read <Rock.Model.Device>().Id; gDevice.DataBind(); }
/// <summary> /// Loads the groups. /// </summary> private void LoadDropDowns() { var groupEntityType = EntityTypeCache.Read(typeof(Group)); var currentGroup = RockPage.GetCurrentContext(groupEntityType) as Group; var groupIdString = Request.QueryString["groupId"]; if (groupIdString != null) { var groupId = groupIdString.AsInteger(); if (currentGroup == null || currentGroup.Id != groupId) { currentGroup = SetGroupContext(groupId, false); } } var parts = (GetAttributeValue("GroupFilter") ?? string.Empty).Split('|'); Guid?groupTypeGuid = null; Guid?rootGroupGuid = null; if (parts.Length >= 1) { groupTypeGuid = parts[0].AsGuidOrNull(); if (parts.Length >= 2) { rootGroupGuid = parts[1].AsGuidOrNull(); } } var rockContext = new RockContext(); var groupService = new GroupService(rockContext); var groupTypeService = new GroupTypeService(rockContext); IQueryable <Group> qryGroups = null; // if rootGroup is set, use that as the filter. Otherwise, use GroupType as the filter if (rootGroupGuid.HasValue) { var rootGroup = groupService.Get(rootGroupGuid.Value); if (rootGroup != null) { qryGroups = groupService.GetAllDescendents(rootGroup.Id).AsQueryable(); } } else if (groupTypeGuid.HasValue) { SetGroupTypeContext(groupTypeGuid); if (GetAttributeValue("IncludeGroupTypeChildren").AsBoolean()) { var childGroupTypeGuids = groupTypeService.Queryable().Where(t => t.ParentGroupTypes.Select(p => p.Guid).Contains(groupTypeGuid.Value)) .Select(t => t.Guid).ToList(); qryGroups = groupService.Queryable().Where(a => childGroupTypeGuids.Contains(a.GroupType.Guid)); } else { qryGroups = groupService.Queryable().Where(a => a.GroupType.Guid == groupTypeGuid.Value); } } // no results if (qryGroups == null) { nbSelectGroupTypeWarning.Visible = true; lCurrentSelection.Text = string.Empty; rptGroups.Visible = false; } else { nbSelectGroupTypeWarning.Visible = false; rptGroups.Visible = true; lCurrentSelection.Text = currentGroup != null?currentGroup.ToString() : GetAttributeValue("NoGroupText"); var groupList = qryGroups.OrderBy(a => a.Order) .ThenBy(a => a.Name).ToList() .Select(a => new GroupItem() { Name = a.Name, Id = a.Id }) .ToList(); // check if the group can be unselected if (!string.IsNullOrEmpty(GetAttributeValue("ClearSelectionText"))) { var blankGroup = new GroupItem { Name = GetAttributeValue("ClearSelectionText"), Id = Rock.Constants.All.Id }; groupList.Insert(0, blankGroup); } rptGroups.DataSource = groupList; rptGroups.DataBind(); } }
/// <summary> /// Handles the Click event of the 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 btnSendTest_Click(object sender, EventArgs e) { var recipients = new List <RecipientData>(); var personDict = new Dictionary <string, object>(); personDict.Add("Person", CurrentPerson); recipients.Add(new RecipientData(CurrentPerson.Email, personDict)); if (GetAttributeValue("CommunicationType") == "System") { var message = new RockEmailMessage(ddlEmail.SelectedValueAsGuid().Value); message.SetRecipients(recipients); message.Send(); } else { // Get existing or new communication record var communication = UpdateCommunication(new RockContext(), ddlEmail.SelectedValueAsGuid().Value); if (communication != null) { using (var rockContext = new RockContext()) { // Using a new context (so that changes in the UpdateCommunication() are not persisted ) var testCommunication = communication.Clone(false); testCommunication.Id = 0; testCommunication.Guid = Guid.NewGuid(); testCommunication.CreatedByPersonAliasId = this.CurrentPersonAliasId; testCommunication.CreatedByPersonAlias = new PersonAliasService(rockContext).Queryable().Where(a => a.Id == this.CurrentPersonAliasId.Value).Include(a => a.Person).FirstOrDefault(); testCommunication.ForeignGuid = null; testCommunication.ForeignId = null; testCommunication.ForeignKey = null; testCommunication.FutureSendDateTime = null; testCommunication.Status = CommunicationStatus.Approved; testCommunication.ReviewedDateTime = RockDateTime.Now; testCommunication.ReviewerPersonAliasId = CurrentPersonAliasId; foreach (var attachment in communication.Attachments) { var cloneAttachment = attachment.Clone(false); cloneAttachment.Id = 0; cloneAttachment.Guid = Guid.NewGuid(); cloneAttachment.ForeignGuid = null; cloneAttachment.ForeignId = null; cloneAttachment.ForeignKey = null; testCommunication.Attachments.Add(cloneAttachment); } var testRecipient = new CommunicationRecipient(); if (communication.GetRecipientCount(rockContext) > 0) { var recipient = communication.GetRecipientsQry(rockContext).FirstOrDefault(); testRecipient.AdditionalMergeValuesJson = recipient.AdditionalMergeValuesJson; } testRecipient.Status = CommunicationRecipientStatus.Pending; testRecipient.PersonAliasId = CurrentPersonAliasId.Value; testRecipient.MediumEntityTypeId = EntityTypeCache.Read("Rock.Communication.Medium.Email").Id; testCommunication.Recipients.Add(testRecipient); var communicationService = new CommunicationService(rockContext); communicationService.Add(testCommunication); rockContext.SaveChanges(); foreach (var medium in testCommunication.GetMediums()) { medium.Send(testCommunication); } testRecipient = new CommunicationRecipientService(rockContext) .Queryable().AsNoTracking() .Where(r => r.CommunicationId == testCommunication.Id) .FirstOrDefault(); communicationService.Delete(testCommunication); rockContext.SaveChanges(); } } } nbSuccess.Text = string.Format("Sent test at {0}", DateTime.Now); }
/// <summary> /// Loads the campuses /// </summary> protected void LoadCampusDropdowns() { var campusEntityType = EntityTypeCache.Read(typeof(Campus)); var currentCampus = RockPage.GetCurrentContext(campusEntityType) as Campus; var campusIdString = Request.QueryString["campusId"]; if (campusIdString != null) { var campusId = campusIdString.AsInteger(); if (currentCampus == null || currentCampus.Id != campusId) { currentCampus = SetCampusContext(campusId, false); } } if (currentCampus == null && GetAttributeValue("DefaultToCurrentUser").AsBoolean() && CurrentPerson != null) { currentCampus = CurrentPerson.GetFamilies().First().Campus; } if (currentCampus != null) { var mergeObjects = new Dictionary <string, object>(); mergeObjects.Add("CampusName", currentCampus.Name); lCurrentCampusSelection.Text = GetAttributeValue("CampusCurrentItemTemplate").ResolveMergeFields(mergeObjects); _currentCampusText = GetAttributeValue("CampusCurrentItemTemplate").ResolveMergeFields(mergeObjects); } else { lCurrentCampusSelection.Text = GetAttributeValue("NoCampusText"); _currentCampusText = GetAttributeValue("NoCampusText"); } var campusList = CampusCache.All() .Select(a => new CampusItem { Name = a.Name, Id = a.Id }) .ToList(); // run lava on each campus string dropdownItemTemplate = GetAttributeValue("CampusDropdownItemTemplate"); if (!string.IsNullOrWhiteSpace(dropdownItemTemplate)) { foreach (var campus in campusList) { var mergeObjects = new Dictionary <string, object>(); mergeObjects.Add("CampusName", campus.Name); campus.Name = dropdownItemTemplate.ResolveMergeFields(mergeObjects); } } // check if the campus can be unselected if (!string.IsNullOrEmpty(GetAttributeValue("CampusClearSelectionText"))) { var blankCampus = new CampusItem { Name = GetAttributeValue("CampusClearSelectionText"), Id = Rock.Constants.All.Id }; campusList.Insert(0, blankCampus); } rptCampuses.DataSource = campusList; rptCampuses.DataBind(); }
/// <summary> /// Handles the Click event of the lbSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void lbSave_Click(object sender, EventArgs e) { var rockContext = new RockContext(); ContentChannel contentChannel; ContentChannelService contentChannelService = new ContentChannelService(rockContext); int contentChannelId = hfId.Value.AsInteger(); if (contentChannelId == 0) { contentChannel = new ContentChannel { Id = 0 }; contentChannelService.Add(contentChannel); } else { contentChannel = contentChannelService.Get(contentChannelId); } if (contentChannel != null) { contentChannel.Name = tbName.Text; contentChannel.Description = tbDescription.Text; contentChannel.ContentChannelTypeId = ddlChannelType.SelectedValueAsInt() ?? 0; contentChannel.ContentControlType = ddlContentControlType.SelectedValueAsEnum <ContentControlType>(); contentChannel.RootImageDirectory = tbRootImageDirectory.Visible ? tbRootImageDirectory.Text : string.Empty; contentChannel.IconCssClass = tbIconCssClass.Text; contentChannel.RequiresApproval = cbRequireApproval.Checked; contentChannel.EnableRss = cbEnableRss.Checked; contentChannel.ChannelUrl = tbChannelUrl.Text; contentChannel.ItemUrl = tbItemUrl.Text; contentChannel.TimeToLive = nbTimetoLive.Text.AsIntegerOrNull(); contentChannel.LoadAttributes(rockContext); Rock.Attribute.Helper.GetEditValues(phAttributes, contentChannel); if (!Page.IsValid || !contentChannel.IsValid) { // Controls will render the error messages return; } rockContext.WrapTransaction(() => { rockContext.SaveChanges(); contentChannel.SaveAttributeValues(rockContext); foreach (var item in new ContentChannelItemService(rockContext) .Queryable() .Where(i => i.ContentChannelId == contentChannel.Id && i.ContentChannelTypeId != contentChannel.ContentChannelTypeId )) { item.ContentChannelTypeId = contentChannel.ContentChannelTypeId; } rockContext.SaveChanges(); // Save the Item Attributes int entityTypeId = EntityTypeCache.Read(typeof(ContentChannelItem)).Id; SaveAttributes(contentChannel.Id, entityTypeId, ItemAttributesState, rockContext); }); var pageReference = RockPage.PageReference; pageReference.Parameters.AddOrReplace("contentChannelId", contentChannel.Id.ToString()); Response.Redirect(pageReference.BuildUrl(), false); } }
/// <summary> /// Liquidizes the child properties of an object for displaying debug information about fields available for lava templates /// </summary> /// <param name="myObject">an object.</param> /// <param name="levelsDeep">The levels deep.</param> /// <param name="rockContext">The rock context.</param> /// <param name="entityHistory">The entity history.</param> /// <param name="parentElement">The parent element.</param> /// <returns></returns> private static object LiquidizeChildren(this object myObject, int levelsDeep = 0, RockContext rockContext = null, Dictionary <int, List <int> > entityHistory = null, string parentElement = "") { // Add protection for stack-overflow if property attributes are not set correctly resulting in child/parent objects being evaluated in loop levelsDeep++; if (levelsDeep > 6) { return(string.Empty); } // If the object is liquidable, get the object return by its ToLiquid() method. if (myObject is DotLiquid.ILiquidizable) { myObject = ((DotLiquid.ILiquidizable)myObject).ToLiquid(); } // If the object is null, return an empty string if (myObject == null) { return(string.Empty); } // If the object is a string, return its value converted to HTML and truncated if (myObject is string) { return(myObject.ToString().Truncate(50).EncodeHtml()); } // If the object is a guid, return its string representation if (myObject is Guid) { return(myObject.ToString()); } // Get the object's type ( checking for a proxy object ) Type entityType = myObject.GetType(); if (entityType.IsDynamicProxyType()) { entityType = entityType.BaseType; } // If this is an IEntity, check to see if it's already been liquidized in prev heirarchy. If so, just return string indicating "--See Previous Entry--" if (myObject is IEntity) { var entity = myObject as IEntity; var entityTypeCache = EntityTypeCache.Read(entityType, false, rockContext); if (entity != null && entityTypeCache != null) { if (entityHistory == null) { entityHistory = new Dictionary <int, List <int> >(); } entityHistory.AddOrIgnore(entityTypeCache.Id, new List <int>()); if (entityHistory[entityTypeCache.Id].Contains(entity.Id)) { return("--See Previous Entry--"); } else { entityHistory[entityTypeCache.Id].Add(entity.Id); } } } // If the object is a Liquid Drop object, return a list of all of the object's properties if (myObject is Drop) { var result = new Dictionary <string, object>(); foreach (var propInfo in entityType.GetProperties( BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { if (propInfo != null) { try { result.Add(propInfo.Name, propInfo.GetValue(myObject, null).LiquidizeChildren(levelsDeep, rockContext, entityHistory)); } catch (Exception ex) { result.Add(propInfo.Name, ex.ToString()); } } } return(result); } // If the object has the [LiquidType] attribute, enumerate the allowed properties and return a list of those properties if (entityType.GetCustomAttributes(typeof(LiquidTypeAttribute), false).Any()) { var result = new Dictionary <string, object>(); var attr = (LiquidTypeAttribute)entityType.GetCustomAttributes(typeof(LiquidTypeAttribute), false).First(); foreach (string propName in attr.AllowedMembers) { var propInfo = entityType.GetProperty(propName); { if (propInfo != null) { try { result.Add(propInfo.Name, propInfo.GetValue(myObject, null).LiquidizeChildren(levelsDeep, rockContext, entityHistory, parentElement + "." + propName)); } catch (Exception ex) { result.Add(propInfo.Name, ex.ToString()); } } } } return(result); } // If the object is a Rock Liquidizable object, call the object's AvailableKeys method to determine the properties available. if (myObject is Lava.ILiquidizable) { var liquidObject = (Lava.ILiquidizable)myObject; var result = new Dictionary <string, object>(); foreach (var key in liquidObject.AvailableKeys) { // Ignore the person property of the person's primary alias (prevent unnecessary recursion) if (key == "Person" && parentElement.Contains(".PrimaryAlias")) { result.AddOrIgnore(key, string.Empty); } else { try { object propValue = null; var propType = entityType.GetPropertyType(key); if (propType?.Name == "ICollection`1") { // if the property type is an ICollection, get the underlying query and just fetch one for an example (just in case there are 1000s of records) var entityDbContext = GetDbContextFromEntity(myObject); if (entityDbContext != null) { var entryCollection = entityDbContext.Entry(myObject)?.Collection(key); if (entryCollection.IsLoaded) { propValue = liquidObject[key]; } else { try { var propQry = entryCollection.Query().Provider.CreateQuery <Rock.Data.IEntity>(entryCollection.Query().Expression); int propCollectionCount = propQry.Count(); List <object> listSample = propQry.Take(1).ToList().Cast <object>().ToList(); if (propCollectionCount > 1) { listSample.Add($"({propCollectionCount - 1} more...)"); } propValue = listSample; } catch { // The Collection might be a database model that isn't an IEntity, so just do it the regular way propValue = liquidObject[key]; } } } } else { propValue = liquidObject[key]; } if (propValue != null) { result.Add(key, propValue.LiquidizeChildren(levelsDeep, rockContext, entityHistory, parentElement + "." + key)); } else { result.AddOrIgnore(key, string.Empty); } } catch (Exception ex) { result.AddOrIgnore(key, ex.ToString()); } } } // Add the attributes if this object has attributes if (liquidObject is Rock.Attribute.IHasAttributes) { var objWithAttrs = (Rock.Attribute.IHasAttributes)liquidObject; if (objWithAttrs.Attributes == null) { rockContext = rockContext ?? new RockContext(); objWithAttrs.LoadAttributes(rockContext); } var objAttrs = new Dictionary <string, object>(); foreach (var objAttr in objWithAttrs.Attributes) { var attributeCache = objAttr.Value; string value = attributeCache.FieldType.Field.FormatValue(null, attributeCache.EntityTypeId, objWithAttrs.Id, objWithAttrs.GetAttributeValue(attributeCache.Key), attributeCache.QualifierValues, false); objAttrs.Add(attributeCache.Key, value.Truncate(50).EncodeHtml()); } if (objAttrs.Any()) { result.Add(string.Format("Attributes <p class='attributes'>Below is a list of attributes that can be retrieved using <code>{{{{ {0} | Attribute:'[AttributeKey]' }}}}</code>.</p>", parentElement), objAttrs); } } return(result); } if (myObject is IDictionary <string, object> ) { var result = new Dictionary <string, object>(); foreach (var keyValue in ((IDictionary <string, object>)myObject)) { try { var parentVariable = (keyValue.Value?.GetType().GetInterface("IList") != null) ? keyValue.Key.ToLower().Singularize() : keyValue.Key; result.Add(keyValue.Key, keyValue.Value?.LiquidizeChildren(levelsDeep, rockContext, entityHistory, parentVariable)); } catch (Exception ex) { result.Add(keyValue.Key, ex.ToString()); } } return(result); } if (myObject is Newtonsoft.Json.Linq.JObject) { var result = new Dictionary <string, object>(); var jObject = myObject as Newtonsoft.Json.Linq.JObject; foreach (var keyValue in jObject) { try { result.Add(keyValue.Key, keyValue.Value.LiquidizeChildren(levelsDeep, rockContext, entityHistory, keyValue.Key)); } catch (Exception ex) { result.Add(keyValue.Key, ex.ToString()); } } return(result); } if (myObject is Newtonsoft.Json.Linq.JValue) { var jValue = (myObject as Newtonsoft.Json.Linq.JValue); if (jValue != null && jValue.Value != null) { return(jValue.Value.ToString()); } else { return(string.Empty); } } if (myObject is IEnumerable) { var result = new List <object>(); // Only show first two items in an enumerable list int iEnumCount = 1; foreach (var value in ((IEnumerable)myObject)) { if (iEnumCount > 2) { result.Add("..."); break; } iEnumCount++; try { result.Add(value.LiquidizeChildren(levelsDeep, rockContext, entityHistory, parentElement)); } catch { } } return(result); } return(myObject.ToStringSafe()); }
/// <summary> /// Gets the settings. /// </summary> private void GetSettings() { // Get Data Automation Settings _reactivateSettings = Rock.Web.SystemSettings.GetValue(SystemSetting.DATA_AUTOMATION_REACTIVATE_PEOPLE).FromJsonOrNull <ReactivatePeople>() ?? new ReactivatePeople(); _inactivateSettings = Rock.Web.SystemSettings.GetValue(SystemSetting.DATA_AUTOMATION_INACTIVATE_PEOPLE).FromJsonOrNull <InactivatePeople>() ?? new InactivatePeople(); _campusSettings = Rock.Web.SystemSettings.GetValue(SystemSetting.DATA_AUTOMATION_CAMPUS_UPDATE).FromJsonOrNull <UpdateFamilyCampus>() ?? new UpdateFamilyCampus(); _adultChildrenSettings = Rock.Web.SystemSettings.GetValue(SystemSetting.DATA_AUTOMATION_ADULT_CHILDREN).FromJsonOrNull <MoveAdultChildren>() ?? new MoveAdultChildren(); // Set Data Automation Controls // Reactivate cbReactivatePeople.Checked = _reactivateSettings.IsEnabled; pnlReactivatePeople.Enabled = _reactivateSettings.IsEnabled; cbLastContribution.Checked = _reactivateSettings.IsLastContributionEnabled; nbLastContribution.Text = _reactivateSettings.LastContributionPeriod.ToStringSafe(); cbAttendanceInServiceGroup.Checked = _reactivateSettings.IsAttendanceInServiceGroupEnabled; nbAttendanceInServiceGroup.Text = _reactivateSettings.AttendanceInServiceGroupPeriod.ToStringSafe(); cbAttendanceInGroupType.Checked = _reactivateSettings.IsAttendanceInGroupTypeEnabled; nbAttendanceInGroupType.Text = _reactivateSettings.AttendanceInGroupTypeDays.ToStringSafe(); rlbAttendanceInGroupType.SetValues(_reactivateSettings.AttendanceInGroupType ?? new List <int>()); cbPrayerRequest.Checked = _reactivateSettings.IsPrayerRequestEnabled; nbPrayerRequest.Text = _reactivateSettings.PrayerRequestPeriod.ToStringSafe(); cbPersonAttributes.Checked = _reactivateSettings.IsPersonAttributesEnabled; nbPersonAttributes.Text = _reactivateSettings.PersonAttributesDays.ToStringSafe(); rlbPersonAttributes.SetValues(_reactivateSettings.PersonAttributes ?? new List <int>()); cbIncludeDataView.Checked = _reactivateSettings.IsIncludeDataViewEnabled; dvIncludeDataView.EntityTypeId = EntityTypeCache.Read(typeof(Rock.Model.Person)).Id; dvIncludeDataView.SetValue(_reactivateSettings.IncludeDataView); cbExcludeDataView.Checked = _reactivateSettings.IsExcludeDataViewEnabled; dvExcludeDataView.EntityTypeId = EntityTypeCache.Read(typeof(Rock.Model.Person)).Id; dvExcludeDataView.SetValue(_reactivateSettings.ExcludeDataView); cbInteractions.Checked = _reactivateSettings.IsInteractionsEnabled; var interactionChannels = new InteractionChannelService(_rockContext) .Queryable().AsNoTracking() .Select(a => new { a.Guid, a.Name }) .ToList(); var reactivateChannelTypes = interactionChannels.Select(c => new InteractionItem(c.Guid, c.Name)).ToList(); if (_reactivateSettings.Interactions != null) { bool noneSelected = !_reactivateSettings.Interactions.Any(i => i.IsInteractionTypeEnabled); foreach (var settingInteractionItem in _reactivateSettings.Interactions) { var interactionChannelType = reactivateChannelTypes.SingleOrDefault(a => a.Guid == settingInteractionItem.Guid); if (interactionChannelType != null) { interactionChannelType.IsInteractionTypeEnabled = noneSelected || settingInteractionItem.IsInteractionTypeEnabled; interactionChannelType.LastInteractionDays = settingInteractionItem.LastInteractionDays; } } } rInteractions.DataSource = reactivateChannelTypes; rInteractions.DataBind(); // Inactivate cbInactivatePeople.Checked = _inactivateSettings.IsEnabled; pnlInactivatePeople.Enabled = _inactivateSettings.IsEnabled; cbNoLastContribution.Checked = _inactivateSettings.IsNoLastContributionEnabled; nbNoLastContribution.Text = _inactivateSettings.NoLastContributionPeriod.ToStringSafe(); cbNoAttendanceInGroupType.Checked = _inactivateSettings.IsNoAttendanceInGroupTypeEnabled; nbNoAttendanceInGroupType.Text = _inactivateSettings.NoAttendanceInGroupTypeDays.ToStringSafe(); rlbNoAttendanceInGroupType.SetValues(_inactivateSettings.AttendanceInGroupType ?? new List <int>()); cbNoPrayerRequest.Checked = _inactivateSettings.IsNoPrayerRequestEnabled; nbNoPrayerRequest.Text = _inactivateSettings.NoPrayerRequestPeriod.ToStringSafe(); cbNoPersonAttributes.Checked = _inactivateSettings.IsNoPersonAttributesEnabled; nbNoPersonAttributes.Text = _inactivateSettings.NoPersonAttributesDays.ToStringSafe(); rlbNoPersonAttributes.SetValues(_inactivateSettings.PersonAttributes ?? new List <int>()); cbNotInDataView.Checked = _inactivateSettings.IsNotInDataviewEnabled; dvNotInDataView.EntityTypeId = EntityTypeCache.Read(typeof(Rock.Model.Person)).Id; dvNotInDataView.SetValue(_inactivateSettings.NotInDataview); cbNoInteractions.Checked = _inactivateSettings.IsNoInteractionsEnabled; var inactivateChannelTypes = interactionChannels.Select(c => new InteractionItem(c.Guid, c.Name)).ToList(); if (_inactivateSettings.NoInteractions != null) { bool noneSelected = !_inactivateSettings.NoInteractions.Any(i => i.IsInteractionTypeEnabled); foreach (var settingInteractionItem in _inactivateSettings.NoInteractions) { var interactionChannelType = inactivateChannelTypes.SingleOrDefault(a => a.Guid == settingInteractionItem.Guid); if (interactionChannelType != null) { interactionChannelType.IsInteractionTypeEnabled = noneSelected || settingInteractionItem.IsInteractionTypeEnabled; interactionChannelType.LastInteractionDays = settingInteractionItem.LastInteractionDays; } } } rNoInteractions.DataSource = inactivateChannelTypes; rNoInteractions.DataBind(); // campus Update cbCampusUpdate.Checked = _campusSettings.IsEnabled; pnlCampusUpdate.Enabled = _campusSettings.IsEnabled; cbMostFamilyAttendance.Checked = _campusSettings.IsMostFamilyAttendanceEnabled; nbMostFamilyAttendance.Text = _campusSettings.MostFamilyAttendancePeriod.ToStringSafe(); cbMostFamilyGiving.Checked = _campusSettings.IsMostFamilyGivingEnabled; nbMostFamilyGiving.Text = _campusSettings.MostFamilyGivingPeriod.ToStringSafe(); ddlAttendanceOrGiving.SetValue(_campusSettings.MostAttendanceOrGiving.ConvertToInt()); cbIgnoreIfManualUpdate.Checked = _campusSettings.IsIgnoreIfManualUpdateEnabled; nbIgnoreIfManualUpdate.Text = _campusSettings.IgnoreIfManualUpdatePeriod.ToStringSafe(); cbIgnoreCampusChanges.Checked = _campusSettings.IsIgnoreCampusChangesEnabled; if (_campusSettings.IgnoreCampusChanges != null && _campusSettings.IgnoreCampusChanges.Any()) { int i = 1; _ignoreCampusChangeRows = _campusSettings.IgnoreCampusChanges .Select(a => new IgnoreCampusChangeRow() { Id = i++, CampusCriteria = a.BasedOn, FromCampusId = a.FromCampus, ToCampusId = a.ToCampus }).ToList(); } else { _ignoreCampusChangeRows = new List <IgnoreCampusChangeRow>() { new IgnoreCampusChangeRow() { Id = 1 } }; } rIgnoreCampusChanges.DataSource = _ignoreCampusChangeRows; rIgnoreCampusChanges.DataBind(); // Adult Children cbAdultChildren.Checked = _adultChildrenSettings.IsEnabled; pnlAdultChildren.Enabled = _adultChildrenSettings.IsEnabled; nbAdultAge.Text = _adultChildrenSettings.AdultAge.ToString(); rpParentRelationship.GroupRoleId = _adultChildrenSettings.ParentRelationshipId; rpSiblingRelationship.GroupRoleId = _adultChildrenSettings.SiblingRelationshipId; cbSameAddress.Checked = _adultChildrenSettings.UseSameHomeAddress; cbSamePhone.Checked = _adultChildrenSettings.UseSameHomePhone; wfWorkflows.SetValues(_adultChildrenSettings.WorkflowTypeIds); nbMaxRecords.Text = _adultChildrenSettings.MaximumRecords.ToString(); }
private void GetData() { var rockContext = new RockContext(); var itemService = new ContentChannelItemService(rockContext); // Get all of the content channels var contentChannelsQry = new ContentChannelService(rockContext).Queryable("ContentChannelType"); List <Guid> contentChannelTypeGuidsInclude = GetAttributeValue("ContentChannelTypesInclude").SplitDelimitedValues().AsGuidList(); List <Guid> contentChannelTypeGuidsExclude = GetAttributeValue("ContentChannelTypesExclude").SplitDelimitedValues().AsGuidList(); if (contentChannelTypeGuidsInclude.Any()) { // if contentChannelTypeGuidsInclude is specified, only get contentChannelTypes that are in the contentChannelTypeGuidsInclude // NOTE: no need to factor in contentChannelTypeGuidsExclude since included would take precendance and the excluded ones would already not be included contentChannelsQry = contentChannelsQry.Where(a => contentChannelTypeGuidsInclude.Contains(a.ContentChannelType.Guid)); } else if (contentChannelTypeGuidsExclude.Any()) { contentChannelsQry = contentChannelsQry.Where(a => !contentChannelTypeGuidsExclude.Contains(a.ContentChannelType.Guid)); } var contentChannelsList = contentChannelsQry.OrderBy(w => w.Name).ToList(); // Create variable for storing authorized channels and the count of active items var channelCounts = new Dictionary <int, int>(); foreach (var channel in contentChannelsList) { if (channel.IsAuthorized(Authorization.VIEW, CurrentPerson)) { channelCounts.Add(channel.Id, 0); } } // Get the pending approval item counts for each channel (if the channel requires approval) itemService.Queryable() .Where(i => channelCounts.Keys.Contains(i.ContentChannelId) && i.Status == ContentChannelItemStatus.PendingApproval && i.ContentChannel.RequiresApproval) .GroupBy(i => i.ContentChannelId) .Select(i => new { Id = i.Key, Count = i.Count() }) .ToList() .ForEach(i => channelCounts[i.Id] = i.Count); // Create a query to return channel, the count of items, and the selected class var qry = contentChannelsList .Where(c => channelCounts.Keys.Contains(c.Id)) .Select(c => new { Channel = c, Count = channelCounts[c.Id], Class = (SelectedChannelId.HasValue && SelectedChannelId.Value == c.Id) ? "active" : "" }); // If displaying active only, update query to exclude those content channels without any items if (tglStatus.Checked) { qry = qry.Where(c => c.Count > 0); } var contentChannels = qry.ToList(); rptChannels.DataSource = contentChannels; rptChannels.DataBind(); ContentChannel selectedChannel = null; if (SelectedChannelId.HasValue) { selectedChannel = contentChannelsList .Where(w => w.Id == SelectedChannelId.Value && channelCounts.Keys.Contains(SelectedChannelId.Value)) .FirstOrDefault(); } if (selectedChannel != null && contentChannels.Count > 0) { // show the content item panel divItemPanel.Visible = true; BindAttributes(selectedChannel); AddDynamicControls(selectedChannel); bool isFiltered = false; var items = GetItems(rockContext, selectedChannel, out isFiltered); var reorderFieldColumn = gContentChannelItems.ColumnsOfType <ReorderField>().FirstOrDefault(); if (selectedChannel.ItemsManuallyOrdered && !isFiltered) { if (reorderFieldColumn != null) { reorderFieldColumn.Visible = true; } gContentChannelItems.AllowSorting = false; } else { if (reorderFieldColumn != null) { reorderFieldColumn.Visible = false; } gContentChannelItems.AllowSorting = true; SortProperty sortProperty = gContentChannelItems.SortProperty; if (sortProperty != null) { items = items.AsQueryable().Sort(sortProperty).ToList(); } else { items = items.OrderByDescending(p => p.StartDateTime).ToList(); } } // Find any possible tags for the items var itemTags = new Dictionary <Guid, string>(); if (selectedChannel.IsTaggingEnabled) { itemTags = items.ToDictionary(i => i.Guid, v => ""); var entityTypeId = EntityTypeCache.Read(Rock.SystemGuid.EntityType.CONTENT_CHANNEL_ITEM.AsGuid()).Id; var testedTags = new Dictionary <int, string>(); foreach (var taggedItem in new TaggedItemService(rockContext) .Queryable().AsNoTracking() .Where(i => i.EntityTypeId == entityTypeId && itemTags.Keys.Contains(i.EntityGuid)) .OrderBy(i => i.Tag.Name)) { if (!testedTags.ContainsKey(taggedItem.TagId)) { testedTags.Add(taggedItem.TagId, taggedItem.Tag.IsAuthorized(Authorization.VIEW, CurrentPerson) ? taggedItem.Tag.Name : string.Empty); } if (testedTags[taggedItem.TagId].IsNotNullOrWhitespace()) { itemTags[taggedItem.EntityGuid] += string.Format("<span class='tag'>{0}</span>", testedTags[taggedItem.TagId]); } } } gContentChannelItems.ObjectList = new Dictionary <string, object>(); items.ForEach(i => gContentChannelItems.ObjectList.Add(i.Id.ToString(), i)); var gridList = items.Select(i => new { i.Id, i.Guid, i.Title, i.StartDateTime, i.ExpireDateTime, i.Priority, Status = DisplayStatus(i.Status), Tags = itemTags.GetValueOrNull(i.Guid), Occurrences = i.EventItemOccurrences.Any(), CreatedByPersonName = i.CreatedByPersonAlias != null ? String.Format("<a href={0}>{1}</a>", ResolveRockUrl(string.Format("~/Person/{0}", i.CreatedByPersonAlias.PersonId)), i.CreatedByPersonName) : String.Empty }).ToList(); // only show the Event Occurrences item if any of the displayed content channel items have any occurrences (and the block setting is enabled) var eventOccurrencesColumn = gContentChannelItems.ColumnsWithDataField("Occurrences").FirstOrDefault(); eventOccurrencesColumn.Visible = gridList.Any(a => a.Occurrences == true); gContentChannelItems.DataSource = gridList; gContentChannelItems.DataBind(); lContentChannelItems.Text = selectedChannel.Name + " Items"; } else { divItemPanel.Visible = false; } }
/// <summary> /// Creates the control(s) necessary for prompting user for a new value /// </summary> /// <param name="configurationValues">The configuration values.</param> /// <param name="id"></param> /// <returns> /// The control /// </returns> public override Control EditControl(Dictionary <string, ConfigurationValue> configurationValues, string id) { int entityTypeId = 0; string entityTypeName = string.Empty; string qualifierColumn = string.Empty; string qualifierValue = string.Empty; if (configurationValues != null) { if (configurationValues.ContainsKey(ENTITY_TYPE_NAME_KEY)) { entityTypeName = configurationValues[ENTITY_TYPE_NAME_KEY].Value; if (!string.IsNullOrWhiteSpace(entityTypeName) && entityTypeName != None.IdValue) { var entityType = EntityTypeCache.Read(entityTypeName); if (entityType != null) { entityTypeId = entityType.Id; } } } if (configurationValues.ContainsKey(QUALIFIER_COLUMN_KEY)) { qualifierColumn = configurationValues[QUALIFIER_COLUMN_KEY].Value; } if (configurationValues.ContainsKey(QUALIFIER_VALUE_KEY)) { qualifierValue = configurationValues[QUALIFIER_VALUE_KEY].Value; } } RockCheckBoxList editControl = new RockCheckBoxList { ID = id }; editControl.RepeatDirection = RepeatDirection.Horizontal; using (var rockContext = new RockContext()) { if (string.IsNullOrWhiteSpace(entityTypeName)) { foreach (var noteType in new NoteTypeService(rockContext) .Queryable() .OrderBy(n => n.EntityType.Name) .ThenBy(n => n.Name)) { editControl.Items.Add(new ListItem(string.Format("{0}: {1}", noteType.EntityType.FriendlyName, noteType.Name), noteType.Guid.ToString().ToUpper())); } } else { foreach (var noteType in new NoteTypeService(rockContext) .Get(entityTypeId, qualifierColumn, qualifierValue) .OrderBy(n => n.Name)) { editControl.Items.Add(new ListItem(noteType.Name, noteType.Guid.ToString().ToUpper())); } } } return(editControl); }
public IQueryable <TreeViewItem> GetChildren(string id, string additionalFields) { var person = GetPerson(); List <TreeViewItem> items = new List <TreeViewItem>(); switch (id) { case "0": { if (!string.IsNullOrWhiteSpace(additionalFields)) { foreach (string fieldInfo in additionalFields.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { string[] parts = fieldInfo.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); string fieldId = parts.Length > 0 ? parts[0] : string.Empty; string[] idParts = fieldId.Split(new char[] { '^' }, StringSplitOptions.RemoveEmptyEntries); string fieldType = idParts.Length > 1 ? idParts[1] : fieldId; var entityType = EntityTypeCache.Read(fieldType, false); if (entityType != null) { items.Add(new TreeViewItem { Id = fieldId, Name = parts.Length > 1 ? parts[1] : entityType.FriendlyName, HasChildren = true }); } else { items.Add(new TreeViewItem { Id = fieldId, Name = parts.Length > 1 ? parts[1] : fieldType.SplitCase(), HasChildren = fieldType == "GlobalAttribute" }); } } } break; } case "GlobalAttribute": { var globalAttributes = Rock.Web.Cache.GlobalAttributesCache.Read(); foreach (var attributeCache in globalAttributes.Attributes.OrderBy(a => a.Key)) { if (attributeCache.IsAuthorized(Authorization.VIEW, person)) { items.Add(new TreeViewItem { Id = "GlobalAttribute|" + attributeCache.Key, Name = attributeCache.Name, HasChildren = false }); } } break; } default: { // In this scenario, the id should be a concatnation of a root qualified entity name and then the property path var idParts = id.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (idParts.Count > 0) { // Get the root type int pathPointer = 0; EntityTypeCache entityType = null; while (entityType == null && pathPointer < idParts.Count()) { string item = idParts[pathPointer]; string[] itemParts = item.Split(new char[] { '^' }, StringSplitOptions.RemoveEmptyEntries); string itemType = itemParts.Length > 1 ? itemParts[1] : item; entityType = EntityTypeCache.Read(itemType, false); pathPointer++; } if (entityType != null) { Type type = entityType.GetEntityType(); // Traverse the Property path while (idParts.Count > pathPointer) { var childProperty = type.GetProperty(idParts[pathPointer]); if (childProperty != null) { type = childProperty.PropertyType; if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ICollection <>) && type.GetGenericArguments().Length == 1) { type = type.GetGenericArguments()[0]; } } pathPointer++; } entityType = EntityTypeCache.Read(type); // Add the tree view items foreach (var propInfo in type.GetProperties()) { if (propInfo.GetCustomAttributes(typeof(System.Runtime.Serialization.DataMemberAttribute)).Count() > 0) { var treeViewItem = new TreeViewItem { Id = id + "|" + propInfo.Name, Name = propInfo.Name.SplitCase() }; Type propertyType = propInfo.PropertyType; if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(ICollection <>) && propertyType.GetGenericArguments().Length == 1) { treeViewItem.Name += " (Collection)"; propertyType = propertyType.GetGenericArguments()[0]; } bool hasChildren = false; if (EntityTypeCache.Read(propertyType.FullName, false) != null) { foreach (var childPropInfo in propertyType.GetProperties()) { if (childPropInfo.GetCustomAttributes(typeof(System.Runtime.Serialization.DataMemberAttribute)).Count() > 0) { hasChildren = true; break; } } } treeViewItem.HasChildren = hasChildren; items.Add(treeViewItem); } } if (entityType.IsEntity) { foreach (Rock.Model.Attribute attribute in new AttributeService(new Rock.Data.RockContext()).GetByEntityTypeId(entityType.Id)) { // Only include attributes without a qualifier (since we don't have a specific instance of this entity type) if (string.IsNullOrEmpty(attribute.EntityTypeQualifierColumn) && string.IsNullOrEmpty(attribute.EntityTypeQualifierValue) && attribute.IsAuthorized(Authorization.VIEW, person)) { items.Add(new TreeViewItem { Id = id + "|" + attribute.Key, Name = attribute.Name }); } } } } } break; } } return(items.OrderBy(i => i.Name).AsQueryable()); }
/// <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) { if (Page.IsValid) { if (ViewMode == VIEW_MODE_EDIT) { int personEntityTypeId = EntityTypeCache.Read(typeof(Person)).Id; var rockContext = new RockContext(); rockContext.WrapTransaction(() => { var changes = new List <string>(); foreach (int attributeId in AttributeList) { var attribute = AttributeCache.Read(attributeId); if (Person != null && ViewMode == VIEW_MODE_EDIT && attribute.IsAuthorized(Authorization.EDIT, CurrentPerson)) { Control attributeControl = fsAttributes.FindControl(string.Format("attribute_field_{0}", attribute.Id)); if (attributeControl != null) { string originalValue = Person.GetAttributeValue(attribute.Key); string newValue = attribute.FieldType.Field.GetEditValue(attributeControl, attribute.QualifierValues); Rock.Attribute.Helper.SaveAttributeValue(Person, attribute, newValue, rockContext); // Check for changes to write to history if ((originalValue ?? string.Empty).Trim() != (newValue ?? string.Empty).Trim()) { string formattedOriginalValue = string.Empty; if (!string.IsNullOrWhiteSpace(originalValue)) { formattedOriginalValue = attribute.FieldType.Field.FormatValue(null, originalValue, attribute.QualifierValues, false); } string formattedNewValue = string.Empty; if (!string.IsNullOrWhiteSpace(newValue)) { formattedNewValue = attribute.FieldType.Field.FormatValue(null, newValue, attribute.QualifierValues, false); } History.EvaluateChange(changes, attribute.Name, formattedOriginalValue, formattedNewValue); } } } } if (changes.Any()) { HistoryService.SaveChanges(rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), Person.Id, changes); } }); } else if (ViewMode == VIEW_MODE_ORDER) { // Split and deliminate again to remove trailing delimiter var attributeOrder = hfAttributeOrder.Value.SplitDelimitedValues().ToList().AsDelimited(","); SetUserPreference(_preferenceKey, attributeOrder); BindAttributes(); } ViewMode = VIEW_MODE_VIEW; CreateControls(false); } }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { BlockTypeService blockTypeService = new BlockTypeService(new RockContext()); SortProperty sortProperty = gBlockTypes.SortProperty; var blockTypes = blockTypeService.Queryable(); // Exclude system blocks if checked. if (!string.IsNullOrWhiteSpace(gfSettings.GetUserPreference("Exclude System"))) { blockTypes = blockTypes.Where(b => b.IsSystem == false); } // Filter by Name string nameFilter = gfSettings.GetUserPreference("Name"); if (!string.IsNullOrEmpty(nameFilter.Trim())) { blockTypes = blockTypes.Where(b => b.Name.Contains(nameFilter.Trim())); } // Filter by Path string path = gfSettings.GetUserPreference("Path"); if (!string.IsNullOrEmpty(path.Trim())) { blockTypes = blockTypes.Where(b => b.Path.Contains(path.Trim())); } string category = gfSettings.GetUserPreference("Category"); if (!string.IsNullOrWhiteSpace(category)) { blockTypes = blockTypes.Where(b => b.Category == category); } var selectQry = blockTypes.Select(a => new { a.Id, a.Name, a.Category, a.Description, a.Path, BlocksCount = a.Blocks.Count(), a.IsSystem }); if (sortProperty != null) { if (sortProperty.Property == "Status") { // special case: See if the file exists and sort by that if (sortProperty.Direction == System.Web.UI.WebControls.SortDirection.Ascending) { gBlockTypes.DataSource = selectQry.ToList().OrderBy(a => System.IO.File.Exists(Request.MapPath(a.Path))).ToList(); } else { gBlockTypes.DataSource = selectQry.ToList().OrderBy(a => !System.IO.File.Exists(Request.MapPath(a.Path))).ToList(); } } else { gBlockTypes.DataSource = selectQry.Sort(sortProperty).ToList(); } } else { gBlockTypes.DataSource = selectQry.OrderBy(b => b.Name).ToList(); } gBlockTypes.EntityTypeId = EntityTypeCache.Read <Rock.Model.BlockType>().Id; gBlockTypes.DataBind(); }
public override void Send(Rock.Model.Communication communication) { int mediumEntityId = EntityTypeCache.Read(Rock.SystemGuid.EntityType.COMMUNICATION_MEDIUM_EMAIL.AsGuid())?.Id ?? 0; Send(communication, mediumEntityId, null); }
/// <summary> /// Binds the group members grid. /// </summary> protected void BindGroupMembersGrid(bool selectAll = false) { if (_group != null) { pnlGroupMembers.Visible = true; lHeading.Text = string.Format("{0} {1}", _group.GroupType.GroupTerm, _group.GroupType.GroupMemberTerm.Pluralize()); if (_group.GroupType.Roles.Any()) { nbRoleWarning.Visible = false; rFilter.Visible = true; gGroupMembers.Visible = true; var rockContext = new RockContext(); GroupMemberService groupMemberService = new GroupMemberService(rockContext); var qry = groupMemberService.Queryable("Person,GroupRole", true).AsNoTracking() .Where(m => m.GroupId == _group.Id); // Filter by First Name string firstName = tbFirstName.Text; if (!string.IsNullOrWhiteSpace(firstName)) { qry = qry.Where(m => m.Person.FirstName.StartsWith(firstName) || m.Person.NickName.StartsWith(firstName)); } // Filter by Last Name string lastName = tbLastName.Text; if (!string.IsNullOrWhiteSpace(lastName)) { qry = qry.Where(m => m.Person.LastName.StartsWith(lastName)); } // Filter by role var validGroupTypeRoles = _group.GroupType.Roles.Select(r => r.Id).ToList(); var roles = new List <int>(); foreach (var roleId in cblRole.SelectedValues.AsIntegerList()) { if (validGroupTypeRoles.Contains(roleId)) { roles.Add(roleId); } } if (roles.Any()) { qry = qry.Where(m => roles.Contains(m.GroupRoleId)); } // Filter by Group Member Status var statuses = new List <GroupMemberStatus>(); foreach (string status in cblGroupMemberStatus.SelectedValues) { if (!string.IsNullOrWhiteSpace(status)) { statuses.Add(status.ConvertToEnum <GroupMemberStatus>()); } } if (statuses.Any()) { qry = qry.Where(m => statuses.Contains(m.GroupMemberStatus)); } // Filter by Campus if (cpCampusFilter.SelectedCampusId.HasValue) { Guid familyGuid = new Guid(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY); int campusId = cpCampusFilter.SelectedCampusId.Value; var qryFamilyMembersForCampus = new GroupMemberService(rockContext).Queryable().Where(a => a.Group.GroupType.Guid == familyGuid && a.Group.CampusId == campusId); qry = qry.Where(a => qryFamilyMembersForCampus.Any(f => f.PersonId == a.PersonId)); } // Filter query by any configured attribute filters if (AvailableAttributes != null && AvailableAttributes.Any()) { var attributeValueService = new AttributeValueService(rockContext); var parameterExpression = attributeValueService.ParameterExpression; foreach (var attribute in AvailableAttributes) { var filterControl = phAttributeFilters.FindControl("filter_" + attribute.Id.ToString()); if (filterControl != null) { var filterValues = attribute.FieldType.Field.GetFilterValues(filterControl, attribute.QualifierValues, Rock.Reporting.FilterMode.SimpleFilter); var expression = attribute.FieldType.Field.AttributeFilterExpression(attribute.QualifierValues, filterValues, parameterExpression); if (expression != null) { var attributeValues = attributeValueService .Queryable() .Where(v => v.Attribute.Id == attribute.Id); attributeValues = attributeValues.Where(parameterExpression, expression, null); qry = qry.Where(w => attributeValues.Select(v => v.EntityId).Contains(w.Id)); } } } } _inactiveStatus = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE); SortProperty sortProperty = gGroupMembers.SortProperty; bool hasGroupRequirements = new GroupRequirementService(rockContext).Queryable().Where(a => a.GroupId == _group.Id).Any(); // If there are group requirements that that member doesn't meet, show an icon in the grid bool includeWarnings = false; var groupMemberIdsThatLackGroupRequirements = new GroupService(rockContext).GroupMembersNotMeetingRequirements(_group.Id, includeWarnings).Select(a => a.Key.Id); List <GroupMember> groupMembersList = null; if (sortProperty != null) { groupMembersList = qry.Sort(sortProperty).ToList(); } else { groupMembersList = qry.OrderBy(a => a.GroupRole.Order).ThenBy(a => a.Person.LastName).ThenBy(a => a.Person.FirstName).ToList(); } // Since we're not binding to actual group member list, but are using AttributeField columns, // we need to save the workflows into the grid's object list gGroupMembers.ObjectList = new Dictionary <string, object>(); groupMembersList.ForEach(m => gGroupMembers.ObjectList.Add(m.Id.ToString(), m)); gGroupMembers.EntityTypeId = EntityTypeCache.Read(Rock.SystemGuid.EntityType.GROUP_MEMBER.AsGuid()).Id; var homePhoneType = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME); var cellPhoneType = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE); // If exporting to Excel, the selectAll option will be true, and home location should be calculated var homeLocations = new Dictionary <int, Location>(); if (selectAll) { foreach (var m in groupMembersList) { homeLocations.Add(m.Id, m.Person.GetHomeLocation(rockContext)); } } var groupMemberIds = groupMembersList.Select(m => m.Id).ToList(); // Get all the group members with any associated registrations _groupMembersWithRegistrations = new RegistrationRegistrantService(rockContext) .Queryable().AsNoTracking() .Where(r => r.Registration != null && r.Registration.RegistrationInstance != null && r.GroupMemberId.HasValue && groupMemberIds.Contains(r.GroupMemberId.Value)) .ToList() .GroupBy(r => r.GroupMemberId.Value) .Select(g => new { GroupMemberId = g.Key, Registrations = g.ToList() .Select(r => new { Id = r.Registration.Id, Name = r.Registration.RegistrationInstance.Name }) .ToDictionary(r => r.Id, r => r.Name) }) .ToDictionary(r => r.GroupMemberId, r => r.Registrations); var registrationField = gGroupMembers.ColumnsOfType <RockTemplateFieldUnselected>().FirstOrDefault(); if (registrationField != null) { registrationField.Visible = _groupMembersWithRegistrations.Any(); } var connectionStatusField = gGroupMembers.ColumnsOfType <DefinedValueField>().FirstOrDefault(a => a.DataField == "ConnectionStatusValueId"); if (connectionStatusField != null) { connectionStatusField.Visible = _group.GroupType.ShowConnectionStatus; } string photoFormat = "<div class=\"photo-icon photo-round photo-round-xs pull-left margin-r-sm js-person-popover\" personid=\"{0}\" data-original=\"{1}&w=50\" style=\"background-image: url( '{2}' ); background-size: cover; background-repeat: no-repeat;\"></div>"; gGroupMembers.DataSource = groupMembersList.Select(m => new { m.Id, m.Guid, m.PersonId, m.Person.NickName, m.Person.LastName, Name = (selectAll ? m.Person.LastName + ", " + m.Person.NickName : string.Format(photoFormat, m.PersonId, m.Person.PhotoUrl, ResolveUrl("~/Assets/Images/person-no-photo-male.svg")) + m.Person.NickName + " " + m.Person.LastName + (hasGroupRequirements && groupMemberIdsThatLackGroupRequirements.Contains(m.Id) ? " <i class='fa fa-exclamation-triangle text-warning'></i>" : string.Empty) + (!string.IsNullOrEmpty(m.Note) ? " <i class='fa fa-file-text-o text-info'></i>" : string.Empty)), m.Person.ConnectionStatusValueId, Email = m.Person.Email, HomePhone = selectAll && homePhoneType != null ? m.Person.PhoneNumbers .Where(p => p.NumberTypeValueId.HasValue && p.NumberTypeValueId.Value == homePhoneType.Id) .Select(p => p.NumberFormatted) .FirstOrDefault() : string.Empty, CellPhone = selectAll && cellPhoneType != null ? m.Person.PhoneNumbers .Where(p => p.NumberTypeValueId.HasValue && p.NumberTypeValueId.Value == cellPhoneType.Id) .Select(p => p.NumberFormatted) .FirstOrDefault() : string.Empty, HomeAddress = homeLocations.ContainsKey(m.Id) && homeLocations[m.Id] != null ? homeLocations[m.Id].FormattedAddress : string.Empty, Latitude = homeLocations.ContainsKey(m.Id) && homeLocations[m.Id] != null ? homeLocations[m.Id].Latitude : (double?)null, Longitude = homeLocations.ContainsKey(m.Id) && homeLocations[m.Id] != null ? homeLocations[m.Id].Longitude : (double?)null, GroupRole = m.GroupRole.Name, m.GroupMemberStatus, RecordStatusValueId = m.Person.RecordStatusValueId, IsDeceased = m.Person.IsDeceased }).ToList(); gGroupMembers.DataBind(); } else { nbRoleWarning.Text = string.Format( "{0} cannot be added to this {1} because the '{2}' group type does not have any roles defined.", _group.GroupType.GroupMemberTerm.Pluralize(), _group.GroupType.GroupTerm, _group.GroupType.Name); nbRoleWarning.Visible = true; rFilter.Visible = false; gGroupMembers.Visible = false; } } else { pnlGroupMembers.Visible = false; } }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { var rockContext = new RockContext(); var communications = new CommunicationService(rockContext) .Queryable().AsNoTracking() .Where(c => c.Status != CommunicationStatus.Transient); string subject = tbSubject.Text; if (!string.IsNullOrWhiteSpace(subject)) { communications = communications.Where(c => c.Subject.Contains(subject)); } Guid?entityTypeGuid = cpMedium.SelectedValue.AsGuidOrNull(); if (entityTypeGuid.HasValue) { communications = communications.Where(c => c.MediumEntityType != null && c.MediumEntityType.Guid.Equals(entityTypeGuid.Value)); } string status = ddlStatus.SelectedValue; if (!string.IsNullOrWhiteSpace(status)) { var communicationStatus = (CommunicationStatus)System.Enum.Parse(typeof(CommunicationStatus), status); communications = communications.Where(c => c.Status == communicationStatus); } if (canApprove) { if (ppSender.PersonId.HasValue) { communications = communications .Where(c => c.SenderPersonAlias != null && c.SenderPersonAlias.PersonId == ppSender.PersonId.Value); } } else { // If can't approve, only show current person's communications communications = communications .Where(c => c.SenderPersonAlias != null && c.SenderPersonAlias.PersonId == CurrentPersonId); } if (drpDates.LowerValue.HasValue) { communications = communications.Where(a => a.CreatedDateTime >= drpDates.LowerValue.Value); } if (drpDates.UpperValue.HasValue) { DateTime upperDate = drpDates.UpperValue.Value.Date.AddDays(1); communications = communications.Where(a => a.CreatedDateTime < upperDate); } string content = tbContent.Text; if (!string.IsNullOrWhiteSpace(content)) { communications = communications.Where(c => c.MediumDataJson.Contains(content)); } var recipients = new CommunicationRecipientService(rockContext).Queryable(); var queryable = communications .Select(c => new CommunicationItem { Id = c.Id, MediumEntityTypeId = c.MediumEntityTypeId, MediumName = c.MediumEntityTypeId.HasValue ? c.MediumEntityType.FriendlyName : null, Subject = c.Subject, CreatedDateTime = c.CreatedDateTime, Sender = c.SenderPersonAlias != null ? c.SenderPersonAlias.Person : null, ReviewedDateTime = c.ReviewedDateTime, Reviewer = c.ReviewerPersonAlias != null ? c.ReviewerPersonAlias.Person : null, Status = c.Status, Recipients = recipients.Where(r => r.CommunicationId == c.Id).Count(), PendingRecipients = recipients.Where(r => r.CommunicationId == c.Id && r.Status == CommunicationRecipientStatus.Pending).Count(), CancelledRecipients = recipients.Where(r => r.CommunicationId == c.Id && r.Status == CommunicationRecipientStatus.Cancelled).Count(), FailedRecipients = recipients.Where(r => r.CommunicationId == c.Id && r.Status == CommunicationRecipientStatus.Failed).Count(), DeliveredRecipients = recipients.Where(r => r.CommunicationId == c.Id && (r.Status == CommunicationRecipientStatus.Delivered || r.Status == CommunicationRecipientStatus.Opened)).Count(), OpenedRecipients = recipients.Where(r => r.CommunicationId == c.Id && r.Status == CommunicationRecipientStatus.Opened).Count() }); var sortProperty = gCommunication.SortProperty; if (sortProperty != null) { queryable = queryable.Sort(sortProperty); } else { queryable = queryable.OrderByDescending(c => c.CreatedDateTime); } gCommunication.EntityTypeId = EntityTypeCache.Read <Rock.Model.Communication>().Id; gCommunication.SetLinqDataSource(queryable); gCommunication.DataBind(); }
protected void AddDynamicControls(ContentChannel channel) { // Remove all columns gContentChannelItems.Columns.Clear(); phAttributeFilters.Controls.Clear(); if (channel != null) { // Add Reorder column var reorderField = new ReorderField(); gContentChannelItems.Columns.Add(reorderField); // Add Title column var titleField = new BoundField(); titleField.DataField = "Title"; titleField.HeaderText = "Title"; titleField.SortExpression = "Title"; gContentChannelItems.Columns.Add(titleField); // Add Attribute columns int entityTypeId = EntityTypeCache.Read(typeof(Rock.Model.ContentChannelItem)).Id; string channelId = channel.Id.ToString(); string channelTypeId = channel.ContentChannelTypeId.ToString(); foreach (var attribute in AvailableAttributes) { var control = attribute.FieldType.Field.FilterControl(attribute.QualifierValues, "filter_" + attribute.Id.ToString(), false, Rock.Reporting.FilterMode.SimpleFilter); if (control != null) { if (control is IRockControl) { var rockControl = (IRockControl)control; rockControl.Label = attribute.Name; rockControl.Help = attribute.Description; phAttributeFilters.Controls.Add(control); } else { var wrapper = new RockControlWrapper(); wrapper.ID = control.ID + "_wrapper"; wrapper.Label = attribute.Name; wrapper.Controls.Add(control); phAttributeFilters.Controls.Add(wrapper); } string savedValue = gfFilter.GetUserPreference(MakeKeyUniqueToChannel(channel.Id, attribute.Key)); if (!string.IsNullOrWhiteSpace(savedValue)) { try { var values = JsonConvert.DeserializeObject <List <string> >(savedValue); attribute.FieldType.Field.SetFilterValues(control, attribute.QualifierValues, values); } catch { // intentionally ignore } } } string dataFieldExpression = attribute.Key; bool columnExists = gContentChannelItems.Columns.OfType <AttributeField>().FirstOrDefault(a => a.DataField.Equals(dataFieldExpression)) != null; if (!columnExists) { AttributeField boundField = new AttributeField(); boundField.DataField = dataFieldExpression; boundField.AttributeId = attribute.Id; boundField.HeaderText = attribute.Name; boundField.ItemStyle.HorizontalAlign = attribute.FieldType.Field.AlignValue; gContentChannelItems.Columns.Add(boundField); } } if (channel.ContentChannelType.IncludeTime) { // Add Start column var startField = new DateTimeField(); startField.DataField = "StartDateTime"; startField.HeaderText = channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Date"; startField.SortExpression = "StartDateTime"; gContentChannelItems.Columns.Add(startField); // Expire column if (channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange) { var expireField = new DateTimeField(); expireField.DataField = "ExpireDateTime"; expireField.HeaderText = "Expire"; expireField.SortExpression = "ExpireDateTime"; gContentChannelItems.Columns.Add(expireField); } } else { // Add Start column var startField = new DateField(); startField.DataField = "StartDateTime"; startField.HeaderText = channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Date"; startField.SortExpression = "StartDateTime"; gContentChannelItems.Columns.Add(startField); // Expire column if (channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange) { var expireField = new DateField(); expireField.DataField = "ExpireDateTime"; expireField.HeaderText = "Expire"; expireField.SortExpression = "ExpireDateTime"; gContentChannelItems.Columns.Add(expireField); } } // Priority column var priorityField = new BoundField(); priorityField.DataField = "Priority"; priorityField.HeaderText = "Priority"; priorityField.SortExpression = "Priority"; priorityField.DataFormatString = "{0:N0}"; priorityField.ItemStyle.HorizontalAlign = HorizontalAlign.Right; gContentChannelItems.Columns.Add(priorityField); // Status column if (channel.RequiresApproval) { var statusField = new BoundField(); gContentChannelItems.Columns.Add(statusField); statusField.DataField = "Status"; statusField.HeaderText = "Status"; statusField.SortExpression = "Status"; statusField.HtmlEncode = false; } // Add occurrences Count column var occurrencesField = new BoolField(); occurrencesField.DataField = "Occurrences"; occurrencesField.HeaderText = "Event Occurrences"; gContentChannelItems.Columns.Add(occurrencesField); // Add Created By column var createdByPersonNameField = new BoundField(); createdByPersonNameField.DataField = "CreatedByPersonName"; createdByPersonNameField.HeaderText = "Created By"; createdByPersonNameField.HtmlEncode = false; gContentChannelItems.Columns.Add(createdByPersonNameField); bool canEditChannel = channel.IsAuthorized(Rock.Security.Authorization.EDIT, CurrentPerson); gContentChannelItems.Actions.ShowAdd = canEditChannel; gContentChannelItems.IsDeleteEnabled = canEditChannel; if (canEditChannel) { var deleteField = new DeleteField(); gContentChannelItems.Columns.Add(deleteField); deleteField.Click += gContentChannelItems_Delete; } } }
/// <summary> /// Loads the schedules /// </summary> private void LoadScheduleDropdowns() { var scheduleEntityType = EntityTypeCache.Read(typeof(Schedule)); var currentSchedule = RockPage.GetCurrentContext(scheduleEntityType) as Schedule; var scheduleIdString = Request.QueryString["scheduleId"]; if (scheduleIdString != null) { var scheduleId = scheduleIdString.AsInteger(); if (currentSchedule == null || currentSchedule.Id != scheduleId) { currentSchedule = SetScheduleContext(scheduleId, false); } } if (currentSchedule != null) { var mergeObjects = new Dictionary <string, object>(); mergeObjects.Add("ScheduleName", currentSchedule.Name); lCurrentScheduleSelection.Text = GetAttributeValue("ScheduleCurrentItemTemplate").ResolveMergeFields(mergeObjects); _currentScheduleText = GetAttributeValue("ScheduleCurrentItemTemplate").ResolveMergeFields(mergeObjects); } else { lCurrentScheduleSelection.Text = GetAttributeValue("NoScheduleText"); _currentScheduleText = GetAttributeValue("NoScheduleText"); } var schedules = new List <ScheduleItem>(); if (GetAttributeValue("ScheduleGroup") != null) { var selectedSchedule = GetAttributeValue("ScheduleGroup"); var selectedScheduleList = selectedSchedule.Split(',').AsGuidList(); schedules.AddRange(new ScheduleService(new RockContext()).Queryable() .Where(a => selectedScheduleList.Contains(a.Guid)) .Select(a => new ScheduleItem { Name = a.Name, Id = a.Id }) .OrderBy(s => s.Name) .ToList() ); } var formattedSchedule = new Dictionary <int, string>(); // run lava on each campus foreach (var schedule in schedules) { var mergeObjects = new Dictionary <string, object>(); mergeObjects.Clear(); mergeObjects.Add("ScheduleName", schedule.Name); schedule.Name = GetAttributeValue("ScheduleDropdownItemTemplate").ResolveMergeFields(mergeObjects); } // check if the schedule can be unselected if (!string.IsNullOrEmpty(GetAttributeValue("ScheduleClearSelectionText"))) { var blankCampus = new ScheduleItem { Name = GetAttributeValue("ScheduleClearSelectionText"), Id = Rock.Constants.All.Id }; schedules.Insert(0, blankCampus); } rptSchedules.DataSource = schedules; rptSchedules.DataBind(); }
/// <summary> /// Binds the grid. /// </summary> /// <param name="report">The report.</param> /// <param name="gReport">The g report.</param> /// <param name="currentPerson">The current person.</param> /// <param name="dataViewFilterOverrides">The data view filter overrides.</param> /// <param name="databaseTimeoutSeconds">The database timeout seconds.</param> /// <param name="isCommunication">if set to <c>true</c> [is communication].</param> /// <param name="errorMessage">The error message.</param> public static void BindGrid(Report report, Grid gReport, Person currentPerson, DataViewFilterOverrides dataViewFilterOverrides, int?databaseTimeoutSeconds, bool isCommunication, out string errorMessage) { errorMessage = null; if (report != null) { var errors = new List <string>(); if (!report.EntityTypeId.HasValue) { gReport.Visible = false; return; } var rockContext = new RockContext(); if (!report.IsAuthorized(Authorization.VIEW, currentPerson)) { gReport.Visible = false; return; } Type entityType = EntityTypeCache.Read(report.EntityTypeId.Value, rockContext).GetEntityType(); if (entityType == null) { errorMessage = string.Format("Unable to determine entityType for {0}", report.EntityType); return; } gReport.EntityTypeId = report.EntityTypeId; bool isPersonDataSet = report.EntityTypeId == EntityTypeCache.Read(typeof(Rock.Model.Person), true, rockContext).Id; if (isPersonDataSet) { gReport.PersonIdField = "Id"; gReport.DataKeyNames = new string[] { "Id" }; } else { gReport.PersonIdField = null; } if (report.EntityTypeId.HasValue) { gReport.RowItemText = EntityTypeCache.Read(report.EntityTypeId.Value, rockContext).FriendlyName; } List <EntityField> entityFields = Rock.Reporting.EntityHelper.GetEntityFields(entityType, true, false); var selectedEntityFields = new Dictionary <int, EntityField>(); var selectedAttributes = new Dictionary <int, AttributeCache>(); var selectedComponents = new Dictionary <int, ReportField>(); // if there is a selectField, keep it to preserve which items are checked var selectField = gReport.Columns.OfType <SelectField>().FirstOrDefault(); gReport.Columns.Clear(); int columnIndex = 0; if (!string.IsNullOrWhiteSpace(gReport.PersonIdField)) { // if we already had a selectField, use it (to preserve checkbox state) gReport.Columns.Add(selectField ?? new SelectField()); columnIndex++; } var reportFieldSortExpressions = new Dictionary <Guid, string>(); gReport.CommunicateMergeFields = new List <string>(); gReport.CommunicationRecipientPersonIdFields = new List <string>(); foreach (var reportField in report.ReportFields.OrderBy(a => a.ColumnOrder)) { bool mergeField = reportField.IsCommunicationMergeField.HasValue && reportField.IsCommunicationMergeField.Value; bool recipientField = reportField.IsCommunicationRecipientField.HasValue && reportField.IsCommunicationRecipientField.Value; columnIndex++; if (reportField.ReportFieldType == ReportFieldType.Property) { var entityField = entityFields.FirstOrDefault(a => a.Name == reportField.Selection); if (entityField != null) { selectedEntityFields.Add(columnIndex, entityField); BoundField boundField = entityField.GetBoundFieldType(); boundField.DataField = string.Format("Entity_{0}_{1}", entityField.Name, columnIndex); boundField.HeaderText = string.IsNullOrWhiteSpace(reportField.ColumnHeaderText) ? entityField.Title : reportField.ColumnHeaderText; boundField.SortExpression = boundField.DataField; reportFieldSortExpressions.AddOrReplace(reportField.Guid, boundField.SortExpression); boundField.Visible = reportField.ShowInGrid; gReport.Columns.Add(boundField); if (mergeField) { gReport.CommunicateMergeFields.Add($"{boundField.DataField}|{boundField.HeaderText.RemoveSpecialCharacters()}"); } if (recipientField) { gReport.CommunicationRecipientPersonIdFields.Add(boundField.DataField); } } } else if (reportField.ReportFieldType == ReportFieldType.Attribute) { Guid?attributeGuid = reportField.Selection.AsGuidOrNull(); if (attributeGuid.HasValue) { var attribute = AttributeCache.Read(attributeGuid.Value, rockContext); if (attribute != null) { selectedAttributes.Add(columnIndex, attribute); BoundField boundField; if (attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.BOOLEAN.AsGuid())) { boundField = new BoolField(); } else if (attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.DEFINED_VALUE.AsGuid())) { boundField = new DefinedValueField(); } else { boundField = new CallbackField(); boundField.HtmlEncode = false; (boundField as CallbackField).OnFormatDataValue += (sender, e) => { string resultHtml = null; if (e.DataValue != null) { bool condensed = true; resultHtml = attribute.FieldType.Field.FormatValueAsHtml(gReport, e.DataValue.ToString(), attribute.QualifierValues, condensed); } e.FormattedValue = resultHtml ?? string.Empty; }; } boundField.DataField = string.Format("Attribute_{0}_{1}", attribute.Id, columnIndex); boundField.HeaderText = string.IsNullOrWhiteSpace(reportField.ColumnHeaderText) ? attribute.Name : reportField.ColumnHeaderText; boundField.SortExpression = boundField.DataField; reportFieldSortExpressions.AddOrReplace(reportField.Guid, boundField.SortExpression); if (attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.INTEGER.AsGuid()) || attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.DATE.AsGuid()) || attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.FILTER_DATE.AsGuid())) { boundField.HeaderStyle.HorizontalAlign = HorizontalAlign.Right; boundField.ItemStyle.HorizontalAlign = HorizontalAlign.Right; } boundField.Visible = reportField.ShowInGrid; gReport.Columns.Add(boundField); if (mergeField) { gReport.CommunicateMergeFields.Add($"{boundField.DataField}|{boundField.HeaderText.RemoveSpecialCharacters()}"); } if (recipientField) { gReport.CommunicationRecipientPersonIdFields.Add(boundField.DataField); } } } } else if (reportField.ReportFieldType == ReportFieldType.DataSelectComponent) { selectedComponents.Add(columnIndex, reportField); DataSelectComponent selectComponent = DataSelectContainer.GetComponent(reportField.DataSelectComponentEntityType.Name); if (selectComponent != null) { try { DataControlField columnField = selectComponent.GetGridField(entityType, reportField.Selection ?? string.Empty); string fieldId = $"{selectComponent.ColumnPropertyName}_{columnIndex}"; if (columnField is BoundField) { (columnField as BoundField).DataField = $"Data_{fieldId}"; var customSortProperties = selectComponent.SortProperties(reportField.Selection ?? string.Empty); bool sortReversed = selectComponent.SortReversed(reportField.Selection ?? string.Empty); if (customSortProperties != null) { if (customSortProperties == string.Empty) { // disable sorting if customSortExpression set to string.empty columnField.SortExpression = string.Empty; } else { columnField.SortExpression = customSortProperties.Split(',').Select(a => string.Format("Sort_{0}_{1}", a, columnIndex)).ToList().AsDelimited(","); } } else { // use default sorting if customSortExpression was null columnField.SortExpression = (columnField as BoundField).DataField; } if (sortReversed == true && !string.IsNullOrWhiteSpace(columnField.SortExpression)) { columnField.SortExpression = columnField.SortExpression + " DESC"; } } columnField.HeaderText = string.IsNullOrWhiteSpace(reportField.ColumnHeaderText) ? selectComponent.ColumnHeaderText : reportField.ColumnHeaderText; if (!string.IsNullOrEmpty(columnField.SortExpression)) { reportFieldSortExpressions.AddOrReplace(reportField.Guid, columnField.SortExpression); } columnField.Visible = reportField.ShowInGrid; gReport.Columns.Add(columnField); if (mergeField) { gReport.CommunicateMergeFields.Add($"Data_{fieldId}|{columnField.HeaderText.RemoveSpecialCharacters()}"); } if (recipientField) { string fieldName = (selectComponent is IRecipientDataSelect) ? $"Recipient_{fieldId}" : $"Data_{fieldId}"; gReport.CommunicationRecipientPersonIdFields.Add(fieldName); } } catch (Exception ex) { ExceptionLogService.LogException(ex, HttpContext.Current); errors.Add(string.Format("{0} - {1}", selectComponent, ex.Message)); } } } } // if no fields are specified, show the default fields (Previewable/All) for the EntityType var dataColumns = gReport.Columns.OfType <object>().Where(a => a.GetType() != typeof(SelectField)); if (dataColumns.Count() == 0) { // show either the Previewable Columns or all (if there are no previewable columns) bool showAllColumns = !entityFields.Any(a => a.FieldKind == FieldKind.Property && a.IsPreviewable); foreach (var entityField in entityFields.Where(a => a.FieldKind == FieldKind.Property)) { columnIndex++; selectedEntityFields.Add(columnIndex, entityField); BoundField boundField = entityField.GetBoundFieldType(); boundField.DataField = string.Format("Entity_{0}_{1}", entityField.Name, columnIndex); boundField.HeaderText = entityField.Name; boundField.SortExpression = boundField.DataField; boundField.Visible = showAllColumns || entityField.IsPreviewable; gReport.Columns.Add(boundField); } } try { gReport.Visible = true; gReport.ExportFilename = report.Name; SortProperty sortProperty = gReport.SortProperty; if (sortProperty == null) { var reportSort = new SortProperty(); var sortColumns = new Dictionary <string, SortDirection>(); foreach (var reportField in report.ReportFields.Where(a => a.SortOrder.HasValue).OrderBy(a => a.SortOrder.Value)) { if (reportFieldSortExpressions.ContainsKey(reportField.Guid)) { var sortField = reportFieldSortExpressions[reportField.Guid]; if (!string.IsNullOrWhiteSpace(sortField)) { sortColumns.Add(sortField, reportField.SortDirection); } } } if (sortColumns.Any()) { reportSort.Property = sortColumns.Select(a => a.Key + (a.Value == SortDirection.Descending ? " desc" : string.Empty)).ToList().AsDelimited(","); sortProperty = reportSort; } } var qryErrors = new List <string>(); System.Data.Entity.DbContext reportDbContext; dynamic qry = report.GetQueryable(entityType, selectedEntityFields, selectedAttributes, selectedComponents, sortProperty, dataViewFilterOverrides, databaseTimeoutSeconds ?? 180, isCommunication, out qryErrors, out reportDbContext); errors.AddRange(qryErrors); if (!string.IsNullOrEmpty(report.QueryHint) && reportDbContext is RockContext) { using (new QueryHintScope(reportDbContext as RockContext, report.QueryHint)) { gReport.SetLinqDataSource(qry); } } else { gReport.SetLinqDataSource(qry); } gReport.DataBind(); } catch (Exception ex) { Exception exception = ex; ExceptionLogService.LogException(ex, HttpContext.Current); while (exception != null) { if (exception is System.Data.SqlClient.SqlException) { // if there was a SQL Server Timeout, have the warning be a friendly message about that. if ((exception as System.Data.SqlClient.SqlException).Number == -2) { errorMessage = "This report did not complete in a timely manner. You can try again or adjust the timeout setting of this block."; return; } else { errors.Add(exception.Message); exception = exception.InnerException; } } else { errors.Add(exception.Message); exception = exception.InnerException; } } } if (errors.Any()) { errorMessage = "WARNING: There was a problem with one or more of the report's data components...<br/><br/> " + errors.AsDelimited("<br/>"); } } }
/// <summary> /// Raises the <see cref="E:Init" /> event. /// </summary> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected override void OnInit(EventArgs e) { Rock.Web.UI.DialogPage dialogPage = this.Page as Rock.Web.UI.DialogPage; if (dialogPage != null) { dialogPage.OnSave += new EventHandler <EventArgs>(masterPage_OnSave); } try { int blockId = Convert.ToInt32(PageParameter("BlockId")); Block _block = new BlockService(new RockContext()).Get(blockId); if (_block.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson)) { var blockType = BlockTypeCache.Read(_block.BlockTypeId); if (blockType != null && !blockType.IsInstancePropertiesVerified) { System.Web.UI.Control control = Page.LoadControl(blockType.Path); if (control is RockBlock) { using (var rockContext = new RockContext()) { var rockBlock = control as RockBlock; int?blockEntityTypeId = EntityTypeCache.Read(typeof(Block)).Id; Rock.Attribute.Helper.UpdateAttributes(rockBlock.GetType(), blockEntityTypeId, "BlockTypeId", blockType.Id.ToString(), rockContext); } blockType.IsInstancePropertiesVerified = true; } } phAttributes.Controls.Clear(); phAdvancedAttributes.Controls.Clear(); _block.LoadAttributes(); if (_block.Attributes != null) { foreach (var attributeCategory in Rock.Attribute.Helper.GetAttributeCategories(_block)) { if (attributeCategory.Category != null && attributeCategory.Category.Name.Equals("customsetting", StringComparison.OrdinalIgnoreCase)) { } else if (attributeCategory.Category != null && attributeCategory.Category.Name.Equals("advanced", StringComparison.OrdinalIgnoreCase)) { Rock.Attribute.Helper.AddEditControls( string.Empty, attributeCategory.Attributes.Select(a => a.Key).ToList(), _block, phAdvancedAttributes, string.Empty, !Page.IsPostBack, new List <string>()); } else { Rock.Attribute.Helper.AddEditControls( attributeCategory.Category != null ? attributeCategory.Category.Name : string.Empty, attributeCategory.Attributes.Select(a => a.Key).ToList(), _block, phAttributes, string.Empty, !Page.IsPostBack, new List <string>()); } } } } else { DisplayError("You are not authorized to edit this block", null); } } catch (SystemException ex) { DisplayError(ex.Message, "<pre>" + HttpUtility.HtmlEncode(ex.StackTrace) + "</pre>"); } base.OnInit(e); }
/// <summary> /// Shows the readonly details. /// </summary> /// <param name="dataView">The data view.</param> private void ShowReadonlyDetails(DataView dataView) { SetEditMode(false); hfDataViewId.SetValue(dataView.Id); lReadOnlyTitle.Text = dataView.Name.FormatAsHtmlTitle(); hlblDataViewId.Text = "Id: " + dataView.Id.ToString(); lDescription.Text = dataView.Description; DescriptionList descriptionListMain = new DescriptionList(); if (dataView.EntityType != null) { descriptionListMain.Add("Applies To", dataView.EntityType.FriendlyName); } if (dataView.Category != null) { descriptionListMain.Add("Category", dataView.Category.Name); } if (dataView.TransformEntityType != null) { descriptionListMain.Add("Post-filter Transformation", dataView.TransformEntityType.FriendlyName); } lblMainDetails.Text = descriptionListMain.Html; DescriptionList descriptionListFilters = new DescriptionList(); if (dataView.DataViewFilter != null && dataView.EntityTypeId.HasValue) { var entityTypeCache = EntityTypeCache.Read(dataView.EntityTypeId.Value); if (entityTypeCache != null) { var entityTypeType = entityTypeCache.GetEntityType(); if (entityTypeType != null) { descriptionListFilters.Add("Filter", dataView.DataViewFilter.ToString(entityTypeType)); } } } lFilters.Text = descriptionListFilters.Html; DescriptionList descriptionListDataviews = new DescriptionList(); var dataViewFilterEntityId = EntityTypeCache.Read(typeof(Rock.Reporting.DataFilter.OtherDataViewFilter)).Id; var rockContext = new RockContext(); DataViewService dataViewService = new DataViewService(rockContext); var dataViews = dataViewService.Queryable() .Where(d => d.DataViewFilter.ChildFilters .Any(f => f.Selection == dataView.Id.ToString() && f.EntityTypeId == dataViewFilterEntityId)); StringBuilder sbDataViews = new StringBuilder(); var dataViewDetailPage = GetAttributeValue("DataViewDetailPage"); foreach (var dataview in dataViews) { if (!string.IsNullOrWhiteSpace(dataViewDetailPage)) { sbDataViews.Append("<a href=\"" + LinkedPageUrl("DataViewDetailPage", new Dictionary <string, string>() { { "DataViewId", dataview.Id.ToString() } }) + "\">" + dataview.Name + "</a><br/>"); } else { sbDataViews.Append(dataview.Name + "<br/>"); } } descriptionListDataviews.Add("Data Views", sbDataViews); lDataViews.Text = descriptionListDataviews.Html; DescriptionList descriptionListReports = new DescriptionList(); StringBuilder sbReports = new StringBuilder(); ReportService reportService = new ReportService(rockContext); var reports = reportService.Queryable().Where(r => r.DataViewId == dataView.Id); var reportDetailPage = GetAttributeValue("ReportDetailPage"); foreach (var report in reports) { if (!string.IsNullOrWhiteSpace(reportDetailPage)) { sbReports.Append("<a href=\"" + LinkedPageUrl("ReportDetailPage", new Dictionary <string, string>() { { "ReportId", report.Id.ToString() } }) + "\">" + report.Name + "</a><br/>"); } else { sbReports.Append(report.Name + "<br/>"); } } descriptionListReports.Add("Reports", sbReports); lReports.Text = descriptionListReports.Html; ShowReport(dataView); }
/// <summary> /// Updates a communication model with the user-entered values /// </summary> /// <param name="communicationService">The service.</param> /// <returns></returns> private Rock.Model.Communication UpdateCommunication(RockContext rockContext, Guid templateGuid) { var communicationService = new CommunicationService(rockContext); var communicationAttachmentService = new CommunicationAttachmentService(rockContext); var communicationRecipientService = new CommunicationRecipientService(rockContext); var MediumEntityTypeId = EntityTypeCache.Read("Rock.Communication.Medium.Email").Id; Rock.Model.Communication communication = null; IQueryable <CommunicationRecipient> qryRecipients = null; CommunicationDetails CommunicationData = new CommunicationDetails(); var template = new CommunicationTemplateService(new RockContext()).Get(templateGuid); if (template != null) { CommunicationDetails.Copy(template, CommunicationData); CommunicationData.EmailAttachmentBinaryFileIds = template.EmailAttachmentBinaryFileIds; } if (communication == null) { communication = new Rock.Model.Communication(); communication.Status = CommunicationStatus.Transient; communication.SenderPersonAliasId = CurrentPersonAliasId; communicationService.Add(communication); } if (qryRecipients == null) { qryRecipients = communication.GetRecipientsQry(rockContext); } communication.IsBulkCommunication = false; var medium = MediumContainer.GetComponentByEntityTypeId(MediumEntityTypeId); if (medium != null) { communication.CommunicationType = medium.CommunicationType; } communication.CommunicationTemplateId = template.Id; //GetMediumData(); foreach (var recipient in communication.Recipients) { recipient.MediumEntityTypeId = MediumEntityTypeId; } CommunicationDetails.Copy(CommunicationData, communication); // delete any attachments that are no longer included foreach (var attachment in communication.Attachments.Where(a => !CommunicationData.EmailAttachmentBinaryFileIds.Contains(a.BinaryFileId)).ToList()) { communication.Attachments.Remove(attachment); communicationAttachmentService.Delete(attachment); } // add any new attachments that were added foreach (var attachmentBinaryFileId in CommunicationData.EmailAttachmentBinaryFileIds.Where(a => !communication.Attachments.Any(x => x.BinaryFileId == a))) { communication.AddAttachment(new CommunicationAttachment { BinaryFileId = attachmentBinaryFileId }, CommunicationType.Email); } communication.FutureSendDateTime = null; return(communication); }
/// <summary> /// Binds the grid. /// </summary> /// <param name="grid">The grid.</param> /// <param name="dataView">The data view.</param> /// <returns></returns> private bool BindGrid(Grid grid, DataView dataView, int?fetchRowCount = null) { grid.DataSource = null; // Only respect the ShowResults option if fetchRowCount is null if (!this.ShowResults && fetchRowCount == null) { return(false); } var errorMessages = new List <string>(); if (dataView.EntityTypeId.HasValue) { var cachedEntityType = EntityTypeCache.Read(dataView.EntityTypeId.Value); if (cachedEntityType != null && cachedEntityType.AssemblyName != null) { Type entityType = cachedEntityType.GetEntityType(); if (entityType != null) { try { grid.CreatePreviewColumns(entityType); var qry = dataView.GetQuery(grid.SortProperty, GetAttributeValue("DatabaseTimeout").AsIntegerOrNull() ?? 180, out errorMessages); if (fetchRowCount.HasValue) { qry = qry.Take(fetchRowCount.Value); } grid.SetLinqDataSource(qry.AsNoTracking()); grid.DataBind(); } catch (Exception ex) { this.LogException(ex); Exception exception = ex; while (exception != null) { if (exception is System.Data.SqlClient.SqlException) { // if there was a SQL Server Timeout, have the warning be a friendly message about that. if ((exception as System.Data.SqlClient.SqlException).Number == -2) { nbEditModeMessage.NotificationBoxType = NotificationBoxType.Warning; nbEditModeMessage.Text = "This dataview did not complete in a timely manner. You can try again or adjust the timeout setting of this block."; return(false); } else { errorMessages.Add(exception.Message); exception = exception.InnerException; } } else { errorMessages.Add(exception.Message); exception = exception.InnerException; } } } } } } var errorBox = (grid == gPreview) ? nbPreviewError : nbGridError; if (errorMessages.Any()) { errorBox.NotificationBoxType = NotificationBoxType.Warning; errorBox.Text = "WARNING: There was a problem with one or more of the filters for this data view...<br/><br/> " + errorMessages.AsDelimited("<br/>"); errorBox.Visible = true; } else { errorBox.Visible = false; } if (dataView.EntityTypeId.HasValue) { grid.RowItemText = EntityTypeCache.Read(dataView.EntityTypeId.Value).FriendlyName; } if (grid.DataSource != null) { grid.ExportFilename = dataView.Name; return(true); } return(false); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid(bool isExporting = false) { var txnCountCol = gBatchList.ColumnsOfType <RockBoundField>().FirstOrDefault(c => c.DataField == "TransactionCount"); if (txnCountCol != null) { txnCountCol.HeaderText = isExporting ? "Transaction Count" : "<span class='hidden-print'>Transaction Count</span><span class='visible-print-inline'>Txns</span>"; } var txnAmountCol = gBatchList.ColumnsOfType <CurrencyField>().FirstOrDefault(c => c.DataField == "TransactionAmount"); if (txnAmountCol != null) { txnAmountCol.HeaderText = isExporting ? "Transaction Amount" : "<span class='hidden-print'>Transaction Total</span><span class='visible-print-inline'>Txn Total</span>"; } var accountsCol = gBatchList.ColumnsOfType <RockBoundField>().FirstOrDefault(c => c.HeaderText == "Accounts"); if (accountsCol != null) { accountsCol.DataField = isExporting ? "AccountSummaryText" : "AccountSummaryHtml"; } try { var qry = GetQuery().AsNoTracking(); var batchRowQry = qry.Select(b => new BatchRow { Id = b.Id, BatchStartDateTime = b.BatchStartDateTime.Value, Name = b.Name, AccountingSystemCode = b.AccountingSystemCode, TransactionCount = b.Transactions.Count(), TransactionAmount = b.Transactions.Sum(t => (decimal?)(t.TransactionDetails.Sum(d => (decimal?)d.Amount) ?? 0.0M)) ?? 0.0M, ControlAmount = b.ControlAmount, CampusName = b.Campus != null ? b.Campus.Name : "", Status = b.Status, UnMatchedTxns = b.Transactions.Any(t => !t.AuthorizedPersonAliasId.HasValue), BatchNote = b.Note, AccountSummaryList = b.Transactions .SelectMany(t => t.TransactionDetails) .GroupBy(d => d.AccountId) .Select(s => new BatchAccountSummary { AccountId = s.Key, AccountOrder = s.Max(d => d.Account.Order), AccountName = s.Max(d => d.Account.Name), Amount = s.Sum(d => (decimal?)d.Amount) ?? 0.0M }) .OrderBy(s => s.AccountOrder) .ToList() }); gBatchList.SetLinqDataSource(batchRowQry.AsNoTracking()); gBatchList.EntityTypeId = EntityTypeCache.Read <Rock.Model.FinancialBatch>().Id; gBatchList.DataBind(); RegisterJavaScriptForGridActions(); var qryTransactionDetails = qry.SelectMany(a => a.Transactions).SelectMany(a => a.TransactionDetails); var accountSummaryQry = qryTransactionDetails.GroupBy(a => a.Account).Select(a => new { a.Key.Name, a.Key.Order, TotalAmount = (decimal?)a.Sum(d => d.Amount) }).OrderBy(a => a.Order); var summaryList = accountSummaryQry.ToList(); var grandTotalAmount = (summaryList.Count > 0) ? summaryList.Sum(a => a.TotalAmount ?? 0) : 0; string currencyFormat = GlobalAttributesCache.Value("CurrencySymbol") + "{0:n}"; lGrandTotal.Text = string.Format(currencyFormat, grandTotalAmount); rptAccountSummary.DataSource = summaryList.Select(a => new { a.Name, TotalAmount = string.Format(currencyFormat, a.TotalAmount) }).ToList(); rptAccountSummary.DataBind(); } catch (Exception ex) { nbWarningMessage.Text = ex.Message; } }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid(bool isExporting = false) { int?personId = null; int?givingGroupId = null; bool validRequest = false; if (TargetPerson != null) { personId = TargetPerson.Id; givingGroupId = TargetPerson.GivingGroupId; validRequest = true; } else { int personEntityTypeId = EntityTypeCache.Read("Rock.Model.Person").Id; if (!ContextTypesRequired.Any(e => e.Id == personEntityTypeId)) { validRequest = true; } } if (validRequest) { var rockContext = new RockContext(); var qry = new FinancialScheduledTransactionService(rockContext) .Queryable("ScheduledTransactionDetails,FinancialPaymentDetail.CurrencyTypeValue,FinancialPaymentDetail.CreditCardTypeValue") .AsNoTracking(); // Amount Range var nre = new NumberRangeEditor(); nre.DelimitedValues = gfSettings.GetUserPreference("Amount"); if (nre.LowerValue.HasValue) { qry = qry.Where(t => t.ScheduledTransactionDetails.Sum(d => d.Amount) >= nre.LowerValue.Value); } if (nre.UpperValue.HasValue) { qry = qry.Where(t => t.ScheduledTransactionDetails.Sum(d => d.Amount) <= nre.UpperValue.Value); } // Frequency int?frequencyTypeId = gfSettings.GetUserPreference("Frequency").AsIntegerOrNull(); if (frequencyTypeId.HasValue) { qry = qry.Where(t => t.TransactionFrequencyValueId == frequencyTypeId.Value); } // Date Range var drp = new DateRangePicker(); drp.DelimitedValues = gfSettings.GetUserPreference("Created"); if (drp.LowerValue.HasValue) { qry = qry.Where(t => t.CreatedDateTime >= drp.LowerValue.Value); } if (drp.UpperValue.HasValue) { DateTime upperDate = drp.UpperValue.Value.Date.AddDays(1); qry = qry.Where(t => t.CreatedDateTime < upperDate); } // Account Id int accountId = int.MinValue; if (int.TryParse(gfSettings.GetUserPreference("Account"), out accountId)) { qry = qry.Where(t => t.ScheduledTransactionDetails.Any(d => d.AccountId == accountId)); } // Active only (no filter) if (string.IsNullOrWhiteSpace(gfSettings.GetUserPreference("Include Inactive"))) { qry = qry.Where(t => t.IsActive); } if (givingGroupId.HasValue) { // Person contributes with family qry = qry.Where(t => t.AuthorizedPersonAlias.Person.GivingGroupId == givingGroupId); } else if (personId.HasValue) { // Person contributes individually qry = qry.Where(t => t.AuthorizedPersonAlias.PersonId == personId); } SortProperty sortProperty = gList.SortProperty; if (sortProperty != null) { if (sortProperty.Property == "Amount") { if (sortProperty.Direction == SortDirection.Ascending) { qry = qry.OrderBy(t => t.ScheduledTransactionDetails.Sum(d => (decimal?)d.Amount) ?? 0.00M); } else { qry = qry.OrderByDescending(t => t.ScheduledTransactionDetails.Sum(d => (decimal?)d.Amount) ?? 0.0M); } } else { qry = qry.Sort(sortProperty); } } else { qry = qry .OrderBy(t => t.AuthorizedPersonAlias.Person.LastName) .ThenBy(t => t.AuthorizedPersonAlias.Person.NickName) .ThenByDescending(t => t.IsActive) .ThenByDescending(t => t.StartDate); } _isExporting = isExporting; gList.SetLinqDataSource <FinancialScheduledTransaction>(qry); gList.DataBind(); _isExporting = false; } }
/// <summary> /// Shows the readonly details. /// </summary> /// <param name="dataView">The data view.</param> private void ShowReadonlyDetails(DataView dataView) { SetEditMode(false); hfDataViewId.SetValue(dataView.Id); lReadOnlyTitle.Text = dataView.Name.FormatAsHtmlTitle(); lDescription.Text = dataView.Description; DescriptionList descriptionListMain = new DescriptionList(); if (dataView.EntityType != null) { descriptionListMain.Add("Applies To", dataView.EntityType.FriendlyName); } if (dataView.Category != null) { descriptionListMain.Add("Category", dataView.Category.Name); } if (dataView.TransformEntityType != null) { descriptionListMain.Add("Post-filter Transformation", dataView.TransformEntityType.FriendlyName); } lblMainDetails.Text = descriptionListMain.Html; DescriptionList descriptionListFilters = new DescriptionList(); if (dataView.DataViewFilter != null && dataView.EntityTypeId.HasValue) { descriptionListFilters.Add("Filter", dataView.DataViewFilter.ToString(EntityTypeCache.Read(dataView.EntityTypeId.Value).GetEntityType())); } lFilters.Text = descriptionListFilters.Html; ShowReport(dataView); }
/// <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); // this event gets fired after block settings are updated. it's nice to repaint the screen if these settings would alter it this.BlockUpdated += Block_BlockUpdated; this.AddConfigurationUpdateTrigger(upnlContent); gChildItems.DataKeyNames = new string[] { "Id" }; gChildItems.AllowSorting = false; gChildItems.Actions.ShowAdd = true; gChildItems.IsDeleteEnabled = true; gChildItems.Actions.AddClick += gChildItems_Add; gChildItems.GridRebind += gChildItems_GridRebind; gChildItems.GridReorder += gChildItems_GridReorder; gChildItems.EntityTypeId = EntityTypeCache.Read <ContentChannelItem>().Id; gParentItems.DataKeyNames = new string[] { "Id" }; gParentItems.AllowSorting = true; gParentItems.Actions.ShowAdd = false; gParentItems.IsDeleteEnabled = false; gParentItems.GridRebind += gParentItems_GridRebind; gParentItems.EntityTypeId = EntityTypeCache.Read <ContentChannelItem>().Id; string clearScript = string.Format("$('#{0}').val('false');", hfIsDirty.ClientID); lbSave.OnClientClick = clearScript; lbCancel.OnClientClick = clearScript; string script = string.Format(@" $('#{0} .btn-toggle').click(function (e) {{ e.stopImmediatePropagation(); $(this).find('.btn').removeClass('active'); $(e.target).addClass('active'); $(this).find('a').each(function() {{ if ($(this).hasClass('active')) {{ $('#{1}').val($(this).attr('data-status')); $(this).removeClass('btn-default'); $(this).addClass( $(this).attr('data-active-css') ); }} else {{ $(this).removeClass( $(this).attr('data-active-css') ); $(this).addClass('btn-default'); }} }}); }}); $(document).ready( function() {{ window.addEventListener('beforeunload', function(e) {{ if ( $('#{2}').val() == 'true' ) {{ var timeout = setTimeout( function() {{ $('#updateProgress').hide(); }}, 1000 ); var confirmMessage = 'You have not saved your changes. Are you sure you want to continue?'; ( e || window.event).returnValue = confirmMessage; return confirmMessage; }} return; }}); $('.js-item-details').find('input').blur( function() {{ $('#{2}').val('true') }}); $('.js-item-details').find('textarea').blur( function() {{ $('#{2}').val('true') }}); $('#{3}').on('summernote.blur', function() {{ $('#{2}').val('true') }}); }}); function isDirty() {{ if ( $('#{2}').val() == 'true' ) {{ if ( confirm('You have not saved your changes. Are you sure you want to continue?') ) {{ return false; }} return true; }} return false; }} ", pnlStatus.ClientID, hfStatus.ClientID, hfIsDirty.ClientID, htmlContent.ClientID); ScriptManager.RegisterStartupScript(pnlStatus, pnlStatus.GetType(), "status-script-" + this.BlockId.ToString(), script, true); }
/// <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) { int? entityTypeId = PageParameter("EntityTypeId").AsIntegerOrNull(); string entityTypeName = string.Empty; Type type = null; // Get Entity Type if (entityTypeId.HasValue) { var entityType = EntityTypeCache.Read(entityTypeId.Value); if (entityType != null) { entityTypeName = entityType.FriendlyName; type = entityType.GetEntityType(); } } // Get Entity Id int entityId = PageParameter("EntityId").AsIntegerOrNull() ?? 0; // Get object type if (type != null) { if (entityId == 0) { iSecured = (ISecured)Activator.CreateInstance(type); } else { // Get the context type since this may be for a non-rock core object Type contextType = null; var contexts = Rock.Reflection.SearchAssembly(type.Assembly, typeof(Rock.Data.DbContext)); if (contexts.Any()) { contextType = contexts.First().Value; } else { contextType = typeof(RockContext); } Type serviceType = typeof(Rock.Data.Service <>); Type[] modelType = { type }; Type service = serviceType.MakeGenericType(modelType); var getMethod = service.GetMethod("Get", new Type[] { typeof(int) }); var context = Activator.CreateInstance(contextType); var serviceInstance = Activator.CreateInstance(service, new object[] { context }); iSecured = getMethod.Invoke(serviceInstance, new object[] { entityId }) as ISecured; } var block = iSecured as Rock.Model.Block; if (block != null) { // If the entity is a block, get any actions that were updated or added by the block type using // one or more SecurityActionAttributes. var blockCache = BlockCache.Read(block.Id); if (blockCache != null && blockCache.BlockType != null) { // just in case the block hasn't had its security actions set (they get loaded on page load), set them if (blockCache.BlockType.SecurityActions == null) { blockCache.BlockType.SetSecurityActions(TemplateControl.LoadControl(block.BlockType.Path) as RockBlock); } foreach (var action in blockCache.BlockType.SecurityActions) { if (block.SupportedActions.ContainsKey(action.Key)) { block.SupportedActions[action.Key] = action.Value; } else { block.SupportedActions.Add(action.Key, action.Value); } } } iSecured = block; } if (iSecured != null) { if (iSecured.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson)) { if (iSecured.SupportedActions.Any()) { lActionDescription.Text = iSecured.SupportedActions.FirstOrDefault().Value; } rptActions.DataSource = iSecured.SupportedActions; rptActions.DataBind(); rGrid.DataKeyNames = new string[] { "Id" }; rGrid.GridReorder += new GridReorderEventHandler(rGrid_GridReorder); rGrid.GridRebind += new GridRebindEventHandler(rGrid_GridRebind); rGrid.RowDataBound += new GridViewRowEventHandler(rGrid_RowDataBound); rGrid.ShowHeaderWhenEmpty = false; rGrid.EmptyDataText = string.Empty; rGrid.ShowActionRow = false; rGridParentRules.DataKeyNames = new string[] { "Id" }; rGridParentRules.ShowHeaderWhenEmpty = false; rGridParentRules.EmptyDataText = string.Empty; rGridParentRules.ShowActionRow = false; BindRoles(); string scriptFormat = @" Sys.Application.add_load(function () {{ $('#modal-popup div.modal-header h3 small', window.parent.document).html('{0}'); }}); "; string script = string.Format(scriptFormat, HttpUtility.JavaScriptStringEncode(iSecured.ToString())); this.Page.ClientScript.RegisterStartupScript(this.GetType(), string.Format("set-html-{0}", this.ClientID), script, true); } else { nbMessage.Text = "Unfortunately, you are not able to edit security because you do not belong to a role that has been configured to allow administration of this item."; } } else { nbMessage.Text = "The item you are trying to secure does not exist or does not implement ISecured."; } } else { nbMessage.Text = string.Format("The requested entity type ('{0}') could not be loaded to determine security attributes.", entityTypeName); } base.OnInit(e); }
private List <StatisticRow> GetDataForDateRange(DateTime startDate, DateTime endDate) { var entityTypeGroupGuid = Rock.SystemGuid.EntityType.GROUP.AsGuid(); var groupEntityType = EntityTypeCache.Read(entityTypeGroupGuid); int entityTypeScheduleEntityId = EntityTypeCache.Read(Rock.SystemGuid.EntityType.SCHEDULE.AsGuid()).Id; var rockContext = new RockContext(); rockContext.Database.CommandTimeout = 2600; var metricService = new MetricService(rockContext); var metricValueService = new MetricValueService(rockContext); var scheduleService = new ScheduleService(rockContext); var groupService = new GroupService(rockContext); var attendanceService = new AttendanceService(rockContext); var attributeService = new AttributeService(rockContext); var attributeValueService = new AttributeValueService(rockContext); var metricCategoryGuidList = GetAttributeValue("Metrics").SplitDelimitedValues().AsGuidList(); var attendanceGroupGuidList = GetAttributeValue("AttendanceGroups").SplitDelimitedValues().AsGuidList(); var parentMetricVolunteerGroupGuids = GetAttributeValue("ServiceVolunteerGroups").SplitDelimitedValues().AsGuidList(); var attendanceGroups = groupService.GetByGuids(attendanceGroupGuidList); var parentMetricVolunteerGroups = groupService.GetByGuids(parentMetricVolunteerGroupGuids); var metrics = metricService.GetByGuids(metricCategoryGuidList).Distinct().ToList(); var datasource = new List <StatisticRow>(); var metricVolunteerGroups = new List <Group>(); foreach (var parentMetricVolunteerGroup in parentMetricVolunteerGroups) { metricVolunteerGroups.Add(parentMetricVolunteerGroup); metricVolunteerGroups.AddRange(groupService.GetAllDescendents(parentMetricVolunteerGroup.Id)); } var metricVolunteerGroupIds = metricVolunteerGroups.Select(g => g.Id).ToList(); var metricVolunteerAttendanceData = attendanceService.Queryable().Where(a => a.GroupId.HasValue && metricVolunteerGroupIds.Contains(a.GroupId.Value) && a.StartDateTime >= startDate && a.StartDateTime <= endDate); foreach (var metric in metrics) { var metricData = metricValueService.Queryable("MetricValuePartitions").Where(mv => mv.MetricValueDateTime >= startDate && mv.MetricValueDateTime <= endDate && mv.MetricId == metric.Id && mv.MetricValuePartitions.FirstOrDefault( mvp => mvp.MetricPartition.EntityTypeId == entityTypeScheduleEntityId).EntityId.HasValue ) .GroupBy( mv => mv.MetricValuePartitions.FirstOrDefault( mvp => mvp.MetricPartition.EntityTypeId == entityTypeScheduleEntityId).EntityId.Value) .ToList() .Select(mv => { var service = scheduleService.Get(mv.Key); return(new StatisticRow { ScheduleDateRanges = GetScheduleDateRanges(service, startDate, endDate), RowId = metric.Id + "-" + mv.Key, SortValue = 0, IsTotal = false, Area = metric.Title, Subarea = "Head Count", StartTime = service.WeeklyTimeOfDay ?? service.StartTimeOfDay, DayOfWeek = service.WeeklyDayOfWeek ?? GetLastDayOfWeek(service, startDate, endDate), Service = service.Name, Count = mv.Sum(a => a.YValue).HasValue ? decimal.ToInt32(mv.Sum(a => a.YValue).Value) : 0, MetricNote = mv.Max(a => a.Note), Value = mv }); }) .ToList(); foreach (var row in metricData) { int volunteers = 0; int total = row.Value.Sum(a => a.YValue).HasValue ? decimal.ToInt32(row.Value.Sum(a => a.YValue).Value) : 0; if (metricVolunteerAttendanceData.Any()) { volunteers += row.ScheduleDateRanges.Sum(dateRange => metricVolunteerAttendanceData.Count(a => (a.DidAttend == null || a.DidAttend.Value) && a.StartDateTime >= dateRange.Start && a.StartDateTime <= dateRange.End)); row.Total = total + volunteers; row.Volunteers = volunteers; } } datasource.AddRange(metricData); if (metricData.Count > 1) { var subTotalRow = new StatisticRow { RowId = metric.Id.ToString(), SortValue = 0, IsTotal = true, Area = metric.Title, Subarea = "Head Count", Service = "Sub-Total", Count = metricData.Sum(mv => mv.Count), Volunteers = metricData.Sum(mv => mv.Volunteers), Total = metricData.Sum(mv => mv.Total) }; datasource.Add(subTotalRow); } } var totalRow = new StatisticRow { RowId = "HeadcountTotal", SortValue = 1, IsTotal = true, Area = "Head Count Total", Subarea = "Head Count", Service = "Total", Count = datasource.Where(row => !row.IsTotal).Sum(row => row.Count), Volunteers = datasource.Where(row => !row.IsTotal).Sum(mv => mv.Volunteers), Total = datasource.Where(row => !row.IsTotal).Sum(mv => mv.Total) }; datasource.Add(totalRow); string attributeKeyString = GetAttributeValue("VolunteerGroupAttributeKey"); var volunteerGroupAttributeIdList = attributeService.Queryable() .Where(a => a.Key == attributeKeyString && a.EntityTypeQualifierColumn == "GroupTypeId" && a.EntityTypeId == groupEntityType.Id).Select(a => a.Id); if (volunteerGroupAttributeIdList.Any()) { // Find the groups that attribute values that have the maaping between group (the entityId) and the place they should be grouped with attending (value) var volunteerGroupMappingList = attributeValueService.Queryable().Where(av => volunteerGroupAttributeIdList.Contains(av.AttributeId) && av.Value != null) .ToList() .Select(av => new { VolunteerAttendanceGroupGuid = av.Value.AsGuid(), VolunteerGroupId = av.EntityId }).ToList(); foreach (var attendanceGroup in attendanceGroups) { foreach (var attendanceChildGroup in attendanceGroup.Groups) { var attendanceChildDescendantGroups = groupService.GetAllDescendents(attendanceChildGroup.Id).ToList(); // Include child group in for cases where attendance needs to be mapped to an area not a specific group (production team isn't for a specific children's group -- it's associated with TC kids as a whole) attendanceChildDescendantGroups.Add(attendanceChildGroup); var attendanceChildDescendantGroupIds = attendanceChildDescendantGroups.Select(g => g.Id); var volunteerGroupIds = volunteerGroupMappingList .Where(vgm => attendanceChildDescendantGroups.Any(g => g.Guid == vgm.VolunteerAttendanceGroupGuid)) .Select(vgm => vgm.VolunteerGroupId).ToList(); var volunteerGroupAttendance = attendanceService.Queryable() .Where(a => volunteerGroupIds.Any(id => id != null && id == a.Group.Id) && a.StartDateTime >= startDate && a.StartDateTime <= endDate) .ToList(); var acg = attendanceChildGroup; var childGroupAttendance = attendanceService.Queryable().Where(a => a.GroupId != null && a.StartDateTime >= startDate && a.StartDateTime <= endDate && (a.GroupId == acg.Id || attendanceChildDescendantGroupIds.Any(id => id == a.GroupId)) && (a.DidAttend == null || a.DidAttend.Value)) .GroupBy(a => a.ScheduleId) .ToList(); // ag is created to prevent a warn "Access to foreach variable in closure." var ag = attendanceGroup; var statisticRows = childGroupAttendance.Select(a => { var attendance = a.FirstOrDefault(); var scheduleDateRanges = GetScheduleDateRanges(attendance.Schedule, startDate, endDate); var row = new StatisticRow(); row.RowId = acg.Id + "-" + a.Key; row.SortValue = 2; row.IsTotal = false; row.Area = ag.Name; row.Subarea = acg.Name; row.Service = attendance.Schedule.Name; row.StartTime = attendance.Schedule.WeeklyTimeOfDay ?? attendance.Schedule.StartTimeOfDay; row.DayOfWeek = attendance.Schedule.WeeklyDayOfWeek ?? GetLastDayOfWeek(attendance.Schedule, startDate, endDate); row.Count = a.Count(); row.Volunteers = volunteerGroupAttendance.Count(b => scheduleDateRanges.Any(s => b.StartDateTime >= s.Start && b.StartDateTime <= s.End)); row.Total = a.Count() + volunteerGroupAttendance.Count(b => scheduleDateRanges.Any(s => b.StartDateTime >= s.Start && b.StartDateTime <= s.End)); return(row); }).ToList(); datasource.AddRange(statisticRows); if (statisticRows.Count > 1) { var subTotalRow = new StatisticRow { RowId = attendanceChildGroup.Id.ToString(), SortValue = 2, IsTotal = true, Area = attendanceGroup.Name, Subarea = attendanceChildGroup.Name, Service = "Sub-Total", Count = statisticRows.Sum(cg => cg.Count), Volunteers = statisticRows.Sum(cg => cg.Volunteers), Total = statisticRows.Sum(cg => cg.Total) }; datasource.Add(subTotalRow); } } } } datasource.Add(new StatisticRow { RowId = "Total", SortValue = 3, IsTotal = true, Area = "Grand Total", Subarea = "Total", Service = "Total", Count = datasource.Where(ds => ds.IsTotal).Sum(cg => cg.Count), Volunteers = datasource.Where(ds => ds.IsTotal).Sum(cg => cg.Volunteers), Total = datasource.Where(ds => ds.IsTotal).Sum(cg => cg.Total) }); return(datasource); }