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

            RockPage.AddCSSLink(ResolveRockUrl("~/Styles/fluidbox.css"));
            RockPage.AddScriptLink(ResolveRockUrl("~/Scripts/imagesloaded.min.js"));
            RockPage.AddScriptLink(ResolveRockUrl("~/Scripts/jquery.fluidbox.min.js"));

            if (CurrentPerson != null)
            {
                lName.Text = CurrentPerson.FullName;

                // Setup Image
                var imgTag = new LiteralControl(Rock.Model.Person.GetPersonPhotoImageTag(CurrentPerson, 188, 188));
                if (CurrentPerson.PhotoId.HasValue)
                {
                    var imgLink = new HyperLink();
                    imgLink.Attributes.Add("href", CurrentPerson.PhotoUrl);
                    phImage.Controls.Add(imgLink);
                    imgLink.Controls.Add(imgTag);
                }
                else
                {
                    phImage.Controls.Add(imgTag);
                }

                if (CurrentPerson.BirthDate.HasValue)
                {
                    var    dtf = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat;
                    string mdp = dtf.ShortDatePattern;
                    mdp = mdp.Replace(dtf.DateSeparator + "yyyy", "").Replace("yyyy" + dtf.DateSeparator, "");

                    string ageText = (CurrentPerson.BirthYear.HasValue && CurrentPerson.BirthYear != DateTime.MinValue.Year) ?
                                     string.Format("{0} yrs old ", CurrentPerson.BirthDate.Value.Age()) : string.Empty;
                    lAge.Text = string.Format("{0}<small>({1})</small><br/>", ageText, CurrentPerson.BirthDate.Value.ToMonthDayString());
                }

                lGender.Text = CurrentPerson.Gender != Gender.Unknown ? CurrentPerson.Gender.ToString() : string.Empty;

                if (CurrentPerson.PhoneNumbers != null)
                {
                    rptPhones.DataSource = CurrentPerson.PhoneNumbers.ToList();
                    rptPhones.DataBind();
                }

                lEmail.Text = CurrentPerson.Email;

                Guid?locationTypeGuid = GetAttributeValue("LocationType").AsGuidOrNull();
                if (locationTypeGuid.HasValue)
                {
                    var addressTypeDv = DefinedValueCache.Read(locationTypeGuid.Value);

                    var familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuidOrNull();

                    if (familyGroupTypeGuid.HasValue)
                    {
                        var familyGroupType = GroupTypeCache.Read(familyGroupTypeGuid.Value);

                        RockContext rockContext = new RockContext();
                        var         address     = new GroupLocationService(rockContext).Queryable()
                                                  .Where(l => l.Group.GroupTypeId == familyGroupType.Id &&
                                                         l.GroupLocationTypeValueId == addressTypeDv.Id &&
                                                         l.Group.Members.Any(m => m.PersonId == CurrentPerson.Id))
                                                  .Select(l => l.Location)
                                                  .FirstOrDefault();
                        if (address != null)
                        {
                            lAddress.Text = string.Format("<div class='margin-b-md'><small>{0} Address</small><br />{1}</div>", addressTypeDv.Value, address.FormattedHtmlAddress);
                        }
                    }
                }

                if (GetAttributeValue("ShowHomeAddress").AsBoolean())
                {
                    var homeAddress = CurrentPerson.GetHomeLocation();
                    if (homeAddress != null)
                    {
                    }
                }
            }
        }
