in mvc3 razor i get error Loading this assembly would produce a different grant set from other instances. (Exception from HRESULT: 0x80131401) - asp.net-mvc-3-areas

I am working on mvc3 razor application firstly my project was runing correctly but after replacement of system.web.mvc.dll and System.Web.WebPages.Razor files from mvc4 folder to mvc3 folder it will give following error while run it.
Loading this assembly would produce a different grant set from other instances. (Exception from HRESULT: 0x80131401)
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.FileLoadException: Loading this assembly would produce a different grant set from other instances. (Exception from HRESULT: 0x80131401)
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:
[FileLoadException: Loading this assembly would produce a different grant set from other instances. (Exception from HRESULT: 0x80131401)]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +192
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +108
System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures) +324
System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +132
System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath) +90
System.Web.Compilation.BuildManager.ExecutePreAppStart() +135
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +516
[HttpException (0x80004005): Loading this assembly would produce a different grant set from other instances. (Exception from HRESULT: 0x80131401)]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9873912
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +456
my web.config settings are as under
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.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=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
Please provide me help to resolve it.

I faced the same problem, I fixed it in web.config:
<system.web>
...
<trust level="Full" />
</system.web>

Related

Provider error after migrating from SQL Server Compact 4.0 to SQL Server Express

We decided to migrate from SQL Server Compact to SQL Server Express (possibly LocalDB) as Compact is no longer supported and we believe Express is more feature rich and likely performs better.
I made the changes necessary (although clearly missed something :) ) and the database is recreated as an .mdf file. The problem seems to be when the database is accessed. I get the error I have pasted below. The upshot is that somehow, somewhere I seem to have a reference to a provider with invariant name System.Data.SqlServerCe.4.0 when I have no intention of doing so.
I have done research and found these two relevant posts, which are not fully answered:
MVC app erroring on SqlServerCe.4.0 provider after converting to Sql Express
and
Entity Framework using the wrong connection provider
I have tried deleting the migrations and have modified the app.config file. I have also deleted on references to SQL Server Compact from the project references. What else should I be looking at? I'm tearing my hair out over this one.
What other information can I provide?
Thanks,
Dave
P.S. Another way to ask the question would be pointing out that https://stackoverflow.com/users/183934/erikej commented in the links above:
"Obviously you reference sqlce somewhere, either in .settings or in code based configuration DbConfiguration class... – ErikEJ Sep 13 '14 at 6:09 "
Where are all possible places that Compact could be referenced?
Exception thrown: 'System.Data.DataException' in EntityFramework.dll
Exception thrown: 'System.Data.DataException' in mscorlib.dll
The thread 0x2df0 has exited with code 0 (0x0).
05.01.2017 21:50:50: Fatal [line: 18 StartupErrorViewModel -> .ctor()]: System.Data.DataException: An exception occurred while initializing the database. See the InnerException for details.
System.Data.Entity.Core.MetadataException: Schema specified is not valid. >
Errors:
(0,0) : error 0152: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlServerCe.4.0'. Make sure the provider is registered in the 'entityFramework' section of the application config file. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.
at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection.Loader.ThrowOnNonWarningErrors()
at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection.Loader.LoadItems(IEnumerable1 xmlReaders, IEnumerable1 sourceFilePaths)
at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection.Loader..ctor(IEnumerable1 xmlReaders, IEnumerable1 sourceFilePaths, Boolean throwOnError, IDbDependencyResolver resolver)
at System.DThe thread 0x6d84 has exited with code 0 (0x0).
ata.Entity.Core.Metadata.Edm.StoreItemCollection.Init(IEnumerable1 xmlReaders, IEnumerable1 filePaths, Boolean throwOnError, IDbDependencyResolver resolver, DbProviderManifest& providerManifest, DbProviderFactory& providerFactory, String& providerInvariantName, String& providerManifestToken, Memoizer2& cachedCTypeFunction)
at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection..ctor(IEnumerable1 xmlReaders)
at System.Data.Entity.Utilities.XDocumentExtensions.GetStorageMappingItemCollection(XDocument model, DbProviderInfo& providerInfo)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(XDocument sourceModel, XDocument targetModel, Lazy1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
at System.Data.Entity.Internal.InternalContext.ModelMatches(VersionedModel model)
at System.Data.Entity.Internal.ModelCompatibilityChecker.CompatibleWithModel(InternalContext internalContext, ModelHashCalculator modelHashCalculator, Boolean throwIfNoMetadata, DatabaseExistenceState existenceState)
at System.Data.Entity.Internal.InternalContext.CompatibleWithModel(Boolean throwIfNoMetadata, DatabaseExistenceState existenceState)
at System.Data.Entity.CreateDatabaseIfNotExists1.InitializeDatabase(TContext context)
at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf1.<CreateInitializationAction>b__e()
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
--- End of inner exception stack trace ---
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
at System.Data.Entity.Internal.RetryAction1.PerformAction(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action1 action)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet1.GetEnumerator()
at System.Data.Entity.Infrastructure.DbQuery1.System.Collections.Generic.IEnumerable.GetEnumerator()
at System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source)
at Med.Vax.DataAccess.Repositories.LocalDbRepository1.GetAll() in C:\MedRepo\vax-box-sw\App\DataAccess\Repositories\LocalDbRepository.cs:line 68
at Med.Vax.App.d__28.MoveNext() in C:\MedRepo\vax-box-sw\App\App\App.xaml.cs:line 198
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task ta'Vax.exe' (CLR v4.0.30319: Vax.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\PresentationFramework-SystemXmlLinq\v4.0_4.0.0.0__b77a5c561934e089\PresentationFramework-SystemXmlLinq.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Vax.exe' (CLR v4.0.30319: Vax.exe): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\PresentationFramework-SystemCore\v4.0_4.0.0.0__b77a5c561934e089\PresentationFramework-SystemCore.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
sk)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Med.Vax.App.d__30.MoveNext() in C:\MedRepo\vax-box-sw\App\App\App.xaml.cs:line 503
ADDITIONAL INFO BASED ON COMMENTS
There are two app.config files, and perhaps this is part of the problem. One in the main app part, and one in the data access layer. Notice the code that is commented out with <!-- --> I asssume this is perfectly fine to do as these are just xml files?
Here's the one in the main app:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="TruMed.AccuVax.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="LoggingVerbosity" value="Debug" />
<add key="StartMaximized" value="True" />
<add key="AllowMultipleInstances" value="False" />
<add key="ScreenSaverTimeoutSeconds" value="60" />
<add key="TranslationFile" value="Translation\TranslationData.xml" />
<add key="SoftwareUpgradeDirectory" value="C:\TruMed\SoftwareUpgrade" />
<add key="FirmwareUpgradeDirectory" value="C:\TruMed\FirmwareUpgrade" />
<add key="PerformDatabaseMaintenance" value="False" />
<add key="AWSRegion" value="us-west-2"/>
<add key="AWSProfilesLocation" value="C:\TruMed\AccuVax\credentials"/>
</appSettings>
<!--
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
<parameters>
<parameter value="System.Data.SqlServerCe.4.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="System.Data.SqlServerCe.4.0" type="System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact" />
</providers>
</entityFramework>
<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.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<userSettings>
<TruMed.AccuVax.Properties.Settings>
<setting name="RobotZParkingLocation" serializeAs="String">
<value>0</value>
</setting>
</TruMed.AccuVax.Properties.Settings>
</userSettings>
</configuration>
and here is the one from the data access layer:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<!--
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
<parameters>
<parameter value="System.Data.SqlServerCe.4.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="System.Data.SqlServerCe.4.0" type="System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact" />
</providers>
</entityFramework>
<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.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
Except for the commented out sections, I do not believe I am mentioning SQL Server Compact!
ADDITIONAL INFO IN RESPONSE TO COMMENTS 2
The configuration string used is pulled from a .json file and looks like this:
LocalDbConnection:
Server=(LocalDB)\\MSSQLLocalDB;Integrated Security=true;Initial Catalog=Vax3
Previously I was using:
Data Source=C:\ProgramData\TruMed\AccuVax\AccuVax.sdf;
Clearly there is some concern I'm using the wrong connection string and/or adapter as I'm getting messages about SQL Server Compact. I have searched the code for AccuVax.sdf and have not found any instances. Again, database is created no problem; the problem seems to be accessing it.
We also had the same problem. We tried to migrate from SQL Compact to SQL Express. We chased and removed any reference to SQL Compact in the solution but that was not enough.
Our final move was to clean completely the solution (any visual studio that are not needed to open the solution):
remove obj, debug, release...
remove .vs folder (that's probably the one)
Finally we reopened the solution, tried again and got it work.
Hope it helps.

Entity Framework Migrations Issue: DbMigrationsConfiguration`1' threw an exception

I can enable migrations, but i cannot update DB or add a migration. When i try to disable-migrations to then re-enable i get
"The term 'disable-migrations' is not recognized ", I have tried removing the package and reinstalling running as admin, changing App.config lines.
I have the same issue at my work pc and my home one, Ive read a lot of posts on here and the suggestions have not fixed my issue. no matter what i do when it comes to modifying I always get this error (adding migration,updating db etc)
PM> add-migration TTT
System.TypeInitializationException: The type initializer for 'System.Data.Entity.Migrations.DbMigrationsConfiguration`1' threw an exception. ---> System.TypeInitializationException: The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception. ---> System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize ---> System.Configuration.ConfigurationErrorsException: Unrecognized configuration section connectionString. (C:\Users\bern4rdo\Desktop\BasicEntityApp\tmp9260.tmp line 8)
at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors)
at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
--- End of inner exception stack trace ---
at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
at System.Configuration.ClientConfigurationSystem.PrepareClientConfigSystem(String sectionName)
at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
at System.Configuration.ConfigurationManager.get_ConnectionStrings()
at System.Data.Entity.Internal.AppConfig..ctor()
at System.Data.Entity.Internal.AppConfig..cctor()
--- End of inner exception stack trace ---
at System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationManager.EnsureLoadedForAssembly(Assembly assemblyHint, Type contextTypeHint)
at System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationManager.EnsureLoadedForContext(Type contextType)
at System.Data.Entity.Migrations.DbMigrationsConfiguration`1..cctor()
--- End of inner exception stack trace ---
at System.Data.Entity.Migrations.DbMigrationsConfiguration`1..ctor()
at BasicEntityApp.Migrations.Configuration..ctor() in C:\Users\bern4rdo\Desktop\BasicEntityApp\Migrations\Configuration.cs:line 10
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Data.Entity.Migrations.Utilities.MigrationsConfigurationFinder.FindMigrationsConfiguration(Type contextType, String configurationTypeName, Func`2 noType, Func`3 multipleTypes, Func`3 noTypeWithName, Func`3 multipleTypesWithName)
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.FindConfiguration()
at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Scaffold(String migrationName, String language, String rootNamespace, Boolean ignoreChanges)
at System.Data.Entity.Migrations.AddMigrationCommand.Execute(String name, Boolean force, Boolean ignoreChanges)
at System.Data.Entity.Migrations.AddMigrationCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
The type initializer for ***'System.Data.Entity.Migrations.DbMigrationsConfiguration`1' threw an exception.**
PM>*
I have checked the file it references in
C:\Users\bern4rdo\Desktop\BasicEntityApp\Migrations\Configuration.cs:line 10
which line 10 is the conneciton string. I have included the app config file below but if I'm able to get a good direction on what to do next, i would appreciate it a lot. I have ruled out things like permissions, ive tried different servers etc
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<connectionString>
<add name="SalesContext" connectionstring="DataSource=BERNARDO\SQLEXPRESS; Initial Catalogue=BasicEntityApp; trusted security=true; trustedserverCertificate=false;" providername="System.Data.sqlClient" />
</connectionString>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
<parameters>
<parameter value="System.Data.SqlServerCe.4.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="System.Data.SqlServerCe.4.0" type="System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact" />
</providers>
</entityFramework>
<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>
</configuration>
Your config section is incorrectly named <connectionString> when it should in fact be <connectionStrings>:
<connectionStrings>
<add name="SalesContext" connectionstring="DataSource=BERNARDO\SQLEXPRESS; Initial Catalogue=BasicEntityApp; trusted security=true; trustedserverCertificate=false;" providername="System.Data.sqlClient" />
</connectionStrings>

