The code demo in this thread indeed works in my test when updating a datasource for a specific gateway. To have better troubleshooting, please add try..catch block to get the detailed error message for your code.
//your code here
catch (HttpOperationException ex)
var content = ex.Response.Content;
By the way, have you debugged the code and which code line raised the error?