Пример #2
0
        private void Render()
        {
            try
            {
                PageCache currentPage = PageCache.Get(RockPage.PageId);
                PageCache rootPage    = null;

                var pageRouteValuePair = GetAttributeValue(ROOT_PAGE).SplitDelimitedValues(false).AsGuidOrNullList();
                if (pageRouteValuePair.Any() && pageRouteValuePair[0].HasValue && !pageRouteValuePair[0].Value.IsEmpty())
                {
                    rootPage = PageCache.Get(pageRouteValuePair[0].Value);
                }

                // If a root page was not found, use current page
                if (rootPage == null)
                {
                    rootPage = currentPage;
                }

                int levelsDeep = Convert.ToInt32(GetAttributeValue(NUM_LEVELS));

                Dictionary <string, string> pageParameters = null;
                if (GetAttributeValue("IncludeCurrentParameters").AsBoolean())
                {
                    pageParameters = CurrentPageReference.Parameters;
                }

                NameValueCollection queryString = null;
                if (GetAttributeValue("IncludeCurrentQueryString").AsBoolean())
                {
                    queryString = CurrentPageReference.QueryString;
                }

                // Get list of pages in current page's hierarchy
                var pageHeirarchy = new List <int>();
                if (currentPage != null)
                {
                    pageHeirarchy = currentPage.GetPageHierarchy().Select(p => p.Id).ToList();
                }

                // 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);
                }

                var pageProperties = new Dictionary <string, object>();
                pageProperties.Add("CurrentPerson", CurrentPerson);
                pageProperties.Add("Context", contextObjects);
                pageProperties.Add("Site", GetSiteProperties(RockPage.Site));
                pageProperties.Add("IncludePageList", GetIncludePageList());
                pageProperties.Add("CurrentPage", this.PageCache);

                using (var rockContext = new RockContext())
                {
                    pageProperties.Add("Page", rootPage.GetMenuProperties(levelsDeep, CurrentPerson, rockContext, pageHeirarchy, pageParameters, queryString));
                }
                string content = GetTemplate().Render(Hash.FromDictionary(pageProperties));

                // check for errors
                if (content.Contains("error"))
                {
                    content = "<div class='alert alert-warning'><h4>Warning</h4>" + content + "</div>";
                }

                phContent.Controls.Clear();
                phContent.Controls.Add(new LiteralControl(content));
            }
            catch (Exception ex)
            {
                LogException(ex);
                StringBuilder errorMessage = new StringBuilder();
                errorMessage.Append("<div class='alert alert-warning'>");
                errorMessage.Append("An error has occurred while generating the page menu. Error details:");
                errorMessage.Append(ex.Message);
                errorMessage.Append("</div>");

                phContent.Controls.Add(new LiteralControl(errorMessage.ToString()));
            }
        }
        private void LoadContent()
        {
            var audienceGuid = GetAttributeValue("Audience").AsGuid();

            if (audienceGuid != Guid.Empty)
            {
                lMessages.Text = string.Empty;
                RockContext rockContext = new RockContext();

                // get event occurrences
                var qry = new EventItemOccurrenceService(rockContext).Queryable()
                          .Where(e => e.EventItem.EventItemAudiences.Any(a => a.DefinedValue.Guid == audienceGuid) && e.EventItem.IsActive);

                // filter occurrences for campus (always include the "All Campuses" events)
                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 || !e.CampusId.HasValue);
                    }
                }
                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) || !e.CampusId.HasValue);
                    }
                }

                // filter by calendar
                var calendarGuid = GetAttributeValue("Calendar").AsGuid();

                if (calendarGuid != Guid.Empty)
                {
                    qry = qry.Where(e => e.EventItem.EventCalendarItems.Any(c => c.EventCalendar.Guid == calendarGuid));
                }

                // 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
                    itemOccurrences.RemoveAll(o => o.GetStartTimes(RockDateTime.Now, DateTime.Now.AddDays(365)).Count() == 0);
                }

                // limit results
                int maxItems = GetAttributeValue("MaxOccurrences").AsInteger();
                itemOccurrences = itemOccurrences.OrderBy(i => i.NextStartDateTime).Take(maxItems).ToList();

                // make lava merge fields
                var mergeFields = new Dictionary <string, object>();

                var contextObjects = new Dictionary <string, object>();
                foreach (var contextEntityType in RockPage.GetContextEntityTypes())
                {
                    var contextEntity = RockPage.GetCurrentContext(contextEntityType);
                    if (contextEntity != null && contextEntity is DotLiquid.ILiquidizable)
                    {
                        var type = Type.GetType(contextEntityType.AssemblyName ?? contextEntityType.Name);
                        if (type != null)
                        {
                            contextObjects.Add(type.Name, contextEntity);
                        }
                    }
                }

                if (contextObjects.Any())
                {
                    mergeFields.Add("Context", contextObjects);
                }

                mergeFields.Add("ListTitle", GetAttributeValue("ListTitle"));
                mergeFields.Add("EventDetailPage", LinkedPageRoute("EventDetailPage"));
                mergeFields.Add("RegistrationPage", LinkedPageRoute("RegistrationPage"));
                mergeFields.Add("EventItemOccurrences", itemOccurrences);

                lContent.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields);

                // show debug info
                if (GetAttributeValue("EnableDebug").AsBoolean() && IsUserAuthorized(Authorization.EDIT))
                {
                    lDebug.Visible = true;
                    lDebug.Text    = @"<div class='alert alert-info'>Due to the size of the lava members the debug info for this block has been supressed. Below are high-level details of
                                    the merge objects available.
                                    <ul>
                                        <li>List Title - The title to pass to lava.
                                        <li>EventItemOccurrences - A list of EventItemOccurrences. View the EvenItemOccurrence model for these properties.</li>
                                        <li>RegistrationPage  - String that contains the relative path to the registration page.</li>
                                        <li>EventDetailPage  - String that contains the relative path to the event detail page.</li>
                                        <li>Global Attribute  - Access to the Global Attributes.</li>
                                    </ul>
                                    </div>";
                }
                else
                {
                    lDebug.Visible = false;
                    lDebug.Text    = string.Empty;
                }
            }
            else
            {
                lMessages.Text = "<div class='alert alert-warning'>No audience is configured for this block.</div>";
            }
        }
        /// <summary>
        /// Loads the campuses
        /// </summary>
        protected void LoadCampusDropdowns()
        {
            var campusEntityType = EntityTypeCache.Get(typeof(Campus));
            var currentCampus    = RockPage.GetCurrentContext(campusEntityType) as Campus;

            var campusIdString = Request.QueryString["campusId"];

            if (campusIdString != null)
            {
                var campusId = campusIdString.AsInteger();

                // if there is a query parameter, ensure that the Campus Context cookie is set (and has an updated expiration)
                // note, the Campus Context might already match due to the query parameter, but has a different cookie context, so we still need to ensure the cookie context is updated
                currentCampus = SetCampusContext(campusId, false);
            }

            if (currentCampus == null && GetAttributeValue("DefaultToCurrentUser").AsBoolean() && CurrentPerson != null)
            {
                currentCampus = CurrentPerson.GetFamily().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();
        }
Пример #5
0
        protected override void OnLoad(EventArgs e)
        {
            RockPage.AddScriptLink("~/Blocks/CheckIn/Scripts/geo-min.js");
            RockPage.AddScriptLink("~/Scripts/iscroll.js");
            RockPage.AddScriptLink("~/Scripts/CheckinClient/checkin-core.js");

            if (!Page.IsPostBack)
            {
                // Set the check-in state from values passed on query string
                CurrentKioskId = PageParameter("KioskId").AsIntegerOrNull();

                CurrentGroupTypeIds = (PageParameter("GroupTypeIds") ?? "")
                                      .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                      .ToList()
                                      .Select(s => s.AsInteger())
                                      .ToList();

                // If valid parameters were used, set state and navigate to welcome page
                if (CurrentKioskId.HasValue && CurrentGroupTypeIds.Any())
                {
                    // Save the check-in state
                    SaveState();

                    // Navigate to the check-in home (welcome) page
                    NavigateToNextPage();
                }
                else
                {
                    bool enableLocationSharing = bool.Parse(GetAttributeValue("EnableLocationSharing") ?? "false");

                    // Inject script used for geo location determiniation
                    if (enableLocationSharing)
                    {
                        lbRetry.Visible = true;
                        AddGeoLocationScript();
                    }
                    else
                    {
                        pnlManualConfig.Visible = true;
                        lbOk.Visible            = true;
                        AttemptKioskMatchByIpOrName();
                    }

                    string script = string.Format(@"
                    <script>
                        $(document).ready(function (e) {{
                            if (localStorage) {{
                                if (localStorage.checkInKiosk) {{
                                    $('[id$=""hfKiosk""]').val(localStorage.checkInKiosk);
                                    if (localStorage.theme) {{
                                        $('[id$=""hfTheme""]').val(localStorage.theme);
                                    }}
                                    if (localStorage.checkInGroupTypes) {{
                                        $('[id$=""hfGroupTypes""]').val(localStorage.checkInGroupTypes);
                                    }}
                                    {0};
                                }}
                            }}
                        }});
                    </script>
                ", this.Page.ClientScript.GetPostBackEventReference(lbRefresh, ""));
                    phScript.Controls.Add(new LiteralControl(script));

                    ddlTheme.Items.Clear();
                    DirectoryInfo di = new DirectoryInfo(this.Page.Request.MapPath(ResolveRockUrl("~~")));
                    foreach (var themeDir in di.Parent.EnumerateDirectories().OrderBy(a => a.Name))
                    {
                        ddlTheme.Items.Add(new ListItem(themeDir.Name, themeDir.Name.ToLower()));
                    }
                    ddlTheme.SetValue(RockPage.Site.Theme.ToLower());

                    Guid kioskDeviceType = Rock.SystemGuid.DefinedValue.DEVICE_TYPE_CHECKIN_KIOSK.AsGuid();
                    ddlKiosk.Items.Clear();
                    using (var rockContext = new RockContext())
                    {
                        ddlKiosk.DataSource = new DeviceService(rockContext).Queryable()
                                              .Where(d => d.DeviceType.Guid.Equals(kioskDeviceType))
                                              .ToList();
                    }
                    ddlKiosk.DataBind();
                    ddlKiosk.Items.Insert(0, new ListItem(None.Text, None.IdValue));

                    if (CurrentKioskId.HasValue)
                    {
                        ListItem item = ddlKiosk.Items.FindByValue(CurrentKioskId.Value.ToString());
                        if (item != null)
                        {
                            item.Selected = true;
                            BindGroupTypes();
                        }
                    }
                }
            }
            else
            {
                phScript.Controls.Clear();
            }
        }
Пример #6
0
        /// <summary>
        /// Loads the drop downs.
        /// </summary>
        private bool SetFilterControls()
        {
            // Get and verify the calendar id
            if (_calendarId <= 0)
            {
                ShowError("Configuration Error", "The 'Event Calendar' setting has not been set correctly.");
                return(false);
            }

            // Get and verify the view mode
            ViewMode = GetAttributeValue("DefaultViewOption");
            if (!GetAttributeValue(string.Format("Show{0}View", ViewMode)).AsBoolean())
            {
                ShowError("Configuration Error", string.Format("The Default View Option setting has been set to '{0}', but the Show {0} View setting has not been enabled.", ViewMode));
                return(false);
            }

            // Show/Hide calendar control
            pnlCalendar.Visible = GetAttributeValue("ShowSmallCalendar").AsBoolean();

            // Get the first/last dates based on today's date and the viewmode setting
            var today = RockDateTime.Today;

            FilterStartDate = today;
            FilterEndDate   = today;
            if (ViewMode == "Week")
            {
                FilterStartDate = today.StartOfWeek(_firstDayOfWeek);
                FilterEndDate   = today.EndOfWeek(_firstDayOfWeek);
            }
            else if (ViewMode == "Month")
            {
                FilterStartDate = new DateTime(today.Year, today.Month, 1);
                FilterEndDate   = FilterStartDate.Value.AddMonths(1).AddDays(-1);
            }
            else if (ViewMode == "Year")
            {
                FilterEndDate = FilterStartDate.Value.AddYears(1).AddDays(-1);
            }

            // Setup small calendar Filter
            calEventCalendar.FirstDayOfWeek = _firstDayOfWeek.ConvertToInt().ToString().ConvertToEnum <FirstDayOfWeek>();
            calEventCalendar.SelectedDates.Clear();
            calEventCalendar.SelectedDates.SelectRange(FilterStartDate.Value, FilterEndDate.Value);

            // Setup Campus Filter
            rcwCampus.Visible    = GetAttributeValue("CampusFilterDisplayMode").AsInteger() > 1;
            cblCampus.DataSource = CampusCache.All();
            cblCampus.DataBind();

            //Check for Campus Parameter
            var campusId  = PageParameter(GetAttributeValue("CampusParameterName")).AsIntegerOrNull();
            var campusStr = PageParameter("Campus");

            if (campusId.HasValue)
            {
                //check if there's a campus with this id.
                var campus = CampusCache.Get(campusId.Value);
                if (campus != null)
                {
                    cblCampus.SetValue(campusId.Value);
                }
            }
            else if (!string.IsNullOrEmpty(campusStr))
            {
                //check if there's a campus with this name.
                campusStr = campusStr.Replace(" ", "").Replace("-", "");
                var campusCache = CampusCache.All().Where(c => c.Name.ToLower().Replace(" ", "").Replace("-", "") == campusStr.ToLower()).FirstOrDefault();
                if (campusCache != null)
                {
                    cblCampus.SetValue(campusCache.Id);
                }
            }
            else
            {
                if (GetAttributeValue("EnableCampusContext").AsBoolean())
                {
                    var contextCampus = RockPage.GetCurrentContext(EntityTypeCache.Get("Rock.Model.Campus")) as Campus;
                    if (contextCampus != null)
                    {
                        cblCampus.SetValue(contextCampus.Id);
                    }
                }
            }

            // Setup Category Filter
            var selectedCategoryGuids = GetAttributeValue("FilterCategories").SplitDelimitedValues(true).AsGuidList();

            rcwCategory.Visible = selectedCategoryGuids.Any() && GetAttributeValue("CategoryFilterDisplayMode").AsInteger() > 1;
            var definedType = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.MARKETING_CAMPAIGN_AUDIENCE_TYPE.AsGuid());

            if (definedType != null)
            {
                var categoryItems = definedType.DefinedValues.ToList();
                if (selectedCategoryGuids.Count() > 0)
                {
                    categoryItems = definedType.DefinedValues.Where(v => selectedCategoryGuids.Contains(v.Guid)).ToList();
                }
                cblCategory.DataSource = categoryItems;
                cblCategory.DataBind();
            }
            var categoryId   = PageParameter(GetAttributeValue("CategoryParameterName")).AsIntegerOrNull();
            var ministrySlug = PageParameter("ministry").ToLower();

            if (categoryId.HasValue)
            {
                if (definedType.DefinedValues.Where(v => (selectedCategoryGuids.Contains(v.Guid) || selectedCategoryGuids.Count() == 0) && v.Id == categoryId.Value).FirstOrDefault() != null)
                {
                    cblCategory.SetValue(categoryId.Value);
                }
            }
            else if (!string.IsNullOrEmpty(ministrySlug))
            {
                var definedValues = definedType.DefinedValues.Where(v => (selectedCategoryGuids.Contains(v.Guid) || selectedCategoryGuids.Count() == 0)).ToList();
                DefinedTypeService definedTypeService = new DefinedTypeService(new RockContext());
                var definedTypeModel = definedTypeService.Get(definedType.Guid);
                foreach (var dv in definedTypeModel.DefinedValues)
                {
                    dv.LoadAttributes();
                    if (dv.GetAttributeValue("URLSlug") == ministrySlug)
                    {
                        cblCategory.SetValue(dv.Id);
                        break;
                    }
                }
            }

            // Date Range Filter
            drpDateRange.Visible       = GetAttributeValue("ShowDateRangeFilter").AsBoolean();
            lbDateRangeRefresh.Visible = drpDateRange.Visible;
            drpDateRange.LowerValue    = FilterStartDate;
            drpDateRange.UpperValue    = FilterEndDate;

            // Get the View Modes, and only show them if more than one is visible
            var viewsVisible = new List <bool> {
                GetAttributeValue("ShowDayView").AsBoolean(),
                GetAttributeValue("ShowWeekView").AsBoolean(),
                GetAttributeValue("ShowMonthView").AsBoolean(),
                GetAttributeValue("ShowYearView").AsBoolean()
            };
            var howManyVisible = viewsVisible.Where(v => v).Count();

            btnDay.Visible   = howManyVisible > 1 && viewsVisible[0];
            btnWeek.Visible  = howManyVisible > 1 && viewsVisible[1];
            btnMonth.Visible = howManyVisible > 1 && viewsVisible[2];
            btnYear.Visible  = howManyVisible > 1 && viewsVisible[3];

            // Set filter visibility
            bool showFilter = (pnlCalendar.Visible || rcwCampus.Visible || rcwCategory.Visible || drpDateRange.Visible);

            pnlFilters.Visible = showFilter;
            pnlList.CssClass   = showFilter ? "col-md-9" : "col-md-12";

            return(true);
        }
Пример #7
0
 /// <summary>
 /// Initialize the scripts required for Chart.js
 /// </summary>
 private void InitializeChartScripts()
 {
     // NOTE: moment.js needs to be loaded before chartjs
     RockPage.AddScriptLink("~/Scripts/moment.min.js", true);
     RockPage.AddScriptLink("~/Scripts/Chartjs/Chart.js", true);
 }
Пример #8
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                // Set the check-in state from values passed on query string
                bool themeRedirect = PageParameter("ThemeRedirect").AsBoolean(false);

                var preferredKioskId = PageParameter("KioskId").AsIntegerOrNull();
                if (preferredKioskId != null)
                {
                    CurrentKioskId = preferredKioskId;
                }

                var checkinTypeId = PageParameter("CheckinTypeId").AsIntegerOrNull();
                if (checkinTypeId != null)
                {
                    CurrentCheckinTypeId = checkinTypeId;
                }

                var queryStringConfig = PageParameter("GroupTypeIds");
                if (!string.IsNullOrEmpty(queryStringConfig))
                {
                    CurrentGroupTypeIds = queryStringConfig.ToStringSafe()
                                          .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                          .ToList()
                                          .Select(s => s.AsInteger())
                                          .ToList();
                }

                if (CurrentCheckInState != null && CurrentCheckInState.Kiosk != null && CurrentGroupTypeIds != null && CurrentGroupTypeIds.Any() && !UserBackedUp)
                {
                    // Set the local cache if a session is already active
                    CurrentKioskId      = CurrentCheckInState.DeviceId;
                    CurrentGroupTypeIds = CurrentCheckInState.ConfiguredGroupTypes;
                    CurrentCheckInState = null;
                    CurrentWorkflow     = null;

                    if (!CurrentCheckinTypeId.HasValue)
                    {
                        foreach (int groupTypeId in CurrentGroupTypeIds)
                        {
                            var checkinType = GetCheckinType(groupTypeId);
                            if (checkinType != null)
                            {
                                CurrentCheckinTypeId = checkinType.Id;
                                break;
                            }
                        }
                    }

                    // Save the check-in state
                    SaveState();

                    // Navigate to the next page
                    NavigateToNextPage();
                }
                else
                {
                    bool useGeoLocationService = GetAttributeValue("EnableLocationSharing").AsBoolean();

                    // Inject script used for geo location determiniation
                    if (!useGeoLocationService)
                    {
                        lbOk.Visible = true;
                        AttemptKioskMatchByIpOrName();
                    }
                    else
                    {
                        RockPage.AddScriptLink("~/Blocks/CheckIn/Scripts/geo-min.js");
                        lbRefresh.Visible = true;
                        AddGeoLocationScript();
                    }

                    AttemptKioskMatchByIpOrName();

                    string script = string.Format(@"<script>
                        $(document).ready(function (e) {{
                            if (localStorage) {{
                                if (localStorage.checkInKiosk) {{
                                    $('[id$=""hfKiosk""]').val(localStorage.checkInKiosk);
                                    if (localStorage.checkInType) {{
                                        $('[id$=""hfCheckinType""]').val(localStorage.checkInType);
                                    }}
                                    if (localStorage.checkInGroupTypes) {{
                                        $('[id$=""hfGroupTypes""]').val(localStorage.checkInGroupTypes);
                                    }}
                                }}
                                {0};
                            }}
                        }});
                        </script>", this.Page.ClientScript.GetPostBackEventReference(lbRefresh, "")
                                                  );
                    phScript.Controls.Add(new LiteralControl(script));

                    // Initiate the check-in variables
                    lbOk.Focus();
                    SaveState();
                }
            }
            else if (Request["__EVENTTARGET"] == lbTestPrint.ClientID)
            {
                SendTestPrint();
            }
            else
            {
                phScript.Controls.Clear();
            }
        }
