SSL connection to the postgresql ASP.NET - asp.net-mvc

I am trying to connect to a postgresql database through SSL. In the appsetting.json file, my connection string is
"DefaultConnection": "Sslmode=Require;Sslrootcert=rootCA.crt;Sslcert=postgres_client.crt;Sslkey=postgres_client.key;Server=xxx.xxx.xxx.xx;Database=my_database;Username=my_username"
When I run the api, I get the error message as followed
System.ArgumentException: Keyword not supported: sslrootcert (Parameter 'keyword')
at Npgsql.NpgsqlConnectionStringBuilder.GetProperty(String keyword)
at Npgsql.NpgsqlConnectionStringBuilder.set_Item(String keyword, Object value)
at System.Data.Common.DbConnectionStringBuilder.set_ConnectionString(String value)
at Npgsql.NpgsqlConnectionStringBuilder..ctor(String connectionString)
at Npgsql.NpgsqlConnection.GetPoolAndSettings()
at Npgsql.NpgsqlConnection.set_ConnectionString(String value)
at Npgsql.NpgsqlConnection..ctor(String connectionString)
at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlRelationalConnection.CreateDbConnection()
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.get_DbConnection()
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.CreateCommand(RelationalCommandParameterObject parameterObject, Guid commandId, DbCommandMethod commandMethod)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.InitializeReader(DbContext _, Boolean result)
at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)
By the way, I am able to connect to my database in the terminal with
psql "sslmode=verify-ca sslrootcert=/rootCA.crt sslcert=postgres_client.crt sslkey=postgres_client.key hostaddr=xxx.xxx.xxx.xx port=xxxx user=my_username dbname=my_database"
So, is my asp.net connection string wrong, or the rootCA.crtfile is not set properly? Thanks in advance for any advice:))

Related

Keyword not supported: 'port' - NpgSql

I have the following problem with the azure web app:
When publishing, the following error occurs:
Keyword not supported: 'port'.
at System.Data.SqlClient.SqlConnectionStringBuilder.GetIndex(String keyword)
at System.Data.SqlClient.SqlConnectionStringBuilder.set_Item(String keyword, Object value)
at System.Data.Common.DbConnectionStringBuilder.set_ConnectionString(String value)
at System.Data.SqlClient.SqlConnectionStringBuilder..ctor(String connectionString)
at Microsoft.Web.Deployment.ConnectionStringMatcher.RemoveExtraSlashFromDataSourceName(String connectionString)
at Microsoft.Web.Deployment.ConnectionStringMatcher.GetStandardConnectionString(String userConnectionString, Boolean isSqlCE)
at Microsoft.Web.Deployment.SqlInfo.GetBuilder(String connectionString, String errorMessageFormat)
appsettings.json:
"ConnectionStrings": {
"DefaultConnection": "Server=xxxxx;Database=xxxxx;Port=5432;User Id=test;Password=xxxxx;Ssl Mode=Require;",
"ProviderName": "Npgsql"
},
Startup.cs:
services.AddDbContext<Context>(options => options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));
Is your PostgreSQL server created in Azure?
According to the error message, the port parameter should not appear in the connection string.
If it is created in azure, your DefaultConnection should be like the following string.
Server=jasonp2testsql.postgres.database.azure.com;Database={your_database};Port=5432;User Id=jasonp2#jasonp2testsql;Password={your_password};Ssl Mode=Require;
You also can refer to this post.
C# SqlConnection Exception: Keyword not Supported 'Port'
And the offical document is useful to you.

Keyword not supported : 'host' error when migration ef on POSTGRESQL

