SQL1159 Initialization error with DB2 .NET Data Provider, reason code 10, tokens 0.0.0, 10.5.4, Process Owner: IIS APPPOOL\webapi - asp.net

I am using IBM DB2 for LUW v10.5. webapi (ASP.NET application) is the name of the application hosted on IIS. Encountered below error when calling webapi methods.
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>The underlying provider failed on Open.</ExceptionMessage>
<ExceptionType>System.Data.EntityException</ExceptionType>
<StackTrace>
at System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) at System.Data.EntityClient.EntityConnection.Open() at System.Data.Objects.ObjectContext.EnsureConnection() at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() at WriteArrayOfPCMUSERToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , CollectionDataContract ) at System.Runtime.Serialization.CollectionDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, Boolean verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type declaredType) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType) at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.DataContractSerializer.WriteObject(XmlWriter writer, Object graph) at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content) at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Owin.HttpMessageHandlerAdapter.<BufferResponseContentAsync>d__27.MoveNext()
</StackTrace>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>
SQL1159 Initialization error with DB2 .NET Data Provider, reason code 10, tokens 0.0.0, 10.5.4, Process Owner: IIS APPPOOL\webapi
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
at IBM.Data.DB2.DB2ConnPool.Open(DB2Connection connection, String& szConnectionString, DB2ConnSettings& ppSettings, Object& ppConn) at IBM.Data.DB2.DB2Connection.Open() at System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure)
</StackTrace>
</InnerException>
</Error>

Detail explanation of SQL1159N can be found at below URL:
SQL1159N An error occurred during initialization of the IBM Data Server Provider for .NET. Reason Code: reason-code.
https://www.ibm.com/support/knowledgecenter/en/SSEPGG_11.5.0/com.ibm.db2.luw.messages.sql.doc/com.ibm.db2.luw.messages.sql.doc-gentopic5.html#sql1159n
Here is snip of Explanation:
You can access the IBM database system with the IBM Data Server Provider for .Net.
This message is returned when there is a problem with the database product installation. This message can also be returned when the Windows extended security feature is enabled and the ID that is used to start the Internet Information Systems (IIS) service does not belong to the DB2ADMNS group or to the DB2USERS group.
The reason code for this message is intended for IBM support personnel only.
Hope this helps.

Related

Unable to serialize the session state 'System.Web.SessionState.HttpSessionState'

Getting "Unable to serialize the session state" error, where I'm trying to store HttpSessionState object in Session. Below is my code which is causing issue. Since HttpSessionState is not serializable class and trying to put into session.
Public Shared Property CurrentSession As HttpSessionState
Get
Return TryCast(HttpContext.Current.Session("CurrentSessionObject"), HttpSessionState)
End Get
Set(value As HttpSessionState)
HttpContext.Current.Session("CurrentSessionObject") = value
End Set
End Property
Server Error in '/' Application.
Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SerializationException: Type 'System.Web.SessionState.HttpSessionState' in Assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is not marked as serializable.]
System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type) +12672675
System.Runtime.Serialization.<>c__DisplayClass9_0.b__0(MemberHolder _) +42
System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory) +73
System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context) +186
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo() +166
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder) +187
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder) +53
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck) +571
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck) +137
System.Web.Util.AltSerialization.WriteValueToStream(Object value, BinaryWriter writer) +1644
[HttpException (0x80004005): Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.]
System.Web.Util.AltSerialization.WriteValueToStream(Object value, BinaryWriter writer) +1733
System.Web.SessionState.SessionStateItemCollection.WriteValueToStreamWithAssert(Object value, BinaryWriter writer) +36
System.Web.SessionState.SessionStateItemCollection.Serialize(BinaryWriter writer) +652
System.Web.SessionState.SessionStateUtility.Serialize(SessionStateStoreData item, Stream stream) +246
System.Web.SessionState.SessionStateUtility.SerializeStoreData(SessionStateStoreData item, Int32 initialStreamSize, Byte[]& buf, Int32& length, Boolean compressionEnabled) +65
System.Web.SessionState.SqlSessionStateStore.SetAndReleaseItemExclusive(HttpContext context, String id, SessionStateStoreData item, Object lockId, Boolean newItem) +138
System.Web.SessionState.SessionStateModule.OnReleaseState(Object source, EventArgs eventArgs) +589
System.Web.SessionState.SessionStateModule.OnEndRequest(Object source, EventArgs eventArgs) +9947060
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +144
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +73
You need to mark the type/s your pushing in to SessionState as serializable, with the [Serializable] attribute.