Пример #9
0
        /// <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();
            var            batchService = new FinancialBatchService(rockContext);
            FinancialBatch batch        = null;

            var changes = new List <string>();

            int batchId = hfBatchId.Value.AsInteger();

            if (batchId == 0)
            {
                batch = new FinancialBatch();
                batchService.Add(batch);
                changes.Add("Created the batch");
            }
            else
            {
                batch = batchService.Get(batchId);
            }

            if (batch != null)
            {
                History.EvaluateChange(changes, "Batch Name", batch.Name, tbName.Text);
                batch.Name = tbName.Text;

                BatchStatus batchStatus = (BatchStatus)ddlStatus.SelectedIndex;
                History.EvaluateChange(changes, "Status", batch.Status, batchStatus);
                batch.Status = batchStatus;

                CampusCache oldCampus = null;
                if (batch.CampusId.HasValue)
                {
                    oldCampus = CampusCache.Read(batch.CampusId.Value);
                }

                CampusCache newCampus = null;
                if (campCampus.SelectedCampusId.HasValue)
                {
                    newCampus = CampusCache.Read(campCampus.SelectedCampusId.Value);
                }

                History.EvaluateChange(changes, "Campus", oldCampus != null ? oldCampus.Name : "None", newCampus != null ? newCampus.Name : "None");
                batch.CampusId = campCampus.SelectedCampusId;

                DateTime?startDateTime = dtpStart.SelectedDateTimeIsBlank ? null : dtpStart.SelectedDateTime;
                History.EvaluateChange(changes, "Start Date/Time", batch.BatchStartDateTime, startDateTime);
                batch.BatchStartDateTime = startDateTime;

                DateTime?endDateTime;
                if (dtpEnd.SelectedDateTimeIsBlank && batch.BatchStartDateTime.HasValue)
                {
                    endDateTime = batch.BatchStartDateTime.Value.AddDays(1);
                }
                else
                {
                    endDateTime = dtpEnd.SelectedDateTimeIsBlank ? null : dtpEnd.SelectedDateTime;
                }

                History.EvaluateChange(changes, "End Date/Time", batch.BatchEndDateTime, endDateTime);
                batch.BatchEndDateTime = endDateTime;

                decimal controlAmount = tbControlAmount.Text.AsDecimal();
                History.EvaluateChange(changes, "Control Amount", batch.ControlAmount.FormatAsCurrency(), controlAmount.FormatAsCurrency());
                batch.ControlAmount = controlAmount;

                History.EvaluateChange(changes, "Accounting System Code", batch.AccountingSystemCode, tbAccountingCode.Text);
                batch.AccountingSystemCode = tbAccountingCode.Text;

                History.EvaluateChange(changes, "Notes", batch.Note, tbNote.Text);
                batch.Note = tbNote.Text;

                cvBatch.IsValid = batch.IsValid;
                if (!Page.IsValid || !batch.IsValid)
                {
                    cvBatch.ErrorMessage = batch.ValidationResults.Select(a => a.ErrorMessage).ToList().AsDelimited("<br />");
                    return;
                }

                rockContext.WrapTransaction(() =>
                {
                    if (rockContext.SaveChanges() > 0)
                    {
                        if (changes.Any())
                        {
                            pdAuditDetails.SetEntity(batch, ResolveRockUrl("~"));
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(FinancialBatch),
                                Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(),
                                batch.Id,
                                changes);
                        }
                    }
                });

                if (batchId == 0)
                {
                    // If created a new batch, navigate to same page so that transaction list displays correctly
                    var pageReference = CurrentPageReference;
                    pageReference.Parameters.AddOrReplace("batchId", batch.Id.ToString());
                    NavigateToPage(pageReference);
                }
                else
                {
                    hfBatchId.SetValue(batch.Id);

                    // Requery the batch to support EF navigation properties
                    var savedBatch = GetBatch(batch.Id);
                    ShowReadonlyDetails(savedBatch);

                    // If there is a batch context item, update the context's properties with new values
                    var contextObjects = new Dictionary <string, object>();
                    foreach (var contextEntityType in RockPage.GetContextEntityTypes())
                    {
                        var contextEntity = RockPage.GetCurrentContext(contextEntityType);
                        if (contextEntity is FinancialBatch)
                        {
                            var contextBatch = contextEntity as FinancialBatch;
                            contextBatch.CopyPropertiesFrom(batch);
                        }
                    }

                    // Then refresh transaction list
                    RockPage.UpdateBlocks("~/Blocks/Finance/TransactionList.ascx");
                }
            }
        }
Пример #10
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            RockPage.AddCSSLink("~/Styles/fluidbox.css");
            RockPage.AddScriptLink("~/Scripts/imagesloaded.min.js");
            RockPage.AddScriptLink("~/Scripts/jquery.fluidbox.min.js");

            // 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(pnlContent);

            if (Person == null)
            {
                return;
            }

            // If this is the empty person, check for an old Alias record and if found, redirect permanent to it instead.
            if (Person.Id == 0)
            {
                //referring to aliasPersonId as person might be merged
                var personId = this.PageParameter(PageParameterKey.PersonId).AsIntegerOrNull();

                if (personId.HasValue)
                {
                    var personAlias = new PersonAliasService(new RockContext()).GetByAliasId(personId.Value);
                    if (personAlias != null)
                    {
                        var pageReference = RockPage.PageReference;
                        pageReference.Parameters.AddOrReplace(PageParameterKey.PersonId, personAlias.PersonId.ToString());
                        Response.RedirectPermanent(pageReference.BuildUrl(), false);
                    }
                }
            }

            pnlFollow.Visible = GetAttributeValue(AttributeKey.AllowFollowing).AsBoolean();

            // Record Type - this is always "business". it will never change.
            if (Person.IsBusiness())
            {
                var parms = new Dictionary <string, string>();
                parms.Add(PageParameterKey.BusinessId, Person.Id.ToString());
                NavigateToLinkedPage(AttributeKey.BusinessDetailPage, parms);
            }
            else if (Person.IsNameless())
            {
                var parms = new Dictionary <string, string>();
                parms.Add(PageParameterKey.NamelessPersonId, Person.Id.ToString());
                NavigateToLinkedPage(AttributeKey.NamelessPersonDetailPage, parms);
            }

            if (Person.IsDeceased)
            {
                divBio.AddCssClass("deceased");
            }

            // Set the browser page title to include person's name
            RockPage.BrowserTitle = Person.FullName;

            string badgeList = GetAttributeValue(AttributeKey.Badges);

            if (!string.IsNullOrWhiteSpace(badgeList))
            {
                foreach (string badgeGuid in badgeList.SplitDelimitedValues())
                {
                    Guid guid = badgeGuid.AsGuid();
                    if (guid != Guid.Empty)
                    {
                        var badge = BadgeCache.Get(guid);
                        if (badge != null)
                        {
                            blStatus.BadgeTypes.Add(badge);
                        }
                    }
                }
            }

            if (Person.AccountProtectionProfile > Rock.Utility.Enums.AccountProtectionProfile.Low)
            {
                hlAccountProtectionLevel.Visible = true;
                hlAccountProtectionLevel.Text    = $"Protection Profile: {Person.AccountProtectionProfile.ConvertToString( true )}";
                if (Person.AccountProtectionProfile == Rock.Utility.Enums.AccountProtectionProfile.Extreme)
                {
                    // show 'danger' if AccountProtectionProfile is extreme
                    hlAccountProtectionLevel.LabelType = LabelType.Danger;
                }
                else
                {
                    hlAccountProtectionLevel.LabelType = LabelType.Warning;
                }
            }
            else
            {
                hlAccountProtectionLevel.Visible = false;
            }

            lbEditPerson.Visible = IsUserAuthorized(Rock.Security.Authorization.EDIT);

            // only show if the when all these are true
            //   -- EnableImpersonation is enabled
            //   -- Not the same as the current person
            //   -- The current user is authorized to Administrate the person
            //   -- PersonToken usage is allowed on the person (due to AccountProtectionProfile)

            bool enableImpersonation = this.GetAttributeValue(AttributeKey.EnableImpersonation).AsBoolean();

            lbImpersonate.Visible = false;
            if (enableImpersonation &&
                Person.Id != CurrentPersonId &&
                Person.IsAuthorized(Rock.Security.Authorization.ADMINISTRATE, this.CurrentPerson)
                )
            {
                // We are allowed to impersonate for anybody that has Token Usage Allowed.
                lbImpersonate.Visible = true;

                if (Person.IsPersonTokenUsageAllowed() == false)
                {
                    // Since the logged-in user would normally see an Impersonate button, but this Person doesn't have TokenUsage allowed,
                    // show the button, but have it be disabled.
                    lbImpersonate.Enabled = false;
                }
                else
                {
                    lbImpersonate.Enabled = true;
                }
            }
        }
