C # с помощью Google Classroom API прочитать список учащихся

#c# #api

#c# #API

Вопрос:

Я пытаюсь написать консольное приложение для нашей начальной школы, Которое будет считывать курсы, студентов, курсовую работу (и т.д.) Из Google Classroom и записывать это в нашу базу данных SQL Server. Я впервые использую API, и у меня очень мало опыта работы с C #, но занятия начинаются через два дня, поэтому я использую поисковые запросы Google, чтобы выяснить, как это сделать.

Я вставил свой приведенный ниже код, который успешно считывает курсы из Google Classroom и записывает их на наш SQL Server. Я подумал, что мог бы использовать ту же логику для остальных таблиц (студенты, курсовая работа и т.д.). Однако, когда я попытался добавить студентов, возникла проблема с этой строкой (список подчеркнут красным).:

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

Я не могу понять, что не так, и, похоже, не могу найти пример в Интернете.

Любая помощь была бы очень признательна.

Спасибо, 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)).Resu<
                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 amp;amp; 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 amp;amp; 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();

        }
    }
}
  

Комментарии:

1. Что говорится в сообщении об ошибке в списке ошибок?

Ответ №1:

При дальнейшем рассмотрении подписи Students.List требуется идентификатор курса в качестве параметра, который в настоящее время не предоставляется. Вдобавок ко всему, возвращаемый тип для Students.List является CoursesResource.StudentsResource.ListRequest . Чтобы исправить, замените строку на:

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