Upgrade Asp.Net Core 2.2 to 3.1 Failed to authenticate HTTPS connection - asp.net-core

I've upgraded solution from 2.2 to 3.1. It consists of several projects (APIs). They all use Kestrel and HTTPS.
After the upgrade I cannot call one service from another (by using HttpClient) and I cannot reroute them by using Ocelot, when i run things locally on localhost. In both cases I'm getting the same error:
Failed to authenticate HTTPS connection.
System.IO.IOException: Authentication failed because the remote party has closed the transport stream.
at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.ProcessAuthentication(LazyAsyncResult lazyResult, CancellationToken cancellationToken)
at System.Net.Security.SslStream.BeginAuthenticateAsServer(SslServerAuthenticationOptions sslServerAuthenticationOptions, CancellationToken cancellationToken, AsyncCallback asyncCallback, Object asyncState)
at System.Net.Security.SslStream.<>c.<AuthenticateAsServerAsync>b__69_0(SslServerAuthenticationOptions arg1, CancellationToken arg2, AsyncCallback callback, Object state)
at System.Threading.Tasks.TaskFactory`1.FromAsyncImpl[TArg1,TArg2](Func`5 beginMethod, Func`2 endFunction, Action`1 endAction, TArg1 arg1, TArg2 arg2, Object state, TaskCreationOptions creationOptions)
at System.Threading.Tasks.TaskFactory.FromAsync[TArg1,TArg2](Func`5 beginMethod, Action`1 endMethod, TArg1 arg1, TArg2 arg2, Object state, TaskCreationOptions creationOptions)
at System.Threading.Tasks.TaskFactory.FromAsync[TArg1,TArg2](Func`5 beginMethod, Action`1 endMethod, TArg1 arg1, TArg2 arg2, Object state)
at System.Net.Security.SslStream.AuthenticateAsServerAsync(SslServerAuthenticationOptions sslServerAuthenticationOptions, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Server.Kestrel.Https.Internal.HttpsConnectionMiddleware.InnerOnConnectionAsync(ConnectionContext context)
When I call each API from postman, it is working.
Furthermore when I set verything to HTTP I'm getting the same error.
Sample code(returns 403 Forbidden):
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://localhost:5004/version");
if (response.IsSuccessStatusCode)
{
serviceVersion = await response.Content.ReadAsStringAsync();
}

Related

Unable to read data from the transport connection: Operation canceled. Operation canceled

I am trying to read data from a cosmos collection using DocumentClient, while trying to read, sometimes I am getting the following error.
Code:
var Client = new DocumentClient(new Uri(accountUri), accountKey);
var collectionLink = UriFactory.CreateDocumentCollectionUri(database, collection);
var query = Client.CreateDocumentQuery<T1>(collectionLink, feedOptions);
var queryable = query.AsDocumentQuery();
var list = new List<T>();
while (queryable.HasMoreResults){
// note that ExecuteNextAsync can return many records in each call
var response = await queryable.ExecuteNextAsync<T>();
list.AddRange(response);
}
return list.FirstOrDefault();
Error:
Unable to read data from the transport connection: Operation canceled. Operation canceled
I tried few threads related to this error but that doesn't help.
Stack Trace:
Exception: at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at Microsoft.Azure.Documents.Client.DocumentClient.HttpRequestMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) at Microsoft.Azure.Documents.GatewayStoreModel.<>c__DisplayClass20_0.<<InvokeAsync>b__0>d.MoveNext() --- End of stack trace from previous location where exception was thrown ---
at Microsoft.Azure.Documents.BackoffRetryUtility`1.<>c__DisplayClass1_0.<<ExecuteAsync>b__0>d.MoveNext() --- End of stack trace from previous location where exception was thrown ---
at Microsoft.Azure.Documents.BackoffRetryUtility`1.ExecuteRetryAsync(Func`1 callbackMethod, Func`3 callShouldRetry, Func`1 inBackoffAlternateCallbackMethod, TimeSpan minBackoffForInBackoffCallback, CancellationToken cancellationToken, Action`1 preRetryCallback) at Microsoft.Azure.Documents.ShouldRetryResult.ThrowIfDoneTrying(ExceptionDispatchInfo capturedException)
at Microsoft.Azure.Documents.BackoffRetryUtility`1.ExecuteRetryAsync(Func`1 callbackMethod, Func`3 callShouldRetry, Func`1 inBackoffAlternateCallbackMethod, TimeSpan minBackoffForInBackoffCallback, CancellationToken cancellationToken, Action`1 preRetryCallback)
at Microsoft.Azure.Documents.BackoffRetryUtility`1.ExecuteAsync(Func`1 callbackMethod, IRetryPolicy retryPolicy, CancellationToken cancellationToken, Action`1 preRetryCallback) at Microsoft.Azure.Documents.GatewayStoreModel.InvokeAsync(DocumentServiceRequest request, ResourceType resourceType, CancellationToken cancellationToken)
at Microsoft.Azure.Documents.GatewayStoreModel.ProcessMessageAsync(DocumentServiceRequest request, CancellationToken cancellationToken)
at Microsoft.Azure.Documents.Client.DocumentClient.ExecuteQueryAsync(DocumentServiceRequest request, CancellationToken cancellationToken)
Note: The collection might be frequently and parallely accessed.
Please help me to resolve this error.
Thanks in Advance.