Entity Framework Migrations: error on web server only

error 0175: The specified store provider cannot be found in the configuration, or is not valid
I am using Entity Framework Code-First Migrations and everything is great locally.
My DB is SQLServer 2008. (Also using SQL CE for local development)
I can use the live SQL Server db connection string locally with no problem.
Here is the Migration code in _appStart.cshtml:
#using EF = System.Data.Entity;
#using TCommon = Told.Web.Common.Logic;
#{
// Manually initialize
var initializer = new EF.MigrateDatabaseToLatestVersion<TCommon.CommonContext, TCommon.Migrations.Configuration>();
System.Data.Entity.Database.SetInitializer(initializer);
initializer.InitializeDatabase(new TCommon.CommonContext());
// DB Maintenance
TCommon.AppUserLogic.CleanDatabase();
// Asp.Net
WebSecurity.InitializeDatabaseConnection("ToldDB", "UserProfile", "UserId", "Email", true);
// Common
TCommon.AppStart.Run();
}
This works great locally. Either against a SQL CE or against my live database. It ran fine locally to migrate my live database to the latest version.
However, when I put it on my web server, it throws this exception:
Exception
Server Error in '/' Application.
Schema specified is not valid. Errors:
(0,0) : error 0175: The specified store provider cannot be found in the configuration, or is not valid.
[MetadataException: Schema specified is not valid. Errors:
(0,0) : error 0175: The specified store provider cannot be found in the configuration, or is not valid.]
System.Data.Metadata.Edm.Loader.ThrowOnNonWarningErrors() +8566285
System.Data.Metadata.Edm.Loader.LoadItems(IEnumerable`1 xmlReaders, IEnumerable`1 sourceFilePaths) +181
System.Data.Metadata.Edm.StoreItemCollection.Init(IEnumerable`1 xmlReaders, IEnumerable`1 filePaths, Boolean throwOnError, DbProviderManifest& providerManifest, DbProviderFactory& providerFactory, String& providerManifestToken, Memoizer`2& cachedCTypeFunction) +211
System.Data.Metadata.Edm.StoreItemCollection..ctor(IEnumerable`1 xmlReaders) +295
System.Data.Entity.Migrations.Extensions.XDocumentExtensions.GetStoreItemCollection(XDocument model, DbProviderInfo& providerInfo) +180
System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(XDocument sourceModel, XDocument targetModel, String connectionString) +48
System.Data.Entity.Migrations.DbMigrator.IsModelOutOfDate(XDocument model, DbMigration lastMigration) +55
System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId) +269
System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration) +456
System.Data.Entity.MigrateDatabaseToLatestVersion`2.InitializeDatabase(TContext context) +64
Now, this has something to do with the migration attempt. So when I wrap the migration call in a try-catch block, I can use the database fine (because I migrated the live db locally).
#using EF = System.Data.Entity;
#using TCommon = Told.Web.Common.Logic;
#{
// Manually initialize
var initializer = new EF.MigrateDatabaseToLatestVersion<TCommon.CommonContext, TCommon.Migrations.Configuration>();
System.Data.Entity.Database.SetInitializer(initializer);
try
{
initializer.InitializeDatabase(new TCommon.CommonContext());
}
catch (Exception ex)
{
}
var db = new TCommon.CommonContext();
var test = db.AppUsers.FirstOrDefault();
// DB Maintenance
TCommon.AppUserLogic.CleanDatabase();
// Asp.Net
WebSecurity.InitializeDatabaseConnection("ToldDB", "UserProfile", "UserId", "Email", true);
// Common
TCommon.AppStart.Run();
}
What would be causing the migration diff-check to fail when I try to run it on my web server?
Edit:
Here is the web.config for the Entity Framework:
<configuration>
<configSections>
...
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
</configSections>
...
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>
</entityFramework>
<system.web>
<trace enabled="true" requestLimit="40" localOnly="false" pageOutput="true" />
<customErrors mode="Off"/>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</assemblies>
</compilation>
</system.web>
...
<connectionStrings>
<add name="ToldDB" connectionString="..." providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
I have now found the answer:
Make sure that you install these nuget-packages:
Microsoft.SqlServer.Compact and
EntityFramework.SqlServerCompact
Deploy again, and make sure that SQL Server CE is now in the \bin-folder (the folders x86 and amd64 with all the files).
And also these files must be in the bin-folder:
System.Data.SqlServerCe.dll
System.Data.SqlServerCe.Entity.dll
Make sure it is the right version. The ones that are installed with SQL Ce did not work, it must be the ones from the nuget package.
Also make sure the Web.config contains this:
<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>
And this:
<dependentAssembly>
<assemblyIdentity name="System.Data" publicKeyToken="b77a5c561934e089" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
Note that you have to do this no matter if you use SqlCE on the production server. I am not sure you need the bin-files for the database itself, though.

Enterprise library 5.0 log to sql server not working

I'm having problems with logging into sql server 2008 Express using Enterprise Library 5.0
It works in my development environment (VS2010) but NOT on my Server 2008/SQL Server 2008 Express.
To make sure it was not the database I also tested with a flat file. Did not work either.
Both files are present in my bin directory.
Microsoft.Practices.EnterpriseLibrary.Logging.dll
Microsoft.Practices.EnterpriseLibrary.Logging.Database.dll
My web.config looks like this:
<configSections>
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="Space4it.Registertime.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<loggingConfiguration name="" tracingEnabled="true" defaultCategory="General">
<listeners>
<add name="Database Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
databaseInstanceName="TimeseddelLogging" writeLogStoredProcName="WriteLog"
addCategoryStoredProcName="AddCategory" formatter="Text Formatter"
traceOutputOptions="LogicalOperationStack, DateTime, Timestamp" />
</listeners>
<formatters>
<add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
template="Timestamp: {timestamp}{newline}
Message: {message}{newline}
Category: {category}{newline}
Priority: {priority}{newline}
EventId: {eventid}{newline}
Severity: {severity}{newline}
Title:{title}{newline}
Machine: {localMachine}{newline}
App Domain: {localAppDomain}{newline}
ProcessId: {localProcessId}{newline}
Process Name: {localProcessName}{newline}
Thread Name: {threadName}{newline}
Win32 ThreadId:{win32ThreadId}{newline}
Extended Properties: {dictionary({key} - {value}{newline})}"
name="Text Formatter" />
</formatters>
<categorySources>
<add switchValue="All" name="General">
<listeners>
<add name="Database Trace Listener" />
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events">
<listeners>
<add name="Database Trace Listener" />
</listeners>
</allEvents>
<notProcessed switchValue="All" name="Unprocessed Category" />
<errors switchValue="All" name="Logging Errors & Warnings">
<listeners>
<add name="Database Trace Listener" />
</listeners>
</errors>
</specialSources>
</loggingConfiguration>
<connectionStrings>
<add name="TimeseddelLogging" connectionString="Data Source=server\sqlexpress;Initial Catalog=logging.database;User ID=username;pwd=password"/>
</connectionStrings>
I connected manually (as a test) using this user and I'm able to enter data in the log table with this user.
I get this error:
Exception:
Message:
Activation error occured while trying to get instance of type LogWriter, key ""
Stack:
at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key) at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstanceTService at Microsoft.Practices.EnterpriseLibrary.Logging.Logger.get_Writer() at Space4it.Common.Log.Log.DoLog(String message, String category, Dictionary`2 metaData, Exception ex, TraceEventType type, LogPriority priority, Int32 eventId) at Space4it.Registertime.Pages.TestForm.ButtonTest_Click(Object sender, EventArgs e)
Inner Exception:
Message:
Resolution of the dependency failed, type = "Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter", name = "(none)". Exception occurred while: while resolving. Exception is: InvalidOperationException - The type Database cannot be constructed. You must configure the container to supply this value. ----------------------------------------------- At the time of the exception, the container was: Resolving Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterImpl,LogWriter.default (mapped from Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter, (none)) Resolving parameter "structureHolder" of constructor Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterImpl(Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterStructureHolder structureHolder, Microsoft.Practices.EnterpriseLibrary.Logging.Instrumentation.ILoggingInstrumentationProvider instrumentationProvider, Microsoft.Practices.EnterpriseLibrary.Logging.ILoggingUpdateCoordinator updateCoordinator) Resolving Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterStructureHolder,LogWriterStructureHolder.default (mapped from Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterStructureHolder, (none)) Resolving parameter "traceSources" of constructor Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterStructureHolder(System.Collections.Generic.IEnumerable1[[Microsoft.Practices.EnterpriseLibrary.Logging.Filters.ILogFilter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]] filters, System.Collections.Generic.IEnumerable1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] traceSourceNames, System.Collections.Generic.IEnumerable1[[Microsoft.Practices.EnterpriseLibrary.Logging.LogSource, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]] traceSources, Microsoft.Practices.EnterpriseLibrary.Logging.LogSource allEventsTraceSource, Microsoft.Practices.EnterpriseLibrary.Logging.LogSource notProcessedTraceSource, Microsoft.Practices.EnterpriseLibrary.Logging.LogSource errorsTraceSource, System.String defaultCategory, System.Boolean tracingEnabled, System.Boolean logWarningsWhenNoCategoriesMatch, System.Boolean revertImpersonation) Resolving Microsoft.Practices.EnterpriseLibrary.Logging.LogSource,General Resolving parameter "traceListeners" of constructor Microsoft.Practices.EnterpriseLibrary.Logging.LogSource(System.String name, System.Collections.Generic.IEnumerable1[[System.Diagnostics.TraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] traceListeners, System.Diagnostics.SourceLevels level, System.Boolean autoFlush, Microsoft.Practices.EnterpriseLibrary.Logging.Instrumentation.ILoggingInstrumentationProvider instrumentationProvider) Resolving Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.ReconfigurableTraceListenerWrapper,Database Trace Listener (mapped from System.Diagnostics.TraceListener, Database Trace Listener) Resolving parameter "wrappedTraceListener" of constructor Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.ReconfigurableTraceListenerWrapper(System.Diagnostics.TraceListener wrappedTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.ILoggingUpdateCoordinator coordinator) Resolving Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener,Database Trace Listener‌implementation (mapped from System.Diagnostics.TraceListener, Database Trace Listener‌implementation) Resolving parameter "database" of constructor Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener(Microsoft.Practices.EnterpriseLibrary.Data.Database database, System.String writeLogStoredProcName, System.String addCategoryStoredProcName, Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.ILogFormatter formatter) Resolving Microsoft.Practices.EnterpriseLibrary.Data.Database,TimeseddelLogging
Inner exception Stack:
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable1 resolverOverrides) at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name, IEnumerable1 resolverOverrides) at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key)
Hope someone can help me :-)
Have a nice day!
The error you're getting is indicating that Entlib hasn't initialized itself properly. The database is a red herring - you haven't gotten the logging block working at all right now.
Is the logging section defined in the <configSections> element of your web.config file?
Update:
You added your configSections element, but what you posted is malformed: <configSections></sectionGroup>. If that's accurate, then that's the problem, malformed config. Fix the close tag and it should start working.