Пример #11
0
        /// <summary>
        /// Renders the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="result">The result.</param>
        public override void Render(Context context, TextWriter result)
        {
            RockPage page = HttpContext.Current.Handler as RockPage;

            var parms = ParseMarkup(_markup, context);

            using (TextWriter twJavascript = new StringWriter())
            {
                base.Render(context, twJavascript);

                if (parms["url"].IsNullOrWhiteSpace())
                {
                    string javascript = "";

                    if (!parms["disableanonymousfunction"].AsBoolean())
                    {
                        javascript = $@"(function(){{
  {twJavascript.ToString()}
}})({parms["references"]});";
                    }
                    else
                    {
                        javascript = twJavascript.ToString();
                    }

                    if (parms.ContainsKey("id"))
                    {
                        var identifier = parms["id"];
                        if (identifier.IsNotNullOrWhitespace())
                        {
                            var controlId = "js-" + identifier;

                            var scriptControl = page.Header.FindControl(controlId);
                            if (scriptControl == null)
                            {
                                scriptControl    = new System.Web.UI.LiteralControl($"{Environment.NewLine}<script>{javascript}</script>{Environment.NewLine}");
                                scriptControl.ID = controlId;
                                page.Header.Controls.Add(scriptControl);
                            }
                        }
                    }
                    else
                    {
                        page.Header.Controls.Add(new System.Web.UI.LiteralControl($"{Environment.NewLine}<script>{javascript}</script>{Environment.NewLine}"));
                    }
                }
                else
                {
                    var url = ResolveRockUrl(parms["url"]);

                    if (parms.ContainsKey("id"))
                    {
                        var identifier = parms["id"];
                        if (identifier.IsNotNullOrWhitespace())
                        {
                            var controlId = "js-" + identifier;

                            var scriptControl = page.Header.FindControl(controlId);
                            if (scriptControl == null)
                            {
                                scriptControl    = new System.Web.UI.LiteralControl($"{Environment.NewLine}<script src='{url}' type='text/javascript'></script>{Environment.NewLine}");
                                scriptControl.ID = controlId;
                                page.Header.Controls.Add(scriptControl);
                            }
                        }
                    }
                    else
                    {
                        page.Header.Controls.Add(new System.Web.UI.LiteralControl($"{Environment.NewLine}<script src='{url}' type='text/javascript'></script>{Environment.NewLine}"));
                    }
                }
            }
        }
        private void SetCampus()
        {
            RockContext rockContext = new RockContext();
            Campus      campus      = null;

            // get device
            string        deviceIp      = GetIPAddress();
            DeviceService deviceService = new DeviceService(rockContext);

            var deviceQry = deviceService.Queryable("Location")
                            .Where(d => d.IPAddress == deviceIp);

            // add device type filter
            if (!string.IsNullOrWhiteSpace(GetAttributeValue("DeviceType")))
            {
                Guid givingKioskGuid = new Guid(GetAttributeValue("DeviceType"));
                deviceQry = deviceQry.Where(d => d.DeviceType.Guid == givingKioskGuid);
            }

            var device = deviceQry.FirstOrDefault();

            if (device != null)
            {
                if (device.Locations.Count > 0)
                {
                    campus = new CampusService(new RockContext()).Get(device.Locations.First().CampusId.Value);

                    // set the context
                    if (campus != null)
                    {
                        var campusEntityType = EntityTypeCache.Read("Rock.Model.Campus");
                        var currentCampus    = RockPage.GetCurrentContext(campusEntityType) as Campus;

                        if (currentCampus == null || currentCampus.Id != campus.Id)
                        {
                            bool pageScope = GetAttributeValue("ContextScope") == "Page";
                            RockPage.SetContextCookie(campus, pageScope, true);
                        }
                    }
                }
            }

            // set display output
            var mergeFields = new Dictionary <string, object>();

            mergeFields.Add("ClientIp", deviceIp);
            mergeFields.Add("Device", device);
            mergeFields.Add("Campus", campus);
            mergeFields.Add("CurrentPerson", CurrentPerson);

            var globalAttributeFields = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields(CurrentPerson);

            globalAttributeFields.ToList().ForEach(d => mergeFields.Add(d.Key, d.Value));

            lOutput.Text = GetAttributeValue("DisplayLava").ResolveMergeFields(mergeFields);

            // show debug info
            if (GetAttributeValue("EnableDebug").AsBoolean() && IsUserAuthorized(Authorization.EDIT))
            {
                lDebug.Visible = true;
                lDebug.Text    = mergeFields.lavaDebugInfo();
            }
        }
        private void LoadContent()
        {
            var audienceGuid = GetAttributeValue("Audience").AsGuid();

            if (audienceGuid != Guid.Empty)
            {
                lMessages.Text = string.Empty;
                RockContext rockContext = new RockContext();

                // get event occurrences
                var qry = new EventItemOccurrenceService(rockContext).Queryable()
                          .Where(e => e.EventItem.EventItemAudiences.Any(a => a.DefinedValue.Guid == audienceGuid) && e.EventItem.IsActive);

                var campusFilter = new List <CampusCache>();

                // filter occurrences for campus (always include the "All Campuses" events)
                if (PageParameter("CampusId").IsNotNullOrWhiteSpace())
                {
                    var contextCampus = CampusCache.Get(PageParameter("CampusId").AsInteger());

                    if (contextCampus != null)
                    {
                        // If an EventItemOccurrence's CampusId is null, then the occurrence is an 'All Campuses' event occurrence, so include those
                        qry = qry.Where(e => e.CampusId == contextCampus.Id || !e.CampusId.HasValue);
                        campusFilter.Add(CampusCache.Get(contextCampus.Id));
                    }
                }
                else if (PageParameter("CampusGuid").IsNotNullOrWhiteSpace())
                {
                    var contextCampus = CampusCache.Get(PageParameter("CampusGuid").AsGuid());

                    if (contextCampus != null)
                    {
                        // If an EventItemOccurrence's CampusId is null, then the occurrence is an 'All Campuses' event occurrence, so include those
                        qry = qry.Where(e => e.CampusId == contextCampus.Id || !e.CampusId.HasValue);
                        campusFilter.Add(CampusCache.Get(contextCampus.Id));
                    }
                }
                else if (GetAttributeValue("UseCampusContext").AsBoolean())
                {
                    var campusEntityType = EntityTypeCache.Get("Rock.Model.Campus");
                    var contextCampus    = RockPage.GetCurrentContext(campusEntityType) as Campus;

                    if (contextCampus != null)
                    {
                        // If an EventItemOccurrence's CampusId is null, then the occurrence is an 'All Campuses' event occurrence, so include those
                        qry = qry.Where(e => e.CampusId == contextCampus.Id || !e.CampusId.HasValue);
                        campusFilter.Add(CampusCache.Get(contextCampus.Id));
                    }
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(GetAttributeValue("Campuses")))
                    {
                        var selectedCampusGuids = GetAttributeValue("Campuses").Split(',').AsGuidList();
                        campusFilter = selectedCampusGuids.Select(a => CampusCache.Get(a)).Where(a => a != null).ToList();
                        var selectedCampusIds = campusFilter.Select(a => a.Id);

                        // If an EventItemOccurrence's CampusId is null, then the occurrence is an 'All Campuses' event occurrence, so include those
                        qry = qry.Where(e => e.CampusId == null || selectedCampusIds.Contains(e.CampusId.Value));
                    }
                }

                // filter by calendar
                var calendarGuid = GetAttributeValue("Calendar").AsGuid();

                if (calendarGuid != Guid.Empty)
                {
                    qry = qry.Where(e => e.EventItem.EventCalendarItems.Any(c => c.EventCalendar.Guid == calendarGuid));
                }

                // 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
                    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();

                // make lava merge fields
                var mergeFields = new Dictionary <string, object>();

                var contextObjects = new Dictionary <string, object>();
                foreach (var contextEntityType in RockPage.GetContextEntityTypes())
                {
                    var contextEntity = RockPage.GetCurrentContext(contextEntityType);
                    if (contextEntity != null && contextEntity is ILavaRenderContext)
                    {
                        var type = Type.GetType(contextEntityType.AssemblyName ?? contextEntityType.Name);
                        if (type != null)
                        {
                            contextObjects.Add(type.Name, contextEntity);
                        }
                    }
                }

                if (contextObjects.Any())
                {
                    mergeFields.Add("Context", contextObjects);
                }

                mergeFields.Add("ListTitle", GetAttributeValue("ListTitle"));
                mergeFields.Add("EventDetailPage", LinkedPageRoute("EventDetailPage"));
                mergeFields.Add("RegistrationPage", LinkedPageRoute("RegistrationPage"));
                mergeFields.Add("EventItemOccurrences", itemOccurrences);

                mergeFields.Add("FilteredCampuses", campusFilter);
                mergeFields.Add("Audience", DefinedValueCache.Get(audienceGuid));

                if (calendarGuid != Guid.Empty)
                {
                    mergeFields.Add("Calendar", new EventCalendarService(rockContext).Get(calendarGuid));
                }

                lContent.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields);
            }
            else
            {
                lMessages.Text = "<div class='alert alert-warning'>No audience is configured for this block.</div>";
            }
        }
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            RockPage.AddScriptLink("~/Scripts/CheckinClient/checkin-core.js");

            var bodyTag = this.Page.Master.FindControl("bodyTag") as HtmlGenericControl;

            if (bodyTag != null)
            {
                bodyTag.AddCssClass("checkin-locationselect-bg");
            }

            if (CurrentWorkflow == null || CurrentCheckInState == null)
            {
                NavigateToHomePage();
            }
            else
            {
                if (!Page.IsPostBack)
                {
                    ClearSelection();

                    var person = CurrentCheckInState.CheckIn.CurrentPerson;
                    if (person == null)
                    {
                        GoBack();
                    }

                    var schedule = person.CurrentSchedule;

                    var groupTypes = person.SelectedGroupTypes(schedule);
                    if (groupTypes == null || !groupTypes.Any())
                    {
                        GoBack();
                    }

                    var group = groupTypes.SelectMany(t => t.SelectedGroups(schedule)).FirstOrDefault();
                    if (group == null)
                    {
                        GoBack();
                    }

                    lTitle.Text    = string.Format(GetAttributeValue("Title"), GetPersonScheduleSubTitle());
                    lSubTitle.Text = string.Format(GetAttributeValue("SubTitle"), group.ToString());
                    lCaption.Text  = GetAttributeValue("Caption");

                    var availLocations = group.GetAvailableLocations(schedule);
                    if (availLocations.Any())
                    {
                        if (availLocations.Count == 1)
                        {
                            if (UserBackedUp)
                            {
                                GoBack();
                            }
                            else
                            {
                                var location = availLocations.First();
                                if (schedule == null)
                                {
                                    location.Selected = true;
                                }
                                else
                                {
                                    location.SelectedForSchedule.Add(schedule.Schedule.Id);
                                }

                                ProcessSelection(person, schedule);
                            }
                        }
                        else
                        {
                            var locations = new List <CheckInLocation>();
                            int sortBy    = GetAttributeValue("SortBy").AsInteger();
                            switch (sortBy)
                            {
                            case 0: locations = availLocations.OrderBy(l => l.Location.Name).ToList();
                                break;

                            case 1: locations = availLocations.OrderBy(l => l.Order).ToList();
                                break;

                            default: locations = availLocations.OrderBy(l => l.Location.Name).ToList();
                                break;
                            }

                            AutoSelect();

                            rSelection.DataSource = locations;

                            rSelection.DataBind();
                        }
                    }
                    else
                    {
                        if (UserBackedUp)
                        {
                            GoBack();
                        }
                        else
                        {
                            pnlNoOptions.Visible = true;
                            rSelection.Visible   = false;
                            lNoOptions.Text      = string.Format(GetAttributeValue("NoOptionMessage"),
                                                                 person.Person.NickName,
                                                                 person.CurrentSchedule != null ? person.CurrentSchedule.ToString() : "this time");
                        }
                    }
                }
            }
        }
