/// <summary>
        /// Display Person Attribute on the Basis of Role
        /// </summary>
        /// <param name="selectedId">The id of the selected group identifier.</param>
        private void DisplayPersonAttributeOnRoleType(int?selectedId)
        {
            GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(new RockContext());
            List <Guid>          attributeGuidList    = new List <Guid>();
            var adultGuid     = Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid();
            var groupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid();

            if (selectedId.HasValue)
            {
                if (groupTypeRoleService.Queryable().Where(gr =>
                                                           gr.GroupType.Guid == groupTypeGuid &&
                                                           gr.Guid == adultGuid &&
                                                           gr.Id == selectedId).Any())
                {
                    attributeGuidList      = GetAttributeValue("PersonAttributes(adults)").SplitDelimitedValues().AsGuidList();
                    ddlGradePicker.Visible = false;
                    tbEmail.Required       = GetAttributeValue("RequireAdultEmailAddress").AsBoolean();
                    _IsEditRecordAdult     = true;
                    BindPhoneNumbers();
                }
                else
                {
                    attributeGuidList      = GetAttributeValue("PersonAttributes(children)").SplitDelimitedValues().AsGuidList();
                    ddlGradePicker.Visible = true;
                    tbEmail.Required       = false;
                    _IsEditRecordAdult     = false;
                    BindPhoneNumbers();
                }
            }
        }
        protected void rblRole_SelectedIndexChanged(object sender, EventArgs e)
        {
            GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(new RockContext());
            List <Guid>          attributeGuidList    = new List <Guid>();
            var adultGuid     = Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid();
            var groupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid();
            var selectedId    = rblRole.SelectedValueAsId();

            if (selectedId.HasValue)
            {
                if (groupTypeRoleService.Queryable().Where(gr =>
                                                           gr.GroupType.Guid == groupTypeGuid &&
                                                           gr.Guid == adultGuid &&
                                                           gr.Id == selectedId).Any())
                {
                    ddlGradePicker.Visible = false;
                    tbEmail.Required       = true;
                }
                else
                {
                    ddlGradePicker.Visible = true;
                    tbEmail.Required       = false;
                }
            }
        }