Database Trace Listener with Enterprise library 2.0 not logging in database

I am using Database TraceListener for logging. I've executed the CreateLoggingDb.cmd and the Logging Database is in place. My web.config looks like the below.
When an excpetion occurs I try to log it as below.
ExceptionPolicy.HandleException(ex, "PayrollException");
The code runs but it does not log in the database table. Please let me know if the settings in web.config are not correct or the procedure for logging has to be different.
<configuration>
<configSections>
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"/>
<section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"/>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</configSections>
<loggingConfiguration name="Logging Application Block" tracingEnabled="true" defaultCategory="General" logWarningsWhenNoCategoriesMatch="true">
<listeners>
<add databaseInstanceName="LoggingConn" writeLogStoredProcName="WriteLog"
addCategoryStoredProcName="AddCategory" formatter="Text Formatter"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
traceOutputOptions="None" type="Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
name="Database Trace Listener" />
</listeners>
<formatters>
<add template="Timestamp: {timestamp}
Message: {message}
Category: {category}
Priority: {priority}
EventId: {eventid}
Severity: {severity}
Title:{title}
Machine: {machine}
Application Domain: {appDomain}
Process Id: {processId}
Process Name: {processName}
Win32 Thread Id: {win32ThreadId}
Thread Name: {threadName}
Extended Properties: {dictionary({key} - {value}
)}" type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" name="Text Formatter"/>
</formatters>
<categorySources>
<add switchValue="All" name="General">
<listeners>
<add name="Database TraceListener"/>
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events"/>
<notProcessed switchValue="All" name="Unprocessed Category"/>
<errors switchValue="All" name="Logging Errors & Warnings">
<listeners>
<add name="Database TraceListener"/>
</listeners>
</errors>
</specialSources>
</loggingConfiguration>
<exceptionHandling>
<exceptionPolicies>
<add name="PayrollException">
<exceptionTypes>
<add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" postHandlingAction="NotifyRethrow" name="Exception">
<exceptionHandlers>
<add exceptionMessage="Payroll Application Exception" wrapExceptionType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionHandlingException, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WrapHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" name="Wrap Handler"/>
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
</exceptionPolicies>
</exceptionHandling>
<connectionStrings>
<add name="Conn" connectionString="Database=Payroll;Server=10.135.158.211;User Id=xanoneappusr;Password=vivekm123;" providerName="System.Data.SqlClient"/>
<add name="LoggingConn" connectionString="Database=Logging;Server=10.135.158.211;User Id=xanoneappusr;Password=vivekm123;" providerName="System.Data.SqlClient"/>
</connectionStrings>
<appSettings>
<add key="PayrollApplication" value="Payroll"/>
</appSettings>
<system.web>
<compilation debug="true" batch="false">
<assemblies>
<add assembly="System.Management, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="System.Configuration.Install, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/></assemblies></compilation>
<roleManager enabled="true"/>
<authentication mode="Forms"/>
<membership>
<providers>
<clear/>
<add connectionStringName="Conn" minRequiredPasswordLength="5" minRequiredNonalphanumericCharacters="0" applicationName="PayrollApplication" name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider"/>
</providers>
</membership>
</system.web>
</configuration>#x#
A few places to start looking are:
Did you use EntLibConfig.exe to build the web.config? This is an exe that comes with Enterprise Library, you should find it in the Bin directory of the Enterprise Library install in Program Files - it gives you a reasonably intuitive graphical interface to set up enterprise library for an application: just point it at the config file for your application and set up the things you want.
For database logging you need to configure your connection strings using the Data Access Application Block - you will need another section in your config file for this.
For your database connection string, what authenticaion mode are you using? Does the user identity running the application have write access to the logging database?
Do you have other database connectivity?
Also - if you are running the .Net framework 3.5 you should consider using version 4.1 of the Enterprise Library.
EDIT after config file supplied
Looking at the config file you've attached (you may want to remove the passwords by the way) I think that you are missing a logging exception handler - the only exception handler you appear to have is a wrap exception handler.
Below is an example of one of one of my exception handling policies (from 4.1 of the Enterprise Library but yours should be similar).
<exceptionPolicies>
<add name="Data Layer Policy">
<exceptionTypes>
<add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="NotifyRethrow" name="Exception">
<exceptionHandlers>
<add logCategory="DataLayer" eventId="100" severity="Error" title="Data Layer Exception"
formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
priority="0" useDefaultLogger="false" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="Logging Handler" />
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
</exceptionPolicies>
The wrap handler is used where you want to wrap one exception around another. You can have both a logging handler and a wrap handler if that is needed - the logging handlers fire before the wrapping ones.