User is logged out when loading X509Certificate2 - cryptography

In my Cart Controller, I force the user to login by using the [Authorize] attribute on my controller class
[Authorize]
public class CartController : Controller
They login no problem. They traverse through a few pages within the CartController and then get to the Payment webpage which is supposed to show a PayPal button. The PayPal button is an HTML form where the contents are encrypted by a Recipient's Public Certificate (PEM format) and I load the PKCS12 certificate, which contains the public certificate and private key of the signer. This works perfectly on my localhost dev machine.
/// <summary>
/// Path to the recipient's public certificate in PEM format
/// </summary>
public string RecipientPublicCertPath
{
get { return _recipientPublicCertPath; }
set
{
_recipientPublicCertPath = value;
_recipientCert = new X509.X509Certificate2(_recipientPublicCertPath);
}
}
/// <summary>
/// Loads the PKCS12 file which contains the public certificate
/// and private key of the signer
/// </summary>
/// <param name="signerPfxCertPath">
/// File path to the signer's public certificate plus private key
/// in PKCS#12 format</param>
/// <param name="signerPfxCertPassword">
/// Password for signer's private key</param>
public void LoadSignerCredential(string signerPfxCertPath, string signerPfxCertPassword)
{
_signerCert = new X509.X509Certificate2(signerPfxCertPath, signerPfxCertPassword);
}
The PROBLEM:
When I put this up on my webhost (Arvixe), and try to do exactly the same as above, when I get to the Payment Page (generating the PayPal button), it churns away for a long time. After about 40 seconds, I am redirected to my website's login page. When I call the functions above, it seems that I get logged out (for no reason) with a redirect url http://www.mysite.com/Account/Login?ReturnUrl=%2fCart%2fPayment which then gives me this stack trace error:
The anti-forgery cookie token and form field token do not match.
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.Mvc.HttpAntiForgeryException: The anti-forgery cookie token and form field token do not match.
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:
[HttpAntiForgeryException (0x80004005): The anti-forgery cookie token and form field token do not match.]
System.Web.Helpers.AntiXsrf.TokenValidator.ValidateTokens(HttpContextBase httpContext, IIdentity identity, AntiForgeryToken sessionToken, AntiForgeryToken fieldToken) +235426
System.Web.Helpers.AntiXsrf.AntiForgeryWorker.Validate(HttpContextBase httpContext) +71
System.Web.Helpers.AntiForgery.Validate() +80
System.Web.Mvc.ValidateAntiForgeryTokenAttribute.OnAuthorization(AuthorizationContext filterContext) +22
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor) +96
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
So I removed the attribute tag [Authorize] from my CartController to see what would happen. I navigate to the webpage within the CartController that will generate the PayPal button. After about 5 seconds I get the following stack trace. Then if I navigate to another section of my website that requires authorization, it forces me to login. This function is logging me out or losing my session when it shouldn't be. Do you know why when I call the above functions it causes this strange behavior? Do you know a fix?
NOTES:
ASP.NET MVC 4.5 C#
Visual Studio 2012
List item
Using Microsoft's builtin logging in platform on
my SQL Server 2012 database.
On my webhost, I can publicly access the PEM and PKCS#12 file no
problem. So it doesn't seem to be a permissions issue.
For the Certificate functions above, I use
- System.Security.Cryptography.Pkcs;
- System.Security.Cryptography.X509Certificates;
Here is the Stack Trace:
Server Error in '/' Application.
Object reference not set to an instance of an object.
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.NullReferenceException: Object reference not set to an instance of an object.
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:
[NullReferenceException: Object reference not set to an instance of an object.]
SwiftMobile_Mexico.Controllers.CartController.Payment() +56
lambda_method(Closure , ControllerBase , Object[] ) +62
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +211
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +28
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +57
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +223
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +24
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9628700
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18045
My Webconfig file:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<sectionGroup name="elmah">
<section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah" />
<section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" />
<section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah" />
<section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah" />
</sectionGroup>
<sectionGroup name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth.Core">
<section name="messaging" type="DotNetOpenAuth.Configuration.MessagingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
<section name="reporting" type="DotNetOpenAuth.Configuration.ReportingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
<section name="openid" type="DotNetOpenAuth.Configuration.OpenIdElement, DotNetOpenAuth.OpenId" requirePermission="false" allowLocation="true" />
<section name="oauth" type="DotNetOpenAuth.Configuration.OAuthElement, DotNetOpenAuth.OAuth" requirePermission="false" allowLocation="true" />
</sectionGroup>
</configSections>
<connectionStrings>
--connection strings here
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="elmah.mvc.disableHandler" value="false" />
<add key="elmah.mvc.disableHandleErrorFilter" value="false" />
<add key="elmah.mvc.requiresAuthentication" value="false" />
<add key="elmah.mvc.allowedRoles" value="*" />
<add key="elmah.mvc.route" value="elmah" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<customErrors mode="Off"></customErrors>
<httpRuntime targetFramework="4.5" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
<httpModules>
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
<add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
<add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
</httpModules>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<modules runAllManagedModulesForAllRequests="true">
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" />
<add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" />
<add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler" />
</modules>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="DotNetOpenAuth.AspNet" publicKeyToken="2780ccd10d57b246" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780ccd10d57b246" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0" />
</dependentAssembly>
</assemblyBinding>
<legacyHMACWarning enabled="0" />
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<!--<elmah></elmah>-->
<elmah>
<security allowRemoteAccess="0" />
<errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="SqlServices" />
<errorFilter>
<test>
<equal binding="HttpStatusCode" value="404" type="Int32" />
</test>
</errorFilter>
</elmah>
<system.net>
<defaultProxy enabled="true" />
<settings>
<!-- This setting causes .NET to check certificate revocation lists (CRL)
before trusting HTTPS certificates. But this setting tends to not
be allowed in shared hosting environments. -->
<!--<servicePointManager checkCertificateRevocationList="true"/>-->
</settings>
</system.net>
<dotNetOpenAuth>
<messaging>
<untrustedWebRequest>
<whitelistHosts>
<!-- Uncomment to enable communication with localhost (should generally not activate in production!) -->
<!--<add name="localhost" />-->
</whitelistHosts>
</untrustedWebRequest>
</messaging>
<!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. -->
<reporting enabled="true" />
<openid>
<relyingParty>
<security requireSsl="false">
<!-- Uncomment the trustedProviders tag if your relying party should only accept positive assertions from a closed set of OpenID Providers. -->
<!--<trustedProviders rejectAssertionsFromUntrustedProviders="true">
<add endpoint="https://www.google.com/accounts/o8/ud" />
</trustedProviders>-->
</security>
<behaviors>
<!-- The following OPTIONAL behavior allows RPs to use SREG only, but be compatible
with OPs that use Attribute Exchange (in various formats). -->
<add type="DotNetOpenAuth.OpenId.RelyingParty.Behaviors.AXFetchAsSregTransform, DotNetOpenAuth.OpenId.RelyingParty" />
</behaviors>
</relyingParty>
</openid>
</dotNetOpenAuth>
<!--<uri>
-->
<!-- The uri section is necessary to turn on .NET 3.5 support for IDN (international domain names),
which is necessary for OpenID urls with unicode characters in the domain/host name.
It is also required to put the Uri class into RFC 3986 escaping mode, which OpenID and OAuth require. -->
<!--
<idn enabled="All" />
<iriParsing enabled="true" />
</uri>-->
</configuration>

