VB.Net Forms Authentication - Roles.CreateRole() - vb.net

So I recently started moving my applications over to a more secure authentication system for my un-managed users. I saw Forms authentication for VB.Net and had no issues getting started. I got two new users created and logged in with working password resets.
I just tried to use the Roles.CreateRole function to create a simple role and it through an error associated with app_data permissions.
I have already tried the excessive 50+ articles of people deleting the SQL folder in APP_Data from the windows XP days but it doesn't work for me. I tried looking for the readme file the error references but with over 400+ readmes in the Visual Studio file I'm lost on finding that information. I have also tried changing the IIS application pool identity to a local user and restarted the whole PC.
If anyone knows where the readme this error references is I would be more than happy to read that first.
Here is the sub where I try to run my code that throws the error when I call Roles.CreateRole
Protected Sub gvUsers_RowCommand(sender As Object, e As GridViewCommandEventArgs)
Dim strUsername = CType(sender, GridView).Rows(e.CommandArgument).Cells(0).Text
Dim intLevel = Convert.ToInt16(CType(sender, GridView).Rows(e.CommandArgument).Cells(1).Text)
Dim objMembers = Membership.FindUsersByName(strUsername)
Dim objUser As MembershipUser = objMembers(strUsername)
If e.CommandName = "Reset Password" Then
lblError.Text = "Reset password for: <b>" & strUsername & "</b> New Password: <b>" & objUser.ResetPassword() & "</b>"
ElseIf e.CommandName = "Delete" Then
lblError.Text = "Deletion request for user: <b>" & strUsername & "</b> resulted in a <b>" & Membership.DeleteUser(strUsername).ToString & "</b> result."
ElseIf e.CommandName = "Increase" Then
Roles.CreateRole("MoldMaintAdmin")
Roles.AddUserToRole(strUsername, "MoldMaintAdmin")
ElseIf e.CommandName = "Decrease" Then
Roles.CreateRole("MoldMaintUser")
Roles.AddUserToRole(strUsername, "MoldMaintUser")
End If
End Sub
Here is the error in detail.
Server Error in '/' Application.
Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.
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.
SQLExpress database file auto-creation error:
The connection string specifies a local Sql Server Express instance using a database location within the application's App_Data directory. The provider attempted to automatically create the application services database because the provider determined that the database does not exist. The following configuration requirements are necessary to successfully check for existence of the application services database and automatically create the application services database:
If the application is running on either Windows 7 or Windows Server 2008R2, special configuration steps are necessary to enable automatic creation of the provider database. Additional information is available at: http://go.microsoft.com/fwlink/?LinkId=160102. If the application's App_Data directory does not already exist, the web server account must have read and write access to the application's directory. This is necessary because the web server account will automatically create the App_Data directory if it does not already exist.
If the application's App_Data directory already exists, the web server account only requires read and write access to the application's App_Data directory. This is necessary because the web server account will attempt to verify that the Sql Server Express database already exists within the application's App_Data directory. Revoking read access on the App_Data directory from the web server account will prevent the provider from correctly determining if the Sql Server Express database already exists. This will cause an error when the provider attempts to create a duplicate of an already existing database. Write access is required because the web server account's credentials are used when creating the new database.
Sql Server Express must be installed on the machine.
The process identity for the web server account must have a local user profile. See the readme document for details on how to create a local user profile for both machine and domain accounts.
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:
[SqlException (0x80131904): Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.]
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager) +907
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +5968584
System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions) +38
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +507
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +154
System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +21
System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +90
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +443
System.Data.SqlClient.SqlConnection.Open() +96
System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +75
[HttpException (0x80004005): Unable to connect to SQL Server database.]
System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +125
System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install) +89
System.Web.Management.SqlServices.Install(String database, String dbFileName, String connectionString) +29
System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString) +386
Here is the webconfig
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
https://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="AuthServices" connectionString="Data Source=localhost\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=authentication;" />
</connectionStrings>
<system.web>
<authentication mode="Forms">
<forms loginUrl="login.aspx" defaultUrl="main.aspx" />
</authentication>
<authorization>
<allow users="?"/>
<!--<deny users="?"/>-->
</authorization>
<membership defaultProvider="AuthServices" userIsOnlineTimeWindow="30">
<providers>
<add
name="AuthServices"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="AuthServices"
applicationName="MoldMaint"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="false"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
passwordAttemptWindow="10" />
</providers>
</membership>
<roleManager
enabled="true"
cacheRolesInCookie="true" >
<providers>
<add name ="AuthServices"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="AuthServices"
applicationName="MoldMaint"/>
</providers>
</roleManager>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.7.2"/>
<httpRuntime targetFramework="4.7.2"/>
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701"/>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+"/>
</compilers>
</system.codedom>
</configuration>

