bpnit
bpnit

Reputation: 3

C# using Google Classroom API Read List of Students

I am trying to write a console app for our elementary school which will read courses, students, coursework (etc) from Google Classrooms and write it to our SQL Server database. This is the first time I have ever used an API and I have very little experience with C# - but school starts in two days, so I'm using Google searches to figure out how to do it.

I pasted my code below that successfully reads the courses from Google Classroom and writes them to our SQL Server. I thought I could use the same logic for the rest of the tables (students, Coursework, etc). However, when I tried to add students, there is a problem with this line (list is underlined in red):

CoursesResource.ListRequest RequestStudents = service.Courses.Students.List();

I can't figure out what is wrong and can't seem to find an example online.

Any help would be very appreciated.

Thanks, JMC


namespace ClassroomQuickstart
{
    class Program
    {
        static string ApplicationName = "Google Classroom ETL Process";
        static string[] Scopes = 
            {
            ClassroomService.Scope.ClassroomAnnouncementsReadonly,
            ClassroomService.Scope.ClassroomCoursesReadonly,
            ClassroomService.Scope.ClassroomCourseworkStudentsReadonly,
            ClassroomService.Scope.ClassroomGuardianlinksStudentsReadonly,
            ClassroomService.Scope.ClassroomRostersReadonly,
            ClassroomService.Scope.ClassroomStudentSubmissionsStudentsReadonly,
            ClassroomService.Scope.ClassroomTopicsReadonly
            };

        static void Main(string[] args)
        {
            UserCredential credential;
            using (var stream = new FileStream("MyCredentials.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = "TokenGoogleClassroomETLClient";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user", 
                    CancellationToken.None, 
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create the service.
            var service = new ClassroomService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

            //==============================================================================================
            // Transfer courses 

            // Define request parameters
            CoursesResource.ListRequest RequestCourses = service.Courses.List();
            RequestCourses.PageSize = 1000;
            ListCoursesResponse ResponseCourses = RequestCourses.Execute();

            if (ResponseCourses.Courses != null && ResponseCourses.Courses.Count > 0)
            {
                Console.WriteLine("\n=========================================");
                Console.WriteLine("\nTransferring Google Classrooms Courses:");

                // prepare the parameterized SQL statement
                StringBuilder sb = new StringBuilder();
                sb.Append("INSERT INTO GoogleClassroomsCourse ");
                sb.Append("(CourseID, CourseName, CourseSection, DescriptionHeading, Description, Room, OwnerID, CreationTime, UpdateTime, EnrollmentCode, CourseState, AlternateLink, TeacherGroupEmail, CourseGroupEmail, GuardianEnabled, CalendarID) ");
                sb.Append("VALUES (@Id , @Name, @Section, @DescriptionHeading, @Description, @Room, @OwnerId, @CreationTime, @UpdateTime, @EnrollmentCode, @CourseState, @AlternateLink, @TeacherGroupEmail, @CourseGroupEmail, @GuardiansEnabled, @CalendarId)");
                String sql = sb.ToString();

                // establish connecion to the SQL Server
                using (SqlConnection connection = new SqlConnection("MyConnectionString"))
                {
                    connection.Open();
                    // process each course record in Google Classrom
                    foreach (var course in ResponseCourses.Courses)
                    {
                        // ouput the course name and id to the console
                        Console.WriteLine("{0} ({1})", course.Name, course.Id);

                        // populate the variables from the current course record
                        string Id = course.Id ?? "";
                        string Name = course.Name ?? "";
                        string Section = course.Section ?? "";
                        string DescriptionHeading = course.DescriptionHeading ?? "";
                        string Description = course.Description ?? "";
                        string Room = course.Room ?? "";
                        string OwnerId = course.OwnerId ?? "";
                        string CreationTime = course.CreationTime.ToString() ?? "";
                        string UpdateTime = course.UpdateTime.ToString() ?? "";
                        string EnrollmentCode = course.EnrollmentCode ?? "";
                        string CourseState = course.CourseState ?? "";
                        string AlternateLink = course.AlternateLink ?? "";
                        string TeacherGroupEmail = course.TeacherGroupEmail ?? "";
                        string CourseGroupEmail = course.CourseGroupEmail ?? "";
                        string GuardiansEnabled = course.GuardiansEnabled.ToString() ?? "";
                        string CalendarId = course.CalendarId ?? "";

                        // write the record to sql database 
                        try
                        {
                            using (SqlCommand command = new SqlCommand(sql, connection))
                            {

                                command.Parameters.AddWithValue("@Id", Id);
                                command.Parameters.AddWithValue("@Name", Name);
                                command.Parameters.AddWithValue("@Section", Section);
                                command.Parameters.AddWithValue("@DescriptionHeading", DescriptionHeading);
                                command.Parameters.AddWithValue("@Description", Description);
                                command.Parameters.AddWithValue("@Room", Room);
                                command.Parameters.AddWithValue("@OwnerId", OwnerId);
                                command.Parameters.AddWithValue("@CreationTime", CreationTime);
                                command.Parameters.AddWithValue("@UpdateTime", UpdateTime);
                                command.Parameters.AddWithValue("@EnrollmentCode", EnrollmentCode);
                                command.Parameters.AddWithValue("@CourseState", CourseState);
                                command.Parameters.AddWithValue("@AlternateLink", AlternateLink);
                                command.Parameters.AddWithValue("@TeacherGroupEmail", TeacherGroupEmail);
                                command.Parameters.AddWithValue("@CourseGroupEmail", CourseGroupEmail);
                                command.Parameters.AddWithValue("@GuardiansEnabled", GuardiansEnabled);
                                command.Parameters.AddWithValue("@CalendarId", CalendarId);

                                int rowsAffected = command.ExecuteNonQuery();
                             }

                        }
                        catch (SqlException e)
                        {
                            Console.WriteLine(e.ToString());
                        }

                        //==============================================================================================
                        // Transfer students in the current course

                        // Define request parameters.
                        CoursesResource.ListRequest RequestStudents = service.Courses.Students.List();
                        RequestStudents.PageSize = 1000;
                        ListStudentsResponse ResponseStudents = RequestStudents.Execute();

                        if (ResponseStudents.Students != null && ResponseStudents.Students.Count > 0)
                        {
                            Console.WriteLine("\n=========================================");
                            Console.WriteLine("\nTransferring Google Classrooms Students:");
                            Console.WriteLine(ResponseStudents.Students.Count.ToString());
                        }

                    }
                connection.Close();
                }
            }
            else
            {
                Console.WriteLine("No courses found.");
            }
            Console.Read();

        }
    }
}

Upvotes: 0

Views: 698

Answers (1)

Hayden
Hayden

Reputation: 2988

Looking further at the signature, Students.List requires a course ID as a parameter, which is currently not provided. On top of this, the return type for Students.List is CoursesResource.StudentsResource.ListRequest. To fix, replace the line with:

CoursesResource.StudentsResource.ListRequest RequestStudents = service.Courses.Students.List(course.Id);

Upvotes: 1

Related Questions