public async Task TestGetUserMembershipsAsync()
        {
            var displayOptions = new DisplayOptions {
                Page = 1, PerPage = 20, Order = OrderType.Asc
            };
            var membershipFilter = new MembershipFilter {
                AccountName = "tothnet", MembershipOrder = MembershipOrder.Status, Status = Status.Accepted
            };

            _wireMockServer
            .Given(Request.Create()
                   .WithPath($"/{MembershipEndpoints.Base}/")
                   .WithParam(Filtering.Page)
                   .WithParam(Filtering.PerPage)
                   .WithParam(Filtering.Order)
                   .WithParam(Filtering.Status)
                   .WithParam(Filtering.AccountName)
                   .WithParam(Filtering.Direction)
                   .UsingGet())
            .RespondWith(Response.Create().WithStatusCode(200)
                         .WithBody(WireMockResponseHelper.CreateTestResponse(UserMembershipTestsData.Memberships)));

            using var client = new CloudFlareClient(WireMockConnection.ApiKeyAuthentication, _connectionInfo);

            var userMembership = await client.Users.Memberships.GetAsync(membershipFilter, displayOptions);

            userMembership.Result.Should().BeEquivalentTo(UserMembershipTestsData.Memberships);
        }
Beispiel #2
0
        public string[] CreateAnnouncement(string courseId, string userUuid, Dictionary <string, object> licenseSettings, string announcementTitle, string announcementMessage)
        {
            string error;
            var    courseIdFixed = string.Format("_{0}_1", courseId);

            var client = BeginBatch(out error, licenseSettings);

            CourseMembershipWrapper membershipWS = client.getCourseMembershipWrapper();
            var membershipFilter = new MembershipFilter
            {
                filterType          = 2,
                filterTypeSpecified = true,
                courseIds           = new[] { courseIdFixed },
            };
            var enrollments = membershipWS.loadCourseMembership(courseIdFixed, membershipFilter);

            var userWS            = client.getUserWrapper();
            var courseUsersFilter = new UserFilter
            {
                filterTypeSpecified = true,
                filterType          = 2,
                id = enrollments.Select(x => x.userId).ToArray(),
            };
            var courseUsers = userWS.getUser(courseUsersFilter);
            var uuidString  = "USER.UUID=" + userUuid;
            var user        = courseUsers.FirstOrDefault(cu => cu != null &&
                                                         cu.expansionData != null &&
                                                         cu.expansionData.Any(ed => string.Compare(uuidString, ed, StringComparison.OrdinalIgnoreCase) == 0));

            if (user == null)
            {
                var adminRoles = new[] { "SYSTEM_ADMIN", "COURSE_CREATOR" };
                user = courseUsers.FirstOrDefault(x => x.systemRoles.Any(role => adminRoles.Contains(role)));
            }

            if (user != null)
            {
                var announcementVO = new AnnouncementVO
                {
                    body                = announcementMessage,
                    creatorUserId       = user.id,
                    courseId            = courseIdFixed,
                    permanent           = true,
                    permanentSpecified  = true,
                    position            = 1,
                    positionSpecified   = true,
                    pushNotify          = true,
                    pushNotifySpecified = true,
                    title               = announcementTitle,
                };

                var annWS   = client.getAnnouncementWrapper();
                var results = annWS.saveCourseAnnouncements(courseIdFixed, new[] { announcementVO });

                return(results);
            }

            return(null);
        }
Beispiel #3
0
        public async Task <HttpResponseMessage> EnquiryMembership([FromBody] MembershipFilter filter)
        {
            var config = new MapperConfiguration(cfg => {
                cfg.CreateMap <MembershipFilter, UserFilter>();
            });

            var filtered = config.CreateMapper().Map <MembershipFilter, UserFilter>(filter);

            var result = _identityService.GetMembershipByFilter(filtered);

            return(await this.ReturnSuccessModel(result.Any()?result : new UserModel[] { }));
        }
Beispiel #4
0
        public ActionResult EnquiryMembership(MembershipFilter filter)
        {
            if (ModelState.IsValid)
            {
                var response = PostAPIRequest <IEnumerable <UserViewModel> >(EndPoints.MEMBERSHIP_ENQUIRY_MEMBERSHIP, filter);

                TempData["ViewBag.Message"] = response.Message;

                return(View(response.ResultData));
            }

            return(Redirect("Index"));
        }
