Can I grade assignments "logged as student" with Google Classroom API? - google-classroom

I have an app using Google Classroom API. When connected as the teacher I can create course works and assignments. When connected as a student I can list my assignments and I can turn in a specific assignment.
I am using the REST API:
https://developers.google.com/classroom/reference/rest
When (logged as student) I turn in an assignment but I would like to include a draft grade.
I know if I were logged as the teacher I could set the grade, but what I want is the app calculating the draft grade based on some specific built-in logic, so that the teacher does not have to do it on their own for each student.
According to the documentation, both "draftGrade" and "assignedGrade" can only be updated by the teacher.
https://developers.google.com/classroom/reference/rest/v1/courses.courseWork.studentSubmissions#StudentSubmission
Any ideas about how to automate setting grades for submissions?

I think that is not possible: you cannot update the draftGrade with student privileges.
What you can do:
From the "student" session you save a draft grade in the application DB, associated to the Submission ID.
From the "teacher" session, and hence "teacher" permissions, you get the grade from the application DB and I call the Path query to set the draftGrade.
Some code (Swift, using GoogleAPIClientForREST) for step 2:
func executeQuery_GradeSubmission(studentSubmission: GTLRClassroom_StudentSubmission) -> GTLRServiceTicket? {
guard let courseID = self.myClassroom?.courseID,
let courseWorkID = self.selectedCourseWorkID else { return nil }
if let grade = self.gradesForSelectedWorkID?[studentSubmission.identifier!] {
studentSubmission.draftGrade = NSNumber(floatLiteral: Double(grade))
}
let query = GTLRClassroomQuery_CoursesCourseWorkStudentSubmissionsPatch.query(withObject: studentSubmission,
courseId: courseID,
courseWorkId: courseWorkID,
identifier: studentSubmission.identifier!)
query.updateMask = "draftGrade"
return self.myClassroom?.service.executeQuery(query,
delegate: self,
didFinish: #selector(displayGradeSubmissionResult(ticket:finishedWithObject:error:)))
}
#objc func displayGradeSubmissionResult(ticket: GTLRServiceTicket, finishedWithObject: GTLRObject, error: Any?){
let classroomSubmissionResponse = finishedWithObject as? GTLRClassroom_StudentSubmission
if let classroomError = error as? NSError {
print("displayGradeSubmissionResult. ERROR: \(classroomError.description)")
// TODO: inform something went wrong
} else {
if let submissionItems = self.classroomSubmissionsResponse?.studentSubmissions {
for submissionItem in submissionItems {
if submissionItem.identifier == classroomSubmissionResponse?.identifier {
submissionItem.draftGrade = classroomSubmissionResponse?.draftGrade
}
}
}
}
}

Related

Problem listing assignments of a student in Google Classroom

I am starting to use Classroom API to enhance local apps in our school. In order to make a report for a class, I want to list all student assignments and gradings. I use loops to go through all courses for a student, then all coursework for every course, and then all submissions for every coursework. Here is the piece of code that I use:
function fListWorkStudent(idStudent)
{
// Variables
var pageToken = null;
var optionalArgs =
{
pageToken: pageToken,
courseStates: 'ACTIVE',
studentId: idStudent,
pageSize: 0
};
var optionalArgs2 =
{
pageToken: pageToken,
userId: idStudent,
pageSize: 0
};
// Courses for a student
var response = Classroom.Courses.list(optionalArgs);
var sCourses = response.courses;
if (sCourses.length === 0)
Logger.log("No courses");
else
{
for (course in sCourses)
{
var idCourse=sCourses[course].id;
var nomprof=getUserName(sCourses[course].ownerId);
// Coursework for every course
var responseW = Classroom.Courses.CourseWork.list(idCourse);
var works = responseW.courseWork;
if (works && (works.length > 0))
{
for work in works)
{
var idWork=works[work].id;
// Submissions for every coursework
var responseS = Classroom.Courses.CourseWork.StudentSubmissions.list(idCourse, idWork, optionalArgs2);
var submissions = responseS.studentSubmissions;
if (submissions && submissions.length >0)
{
for (submission in submissions)
{
// Prepare report here
}
}
}
}
}
}
}
The problem with this code is that when I call Classroom.Courses.CourseWork.StudentSubmissions.list(idCourse, idWork, optionalArgs2) to get the submissions filtered of selected student, and the loop reaches a coursework not assigned to that student, the call fails with error 'classroom.courses.courseWork.studentSubmissions.list; error: Requested entity was not found.'
I could solve it by checking in the loop if the coursework is not assigned to that student before calling the API function, or maybe using a try..catch clause to catch the possible error, but I would like to know if there is a smarter solution to this issue.
Regards
Rafael
Unfortunately the API does not give you an endpoint to list directly all assignment / submissions of a given student
However, you are not alone with this problem, there is already a feature request for this functionality on Google's Public Issue Tracker.
I recommend you to give it a "star" in order to increase visibility.
In the mean time, indeed you either need to implement a try...catch statement, or a conditonal statement, something like:
if(works[work].assigneeMode == "ALL_STUDENTS" || (works[work].assigneeMode == "INDIVIDUAL_STUDENTS" && works[work].individualStudentsOptions.studentIds.indexOf(idStudent)!=-1))
{
var responseS = Classroom.Courses.CourseWork.StudentSubmissions.list(idCourse, idWork, optionalArgs2);
...
}