Currently I am doing database migration using MVC6 on .netcore 2.0. here is the link that I am following, to migrate POSTGRESQL : https://damienbod.com/2016/01/11/asp-net-5-with-postgresql-and-entity-framework-7/
in my appsettings.json:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"DataAccessPostgreSqlProvider": "User ID=ids;Password=****;Host=127.0.0.1;Port=5432;Database=IDS;Pooling=true;"
}
}
I start migrate using the following command:
dotnet ef migrations add testPG
it is successful and no error at all but when I tried to run the following command on command prompt, the error is coming out.
dotnet ef database update
here is the error what I saw on cmd.
can somebody pls enlighten me to this?
Edited full stacktrace is here :
info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
User profile is available. Using 'C:\Users\Richard\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
System.ArgumentException: Keyword not supported: 'hostaddr'.
at System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary`2 parsetable, String connectionString, Boolean buildChain, Dictionary`2 synonyms)
at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary`2 synonyms)
at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous)
at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions)
at System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key)
at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
at System.Data.SqlClient.SqlConnection..ctor(String connectionString)
at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerConnection.CreateDbConnection()
at Microsoft.EntityFrameworkCore.Internal.LazyRef`1.get_Value()
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.get_DbConnection()
at Microsoft.EntityFrameworkCore.Internal.RelationalLoggerExtensions.MigrateUsingConnection(IDiagnosticsLogger`1 diagnostics, IMigrator migrator, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_1.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Keyword not supported: 'hostaddr'.
Thanks You
Frog
Make sure that the class which implements IDesignTimeDbContextFactory contains the correct DB definition for PostgreSQL. Pay attention to this line builder.UseNpgsql(connectionString); here:
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<DomainModelPostgreSqlContext>
{
public DomainModelPostgreSqlContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<DomainModelPostgreSqlContext>();
var connectionString = configuration.GetConnectionString("DataAccessPostgreSqlProvider");
builder.UseNpgsql(connectionString);
return new DomainModelPostgreSqlContext(builder.Options);
}
}
Are you sure ,you are not using SQL Server connection (using (IDbConnection pgcon = new SqlConnection(con))) instead of PostgresSQL connection( using (IDbConnection pgcon = new NpgsqlConnection(con)))in your code?It happened to me before.
I had this same issue. After searching all over with no luck, I figured it out. The keyword "host" is in your connection string. You should replace this with server.
For example:
Host=127.0.0.1 should be Server=127.0.0.1

Using Unity with Windows Azure: An attempt was made to access a socket in a way forbidden by its access permissions

I am currently developing an ASP.NET MVC application that uses Unity for the IoC container. The solution is deployed to Windows Azure using a SQL Azure backend and implments Azure Caching.
After deploying the app to Windows Azure everything seems to work fine. But then after a few requests I get the error "An attempt was made to access a socket in a way forbidden by its access permissions".
For example, if I browse to the site and repeatedly initiate an AJAX POST (e.g. autocomplete input) request it will work fine for the first few requests, but then crash out (by means of displaying a HTTP 500 error in the Chrome Dev Tools console). Then if I try and fresh the page I get the sockets error until the app is restart or the pool is recycled.
Even if I flick between pages I get the same error after a while, i.e. it's not just isolated to the AJAX request. The AJAX request is just the quickest way to replicate the issue.
I'm wondering if the error An error occurred when trying to create a controller of type 'MySite.Web.MVC.Controllers.LocationsController'. Make sure that the controller has a parameterless public constructor.] in the stack trace is a red herring because the ILocationCacheService mapping used by the controller is being resolved by Unity. The AJAX request works for the first few times so it definitely resolves the mapping.
Everything works fine locally, or at least I can't replicate the error.
Stack Trace
Server Error in '/' Application.
An attempt was made to access a socket in a way forbidden by its access permissions
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.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions
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:
[SocketException (0x271d): An attempt was made to access a socket in a way forbidden by its access permissions]
System.Net.Sockets.Socket.DoMultipleAddressConnectCallback(Object result, MultipleAddressConnectAsyncResult context) +1847654
System.Net.Sockets.Socket.DoDnsCallback(IAsyncResult result, MultipleAddressConnectAsyncResult context) +34
System.Net.Sockets.Socket.BeginConnect(String host, Int32 port, AsyncCallback requestCallback, Object state) +271
Microsoft.ApplicationServer.Caching.SocketConnectionFactory.BeginConnect(String host, Int32 port, AsyncCallback callback, Object state, TimeSpan timeout) +469
Microsoft.ApplicationServer.Caching.TcpClientChannelFactory.BeginConnect(String host, Int32 port, AsyncCallback callback, Object state) +119
Microsoft.ApplicationServer.Caching.TcpClientChannel.ConnectAsync() +368
Microsoft.ApplicationServer.Caching.SocketClientChannel.TryGetTcpChannelUntilTimeout(TcpClientChannel clientChannel, ITcpChannel& chnl) +41
Microsoft.ApplicationServer.Caching.SocketClientChannel.Send(EndpointID endpoint, IVelocityRequestPacket packet) +188
Microsoft.ApplicationServer.Caching.SocketClientChannel.Send(EndpointID endpoint, ICreateMessage message) +112
Microsoft.ApplicationServer.Caching.SimpleSendReceiveModule.Send(EndpointID endpoint, RequestBody request, Int32 retries) +73
Microsoft.ApplicationServer.Caching.SimpleSendReceiveModule.SendMsgAndWait(EndpointID endpt, RequestBody reqMsg, TimeSpan requestTimeout, IRequestTracker& tracker) +428
Microsoft.ApplicationServer.Caching.SocketClientProtocol.SendMessage(EndpointID endPt, RequestBody request) +52
Microsoft.ApplicationServer.Caching.DataCacheFactory.EstablishConnection(IEnumerable`1 servers, RequestBody request, Func`3 sendMessageDelegate, DataCacheReadyRetryPolicy retryPolicy) +253
Microsoft.ApplicationServer.Caching.<>c__DisplayClass5.<Initialize>b__2(RequestBody req) +83
Microsoft.ApplicationServer.Caching.SocketClientProtocol.SendReceive(IVelocityRequestPacket request, Func`2 delegate, EndpointID& destination) +34
Microsoft.ApplicationServer.Caching.SocketClientProtocol.Initialize(IEnumerable`1 servers) +367
Microsoft.ApplicationServer.Caching.DataCacheFactory.GetCache(String cacheName, CreateNewCacheDelegate cacheCreationDelegate, DataCacheInitializationViaCopyDelegate initializeDelegate) +400
Microsoft.ApplicationServer.Caching.DataCacheFactory.GetCache(String cacheName) +61
Microsoft.ApplicationServer.Caching.DataCacheFactory.GetDefaultCache() +11
MySite.Services.Cache.Implementations.LocationCacheService..ctor(ILocationService locationService) +64
lambda_method(Closure , IBuilderContext ) +176
Microsoft.Practices.ObjectBuilder2.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context) +35
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) +10
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +196
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +193
Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) +113
Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context) +48
lambda_method(Closure , IBuilderContext ) +107
Microsoft.Practices.ObjectBuilder2.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context) +35
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) +10
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +196
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +193
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides) +165
[ResolutionFailedException: Resolution of the dependency failed, type = "MySite.Web.MVC.Controllers.LocationsController", name = "(none)".
Exception occurred while: Calling constructor MySite.Services.Cache.Implementations.LocationCacheService(MySite.Services.Interfaces.ILocationService locationService).
Exception is: SocketException - An attempt was made to access a socket in a way forbidden by its access permissions
-----------------------------------------------
At the time of the exception, the container was:
Resolving MySite.Web.MVC.Controllers.LocationsController,(none)
Resolving parameter "locationCacheService" of constructor MySite.Web.MVC.Controllers.LocationsController(MySite.Services.Cache.Interfaces.ILocationCacheService locationCacheService)
Resolving MySite.Services.Cache.Implementations.LocationCacheService,(none) (mapped from MySite.Services.Cache.Interfaces.ILocationCacheService, (none))
Calling constructor MySite.Services.Cache.Implementations.LocationCacheService(MySite.Services.Interfaces.ILocationService locationService)
]
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides) +329
Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides) +15
Microsoft.Practices.Unity.UnityContainerExtensions.Resolve(IUnityContainer container, Type t, ResolverOverride[] overrides) +18
Unity.Mvc4.UnityDependencyResolver.GetService(Type serviceType) +67
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +41
[InvalidOperationException: An error occurred when trying to create a controller of type 'MySite.Web.MVC.Controllers.LocationsController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +178
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +77
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +66
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +191
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +50
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() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
I managed to resolve this issue using connection pooling for cache with maxconnectionstoserver="1". Here is the web.config setting for the datacacheclient section:
<dataCacheClient name="default" isCompressionEnabled="true" maxConnectionsToServer="1" connectionPool="true" useLegacyProtocol="false">

Error when serializing byte[]

In our backing database, we have a Data field that is of type varbinary(max). Using Breeze we are able to save data in this field, however, when we want to call it back down we are getting errors. In our generated models, the field gets mapped to a byte[]. But when Breeze tries to serialize that into a string it throws up errors.
$id: "1",
$type: "System.Web.Http.HttpError, System.Web.Http",
Message: "An error has occurred.",
ExceptionMessage: "The specified cast from a materialized 'System.String' type to the 'System.Byte[]' type is not valid.",
ExceptionType: "System.InvalidOperationException",
StackTrace: " at System.Data.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal) at System.Data.Common.Internal.Materialization.Shaper.GetColumnValueWithErrorHandling[TColumn](Int32 ordinal) at lambda_method(Closure , Shaper ) at System.Data.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper) at System.Data.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext() at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at Breeze.WebApi.ODataActionFilter.OnActionExecuted(HttpActionExecutedContext actionExecutedContext) at System.Web.Http.Filters.ActionFilterAttribute.CallOnActionExecuted(HttpActionContext actionContext, HttpResponseMessage response, Exception exception) at System.Web.Http.Filters.ActionFilterAttribute.<>c__DisplayClass2.<System.Web.Http.Filters.IActionFilter.ExecuteActionFilterAsync>b__0(HttpResponseMessage response) at System.Threading.Tasks.TaskHelpersExtensions.<>c__DisplayClass41`2.<Then>b__40(Task`1 t) at System.Threading.Tasks.TaskHelpersExtensions.ThenImpl[TTask,TOuterResult](TTask task, Func`2 continuation, CancellationToken cancellationToken, Boolean runSynchronously)"
Any help would be great!
I have been unable to reproduce this.
Breeze is able to take a server side byte[] and convert it to a string on the client. You can see an example of this in the breeze 'DocCode' samples whenever an Employee entity is returned. The Employee type has a Photo property that has a server side datatype of 'byte[]' which is returned to the breeze client as a 'string'.
What I think you are running into is a server side materialization issue where you are trying to materialize a binary blob on the database into a string property. This would occur if your model property was typed as a 'String' instead of as a 'byte[]'.
Hope this helps.

ASP.NET-MVC (IIS6) Error on high traffic: Specified cast is not valid

I just launched my tiny webapp on my humble dedicated server (Win2003)... running ASP.NET MVC, LINQ2SQL, SQL Express 2005, and IIS6 (setup with wildcard mapping)
The website runs smoothly 90% of the times. However, on relatively high traffic, LINQ2SQL throws the error:
Specified cast is not valid
This error is ONLY thrown at high traffic. I have NO IDEA how or exactly why this happens. Caching did not remove this problem entirely.
Anyone seen this problem before? are there any secret SQL Server tweaking I should've done?
Or at least, any ideas on how to diagnose this issue? because i'm out!
Naimi
Stacktrace (from Event Log):
at System.Data.SqlClient.SqlBuffer.get_SqlGuid()
at System.Data.SqlClient.SqlDataReader.GetGuid(Int32 i)
at Read_Friend(ObjectMaterializer`1 )
at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext()
at Dudlers.Web.Models.DudlersDataContext.GetFriendRequests(Guid userId) in C:\Web\Models\DudlersDataContext.cs:line 562
at Dudlers.Web.Controllers.BaseController.View(String viewName, String masterName, Object viewData) in C:\Web\Controllers\BaseController.cs:line 39
at System.Web.Mvc.Controller.View(String viewName)
at Dudlers.Web.Controllers.CatController.Index() in C:\Web\Controllers\CatController.cs:line 25
at lambda_method(ExecutionScope , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(MethodInfo methodInfo, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.c__DisplayClassb.b__8()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.c__DisplayClassb.c__DisplayClassd.b__a()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(MethodInfo methodInfo, IDictionary`2 parameters, IList`1 filters)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext)
at System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext)
at System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext)
at System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext)
at System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
We had a similar problem with LINQ that we get "Unable to cast object of type 'System.Int32' to type 'System.String'" and "Specified cast is not valid."
Examples of stacktraces
System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'.
at System.Data.SqlClient.SqlBuffer.get_String()
at System.Data.SqlClient.SqlDataReader.GetString(Int32 i)
at Read_Person(ObjectMaterializer`1 )
at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at RF.Ias.Services.Person.BusinessLogic.PersonTransactionScripts.GetPersons(IEnumerable`1 personIds, Boolean includeAddress, Boolean includeContact)
at CompositionAopProxy_5b0727341ad64f29b816c1b73d11dd44.GetPersons(IEnumerable`1 personIds, Boolean includeAddress, Boolean includeContact)
at RF.Ias.Services.Person.ServiceImplementation.PersonService.GetPersons(GetPersonRequest request)
System.InvalidCastException: Specified cast is not valid.
at System.Data.SqlClient.SqlBuffer.get_Int32()
at System.Data.SqlClient.SqlDataReader.GetInt32(Int32 i)
at Read_GetRolesForOrganisationResult(ObjectMaterializer`1 )
at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at RF.Ias.Services.Role.DataAccess.RoleDataAccess.GetRolesForOrganisation(GetRolesForOrganisationCriteria criteria, Int32 pageIndex, Int32 pageSize, Int32& recordCount)
at RF.Ias.Services.Role.BusinessLogic.RoleTransactionScripts.GetRolesForOrganisation(GetRolesForOrganisationCriteria criteria, Int32 pageIndex, Int32 pageSize, Int32& recordCount)
at CompositionAopProxy_4bd29c6074f54d10a2c09bd4ab27ca66.GetRolesForOrganisation(GetRolesForOrganisationCriteria criteria, Int32 pageIndex, Int32 pageSize, Int32& recordCount)
at RF.Ias.Services.Role.ServiceImplementation.RoleService.GetRolesForOrganisation(GetRolesForOrganisationRequest request)
We used to get these exceptions if we first got a exception like this "System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first." or " A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.)".
The first exception occur for a different instance of the DataCOntext then for all those that then are following.
After some research and asking in this thread , I found that the reason was that I did not dispose the DataContexts. After I started to do that, it dissappered.
Sounds like maybe a race condition, or perhaps a rare bug that is only correlated with high traffic because that when most of your requests occur.

Resources