Beispiel #5
0
        public async Task <GroupMembershipVO[]> BbGroupMembership(string courseId, MembershipFilter filter)
        {
            _tryCount += 1;

            if (_tryCount == 3)
            {
                await ResetConnection();

                _memClient = null;
            }

            if (_memClient == null)
            {
                _memClient = await GetMemClient();
            }
            var gmVo = await _memClient.getGroupMembershipAsync(courseId, filter);

            _tryCount = 0;
            return(gmVo.@return);
        }
        /// <inheritdoc />
        public async Task <CloudFlareResult <IReadOnlyList <Membership> > > GetAsync(MembershipFilter filter = null, DisplayOptions displayOptions = null, CancellationToken cancellationToken = default)
        {
            var builder = new ParameterBuilderHelper();

            builder
            .InsertValue(Filtering.Status, filter?.Status)
            .InsertValue(Filtering.AccountName, filter?.AccountName)
            .InsertValue(Filtering.Order, filter?.MembershipOrder)
            .InsertValue(Filtering.Page, displayOptions?.Page)
            .InsertValue(Filtering.PerPage, displayOptions?.PerPage)
            .InsertValue(Filtering.Direction, displayOptions?.Order);

            var requestUri = $"{MembershipEndpoints.Base}";

            if (builder.ParameterCollection.HasKeys())
            {
                requestUri = $"{requestUri}/?{builder.ParameterCollection}";
            }

            return(await Connection.GetAsync <IReadOnlyList <Membership> >(requestUri, cancellationToken).ConfigureAwait(false));
        }
Beispiel #7
0
        /// <summary>
        /// Filters a <see cref="ReadOnlyBoardMembershipCollection"/> for a given <see cref="MembershipFilter"/>.
        /// </summary>
        /// <param name="memberships">The <see cref="ReadOnlyBoardMembershipCollection"/></param>
        /// <param name="filter">The new <see cref="MembershipFilter"/> by which to filter.  Can be combined using the bitwise OR operator.</param>
        /// <returns>The filtered collection.</returns>
        /// <remarks>The new filter parameter will function as an OR parameter.</remarks>
        public static ReadOnlyBoardMembershipCollection Filter(this ReadOnlyBoardMembershipCollection memberships, MembershipFilter filter)
        {
            var collection = new ReadOnlyBoardMembershipCollection(memberships, memberships.Auth);

            collection.AddFilter(new[] { filter });
            return(collection);
        }
        /// <summary>
        /// Adds a filter to the collection.
        /// </summary>
        /// <param name="filter">The filter value.</param>
        public void Filter(MembershipFilter filter)
        {
            var filters = filter.GetFlags().Cast <MembershipFilter>();

            Filter(filters);
        }
Beispiel #9
0
        public async Task <MemReconResult> ReconcileCourseMembers(int courseId)
        {
            //await GetProfile();

            var ecatCourse = await ctxManager.Context.Courses
                             .Where(crse => crse.Id == courseId)
                             .Select(crse => new CourseReconcile
            {
                Course             = crse,
                FacultyToReconcile = crse.Faculty.Select(fac => new UserReconcile
                {
                    PersonId  = fac.FacultyPersonId,
                    BbUserId  = fac.FacultyProfile.Person.BbUserId,
                    CanDelete = !fac.FacSpComments.Any() &&
                                !fac.FacSpResponses.Any() &&
                                !fac.FacStratResponse.Any()
                }).ToList(),
                StudentsToReconcile = crse.Students.Select(sic => new UserReconcile
                {
                    PersonId  = sic.StudentPersonId,
                    BbUserId  = sic.Student.Person.BbUserId,
                    CanDelete = !sic.WorkGroupEnrollments.Any()
                }).ToList()
            }).SingleOrDefaultAsync();

            Contract.Assert(ecatCourse != null);

            var reconResult = new MemReconResult
            {
                Id        = Guid.NewGuid(),
                CourseId  = courseId,
                AcademyId = Faculty?.AcademyId
            };

            var autoRetryCm = new Retrier <CourseMembershipVO[]>();

            var courseMemFilter = new MembershipFilter
            {
                filterTypeSpecified = true,
                filterType          = (int)CrseMembershipFilterType.LoadByCourseId,
            };

            var bbCourseMems = await autoRetryCm.Try(() => _bbWs.BbCourseMembership(ecatCourse.Course.BbCourseId, courseMemFilter), 3);

            var existingCrseUserIds = ecatCourse.FacultyToReconcile
                                      .Select(fac => fac.BbUserId).ToList();

            existingCrseUserIds.AddRange(ecatCourse.StudentsToReconcile.Select(sic => sic.BbUserId));

            var newMembers = bbCourseMems
                             .Where(cm => !existingCrseUserIds.Contains(cm.userId))
                             .Where(cm => cm.available == true)
                             .ToList();

            if (newMembers.Any())
            {
                //var queryCr = await autoRetryCr.Try(client.getCourseRolesAsync(bbCourseMems.Select(bbcm => bbcm.roleId).ToArray()), 3);

                //var bbCourseRoles = [email protected]();
                reconResult = await AddNewUsers(newMembers, reconResult);

                reconResult.NumAdded = newMembers.Count();
            }

            var usersBbIdsToRemove = existingCrseUserIds.Where(ecu => !bbCourseMems.Select(cm => cm.userId).Contains(ecu)).ToList();

            if (usersBbIdsToRemove.Any())
            {
                reconResult.RemovedIds = await RemoveOrFlagUsers(ecatCourse, usersBbIdsToRemove);

                reconResult.NumRemoved = reconResult.RemovedIds.Count();
            }

            return(reconResult);
        }
        /// <summary>
        /// Adds a filter to the collection.
        /// </summary>
        /// <param name="membership">The filter value.</param>
        public void Filter(MembershipFilter membership)
        {
            var memberships = membership.GetFlags().Cast <MembershipFilter>();

            Filter(memberships);
        }