In the role manager section under < system.web >< roleManager > add a default provider inside role manager. I have already declared "AuthServices" in the connection strings section at the top of my original posting.
<roleManager defaultProvider="AuthServices" enabled="true" cacheRolesInCookie="true">
<providers>
<add name ="AuthServices"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="AuthServices"
applicationName="MoldMaint"/>
</providers>
</roleManager>

Related

WCF customUserNamePasswordValidatorType error - Could not load file or assembly 'CustomUserNameValidator' or one of its dependencies

I have created a simply WCF web service and require WCF Security with username/password added to the service and have read through the following MS documentation https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-use-a-custom-user-name-and-password-validator to try and do so.
However, I am getting the error below when I run the project and go to http://localhost:50533/Service.svc:
Server Error in '/' Application.
Could not load file or assembly 'CustomUserNameValidator' or one of its dependencies. The system cannot find the file specified.
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.IO.FileNotFoundException: Could not load file or assembly 'CustomUserNameValidator' or one of its dependencies. The system cannot find the file specified.
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.
Assembly Load Trace: The following information can be helpful to determine why the assembly 'CustomUserNameValidator' could not be loaded.
=== Pre-bind state information ===
LOG: DisplayName = CustomUserNameValidator
(Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: CustomUserNameValidator | Domain ID: 6
WRN: A partial bind occurs when only part of the assembly display name is provided.
WRN: This might result in the binder loading an incorrect assembly.
WRN: It is recommended to provide a fully specified textual identity for the assembly,
WRN: that consists of the simple name, version, culture, and public key token.
WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue.
LOG: Appbase = file:///C:/Users/xxxx/source/repos/Misc/WCFDummyService/WCFDummyService/
LOG: Initial PrivatePath = C:\Users\xxxx\source\repos\Misc\WCFDummyService\WCFDummyService\bin
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Users\xxxx\source\repos\Misc\WCFDummyService\WCFDummyService\web.config
LOG: Using host configuration file: C:\Users\xxxx\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Users/xxxx/AppData/Local/Temp/Temporary ASP.NET Files/vs/2193ee9a/db4d60f6/CustomUserNameValidator.DLL.
LOG: Attempting download of new URL file:///C:/Users/xxxx/AppData/Local/Temp/Temporary ASP.NET Files/vs/2193ee9a/db4d60f6/CustomUserNameValidator/CustomUserNameValidator.DLL.
LOG: Attempting download of new URL file:///C:/Users/xxxx/source/repos/Misc/WCFDummyService/WCFDummyService/bin/CustomUserNameValidator.DLL.
LOG: Attempting download of new URL file:///C:/Users/xxxx/source/repos/Misc/WCFDummyService/WCFDummyService/bin/CustomUserNameValidator/CustomUserNameValidator.DLL.
LOG: Attempting download of new URL file:///C:/Users/xxxx/AppData/Local/Temp/Temporary ASP.NET Files/vs/2193ee9a/db4d60f6/CustomUserNameValidator.EXE.
LOG: Attempting download of new URL file:///C:/Users/xxxx/AppData/Local/Temp/Temporary ASP.NET Files/vs/2193ee9a/db4d60f6/CustomUserNameValidator/CustomUserNameValidator.EXE.
LOG: Attempting download of new URL file:///C:/Users/xxxx/source/repos/Misc/WCFDummyService/WCFDummyService/bin/CustomUserNameValidator.EXE.
LOG: Attempting download of new URL file:///C:/Users/xxxx/source/repos/Misc/WCFDummyService/WCFDummyService/bin/CustomUserNameValidator/CustomUserNameValidator.EXE.
Stack Trace:
[FileNotFoundException: Could not load file or assembly 'CustomUserNameValidator' or one of its dependencies. The system cannot find the file specified.]
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type) +0
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName) +71
System.RuntimeType.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark) +41
System.Type.GetType(String typeName, Boolean throwOnError) +35
System.ServiceModel.Configuration.UserNameServiceElement.ApplyConfiguration(UserNamePasswordServiceCredential userName) +356
System.ServiceModel.Configuration.ServiceCredentialsElement.ApplyConfiguration(ServiceCredentials behavior) +128
System.ServiceModel.Configuration.ServiceCredentialsElement.CreateBehavior() +165
System.ServiceModel.Description.ConfigLoader.LoadBehaviors(ServiceModelExtensionCollectionElement`1 behaviorElement, KeyedByTypeCollection`1 behaviors, Boolean commonBehaviors) +204
System.ServiceModel.Description.ConfigLoader.LoadServiceDescription(ServiceHostBase host, ServiceDescription description, ServiceElement serviceElement, Action`1 addBaseAddress, Boolean skipHost) +13502205
System.ServiceModel.ServiceHostBase.LoadConfigurationSectionInternal(ConfigLoader configLoader, ServiceDescription description, ServiceElement serviceSection) +74
System.ServiceModel.ServiceHostBase.ApplyConfiguration() +188
System.ServiceModel.ServiceHost.ApplyConfiguration() +65
System.ServiceModel.ServiceHostBase.InitializeDescription(UriSchemeKeyedCollection baseAddresses) +188
System.ServiceModel.ServiceHost.InitializeDescription(Type serviceType, UriSchemeKeyedCollection baseAddresses) +49
System.ServiceModel.ServiceHost..ctor(Type serviceType, Uri[] baseAddresses) +153
System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(Type serviceType, Uri[] baseAddresses) +34
System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String constructorString, Uri[] baseAddresses) +538
System.ServiceModel.HostingManager.CreateService(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +1489
System.ServiceModel.HostingManager.ActivateService(ServiceActivationInfo serviceActivationInfo, EventTraceActivity eventTraceActivity) +53
System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +666
[ServiceActivationException: The service '/Service.svc' cannot be activated due to an exception during compilation. The exception message is: Could not load file or assembly 'CustomUserNameValidator' or one of its dependencies. The system cannot find the file specified..]
System.Runtime.AsyncResult.End(IAsyncResult result) +513025
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +182
System.ServiceModel.Activation.ServiceHttpHandler.EndProcessRequest(IAsyncResult result) +12
System.Web.CallHandlerExecutionStep.InvokeEndHandler(IAsyncResult ar) +161
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +128
I have noticed this error only appears due to adding the following into my Web.Config file
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WCFDummyService.CustomUserNameValidator, CustomUserNameValidator" />
</serviceCredentials>
I've modified the value in customUserNamePasswordValidatorType numerous times to try and fix it but the error still comes up or a similar one.
See below for the full Web.Config file.
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.6"/>
<httpRuntime targetFramework="4.6"/>
<pages>
<namespaces>
<add namespace="System.Runtime.Serialization"/>
<add namespace="System.ServiceModel"/>
<add namespace="System.ServiceModel.Web"/>
</namespaces>
</pages>
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Binding1">
<security mode="Transport">
<message clientCredentialType="UserName" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WCFDummyService.CustomUserNameValidator, CustomUserNameValidator" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
The Code is simply the default WCF Service code you get out of the box when creating a new WCF Service project in Visual Studio and I've just added a new CustomUserNameValidator class.
If you want to see this class, here is the code for it:
Imports System.IdentityModel.Selectors
Public Class CustomUserNameValidator
Inherits UserNamePasswordValidator
Public Overrides Sub Validate(ByVal userName As String, ByVal password As String)
If userName Is Nothing OrElse password Is Nothing Then
Throw New ArgumentNullException()
End If
If Not (userName = "user" AndAlso password = "pass123") Then
Throw New FaultException("Unknown Username or Incorrect Password")
End If
End Sub
End Class
Also, this is all that shows in Properties for the file.
If you can please help with the error, that would be very much appreciated.
You must to be sure that the “Build Action” on the “CustomUserNameValidator.vb” Properties is set to “Compile”.
It seems to be set on “Content” based on what you are describing.
The image shows how you can do that or take a look here:
https://learn.microsoft.com/en-us/visualstudio/ide/build-actions?view=vs-2022
The reason I was getting the problem above was because I needed to set this in the web.config
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="CustomUserNameValidator, App_Code" />
</serviceCredentials>
When I went to the following path on my machine, the only dll was App_Code.tjgywzog.dll so figured the assembly is just App_Code and then it just has to use the class name CustomUserNameValidator since my code is not using namespaces.

Accessing EF6 in code throws System.NotSupportedException in EntityFramework.dll

based on .NET 4.0 and EF 6.1, I've created a project names Database with an Entity Model to access a SQL Server instance via Designer in Visual Studio 2013.
Additionally, there is an Console Application (also .NET 4.0) trying to consume the entities of the Database-project.
The credentials for the underlying database are stored in the Console Application's App.config within the key <connectionStrings>.
When creating a DbContext in the following way, I can perfectly access the entities:
var db = new MyEntities();
var o1 = db.Buildings.First();
MyEntities is the class that the Entity Framework creates automatically, inheriting from DbContext.
For some compatibility reasons to our guidelines, I'm trying to split up the connectionString into own keys (database, instance, user, password) within Ap.config.
For this, I'm using EntityConnectionStringBuilder to build up the EntityConnection with ProviderConnectionString, Metadata and Provider. It look's like this:
Dim sqlBuilder = New SqlConnectionStringBuilder()
sqlBuilder.MultipleActiveResultSets = True
sqlBuilder.DataSource = "database instance"
sqlBuilder.InitialCatalog = "database"
sqlBuilder.UserID = "user"
sqlBuilder.Password = "password"
Dim providerConnectionString = sqlBuilder.ToString()
Dim metaData = #"res://*/DBModel.csdl|res://*/DBModel.ssdl|res://*/DBModel.msl"
Dim entityConnectionBuilder As New EntityConnectionStringBuilder() With { _
.Metadata = metaData, _
.ProviderConnectionString = providerConnectionString, _
.Provider = "System.Data.SqlClient"}
Dim s = entityConnectionBuilder.ToString()
entityConnection = New EntityConnection(s)
In my Console Application, I call:
var db1 = new MyEntities(entityConnection);
var o2 = db1.Buildings.First();
When executing the last line, the following exception will be thrown:
An unhandled exception of type 'System.NotSupportedException' occurred in EntityFramework.dll
Additional information: Unable to determine the DbProviderFactory type for connection of type 'System.Data.EntityClient.EntityConnection'. Make sure that the ADO.NET provider is installed or registered in the application config.
App.config of Console Application contains the following:
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
</startup>
<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>
</configuration>
Any ideas, why this exception occurs?

Error on running a WCF workflow application after installation of AppFabric

I have installed Windows Server AppFabric and I can now not run even the most basic WCF Workflow Service Application. I have gone through the configuration and setup databases for the persistence store, monitor and cache which worked ok.
So I have stripped it back and just created and run an empty WCF Workflow Service Application. When I click on the Service1.xaml file I get the error below.
I have checked the databases and I have dbowner access to all of them (have substituted my real logon details here).
I am using VS2010 with .NET 4 update 1.
Server Error in '/' Application.
Cannot open database "AppFabricPersistenceDB" requested by the login. The login failed.
Login failed for user 'mydomain\myusername'.
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.
Details
Exception Details: System.Data.SqlClient.SqlException: Cannot open database "AppFabricPersistenceDB" requested by the login. The login failed.
Login failed for user 'mydomain\myusername'.
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:
[SqlException (0x80131904): Cannot open database "AppFabricPersistenceDB" requested by the login. The login failed.
Login failed for user 'mydomain\myusername'.]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +5064458
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() +234
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2275
System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +35
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, SqlConnection owningObject) +183
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout) +239
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) +232
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.Activities.DurableInstancing.SqlCommandAsyncResult.StartCommandInternal(Boolean synchronous) +557
System.Activities.DurableInstancing.SqlWorkflowInstanceStoreAsyncResult.StartOperation() +377
[InstancePersistenceCommandException: The execution of the InstancePersistenceCommand named {urn:schemas-microsoft-com:System.Activities.Persistence/command}CreateWorkflowOwner was interrupted by an error.]
System.Runtime.AsyncResult.End(IAsyncResult result) +688590
System.Runtime.DurableInstancing.InstancePersistenceContext.OuterExecute(InstanceHandle initialInstanceHandle, InstancePersistenceCommand command, Transaction transaction, TimeSpan timeout) +78
System.Runtime.DurableInstancing.InstanceStore.Execute(InstanceHandle handle, InstancePersistenceCommand command, TimeSpan timeout) +82
System.ServiceModel.Activities.Dispatcher.DurableInstanceManager.Open(TimeSpan timeout) +294
[CommunicationException: The InstanceStore could not be initialized.]
System.ServiceModel.Activities.Dispatcher.DurableInstanceManager.Open(TimeSpan timeout) +394
System.ServiceModel.Activities.WorkflowServiceHost.OnOpen(TimeSpan timeout) +105
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +318
System.ServiceModel.HostingManager.ActivateService(String normalizedVirtualPath) +206
System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath) +651
[ServiceActivationException: The service '/Service1.xamlx' cannot be activated due to an exception during compilation. The exception message is: The InstanceStore could not be initialized..]
System.Runtime.AsyncResult.End(IAsyncResult result) +688590
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +190
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.ExecuteSynchronous(HttpApplication context, String routeServiceVirtualPath, Boolean flowContext, Boolean ensureWFService) +234
System.ServiceModel.Activation.HttpModule.ProcessRequest(Object sender, EventArgs e) +379
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +148
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272
The AppFabric configuration tool updates the web.config file in at this location only
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config
When building with the "Any CPU" option as I was you must manually edit this file
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\web.config
With these settings (from the Framework64 version)
<connectionStrings>
<add connectionString="Data Source=(local);Initial Catalog=AppFabricMonitoringDB;Integrated Security=True" name="ApplicationServerMonitoringConnectionString" providerName="System.Data.SqlClient" />
<add connectionString="Data Source=(local);Initial Catalog=AppFabricPersistenceDB;Integrated Security=True" name="ApplicationServerWorkflowInstanceStoreConnectionString" providerName="System.Data.SqlClient" />
</connectionStrings>
They were previously set to the default
<connectionStrings>
<add connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=AppFabricMonitoringDB;Integrated Security=True" name="ApplicationServerMonitoringConnectionString" providerName="System.Data.SqlClient" />
<add connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=AppFabricPersistenceDB;Integrated Security=True" name="ApplicationServerWorkflowInstanceStoreConnectionString" providerName="System.Data.SqlClient" />
</connectionStrings>

How can I make NServiceBus Host based windows service wait for SQL Server to start?

I have several NServiceBus Generic Host based windows services installed on the same server as the SQL Server instance that contains my subscription storage database. When the server boots my NServiceBus Host services try to access the subscription storage database before SQL Server is up.
Here's what I've tried so far:
Added a windows server dependency on MSSQLSERVER. This did not solve the problem.
Added a 1 minute sleep in IWantCustomInitialization.Init to verify the cause of the problem described above. This solved the problem but it's a very crude solution.
What is the recommended way to handle this problem?
For reference find my DBSubscriptionStorageConfig and the exception that occurs when my windows services try to start below.
<DBSubscriptionStorageConfig>
<NHibernateProperties>
<add Key="connection.provider" Value="NHibernate.Connection.DriverConnectionProvider"/>
<add Key="connection.driver_class" Value="NHibernate.Driver.SqlClientDriver"/>
<add Key="connection.connection_string" Value="Data Source=.;Initial Catalog=NServiceBus;Integrated Security=SSPI"/>
<add Key="dialect" Value="NHibernate.Dialect.MsSql2008Dialect"/>
</NHibernateProperties>
</DBSubscriptionStorageConfig>
ERROR NHibernate.Tool.hbm2ddl.SchemaUpdate [(null)] <(null)> - could not get database metadata
System.Data.SqlClient.SqlException (0x80131904): Cannot open database "NServiceBus" requested by the login. The login failed.
Login failed for user 'SE1\fooservice'.
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler,
SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject,
TimeoutTimer timeout, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity,
SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options,
Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection,
DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at NHibernate.Connection.DriverConnectionProvider.GetConnection()
at NHibernate.Tool.hbm2ddl.ManagedProviderConnectionHelper.Prepare()
at NHibernate.Tool.hbm2ddl.SchemaUpdate.Execute(Action`1 scriptAction, Boolean doUpdate)
I ended up creating a class which implements IWantCustomInitialization to prevent my windows services from starting before they can connect to the database. The class should probably have some logging code added but it solves my problem for now.
Here's the code.
public class DbDependencyChecker : IWantCustomInitialization
{
private const int ConnectionRetries = 15;
private const int TimeBetweenRetries = 60000;
private const string DefaultConnectionName = "DbDependency";
private const string CustomConnectionNameKey = "DbDependencyConnectionName";
public void Init()
{
var connectionName = ConfigurationManager.AppSettings[CustomConnectionNameKey];
if (string.IsNullOrWhiteSpace(connectionName))
connectionName = DefaultConnectionName;
var providerName = ConfigurationManager.ConnectionStrings[connectionName].ProviderName;
var connectionString = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
if (string.IsNullOrWhiteSpace(providerName) || string.IsNullOrWhiteSpace(connectionString))
return;
for (var i = 0; i < ConnectionRetries; i++)
{
if (TryToConnect(providerName, connectionString))
break;
System.Threading.Thread.Sleep(TimeBetweenRetries);
}
}
private static bool TryToConnect(string providerName, string connectionString)
{
try
{
using (var connection = CreateConnection(providerName, connectionString))
{
connection.Open();
}
return true;
}
catch (Exception)
{
return false;
}
}
private static IDbConnection CreateConnection(string providerName, string connectionString)
{
var provider = DbProviderFactories.GetFactory(providerName);
var connection = provider.CreateConnection();
connection.ConnectionString = connectionString;
return connection;
}
}
The config file would look like this:
<connectionStrings>
<add name="SomeDb" providerName="System.Data.SqlClient" connectionString="connection string" />
</connectionStrings>
<appSettings>
<add key="DbDependencyConnectionName" value="SomeDb"/>
</appSettings>
Or like this:
<connectionStrings>
<add name="DbDependency" providerName="System.Data.SqlClient" connectionString="connection string"/>
</connectionStrings>
does using a startup type for the windows service of Automatic (Delayed Start) fix it? wouldn't think it would require a full minute delay and this might be a little more desirable than having that internal to the application (especially if you someday have the database on another machine and don't have sql server running there.