Пример #15
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            RockPage.AddScriptLink("~/Scripts/iscroll.js");
            RockPage.AddScriptLink("~/Scripts/CheckinClient/checkin-core.js");

            if (CurrentWorkflow == null || CurrentCheckInState == null)
            {
                NavigateToHomePage();
            }
            else
            {
                if (!Page.IsPostBack)
                {
                    ClearSelection();

                    var person = CurrentCheckInState.CheckIn.Families.Where(f => f.Selected)
                                 .SelectMany(f => f.People.Where(p => p.Selected))
                                 .FirstOrDefault();

                    if (person == null)
                    {
                        GoBack();
                    }

                    lPersonName.Text = person.Person.FullName;

                    var availGroupTypes = person.GroupTypes.Where(t => !t.ExcludedByFilter).ToList();
                    if (availGroupTypes.Count == 1)
                    {
                        if (UserBackedUp)
                        {
                            GoBack();
                        }
                        else
                        {
                            availGroupTypes.FirstOrDefault().Selected = true;
                            ProcessSelection();
                        }
                    }
                    else
                    {
                        bool SelectAll = GetAttributeValue("SelectAll").AsBoolean(false);
                        if (SelectAll)
                        {
                            if (UserBackedUp)
                            {
                                GoBack();
                            }
                            else
                            {
                                availGroupTypes.ForEach(t => t.Selected = true);
                                ProcessSelection();
                            }
                        }
                        else
                        {
                            rSelection.DataSource = availGroupTypes
                                                    .OrderBy(g => g.GroupType.Order)
                                                    .ToList();

                            rSelection.DataBind();
                        }
                    }
                }
            }
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            RockPage.AddScriptLink("~/Scripts/iscroll.js");
            RockPage.AddScriptLink("~/Scripts/CheckinClient/checkin-core.js");

            if (CurrentWorkflow == null || CurrentCheckInState == null)
            {
                NavigateToHomePage();
            }
            else
            {
                if (!Page.IsPostBack)
                {
                    ClearSelection();

                    var person = CurrentCheckInState.CheckIn.CurrentPerson;
                    if (person == null)
                    {
                        GoBack();
                    }

                    var schedule = person.CurrentSchedule;
                    lPersonName.Text = GetPersonScheduleSubTitle();

                    var availGroupTypes = person.GetAvailableGroupTypes(schedule);
                    if (availGroupTypes.Count == 1)
                    {
                        if (UserBackedUp)
                        {
                            GoBack();
                        }
                        else
                        {
                            var groupType = availGroupTypes.First();
                            if (schedule == null)
                            {
                                groupType.Selected = true;
                            }
                            else
                            {
                                groupType.SelectedForSchedule.Add(schedule.Schedule.Id);
                            }

                            ProcessSelection(person, schedule);
                        }
                    }
                    else
                    {
                        bool SelectAll = GetAttributeValue("SelectAll").AsBoolean(false);
                        if (SelectAll)
                        {
                            if (UserBackedUp)
                            {
                                GoBack();
                            }
                            else
                            {
                                availGroupTypes.ForEach(t => t.Selected = true);
                                ProcessSelection(person, schedule);
                            }
                        }
                        else
                        {
                            rSelection.DataSource = availGroupTypes
                                                    .OrderBy(g => g.GroupType.Order)
                                                    .ToList();

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

            RockPage.AddScriptLink("~/Scripts/iscroll.js");
            RockPage.AddScriptLink("~/Scripts/CheckinClient/checkin-core.js");

            if (CurrentWorkflow == null || CurrentCheckInState == null)
            {
                NavigateToHomePage();
            }
            else
            {
                if (!Page.IsPostBack)
                {
                    ClearSelection();

                    CheckInPerson person = null;
                    CheckInGroup  group  = null;

                    person = CurrentCheckInState.CheckIn.Families.Where(f => f.Selected)
                             .SelectMany(f => f.People.Where(p => p.Selected))
                             .FirstOrDefault();

                    if (person != null)
                    {
                        group = person.GroupTypes.Where(t => t.Selected)
                                .SelectMany(t => t.Groups.Where(g => g.Selected))
                                .FirstOrDefault();
                    }

                    if (group == null)
                    {
                        GoBack();
                    }

                    lTitle.Text    = person.ToString();
                    lSubTitle.Text = group.ToString();

                    var availLocations = group.Locations.Where(l => !l.ExcludedByFilter).ToList();
                    if (availLocations.Count == 1)
                    {
                        if (UserBackedUp)
                        {
                            GoBack();
                        }
                        else
                        {
                            availLocations.FirstOrDefault().Selected = true;
                            ProcessSelection();
                        }
                    }
                    else
                    {
                        rSelection.DataSource = availLocations
                                                .OrderBy(l => l.Location.Name)
                                                .ToList();

                        rSelection.DataBind();
                    }
                }
            }
        }
Пример #18
0
        public void RaisePostBackEvent(string eventArgument)
        {
            if (_batch != null)
            {
                if (eventArgument == "MoveTransactions" &&
                    _ddlMove != null &&
                    _ddlMove.SelectedValue != null &&
                    !String.IsNullOrWhiteSpace(_ddlMove.SelectedValue))
                {
                    var txnsSelected = new List <int>();

                    gTransactions.SelectedKeys.ToList().ForEach(b => txnsSelected.Add(b.ToString().AsInteger()));

                    if (txnsSelected.Any())
                    {
                        var rockContext  = new RockContext();
                        var batchService = new FinancialBatchService(rockContext);

                        var newBatch = batchService.Get(_ddlMove.SelectedValue.AsInteger());
                        var oldBatch = batchService.Get(_batch.Id);

                        if (newBatch != null && newBatch.Status == BatchStatus.Open)
                        {
                            var txnService   = new FinancialTransactionService(rockContext);
                            var txnsToUpdate = txnService.Queryable()
                                               .Where(t => txnsSelected.Contains(t.Id))
                                               .ToList();

                            foreach (var txn in txnsToUpdate)
                            {
                                txn.BatchId             = newBatch.Id;
                                oldBatch.ControlAmount -= txn.TotalAmount;
                                newBatch.ControlAmount += txn.TotalAmount;
                            }

                            rockContext.SaveChanges();

                            var pageRef = new Rock.Web.PageReference(RockPage.PageId);
                            pageRef.Parameters = new Dictionary <string, string>();
                            pageRef.Parameters.Add("batchid", newBatch.Id.ToString());
                            string newBatchLink = string.Format("<a href='{0}'>{1}</a>",
                                                                pageRef.BuildUrl(), newBatch.Name);

                            RockPage.UpdateBlocks("~/Blocks/Finance/BatchDetail.ascx");

                            nbResult.Text = string.Format("{0} transactions were moved to the '{1}' batch.",
                                                          txnsToUpdate.Count().ToString("N0"), newBatchLink);
                            nbResult.NotificationBoxType = NotificationBoxType.Success;
                            nbResult.Visible             = true;
                        }
                        else
                        {
                            nbResult.Text = string.Format("The selected batch does not exist, or is no longer open.");
                            nbResult.NotificationBoxType = NotificationBoxType.Danger;
                            nbResult.Visible             = true;
                        }
                    }
                    else
                    {
                        nbResult.Text = string.Format("There were not any transactions selected.");
                        nbResult.NotificationBoxType = NotificationBoxType.Warning;
                        nbResult.Visible             = true;
                    }
                }

                _ddlMove.SelectedIndex = 0;
            }

            BindGrid();
        }
Пример #19
0
        /// <summary>
        /// Loads the content.
        /// </summary>
        private void LoadContent()
        {
            var rockContext       = new RockContext();
            var eventCalendarGuid = GetAttributeValue("EventCalendar").AsGuid();
            var eventCalendar     = new EventCalendarService(rockContext).Get(eventCalendarGuid);

            if (eventCalendar == null)
            {
                lMessages.Text = "<div class='alert alert-warning'>No event calendar is configured for this block.</div>";
                lContent.Text  = string.Empty;
                return;
            }
            else
            {
                lMessages.Text = string.Empty;
            }

            var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);

            // Grab events
            // NOTE: Do not use AsNoTracking() so that things can be lazy loaded if needed
            var qry = eventItemOccurrenceService
                      .Queryable("EventItem, EventItem.EventItemAudiences,Schedule")
                      .Where(m =>
                             m.EventItem.EventCalendarItems.Any(i => i.EventCalendarId == eventCalendar.Id) &&
                             m.EventItem.IsActive);

            // Filter by campus (always include the "All Campuses" events)
            if (GetAttributeValue("UseCampusContext").AsBoolean())
            {
                var campusEntityType = EntityTypeCache.Get <Campus>();
                var contextCampus    = RockPage.GetCurrentContext(campusEntityType) as Campus;

                if (contextCampus != null)
                {
                    qry = qry.Where(e => e.CampusId == contextCampus.Id || !e.CampusId.HasValue);
                }
            }
            else
            {
                var campusGuidList = GetAttributeValue("Campuses").Split(',').AsGuidList();
                if (campusGuidList.Any())
                {
                    qry = qry.Where(e => !e.CampusId.HasValue || campusGuidList.Contains(e.Campus.Guid));
                }
            }

            // make sure they have a date range
            var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(this.GetAttributeValue("DateRange"));
            var today     = RockDateTime.Today;

            dateRange.Start = dateRange.Start ?? today;
            if (dateRange.End == null)
            {
                dateRange.End = dateRange.Start.Value.AddDays(1000);
            }

            // Get the occurrences
            var occurrences          = qry.ToList();
            var occurrencesWithDates = occurrences
                                       .Select(o => new EventOccurrenceDate
            {
                EventItemOccurrence = o,
                Dates = o.GetStartTimes(dateRange.Start.Value, dateRange.End.Value).ToList()
            })
                                       .Where(d => d.Dates.Any())
                                       .ToList();

            CalendarEventDates = new List <DateTime>();

            var eventOccurrenceSummaries = new List <EventOccurrenceSummary>();

            foreach (var occurrenceDates in occurrencesWithDates)
            {
                var eventItemOccurrence = occurrenceDates.EventItemOccurrence;
                foreach (var datetime in occurrenceDates.Dates)
                {
                    CalendarEventDates.Add(datetime.Date);

                    if (datetime >= dateRange.Start.Value && datetime < dateRange.End.Value)
                    {
                        eventOccurrenceSummaries.Add(new EventOccurrenceSummary
                        {
                            EventItemOccurrence = eventItemOccurrence,
                            EventItem           = eventItemOccurrence.EventItem,
                            Name        = eventItemOccurrence.EventItem.Name,
                            DateTime    = datetime,
                            Date        = datetime.ToShortDateString(),
                            Time        = datetime.ToShortTimeString(),
                            Location    = eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses",
                            Description = eventItemOccurrence.EventItem.Description,
                            Summary     = eventItemOccurrence.EventItem.Summary,
                            DetailPage  = string.IsNullOrWhiteSpace(eventItemOccurrence.EventItem.DetailsUrl) ? null : eventItemOccurrence.EventItem.DetailsUrl
                        });
                    }
                }
            }

            eventOccurrenceSummaries = eventOccurrenceSummaries
                                       .OrderBy(e => e.DateTime)
                                       .ThenBy(e => e.Name)
                                       .ToList();

            // limit results
            int?maxItems = GetAttributeValue("MaxOccurrences").AsIntegerOrNull();

            if (maxItems.HasValue)
            {
                eventOccurrenceSummaries = eventOccurrenceSummaries.Take(maxItems.Value).ToList();
            }

            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);

            mergeFields.Add("DetailsPage", LinkedPageRoute("DetailsPage"));
            mergeFields.Add("EventOccurrenceSummaries", eventOccurrenceSummaries);

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

            RockPage.AddScriptLink("~/Scripts/iscroll.js");
            RockPage.AddScriptLink("~/Scripts/CheckinClient/checkin-core.js");

            var bodyTag = this.Page.Master.FindControl("bodyTag") as HtmlGenericControl;

            if (bodyTag != null)
            {
                bodyTag.AddCssClass("checkin-groupselect-bg");
            }

            if (CurrentWorkflow == null || CurrentCheckInState == null)
            {
                NavigateToHomePage();
            }
            else
            {
                if (!Page.IsPostBack)
                {
                    ClearSelection();

                    var person = CurrentCheckInState.CheckIn.CurrentPerson;
                    if (person == null)
                    {
                        GoBack();
                    }

                    var schedule = person.CurrentSchedule;

                    var groupTypes = person.SelectedGroupTypes(schedule);
                    if (groupTypes == null || !groupTypes.Any())
                    {
                        GoBack();
                    }

                    lTitle.Text = GetPersonScheduleSubTitle();

                    lSubTitle.Text = groupTypes
                                     .Where(t => t.GroupType != null)
                                     .Select(t => t.GroupType.Name)
                                     .ToList().AsDelimited(", ");

                    var availGroups = groupTypes.SelectMany(t => t.GetAvailableGroups(schedule)).ToList();
                    if (availGroups.Any())
                    {
                        if (availGroups.Count == 1)
                        {
                            if (UserBackedUp)
                            {
                                GoBack();
                            }
                            else
                            {
                                var group = availGroups.First();
                                if (schedule == null)
                                {
                                    group.Selected = true;
                                }
                                else
                                {
                                    group.SelectedForSchedule.Add(schedule.Schedule.Id);
                                }

                                ProcessSelection(person, schedule);
                            }
                        }
                        else
                        {
                            rSelection.DataSource = availGroups
                                                    .OrderBy(g => g.Group.Order)
                                                    .ToList();

                            rSelection.DataBind();
                        }
                    }
                    else
                    {
                        if (UserBackedUp)
                        {
                            GoBack();
                        }
                        else
                        {
                            pnlNoOptions.Visible   = true;
                            rSelection.Visible     = false;
                            lNoOptionName.Text     = person.Person.NickName;
                            lNoOptionSchedule.Text = person.CurrentSchedule != null?person.CurrentSchedule.ToString() : "this time";
                        }
                    }
                }
            }
        }
Пример #21
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            RockPage.AddScriptLink("~/Scripts/iscroll.js");
            RockPage.AddScriptLink("~/Scripts/CheckinClient/checkin-core.js");

            var bodyTag = this.Page.Master.FindControl("bodyTag") as HtmlGenericControl;

            if (bodyTag != null)
            {
                bodyTag.AddCssClass("checkin-timeselect-bg");
            }

            if (CurrentWorkflow == null || CurrentCheckInState == null)
            {
                NavigateToHomePage();
            }
            else
            {
                if (!Page.IsPostBack)
                {
                    ClearSelection();

                    var personSchedules   = new List <CheckInSchedule>();
                    var distinctSchedules = new List <CheckInSchedule>();
                    if (CurrentCheckInType != null && CurrentCheckInType.TypeOfCheckin == TypeOfCheckin.Family)
                    {
                        CheckInFamily family = CurrentCheckInState.CheckIn.CurrentFamily;
                        if (family != null)
                        {
                            foreach (var schedule in family.GetPeople(true).SelectMany(p => p.PossibleSchedules).ToList())
                            {
                                personSchedules.Add(schedule);
                                if (!distinctSchedules.Any(s => s.Schedule.Id == schedule.Schedule.Id))
                                {
                                    distinctSchedules.Add(schedule);
                                }
                            }
                        }
                        else
                        {
                            GoBack();
                        }

                        lTitle.Text   = family.ToString();
                        lbSelect.Text = "Next";
                        lbSelect.Attributes.Add("data-loading-text", "Loading...");
                    }
                    else
                    {
                        CheckInPerson person = CurrentCheckInState.CheckIn.Families.Where(f => f.Selected)
                                               .SelectMany(f => f.People.Where(p => p.Selected))
                                               .FirstOrDefault();

                        CheckInGroup    group    = null;
                        CheckInLocation location = null;

                        if (person != null)
                        {
                            group = person.GroupTypes.Where(t => t.Selected)
                                    .SelectMany(t => t.Groups.Where(g => g.Selected))
                                    .FirstOrDefault();

                            if (group != null)
                            {
                                location = group.Locations.Where(l => l.Selected)
                                           .FirstOrDefault();
                            }
                        }

                        if (location == null)
                        {
                            GoBack();
                        }

                        lTitle.Text    = person.ToString();
                        lSubTitle.Text = string.Format("{0} - {1}", group.ToString(), location.ToString());
                        lbSelect.Text  = "Check In";
                        lbSelect.Attributes.Add("data-loading-text", "Printing...");

                        personSchedules   = location.Schedules.Where(s => !s.ExcludedByFilter).ToList();
                        distinctSchedules = personSchedules;
                    }

                    if (distinctSchedules.Count == 1)
                    {
                        personSchedules.ForEach(s => s.Selected = true);
                        ProcessSelection(maWarning);
                    }
                    else
                    {
                        string script = string.Format(@"
    <script>
        function GetTimeSelection() {{
            var ids = '';
            $('div.checkin-timelist button.active').each( function() {{
                ids += $(this).attr('schedule-id') + ',';
            }});
            if (ids == '') {{
                bootbox.alert('Please select at least one time');
                return false;
            }}
            else
            {{
                $('#{0}').button('loading')
                $('#{1}').val(ids);
                return true;
            }}
        }}
    </script>
", lbSelect.ClientID, hfTimes.ClientID);
                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "SelectTime", script);

                        rSelection.DataSource = distinctSchedules
                                                .OrderBy(s => s.StartTime.Value.TimeOfDay)
                                                .ThenBy(s => s.Schedule.Name)
                                                .ToList();

                        rSelection.DataBind();
                    }
                }
            }
        }