How to bind FloatRatingView rating to variable using RxSwift

I am attempting to integrate this library with my RxSwift project, https://github.com/glenyi/FloatRatingView
I am unable to get the updated rating.
Here is how I have created the FloatRatingView in the Controller,
let starRater : FloatRatingView = {
let floatRatingView = FloatRatingView()
floatRatingView.emptyImage = UIImage(named: "EmptyStar")
return floatRatingView
}()
The Model contains the following,
let my_rating = Variable<Float?>(nil)
What I want to be able to do is to update the value in the my_rating variable when a user changes the rating by tapping on a star. Here is what I've written for this,
_ = starRater.rx.rating
.asObservable()
.bindTo(viewModel.my_rating.rx_value)
But here is the error I'm receiving.
Value of type 'Reactive FloatRatingView' has no member 'rating'
Here is how I will retrieve the value from my_rating variable,
let stars = self.my_rating.value
Kindly help me out. Thanks.
You need to add a bindable sink for the property, it would be something like this:
extension Reactive where Base: FloatRatingView {
/// Bindable sink for `rating` property
public var progress: UIBindingObserver<Base, Float> {
return UIBindingObserver(UIElement: self.base) { floatRatingView, rating in
floatRatingView.rating = rating
}
}
}

(Windows Phone 10) Is possible to edit, add new contact programmatically in windows phone 10?

I want to implement function edit and add contact programatically in windows phone 10.
Is it possible? Has any sample about it ?
Here is a code snippet for creating the contact:
public async Task AddContact(String FirstName, String LastName)
{
var contact = new Windows.ApplicationModel.Contacts.Contact();
contact.FirstName = FirstName;
contact.LastName = LastName;
//Here you can set other properties...
//Get he contact store for the app (so no lists from outlook and other stuff will be in the returned lists..)
var contactstore = await Windows.ApplicationModel.Contacts.ContactManager.RequestStoreAsync(Windows.ApplicationModel.Contacts.ContactStoreAccessType.AppContactsReadWrite);
try
{
var contactLists = await contactstore.FindContactListsAsync();
Windows.ApplicationModel.Contacts.ContactList contactList;
//if there is no contact list we create one
if (contactLists.Count == 0)
{
contactList = await contactstore.CreateContactListAsync("MyList");
}
//otherwise if there is one then we reuse it
else
{
contactList = contactLists.FirstOrDefault();
}
await contactList.SaveContactAsync(contact);
}
catch
{
//Handle it properly...
}
}
And here is a short sample for changing an existing contact:
//you can obviusly couple the changes better then this... this is just to show the basics
public async Task ChangeContact(Windows.ApplicationModel.Contacts.Contact ContactToChange, String NewFirstName, String NewLastName)
{
var contactStore = await Windows.ApplicationModel.Contacts.ContactManager.RequestStoreAsync(Windows.ApplicationModel.Contacts.ContactStoreAccessType.AppContactsReadWrite);
var contactList = await contactStore.GetContactListAsync(ContactToChange.ContactListId);
var contact = await contactList.GetContactAsync(ContactToChange.Id);
contact.FirstName = NewFirstName;
contact.LastName = NewLastName;
await contactList.SaveContactAsync(contact);
}
And very important:
In the appxmanifest you have to add the contacts capability. Right click to it in the solution explorer and "View Code" and then under Capabilities put
<uap:Capability Name="contacts" />
There is no UI for this. See this.
Both samples are meant to be for starting point... obviously it's not production ready and you have to adapt it to your scenario.
Update
Since this came up in the comments I extend my answer a little bit.
Based on this (plus my own experimentation) the ContactListId for aggregated contacts is null (which makes sense if you think about it). Here is how to get the raw contact with ContactlLstId (code is based on the comment from the link)
public async Task IterateThroughContactsForContactListId()
{
ContactStore allAccessStore = await ContactManager.RequestStoreAsync(ContactStoreAccessType.AllContactsReadOnly);
var contacts = await allAccessStore.FindContactsAsync();
foreach (var contact in contacts)
{
//process aggregated contacts
if (contact.IsAggregate)
{
//here contact.ContactListId is "" (null....)
//in this case if you need the the ContactListId then you need to iterate through the raw contacts
var rawContacts = await allAccessStore.AggregateContactManager.FindRawContactsAsync(contact);
foreach (var rawContact in rawContacts)
{
//Here you should have ContactListId
Debug.WriteLine($"aggregated, name: {rawContact.DisplayName }, ContactListId: {rawContact.ContactListId}");
}
}
else //not aggregated contacts should work
{
Debug.WriteLine($"not aggregated, name: {contact.DisplayName }, ContactListId: {contact.ContactListId}");
}
}
}
And another important thing:
According to the documentation you won’t be able to change all the contacts which are created by other apps.
AllContactsReadWrite:
Read and write access to all app and system contacts. This value is
not available to all apps. Your developer account must be specially
provisioned by Microsoft in order to request this level of access.
In some cases, I get a System.UnauthorizedAccessException when SaveContactAsync(contact) is called. One example for this was when the contact was in the Skype Contact List.