CertificateUnknown error when connecting to Heroku Postgres database

So I am in the middle of migrating from SQL Server to PostgreSQL, and I am building a temporary solution for the migration period to allow my ASP.NET app to connect to my Heroku Postgres database and make use of Entity Framework etc.
So far I have managed to connect to the database from pgAdmin III for windows with no problems, but when connecting from ASP.NET app, I get this error:
CertificateUnknown: Server certificate was not accepted. Chain status: A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider.
. The specified hostname was not present in the certificate.
I am still fairly new to heroku, but it does not make sense why I can connect from pgAdmin with the same settings as my ASP.NET app but it doesn't work in the app itself.
Full stack trace:
[ClientAlertException: CertificateUnknown: Server certificate was not accepted. Chain status: A certificate chain processed, but
terminated in a root certificate which is not trusted by the trust
provider. . The specified hostname was not present in the
certificate.]
TlsClientStream.TlsClientStream.SendAlertFatal(AlertDescription
description, String message) +44
TlsClientStream.TlsClientStream.ParseCertificateMessage(Byte[] buf,
Int32& pos) +1359
TlsClientStream.TlsClientStream.TraverseHandshakeMessages() +415
TlsClientStream.TlsClientStream.GetInitialHandshakeMessages(Boolean
allowApplicationData) +336
TlsClientStream.TlsClientStream.PerformInitialHandshake(String
hostName, X509CertificateCollection clientCertificates,
RemoteCertificateValidationCallback
remoteCertificateValidationCallback, Boolean
checkCertificateRevocation) +198
[IOException: TlsClientStream.ClientAlertException:
CertificateUnknown: Server certificate was not accepted. Chain status:
A certificate chain processed, but terminated in a root certificate
which is not trusted by the trust provider. . The specified hostname
was not present in the certificate. at
TlsClientStream.TlsClientStream.SendAlertFatal(AlertDescription
description, String message) at
TlsClientStream.TlsClientStream.ParseCertificateMessage(Byte[] buf,
Int32& pos) at
TlsClientStream.TlsClientStream.TraverseHandshakeMessages() at
TlsClientStream.TlsClientStream.GetInitialHandshakeMessages(Boolean
allowApplicationData) at
TlsClientStream.TlsClientStream.PerformInitialHandshake(String
hostName, X509CertificateCollection clientCertificates,
RemoteCertificateValidationCallback
remoteCertificateValidationCallback, Boolean
checkCertificateRevocation)]
TlsClientStream.TlsClientStream.PerformInitialHandshake(String
hostName, X509CertificateCollection clientCertificates,
RemoteCertificateValidationCallback
remoteCertificateValidationCallback, Boolean
checkCertificateRevocation) +289
Npgsql.NpgsqlConnector.RawOpen(NpgsqlTimeout timeout) +1372
Npgsql.NpgsqlConnector.Open(NpgsqlTimeout timeout) +314
Npgsql.NpgsqlConnection.OpenInternal() +461
Npgsql.NpgsqlConnection.Open() +4
Npgsql.NpgsqlServices.UsingPostgresDBConnection(NpgsqlConnection
connection, Action`1 action) +162
Npgsql.NpgsqlServices.GetDbProviderManifestToken(DbConnection
connection) +99
System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection
connection) +87
[ProviderIncompatibleException: The provider did not return a
ProviderManifestToken string.]
System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection
connection) +271
System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices
providerServices, DbConnection connection) +27
[ProviderIncompatibleException: An error occurred accessing the
database. This usually means that the connection to the database
failed. Check that the connection string is correct and that the
appropriate DbContext constructor is being used to specify it or find
it in the application's config file. See
http://go.microsoft.com/fwlink/?LinkId=386386 for information on
DbContext and connections. See the inner exception for details of the
failure.]
System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices
providerServices, DbConnection connection) +89
System.Data.Entity.Infrastructure.<>c__DisplayClass1.b__0(Tuple3
k) +31
System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey
key, Func2 valueFactory) +62
System.Data.Entity.Infrastructure.DefaultManifestTokenResolver.ResolveManifestToken(DbConnection
connection) +251
System.Data.Entity.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection
connection, DbProviderManifest& providerManifest) +56
System.Data.Entity.DbModelBuilder.Build(DbConnection
providerConnection) +43
System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext
internalContext) +62
System.Data.Entity.Internal.RetryLazy2.GetValue(TInput input) +123
System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
+627 System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type
entityType) +18
System.Data.Entity.Internal.Linq.InternalSet1.Initialize() +53
System.Data.Entity.Internal.Linq.InternalSet1.get_InternalContext()
+15 System.Data.Entity.Infrastructure.DbQuery1.System.Linq.IQueryable.get_Provider()
+38 System.Linq.Queryable.Where(IQueryable1 source, Expression1 predicate) +83
Saleboat.Logic.MeetingLogic.CheckMeetingFilter.OnActionExecuting(ActionExecutingContext
filterContext) in C:\Users\Michael\Documents\Visual Studio
2013\Projects\Saleboat\project-saleboat\Saleboat\Logic\MeetingLogic\CheckMeetingFilter.cs:22
System.Web.Mvc.Async.AsyncInvocationWithFilters.InvokeActionMethodFilterAsynchronouslyRecursive(Int32
filterIndex) +176
System.Web.Mvc.Async.AsyncInvocationWithFilters.InvokeActionMethodFilterAsynchronouslyRecursive(Int32
filterIndex) +644
System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__31(AsyncCallback
asyncCallback, Object asyncState) +58
System.Web.Mvc.Async.WrappedAsyncResult1.CallBeginDelegate(AsyncCallback
callback, Object callbackState) +14
System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback
callback, Object state, Int32 timeout) +128
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeActionMethodWithFilters(ControllerContext
controllerContext, IList1 filters, ActionDescriptor actionDescriptor,
IDictionary2 parameters, AsyncCallback callback, Object state) +197
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__19(AsyncCallback
asyncCallback, Object asyncState) +743
System.Web.Mvc.Async.WrappedAsyncResult1.CallBeginDelegate(AsyncCallback
callback, Object callbackState) +14
System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback
callback, Object state, Int32 timeout) +128
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext
controllerContext, String actionName, AsyncCallback callback, Object
state) +343
System.Web.Mvc.Controller.<BeginExecuteCore>b__1c(AsyncCallback
asyncCallback, Object asyncState, ExecuteCoreState innerState) +25
System.Web.Mvc.Async.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback
callback, Object callbackState) +30
System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback
callback, Object state, Int32 timeout) +128
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback,
Object state) +465
System.Web.Mvc.Controller.<BeginExecute>b__14(AsyncCallback
asyncCallback, Object callbackState, Controller controller) +18
System.Web.Mvc.Async.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback
callback, Object callbackState) +20
System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback
callback, Object state, Int32 timeout) +128
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext,
AsyncCallback callback, Object state) +374
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext
requestContext, AsyncCallback callback, Object state) +16
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback
asyncCallback, Object asyncState, ProcessRequestState innerState) +52
System.Web.Mvc.Async.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback
callback, Object callbackState) +30
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback
callback, Object state, Int32 timeout) +128
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase
httpContext, AsyncCallback callback, Object state) +384
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext,
AsyncCallback callback, Object state) +48
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext
context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+103 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
With Npgsql 3.1.5 try to use "Trust Server Certificate=true" in connection string.
Example connection string:
Server=[servername];Port=[port];User Id=[username];Password=[password];Database=[databasename];sslmode=Require;Trust Server Certificate=true

Bonobo Can't Open Database File

I'm trying to install Bonobo on Windows 7/IIS 7/.Net 4.5 but I'm having trouble with SQLite. I get the following error when I load up the page in a browser
unable to open database file
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SQLite.SQLiteException: unable to open database file
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SQLiteException (0xe): unable to open database file]
System.Data.SQLite.SQLite3.Open(String strFilename, SQLiteConnectionFlags connectionFlags, SQLiteOpenFlagsEnum openFlags, Int32 maxPoolSize, Boolean usePool) +731
System.Data.SQLite.SQLiteConnection.Open() +445916
System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) +102
[EntityException: The underlying provider failed on Open.]
System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) +11430327
System.Data.EntityClient.EntityConnection.Open() +142
System.Data.Objects.ObjectContext.EnsureConnection() +97
System.Data.Objects.ObjectContext.ExecuteStoreCommand(String commandText, Object[] parameters) +53
Bonobo.Git.Server.Data.Update.AutomaticUpdater.UpdateDatabase() +444
Bonobo.Git.Server.MvcApplication.Application_Start() +145
[HttpException (0x80004005): The underlying provider failed on Open.]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +12962661
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +175
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +304
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +404
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +475
[HttpException (0x80004005): The underlying provider failed on Open.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +12979668
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +159
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +12819261
I have SQLite installed now (though, I don't think that matters... Bonobo comes with its own SQLite dlls. I AM running on a 64 bit system. I don't know if that has anything to do with compatability. I've followed the installation instructions on the Bonobo site to the tee, but I still get this error and Google hasn't provided any answers for me. Could anyone point me in the right direction?
You should try to set the right security options for your IIS.
From http://bonobogitserver.com/install/

Post error: Either BinaryRead, Form, Files, or InputStream was accessed before the internal storage

Any post in my Asp.net MVC generate this error:
Server Error in '/' Application.
Either BinaryRead, Form, Files, or InputStream was accessed before the internal storage was filled by the caller of HttpRequest.GetBufferedInputStream.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Either BinaryRead, Form, Files, or InputStream was accessed before the internal storage was filled by the caller of HttpRequest.GetBufferedInputStream.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidOperationException: Either BinaryRead, Form, Files, or InputStream was accessed before the internal storage was filled by the caller of HttpRequest.GetBufferedInputStream.] System.Web.HttpRequest.GetEntireRawContent() +12673515 System.Web.HttpRequest.get_InputStream() +61 System.Web.Mvc.JsonValueProviderFactory.GetValueProvider(ControllerContext controllerContext) +132 System.Web.Mvc.<>c__DisplayClassc.<GetValueProvider>b__7(ValueProviderFactory factory) +28 System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +248 System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +165 System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +536 System.Linq.Enumerable.ToList(IEnumerable`1 source) +80 System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext controllerContext) +343 System.Web.Mvc.ControllerBase.get_ValueProvider() +57 System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +81 System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +153 System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +839919 System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +146 System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +166 System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag) +27 System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +50 System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +146 System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +166 System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +827009 System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +146 System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +166 System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag) +27 System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +401 System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +787114 System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +146 System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +166 System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag) +27 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +343 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +12622419 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18213
Full error details:
System.InvalidOperationException
Either BinaryRead, Form, Files, or InputStream was accessed before the internal storage was filled by the caller of HttpRequest.GetBufferedInputStream.
System.InvalidOperationException: Either BinaryRead, Form, Files, or InputStream was accessed before the internal storage was filled by the caller of HttpRequest.GetBufferedInputStream.
at System.Web.HttpRequest.GetEntireRawContent()
at System.Web.HttpRequest.get_InputStream()
at System.Web.HttpRequestWrapper.get_InputStream()
at System.Web.Mvc.JsonValueProviderFactory.GetDeserializedObject(ControllerContext controllerContext)
at System.Web.Mvc.JsonValueProviderFactory.GetValueProvider(ControllerContext controllerContext)
at Castle.Proxies.Invocations.ValueProviderFactory_GetValueProvider.InvokeMethodOnTarget()
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Glimpse.Core.Extensibility.CastleInvocationToAlternateMethodContextAdapter.Proceed()
at Glimpse.Core.Extensions.AlternateMethodContextExtensions.TryProceedWithTimer(IAlternateMethodContext context, TimerResult& timerResult)
at Glimpse.Core.Extensibility.AlternateMethod.NewImplementation(IAlternateMethodContext context)
at Glimpse.Core.Extensibility.AlternateTypeToCastleInterceptorAdapter.Intercept(IInvocation invocation)
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.ValueProviderFactoryProxy.GetValueProvider(ControllerContext controllerContext)
at System.Web.Mvc.ValueProviderFactoryCollection.<>c__DisplayClassc.<GetValueProvider>b__7(ValueProviderFactory factory)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext controllerContext)
at System.Web.Mvc.ControllerBase.get_ValueProvider()
at System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)
at System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state)
at System.Web.Mvc.Controller.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Route config:
Default
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "home", action = "index", id = UrlParameter.Optional },
namespaces: new string[] { "CreditoImobiliarioBB.Web.Controllers" }
);
}
Areas
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Usuario_default"
,"usuario/{controller}/{action}/{id}"
,new { controller="home", action = "index", id = UrlParameter.Optional }
, namespaces: new string[] { "CreditoImobiliarioBB.Web.Areas.Usuario.Controllers" }
);
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
name: "Relatorios",
url: "{controller}/{id}/relatorio/{action}",
defaults: new { id = 1 },
constraints: new { id = #"^\d+$" },
namespaces: new string[] { "CreditoImobiliarioBB.Web.Areas.Relatorios" }
);
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
name: "Documentos",
url: "{controller}/{id}/documento/{action}",
defaults: null,
constraints: new { id = #"^\d+$" }
);
}
Just posting the findings here - as a summary of the chat - since others may get this error. Don't hand out bounty, since I didn't actually find the solution. ;-)
The error itself is a result of trying to access BinaryRead, Form, Files or InputStream after something else has already accessed the request entity body stream (in other words, the content of the request) using a different method.
These "different methods" seem to include GetBufferedInputStream and GetBufferlessInputStream. These methods appear (not sure) to all be mutually exclusive. In other words, for a single request, you can only use one of:
BinaryRead(), Form, Files, InputStream (these will "cooperate" with each other),
GetBufferedInputStream(), or
GetBufferlessInputStream()
GetBufferedInputStream should cooperate with the "classic" access methods, according to the documentation - in fact, that's its only difference from GetBufferlessInputStream. Nonetheless, in this case, the error stems from GetBufferedInputStream() being used, followed by InputStream.
The different methods are (inadequately) described in the documentation for the ReadEntityBodyMode property and its enum type.
A recent commit to the ASP.NET WebAPI changed its method of reading the body entity to GetBufferedInputStream() where before it used request.InputStream.
This appears to conflict with MVC's JsonValueProviderFactory.GetDeserializedObject which uses the "classic" InputStream property to read the entity body. If we take the error message at face value, GetBufferedInputStream() has already been called, but it isn't done reading when InputStream is accessed, so InputStream hasn't been filled yet.
Need to do more testing, but a temporary fix (found by #KiranChalla) is to revert to a build from before the above-mentioned commit.
We've reverted to using request.InputStream in Web API due to this problem (commit 9c76bb9090490541a453fcead75485ea50b88022).
JimmiTh's answer correctly notes a discrepancy between the initial release notes and the implementation. As implied in the later documentation mentioned above (though it is not particularly clear), request.GetBufferlessInputStream(), request.GetBufferedInputStream() and request.InputStream (along with Form, Files, etc.) are three mutually exclusive methods of request body access.
It appears that, contrary to the initial release notes, request.GetBufferedInputStream() is not currently usable unless no other callers for the same request use any of InputStream, Form, Files, etc. I'm also following up to see if something better can be done compatibility between these two methods.
David
An update after talking with the product team:
Calling request.GetBufferedInputStream() or request.GetBufferlessInputStream() means "I'm handling the stream explicitly myself; take me into advanced mode where automatic stream processing is disabled." However, in the case of buffered only, the members that normally rely on automatic stream processing (Form, Files, InputStream, etc.) are re-enabled after the buffered stream has been fully read.
So, as the exception message hints, touching any of those properties before finishing reading the stream will fail:
public ActionResult Index()
{
Request.GetBufferedInputStream();
var ignore = Request.InputStream;
return View();
}
But doing so after finishing reading the stream will succeed:
public ActionResult Index()
{
var stream = Request.GetBufferedInputStream();
new StreamReader(stream).ReadToEnd();
var ignore = Request.InputStream;
return View();
}
The documentation isn't particularly clear here; I'll ask the product team if they can improve it.
We're planning on switching back to GetBufferedInputStream in Web API; we'll just make sure it plays better with MVC in terms of when this call happens relative to consuming the stream and MVC executing.
I had the same issue when uploading files via Web API. Apparently "maximum request length exceeded" was hiding beneath this error, so increasing maxRequestLength in web.config solved it in my case.
Today I learned that if you are using WebApi and your stream is a System.Net.Http.StreamContent.ReadOnlyStream and you try and read 0 bytes from it (stream.Read(buffer, 0, 0)), it will throw a System.InvalidOperationException, which when caught in a try/catch will show up as an exception with the message "Either BinaryRead, Form, Files, or InputStream was accessed before the internal storage was filled by the caller of HttpRequest.GetBufferedInputStream."
I realize this seems silly, but you can do the same thing on a memory stream or file stream and no exception is thrown and in my case it was coming from MsgPackCli, hopefully this saves someone 4 hours.

Error Updating Dynamic Entity When Setting Property Value of Type PickList

I've added a custom attribute ("custom_contacttype") to the Contact entity. This attribute is of type picklist which is comprised of seven values. I'm developing using Advanced Developer Extensions for Microsoft Dynamics CRM against CRM 4.0. After I set the value for this attribute and call SaveChanges() I get "Object reference not set to an instance of an object." error. I've been battling this one for a while. What am I doing wrong? Below is my code:
var crm = new CrmDataContext(context.Connection);
var saveContact = crm.GetEntities("contact").Where(p => p.GetPropertyValue<Guid> ("contactid") == contact.Id.Value).Single();
saveContact.SetPropertyValue("custom_contacttype", 2, typeof(Picklist));
crm.UpdateObject(saveContact);
crm.SaveChanges();
Trace Log from CRM Server:
[2011-07-01 16:39:33.7] Process: w3wp |Organization:f827deb3-c6cc-df11-bc07-005056887b79 |Thread: 8 |Category: Platform.Sdk |User: 822138f1-c574-e011-9dca-005056887b79 |Level: Error | PluginStep.Execute
at PluginStep.Execute(PipelineExecutionContext context)
at Pipeline.Execute(PipelineExecutionContext context)
at MessageProcessor.Execute(PipelineExecutionContext context)
at InternalMessageDispatcher.Execute(PipelineExecutionContext context)
at ExternalMessageDispatcher.Execute(String messageName, Int32 primaryObjectTypeCode, Int32 secondaryObjectTypeCode, PropertyBag fields, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId)
at CrmServiceInternal.Update(String namespaceName, BusinessEntityBase entity, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId)
at CrmService.Update(BusinessEntity entity)
at RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at LogicalMethodInfo.Invoke(Object target, Object[] values)
at WebServiceHandler.Invoke()
at WebServiceHandler.CoreProcessRequest()
at SyncSessionlessHandler.ProcessRequest(HttpContext context)
at CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
at ApplicationStepManager.ResumeSteps(Exception error)
at HttpApplication.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
at HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr)
at HttpRuntime.ProcessRequestNoDemand(HttpWorkerRequest wr)
at ISAPIRuntime.ProcessRequest(IntPtr ecb, Int32 iWRType)
Web Service Plug-in failed in SdkMessageProcessingStepId: {27DF4121-19BC-DF11-A90E-005056887B79}; EntityName: contact; Stage: 10; MessageName: Update; AssemblyName: AccessCRM.ChangeLogContactData, AccessCRM, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a030c130976783ab; ClassName: AccessCRM.ChangeLogContactData; Exception: Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
at AccessCRM.PluginUtilities.GetStringValueFromProperty(Property p)
at AccessCRM.ChangeLogContactData.Execute(IPluginExecutionContext context)
at Microsoft.Crm.Extensibility.PluginStep.Execute(PipelineExecutionContext context)
.
[2011-07-01 16:39:33.7] Process: w3wp |Organization:f827deb3-c6cc-df11-bc07-005056887b79 |Thread: 8 |Category: Platform.Sdk |User: 822138f1-c574-e011-9dca-005056887b79 |Level: Error | PluginExecutionExceptionHandler.Handle
at PluginExecutionExceptionHandler.Handle(Stream from, Stream to, Exception exception)
at CompositeSoapExtensionExceptionHandler.Handle(Stream to, Stream from, Exception exception)
at CrmAuthenticationSoapExtensionBase.ProcessMessage(SoapMessage message)
at SoapMessage.RunExtensions(SoapExtension[] extensions, Boolean throwOnException)
at SoapServerProtocol.WriteException(Exception e, Stream outputStream)
at WebServiceHandler.WriteException(Exception e)
at WebServiceHandler.Invoke()
at WebServiceHandler.CoreProcessRequest()
at SyncSessionlessHandler.ProcessRequest(HttpContext context)
at CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
at ApplicationStepManager.ResumeSteps(Exception error)
at HttpApplication.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
at HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr)
at HttpRuntime.ProcessRequestNoDemand(HttpWorkerRequest wr)
at ISAPIRuntime.ProcessRequest(IntPtr ecb, Int32 iWRType)
CrmSoapExtension detected InvalidPluginExecutionException:
System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> Microsoft.Crm.Sdk.InvalidPluginExecutionException: Object reference not set to an instance of an object. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at AccessCRM.PluginUtilities.GetStringValueFromProperty(Property p)
at AccessCRM.ChangeLogContactData.Execute(IPluginExecutionContext context)
at Microsoft.Crm.Extensibility.PluginStep.Execute(PipelineExecutionContext context)
--- End of inner exception stack trace ---
at Microsoft.Crm.Extensibility.PluginStep.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.Pipeline.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.MessageProcessor.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.InternalMessageDispatcher.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.ExternalMessageDispatcher.Execute(String messageName, Int32 primaryObjectTypeCode, Int32 secondaryObjectTypeCode, PropertyBag fields, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId)
at Microsoft.Crm.Sdk.CrmServiceInternal.Update(String namespaceName, BusinessEntityBase entity, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId)
at Microsoft.Crm.Sdk.Crm2007.CrmService.Update(BusinessEntity entity)
--- End of inner exception stack trace ---
Looking at the stack trace, the error is actually being thrown in a plugin, not in the code you have pasted above. Look at this line in particular:
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
at AccessCRM.PluginUtilities.GetStringValueFromProperty(Property p)
at AccessCRM.ChangeLogContactData.Execute(IPluginExecutionContext context)
You'd need to post up the code for that plugin for us to have another look.
Alternatively use Remote Debugging to debug this yourself.

Resources