After upgrading to .Net 4.0, I'm getting the exception "Could not load file or assembly 'System.Windows, Version=2.0.5.0'"

We recently upgraded our web app from 3.5 to 4.0. Now after I login and load a page with Microsoft ScriptManager on it, I get:
Could not load file or assembly 'System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' or one of its dependencies. The system cannot find the file specified.
It only happens the first time, reload the page and everything works.
UPDATE: We have all Silverlight v4 projects.I found the System.Windows.dll in the C:\Program Files\Reference Assemblies\Microsoft\Framework\Silverlight\v4.0 directory. Why would it look for version 2.0?
Here's the entire exception (edited and removed folder paths)
Server Error in '/test' Application.
Could not load file or assembly 'System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' or one of its dependencies. The system cannot find the file specified.
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.IO.FileNotFoundException: Could not load file or assembly 'System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' or one of its dependencies. The system cannot find the file specified.
Source Error:
Line 450: <UC5:PageTitle ID="PageTitle" runat="server" />
Line 451: <UC2:PageTabs ID="testPageTabs" runat="server" />
Line 452: <asp:ScriptManager ID="ScriptManager1" runat="server"/>
Line 453: <div id="step1Div" style="padding-top: 10px; padding-left: 10px" runat="server">
Line 454: <asp:ValidationSummary ID="displayValidationSummary" ValidationGroup="displayCreateEditValidationGroup" runat="server" />
Source File: c:{directories}\Pages\Administration\DisplayCreateEdit.aspx Line: 452
Assembly Load Trace: The following information can be helpful to determine why the assembly 'System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' could not be loaded.
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
Stack Trace:
[FileNotFoundException: Could not load file or assembly 'System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' or one of its dependencies. The system cannot find the file specified.]
System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type) +0
System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext) +180
System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) +192
System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg) +115
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecoratedTargetSecurityTransparent) +426
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType) +103
System.Reflection.RuntimeAssembly.GetCustomAttributes(Boolean inherit) +33
System.Web.UI.AssemblyCache.GetAjaxFrameworkAssemblyAttribute(Assembly assembly) +76
System.Web.UI.ScriptManager.get_DefaultAjaxFrameworkAssembly() +388
System.Web.UI.ScriptManager..ctor() +26
ASP.pages_administration_displaycreateedit_aspx.__BuildControlScriptManager1() in c:{directories}\Pages\Administration\DisplayCreateEdit.aspx:452
ASP.pages_administration_displaycreateedit_aspx.__BuildControlContent1(Control __ctrl) in c:{directories}\Pages\Administration\DisplayCreateEdit.aspx:9
System.Web.UI.CompiledTemplateBuilder.InstantiateIn(Control container) +12
System.Web.UI.MasterPage.InstantiateInContentPlaceHolder(Control contentPlaceHolder, ITemplate template) +87
ASP.master_master.__BuildControlContentPlaceHolder1() in c:{directories}\Master.master:28
ASP.master_master.__BuildControlmasterForm() in c:{directories}\Master.master:13
ASP.master_master.__BuildControlTree(master_master __ctrl) in c:{directories}\Master.master:1
ASP.master_master.FrameworkInitialize() in c:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\zoning\dff1a5fe\99aa3a7f\App_Web_shgw15qp.4.cs:0
System.Web.UI.UserControl.InitializeAsUserControlInternal() +35
System.Web.UI.MasterPage.CreateMaster(TemplateControl owner, HttpContext context, VirtualPath masterPageFile, IDictionary contentTemplateCollection) +8832342
System.Web.UI.Page.get_Master() +54
System.Web.UI.Page.ApplyMasterPage() +15
System.Web.UI.Page.PerformPreInit() +45
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +328
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1
And the system.web of our web.config:
<system.web>
<pages validateRequest="false" buffer="true" theme="Summer" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
<controls>
<add namespace="AjaxControlToolkit" assembly="AjaxControlToolkit" tagPrefix="ajaxToolkit"/>
</controls>
<tagMapping>
<add tagType="System.Web.UI.WebControls.TextBox" mappedTagType="CleanTextBox"/>
<add tagType="System.Web.UI.HtmlControls.HtmlTextArea" mappedTagType="CleanTextArea"/>
</tagMapping>
</pages>
<compilation debug="true" targetFramework="4.0">
<assemblies>
</assemblies>
</compilation>
<authentication mode="Forms">
<forms requireSSL="false" cookieless="UseDeviceProfile" loginUrl="~/Pages/Authentication/Login.aspx" timeout="60" defaultUrl="~/Pages/Authentication/AccountHome.aspx" slidingExpiration="true" name="sqlAuthCookie" protection="All"/>
</authentication>
<sessionState timeout="60" mode="StateServer" stateConnectionString="tcpip=localhost" stateNetworkTimeout="60" cookieless="false"/>
<customErrors mode="RemoteOnly" defaultRedirect="~/Pages/Global/DefaultError.aspx">
<error statusCode="404" redirect="~/Pages/Global/404.htm"/>
<error statusCode="403" redirect="~/Pages/Global/403.htm"/>
</customErrors>
<httpHandlers>
<add path="*js.axd" verb="*" type="ScriptCompressorHandler"/>
<add path="*css.axd" verb="*" type="CssCompressorHandler"/>
<add path="*css" verb="*" type="CssCompressorHandler"/>
<add verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</httpHandlers>
<httpModules>
<remove name="WindowsAuthentication"/>
<remove name="PassportAuthentication"/>
<remove name="AnonymousIdentification"/>
<remove name="RoleManager"/>
<remove name="Profile"/>
<remove name="ErrorHandlerModule"/>
<add type="ScriptCompressorModule" name="ScriptCompressorModule"/>
<add type="CssCompressorModule" name="CssCompressorModule"/>
</httpModules>
<machineKey validationKey="{key}" decryptionKey="{key}" validation="SHA1"/>
<httpRuntime maxRequestLength="1048576" executionTimeout="3600" requestValidationMode="2.0"/>
</system.web>
See the same problem here and Microsoft Feedback/Bug report
Edit: I'm running VS 2010, XP with IIS 5.0 (I miss Win 7 at work every day :-)). We have the web app running under the local IIS instance, not Cassini. We deployed it to a test server and I did not see the exception. After I installed the C:\Program Files\Reference Assemblies\Microsoft\Framework\Silverlight\v4.0\System.windows.dll to the GAC and then removed it and haven't seen the same exception, though my colleague hasn't done this and still sees it occasionally. I think it only happens when the app is restarted (which happens every time we rebuild the app when developing locally).
Sounds like one of the projects in your solution is referencing the v2 system assemblies. Make sure that all of your projects and application pools are set to use 4.0. You can set this in the project properties in Visual Studio.
(Note that you'll have to rebuild your solution with the new settings if you haven't already).
I have been having the same issues for a long time, but just found some old Silverlight Assemblies in my bin folder, removed those and voila.. error gone
Adding reference to AjaxControlToolkit.dll and adding the header
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
to the aspx that contains the script manager solved the problem for me.