I found the problem: I should have added in the MachineKeySet parameter in.
_signerCert = new X509.X509Certificate2(signerPfxCertPath, signerPfxCertPassword, X509KeyStorageFlags.MachineKeySet);
Please see this post for details: "An internal error occurred." when loading pfx file with X509Certificate2

Related

WCF Receive error

I have created a wcf service which successfully receives from EF mapped to database but on read in other application it throws error:
Below is the stack trace
<E2ETraceEvent xmlns="http://schemas.microsoft.com/2004/06/E2ETraceEvent"><System xmlns="http://schemas.microsoft.com/2004/06/windows/eventlog/system"><EventID>131075</EventID><Type>3</Type><SubType Name="Error">0</SubType><Level>2</Level><TimeCreated SystemTime="2015-11-01T11:40:38.7842236Z" /><Source Name="System.ServiceModel" /><Correlation ActivityID="{00000000-0000-0000-6c00-0080000000ed}" /><Execution ProcessName="iisexpress" ProcessID="7572" ThreadID="10" /><Channel/><Computer>NKMPC</Computer></System><ApplicationData><TraceData><DataItem><TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Error"><TraceIdentifier>http://msdn.microsoft.com/en-US/library/System.ServiceModel.Diagnostics.ThrowingException.aspx</TraceIdentifier><Description>Throwing an exception.</Description><AppDomain>/LM/W3SVC/5/ROOT-1-130908516275895175</AppDomain><Exception><ExceptionType>System.ServiceModel.CommunicationException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType><Message>An error occurred while receiving the HTTP response to http://localhost:1948/ServiceFamilyMember.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.</Message><StackTrace> at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&amp; msgData, Int32 type)
at MittalFamilyV1._0.WCFServRefFM.IServiceFamilyMember.GetMemberById(Int32 Id)
at MittalFamilyV1._0.WCFServRefFM.ServiceFamilyMemberClient.GetMemberById(Int32 Id)
at MittalFamilyV1._0.Controllers.SelfController.Index()
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.&lt;&gt;c__DisplayClass42.&lt;BeginInvokeSynchronousActionMethod&gt;b__41()
at System.Web.Mvc.Async.AsyncResultWrapper.&lt;&gt;c__DisplayClass8`1.&lt;BeginSynchronous&gt;b__7(IAsyncResult _)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.&lt;&gt;c__DisplayClass37.&lt;&gt;c__DisplayClass39.&lt;BeginInvokeActionMethodWithFilters&gt;b__33()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.&lt;&gt;c__DisplayClass4f.&lt;InvokeActionMethodFilterAsynchronously&gt;b__49()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.&lt;&gt;c__DisplayClass37.&lt;BeginInvokeActionMethodWithFilters&gt;b__36(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.&lt;&gt;c__DisplayClass25.&lt;&gt;c__DisplayClass2a.&lt;BeginInvokeAction&gt;b__20()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.&lt;&gt;c__DisplayClass25.&lt;BeginInvokeAction&gt;b__22(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.&lt;&gt;c__DisplayClass1d.&lt;BeginExecuteCore&gt;b__18(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.&lt;&gt;c__DisplayClass4.&lt;MakeVoidDelegate&gt;b__3(IAsyncResult ar)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.&lt;&gt;c__DisplayClass4.&lt;MakeVoidDelegate&gt;b__3(IAsyncResult ar)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.&lt;&gt;c__DisplayClass8.&lt;BeginProcessRequest&gt;b__3(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.&lt;&gt;c__DisplayClass4.&lt;MakeVoidDelegate&gt;b__3(IAsyncResult ar)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously)
at System.Web.HttpApplication.PipelineStepManager.ResumeSteps(Exception error)
at System.Web.HttpApplication.BeginProcessRequestNotification(HttpContext context, AsyncCallback cb)
at System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context)
at System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(IntPtr rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)
at System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(IntPtr rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)
at System.Web.Hosting.UnsafeIISMethods.MgdIndicateCompletion(IntPtr pHandler, RequestNotificationStatus&amp; notificationStatus)
at System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(IntPtr rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)
at System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(IntPtr rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)
</StackTrace><ExceptionString>System.ServiceModel.CommunicationException: An error occurred while receiving the HTTP response to http://localhost:1948/ServiceFamilyMember.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details. ---&gt; System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. ---&gt; System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---&gt; System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
--- End of inner exception stack trace ---</ExceptionString><InnerException><ExceptionType>System.Net.WebException, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType><Message>The underlying connection was closed: An unexpected error occurred on a receive.</Message><StackTrace> at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)</StackTrace><ExceptionString>System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. ---&gt; System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---&gt; System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)</ExceptionString><InnerException><ExceptionType>System.IO.IOException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType><Message>Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.</Message><StackTrace> at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)</StackTrace><ExceptionString>System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---&gt; System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)</ExceptionString><InnerException><ExceptionType>System.Net.Sockets.SocketException, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType><Message>An existing connection was forcibly closed by the remote host</Message><StackTrace> at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)</StackTrace><ExceptionString>System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)</ExceptionString><NativeErrorCode>2746</NativeErrorCode></InnerException></InnerException></InnerException></Exception></TraceRecord></DataItem></TraceData></ApplicationData></E2ETraceEvent>
My web config is:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<sectionGroup name="devExpress">
<section name="themes" type="DevExpress.Web.ASPxClasses.ThemesConfigurationSection, DevExpress.Web.v13.1, Version=13.1.5.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" requirePermission="false" />
<section name="compression" type="DevExpress.Web.ASPxClasses.CompressionConfigurationSection, DevExpress.Web.v13.1, Version=13.1.5.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" requirePermission="false" />
<section name="settings" type="DevExpress.Web.ASPxClasses.SettingsConfigurationSection, DevExpress.Web.v13.1, Version=13.1.5.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" requirePermission="false" />
<section name="errors" type="DevExpress.Web.ASPxClasses.ErrorsConfigurationSection, DevExpress.Web.v13.1, Version=13.1.5.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" requirePermission="false" />
</sectionGroup>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
</connectionStrings>
<!--<configSections>
-->
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<!--
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>-->
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<httpRuntime targetFramework="4.5" />
<compilation debug="true" targetFramework="4.5">
<assemblies>
</assemblies>
</compilation>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
<httpHandlers>
</httpHandlers>
<httpModules>
</httpModules>
<globalization culture="" uiCulture="" />
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
<!--<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>-->
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="3.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IServiceFamilyMember" receiveTimeout="01:10:00" openTimeout="01:10:00"
closeTimeout="01:10:00"
sendTimeout="01:10:00" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:1948/ServiceFamilyMember.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IServiceFamilyMember" contract="WCFServRefFM.IServiceFamilyMember" name="BasicHttpBinding_IServiceFamilyMember" />
</client>
</system.serviceModel>
<system.diagnostics>
<trace autoflush="true" />
<sources>
<source name="System.ServiceModel"
switchValue="Error"
propagateActivity="true">
<listeners>
<add name="sdt"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData= "SdrConfigExample.e2e" />
</listeners>
</source>
</sources>
</system.diagnostics>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SqlServerCe.4.0" />
<add name="Microsoft SQL Server Compact Data Provider 4.0" invariant="System.Data.SqlServerCe.4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</DbProviderFactories>
</system.data>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
<parameters>
<parameter value="System.Data.SqlServerCe.4.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlServerCe.4.0" type="System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact" />
</providers>
</entityFramework>
</configuration>
My read code in controller is
IEnumerable
<MittalFamilyV1._0.WCFServRefFM.FamilyMember> werr;
werr =s.GetMemberById(1).ToList<MittalFamilyV1._0.WCFServRefFM.FamilyMember>();
Please help
Regards
Nikhil Mittal
The error was due to lazy losing in poco classes which was called after wcf service closed.
Removing virtual keyword resolved the issue

Azure In Role Caching Doesn't start on server with "Not running in a hosted service or the Development Fabric."

I started to use Azure in-role caching and everything works great in Azure compute emulator on my local machine, but not on server. I've already dealed with some problems, like lack of msshrtmi.dll on server, but now can't understand why get this error:
Not running in a hosted service or the Development Fabric.
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: Not running in a hosted service or the Development Fabric.
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: Not running in a hosted service or the Development Fabric.]
Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitor.GetDefaultStartupInfoForCurrentRoleInstance() +535
Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener..ctor() +34
[ConfigurationErrorsException: Could not create Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=2.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35.]
System.Diagnostics.TraceUtils.GetRuntimeObject(String className, Type baseType, String initializeData) +1588
System.Diagnostics.TypedElement.BaseGetRuntimeObject() +103
System.Diagnostics.ListenerElement.GetRuntimeObject() +825
System.Diagnostics.ListenerElementsCollection.GetRuntimeObject() +261
System.Diagnostics.TraceInternal.get_Listeners() +256
System.Diagnostics.Trace.get_Listeners() +79
Microsoft.ApplicationServer.Caching.DataCacheServerLogManager..cctor() +97
[TypeInitializationException: The type initializer for 'Microsoft.ApplicationServer.Caching.DataCacheServerLogManager' threw an exception.]
Microsoft.ApplicationServer.Caching.DataCacheServerLogManager.ChangeLogLevel(TraceLevel traceLevel) +0
Microsoft.ApplicationServer.Caching.ServiceConfigurationManager..cctor() +24
[TypeInitializationException: The type initializer for 'Microsoft.ApplicationServer.Caching.ServiceConfigurationManager' threw an exception.]
Microsoft.ApplicationServer.Caching.ServiceConfigurationManager.GetHostDefaults() +0
Microsoft.ApplicationServer.Caching.OMCacheNodeProperties..ctor(IHostConfiguration props, Int32 maxNC, Boolean perfCounterRequired) +69
Microsoft.ApplicationServer.Caching.LocalCacheStore..ctor(EvictionParametrs evictionParams) +50
Microsoft.ApplicationServer.Caching.DataCacheFactory..ctor(DataCacheFactoryConfiguration configuration) +555
Microsoft.Web.DistributedCache.DataCacheFactoryWrapper.CreateDataCacheFactoryFromConfiguration(DataCacheFactoryConfiguration config) +35
Microsoft.Web.DistributedCache.CacheHelpers.RunCacheCreationHooks(CacheConnectingEventArgs fetchingEventArgs, IDataCacheFactory dataCacheFactory, Object sender, EventHandler`1 fetchingHandler, EventHandler`1 fetchedHandler) +70
Microsoft.Web.DistributedCache.DistributedCacheOutputCacheProvider.CreateInternalProvider(IHttpRuntime httpRuntime, OutputCacheInitializationData initData, IDataCacheFactory dataCacheFactory, EventHandler`1 cacheFetching, EventHandler`1 cacheFetched) +123
Microsoft.Web.DistributedCache.DistributedCacheOutputCacheProvider.GetInternalProvider() +224
Microsoft.Web.DistributedCache.DistributedCacheOutputCacheProvider.Get(String key) +13
System.Web.Caching.OutputCache.Get(String key) +80
System.Web.Caching.OutputCacheModule.OnEnter(Object source, EventArgs eventArgs) +321
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +182
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +165
All I found about this error is that it occurs if you start local Azure compute emulator with in-role caching and without administrative rights. But in emulator everything works fine and problem occurs only after I publish to staging environment. (if switch to production, error remains).
I use cache for resolving routes like /username and /countryname etc. So available usernames and country names will be cached and updated on changes in database. I have static class with static DataCache object which is created on first request to cache. But even home page doesn't start so error occurs before I try to create cache object.
Web.Config. Is I remove all cache and cache diagnostics related configurations from web.config, app starts.
<configuration>
<configSections>
<section name="dataCacheClients" type="Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core" allowLocation="true" allowDefinition="Everywhere" />
<section name="cacheDiagnostics" type="Microsoft.ApplicationServer.Caching.AzureCommon.DiagnosticsConfigurationSection, Microsoft.ApplicationServer.Caching.AzureCommon" allowLocation="true" allowDefinition="Everywhere" /></configSections>
<system.diagnostics>
<trace>
<listeners>
<add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=2.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="AzureDiagnostics" />
</listeners>
</trace>
</system.diagnostics>
<system.data>
<DbProviderFactories>
<add name="Sql Azure Reliable Provider" invariant="ReliableDbProvider.SqlAzure" description="Reliable Db Provider for SQL Azure" type="ReliableDbProvider.SqlAzure.SqlAzureProvider, ReliableDbProvider" />
<add name="Sql Azure Reliable Provider With Timeout Retries" invariant="ReliableDbProvider.SqlAzureWithTimeoutRetries" description="Reliable Db Provider for SQL Azure with Timeout Retries" type="ReliableDbProvider.SqlAzureWithTimeoutRetries.SqlAzureProvider, ReliableDbProvider" />
</DbProviderFactories>
</system.data>
<connectionStrings>
<add name="AppDB" connectionString="value" />
<add name="StorageConnectionString" connectionString="value" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<!--
For a description of web.config changes see http://go.microsoft.com/fwlink/?LinkId=235367.
The following attributes can be set on the <httpRuntime> tag.
<system.Web>
<httpRuntime targetFramework="4.5" />
</system.Web>
-->
<system.web>
<customErrors mode="Off" />
<roleManager enabled="true" defaultProvider="provider">
<providers>
<clear />
<remove name="AspNetSqlRoleProvider" />
<add name="name" type="type" />
</providers>
</roleManager>
<membership defaultProvider="provider">
<providers>
<clear />
<remove name="AspNetSqlMembershipProvider" />
<add name="name" type="type" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="8" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression="" applicationName="name" />
</providers>
</membership>
<machineKey validationKey="key" decryptionKey="key" validation="SHA1" decryption="AES" />
<httpCookies httpOnlyCookies="true" requireSSL="false" />
<authentication mode="Forms">
<forms loginUrl="~/account/logon" protection="All" path="/" enableCrossAppRedirects="true" timeout="2880" />
</authentication>
<compilation debug="true" targetFramework="4.5">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<pages controlRenderingCompatibilityVersion="4.0">
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
<add namespace="System.Web.Optimization" />
</namespaces>
</pages>
<httpRuntime maxRequestLength="1048576" />
<globalization enableClientBasedCulture="true" uiCulture="auto" culture="auto" />
<!-- Windows Azure Cache session state provider --><!--<sessionState mode="Custom" customProvider="AFCacheSessionStateProvider">
<providers>
<add name="AFCacheSessionStateProvider" type="Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider, Microsoft.Web.DistributedCache" cacheName="default" dataCacheClientName="default" applicationName="AFCacheSessionState"/>
</providers>
</sessionState>--><!-- Windows Azure Cache output cache provider --><!--Uncomment this section to use Windows Azure Cache for output cache-->
<caching>
<outputCache defaultProvider="AFCacheOutputCacheProvider">
<providers>
<add name="AFCacheOutputCacheProvider" type="Microsoft.Web.DistributedCache.DistributedCacheOutputCacheProvider, Microsoft.Web.DistributedCache" cacheName="default" dataCacheClientName="default" applicationName="AFCacheOutputCache" />
</providers>
</outputCache>
</caching>
</system.web>
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00" />
</staticContent>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="false" />
<directoryBrowse enabled="false" />
<httpProtocol>
<customHeaders>
<!-- Enable Cross Domain AJAX calls -->
<remove name="Access-Control-Allow-Origin" />
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
<handlers>
<add name="UrlRoutingHandler" type="System.Web.Routing.UrlRoutingHandler, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" path="path" verb="GET" />
<add name="UrlRoutingHandlerEmailLogo" type="System.Web.Routing.UrlRoutingHandler,System.Web, Version=4.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a" path="path" verb="GET" />
<add name="UrlRoutingHandlerSitemap" type="System.Web.Routing.UrlRoutingHandler, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" path="path" verb="GET" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Abstractions" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.WindowsAzure.Diagnostics" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.0.0" newVersion="2.2.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network host="host" userName="username" password="password" />
</smtp>
</mailSettings>
</system.net>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483644" />
</webServices>
</scripting>
</system.web.extensions>
<dataCacheClients>
<dataCacheClient name="default">
<autoDiscover isEnabled="true" identifier="sub2o" />
<localCache isEnabled="true" sync="TimeoutBased" objectCount="100000" ttlValue="300" />
</dataCacheClient>
</dataCacheClients>
<cacheDiagnostics>
<crashDump dumpLevel="Off" dumpStorageQuotaInMB="100" />
</cacheDiagnostics>
</configuration>
ServiceConfiguration.Cloud.cscfg
<ServiceConfiguration serviceName="WindowsAzure" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration" osFamily="3" osVersion="*" schemaVersion="2013-10.2.2">
<Role name="sub2o">
<Instances count="1" />
<ConfigurationSettings>
<Setting name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString" value="DefaultEndpointsProtocol=https;AccountName=name;AccountKey=key" />
<Setting name="Microsoft.WindowsAzure.Plugins.RemoteAccess.Enabled" value="true" />
<Setting name="Microsoft.WindowsAzure.Plugins.RemoteAccess.AccountUsername" value="username" />
<Setting name="Microsoft.WindowsAzure.Plugins.RemoteAccess.AccountEncryptedPassword" value="password" />
<Setting name="Microsoft.WindowsAzure.Plugins.RemoteAccess.AccountExpiration" value="2014-09-07T23:59:59.0000000+04:00" />
<Setting name="Microsoft.WindowsAzure.Plugins.RemoteForwarder.Enabled" value="true" />
<Setting name="Microsoft.AppInsights.AccountId" value="ID" />
<Setting name="Microsoft.AppInsights.InstrumentationKey" value="KEY" />
<Setting name="Microsoft.AppInsights.EnableMonitoring" value="true" />
<!-- Uncomment the following section if you want to change the Display Name of your application on the Application Insights Portal. (Default is your WebRole Name)-->
<!--<Setting name="Microsoft.AppInsights.DisplayName" value="Name" />-->
<Setting name="Microsoft.WindowsAzure.Plugins.Caching.ClientDiagnosticLevel" value="1" />
<Setting name="Microsoft.WindowsAzure.Plugins.Caching.NamedCaches" value="{"caches":[{"name":"default","policy":{"eviction":{"type":0},"expiration":{"defaultTTL":10,"isExpirable":true,"type":1},"serverNotification":{"isEnabled":false}},"secondaries":0}]}" />
<Setting name="Microsoft.WindowsAzure.Plugins.Caching.DiagnosticLevel" value="1" />
<Setting name="Microsoft.WindowsAzure.Plugins.Caching.CacheSizePercentage" value="30" />
<Setting name="Microsoft.WindowsAzure.Plugins.Caching.ConfigStoreConnectionString" value="DefaultEndpointsProtocol=https;AccountName=name;AccountKey=key" />
</ConfigurationSettings>
<Certificates>
<Certificate name="Microsoft.WindowsAzure.Plugins.RemoteAccess.PasswordEncryption" thumbprint="value" thumbprintAlgorithm="sha1" />
</Certificates>
</Role>
</ServiceConfiguration>
ServiceDefinition.csdef
<?xml version="1.0"?>
<ServiceDefinition name="WindowsAzure" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition" schemaVersion="2013-10.2.2">
<WebRole name="sub2o" vmsize="Small">
<Sites>
<Site name="Web">
<Bindings>
<Binding name="Endpoint1" endpointName="Endpoint1" />
</Bindings>
</Site>
</Sites>
<Endpoints>
<InputEndpoint name="Endpoint1" protocol="http" port="80" />
</Endpoints>
<Imports>
<Import moduleName="Diagnostics" />
<Import moduleName="RemoteAccess" />
<Import moduleName="RemoteForwarder" />
<Import moduleName="Caching" />
</Imports>
<Startup priority="-2">
<Task commandLine="AppInsightsAgent\UnifiedBootstrap.bat" executionContext="elevated" taskType="background">
</Task>
<Task commandLine="Microsoft.WindowsAzure.Caching\ClientPerfCountersInstaller.exe install" executionContext="elevated" taskType="simple" />
</Startup>
<ConfigurationSettings>
<Setting name="Microsoft.AppInsights.AccountId" />
<Setting name="Microsoft.AppInsights.InstrumentationKey" />
<Setting name="Microsoft.AppInsights.EnableMonitoring" />
<!-- Uncomment the following section if you want to change the Display Name of your application on the Application Insights Portal. (Default is your WebRole Name)-->
<!--<Setting name="Microsoft.AppInsights.DisplayName" />-->
<Setting name="Microsoft.WindowsAzure.Plugins.Caching.ClientDiagnosticLevel" />
</ConfigurationSettings>
<LocalResources>
<LocalStorage name="DiagnosticStore" sizeInMB="20000" cleanOnRoleRecycle="false" />
</LocalResources>
</WebRole>
</ServiceDefinition>
Problem was caused by conflict between SDK 2.2 and 2.3. Just need to update SDK for Windows Azure Cloud Service project from Properties->Application. So simple.

Why does Entity Framework with Windows Authentication not pass my credentials to SQL Server?

I'm trying to get an MVC 4 intranet site with Entity Framework 5 working on web server running IIS6 but Windows Authentication/Integrated Security is not working right because the error says
Stack Trace:
[SqlException (0x80131904): Login failed for user
'EASTDOMAIN\WEBDEV2$'.]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection) +5104926
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() +260
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior,
SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj) +2294
System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean
enlistOK) +35
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo
serverInfo, String newPassword, Boolean ignoreSniOpenTimeout,
TimeoutTimer timeout, SqlConnection owningObject, Boolean
withFailover) +250
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo
serverInfo, String newPassword, Boolean redirectedUserInstance,
SqlConnection owningObject, SqlConnectionString connectionOptions,
TimeoutTimer timeout) +932
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection
owningObject, TimeoutTimer timeout, SqlConnectionString
connectionOptions, String newPassword, Boolean redirectedUserInstance)
+195 System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity
identity, SqlConnectionString connectionOptions, Object providerInfo,
String newPassword, SqlConnection owningObject, Boolean
redirectedUserInstance) +316
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions
options, Object poolGroupProviderInfo, DbConnectionPool pool,
DbConnection owningConnection) +185
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection
owningConnection, DbConnectionPool pool, DbConnectionOptions options)
+33 System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection
owningObject) +524
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection
owningObject) +66
System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection
owningObject) +479
System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection
owningConnection) +108
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection
outerConnection, DbConnectionFactory connectionFactory) +126
System.Data.SqlClient.SqlConnection.Open() +125
System.Data.SqlClient.SqlProviderServices.UsingConnection(SqlConnection
sqlConnection, Action1 act) +85
System.Data.SqlClient.SqlProviderServices.UsingMasterConnection(SqlConnection
sqlConnection, Action1 act) +341
System.Data.SqlClient.SqlProviderServices.GetDbProviderManifestToken(DbConnection
connection) +258
System.Data.Common.DbProviderServices.GetProviderManifestToken(DbConnection
connection) +34
[ProviderIncompatibleException: The provider did not return a
ProviderManifestToken string.]
System.Data.Common.DbProviderServices.GetProviderManifestToken(DbConnection
connection) +163
System.Data.Entity.ModelConfiguration.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices
providerServices, DbConnection connection) +41
[ProviderIncompatibleException: An error occurred while getting
provider information from the database. This can be caused by Entity
Framework using an incorrect connection string. Check the inner
exceptions for details and ensure that the connection string is
correct.]
System.Data.Entity.ModelConfiguration.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices
providerServices, DbConnection connection) +166
System.Data.Entity.ModelConfiguration.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection
connection, DbProviderManifest& providerManifest) +40
System.Data.Entity.DbModelBuilder.Build(DbConnection
providerConnection) +46
System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext
internalContext) +62
System.Data.Entity.Internal.RetryLazy2.GetValue(TInput input) +117
System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
+453 System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type
entityType) +18
System.Data.Entity.Internal.Linq.InternalSet1.Initialize() +56
System.Data.Entity.Internal.Linq.InternalSet1.Include(String path)
+18 System.Data.Entity.Infrastructure.DbQuery1.Include(String path) +73 System.Data.Entity.DbExtensions.Include(IQueryable1
source, String path) +85
System.Data.Entity.DbExtensions.Include(IQueryable1 source,
Expression1 path) +126
Reclosing.Controllers.RecloserController.Index() +198
lambda_method(Closure , ControllerBase , Object[] ) +62
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase
controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext
controllerContext, IDictionary2 parameters) +188
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext
controllerContext, ActionDescriptor actionDescriptor, IDictionary2
parameters) +27
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
+28 System.Web.Mvc.Async.<>c__DisplayClass81.b__7(IAsyncResult
) +12 System.Web.Mvc.Async.WrappedAsyncResult1.End() +50 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult
asyncResult) +29
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
+59 System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
+240 System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +12 System.Web.Mvc.Async.WrappedAsyncResult1.End()
+50 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult
asyncResult) +31
System.Web.Mvc.Async.<>c_DisplayClass2a.b_20()
+23 System.Web.Mvc.Async.<>c_DisplayClass25.b_22(IAsyncResult
asyncResult) +128 System.Web.Mvc.Async.WrappedAsyncResult1.End()
+50 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult
asyncResult) +26
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult
asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult
ar) +25 System.Web.Mvc.Async.WrappedAsyncResult1.End() +55
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +41
System.Web.Mvc.Async.<>c_DisplayClass4.b__3(IAsyncResult
ar) +25 System.Web.Mvc.Async.WrappedAsyncResult1.End() +55
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +28
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult
asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult
asyncResult) +28
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult
ar) +25 System.Web.Mvc.Async.WrappedAsyncResult1.End() +55
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
+30 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult
result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+9042429 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
-------------------------------------------------------------------------------- Version Information: Microsoft .NET Framework Version:4.0.30319;
ASP.NET Version:4.0.30319.1016
Here is my web.config:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="ReclosingContext" connectionString="Data Source=sqlserverbox\devtest;Initial Catalog=Reclosing;Integrated Security=SSPI;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation targetFramework="4.0" />
<authentication mode="Windows" />
<authorization>
<deny users="?" />
</authorization>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
<remove name="cshtml-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="cshtml-ISAPI-4.0_64bit" path="*.cshtml, *." verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
</handlers>
<defaultDocument>
<files>
<add value="index.aspx" />
</files>
</defaultDocument></system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.3.0.0" newVersion="1.3.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<location path="Web.config">
<system.web>
<compilation defaultLanguage="c#" />
</system.web>
</location>
</configuration>
'EASTDOMAIN\WEBDEV2$' is not my UserID, but is the domain\servername.
I've tried playing around with adding an impersonate to the config to no avail. This worked fine in IIS Express on my local PC connecting to the same SQL 2005 DB (which is on its own box). My local PC runs Windows 7 using VS2012.
I'm new to this so if anyone can help, I could really use it! I'm getting tired of beating my head against the wall!
One of the server guys at work pointed me to this link which is a helpful reference: http://msdn.microsoft.com/en-us/library/bsz5788z%28v=vs.100%29.aspx
He and others discouraged me from using Windows Authentication. One reason was that I would start having to add each new user as an account to the database and it could become very cumbersome with a large user base. Also, in our environment where we have the potential for users coming from different log in domains, then the issues with having the correct trusts and authentication paths between domains comes into play.
So I stopped trying to use Windows Authentication to connect to the database, and created a single log on account in the database for EF in the MVC application to use (from the web server to the DB server). It works great this way, however, I'll have to set up some sort of database table to track and authorize which users have read/write access to the main data vs all the read-only users (who won't be in that table).
My connection string changed to have this connection string:
<add name="ReclosingContext" connectionString="Data Source=sqlserverbox\devtest;Initial Catalog=Reclosing;Integrated Security=False;User ID=xxxxxxxx;Password=xxxxxxxxx;MultipleActiveResultSets=True"
providerName="System.Data.SqlClient" />
I thought Windows Authentication\Integrated Security would make things simpler and better for the users for the entire application, but found that in our environment, it is better not to use it for the SQL Server connection.

NServiceBus Saga Persistence

We have an NServiceBus service configured to run sagas. With InMemory-persistence everything runs fine. When trying to change the profile to NServiceBus.Integration, we get an error when starting the service.
Endpoint configuration:
public class MyEndpoint : IConfigureThisEndpoint, AsA_Server, IWantCustomInitialization
{
private IContainer _container;
public void Init()
{
log4net.Config.XmlConfigurator.Configure();
SetupStructureMap();
Configure.With()
.Log4Net()
.StructureMapBuilder(_container)
.Sagas()
.XmlSerializer();
}
private void SetupStructureMap()
{
[...]
}
}
Error message:
FATAL 2012-01-18 11:11:52,197 2640ms GenericHost Start - FluentNHibernate.Cfg.FluentConfigurationException: An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.
* Database was not configured through Database method.
---> System.ArgumentException: The number of generic arguments provided doesn't equal the arity of the generic type definition.
Parameter name: instantiation
at System.RuntimeType.MakeGenericType(Type[] instantiation)
at FluentNHibernate.Automapping.AutoMapManyToMany.GetInverseProperty(PropertyInfo property)
at FluentNHibernate.Automapping.AutoMapManyToMany.MapsProperty(PropertyInfo property)
at FluentNHibernate.Automapping.AutoMapper.TryToMapProperty(ClassMappingBase mapping, PropertyInfo property, IList`1 mappedProperties)
at FluentNHibernate.Automapping.AutoMapper.MapEverythingInClass(ClassMappingBase mapping, Type entityType, IList`1 mappedProperties)
at FluentNHibernate.Automapping.AutoMapper.MergeMap(Type classType, ClassMappingBase mapping, IList`1 mappedProperties)
at FluentNHibernate.Automapping.AutoMapper.Map(Type classType, List`1 types)
at FluentNHibernate.Automapping.AutoPersistenceModel.AddMapping(Type type)
at FluentNHibernate.Automapping.AutoPersistenceModel.CompileMappings()
at FluentNHibernate.Cfg.AutoMappingsContainer.Apply(Configuration cfg)
at FluentNHibernate.Cfg.MappingConfiguration.Apply(Configuration cfg)
at FluentNHibernate.Cfg.FluentConfiguration.BuildConfiguration()
--- End of inner exception stack trace ---
at FluentNHibernate.Cfg.FluentConfiguration.BuildConfiguration()
at NServiceBus.SagaPersisters.NHibernate.Config.Internal.SessionFactoryBuilder.UpdateDatabaseSchemaUsing(FluentConfiguration fluentConfiguration)
at NServiceBus.SagaPersisters.NHibernate.Config.Internal.SessionFactoryBuilder.Build(IDictionary`2 nhibernateProperties, Boolean updateSchema)
at NServiceBus.ConfigureNHibernateSagaPersister.NHibernateSagaPersister(Configure config, IDictionary`2 nhibernateProperties, Boolean autoUpdateSchema)
at NServiceBus.ConfigureNHibernateSagaPersister.NHibernateSagaPersisterWithSQLiteAndAutomaticSchemaGeneration(Configure config)
at NServiceBus.Host.Internal.ProfileHandlers.IntegrationProfileHandler.NServiceBus.IHandleProfile.ProfileActivated()
at NServiceBus.Host.Internal.ProfileManager.<ActivateProfileHandlers>b__14(IHandleProfile hp)
at System.Collections.Generic.List`1.ForEach(Action`1 action)
at NServiceBus.Host.Internal.ProfileManager.ActivateProfileHandlers()
at NServiceBus.Host.Internal.GenericHost.Start()
* Database was not configured through Database method.
Configuration file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core" />
<section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core" />
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" requirePermission="false" />
<section name="MsmqSubscriptionStorageConfig" type="NServiceBus.Config.MsmqSubscriptionStorageConfig,NServiceBus.Core" />
</configSections>
<MsmqTransportConfig InputQueue="MyQueue" ErrorQueue="MyQueueError" NumberOfWorkerThreads="1" MaxRetries="5" />
<UnicastBusConfig>
<MessageEndpointMappings>
<add Messages="My.MessageContracts" Endpoint="MyQueue" />
</MessageEndpointMappings>
</UnicastBusConfig>
<log4net debug="false">
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="C:\Log\My.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
</layout>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>
</configuration>
Looks like you are missing the following from the config, it is in the app.config of the OrderService in the samples:
<section name="DBSubscriptionStorageConfig" type="NServiceBus.Config.DBSubscriptionStorageConfig, NServiceBus.Core" />
<section name="NHibernateSagaPersisterConfig" type="NServiceBus.Config.NHibernateSagaPersisterConfig, NServiceBus.Core" />
<DBSubscriptionStorageConfig>
<NHibernateProperties>
<add Key="connection.provider" Value="NHibernate.Connection.DriverConnectionProvider"/>
<add Key="connection.driver_class" Value="NHibernate.Driver.SQLite20Driver"/>
<add Key="connection.connection_string" Value="Data Source=.\Subscriptions.sqlite;Version=3;New=True;"/>
<add Key="dialect" Value="NHibernate.Dialect.SQLiteDialect"/>
</NHibernateProperties>
</DBSubscriptionStorageConfig>
<NHibernateSagaPersisterConfig>
<NHibernateProperties>
<add Key="connection.provider" Value="NHibernate.Connection.DriverConnectionProvider"/>
<add Key="connection.driver_class" Value="NHibernate.Driver.SqlClientDriver"/>
<add Key="connection.connection_string" Value="Server=localhost;initial catalog=NServiceBus;Integrated Security=SSPI"/>
<add Key="dialect" Value="NHibernate.Dialect.MsSql2000Dialect"/>
</NHibernateProperties>
</NHibernateSagaPersisterConfig>
The problem was, as Andreas touched upon, on persisting the SagaData-class using NHibernate/Fluent NHibernate.
Just to summarize all the things that were wrong:
In order to use the profile NServicebus.Integration, you need to add a reference to SQLite (use NuGet)
In order to use the profile NServiceBus.Production, you need to set up connection to the database in app.config, as Adam showed in his answer.
In order to use both these two profiles, your SagaData-class must be playing by the rules of NHibernate:
All properties must be virtual
The class must not be sealed
The same goes for the type of all properties
All this is for NServiceBus 2.6. In 3.0, which is in Beta6 now, they use RavenDB instead, with no binding to NHibernate or SQLite. How the transition from 2.6 to 3.0 is, I do not know yet, but I think this is the way we are going on this project.

mod_mono question: Could not resolve the name 'ConfigurationManager'

I'm running mod_mono 2.4.4 on Ubuntu and I'm finding that I've had to go through my VB files and add "imports System.Configuration" to all of them to resolve the name error. This was not necessary in mod_aspdotnet on the Windows side.
I have, however, run into one error of which I can't find the source:
System.Web.Compilation.CompilationException: VBNC30451: Could not resolve the name 'ConfigurationManager'
at System.Web.Compilation.AssemblyBuilder.BuildAssembly (System.Web.VirtualPath virtualPath, System.CodeDom.Compiler.CompilerParameters options) [0x00000]
at System.Web.Compilation.AssemblyBuilder.BuildAssembly (System.Web.VirtualPath virtualPath) [0x00000]
at System.Web.Compilation.BuildManager.GenerateAssembly (System.Web.Compilation.AssemblyBuilder abuilder, System.Collections.Generic.List`1 buildItems, System.Web.VirtualPath virtualPath, BuildKind buildKind) [0x00000]
at System.Web.Compilation.BuildManager.BuildAssembly (System.Web.VirtualPath virtualPath) [0x00000]
Is this the result of a missed step or incorrect configuration that I have to keep adding this import?
Somewhere, probably /etc/mono/2.0/web.config, there's a default configuration file. Verify that it contains something like this:
<pages>
<namespaces>
<add namespace="System" />
<add namespace="System.Collections" />
<add namespace="System.Collections.Specialized" />
<add namespace="System.Configuration" />
<add namespace="System.Text" />
<add namespace="System.Text.RegularExpressions" />
<add namespace="System.Web" />
<add namespace="System.Web.Caching" />
<add namespace="System.Web.SessionState" />
<add namespace="System.Web.Security" />
<add namespace="System.Web.Profile" />
<add namespace="System.Web.UI" />
<add namespace="System.Web.UI.WebControls" />
<!-- <add namespace="System.Web.UI.WebControls.WebParts" /> -->
<add namespace="System.Web.UI.HtmlControls" />
</namespaces>
</pages>
Which is the default. That should take care of adding the default imports.
Btw, mod_mono 2.4.4 is a bit old these days. Try getting newer packages.