Tuesday, March 20, 2012

Operation is not valid due to the current state of the object


I was getting the above error because of this attribute in web.config
<pages maxPageStateFieldLength="20"

Which converts viewstate from this
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTQ2NDc1NTU1Mw8WAh4HX2xpbmVQSwIMFgICAw9kFgYCBw8UKwAFDxYEHg9EYXR .. . . . “ />

To this

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE0NzQ5NTI4" />
<input type="hidden" name="__VIEWSTATE1" id="__VIEWSTATE1" value="ODcPFgIeB19saW5lUEsC" />
<input type="hidden" name="__VIEWSTATE2" id="__VIEWSTATE2" value="DBYCAgMPZBYIAgMPPCsA" />
<input type="hidden" name="__VIEWSTATE3" id="__VIEWSTATE3" value="BAEADxYCHgVWYWx1ZQUM" />
<input type="hidden" name="__VIEWSTATE4" id="__VIEWSTATE4" value="VTFBID4gTGluZSAyZGQC" />
<input type="hidden" name="__VIEWSTATE5" id="__VIEWSTATE5" value="Bw8UKwAFDxYEHg9EYXRh" />
<input type="hidden" name="__VIEWSTATE6" id="__VIEWSTATE6" value="U291cmNlQm91bmRnHwEF" />
<input type="hidden" name="__VIEWSTATE7" id="__VIEWSTATE7" value="BjIxNDM5OGRkZDwrAAkB" />
<input type="hidden" name="__VIEWSTATE8" id="__VIEWSTATE8" value="CBQrAAQWBB4SRW5hYmxl" />
<input type="hidden" name="__VIEWSTATE9" id="__VIEWSTATE9" value="Q2FsbGJhY2tNb2RlZx4n" />
<input type="hidden" name="__VIEWSTATE10" id="__VIEWSTATE10" value="RW5hYmxlU3luY2hyb25p" />
<input type="hidden" name="__VIEWSTATE11" id="__VIEWSTATE11" value="emF0aW9uT25QZXJmb3Jt" />
<input type="hidden" name="__VIEWSTATE12" id="__VIEWSTATE12" value="Q2FsbGJhY2sgaGQPFgIe" />
….
Etc….

And in .NET4, there’s a maximum amount of input fields which can be present in a form (default = 1000).  If exceeded, the error in the subject occurs :’(

Tuesday, March 13, 2012

LINQ - Specified cast is not valid using SingleOrDefault

Was getting the below error when using SingleOrDefault

System.InvalidCastException: Specified cast is not valid

The problem was that I had changed the database schema but forgot to refresh the LinqToSql (DataContext) file