Beispiel #11
0
        public List <LmsUserDTO> GetUsersForCourse(
            Dictionary <string, object> licenseSettings,
            string courseId,
            string[] userIds,
            out string error,
            ref WebserviceWrapper client)
        {
            var courseIdFixed = string.Format("_{0}_1", courseId);

            var enrollmentsResult = LoginIfNecessary(
                ref client,
                c =>
            {
                string errorDuringEnrollments = null;
                var resultedList = new List <LmsUserDTO>();

                // NOTE: check http://library.blackboard.com/ref/fd8c40a0-f670-4c48-9e02-c5d84e61eda7/blackboard/ws/coursemembership/CourseMembershipWS.html
                // for filterType
                //var membershipFilter = new MembershipFilter
                //{
                //    filterType = (userIds == null) ? 2 : 6,
                //    filterTypeSpecified = true,
                //    courseIds = new[] { courseIdFixed },
                //    userIds = userIds,
                //};
                var membershipFilter = new MembershipFilter
                {
                    filterType          = 2,
                    filterTypeSpecified = true,
                    courseIds           = new[] { courseIdFixed },
                };

                CourseMembershipWrapper membership = c.getCourseMembershipWrapper();

                if (membership != null)
                {
                    CourseMembershipVO[] enrollments = membership.loadCourseMembership(courseIdFixed, membershipFilter);
                    if (HadError(c, out errorDuringEnrollments))
                    {
                        return(new Tuple <List <LmsUserDTO>, string>(resultedList, errorDuringEnrollments));
                    }

                    if (enrollments != null)
                    {
                        var activeEnrollments = enrollments.Where(x => x.available.HasValue && x.available.Value);

                        CourseMembershipRoleVO[] roles = membership.loadRoles(null);
                        var userFilter = new UserFilter
                        {
                            filterTypeSpecified = true,
                            filterType          = 2,
                            id = activeEnrollments.Select(x => x.userId).ToArray(),
                        };
                        UserWrapper userService = c.getUserWrapper();
                        if (userService != null)
                        {
                            UserVO[] users = userService.getUser(userFilter);
                            if (users == null)
                            {
                                HadError(c, out errorDuringEnrollments);
                                return(new Tuple <List <LmsUserDTO>, string>(resultedList, errorDuringEnrollments));
                            }

                            resultedList = activeEnrollments.Select(
                                e =>
                            {
                                var user        = users.FirstOrDefault(u => e.userId == u.id);
                                var ltiIdString = user != null && user.expansionData != null
                                            ? user.expansionData.FirstOrDefault(ed => ed.StartsWith("USER.UUID", StringComparison.OrdinalIgnoreCase))
                                            : null;
                                if (ltiIdString != null)
                                {
                                    ltiIdString = ltiIdString.Substring(ltiIdString.IndexOf('=') + 1);
                                }

                                return(new LmsUserDTO
                                {
                                    Id = e.userId,
                                    Login = user.With(x => x.name),
                                    Email = user.With(x => x.extendedInfo).With(x => x.emailAddress),
                                    Name = user.With(x => x.extendedInfo).Return(x => string.Format("{0} {1}", x.givenName, x.familyName).Trim(), user.With(s => s.name)),
                                    LmsRole = GetRole(e.roleId, roles),
                                    LtiId = ltiIdString,
                                });
                            }).ToList();
                        }
                    }
                }

                return(new Tuple <List <LmsUserDTO>, string>(resultedList, errorDuringEnrollments));
            },
                licenseSettings,
                out error);

            if (enrollmentsResult == null)
            {
                error = error ?? "SOAP. Unable to retrive result from API";
                return(new List <LmsUserDTO>());
            }
            return(enrollmentsResult);
        }