Users restrictions for associated data in ASP Membership

I have a site I'm porting to MVC to clean up the code and simplify things. I use the asp membership and profile providers, but I'm wondering if I'm doing this correctly for my situtation. I'm pretty new to MVC, so I wan to get this right in the early stages.
Users are individuals and they are part of larger "institutions" that they either set up or pick at registration. In this case, the institution is a winery. I want the users to be able to view all wines from every winery, but only edit ones that belong to them.
What's the best way to do this? Right now I render the link to the edit field in my index view based on their instution ID and the producer ID. I feel like a data annotation might work better here, but I don't exactly how to implement that for a group of wines. Do I need multiple providers? I use roles to limit the editing, but right now an editor role could manually enter the path of another wine to edit it when that wine doesn't belong to them.
Any pointers here would be awesome. I know I can do it in the controller methods, but I'm looking for the 'right' way to do it. Thanks.
I'm running into the same issue at work right now, and the best proposed solution we have right now is implementing an "ownership" table. You won't be able to solve this using roles.
So basically you have an owner ID, owned object's ID, and the type of objects ID all held together. Lets take an edit request for example. We know that you can only edit the data person X owns, so we have a stored procedure that if a key combination exists in our ownership table where person.ID = owner ID, and item.ID = object ID, and item.TypeID = objectTypeID. If it exists, it goes along performing its edits, otherwise it returns an error.
You can use this scheme to return ownership lists, user validation, and a host of other issues you may come across. You probably won't need the ObjectTypeID if you only have one type's ownership being tracked. Hope this helps!
I figured this out by applying a custom AuthorizeAttribute to the edit, delete, and create actions.
Here is what I ended up doing:
public class ProducerEditAttribute : AuthorizeAttribute
{
private vfContext db = new vfContext();
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
bool bAdmin = filterContext.HttpContext.User.IsInRole("admin");
bool bProdEdit = filterContext.HttpContext.User.IsInRole("producereditor");
bool bProd = filterContext.HttpContext.User.IsInRole("producer");
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
if (bAdmin)
{
//authorized
}
if (bProdEdit || bProd)
{
//check for current wine belonging to the producer.
Producer currentProd = db.Producers.Find(Profile.GetProfile(filterContext.HttpContext.User.Identity.Name).InstitutionID);
Wine currentWine;
object WineID;
if (filterContext.RouteData.Values.TryGetValue("id", out WineID))
{
currentWine = db.Wines.Find(int.Parse(WineID.ToString()));
if (currentProd.Wines.Contains(currentWine) && bProdEdit)
{
//authorized
}
else if (bProd)
{
var result = new ViewResult();
result.ViewName = "Login.cshtml"; //this can be a property you don't have to hard code it
result.MasterName = "_Layout.cshtml"; //this can also be a property
result.ViewBag.Message = "You do not have permission for add/edit/delete funciontionality. Please request.";
filterContext.Result = result;
}
else
{
var result = new ViewResult();
result.ViewName = "Login.cshtml";
result.MasterName = "_Layout.cshtml";
filterContext.Result = result;
}
}
}
else
{
var result = new ViewResult();
result.ViewName = "Login.cshtml";
result.MasterName = "_Layout.cshtml";
}
}
}
}

Linq Query for Complex Object

Everyone - I have the following set of objects:
User { String:Name, List<Devices> }
Device {String:Name, DeviceVariationInfo }
DeviceVariationInfo { String:OS }
In the database those object are split into the following tables:
Users, Devices, DevieVariationsInfo, UserToDevices
I am trying to query the the list of devices along with their variation info for a certain user, and am using the following query, which always returns a list of 0 items in Devices. I am pretty sure I am doing something wrong here.. =)
private void GetUserDevices(ref User user)
{
User locUSer = user;
if (user != null)
{
var deviesQuery = from dts in _dataConext.DB_UserToDevices
where dts.UserId == locUSer.Id
join ds in _dataConext.DB_Devices on dts.DeviceID equals ds.Id
join dsv in _dataConext.DB_DeviceVariations on ds.Id equals dsv.DeviceId
select new Device
{
Version = ds.Version,
VariationInfo = new DeviceVariation
{
OSVersion = dsv.OS
},
Name = ds.FriendlyName,
Id = ds.Id
};
if (deviesQuery != null)
user.Devices = deviesQuery.ToList();
}
}
A couple of notes:
Is User a class? If so, why are you passing it into GetUserDevices by ref? Don't do that unless you want to change the meaning of that reference.
Also, why are you doing this? User locUSer = user;
Here's how I'd go about debugging your problem: remove parts of that query until you get data back. For example, remove the last join statement, rerun the query, and see where you're going wrong.

Resources