ContactsRequest.Insert(feedUri, newEntry) sometimes fails with System.Net.ProtocolViolationException

I have this piece of code for adding a contact in a test gmail account I created:

public class SomeClass { private const string ClientId = "someclientid" private const string CliendSecret = "muchsecretwow"; private const string ApplicationName = "such app"; private const string RedirectUri = "http://localhost"; private const string Scopes = "https://www.google.com/m8/feeds/"; private OAuth2Parameters _parameters; private string _accessToken, _refreshToken; public void GoogleApiCallAddContact() { GetOAuthParameters(); if (!GetTokensFromMemory()) throw new Exception("please create new authorization code"); _parameters.AccessToken = _accessToken; _parameters.RefreshToken = _refreshToken; var settings = new RequestSettings(ApplicationName, _parameters); var cr = new ContactsRequest(settings); var newEntry = new Contact { Name = new Name { FullName = "John Foo", GivenName = "John", FamilyName = "Foo", }, Content = "some info" }; newEntry.Emails.Add(new EMail { Primary = true, Rel = ContactsRelationships.IsOther, Address = "foo@somemailserver.com" }); var feedUri = new Uri("https://www.google.com/m8/feeds/contacts/default/full"); cr.Insert(feedUri, newEntry); } private void GetOAuthParameters() { _parameters = new OAuth2Parameters { ClientId = ClientId, ClientSecret = CliendSecret, RedirectUri = RedirectUri, Scope = Scopes, }; } private bool GetTokensFromMemory() { if (File.Exists("./tokens.txt")) { var lines = File.ReadLines("./tokens.txt").ToList(); _accessToken = lines[0]; _refreshToken = lines[1]; return true; } _accessToken = _refreshToken = null; return false; } }

Sometimes(and sometimes not,maybe depending on non-deterministic parameters) I get this exception:

System.Net.ProtocolViolationException : When performing a write operation with AllowWriteStreamBuffering set to false, you must either set ContentLength to a non-negative number or set SendChunked to true. at System.Net.HttpWebRequest.CheckProtocol(Boolean onRequestStream) at System.Net.HttpWebRequest.GetResponse() at Google.GData.Client.GDataRequest.Execute() at Google.GData.Client.GDataGAuthRequest.Execute(Int32 retryCounter) at Google.GData.Client.GOAuth2Request.Execute() at Google.GData.Client.Service.EntrySend(Uri feedUri, AtomBase baseEntry, GDataRequestType type, AsyncSendData data) at Google.GData.Client.Service.Insert(Uri feedUri, AtomEntry newEntry, AsyncSendData data) at Google.GData.Client.Service.Insert(Uri feedUri, TEntry entry) at Google.GData.Client.FeedRequest`1.Insert(Uri address, Y entry) at SomeDirectory.Tests.SomeClass.GoogleApiCallAddContact() in GmailApiLearningTests.cs: line 124

Which seems to be out of my code's scope, since it's deep within gdata's implementation. It's also strange that when I get this exception on adding a contact, an other test that uses a ContactRequest to get all contacts works just fine. Any insights on this?


<strong>Update:</strong> To anyone having the same issue do this:

try{ cr.Insert(feedUri,newEntry); } catch(System.Net.ProtocolViolationException) { cr.Insert(feedUri,newEntry); }

The problem is that the first insert fails(because of the invalid access token), the client lib calls OAuthUtil.RefreshAccessToken(parameters) but somehow fails to re-issue the insert with the new token or at least fail with a GDataRequestException->WebException for unauthorized. So by doing the above, you get your tokens refreshed and manually re-issue the insert call.


I had the same error and the problem was that the token had expired. You can confirm that using fiddler. I had a 401 error. Once I refreshed the token, everything worked fine. Hope that help.


  • How to reference to another object in Java?
  • Font awesome not loading when using Python simple http server
  • Add Organization info to Google Contacts API
  • serializing with gson and back does not work with generic types
  • Paypal reports email address already taken when trying to import test accounts into Paypal Developer
  • Google Contacts API get phone number (PHP)
  • mail server requires authentication when attempting to send to a non-local e-mail address when using
  • Why is it still possible to insert a foreign key that doesn't exist?
  • R - Change list of ggplot objects into a list of grobs that grid.arrange will accept?
  • Insert Statement
  • Cannot style mat-tab without ::ng-deep and !important
  • Jquery Show & ScrollTop (or ScrollTo)
  • How to add regEx in angular filter
  • AlertDialog style when using setView()
  • New Firebase failed: First argument must be a valid firebase URL and the path can't contain “.”
  • JSON encode and decode on PHP
  • Building Qt project for C++11 standard
  • Login not working in Firefox in Meteor
  • Adjust width of select element according to selected option's width
  • How do I access an unhandled exception in an MVC Error view?
  • Why querying a date BC is changed to AD in Java?
  • Email verification using google app script and google forms
  • Jquery UI tool tip close icon
  • Database structure design with variable amounts of fields
  • How to rebase a series of branches?
  • Email format validation in mvc3 view
  • DotNetZip - Calculate final zip size before calling Save(stream)
  • sending/ receiving email in Java
  • Warning: Can't call setState (or forceUpdate) on an unmounted component
  • Load html files in TinyMce
  • Free memory of cv::Mat loaded using FileStorage API
  • Angular 2 constructor injection vs direct access
  • Java static initializers and reflection
  • Android Google Maps API OnLocationChanged only called once
  • sending mail using smtp is too slow
  • Busy indicator not showing up in wpf window [duplicate]
  • Recursive/Hierarchical Query Using Postgres
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can I use `wmic` in a Windows PE script?
  • UserPrincipal.Current returns apppool on IIS