Пример #22
0
        private void DisplayDetails()
        {
            RockContext rockContext = new RockContext();

            EventItemService eventItemService = new EventItemService(rockContext);
            var qry = eventItemService
                      .Queryable();

            // get the eventItem id if the event item is set via block attribute
            var eventItemAttGuid = GetAttributeValue("EventItem").AsGuid();
            int eventItemId      = qry.Where(i => i.Guid == eventItemAttGuid).Select(i => i.Id).FirstOrDefault();

            // get the eventItem id if the event item block attribute isn't set
            if (eventItemId == 0 && !string.IsNullOrWhiteSpace(PageParameter("EventItemId")))
            {
                eventItemId = Convert.ToInt32(PageParameter("EventItemId"));
            }
            if (eventItemId > 0)
            {
                /*var qry = eventItemService
                 *  .Queryable()
                 *  ;*/
                qry = qry.Where(i => i.Id == eventItemId);
            }
            else
            {
                // Get the Slug Attribute
                var slugAttribute = AttributeCache.Get(GetAttributeValue("URLSlugAttribute").AsGuid());

                // get the slug
                if (!string.IsNullOrWhiteSpace(PageParameter("URLSlug")) && slugAttribute != null)
                {
                    int slugAttributeId = slugAttribute.Id;
                    EventCalendarItemService eventCalendarItemService = new EventCalendarItemService(rockContext);
                    AttributeValueService    attributeValueService    = new AttributeValueService(rockContext);

                    var tmQry = qry.Join(eventCalendarItemService.Queryable(),
                                         ei => ei.Id,
                                         aci => aci.EventItemId,
                                         (ei, aci) => new { EventItem = ei, EventCalendarItem = aci }
                                         )
                                .Join(attributeValueService.Queryable(),
                                      ei => new { Id = ei.EventCalendarItem.Id, AttributeId = slugAttributeId },
                                      av => new { Id = av.EntityId ?? 0, AttributeId = av.AttributeId },
                                      (ei, av) => new { EventItem = ei.EventItem, EventCalendarItem = ei.EventCalendarItem, Slug = av });

                    string urlSlug = PageParameter("URLSlug");

                    tmQry = tmQry.Where(obj => obj.Slug.Value.Contains(urlSlug));

                    // The page parameter could contain something like 'camp' while the slug value list contains 'camp-freedom' so we need to double-check
                    // to make sure we have an exact match
                    qry = tmQry.ToList().AsQueryable().Where(obj => obj.Slug.Value.ToLower().Split('|').Contains(urlSlug.ToLower())).Select(obj => obj.EventItem);
                }
                else
                {
                    // If we don't have an eventItemId or slug we shouldn't get the first item in the database.  That would be . . . not good
                    qry = null;
                }
            }

            if (qry != null)
            {
                var eventItem = qry.FirstOrDefault();

                if (eventItem != null)
                {
                    // removing any occurrences that don't have a start time in the next twelve months
                    var occurrenceList = eventItem.EventItemOccurrences.ToList();
                    occurrenceList.RemoveAll(o => o.GetStartTimes(RockDateTime.Now, RockDateTime.Now.AddYears(1)).Count() == 0);

                    //Check for Campus Id Parameter
                    var campusId = PageParameter("CampusId").AsIntegerOrNull();
                    if (campusId.HasValue)
                    {
                        //check if there's a campus with this id.
                        var campus = CampusCache.Get(campusId.Value);
                        if (campus != null)
                        {
                            occurrenceList.RemoveAll(o => o.CampusId != null && o.CampusId != campus.Id);
                        }
                    }

                    //Check for Campus
                    var campusStr = PageParameter("Campus");
                    if (!string.IsNullOrEmpty(campusStr))
                    {
                        //check if there's a campus with this name.
                        var campus = CampusCache.All().Where(c => c.Name.ToLower().RemoveSpaces() == campusStr.ToLower().RemoveSpaces()).FirstOrDefault();
                        if (campus != null)
                        {
                            occurrenceList.RemoveAll(o => o.CampusId != null && o.CampusId != campus.Id);
                        }
                        else
                        {
                            // check one more time to see if there's a campus slug that matches
                            campus = CampusCache.All().Where(c => c.AttributeValues["Slug"].ToString() == campusStr.ToLower()).FirstOrDefault();
                            if (campus != null)
                            {
                                occurrenceList.RemoveAll(o => o.CampusId != null && o.CampusId != campus.Id);
                            }
                        }
                    }

                    eventItem.EventItemOccurrences = occurrenceList.OrderBy(o => o.NextStartDateTime.HasValue ? o.NextStartDateTime : DateTime.Now).ToList();

                    var mergeFields = new Dictionary <string, object>();
                    mergeFields.Add("RegistrationPage", LinkedPageRoute("RegistrationPage"));

                    var campusEntityType = EntityTypeCache.Get("Rock.Model.Campus");
                    var contextCampus    = RockPage.GetCurrentContext(campusEntityType) as Campus;

                    if (contextCampus != null)
                    {
                        mergeFields.Add("CampusContext", contextCampus);
                    }

                    // determine registration status (Register, Full, or Join Wait List) for each unique registration instance
                    Dictionary <int, string> registrationStatusLabels = new Dictionary <int, string>();
                    foreach (var occurance in eventItem.EventItemOccurrences)
                    {
                        foreach (var registrationInstance in occurance.Linkages.Select(a => a.RegistrationInstance).Distinct().ToList())
                        {
                            if (registrationStatusLabels.ContainsKey(registrationInstance.Id))
                            {
                                continue;
                            }
                            var maxRegistrantCount       = 0;
                            var currentRegistrationCount = 0;

                            if (registrationInstance != null)
                            {
                                if (registrationInstance.MaxAttendees != 0)
                                {
                                    maxRegistrantCount = registrationInstance.MaxAttendees;
                                }
                            }


                            int?registrationSpotsAvailable = null;
                            if (maxRegistrantCount != 0)
                            {
                                currentRegistrationCount = new RegistrationRegistrantService(rockContext).Queryable().AsNoTracking()
                                                           .Where(r =>
                                                                  r.Registration.RegistrationInstanceId == registrationInstance.Id &&
                                                                  r.OnWaitList == false)
                                                           .Count();
                                registrationSpotsAvailable = maxRegistrantCount - currentRegistrationCount;
                            }

                            string registrationStatusLabel = "Register";

                            if (registrationSpotsAvailable.HasValue && registrationSpotsAvailable.Value < 1)
                            {
                                if (registrationInstance.RegistrationTemplate.WaitListEnabled)
                                {
                                    registrationStatusLabel = "Join Wait List";
                                }
                                else
                                {
                                    registrationStatusLabel = "Full";
                                }
                            }

                            registrationStatusLabels.Add(registrationInstance.Id, registrationStatusLabel);
                        }
                    }

                    // Status of each registration instance
                    mergeFields.Add("RegistrationStatusLabels", registrationStatusLabels);

                    mergeFields.Add("Event", eventItem);
                    mergeFields.Add("CurrentPerson", CurrentPerson);

                    lOutput.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields);

                    if (GetAttributeValue("SetPageTitle").AsBoolean())
                    {
                        string pageTitle = eventItem != null ? eventItem.Name : "Event";
                        RockPage.PageTitle    = pageTitle;
                        RockPage.BrowserTitle = String.Format("{0} | {1}", pageTitle, RockPage.Site.Name);
                        RockPage.Header.Title = String.Format("{0} | {1}", pageTitle, RockPage.Site.Name);
                    }
                }
                else
                {
                    lOutput.Text = EventNotFoundLava();
                }
            }
            else
            {
                lOutput.Text = EventNotFoundLava();
            }
        }
        /// <summary>
        /// Loads the schedules
        /// </summary>
        private void LoadScheduleDropdowns()
        {
            var scheduleEntityType = EntityTypeCache.Get(typeof(Schedule));
            var currentSchedule    = RockPage.GetCurrentContext(scheduleEntityType) as Schedule;

            var scheduleIdString = Request.QueryString["scheduleId"];

            if (scheduleIdString != null)
            {
                var scheduleId = scheduleIdString.AsInteger();

                // if there is a query parameter, ensure that the Schedule Context cookie is set (and has an updated expiration)
                // note, the Schedule Context might already match due to the query parameter, but has a different cookie context, so we still need to ensure the cookie context is updated
                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();
        }
Пример #24
0
        /// <summary>
        /// Loads the drop downs.
        /// </summary>
        private bool SetFilterControls()
        {
            // Get and verify the calendar id
            if (_calendarId <= 0)
            {
                ShowError("Configuration Error", "The 'Event Calendar' setting has not been set correctly.");
                return(false);
            }

            // Get and verify the view mode
            ViewMode = GetAttributeValue("DefaultViewOption");
            if (!GetAttributeValue(string.Format("Show{0}View", ViewMode)).AsBoolean())
            {
                ShowError("Configuration Error", string.Format("The Default View Option setting has been set to '{0}', but the Show {0} View setting has not been enabled.", ViewMode));
                return(false);
            }

            // Show/Hide calendar control
            pnlCalendar.Visible = GetAttributeValue("ShowSmallCalendar").AsBoolean();

            // Get the first/last dates based on today's date and the viewmode setting
            var today = RockDateTime.Today;

            FilterStartDate = today;
            FilterEndDate   = today;
            if (ViewMode == "Week")
            {
                FilterStartDate = today.StartOfWeek(_firstDayOfWeek);
                FilterEndDate   = today.EndOfWeek(_firstDayOfWeek);
            }
            else if (ViewMode == "Month")
            {
                FilterStartDate = new DateTime(today.Year, today.Month, 1);
                FilterEndDate   = FilterStartDate.Value.AddMonths(1).AddDays(-1);
            }

            // Setup small calendar Filter
            calEventCalendar.FirstDayOfWeek = _firstDayOfWeek.ConvertToInt().ToString().ConvertToEnum <FirstDayOfWeek>();
            calEventCalendar.SelectedDates.Clear();
            calEventCalendar.SelectedDates.SelectRange(FilterStartDate.Value, FilterEndDate.Value);

            // Setup Campus Filter
            rcwCampus.Visible    = GetAttributeValue("CampusFilterDisplayMode").AsInteger() > 1;
            cblCampus.DataSource = CampusCache.All();
            cblCampus.DataBind();
            if (GetAttributeValue("EnableCampusContext").AsBoolean())
            {
                var contextCampus = RockPage.GetCurrentContext(EntityTypeCache.Read("Rock.Model.Campus")) as Campus;
                if (contextCampus != null)
                {
                    cblCampus.SetValue(contextCampus.Id);
                }
            }

            // Setup Category Filter
            var selectedCategoryGuids = GetAttributeValue("FilterCategories").SplitDelimitedValues(true).AsGuidList();

            rcwCategory.Visible = selectedCategoryGuids.Any() && GetAttributeValue("CategoryFilterDisplayMode").AsInteger() > 1;
            var definedType = DefinedTypeCache.Read(Rock.SystemGuid.DefinedType.MARKETING_CAMPAIGN_AUDIENCE_TYPE.AsGuid());

            if (definedType != null)
            {
                cblCategory.DataSource = definedType.DefinedValues.Where(v => selectedCategoryGuids.Contains(v.Guid));
                cblCategory.DataBind();
            }

            // Date Range Filter
            drpDateRange.Visible       = GetAttributeValue("ShowDateRangeFilter").AsBoolean();
            lbDateRangeRefresh.Visible = drpDateRange.Visible;
            drpDateRange.LowerValue    = FilterStartDate;
            drpDateRange.UpperValue    = FilterEndDate;

            // Get the View Modes, and only show them if more than one is visible
            var viewsVisible = new List <bool> {
                GetAttributeValue("ShowDayView").AsBoolean(),
                GetAttributeValue("ShowWeekView").AsBoolean(),
                GetAttributeValue("ShowMonthView").AsBoolean()
            };
            var howManyVisible = viewsVisible.Where(v => v).Count();

            btnDay.Visible   = howManyVisible > 1 && viewsVisible[0];
            btnWeek.Visible  = howManyVisible > 1 && viewsVisible[1];
            btnMonth.Visible = howManyVisible > 1 && viewsVisible[2];

            // Set filter visibility
            bool showFilter = (pnlCalendar.Visible || rcwCampus.Visible || rcwCategory.Visible || drpDateRange.Visible);

            pnlFilters.Visible = showFilter;
            pnlList.CssClass   = showFilter ? "col-md-9" : "col-md-12";

            return(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)
        {
            base.OnInit(e);

            gRegInstances.DataKeyNames = new string[] { "Id" };
            gRegInstances.GridRebind  += gRegInstances_GridRebind;

            // hide this block if it determines it's on the event detail page
            if (RockPage.PageParameter("RegistrationTemplateId").IsNotNullOrWhiteSpace() || RockPage.PageParameter("CategoryId").IsNotNullOrWhiteSpace())
            {
                this.Visible = false;
            }
        }
        /// <summary>
        /// Updates the list.
        /// </summary>
        private void UpdateList()
        {
            using (var rockContext = new RockContext())
            {
                var searchSelections = new Dictionary <string, string>();

                var connectionTypeId             = GetAttributeValue(AttributeKey.ConnectionTypeId).AsInteger();
                var connectionType               = new ConnectionTypeService(rockContext).Get(connectionTypeId);
                var connectionOpportunityService = new ConnectionOpportunityService(rockContext);

                var qrySearch = connectionOpportunityService.Queryable().Where(a => a.ConnectionTypeId == connectionTypeId && a.IsActive && a.ConnectionType.IsActive);

                if (GetAttributeValue(AttributeKey.DisplayNameFilter).AsBoolean())
                {
                    tbSearchName.Label = GetAttributeValue(AttributeKey.NameLabel);
                    if (!string.IsNullOrWhiteSpace(tbSearchName.Text))
                    {
                        searchSelections.Add("tbSearchName", tbSearchName.Text);
                        var searchTerms = tbSearchName.Text.ToLower().SplitDelimitedValues(true);
                        if (GetAttributeValue(AttributeKey.SearchDescription).AsBoolean())
                        {
                            qrySearch = qrySearch.Where(o => searchTerms.Any(t => t.Contains(o.Name.ToLower()) || o.Name.ToLower().Contains(t) || t.Contains(o.Summary.ToLower()) || o.Summary.ToLower().Contains(t) || t.Contains(o.Description.ToLower()) || o.Description.ToLower().Contains(t)));
                        }
                        else
                        {
                            qrySearch = qrySearch.Where(o => searchTerms.Any(t => t.Contains(o.Name.ToLower()) || o.Name.ToLower().Contains(t)));
                        }
                    }
                }

                if (GetAttributeValue(AttributeKey.DisplayCampusFilter).AsBoolean())
                {
                    cblCampus.Label = GetAttributeValue(AttributeKey.CampusLabel);
                    var searchCampuses = cblCampus.SelectedValuesAsInt;
                    if (searchCampuses.Count > 0)
                    {
                        searchSelections.Add("cblCampus", searchCampuses.AsDelimited("|"));
                        qrySearch = qrySearch.Where(o => o.ConnectionOpportunityCampuses.Any(c => searchCampuses.Contains(c.CampusId)));
                    }
                }

                if (GetAttributeValue(AttributeKey.DisplayAttributeFilters).AsBoolean())
                {
                    // Filter query by any configured attribute filters
                    if (AvailableAttributes != null && AvailableAttributes.Any())
                    {
                        foreach (var attribute in AvailableAttributes)
                        {
                            string filterControlId = "filter_" + attribute.Id.ToString();
                            var    filterControl   = phAttributeFilters.FindControl(filterControlId);
                            qrySearch = attribute.FieldType.Field.ApplyAttributeQueryFilter(qrySearch, filterControl, attribute, connectionOpportunityService, Rock.Reporting.FilterMode.SimpleFilter);
                        }
                    }
                }

                if (AttributeOne != null)
                {
                    var control = phAttributeOne.Controls[0] as DropDownList;
                    if (control != null)
                    {
                        searchSelections.Add("ddlAttributeOne", control.SelectedValue);

                        var attributeValueService = new AttributeValueService(rockContext);
                        var parameterExpression   = attributeValueService.ParameterExpression;

                        var value = AttributeOne.FieldType.Field.GetEditValue(control, AttributeOne.QualifierValues);
                        if (!string.IsNullOrWhiteSpace(value))
                        {
                            var attributeValues = attributeValueService
                                                  .Queryable()
                                                  .Where(v => v.Attribute.Id == AttributeOne.Id)
                                                  .Where(v => v.Value.Equals(value));
                            qrySearch = qrySearch.Where(o => attributeValues.Select(v => v.EntityId).Contains(o.Id));
                        }
                    }
                    else
                    {
                        var newDdlOne = phAttributeOne.Controls[2] as DropDownList;

                        searchSelections.Add("ddlAttributeOne", newDdlOne.SelectedValue);

                        var attributeValueService = new AttributeValueService(rockContext);
                        var parameterExpression   = attributeValueService.ParameterExpression;

                        var value = newDdlOne.SelectedValue;
                        if (!string.IsNullOrWhiteSpace(value))
                        {
                            var attributeValues = attributeValueService
                                                  .Queryable()
                                                  .Where(v => v.Attribute.Id == AttributeOne.Id)
                                                  .Where(v => v.Value.Contains(value));
                            qrySearch = qrySearch.Where(o => attributeValues.Select(v => v.EntityId).Contains(o.Id));
                        }
                    }
                }

                if (AttributeTwo != null)
                {
                    var control = phAttributeTwo.Controls[0] as DropDownList;
                    if (control != null)
                    {
                        searchSelections.Add("ddlAttributeTwo", control.SelectedValue);

                        var attributeValueService = new AttributeValueService(rockContext);
                        var parameterExpression   = attributeValueService.ParameterExpression;

                        var value = AttributeTwo.FieldType.Field.GetEditValue(control, AttributeTwo.QualifierValues);
                        if (!string.IsNullOrWhiteSpace(value))
                        {
                            var attributeValues = attributeValueService
                                                  .Queryable()
                                                  .Where(v => v.Attribute.Id == AttributeTwo.Id)
                                                  .Where(v => v.Value.Equals(value));
                            qrySearch = qrySearch.Where(o => attributeValues.Select(v => v.EntityId).Contains(o.Id));
                        }
                    }
                    else
                    {
                        var newDdlTwo = phAttributeTwo.Controls[2] as DropDownList;

                        searchSelections.Add("ddlAttributeTwo", newDdlTwo.SelectedValue);

                        var attributeValueService = new AttributeValueService(rockContext);
                        var parameterExpression   = attributeValueService.ParameterExpression;

                        var value = newDdlTwo.SelectedValue;
                        if (!string.IsNullOrWhiteSpace(value))
                        {
                            var attributeValues = attributeValueService
                                                  .Queryable()
                                                  .Where(v => v.Attribute.Id == AttributeTwo.Id)
                                                  .Where(v => v.Value.Contains(value));
                            qrySearch = qrySearch.Where(o => attributeValues.Select(v => v.EntityId).Contains(o.Id));
                        }
                    }
                }

                string sessionKey = string.Format("ConnectionSearch_{0}", this.BlockId);
                Session[sessionKey] = searchSelections;

                var opportunities = qrySearch.OrderBy(s => s.PublicName).ToList();

                var mergeFields = new Dictionary <string, object>();
                mergeFields.Add("CurrentPerson", CurrentPerson);
                mergeFields.Add("CampusContext", RockPage.GetCurrentContext(EntityTypeCache.Get("Rock.Model.Campus")) as Campus);
                var pageReference = new PageReference(GetAttributeValue(AttributeKey.DetailPage), null);
                mergeFields.Add("DetailPage", BuildDetailPageUrl(pageReference.BuildUrl()));

                // iterate through the opportunities and lava merge the summaries and descriptions
                foreach (var opportunity in opportunities)
                {
                    opportunity.Summary     = opportunity.Summary.ResolveMergeFields(mergeFields);
                    opportunity.Description = opportunity.Description.ResolveMergeFields(mergeFields);
                }

                mergeFields.Add("Opportunities", opportunities);

                lOutput.Text = GetAttributeValue(AttributeKey.LavaTemplate).ResolveMergeFields(mergeFields);

                if (GetAttributeValue(AttributeKey.SetPageTitle).AsBoolean())
                {
                    string pageTitle = "Connection";
                    RockPage.PageTitle    = pageTitle;
                    RockPage.BrowserTitle = String.Format("{0} | {1}", pageTitle, RockPage.Site.Name);
                    RockPage.Header.Title = String.Format("{0} | {1}", pageTitle, RockPage.Site.Name);
                }
            }
        }
Пример #27
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>EventItem
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            gAudiences.DataKeyNames      = new string[] { "Guid" };
            gAudiences.Actions.ShowAdd   = true;
            gAudiences.Actions.AddClick += gAudiences_Add;
            gAudiences.GridRebind       += gAudiences_GridRebind;

            // 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(upnlEventItemList);

            // Get the calendar id of the calendar that user navigated from
            _calendarId = PageParameter("EventCalendarId").AsIntegerOrNull();

            _canEdit    = UserCanEdit;
            _canApprove = UserCanAdministrate;

            // Load the other calendars user is authorized to view
            cblCalendars.Items.Clear();
            using (var rockContext = new RockContext())
            {
                foreach (var calendar in new EventCalendarService(rockContext)
                         .Queryable().AsNoTracking()
                         .OrderBy(c => c.Name))
                {
                    if (!_calendarId.HasValue && calendar.IsAuthorized(Authorization.EDIT, CurrentPerson))
                    {
                        _calendarId = calendar.Id;
                    }

                    if (calendar.Id == (_calendarId ?? 0))
                    {
                        _canEdit = _canEdit ||
                                   calendar.IsAuthorized(Authorization.EDIT, CurrentPerson);

                        _canApprove = _canApprove ||
                                      calendar.IsAuthorized(Authorization.APPROVE, CurrentPerson) ||
                                      calendar.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson);
                    }

                    if (UserCanEdit || calendar.IsAuthorized(Authorization.EDIT, CurrentPerson))
                    {
                        cblCalendars.Items.Add(new ListItem(calendar.Name, calendar.Id.ToString()));
                    }
                }
            }
            cblCalendars.SelectedIndexChanged += cblCalendars_SelectedIndexChanged;

            RockPage.AddCSSLink(ResolveRockUrl("~/Styles/fluidbox.css"));
            RockPage.AddScriptLink(ResolveRockUrl("~/Scripts/imagesloaded.min.js"));
            RockPage.AddScriptLink(ResolveRockUrl("~/Scripts/jquery.fluidbox.min.js"));
            ScriptManager.RegisterStartupScript(lImage, lImage.GetType(), "image-fluidbox", "$('.photo a').fluidbox();", true);

            string deleteScript = @"
    $('a.js-delete-event').click(function( e ){
        e.preventDefault();
        Rock.dialogs.confirm('Are you sure you want to delete this event? All of the event occurrences will also be deleted!', function (result) {
            if (result) {
                window.location = e.target.href ? e.target.href : e.target.parentElement.href;
            }
        });
    });
";

            ScriptManager.RegisterStartupScript(btnDelete, btnDelete.GetType(), "deleteInstanceScript", deleteScript, true);
        }
        /// <summary>
        /// Sets the filters.
        /// </summary>
        private void SetFilters(bool setValues)
        {
            using (var rockContext = new RockContext())
            {
                string sessionKey       = string.Format("ConnectionSearch_{0}", this.BlockId);
                var    searchSelections = Session[sessionKey] as Dictionary <string, string>;
                setValues = setValues && searchSelections != null;

                var connectionType = new ConnectionTypeService(rockContext).Get(GetAttributeValue(AttributeKey.ConnectionTypeId).AsInteger());

                if (!GetAttributeValue(AttributeKey.DisplayNameFilter).AsBoolean())
                {
                    tbSearchName.Visible = false;
                }

                if (GetAttributeValue(AttributeKey.DisplayCampusFilter).AsBoolean())
                {
                    cblCampus.Visible    = true;
                    cblCampus.DataSource = CampusCache.All(GetAttributeValue(AttributeKey.DisplayInactiveCampuses).AsBoolean());
                    cblCampus.DataBind();
                }
                else
                {
                    cblCampus.Visible = false;
                }

                if (setValues)
                {
                    if (searchSelections.ContainsKey("tbSearchName"))
                    {
                        tbSearchName.Text = searchSelections["tbSearchName"];
                    }
                    if (searchSelections.ContainsKey("cblCampus"))
                    {
                        var selectedItems = searchSelections["cblCampus"].SplitDelimitedValues().AsIntegerList();
                        cblCampus.SetValues(selectedItems);
                    }
                }
                else if (GetAttributeValue(AttributeKey.EnableCampusContext).AsBoolean())
                {
                    var campusEntityType = EntityTypeCache.Get("Rock.Model.Campus");
                    var contextCampus    = RockPage.GetCurrentContext(campusEntityType) as Campus;

                    if (contextCampus != null)
                    {
                        cblCampus.SetValue(contextCampus.Id.ToString());
                    }
                }

                if (GetAttributeValue(AttributeKey.DisplayAttributeFilters).AsBoolean())
                {
                    // Parse the attribute filters
                    AvailableAttributes = new List <AttributeCache>();
                    if (connectionType != null)
                    {
                        int entityTypeId = new ConnectionOpportunity().TypeId;
                        foreach (var attributeModel in new AttributeService(new RockContext()).Queryable()
                                 .Where(a =>
                                        a.EntityTypeId == entityTypeId &&
                                        a.EntityTypeQualifierColumn.Equals("ConnectionTypeId", StringComparison.OrdinalIgnoreCase) &&
                                        a.EntityTypeQualifierValue.Equals(connectionType.Id.ToString()) &&
                                        a.AllowSearch == true)
                                 .OrderBy(a => a.Order)
                                 .ThenBy(a => a.Name))
                        {
                            AvailableAttributes.Add(AttributeCache.Get(attributeModel));
                        }
                    }

                    // Clear the filter controls
                    phAttributeFilters.Controls.Clear();

                    if (AvailableAttributes != null)
                    {
                        foreach (var attribute in AvailableAttributes)
                        {
                            string controlId = "filter_" + attribute.Id.ToString();
                            var    control   = attribute.FieldType.Field.FilterControl(attribute.QualifierValues, controlId, 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);
                                }

                                if (setValues && searchSelections.ContainsKey(controlId))
                                {
                                    var values = searchSelections[controlId].FromJsonOrNull <List <string> >();
                                    attribute.FieldType.Field.SetFilterValues(control, attribute.QualifierValues, values);
                                }
                            }
                        }
                    }
                }
                else
                {
                    phAttributeFilters.Visible = false;
                }

                if (connectionType != null)
                {
                    int entityTypeId    = new ConnectionOpportunity().TypeId;
                    var attributeOneKey = GetAttributeValue(AttributeKey.AttributeOneKey);
                    var attributeTwoKey = GetAttributeValue(AttributeKey.AttributeTwoKey);

                    if (!string.IsNullOrWhiteSpace(attributeOneKey))
                    {
                        if (!string.IsNullOrWhiteSpace(attributeTwoKey))
                        {
                            pnlAttributeOne.CssClass = "col-sm-6";
                        }
                        else
                        {
                            pnlAttributeOne.CssClass = "col-sm-12";
                        }

                        AttributeOne = AttributeCache.Get(new AttributeService(new RockContext()).Queryable()
                                                          .FirstOrDefault(a =>
                                                                          a.EntityTypeId == entityTypeId &&
                                                                          a.EntityTypeQualifierColumn.Equals("ConnectionTypeId", StringComparison.OrdinalIgnoreCase) &&
                                                                          a.EntityTypeQualifierValue.Equals(connectionType.Id.ToString()) &&
                                                                          a.Key == attributeOneKey));
                    }

                    if (!string.IsNullOrWhiteSpace(attributeTwoKey))
                    {
                        if (!string.IsNullOrWhiteSpace(attributeOneKey))
                        {
                            pnlAttributeTwo.CssClass = "col-sm-6";
                        }
                        else
                        {
                            pnlAttributeTwo.CssClass = "col-sm-12";
                        }

                        AttributeTwo = AttributeCache.Get(new AttributeService(new RockContext()).Queryable()
                                                          .FirstOrDefault(a =>
                                                                          a.EntityTypeId == entityTypeId &&
                                                                          a.EntityTypeQualifierColumn.Equals("ConnectionTypeId", StringComparison.OrdinalIgnoreCase) &&
                                                                          a.EntityTypeQualifierValue.Equals(connectionType.Id.ToString()) &&
                                                                          a.Key == attributeTwoKey));
                    }
                }

                if (AttributeOne != null)
                {
                    phAttributeOne.Controls.Clear();
                    AttributeOne.AddControl(phAttributeOne.Controls, string.Empty, string.Empty, true, true, false);
                    var control = phAttributeOne.Controls[0] as DropDownList;
                    if (control != null)
                    {
                        control.EnableViewState       = true;
                        control.AutoPostBack          = true;
                        control.SelectedIndexChanged += new EventHandler(ddlAttributeOne_SelectedIndexChanged);
                    }
                    else
                    {
                        var          theseControls = phAttributeOne.Controls[0] as DropDownList;
                        DropDownList ddl           = new DropDownList();
                        string[]     theseValues   = AttributeOne.QualifierValues.Values.ElementAt(0).Value.Split(',');
                        if (theseValues.Count() == 1 && theseValues[0] == "rb")
                        {
                            theseValues = AttributeOne.QualifierValues.Values.ElementAt(1).Value.Split(',');
                        }
                        foreach (string nameValue in theseValues)
                        {
                            string[] nameAndValue = nameValue.Split(new char[] { '^' });

                            if (nameAndValue.Length == 2)
                            {
                                ddl.Items.Add(new ListItem(nameAndValue[1].Trim(), nameAndValue[0].Trim()));
                            }
                        }

                        ddl.Items.Insert(0, new ListItem(String.Empty, String.Empty));
                        ddl.SelectedIndex = 0;
                        ddl.CssClass      = "form-control";
                        var attributeOneLabel = new HtmlGenericContainer("label");
                        attributeOneLabel.InnerHtml = AttributeOne.Name;
                        attributeOneLabel.CssClass  = "control-label";

                        phAttributeOne.Controls.Clear();
                        phAttributeOne.Controls.Add(new Literal()
                        {
                            Text = "<div class='form-group rock-drop-down-list'>"
                        });
                        phAttributeOne.Controls.Add(attributeOneLabel);
                        phAttributeOne.Controls.Add(ddl);
                        phAttributeOne.Controls.Add(new Literal()
                        {
                            Text = "</div>"
                        });

                        var newDdl = phAttributeOne.Controls[2] as DropDownList;

                        newDdl.EnableViewState       = true;
                        newDdl.AutoPostBack          = true;
                        newDdl.SelectedIndexChanged += new EventHandler(ddlAttributeOne_SelectedIndexChanged);
                    }
                }

                if (AttributeTwo != null)
                {
                    phAttributeTwo.Controls.Clear();
                    AttributeTwo.AddControl(phAttributeTwo.Controls, string.Empty, string.Empty, true, true, false);
                    var control = phAttributeTwo.Controls[0] as DropDownList;
                    if (control != null)
                    {
                        control.EnableViewState       = true;
                        control.AutoPostBack          = true;
                        control.SelectedIndexChanged += new EventHandler(ddlAttributeTwo_SelectedIndexChanged);
                    }
                    else
                    {
                        var          theseControls = phAttributeTwo.Controls[0] as DropDownList;
                        DropDownList ddl           = new DropDownList();
                        string[]     theseValues   = AttributeTwo.QualifierValues.Values.ElementAt(0).Value.Split(',');
                        if (theseValues.Count() == 1 && theseValues[0] == "rb")
                        {
                            theseValues = AttributeTwo.QualifierValues.Values.ElementAt(1).Value.Split(',');
                        }

                        foreach (string nameValue in theseValues)
                        {
                            string[] nameAndValue = nameValue.Split(new char[] { '^' });

                            if (nameAndValue.Length == 2)
                            {
                                ddl.Items.Add(new ListItem(nameAndValue[1].Trim(), nameAndValue[0].Trim()));
                            }
                        }

                        ddl.Items.Insert(0, new ListItem(String.Empty, String.Empty));
                        ddl.SelectedIndex = 0;
                        ddl.CssClass      = "form-control";
                        var attributeTwoLabel = new HtmlGenericContainer("label");
                        attributeTwoLabel.InnerHtml = AttributeTwo.Name;
                        attributeTwoLabel.CssClass  = "control-label";

                        phAttributeTwo.Controls.Clear();
                        phAttributeTwo.Controls.Add(new Literal()
                        {
                            Text = "<div class='form-group rock-drop-down-list'>"
                        });
                        phAttributeTwo.Controls.Add(attributeTwoLabel);
                        phAttributeTwo.Controls.Add(ddl);
                        phAttributeTwo.Controls.Add(new Literal()
                        {
                            Text = "</div>"
                        });

                        var newDdl = phAttributeTwo.Controls[2] as DropDownList;

                        newDdl.EnableViewState       = true;
                        newDdl.AutoPostBack          = true;
                        newDdl.SelectedIndexChanged += new EventHandler(ddlAttributeTwo_SelectedIndexChanged);
                    }
                }
            }
        }
Пример #29
0
 /// <summary>
 /// Initialize stuff required for syntax highlighting.
 /// </summary>
 private void InitSyntaxHighlighting()
 {
     RockPage.AddCSSLink("~/Blocks/Examples/prettify.css");
     RockPage.AddScriptLink("//cdnjs.cloudflare.com/ajax/libs/prettify/r298/prettify.js", false);
 }
Пример #30
0
        /// <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();
            }
        }