Services hosted using HttpSysCommunicationListener throwing error

I am getting, "Exception has been thrown by the target of an invocation" when trying to run Service created using Service Fabric template with ASP.NET core Stateless Service.
Below is complete stack trace, please let me know what I am doing wrong
Exception has been thrown by the target of an invocation.
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass22_0.<RealizeService>b__0(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureServer()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
at SLService.SLService.<>c__DisplayClass1_0.<CreateServiceInstanceListeners>b__1(String url, AspNetCoreCommunicationListener listener)
at Microsoft.ServiceFabric.Services.Communication.AspNetCore.AspNetCoreCommunicationListener.OpenAsync(CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Runtime.StatelessServiceInstanceAdapter.<OpenCommunicationListenersAsync>d__19.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at Microsoft.ServiceFabric.Services.Runtime.StatelessServiceInstanceAdapter.OpenCommunicationListenersAsync(CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Runtime.StatelessServiceInstanceAdapter.<System-Fabric-IStatelessServiceInstance-OpenAsync>d__13.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at Microsoft.ServiceFabric.Services.Runtime.StatelessServiceInstanceAdapter.System.Fabric.IStatelessServiceInstance.OpenAsync(IStatelessServicePartition partition, CancellationToken cancellationToken)
at System.Fabric.StatelessServiceBroker.OpenAsync(IFabricStatelessServicePartition partition, CancellationToken cancellationToken)
at System.Fabric.StatelessServiceBroker.<>c__DisplayClass10_0.<System.Fabric.Interop.NativeRuntime.IFabricStatelessServiceInstance.BeginOpen>b__0(CancellationToken cancellationToken)
at System.Fabric.Interop.Utility.WrapNativeAsyncMethodImplementation(Func`2 func, IFabricAsyncOperationCallback callback, String functionTag, InteropApi interopApi)
Please find exact trace captured,
System.Reflection.TargetInvocationException occurred
HResult=0x80131604
Message=Exception has been thrown by the target of an invocation.
Source=mscorlib
StackTrace:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass22_0.<RealizeService>b__0(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureServer()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
at SLService.SLService.<>c__DisplayClass1_0.<CreateServiceInstanceListeners>b__1(String url, AspNetCoreCommunicationListener listener) in C:\Users\asupadhy\source\repos\SLCore\SLService\SLService.cs:line 38
at Microsoft.ServiceFabric.Services.Communication.AspNetCore.AspNetCoreCommunicationListener.OpenAsync(CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Runtime.StatelessServiceInstanceAdapter.<OpenCommunicationListenersAsync>d__19.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at Microsoft.ServiceFabric.Services.Runtime.StatelessServiceInstanceAdapter.OpenCommunicationListenersAsync(CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Runtime.StatelessServiceInstanceAdapter.<System-Fabric-IStatelessServiceInstance-OpenAsync>d__13.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at Microsoft.ServiceFabric.Services.Runtime.StatelessServiceInstanceAdapter.System.Fabric.IStatelessServiceInstance.OpenAsync(IStatelessServicePartition partition, CancellationToken cancellationToken)
at System.Fabric.StatelessServiceBroker.OpenAsync(IFabricStatelessServicePartition partition, CancellationToken cancellationToken)
at System.Fabric.StatelessServiceBroker.<>c__DisplayClass10_0.<System.Fabric.Interop.NativeRuntime.IFabricStatelessServiceInstance.BeginOpen>b__0(CancellationToken cancellationToken)
at System.Fabric.Interop.Utility.WrapNativeAsyncMethodImplementation(Func`2 func, IFabricAsyncOperationCallback callback, String functionTag, InteropApi interopApi)
Inner Exception 1:
AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

RavenDB - EmbeddableDocumentStore already disposed or NRE

This question is about creating a single instance of the Raven document store in the lifetime of a ASP.Net MVC application and subsequently using a new IDocumentSession per request to serve the client with. I believe to have followed the recommended procedure described at http://ravendb.net/kb/3/using-ravendb-in-an-asp-net-mvc-website I'm still experiencing errors once the site is deployed.
My code looks as follows. The HepApp class contains the document store and is referenced by the application:
internal class HepApp
{
internal static readonly Object padlock = new object();
private static IDocumentStore _DB;
internal IDocumentStore DB
{
get
{
if (_DB == null)
{
lock (padlock)
{
if (_DB == null)
{
_DB = new EmbeddableDocumentStore().Initialize();
return _DB;
}
}
}
return _DB;
}
}
public IDocumentSession GetSession()
{
return DB.OpenSession();
}
}
My MVC Controller:
public class HomeController : Controller
{
IDocumentSession RavenSession;
public HomeController()
{
}
protected void Init()
{
RavenSession = MvcApplication.HepApp.GetSession();
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
Init();
}
The application class Global.asax binds to:
public class MvcApplication : System.Web.HttpApplication
{
static readonly Object padlock = new object();
static HepApp _HepApp;
internal static HepApp HepApp
{
get
{
if(_HepApp == null)
{
lock(padlock)
{
if(_HepApp == null)
{
_HepApp = new HepApp();
}
}
}
return _HepApp;
}
}
When the application starts the document store should be initialized and live for the remainder of the application's lifetime. For each request a new Session object is created. At least, that's the idea. Instead null reference errors occur in OnActionExecuting (though I suspect the HomeController.Init method but it doesn't appear on the stack) or the EmbeddableDocumentStore object is reported als already disposed. Confusingly, these errors only crop up after the application has been running for a while which might suggest it's an app pool recycle issue
EDIT:
The errors differ but all seem to indicate a problem with the instantiation of the database store :
[EsentFileAccessDeniedException: Cannot access file, the file is locked or in use]
[InvalidOperationException: Could not write to location: \192.168.0.100\localuser\x\App_Data/Raven. Make sure you have read/write permissions for this path.]
System.InvalidOperationException: Could not write to location: \192.168.0.100\localuser\x\App_Data/Raven. Make sure you have read/write permissions for this path. ---> Microsoft.Isam.Esent.Interop.EsentFileAccessDeniedException: Cannot access file, the file is locked or in use
at Microsoft.Isam.Esent.Interop.Api.Check(Int32 err)
at Microsoft.Isam.Esent.Interop.Api.JetInit(JET_INSTANCE& instance)
at Raven.Storage.Esent.TransactionalStorage.Initialize(IUuidGenerator uuidGenerator, OrderedPartCollection1 documentCodecs)
--- End of inner exception stack trace ---
at Raven.Storage.Esent.TransactionalStorage.Initialize(IUuidGenerator uuidGenerator, OrderedPartCollection1 documentCodecs)
at Raven.Database.DocumentDatabase..ctor(InMemoryRavenConfiguration configuration, TransportState transportState)
at Raven.Client.Embedded.EmbeddableDocumentStore.InitializeInternal()
at Raven.Client.Document.DocumentStore.Initialize()
at HEPlaceHolder.HepApp.get_DB() in e:\projects\HEPlaceHolder\HEPlaceHolder\Logic\HepApp.cs:line 27
at HEPlaceHolder.Controllers.HomeController.OnActionExecuting(ActionExecutingContext filterContext) in e:\projects\HEPlaceHolder\HEPlaceHolder\Controllers\HomeController.cs:line 31
at System.Web.Mvc.Controller.System.Web.Mvc.IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.InvokeActionMethodFilterAsynchronouslyRecursive(Int32 filterIndex)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass33.b__31(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeActionMethodWithFilters(ControllerContext controllerContext, IList1 filters, ActionDescriptor actionDescriptor, IDictionary2 parameters, AsyncCallback callback, Object state)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.b__19(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.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.b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state)
at System.Web.Mvc.Controller.b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.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.b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.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)
[ObjectDisposedException: The document store has already been disposed and cannot be used
Object name: 'EmbeddableDocumentStore'.]
Raven.Client.DocumentStoreBase.EnsureNotClosed() +82
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
[NullReferenceException: Object reference not set to an instance of an object.]
HEPlaceHolder.Controllers.HomeController.OnActionExecuting(ActionExecutingContext filterContext) in e:\projects\HEPlaceHolder\HEPlaceHolder\Controllers\HomeController.cs:31
System.Web.Mvc.Controller.System.Web.Mvc.IActionFilter.OnActionExecuting(ActionExecutingContext filterContext) +10
System.InvalidOperationException: Could not open transactional storage: \192.168.0.100\localuser\x\App_Data/Raven\Data ---> Microsoft.Isam.Esent.Interop.EsentTempPathInUseException: Temp path already used by another database instance
at Microsoft.Isam.Esent.Interop.Api.Check(Int32 err)
at Microsoft.Isam.Esent.Interop.Api.JetInit(JET_INSTANCE& instance)
at Raven.Storage.Esent.TransactionalStorage.Initialize(IUuidGenerator uuidGenerator, OrderedPartCollection1 documentCodecs)
--- End of inner exception stack trace ---
at Raven.Storage.Esent.TransactionalStorage.Initialize(IUuidGenerator uuidGenerator, OrderedPartCollection1 documentCodecs)
at Raven.Database.DocumentDatabase..ctor(InMemoryRavenConfiguration configuration, TransportState transportState)
at Raven.Client.Embedded.EmbeddableDocumentStore.InitializeInternal()
at Raven.Client.Document.DocumentStore.Initialize()
at HEPlaceHolder.HepApp.get_DB() in e:\projects\HEPlaceHolder\HEPlaceHolder\Logic\HepApp.cs:line 27
at HEPlaceHolder.Controllers.HomeController.OnActionExecuting(ActionExecutingContext filterContext) in e:\projects\HEPlaceHolder\HEPlaceHolder\Controllers\HomeController.cs:line 31
at System.Web.Mvc.Controller.System.Web.Mvc.IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.InvokeActionMethodFilterAsynchronouslyRecursive(Int32 filterIndex)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass33.b__31(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeActionMethodWithFilters(ControllerContext controllerContext, IList1 filters, ActionDescriptor actionDescriptor, IDictionary2 parameters, AsyncCallback callback, Object state)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.b__19(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.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.b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state)
at System.Web.Mvc.Controller.b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.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.b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.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)
EDIT:
Whenever the bin folder is updated with a tweaked version to debug the problem the site will initially run ok, presumably because the application is reset.

WCF-Exception while returning List<T>

in my following application, i generate a List of the class 'JobManager'.
List<JobManager>
The access to the database and filling my list is working perfect. It seems there is a problem for returning such list to my client.
In detail,my code looks like this
IService Class
OperationContract(Name = "ReadJobQueue")]
[FaultContract(typeof(FaultException))]
List<JobManager> AccessManager(List<string> status,string process, string dtFrom, string dtTo);
Service : IService
public List<JobManager> AccessManager(List<string> status, string process, string dtFrom, string dtTo)
{
//return 'new List<JobManager>()' does work, without any data being filled.
return new JobBuilder(status, process, dtFrom, dtTo);
}
[DataContract]
public class JobManager
{
List<JobManager> _jobManagerchildren = new List<JobManager>();
[DataMember(IsRequired = true, Order = 0)]
public string Description { get; set; }
[DataMember]
public List<JobManager> JobManagerChildren
{
get { return _jobManagerchildren; }
internal set { _jobManagerchildren = value; }
}
}
internal class JobBuilder : List<JobManager>
{
public JobBuilder(List<string> status, string process, string dtFrom, string dtTo)
: base()
{
DataTable dt = new Database().AccessJobQueue(status, process, dtFrom, dtTo);
foreach (DataRow row in dt.Rows)
{
Add(new JobManager { Description = row[1].ToString(), JobManagerChildren = JobDetail(row[0].ToString()) });
}
}
...
}
Have i missed something for my JobManager class?
edit error code / exception
System.Net.Sockets.SocketException:
An existing connection was been closed by the remotehost
bei System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size
, SocketFlags socketFlags)
bei System.ServiceModel.Channels.SocketConnection.ReadCore(Byte[] buffer, Int
32 offset, Int32 size, TimeSpan timeout, Boolean closing)
--- Ende der internen Ausnahmestapelüberwachung ---
bei System.ServiceModel.Channels.SocketConnection.ReadCore(Byte[] buffer, Int
32 offset, Int32 size, TimeSpan timeout, Boolean closing)
bei System.ServiceModel.Channels.SocketConnection.Read(Byte[] buffer, Int32 o
ffset, Int32 size, TimeSpan timeout)
bei System.ServiceModel.Channels.DelegatingConnection.Read(Byte[] buffer, Int
32 offset, Int32 size, TimeSpan timeout)
bei System.ServiceModel.Channels.ConnectionStream.Read(Byte[] buffer, Int32 o
ffset, Int32 count)
bei System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32
count)
bei System.Net.Security.NegotiateStream.StartFrameHeader(Byte[] buffer, Int32
offset, Int32 count, AsyncProtocolRequest asyncRequest)
bei System.Net.Security.NegotiateStream.ProcessRead(Byte[] buffer, Int32 offs
et, Int32 count, AsyncProtocolRequest asyncRequest)
--- Ende der internen Ausnahmestapelüberwachung ---
bei System.Net.Security.NegotiateStream.ProcessRead(Byte[] buffer, Int32 offs
et, Int32 count, AsyncProtocolRequest asyncRequest)
bei System.Net.Security.NegotiateStream.Read(Byte[] buffer, Int32 offset, Int
32 count)
bei System.ServiceModel.Channels.StreamConnection.Read(Byte[] buffer, Int32 o
ffset, Int32 size, TimeSpan timeout)
--- Ende der internen Ausnahmestapelüberwachung ---
Server stack trace:
bei System.ServiceModel.Channels.StreamConnection.Read(Byte[] buffer, Int32 o
ffset, Int32 size, TimeSpan timeout)
bei System.ServiceModel.Channels.SessionConnectionReader.Receive(TimeSpan tim
eout)
bei System.ServiceModel.Channels.SynchronizedMessageSource.Receive(TimeSpan t
imeout)
bei System.ServiceModel.Channels.FramingDuplexSessionChannel.Receive(TimeSpan
timeout)
bei System.ServiceModel.Channels.FramingDuplexSessionChannel.TryReceive(TimeS
pan timeout, Message& message)
bei System.ServiceModel.Dispatcher.DuplexChannelBinder.Request(Message messag
e, TimeSpan timeout)
bei System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean o
neway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan ti
meout)
bei System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCal
lMessage methodCall, ProxyOperationRuntime operation)
bei System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
bei System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage re
qMsg, IMessage retMsg)
bei System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgD
ata, Int32 type)
bei WcfSys.Shared.IService.AccessManager(List`1 status, String process, S
tring dtFrom, String dtTo)
bei WcfSys.Server.Program.Main() in WcfSys.Ser
ver\Program.cs:Zeile 66.
Actually, what you're sending back to the client is a List<JobManager>, but actually it's a derived class. So there are two ways of fixing this:
Copy all entries from JobBuilder to a new List<JobManager> and return that new list
Make JobBuilder a DataContract, too.
As - by OOP principles - it is know that the object you're returning is a JobBuilder, the runtime tries to serialize the JobBuilder instance. This, however, is not a know type for WCF communication.

Invalid value for key 'attachdbfilename' on WebSecurity.InitializeDatabaseConnection

I get this error message when trying to initialize my database connection using SimpleMembership. The first initialize statement goes through, while the second does not. The goal is to use connection strings defined in the Azure service configuration when running Azure emulator or when deployed.
Web.config:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-**********;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-**********.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
Azure .cscfg configuration files:
<Setting name="SqlConnectionString" value="Server=Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-********;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-********.mdf" />
SimpleMembershipInitializer:
string connectionStringName = "DefaultConnection";
string connectionString = CloudConfigurationManager.GetSetting("SqlConnectionString");
const string userTableName = "UserProfile";
const string providerName = "System.Data.SqlClient";
const string userIdColumn = "UserId";
const string userNameColumn = "UserName";
// This works fine.
// WebSecurity.InitializeDatabaseConnection(connectionStringName, userTableName, userIdColumn, userNameColumn, autoCreateTables: true);
// This throws exception.
// WebSecurity.InitializeDatabaseConnection(connectionString, providerName, userTableName, userIdColumn, userNameColumn, autoCreateTables: true);
Environment: Visual Studio 2012, EntityFramework 5.0 and MVC4 RTM with default SimpleMembership structure.
Full stacktrace:
[ArgumentException: Invalid value for key 'attachdbfilename'.]
System.Data.SqlClient.SqlConnectionString.VerifyLocalHostAndFixup(String& host, Boolean enforceLocalHost, Boolean fixup) +888986
System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) +5330002
System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) +24
System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) +167
System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key) +61
System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) +66
WebMatrix.Data.DbProviderFactoryWrapper.CreateConnection(String connectionString) +96
WebMatrix.Data.<>c__DisplayClass15.<OpenConnectionStringInternal>b__14() +16
WebMatrix.Data.Database.get_Connection() +19
WebMatrix.Data.Database.EnsureConnectionOpen() +12
WebMatrix.Data.<QueryInternal>d__0.MoveNext() +66
System.Linq.Enumerable.FirstOrDefault(IEnumerable`1 source) +164
WebMatrix.Data.Database.QuerySingle(String commandText, Object[] args) +103
WebMatrix.WebData.DatabaseWrapper.QuerySingle(String commandText, Object[] parameters) +14
WebMatrix.WebData.SimpleMembershipProvider.CheckTableExists(IDatabase db, String tableName) +57
WebMatrix.WebData.SimpleMembershipProvider.CreateTablesIfNeeded() +49
WebMatrix.WebData.WebSecurity.InitializeMembershipProvider(SimpleMembershipProvider simpleMembership, DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean createTables) +73
WebMatrix.WebData.WebSecurity.InitializeProviders(DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +51
WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection(String connectionString, String providerName, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +63
MyProject.Filters.SimpleMembershipInitializer..ctor() in c:\Repos\MyRepo\trunk\Web\MyProject\Filters\InitializeSimpleMembershipAttribute.cs:55
[InvalidOperationException: The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588]
MyProject.Filters.SimpleMembershipInitializer..ctor() in c:\Repos\MyRepo\trunk\Web\MyProject\Filters\InitializeSimpleMembershipAttribute.cs:59
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +113
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232
System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
System.Activator.CreateInstance(Type type) +6
System.Threading.LazyHelpers`1.ActivatorFactorySelector() +68
System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +115
System.Threading.LazyInitializer.EnsureInitialized(T& target, Boolean& initialized, Object& syncLock) +106
MyProject.Filters.InitializeSimpleMembershipAttribute.OnActionExecuting(ActionExecutingContext filterContext) in c:\Repos\MyRepo\trunk\Web\MyProject\Filters\InitializeSimpleMembershipAttribute.cs:23
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func`1 nextInChain) +69
System.Web.Mvc.Async.<>c__DisplayClass3b.<BeginInvokeActionMethodWithFilters>b__35() +21
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func`1 nextInChain) +489
System.Web.Mvc.Async.<>c__DisplayClass3b.<BeginInvokeActionMethodWithFilters>b__35() +21
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__31(AsyncCallback asyncCallback, Object asyncState) +191
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters, AsyncCallback callback, Object state) +197
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +446
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +302
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +30
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +382
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +317
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +15
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +71
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +249
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
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
It seems to me you might be suffering from the lack of double-escaping (do \\v11.0 instead of \v11.0), as discussed in this post.
I'm ashamed to realize I had a typo in my connection strings. I was getting connection strings from Azure Deployment configuration files, such as:
<Setting name="SqlConnectionString" value="Server=Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-********;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-********.mdf" />
The typo was included here, at the start of the value string. It must've been a copy'n'paste bug.
This string was duplicated in Azure configuration files Local.cscfg and Cloud.cscfg, for Azure emulator and Azure deployment respectively, as well as in web.config for running locally outside emulator. The typo was only in the Local.cscfg file, which made me very confused when trying to figure out why it did not work in certain scenarios. In addition the typo was for some reason very hard for me to spot. In hindsight I don't see how I didn't figure this out sooner.
I don't have a solution yet, but here is my own investigation and theory so far:
I took a look at the source code of WebSecurity.InitializeDatabaseConnection() and think maybe I have found a bug. It doesn't seem to ever set the DatabaseConnectionInfo.Type property, which defaults to ConnectionStringName, which could explain why it doesn't like my connection string, since it would interpret it as a connection string name instead.
WebSecurity class:
public static void InitializeDatabaseConnection(string connectionString, string providerName, string userTableName, string userIdColumn, string userNameColumn, bool autoCreateTables)
{
WebSecurity.InitializeProviders(new DatabaseConnectionInfo()
{
ConnectionString = connectionString,
ProviderName = providerName
}, userTableName, userIdColumn, userNameColumn, autoCreateTables);
}
DatabaseConnectionInfo class:
public Database Connect()
{
switch (this.Type)
{
case DatabaseConnectionInfo.ConnectionType.ConnectionStringName:
return Database.Open(this.ConnectionStringName);
case DatabaseConnectionInfo.ConnectionType.ConnectionString:
return Database.OpenConnectionString(this.ConnectionString, this.ProviderName);
default:
return (Database) null;
}
}
private enum ConnectionType
{
ConnectionStringName,
ConnectionString,
}