Exemplo n.º 3
0
        private void ShowModal(Person person, int?roleId, int?groupMemberId)
        {
            Guid roleGuid = Guid.Empty;

            if (Guid.TryParse(GetAttributeValue("GroupType/RoleFilter"), out roleGuid))
            {
                var groupTypeRoleService = new GroupTypeRoleService(new RockContext());
                var role = groupTypeRoleService.Get(ownerRoleGuid);
                grpRole.ExcludeGroupRoles.Add(role.Id);

                grpRole.GroupTypeId = groupTypeRoleService.Queryable()
                                      .Where(r => r.Guid == roleGuid)
                                      .Select(r => r.GroupTypeId)
                                      .FirstOrDefault();
            }
            grpRole.GroupRoleId = roleId;
            ppPerson.SetValue(person);

            ShowDialog(groupMemberId ?? 0, true);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Handles the SelectItem event of the gp 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 gp_SelectItem(object sender, EventArgs e)
        {
            var rockContext = new RockContext();

            int groupId      = gp.SelectedValueAsId() ?? 0;
            var groupService = new GroupService(rockContext);

            var group = groupService.Get(groupId);

            if (group != null)
            {
                var groupTypeRoleService = new GroupTypeRoleService(rockContext);
                var qryGroupTypeRoles    = groupTypeRoleService.Queryable();
                if (cbChildGroups.Checked)
                {
                    var childGroupTypeIds = groupService.GetAllDescendents(group.Id).Select(a => a.GroupTypeId).Distinct().ToList();
                    qryGroupTypeRoles = qryGroupTypeRoles.Where(a => a.GroupTypeId.HasValue && (a.GroupTypeId == group.GroupTypeId || childGroupTypeIds.Contains(a.GroupTypeId.Value)));
                }
                else
                {
                    qryGroupTypeRoles = qryGroupTypeRoles.Where(a => a.GroupTypeId.HasValue && a.GroupTypeId == group.GroupTypeId);
                }

                var list = qryGroupTypeRoles.OrderBy(a => a.GroupType.Order).ThenBy(a => a.GroupType.Name).ThenBy(a => a.Order).ThenBy(a => a.Name).ToList();
                cblRole.Items.Clear();
                foreach (var item in list)
                {
                    cblRole.Items.Add(new ListItem(string.Format("{0} ({1})", item.Name, item.GroupType.Name), item.Guid.ToString()));
                }

                cblRole.Visible       = list.Count > 0;
                cbChildGroups.Visible = true;
            }
            else
            {
                cblRole.Visible       = false;
                cbChildGroups.Visible = false;
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Handles the SelectedIndexChanged event of the ddlGroup control to populate the ddlGroupRole 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 ddlGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlGroupRole.Items.Clear();

            int?groupId = ddlGroup.SelectedValue.AsIntegerOrNull();

            if (groupId == null)
            {
                return;
            }

            ddlGroupRole.Required = true;
            var rockContext = new RockContext();

            var groupSyncService = new GroupSyncService(rockContext);
            var syncList         = groupSyncService
                                   .Queryable()
                                   .AsNoTracking()
                                   .Where(s => s.GroupId == groupId)
                                   .Select(s => s.GroupTypeRoleId)
                                   .ToList();

            nbModalDetailSyncMessage.Visible = syncList.Count > 0 ? true : false;

            var groupService  = new GroupService(rockContext);
            var selectedGroup = groupService.GetNoTracking(groupId.Value);

            var groupTypeRoleService = new GroupTypeRoleService(rockContext);
            var qry = groupTypeRoleService
                      .Queryable()
                      .AsNoTracking()
                      .Where(r => r.GroupTypeId == selectedGroup.GroupTypeId)
                      .Where(r => !syncList.Contains(r.Id))
                      .ToList();

            ddlGroupRole.DataSource = qry;
            ddlGroupRole.DataBind();
        }
Exemplo n.º 6
0
        /// <summary>
        /// Handles the SelectItem event of the gp 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 gp_SelectItem(object sender, EventArgs e)
        {
            int groupId      = gp.SelectedValueAsId() ?? 0;
            var groupService = new GroupService();
            var group        = groupService.Get(groupId);

            if (group != null)
            {
                var groupTypeRoleService = new GroupTypeRoleService();
                var list = groupTypeRoleService.Queryable().Where(a => a.GroupTypeId == group.GroupTypeId).OrderBy(a => a.Order).ToList();
                cblRole.Items.Clear();
                foreach (var item in list)
                {
                    cblRole.Items.Add(new ListItem(item.Name, item.Id.ToString()));
                }

                cblRole.Visible = list.Count > 0;
            }
            else
            {
                cblRole.Visible = false;
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Handles the SelectItem event of the gp 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 gp_SelectItem(object sender, EventArgs e)
        {
            var rockContext = new RockContext();

            var groupIdList  = gp.SelectedValues.AsIntegerList();
            var groupService = new GroupService(rockContext);

            var qryGroups = groupService.GetByIds(groupIdList);

            if (qryGroups.Any())
            {
                var        groupTypeRoleService = new GroupTypeRoleService(rockContext);
                var        qryGroupTypeRoles    = groupTypeRoleService.Queryable();
                List <int> selectedGroupTypeIds = qryGroups.Select(a => a.GroupTypeId).Distinct().ToList();

                if (cbChildGroups.Checked)
                {
                    List <int> childGroupTypeIds = new List <int>();
                    foreach (var groupId in qryGroups.Select(a => a.Id).ToList())
                    {
                        if (cbChildGroupsPlusDescendants.Checked)
                        {
                            // get all children and descendants of the selected group(s)
                            var descendants = groupService.GetAllDescendents(groupId);
                            if (!cbIncludeInactiveGroups.Checked)
                            {
                                descendants = descendants.Where(a => a.IsActive == true);
                            }

                            childGroupTypeIds.AddRange(descendants.Select(a => a.GroupTypeId).Distinct().ToList());
                        }
                        else
                        {
                            // get only immediate children of the selected group(s)
                            var childGroups = groupService.Queryable().Where(a => a.ParentGroupId == groupId);
                            if (!cbIncludeInactiveGroups.Checked)
                            {
                                childGroups = childGroups.Where(a => a.IsActive == true);
                            }

                            childGroupTypeIds.AddRange(childGroups.Select(a => a.GroupTypeId).Distinct().ToList());
                        }
                    }

                    childGroupTypeIds = childGroupTypeIds.Distinct().ToList();

                    if (cbIncludeSelectedGroup.Checked)
                    {
                        qryGroupTypeRoles = qryGroupTypeRoles.Where(a => a.GroupTypeId.HasValue && (selectedGroupTypeIds.Contains(a.GroupTypeId.Value) || childGroupTypeIds.Contains(a.GroupTypeId.Value)));
                    }
                    else
                    {
                        qryGroupTypeRoles = qryGroupTypeRoles.Where(a => a.GroupTypeId.HasValue && childGroupTypeIds.Contains(a.GroupTypeId.Value));
                    }
                }
                else
                {
                    qryGroupTypeRoles = qryGroupTypeRoles.Where(a => a.GroupTypeId.HasValue && selectedGroupTypeIds.Contains(a.GroupTypeId.Value));
                }

                var list = qryGroupTypeRoles.OrderBy(a => a.GroupType.Order).ThenBy(a => a.GroupType.Name).ThenBy(a => a.Order).ThenBy(a => a.Name).ToList();
                cblRole.Items.Clear();
                foreach (var item in list)
                {
                    cblRole.Items.Add(new ListItem(string.Format("{0} ({1})", item.Name, item.GroupType.Name), item.Guid.ToString()));
                }

                cblRole.Visible = list.Count > 0;
            }
            else
            {
                cblRole.Visible = false;
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Handles the SelectItem event of the gp 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 gp_SelectItem(object sender, EventArgs e)
        {
            FilterField filterField = (sender as Control).FirstParentControlOfType <FilterField>();

            GroupPicker      groupPicker   = filterField.ControlsOfTypeRecursive <GroupPicker>().FirstOrDefault(a => a.HasCssClass("js-group-picker"));
            RockCheckBox     cbChildGroups = filterField.ControlsOfTypeRecursive <RockCheckBox>().FirstOrDefault(a => a.HasCssClass("js-include-child-groups"));
            RockCheckBox     cbChildGroupsPlusDescendants = filterField.ControlsOfTypeRecursive <RockCheckBox>().FirstOrDefault(a => a.HasCssClass("js-include-child-groups-descendants"));
            RockCheckBox     cbIncludeInactiveGroups      = filterField.ControlsOfTypeRecursive <RockCheckBox>().FirstOrDefault(a => a.HasCssClass("js-include-inactive-groups"));
            RockCheckBox     cbIncludeSelectedGroup       = filterField.ControlsOfTypeRecursive <RockCheckBox>().FirstOrDefault(a => a.HasCssClass("js-include-selected-groups"));
            RockCheckBoxList cblRoles = filterField.ControlsOfTypeRecursive <RockCheckBoxList>().FirstOrDefault(a => a.HasCssClass("js-roles"));

            var rockContext = new RockContext();

            var groupIdList  = groupPicker.SelectedValues.AsIntegerList();
            var groupService = new GroupService(rockContext);

            var selectedGroups = groupService.GetByIds(groupIdList).Select(s => new { s.Id, s.GroupTypeId }).ToList();

            if (selectedGroups.Any())
            {
                var        groupTypeRoleService = new GroupTypeRoleService(rockContext);
                var        qryGroupTypeRoles    = groupTypeRoleService.Queryable();
                List <int> selectedGroupTypeIds = selectedGroups.Select(a => a.GroupTypeId).Distinct().ToList();

                if (cbChildGroups.Checked)
                {
                    List <int> childGroupTypeIds = new List <int>();
                    foreach (var groupId in selectedGroups.Select(a => a.Id).ToList())
                    {
                        if (cbChildGroupsPlusDescendants.Checked)
                        {
                            // get all children and descendants of the selected group(s)
                            var descendantGroupTypes = groupService.GetAllDescendentsGroupTypes(groupId, cbIncludeInactiveGroups.Checked);

                            childGroupTypeIds.AddRange(descendantGroupTypes.Select(a => a.Id).ToList());
                        }
                        else
                        {
                            // get only immediate children of the selected group(s)
                            var childGroups = groupService.Queryable().Where(a => a.ParentGroupId == groupId);
                            if (!cbIncludeInactiveGroups.Checked)
                            {
                                childGroups = childGroups.Where(a => a.IsActive == true);
                            }

                            childGroupTypeIds.AddRange(childGroups.Select(a => a.GroupTypeId).Distinct().ToList());
                        }
                    }

                    childGroupTypeIds = childGroupTypeIds.Distinct().ToList();

                    if (cbIncludeSelectedGroup.Checked)
                    {
                        qryGroupTypeRoles = qryGroupTypeRoles.Where(a => a.GroupTypeId.HasValue && (selectedGroupTypeIds.Contains(a.GroupTypeId.Value) || childGroupTypeIds.Contains(a.GroupTypeId.Value)));
                    }
                    else
                    {
                        qryGroupTypeRoles = qryGroupTypeRoles.Where(a => a.GroupTypeId.HasValue && childGroupTypeIds.Contains(a.GroupTypeId.Value));
                    }
                }
                else
                {
                    qryGroupTypeRoles = qryGroupTypeRoles.Where(a => a.GroupTypeId.HasValue && selectedGroupTypeIds.Contains(a.GroupTypeId.Value));
                }

                var list = qryGroupTypeRoles.OrderBy(a => a.GroupType.Order).ThenBy(a => a.GroupType.Name).ThenBy(a => a.Order).ThenBy(a => a.Name).Select(a => new
                {
                    a.Name,
                    GroupTypeName = a.GroupType.Name,
                    a.Guid
                }).ToList();
                cblRoles.Items.Clear();
                foreach (var item in list)
                {
                    cblRoles.Items.Add(new ListItem(string.Format("{0} ({1})", item.Name, item.GroupTypeName), item.Guid.ToString()));
                }

                cblRoles.Visible = list.Count > 0;
            }
            else
            {
                cblRoles.Visible = false;
            }
        }
Exemplo n.º 9
0
        /// <summary>Process all trips (events) from Service Reef.</summary>
        /// <param name="message">The message that is returned depending on the result.</param>
        /// <param name="state">The state of the process.</param>
        /// <returns><see cref="WorkerResultStatus"/></returns>
        public void Execute(IJobExecutionContext context)
        {
            RockContext           dbContext             = new RockContext();
            PersonService         personService         = new PersonService(dbContext);
            PersonAliasService    personAliasService    = new PersonAliasService(dbContext);
            GroupService          groupService          = new GroupService(dbContext);
            GroupMemberService    groupMemberService    = new GroupMemberService(dbContext);
            AttributeService      attributeService      = new AttributeService(dbContext);
            AttributeValueService attributeValueService = new AttributeValueService(dbContext);
            GroupTypeRoleService  groupTypeRoleService  = new GroupTypeRoleService(dbContext);
            DefinedValueService   definedValueService   = new DefinedValueService(dbContext);
            DefinedTypeService    definedTypeService    = new DefinedTypeService(dbContext);
            LocationService       locationService       = new LocationService(dbContext);

            // Get the datamap for loading attributes
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            String warnings  = string.Empty;
            var    total     = 1;
            var    processed = 0;

            try
            {
                DateRange dateRange = Rock.Web.UI.Controls.SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(dataMap.GetString("DateRange") ?? "-1||");

                String            SRApiKey         = Encryption.DecryptString(dataMap.GetString("ServiceReefAPIKey"));
                String            SRApiSecret      = Encryption.DecryptString(dataMap.GetString("ServiceReefAPISecret"));
                String            SRApiUrl         = dataMap.GetString("ServiceReefAPIURL");
                DefinedValueCache connectionStatus = DefinedValueCache.Get(dataMap.GetString("DefaultConnectionStatus").AsGuid(), dbContext);
                if (SRApiUrl.Last() != '/')
                {
                    SRApiUrl += "/";
                }

                Group                group           = groupService.Get(dataMap.GetString("ParentGroup").AsGuid());
                GroupTypeCache       parentGroupType = GroupTypeCache.Get(dataMap.Get("YearGroupType").ToString().AsGuid(), dbContext);
                GroupTypeCache       groupType       = GroupTypeCache.Get(dataMap.Get("TripGroupType").ToString().AsGuid(), dbContext);
                Rock.Model.Attribute attribute       = attributeService.Get(dataMap.GetString("ServiceReefUserId").AsGuid());
                Rock.Model.Attribute attribute2      = attributeService.Get(dataMap.GetString("ServiceReefProfileURL").AsGuid());
                var entitytype = EntityTypeCache.Get(typeof(Group)).Id;

                // Setup the ServiceReef API Client
                var client = new RestClient(SRApiUrl);
                client.Authenticator = new HMACAuthenticator(SRApiKey, SRApiSecret);

                // Get all events from ServiceReef
                var request = new RestRequest("v1/events", Method.GET);
                request.AddParameter("pageSize", 100);
                if (dateRange.Start.HasValue)
                {
                    request.AddParameter("startDate", dateRange.Start.Value.ToString("o"));
                }
                if (dateRange.End.HasValue)
                {
                    request.AddParameter("endDate", dateRange.End.Value.ToString("o"));
                }
                request.AddParameter("page", 1);

                while (total > processed)
                {
                    var response = client.Execute <Contracts.Events>(request);

                    if (response.StatusCode != System.Net.HttpStatusCode.OK)
                    {
                        throw new Exception("ServiceReef API Response: " + response.StatusDescription + " Content Length: " + response.ContentLength);
                    }

                    if (response.Data != null && response.Data.PageInfo != null)
                    {
                        total = response.Data.PageInfo.TotalRecords;

                        foreach (Contracts.Events.Result result in response.Data.Results)
                        {
                            // Process the event
                            Group trip        = null;
                            Group trip2       = null;
                            var   startdate   = result.StartDate;
                            var   parentgroup = string.Format("{0} Mission Trips", startdate.Year);

                            if (result.EventId > 0)
                            {
                                trip  = groupService.Queryable().Where(t => t.Name == parentgroup).FirstOrDefault();
                                trip2 = groupService.Queryable().Where(t => t.ForeignId == result.EventId && t.GroupTypeId == groupType.Id).FirstOrDefault();
                            }
                            Guid guid  = Guid.NewGuid();
                            Guid guid2 = Guid.NewGuid();

                            if (trip == null)
                            {
                                // Create trip parent Group
                                Group tripPG = new Group();
                                tripPG.Name           = parentgroup;
                                tripPG.GroupTypeId    = parentGroupType.Id;
                                tripPG.ParentGroupId  = group.Id;
                                tripPG.IsSystem       = false;
                                tripPG.IsActive       = true;
                                tripPG.IsSecurityRole = false;
                                tripPG.Order          = 0;
                                tripPG.Guid           = guid;
                                groupService.Add(tripPG);

                                // Now save the trip parent group
                                dbContext.SaveChanges();
                                trip = tripPG;
                            }

                            if (trip2 == null)
                            {
                                // Create the trip
                                Group tripG = new Group();
                                tripG.Name           = result.Name;
                                tripG.GroupTypeId    = groupType.Id;
                                tripG.ParentGroupId  = trip.Id;
                                tripG.IsSystem       = false;
                                tripG.IsActive       = true;
                                tripG.IsSecurityRole = false;
                                tripG.Order          = 0;
                                tripG.ForeignId      = result.EventId;
                                groupService.Add(tripG);

                                // Now save the trip
                                dbContext.SaveChanges();
                                trip2 = tripG;
                            }
                            trip2.LoadAttributes();

                            if (startdate != DateTime.MinValue)
                            {
                                trip2.SetAttributeValue("Year", startdate.Year.ToString());
                                trip2.SetAttributeValue("Month", startdate.ToString("MMMM"));
                                trip2.SaveAttributeValues();
                            }
                            dbContext.SaveChanges();
                            var eventRequest = new RestRequest("v1/events/{eventId}", Method.GET);
                            eventRequest.AddUrlSegment("eventId", result.EventId.ToString());
                            var eventResult = client.Execute <Contracts.Event>(eventRequest);

                            if (eventResult.Data != null && eventResult.Data.Categories.Count > 0)
                            {
                                foreach (Contracts.Event.CategorySimple categorysimple in eventResult.Data.Categories)
                                {
                                    var option = categorysimple.Options.FirstOrDefault();

                                    if (option != null)
                                    {
                                        trip2.SetAttributeValue(categorysimple.Name.RemoveAllNonAlphaNumericCharacters(), option.Name);
                                        trip2.SaveAttributeValues();
                                    }
                                }
                                dbContext.SaveChanges();
                            }
                            var    amount   = 1;
                            var    handled  = 0;
                            String rest     = String.Format("v1/events/{0}/participants", result.EventId);
                            var    request2 = new RestRequest(rest, Method.GET);
                            request2.AddParameter("pageSize", 100);
                            request2.AddParameter("page", 1);

                            // We haven't processed this before so get busy!
                            while (amount > handled)
                            {
                                var response2 = client.Execute <Contracts.Participants>(request2);

                                if (response2.StatusCode != System.Net.HttpStatusCode.OK)
                                {
                                    throw new Exception("ServiceReef API Response: " + response2.StatusDescription + " Content Length: " + response2.ContentLength);
                                }

                                if (response2.Data != null && response2.Data.PageInfo != null)
                                {
                                    amount = response2.Data.PageInfo.TotalRecords;

                                    foreach (Contracts.Participants.Result result2 in response2.Data.Results)
                                    {
                                        Person person = null;
                                        if (result2.RegistrationStatus != "Draft")
                                        {
                                            if (result2.UserId > 0)
                                            {
                                                var memberRequest = new RestRequest("v1/members/{userId}", Method.GET);
                                                memberRequest.AddUrlSegment("userId", result2.UserId.ToString());
                                                var memberResult = client.Execute <Contracts.Member>(memberRequest);

                                                if (memberResult.Data != null && memberResult.Data.ArenaId > 0)
                                                {
                                                    Person personMatch = personAliasService.Queryable().Where(pa => pa.AliasPersonId == memberResult.Data.ArenaId).Select(pa => pa.Person).FirstOrDefault();

                                                    if (personMatch != null)
                                                    {
                                                        person = personMatch;
                                                    }
                                                }
                                            }

                                            // 2. If we didn't get a person match via their Alias Id
                                            //    then use their ServiceReef UserId attribute
                                            if (person == null && attribute != null)
                                            {
                                                var personIds = attributeValueService.Queryable().Where(av => av.AttributeId == attribute.Id && av.Value == result2.UserId.ToString()).Select(av => av.EntityId);
                                                if (personIds.Count() == 1)
                                                {
                                                    person = personService.Get(personIds.FirstOrDefault().Value);
                                                }
                                            }

                                            // 3. If we STILL don't have a person match then
                                            //    just use the standard person match/create logic
                                            if (person == null)
                                            {
                                                String street1    = null;
                                                String postalCode = null;

                                                if (result2.Address != null)
                                                {
                                                    street1    = result2.Address.Address1;
                                                    postalCode = result2.Address.Zip;
                                                }
                                                var           email        = result2.Email.Trim();
                                                List <Person> matches      = null;
                                                Location      homelocation = new Location();

                                                if (!email.IsValidEmail())
                                                {
                                                    email   = null;
                                                    matches = personService.Queryable()
                                                              .Where(p => p.FirstName == result2.FirstName.Trim() && p.LastName == result2.LastName.Trim()).ToList();

                                                    if (matches.Count() > 0 && !string.IsNullOrEmpty(street1) && !string.IsNullOrEmpty(postalCode))
                                                    {
                                                        homelocation.Street1    = street1;
                                                        homelocation.PostalCode = postalCode;
                                                        locationService.Verify(homelocation, true);
                                                    }

                                                    foreach (Person match in matches)
                                                    {
                                                        Boolean addressMatches = false;
                                                        // Check the address
                                                        if (!string.IsNullOrEmpty(street1) && !string.IsNullOrEmpty(postalCode))
                                                        {
                                                            if (match.GetHomeLocation(dbContext) != null)
                                                            {
                                                                if (match.GetHomeLocation(dbContext).Street1 == street1 && match.GetHomeLocation(dbContext).PostalCode.Split('-')[0] == postalCode)
                                                                {
                                                                    addressMatches = true;
                                                                }
                                                            }
                                                        }

                                                        if (!addressMatches)
                                                        {
                                                            matches.Remove(person);
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    matches = personService.GetByMatch(result2.FirstName.Trim(), result2.LastName.Trim(), null, email, null, street1, postalCode).ToList();
                                                }

                                                if (matches.Count > 1)
                                                {
                                                    // Find the oldest member record in the list
                                                    person = matches.Where(p => p.ConnectionStatusValue.Value == "Member").OrderBy(p => p.Id).FirstOrDefault();

                                                    if (person == null)
                                                    {
                                                        // Find the oldest attendee record in the list
                                                        person = matches.Where(p => p.ConnectionStatusValue.Value == "Attendee").OrderBy(p => p.Id).FirstOrDefault();
                                                        if (person == null)
                                                        {
                                                            person = matches.OrderBy(p => p.Id).First();
                                                        }
                                                    }
                                                }
                                                else if (matches.Count == 1)
                                                {
                                                    person = matches.First();
                                                }
                                                else
                                                {
                                                    // Create the person
                                                    Guid guid3 = Guid.NewGuid();
                                                    person           = new Person();
                                                    person.FirstName = result2.FirstName.Trim();
                                                    person.LastName  = result2.LastName.Trim();
                                                    if (email.IsValidEmail())
                                                    {
                                                        person.Email = email;
                                                    }
                                                    person.RecordTypeValueId       = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                                                    person.ConnectionStatusValueId = connectionStatus.Id;
                                                    person.RecordStatusValueId     = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid()).Id;
                                                    person.IsSystem      = false;
                                                    person.IsDeceased    = false;
                                                    person.IsEmailActive = true;
                                                    person.Guid          = guid3;
                                                    var masteranswer = result2.MasterApplicationAnswers.Find(a => a.Question == "Gender");
                                                    var answer       = result2.ApplicationAnswers.Find(a => a.Question == "Gender");
                                                    var flag         = true;

                                                    if (masteranswer != null)
                                                    {
                                                        var gender = masteranswer.Answer;

                                                        if (!String.IsNullOrEmpty(gender))
                                                        {
                                                            gender.Trim();

                                                            if (gender == "Male" || gender == "male")
                                                            {
                                                                person.Gender = Gender.Male;
                                                            }
                                                            else
                                                            {
                                                                person.Gender = Gender.Female;
                                                            }
                                                            flag = false;
                                                        }
                                                    }

                                                    if (answer != null && flag == true)
                                                    {
                                                        var gender2 = answer.Answer;

                                                        if (!String.IsNullOrEmpty(gender2))
                                                        {
                                                            gender2.Trim();

                                                            if (gender2 == "Male" || gender2 == "male")
                                                            {
                                                                person.Gender = Gender.Male;
                                                            }
                                                            else
                                                            {
                                                                person.Gender = Gender.Female;
                                                            }
                                                        }
                                                        else
                                                        {
                                                            person.Gender = Gender.Unknown;
                                                        }
                                                    }
                                                    else if (flag == true)
                                                    {
                                                        person.Gender = Gender.Unknown;
                                                    }
                                                    Group         family   = PersonService.SaveNewPerson(person, dbContext);
                                                    GroupLocation location = new GroupLocation();
                                                    location.GroupLocationTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME).Id;
                                                    location.Location = new Location()
                                                    {
                                                        Street1    = result2.Address.Address1,
                                                        Street2    = result2.Address.Address2,
                                                        City       = result2.Address.City,
                                                        State      = result2.Address.State,
                                                        PostalCode = result2.Address.Zip,
                                                        Country    = result2.Address.Country
                                                    };
                                                    location.IsMappedLocation = true;
                                                    family.CampusId           = CampusCache.All().FirstOrDefault().Id;
                                                    family.GroupLocations.Add(location);

                                                    dbContext.SaveChanges();
                                                }
                                            }
                                            Guid guid4      = Guid.NewGuid();
                                            Guid guid5      = Guid.NewGuid();
                                            var  userid     = result2.UserId;
                                            var  profileurl = result2.ProfileUrl;
                                            person.LoadAttributes();

                                            if (userid > 0)
                                            {
                                                person.SetAttributeValue(attribute.Key, result2.UserId.ToString());
                                            }

                                            if (!String.IsNullOrEmpty(profileurl))
                                            {
                                                person.SetAttributeValue(attribute2.Key, result2.ProfileUrl);
                                            }
                                            person.SaveAttributeValues();
                                            dbContext.SaveChanges();
                                            var member = groupService.GroupHasMember(trip2.Guid, person.Id);

                                            if (member == false)
                                            {
                                                Guid        guid6       = Guid.NewGuid();
                                                GroupMember participant = new GroupMember();
                                                participant.PersonId = person.Id;
                                                participant.GroupId  = trip2.Id;
                                                participant.IsSystem = false;
                                                participant.Guid     = guid6;
                                                var grouprole = groupTypeRoleService.Queryable().Where(r => r.GroupTypeId == trip2.GroupTypeId).FirstOrDefault().Id;
                                                participant.GroupRoleId = groupType.DefaultGroupRoleId.GetValueOrDefault(grouprole);

                                                if (result2.RegistrationStatus == "Approved")
                                                {
                                                    participant.GroupMemberStatus = GroupMemberStatus.Active;
                                                }
                                                else if (result2.RegistrationStatus == "Cancelled")
                                                {
                                                    participant.GroupMemberStatus = GroupMemberStatus.Inactive;
                                                }
                                                else
                                                {
                                                    participant.GroupMemberStatus = GroupMemberStatus.Pending;
                                                }

                                                groupMemberService.Add(participant);
                                                dbContext.SaveChanges();
                                            }
                                        }
                                        handled++;
                                    }
                                }
                                else
                                {
                                    amount = 0;
                                }
                                var pageParam2 = request2.Parameters.Where(p => p.Name == "page").FirstOrDefault();
                                pageParam2.Value = (int)pageParam2.Value + 1;
                            }
                            processed++;
                        }
                    }
                    else
                    {
                        total = 0;
                    }
                    // Update the page number for the next request
                    var pageParam = request.Parameters.Where(p => p.Name == "page").FirstOrDefault();
                    pageParam.Value = (int)pageParam.Value + 1;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("ServiceReef Job Failed", ex);
            }
            finally
            {
                dbContext.SaveChanges();
            }

            if (warnings.Length > 0)
            {
                throw new Exception(warnings);
            }
            context.Result = "Successfully imported " + processed + " trips.";
        }
Exemplo n.º 10
0
        /// <summary>
        /// Loads the group membership data.
        /// </summary>
        /// <param name="csvData">The CSV data.</param>
        private int LoadGroupMember( CSVInstance csvData )
        {
            var lookupContext = new RockContext();
            var groupTypeRoleService = new GroupTypeRoleService( lookupContext );
            var groupMemberService = new GroupMemberService( lookupContext );

            Dictionary<string, int> importedMembers = groupMemberService.Queryable( true ).AsNoTracking()
                .Where( m => m.ForeignKey != null )
                .ToDictionary( m => m.ForeignKey, m => m.Id );

            var groupTypeRoles = new Dictionary<int?, Dictionary<string, int>>();
            foreach ( var role in groupTypeRoleService.Queryable().AsNoTracking().GroupBy( r => r.GroupTypeId ) )
            {
                groupTypeRoles.Add( role.Key, role.ToDictionary( r => r.Name, r => r.Id, StringComparer.OrdinalIgnoreCase ) );
            }

            var currentGroup = new Group();
            var newMemberList = new List<GroupMember>();

            int completed = 0;
            int imported = 0;

            ReportProgress( 0, string.Format( "Starting group member import ({0:N0} already exist).", importedMembers.Count ) );

            string[] row;
            // Uses a look-ahead enumerator: this call will move to the next record immediately
            while ( ( row = csvData.Database.FirstOrDefault() ) != null )
            {
                string rowGroupMemberKey = row[GroupMemberId];
                string rowGroupKey = row[GroupMemberGroupId];
                string rowPersonKey = row[GroupMemberPersonId];
                string rowCreatedDate = row[GroupMemberCreatedDate];
                string rowMemberRole = row[GroupMemberRole];
                string rowMemberActive = row[GroupMemberActive];
                int? rowGroupMemberId = rowGroupMemberKey.AsType<int?>();

                //
                // Find this person in the database.
                //
                var personKeys = GetPersonKeys( rowPersonKey );
                if ( personKeys == null || personKeys.PersonId == 0 )
                {
                    LogException( "InvalidPersonKey", string.Format( "Person key {0} not found", rowPersonKey ) );
                    ReportProgress( 0, string.Format( "Person key {0} not found", rowPersonKey ) );
                }

                //
                // Check that this member isn't already in our data
                //
                bool memberExists = false;
                if ( importedMembers.Count > 0 )
                {
                    memberExists = importedMembers.ContainsKey( rowGroupMemberKey );
                }

                if ( !memberExists && ( personKeys != null && personKeys.PersonId != 0 ) )
                {
                    if ( currentGroup == null || rowGroupKey != currentGroup.ForeignKey )
                    {
                        currentGroup = ImportedGroups.FirstOrDefault( g => g.ForeignKey.Equals( rowGroupKey ) );
                    }
                    if ( currentGroup != null )
                    {
                        GroupMember groupMember = new GroupMember();
                        groupMember.PersonId = personKeys.PersonId;
                        groupMember.GroupId = currentGroup.Id;
                        groupMember.CreatedDateTime = ParseDateOrDefault( rowCreatedDate, ImportDateTime );
                        groupMember.ModifiedDateTime = ImportDateTime;
                        groupMember.CreatedByPersonAliasId = ImportPersonAliasId;
                        groupMember.ForeignKey = rowGroupMemberKey;
                        groupMember.ForeignId = rowGroupMemberId;
                        groupMember.GroupMemberStatus = GetGroupMemberStatus( rowMemberActive );

                        //
                        // Find and set the group role id.
                        //
                        if ( !string.IsNullOrEmpty( rowMemberRole ) )
                        {
                            var typeExists = groupTypeRoles.ContainsKey( currentGroup.GroupTypeId );
                            if ( typeExists && groupTypeRoles[currentGroup.GroupTypeId].ContainsKey( rowMemberRole ) )
                            {
                                groupMember.GroupRoleId = groupTypeRoles[currentGroup.GroupTypeId][rowMemberRole];
                            }
                            else
                            {
                                var newRoleId = AddGroupRole( lookupContext, currentGroup.GroupType.Guid.ToString(), rowMemberRole );
                                // check if adding an additional role for this grouptype or creating the first one
                                if ( typeExists )
                                {
                                    groupTypeRoles[currentGroup.GroupType.Id].Add( rowMemberRole, newRoleId );
                                }
                                else
                                {
                                    groupTypeRoles.Add( currentGroup.GroupType.Id, new Dictionary<string, int> { { rowMemberRole, newRoleId } } );
                                }

                                groupMember.GroupRoleId = newRoleId;
                            }
                        }
                        else
                        {
                            if ( currentGroup.GroupType.DefaultGroupRoleId != null )
                            {
                                groupMember.GroupRoleId = ( int ) currentGroup.GroupType.DefaultGroupRoleId;
                            }
                            else
                            {
                                groupMember.GroupRoleId = currentGroup.GroupType.Roles.First().Id;
                            }
                        }

                        //
                        // Add member to the group.
                        //
                        currentGroup.Members.Add( groupMember );
                        newMemberList.Add( groupMember );
                        imported++;
                    }
                    else
                    {
                        LogException( "InvalidGroupKey", string.Format( "Group key {0} not found", rowGroupKey ) );
                    }
                }

                //
                // Notify user of our status.
                //
                completed++;
                if ( completed % ( ReportingNumber * 10 ) < 1 )
                {
                    ReportProgress( 0, string.Format( "{0:N0} rows processed, {1:N0} members imported.", completed, imported ) );
                }

                if ( completed % ReportingNumber < 1 )
                {
                    SaveGroupMembers( newMemberList );
                    lookupContext.SaveChanges();
                    ReportPartialProgress();

                    // Clear out variables
                    currentGroup = new Group();
                    newMemberList.Clear();
                }
            }

            //
            // Save any final changes to new groups
            //
            if ( newMemberList.Any() )
            {
                SaveGroupMembers( newMemberList );
            }

            //
            // Save any changes to existing groups
            //
            lookupContext.SaveChanges();
            lookupContext.Dispose();

            ReportProgress( 0, string.Format( "Finished group member import: {0:N0} members added.", imported ) );

            return completed;
        }
Exemplo n.º 11
0
        /// <summary>
        /// Loads the group membership data.
        /// </summary>
        /// <param name="csvData">The CSV data.</param>
        private int LoadRelationshipGroupMember( CSVInstance csvData )
        {
            AddMissingRelationshipGroups();

            var lookupContext = new RockContext();
            var groupTypeRoleService = new GroupTypeRoleService( lookupContext );
            var groupMemberService = new GroupMemberService( lookupContext );

            var newMemberList = new List<GroupMember>();

            int completed = 0;
            int imported = 0;

            ReportProgress( 0, "Starting relationship import." );
            var knownRelationshipGroupType = CachedTypes.KnownRelationshipGroupType;

            if ( knownRelationshipGroupType != null )
            {
                var relationshipGroupTypeRoles = groupTypeRoleService
                    .Queryable().AsNoTracking()
                    .Where( r => r.GroupTypeId == knownRelationshipGroupType.Id )
                    .ToDictionary( r => r.Name, r => r.Id );

                string[] row;
                // Uses a look-ahead enumerator: this call will move to the next record immediately
                while ( ( row = csvData.Database.FirstOrDefault() ) != null )
                {
                    string rowGroupMemberKey = row[GroupMemberId];
                    string rowGroupKey = row[GroupMemberGroupId];
                    string rowPersonKey = row[GroupMemberPersonId];
                    string rowCreatedDate = row[GroupMemberCreatedDate];
                    string rowMemberRole = row[GroupMemberRole];
                    string rowMemberActive = row[GroupMemberActive];
                    int? rowGroupMemberId = rowGroupMemberKey.AsType<int?>();

                    //
                    // Find Owner
                    //
                    var ownerKeys = GetPersonKeys( rowGroupKey );
                    if ( ownerKeys == null || ownerKeys.PersonId == 0 )
                    {
                        LogException( "InvalidGroupKey", string.Format( "Owner person key {0} not found", rowGroupKey ) );
                        ReportProgress( 0, string.Format( "Owner person key {0} not found", rowGroupKey ) );
                    }

                    //
                    // Find this person in the database.
                    //
                    var personKeys = GetPersonKeys( rowPersonKey );
                    if ( personKeys == null || personKeys.PersonId == 0 )
                    {
                        LogException( "InvalidPersonKey", string.Format( "Person key {0} not found", rowPersonKey ) );
                        ReportProgress( 0, string.Format( "Person key {0} not found", rowPersonKey ) );
                    }

                    if ( ownerKeys != null && ownerKeys.PersonId != 0 )
                    {
                        var knownRelationshipGroup = new GroupMemberService( lookupContext ).Queryable( true )
                                    .AsNoTracking()
                                    .Where(
                                        m => m.PersonId == ownerKeys.PersonId
                                        && m.GroupRoleId == CachedTypes.KnownRelationshipOwnerRoleId
                                        && m.Group.GroupTypeId == knownRelationshipGroupType.Id
                                    )
                                    .Select( m => m.Group )
                                    .FirstOrDefault();

                        if ( knownRelationshipGroup != null && knownRelationshipGroup.Id > 0 )
                        {
                            if ( personKeys != null && personKeys.PersonId != 0 )
                            {
                                GroupMember groupMember = new GroupMember();
                                groupMember.PersonId = personKeys.PersonId;
                                groupMember.GroupId = knownRelationshipGroup.Id;
                                groupMember.CreatedDateTime = ParseDateOrDefault( rowCreatedDate, ImportDateTime );
                                groupMember.ModifiedDateTime = ImportDateTime;
                                groupMember.CreatedByPersonAliasId = ImportPersonAliasId;
                                groupMember.ForeignKey = rowGroupMemberKey;
                                groupMember.ForeignId = rowGroupMemberId;
                                groupMember.GroupMemberStatus = GetGroupMemberStatus( rowMemberActive );

                                //
                                // Find and set the group role id.
                                //
                                if ( !string.IsNullOrEmpty( rowMemberRole ) )
                                {
                                    if ( relationshipGroupTypeRoles.ContainsKey( rowMemberRole ) )
                                    {
                                        groupMember.GroupRoleId = relationshipGroupTypeRoles[rowMemberRole];
                                    }
                                    else
                                    {
                                        var newRoleId = AddGroupRole( lookupContext, knownRelationshipGroupType.Guid.ToString(), rowMemberRole );
                                        relationshipGroupTypeRoles.Add( rowMemberRole, newRoleId );
                                        groupMember.GroupRoleId = newRoleId;
                                    }
                                }
                                else
                                {
                                    if ( knownRelationshipGroupType.DefaultGroupRoleId != null )
                                    {
                                        groupMember.GroupRoleId = ( int ) knownRelationshipGroupType.DefaultGroupRoleId;
                                    }
                                    else
                                    {
                                        groupMember.GroupRoleId = knownRelationshipGroupType.Roles.First().Id;
                                    }
                                }

                                //
                                // Add member to the group.
                                //
                                knownRelationshipGroup.Members.Add( groupMember );
                                newMemberList.Add( groupMember );
                                imported++;
                            }
                            else
                            {
                                LogException( "InvalidPersonKey", string.Format( "Person with Foreign Id {0} not found", rowPersonKey ) );
                            }
                        }
                        else
                        {
                            LogException( "InvalidGroupKey", string.Format( "Relationship Group with Owner Person Foreign Id {0} not found", rowGroupKey ) );
                        }
                    }
                    else
                    {
                        LogException( "InvalidGroupKey", string.Format( "Relationship Group Owner with Person Foreign Id {0} not found", rowGroupKey ) );
                    }

                    //
                    // Notify user of our status.
                    //
                    completed++;
                    if ( completed % ( ReportingNumber * 10 ) < 1 )
                    {
                        ReportProgress( 0, string.Format( "{0:N0} rows processed, {1:N0} relationships imported.", completed, imported ) );
                    }

                    if ( completed % ReportingNumber < 1 )
                    {
                        SaveGroupMembers( newMemberList );
                        lookupContext.SaveChanges();
                        ReportPartialProgress();

                        // Clear out variables
                        newMemberList.Clear();
                    }
                }
            }
            else
            {
                ReportProgress( 0, "Known Relationship Group Type Missing!" );
            }
            //
            // Save any final changes to new groups
            //
            if ( newMemberList.Any() )
            {
                SaveGroupMembers( newMemberList );
            }

            //
            // Save any changes to existing groups
            //
            lookupContext.SaveChanges();
            lookupContext.Dispose();

            ReportProgress( 0, string.Format( "Finished relationship import: {0:N0} relationships added.", imported ) );

            return completed;
        }
Exemplo n.º 12
0
        /// <summary>Process all leagues (programs) from LeagueApps.</summary>
        /// <param name="message">The message that is returned depending on the result.</param>
        /// <param name="state">The state of the process.</param>
        /// <returns><see cref="WorkerResultStatus"/></returns>
        public void Execute(IJobExecutionContext context)
        {
            RockContext           dbContext             = new RockContext();
            GroupService          groupService          = new GroupService(dbContext);
            AttributeService      attributeService      = new AttributeService(dbContext);
            AttributeValueService attributeValueService = new AttributeValueService(dbContext);
            GroupTypeRoleService  groupTypeRoleService  = new GroupTypeRoleService(dbContext);
            DefinedValueService   definedValueService   = new DefinedValueService(dbContext);
            DefinedTypeService    definedTypeService    = new DefinedTypeService(dbContext);
            BinaryFileService     binaryFileService     = new BinaryFileService(dbContext);

            // Get the datamap for loading attributes
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            String warnings  = string.Empty;
            var    processed = 0;

            try
            {
                String            siteid           = Encryption.DecryptString(dataMap.GetString("LeagueAppsSiteId"));
                String            clientid         = Encryption.DecryptString(dataMap.GetString("LeagueAppsClientId"));
                DefinedValueCache connectionStatus = DefinedValueCache.Get(dataMap.GetString("DefaultConnectionStatus").AsGuid(), dbContext);
                var p12File = binaryFileService.Get(dataMap.GetString("LeagueAppsServiceAccountFile").AsGuid());

                Group                group = groupService.Get(dataMap.GetString("ParentGroup").AsGuid());
                GroupTypeCache       grandparentGroupType = GroupTypeCache.Get(dataMap.Get("YearGroupType").ToString().AsGuid(), dbContext);
                GroupTypeCache       parentGroupType      = GroupTypeCache.Get(dataMap.Get("CategoryGroupType").ToString().AsGuid(), dbContext);
                GroupTypeCache       groupType            = GroupTypeCache.Get(dataMap.Get("LeagueGroupType").ToString().AsGuid(), dbContext);
                DefinedTypeCache     sports               = DefinedTypeCache.Get(dataMap.Get("SportsType").ToString().AsGuid(), dbContext);
                DefinedTypeCache     seasons              = DefinedTypeCache.Get(dataMap.Get("SeasonsType").ToString().AsGuid(), dbContext);
                DefinedTypeCache     genders              = DefinedTypeCache.Get(dataMap.Get("GendersType").ToString().AsGuid(), dbContext);
                Rock.Model.Attribute personattribute      = attributeService.Get(dataMap.GetString("LeagueAppsUserId").AsGuid());
                Rock.Model.Attribute groupmemberattribute = attributeService.Get(dataMap.GetString("LeagueGroupTeam").AsGuid());
                var entitytype = EntityTypeCache.Get(typeof(Group)).Id;

                var client = new RestClient("https://public.leagueapps.io");

                // Get all programs from LeagueApps
                var request = new RestRequest("/v1/sites/{siteid}/programs/current", Method.GET);
                request.AddUrlSegment("siteid", siteid);
                request.AddHeader("la-api-key", clientid);
                var response = client.Get(request);

                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    throw new Exception("LeagueApps API Response: " + response.StatusDescription + " Content Length: " + response.ContentLength);
                }

                if (response.Content != null)
                {
                    var export   = response.Content.ToString();
                    var programs = JsonConvert.DeserializeObject <List <Contracts.Programs> >(export);
                    var groups   = groupService.Queryable().Where(g => g.GroupTypeId == groupType.Id).ToList();

                    foreach (Contracts.Programs program in programs)
                    {
                        // Process the program
                        Group league    = null;
                        Group league2   = null;
                        Group league3   = null;
                        var   startdate = program.startTime;
                        var   mode      = program.mode.ToLower();
                        mode = mode.First().ToString().ToUpper() + mode.Substring(1);
                        var grandparentgroup = string.Format("{0}", startdate.Year);
                        if (program.programId > 0)
                        {
                            league = groupService.Queryable().Where(l => l.Name == grandparentgroup && l.ParentGroupId == group.Id).FirstOrDefault();
                            if (league != null)
                            {
                                league2 = groupService.Queryable().Where(l => l.Name == mode && l.ParentGroupId == league.Id).FirstOrDefault();
                                if (league2 != null)
                                {
                                    league3 = groupService.Queryable().Where(l => l.ForeignId == program.programId && l.GroupTypeId == groupType.Id && l.ParentGroupId == league2.Id).FirstOrDefault();
                                }
                            }
                        }
                        Guid guid  = Guid.NewGuid();
                        Guid guid2 = Guid.NewGuid();
                        Guid guid3 = Guid.NewGuid();

                        if (league == null)
                        {
                            // Create league grandparent Group
                            Group leagueGPG = new Group();
                            leagueGPG.Name           = grandparentgroup;
                            leagueGPG.GroupTypeId    = grandparentGroupType.Id;
                            leagueGPG.ParentGroupId  = group.Id;
                            leagueGPG.IsSystem       = false;
                            leagueGPG.IsActive       = true;
                            leagueGPG.IsSecurityRole = false;
                            leagueGPG.Order          = 0;
                            leagueGPG.Guid           = guid;
                            groupService.Add(leagueGPG);

                            // Now save the league grandparent group
                            dbContext.SaveChanges();
                            league = leagueGPG;
                        }

                        if (league2 == null)
                        {
                            // Create league parent Group
                            Group leaguePG = new Group();
                            leaguePG.Name           = mode;
                            leaguePG.GroupTypeId    = parentGroupType.Id;
                            leaguePG.ParentGroupId  = league.Id;
                            leaguePG.IsSystem       = false;
                            leaguePG.IsActive       = true;
                            leaguePG.IsSecurityRole = false;
                            leaguePG.Order          = 0;
                            leaguePG.Guid           = guid2;
                            groupService.Add(leaguePG);

                            // Now save the league parent group
                            dbContext.SaveChanges();
                            league2 = leaguePG;
                        }

                        if (league3 == null)
                        {
                            // Create the league
                            Group leagueG = new Group();
                            leagueG.Name           = program.name;
                            leagueG.GroupTypeId    = groupType.Id;
                            leagueG.ParentGroupId  = league2.Id;
                            leagueG.IsSystem       = false;
                            leagueG.IsActive       = true;
                            leagueG.IsSecurityRole = false;
                            leagueG.Order          = 0;
                            leagueG.Description    = HTMLConvertor.Convert(program.description);
                            leagueG.ForeignId      = program.programId;
                            groupService.Add(leagueG);

                            // Now save the league
                            dbContext.SaveChanges();
                            league3 = leagueG;
                        }
                        else
                        {
                            groups.Remove(league3);
                        }
                        league3.LoadAttributes();
                        var sport       = definedValueService.Queryable().Where(d => d.Value == program.sport && d.DefinedTypeId == sports.Id).FirstOrDefault();
                        var season      = definedValueService.Queryable().Where(d => d.Value == program.season && d.DefinedTypeId == seasons.Id).FirstOrDefault();
                        var groupgender = definedValueService.Queryable().Where(d => d.Value == program.gender && d.DefinedTypeId == genders.Id).FirstOrDefault();

                        if (!sport.IsNull())
                        {
                            league3.SetAttributeValue("Sport", sport.Guid);
                        }

                        if (!season.IsNull())
                        {
                            league3.SetAttributeValue("Season", season.Guid);
                        }
                        league3.SetAttributeValue("ExperienceLevel", program.experienceLevel);

                        if (!groupgender.IsNull())
                        {
                            league3.SetAttributeValue("Gender", groupgender.Guid);
                        }

                        if (startdate != DateTime.MinValue)
                        {
                            league3.SetAttributeValue("StartTime", startdate);
                        }

                        if (program.publicRegistrationTime != DateTime.MinValue)
                        {
                            league3.SetAttributeValue("PublicRegistrationTime", program.publicRegistrationTime);
                        }

                        if (program.ageLimitEffectiveDate != DateTime.MinValue)
                        {
                            league3.SetAttributeValue("AgeLimitDate", program.ageLimitEffectiveDate.Date.ToString("d"));
                        }
                        league3.SetAttributeValue("ProgramURL", program.programUrlHtml);
                        league3.SetAttributeValue("RegisterURL", program.registerUrlHtml);
                        league3.SetAttributeValue("ScheduleURL", program.scheduleUrlHtml);
                        league3.SetAttributeValue("StandingsURL", program.standingsUrlHtml);
                        league3.SetAttributeValue("ProgramLogo", program.programLogo150);
                        league3.SaveAttributeValues();
                        dbContext.SaveChanges();
                        APIClient.RunAsync(p12File, clientid, true, "/v2/sites/" + siteid + "/export/registrations-2?last-updated=0&last-id=0&program-id=" + program.programId).GetAwaiter().GetResult();
                        var applicants = APIClient.names;

                        context.UpdateLastStatusMessage("Processing league " + (processed + 1) + " of " + programs.Count + ": " + program.startTime.Year + " > " + program.mode + " > " + program.name + " (" + applicants.Count + " members).");

                        foreach (Contracts.Registrations applicant in applicants)
                        {
                            // Use a fresh RockContext on every person/groupmember to keep things moving quickly
                            using (var rockContext = new RockContext())
                            {
                                PersonService      personService      = new PersonService(rockContext);
                                GroupMemberService groupMemberService = new GroupMemberService(rockContext);
                                LocationService    locationService    = new LocationService(rockContext);

                                Person person = null;

                                // 1. Try to load the person using the LeagueApps UserId
                                var attributevalue = applicant.userId.ToString();
                                var personIds      = attributeValueService.Queryable().Where(av => av.AttributeId == personattribute.Id &&
                                                                                             (av.Value == attributevalue ||
                                                                                              av.Value.Contains("|" + attributevalue + "|") ||
                                                                                              av.Value.StartsWith(attributevalue + "|"))).Select(av => av.EntityId);
                                if (personIds.Count() == 1)
                                {
                                    person = personService.Get(personIds.FirstOrDefault().Value);
                                }

                                // 2. If we don't have a person match then
                                //    just use the standard person match/create logic
                                if (person == null)
                                {
                                    APIClient.RunAsync(p12File, clientid, false, "/v2/sites/" + siteid + "/members/" + applicant.userId).GetAwaiter().GetResult();
                                    var member     = APIClient.user;
                                    var street1    = member.address1;
                                    var postalCode = member.zipCode;

                                    var email = string.IsNullOrEmpty(member.email) ? String.Empty : member.email.Trim();

                                    if (email != String.Empty)
                                    {
                                        if (!email.IsValidEmail())
                                        {
                                            email = String.Empty;
                                        }
                                    }

                                    List <Person> matches = personService.GetByMatch(member.firstName.Trim(), member.lastName.Trim(), member.birthDate, email, null, street1, postalCode).ToList();

                                    Location location = new Location()
                                    {
                                        Street1    = member.address1,
                                        Street2    = member.address2,
                                        City       = member.city,
                                        State      = member.state,
                                        PostalCode = member.zipCode,
                                        Country    = member.country ?? "US"
                                    };

                                    if (matches.Count > 1)
                                    {
                                        // Find the oldest member record in the list
                                        person = matches.Where(p => p.ConnectionStatusValue.Value == "Member").OrderBy(p => p.Id).FirstOrDefault();

                                        if (person == null)
                                        {
                                            // Find the oldest attendee record in the list
                                            person = matches.Where(p => p.ConnectionStatusValue.Value == "Attendee").OrderBy(p => p.Id).FirstOrDefault();
                                            if (person == null)
                                            {
                                                person = matches.OrderBy(p => p.Id).First();
                                            }
                                        }
                                    }
                                    else if (matches.Count == 1)
                                    {
                                        person = matches.First();
                                    }
                                    else
                                    {
                                        // Create the person
                                        Guid guid4 = Guid.NewGuid();
                                        person           = new Person();
                                        person.FirstName = member.firstName.Trim();
                                        person.LastName  = member.lastName.Trim();
                                        person.SetBirthDate(member.birthDate.Value);

                                        if (email != String.Empty)
                                        {
                                            person.Email = email;
                                        }
                                        person.RecordTypeValueId       = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                                        person.ConnectionStatusValueId = connectionStatus.Id;
                                        person.RecordStatusValueId     = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid()).Id;
                                        person.IsSystem   = false;
                                        person.IsDeceased = false;
                                        person.Guid       = guid4;
                                        var gender = member.gender;

                                        if (!String.IsNullOrEmpty(gender))
                                        {
                                            gender.Trim();

                                            if (gender == "Male" || gender == "male")
                                            {
                                                person.Gender = Gender.Male;
                                            }
                                            else if (gender == "Female" || gender == "female")
                                            {
                                                person.Gender = Gender.Female;
                                            }
                                            else
                                            {
                                                person.Gender = Gender.Unknown;
                                            }
                                        }
                                        else
                                        {
                                            person.Gender = Gender.Unknown;
                                        }


                                        var groupLocationTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME).Id;

                                        locationService.Verify(location, true);
                                        bool existingFamily = false;
                                        if (!string.IsNullOrWhiteSpace(member.address1))
                                        {
                                            var familyGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY);

                                            // See if we can find an existing family using the location where everyone is a web prospect
                                            var matchingLocations = locationService.Queryable().Where(l => l.Street1 == location.Street1 && l.PostalCode == location.PostalCode);
                                            var matchingFamilies  = matchingLocations.Where(l => l.GroupLocations.Any(gl => gl.Group.GroupTypeId == familyGroupType.Id)).SelectMany(l => l.GroupLocations).Select(gl => gl.Group);
                                            var matchingFamily    = matchingFamilies.Where(f => f.Members.All(m => m.Person.ConnectionStatusValueId == connectionStatus.Id) && f.Name == member.lastName + " Family");
                                            if (matchingFamily.Count() == 1)
                                            {
                                                var adultRole = familyGroupType.Roles
                                                                .FirstOrDefault(r =>
                                                                                r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()));

                                                var childRole = familyGroupType.Roles
                                                                .FirstOrDefault(r =>
                                                                                r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid()));

                                                var age = person.Age;

                                                var familyRole = age.HasValue && age < 18 ? childRole : adultRole;
                                                PersonService.AddPersonToFamily(person, true, matchingFamily.FirstOrDefault().Id, familyRole.Id, rockContext);
                                                existingFamily = true;
                                            }
                                        }

                                        if (!existingFamily)
                                        {
                                            Group         family        = PersonService.SaveNewPerson(person, rockContext);
                                            GroupLocation groupLocation = new GroupLocation();
                                            groupLocation.GroupLocationTypeValueId = groupLocationTypeValueId;
                                            groupLocation.Location         = location;
                                            groupLocation.IsMappedLocation = true;
                                            family.CampusId = CampusCache.All().FirstOrDefault().Id;
                                            family.GroupLocations.Add(groupLocation);
                                        }

                                        rockContext.SaveChanges();
                                    }

                                    var groupLocationType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME);

                                    // Check to see if the address/location should be updated.
                                    if (member.dateJoined > person.GetFamilies().SelectMany(f => f.GroupLocations).Where(gl => gl.GroupLocationTypeValueId == groupLocationType.Id).Max(gl => gl.CreatedDateTime ?? gl.Location.CreatedDateTime))
                                    {
                                        if (!location.StandardizedDateTime.HasValue)
                                        {
                                            locationService.Verify(location, true);
                                        }
                                        var allLocations = person.GetFamilies().SelectMany(f => f.GroupLocations);
                                        if (location.Street1 != null && location.StandardizedDateTime != null && !allLocations.Any(hl => hl.Location.Street1 == location.Street1) && !location.Street1.Contains("PO Box") && !location.Street1.Contains("PMB"))
                                        {
                                            locationService.Add(location);
                                            rockContext.SaveChanges();


                                            // Get all existing addresses of the specified type
                                            var groupLocations = person.PrimaryFamily.GroupLocations.Where(l => l.GroupLocationTypeValueId == groupLocationType.Id).ToList();

                                            // Create a new address of the specified type, saving all existing addresses of that type as Previous Addresses
                                            // Use the Is Mailing and Is Mapped values from any of the existing addresses of that type have those values set to true
                                            GroupService.AddNewGroupAddress(rockContext, person.PrimaryFamily,
                                                                            groupLocationType.Guid.ToString(), location.Id, true,
                                                                            "LeagueApps Import Data Job",
                                                                            groupLocations.Any(x => x.IsMailingLocation),
                                                                            groupLocations.Any(x => x.IsMappedLocation));
                                        }
                                    }

                                    // Update the person's LeagueApps User ID attribute
                                    person.LoadAttributes();
                                    var attributevaluelist = person.GetAttributeValue(personattribute.Key).SplitDelimitedValues().ToList();
                                    if (!attributevaluelist.Contains(applicant.userId.ToString()))
                                    {
                                        attributevaluelist.Add(applicant.userId.ToString());
                                        person.SetAttributeValue(personattribute.Key, string.Join("|", attributevaluelist) + "|");
                                        person.SaveAttributeValues(rockContext);
                                    }
                                }

                                // Check to see if the group member already exists
                                GroupMember groupmember = league3.Members.Where(m => m.PersonId == person.Id).FirstOrDefault();

                                if (groupmember == null)
                                {
                                    Guid guid5 = Guid.NewGuid();
                                    groupmember          = new GroupMember();
                                    groupmember.PersonId = person.Id;
                                    groupmember.GroupId  = league3.Id;
                                    groupmember.IsSystem = false;
                                    groupmember.Guid     = guid5;

                                    if (!String.IsNullOrEmpty(applicant.role))
                                    {
                                        var role = applicant.role.Split('(')[0].Trim();

                                        if (role == "FREEAGENT" || role == "PLAYER")
                                        {
                                            role = "Member";
                                        }
                                        else if (role == "CAPTAIN")
                                        {
                                            role = "Captain";
                                        }
                                        else if (role == "HEAD COACH" || role == "Head Coach")
                                        {
                                            role = "Head Coach";
                                        }
                                        else if (role == "ASST. COACH" || role == "Asst. Coach")
                                        {
                                            role = "Asst. Coach";
                                        }
                                        else
                                        {
                                            role = "Member";
                                        }
                                        var grouprole = groupTypeRoleService.Queryable().Where(r => r.GroupTypeId == groupType.Id && r.Name == role).FirstOrDefault().Id;
                                        groupmember.GroupRoleId = grouprole;
                                    }
                                    else
                                    {
                                        groupmember.GroupRoleId = groupType.DefaultGroupRoleId.Value;
                                    }
                                    groupmember.GroupMemberStatus = GroupMemberStatus.Active;
                                    groupMemberService.Add(groupmember);
                                    rockContext.SaveChanges();
                                }

                                // Make sure we update the team if necessary
                                groupmember.LoadAttributes();
                                groupmember.SetAttributeValue(groupmemberattribute.Key, applicant.team);
                                groupmember.SaveAttributeValues(rockContext);
                            }
                        }
                        processed++;
                    }

                    foreach (Group sportsleague in groups)
                    {
                        sportsleague.IsActive = false;
                        dbContext.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("LeagueApps Job Failed", ex);
            }
            finally
            {
                dbContext.SaveChanges();
            }

            if (warnings.Length > 0)
            {
                throw new Exception(warnings);
            }
            context.Result = "Successfully imported " + processed + " leagues.";
        }
Exemplo n.º 13
0
        /// <summary>Process all leagues (programs) from LeagueApps.</summary>
        /// <param name="message">The message that is returned depending on the result.</param>
        /// <param name="state">The state of the process.</param>
        /// <returns><see cref="WorkerResultStatus"/></returns>
        public void Execute(IJobExecutionContext context)
        {
            RockContext           dbContext             = new RockContext();
            GroupService          groupService          = new GroupService(dbContext);
            AttributeService      attributeService      = new AttributeService(dbContext);
            AttributeValueService attributeValueService = new AttributeValueService(dbContext);
            GroupTypeRoleService  groupTypeRoleService  = new GroupTypeRoleService(dbContext);
            DefinedValueService   definedValueService   = new DefinedValueService(dbContext);
            DefinedTypeService    definedTypeService    = new DefinedTypeService(dbContext);
            BinaryFileService     binaryFileService     = new BinaryFileService(dbContext);

            // Get the datamap for loading attributes
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            var warnings  = string.Empty;
            var processed = 0;

            try
            {
                var apiClient = new APIClient();

                var settings = SettingsComponent.GetComponent <LeagueAppsSettings>();

                //Group Attributes
                var parentGroup          = groupService.Get(settings.GetAttributeValue(Constants.ParentGroup).AsGuid());
                var yearGroupType        = GroupTypeCache.Get(settings.GetAttributeValue(Constants.YearGroupType).AsGuid());
                var categoryGroupType    = GroupTypeCache.Get(settings.GetAttributeValue(Constants.CategoryGroupType).AsGuid());
                var leagueGroupType      = GroupTypeCache.Get(settings.GetAttributeValue(Constants.LeagueGroupType).AsGuid());
                var sportsType           = DefinedTypeCache.Get(Constants.SPORTS_TYPE.AsGuid());
                var seasonsType          = DefinedTypeCache.Get(Constants.SEASONS_TYPE.AsGuid());
                var gendersType          = DefinedTypeCache.Get(Constants.GENDERS_TYPE.AsGuid());
                var groupMemberAttribute = AttributeCache.Get(settings.GetAttributeValue(Constants.LeagueGroupTeam).AsGuid());

                //Person Attribute
                var personattribute  = AttributeCache.Get(Constants.ATTRIBUTE_PERSON_USER_ID.AsGuid());
                var connectionStatus = DefinedValueCache.Get(settings.GetAttributeValue(Constants.DefaultConnectionStatus).AsGuid());

                var groupEntityType = EntityTypeCache.Get(typeof(Group)).Id;

                var programs = apiClient.GetPublic <List <Programs> >("/v1/sites/{siteid}/programs/current");


                var groups = groupService.Queryable().Where(g => g.GroupTypeId == leagueGroupType.Id).ToList();

                foreach (Contracts.Programs program in programs)
                {
                    // Process the program
                    Group league    = null;
                    Group league2   = null;
                    Group league3   = null;
                    var   startdate = program.startTime;
                    var   mode      = program.mode.ToLower();
                    mode = mode.First().ToString().ToUpper() + mode.Substring(1);
                    var grandparentgroup = string.Format("{0}", startdate.Year);
                    if (program.programId > 0)
                    {
                        league = groupService.Queryable().Where(l => l.Name == grandparentgroup && l.ParentGroupId == parentGroup.Id).FirstOrDefault();
                        if (league != null)
                        {
                            league2 = groupService.Queryable().Where(l => l.Name == mode && l.ParentGroupId == league.Id).FirstOrDefault();
                            if (league2 != null)
                            {
                                league3 = groupService.Queryable().Where(l => l.ForeignId == program.programId && l.GroupTypeId == leagueGroupType.Id && l.ParentGroupId == league2.Id).FirstOrDefault();
                            }
                        }
                    }
                    Guid guid  = Guid.NewGuid();
                    Guid guid2 = Guid.NewGuid();
                    Guid guid3 = Guid.NewGuid();

                    if (league == null)
                    {
                        // Create league grandparent Group
                        Group leagueGPG = new Group();
                        leagueGPG.Name           = grandparentgroup;
                        leagueGPG.GroupTypeId    = yearGroupType.Id;
                        leagueGPG.ParentGroupId  = parentGroup.Id;
                        leagueGPG.IsSystem       = false;
                        leagueGPG.IsActive       = true;
                        leagueGPG.IsSecurityRole = false;
                        leagueGPG.Order          = 0;
                        leagueGPG.Guid           = guid;
                        groupService.Add(leagueGPG);

                        // Now save the league grandparent group
                        dbContext.SaveChanges();
                        league = leagueGPG;
                    }

                    if (league2 == null)
                    {
                        // Create league parent Group
                        Group leaguePG = new Group();
                        leaguePG.Name           = mode;
                        leaguePG.GroupTypeId    = categoryGroupType.Id;
                        leaguePG.ParentGroupId  = league.Id;
                        leaguePG.IsSystem       = false;
                        leaguePG.IsActive       = true;
                        leaguePG.IsSecurityRole = false;
                        leaguePG.Order          = 0;
                        leaguePG.Guid           = guid2;
                        groupService.Add(leaguePG);

                        // Now save the league parent group
                        dbContext.SaveChanges();
                        league2 = leaguePG;
                    }

                    if (league3 == null)
                    {
                        // Create the league
                        Group leagueG = new Group();
                        leagueG.Name           = program.name;
                        leagueG.GroupTypeId    = leagueGroupType.Id;
                        leagueG.ParentGroupId  = league2.Id;
                        leagueG.IsSystem       = false;
                        leagueG.IsActive       = true;
                        leagueG.IsSecurityRole = false;
                        leagueG.Order          = 0;
                        leagueG.Description    = HTMLConvertor.Convert(program.description);
                        leagueG.ForeignId      = program.programId;
                        groupService.Add(leagueG);

                        // Now save the league
                        dbContext.SaveChanges();
                        league3 = leagueG;
                    }
                    else
                    {
                        groups.Remove(league3);
                    }
                    league3.LoadAttributes();
                    var sport       = definedValueService.Queryable().Where(d => d.Value == program.sport && d.DefinedTypeId == sportsType.Id).FirstOrDefault();
                    var season      = definedValueService.Queryable().Where(d => d.Value == program.season && d.DefinedTypeId == seasonsType.Id).FirstOrDefault();
                    var groupgender = definedValueService.Queryable().Where(d => d.Value == program.gender && d.DefinedTypeId == gendersType.Id).FirstOrDefault();

                    if (!sport.IsNull())
                    {
                        league3.SetAttributeValue("Sport", sport.Guid);
                    }

                    if (!season.IsNull())
                    {
                        league3.SetAttributeValue("Season", season.Guid);
                    }
                    league3.SetAttributeValue("ExperienceLevel", program.experienceLevel);

                    if (!groupgender.IsNull())
                    {
                        league3.SetAttributeValue("Gender", groupgender.Guid);
                    }

                    if (startdate != DateTime.MinValue)
                    {
                        league3.SetAttributeValue("StartTime", startdate);
                    }

                    if (program.publicRegistrationTime != DateTime.MinValue)
                    {
                        league3.SetAttributeValue("PublicRegistrationTime", program.publicRegistrationTime);
                    }

                    if (program.ageLimitEffectiveDate != DateTime.MinValue)
                    {
                        league3.SetAttributeValue("AgeLimitDate", program.ageLimitEffectiveDate.Date.ToString("d"));
                    }
                    league3.SetAttributeValue("ProgramURL", program.programUrlHtml);
                    league3.SetAttributeValue("RegisterURL", program.registerUrlHtml);
                    league3.SetAttributeValue("ScheduleURL", program.scheduleUrlHtml);
                    league3.SetAttributeValue("StandingsURL", program.standingsUrlHtml);
                    league3.SetAttributeValue("ProgramLogo", program.programLogo150);
                    league3.SaveAttributeValues();
                    dbContext.SaveChanges();

                    var applicants = apiClient.GetPrivate <List <Registrations> >("/v2/sites/{siteid}/export/registrations-2?last-updated=0&last-id=0&program-id=" + program.programId);

                    context.UpdateLastStatusMessage("Processing league " + (processed + 1) + " of " + programs.Count + ": " + program.startTime.Year + " > " + program.mode + " > " + program.name + " (" + applicants.Count + " members).");

                    foreach (Contracts.Registrations applicant in applicants)
                    {
                        // Use a fresh RockContext on every person/groupmember to keep things moving quickly
                        using (var rockContext = new RockContext())
                        {
                            PersonService      personService      = new PersonService(rockContext);
                            GroupMemberService groupMemberService = new GroupMemberService(rockContext);
                            LocationService    locationService    = new LocationService(rockContext);

                            Person person = null;

                            // 1. Try to load the person using the LeagueApps UserId
                            var attributevalue = applicant.userId.ToString();
                            var personIds      = attributeValueService.Queryable().Where(av => av.AttributeId == personattribute.Id &&
                                                                                         (av.Value == attributevalue ||
                                                                                          av.Value.Contains("|" + attributevalue + "|") ||
                                                                                          av.Value.StartsWith(attributevalue + "|"))).Select(av => av.EntityId);
                            if (personIds.Count() == 1)
                            {
                                person = personService.Get(personIds.FirstOrDefault().Value);
                            }

                            // 2. If we don't have a person match then
                            //    just use the standard person match/create logic
                            if (person == null)
                            {
                                var member = apiClient.GetPrivate <Member>("/v2/sites/{siteid}/members/" + applicant.userId);
                                person = LeagueAppsHelper.CreatePersonFromMember(member, connectionStatus);
                            }

                            // Check to see if the group member already exists
                            var groupmember = groupMemberService.GetByGroupIdAndPersonId(league3.Id, person.Id).FirstOrDefault();

                            if (groupmember == null)
                            {
                                Guid guid5 = Guid.NewGuid();
                                groupmember          = new GroupMember();
                                groupmember.PersonId = person.Id;
                                groupmember.GroupId  = league3.Id;
                                groupmember.IsSystem = false;
                                groupmember.Guid     = guid5;

                                if (!String.IsNullOrEmpty(applicant.role))
                                {
                                    var role = applicant.role.Split('(')[0].Trim();

                                    if (role == "FREEAGENT" || role == "PLAYER")
                                    {
                                        role = "Member";
                                    }
                                    else if (role == "CAPTAIN")
                                    {
                                        role = "Captain";
                                    }
                                    else if (role == "HEAD COACH" || role == "Head Coach")
                                    {
                                        role = "Head Coach";
                                    }
                                    else if (role == "ASST. COACH" || role == "Asst. Coach")
                                    {
                                        role = "Asst. Coach";
                                    }
                                    else
                                    {
                                        role = "Member";
                                    }
                                    var grouprole = groupTypeRoleService.Queryable().Where(r => r.GroupTypeId == leagueGroupType.Id && r.Name == role).FirstOrDefault().Id;
                                    groupmember.GroupRoleId = grouprole;
                                }
                                else
                                {
                                    groupmember.GroupRoleId = leagueGroupType.DefaultGroupRoleId.Value;
                                }
                                groupmember.GroupMemberStatus = GroupMemberStatus.Active;
                                groupMemberService.Add(groupmember);
                                rockContext.SaveChanges();
                            }

                            // Make sure we update the team if necessary
                            groupmember.LoadAttributes();
                            groupmember.SetAttributeValue(groupMemberAttribute.Key, applicant.team);
                            groupmember.SaveAttributeValues(rockContext);
                        }
                    }
                    processed++;
                }

                foreach (Group sportsleague in groups)
                {
                    sportsleague.IsActive = false;
                    dbContext.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("LeagueApps Job Failed", ex);
            }
            finally
            {
                dbContext.SaveChanges();
            }

            if (warnings.Length > 0)
            {
                throw new Exception(warnings);
            }
            context.Result = "Successfully imported " + processed + " leagues.";
        }