Beispiel #12
0
        static String[,] getCourseList(String courseuser)
        {
            // Create a two dimensional array to house the course and membership data
            String[,] courseList = new String[10000, 4];

            // Add headers as the first element of the array
            courseList[0, 0] = "COURSE ID";
            courseList[0, 1] = "COURSE NAME";
            courseList[0, 2] = "MEMBERSHIP ID";
            courseList[0, 3] = "COURSE ROLE";

            if (DEBUG)
            {
                Console.WriteLine(courseList[0, 0] + "," + courseList[0, 1] + "," + courseList[0, 2] + "," + courseList[0, 3]);
            }

            // Get the list of courseIds associated with the user requested.
            CourseIdVO [] courses = ctx.getMemberships(courseuser);

            if (courses == null)
            {
                return(courseList);
            }

            // Initialize a user filter, set to get user by username and availability.
            UserFilter uf = new UserFilter();

            uf.filterType          = 6;
            uf.filterTypeSpecified = true;
            uf.name = new string[] { courseuser };

            // Get the user object
            UserVO [] user = usr.getUser(uf);

            if (user == null)
            {
                return(courseList);
            }

            int i = 1;

            // Iterate through the course list returned from contextWS.getMemberships()
            foreach (CourseIdVO courseIdVO in courses)
            {
                try
                {
                    // Grab the course Id
                    String courseId = courseIdVO.externalId;

                    // Initialize a new Course Filter and Membership Filter
                    CourseFilter     cf = new CourseFilter();
                    MembershipFilter mf = new MembershipFilter();

                    // Set course filter to search for courses by user Id. Yes, this is redundant, however
                    // ContextWS.getMemberships returns both courses and organizations. This only retrieves courses
                    cf.filterType          = 3;
                    cf.filterTypeSpecified = true;
                    cf.ids = new string[] { courseId };

                    // Set the membership filter to get memberships by course Id and UserId.
                    // Getting by user Id only (filter type 5) always fails. The course Id will be added
                    // during the foreach loop below.
                    mf.filterType          = 6;
                    mf.filterTypeSpecified = true;
                    mf.userIds             = new string[] { user[0].id };

                    // Load courses according to the course filter above
                    CourseVO[] course = crs.loadCourses(cf);

                    // if course is null, either the call failed, or the courseId actually refers to an organization.
                    // Check for course == null so we don't throw an exception when attempting to access the array.
                    if (course == null || course[0] == null)
                    {
                        continue;
                    }
                    else
                    {
                        // Add the current course Id to the membership filter
                        mf.courseIds = new string[] { courseId };

                        // Get Course memberships for the given user and course, as specified in the membership filter
                        CourseMembershipVO[] memberships = crm.loadCourseMembership(courseId, mf);

                        // If memberships were returned...
                        if (memberships != null)
                        {
                            // add the course id, the course name, the membership pk1, and the role id
                            courseList[i, 0] = course[0].courseId;
                            courseList[i, 1] = course[0].name;
                            courseList[i, 2] = memberships[0].id;
                            courseList[i, 3] = memberships[0].roleId;
                            if (DEBUG)
                            {
                                Console.WriteLine(i + ": " + courseList[i, 0] + "," + courseList[i, 1] + "," + courseList[i, 2] + "," + courseList[i, 3]);
                            }
                            i++;
                        }
                    }
                }
                catch (Exception e)
                {
                    // This error handling is not very useful, but essentially it is likely failing because of a
                    // NullReferenceException, so the current courselist is returned.
                    return(courseList);
                }
            }
            // Finished processing, return courseLIst.
            return(courseList);
        }