Intermittent Entity framework 3.4 error in hosted environment (medium trust) - frameworks

I have an application that is being hosted in medium trust environment (godaddy). I am getting strange problem that occurs periodically when I am trying to use the application.
Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
I have read a bunch of other posts that talk about issues running in a medium trust environment. My question really goes to trying to understand why it works sometimes and other times I get the above message. When error occurs it will eventually correct itself. And obvously if I recycle IIS that fixes is as well. I'm hoping their is a workaround for this.
Based on the callstack it looks like it related to esablishing the connection and trying to load the MetadataWorkspace from my assembly. My MetadataWorkspace is contained in my App_Code folder for my web app.
Partial Callstack:
System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
at System.Security.CodeAccessPermission.Demand()
at System.Reflection.Assembly.VerifyCodeBaseDiscovery(String codeBase)
at System.Reflection.Assembly.GetName(Boolean copiedName)
at System.Reflection.Assembly.GetName()
at System.Data.Metadata.Edm.DefaultAssemblyResolver.AssemblyComparer`1.Equals(T x, T y)
at System.Collections.Generic.HashSet`1.AddIfNotPresent(T value)
at System.Collections.Generic.HashSet`1.Add(T item)
at System.Data.Metadata.Edm.DefaultAssemblyResolver.GetAllDiscoverableAssemblies()
at System.Data.Metadata.Edm.DefaultAssemblyResolver.GetWildcardAssemblies()
at System.Data.Metadata.Edm.MetadataArtifactLoaderCompositeResource.LoadResources(String assemblyName, String resourceName, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)
at System.Data.Metadata.Edm.MetadataArtifactLoaderCompositeResource.CreateResourceLoader(String path, ExtensionCheck extensionCheck, String validExtension, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)
at System.Data.Metadata.Edm.MetadataArtifactLoader.Create(String path, ExtensionCheck extensionCheck, String validExtension, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)
at System.Data.EntityClient.EntityConnection.SplitPaths(String paths)
at System.Data.EntityClient.EntityConnection.GetMetadataWorkspace(Boolean initializeAllCollections)
at System.Data.Objects.ObjectContext.RetrieveMetadataWorkspaceFromConnection()
at System.Data.Objects.ObjectContext..ctor(EntityConnection connection, Boolean isConnectionConstructor)
at System.Data.Objects.ObjectContext..ctor(String connectionString, String defaultContainerName)
I there a workaround for this?

Related

Unexpected exception chain after updating EF 6.x

I updated from EF6.2 to EF6.4 and I encountered this exception chain:
[VerificationException: Operation could destabilize the runtime.]
System.Data.Entity.Core.Metadata.Edm.FacetDescription.Validate(String declaringTypeName) +70
System.Data.Entity.Core.Metadata.Edm.FacetDescription..ctor(String facetName, EdmType facetType, Nullable`1 minValue, Nullable`1 maxValue, Object defaultValue, Boolean isConstant, String declaringTypeName) +103
System.Data.Entity.Core.SchemaObjectModel.FacetDescriptionElement.CreateAndValidateFacetDescription(String declaringTypeName) +115
System.Data.Entity.Core.SchemaObjectModel.TypeElement.ResolveTopLevelNames() +119
System.Data.Entity.Core.SchemaObjectModel.Schema.ResolveTopLevelNames() +206
System.Data.Entity.Core.SchemaObjectModel.Schema.Resolve() +16
System.Data.Entity.Core.SchemaObjectModel.SchemaManager.ParseAndValidate(IEnumerable`1 xmlReaders, IEnumerable`1 sourceFilePaths, SchemaDataModelOption dataModel, AttributeValueNotification providerNotification, AttributeValueNotification providerManifestTokenNotification, ProviderManifestNeeded providerManifestNeeded, IList`1& schemaCollection) +554
System.Data.Entity.Core.SchemaObjectModel.SchemaManager.ParseAndValidate(IEnumerable`1 xmlReaders, IEnumerable`1 sourceFilePaths, SchemaDataModelOption dataModel, DbProviderManifest providerManifest, IList`1& schemaCollection) +156
System.Data.Entity.Core.SchemaObjectModel.SchemaManager.LoadProviderManifest(XmlReader xmlReader, String location, Boolean checkForSystemNamespace, Schema& schema) +151
System.Data.Entity.Core.Common.DbXmlEnabledProviderManifest.Load(XmlReader reader) +75
System.Data.Entity.Core.Common.DbXmlEnabledProviderManifest..ctor(XmlReader reader) +116
System.Data.Entity.SqlServer.SqlProviderManifest..ctor(String manifestToken) +37
System.Data.Entity.SqlServer.<>c.<GetDbProviderManifest>b__29_0(String s) +25
System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) +65
System.Data.Entity.SqlServer.SqlProviderServices.GetDbProviderManifest(String versionHint) +125
System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifest(String manifestToken) +55
[ProviderIncompatibleException: The provider did not return a ProviderManifest instance.]
System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifest(String manifestToken) +187
System.Data.Entity.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection connection, DbProviderManifest& providerManifest) +119
System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection) +43
System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) +159
System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input) +124
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +678
System.Data.Entity.Internal.InternalContext.Initialize() +20
Website.Db.Context..ctor(DbConnection Connection) in Context.vb:15
Website._Default.GetNewsItems() in Default.aspx.vb:13
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +92
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +191
System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +19
lambda_method(Closure , MethodInfo , Object , Object[] ) +39
System.Web.UI.WebControls.ModelDataSourceView.InvokeMethod(ModelDataSourceMethod method, Boolean isAsyncMethod) +326
System.Web.UI.WebControls.ModelDataSourceView.InvokeMethod(ModelDataSourceMethod method) +7
System.Web.UI.WebControls.ModelDataSourceView.GetSelectMethodResult(DataSourceSelectArguments arguments) +68
System.Web.UI.WebControls.ModelDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) +14
System.Web.UI.WebControls.Repeater.GetData() +233
System.Web.UI.WebControls.Repeater.CreateControlHierarchy(Boolean useDataSource) +207
System.Web.UI.WebControls.Repeater.OnDataBinding(EventArgs e) +62
System.Web.UI.WebControls.Repeater.DataBind() +131
System.Web.UI.WebControls.Repeater.EnsureDataBound() +114
System.Web.UI.WebControls.Repeater.OnPreRender(EventArgs e) +16
System.Web.UI.Control.PreRenderRecursiveInternal() +166
System.Web.UI.Control.PreRenderRecursiveInternal() +236
System.Web.UI.Control.PreRenderRecursiveInternal() +236
System.Web.UI.Control.PreRenderRecursiveInternal() +236
System.Web.UI.Control.PreRenderRecursiveInternal() +236
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4722
Here's line 15 of Context.vb:
Database.SetInitializer(New MigrateDatabaseToLatestVersion(Of Context, Migrations.Configuration))
A pretty straightforward database call, I'd say.
However, when I bumped back down to EF6.2, the error stopped.
I'm finding plenty of references to the individual exceptions here on SO, but nothing I've found so far quite fits the context of the combination of the three taken together with what the code is doing (general database access).
Do I need to alter my DAL code somehow in order to accommodate the EF6.4 update? Were there some breaking changes?
--EDIT--
Running locally under an explicit setting of Medium Trust, I get a different chain:
[PolicyException: Execution permission cannot be acquired.]
System.Security.CodeAccessSecurityEngine.TryResolveGrantSet(Evidence evidence, PermissionSet& grantSet) +14092083
System.Security.CodeAccessSecurityEngine.ResolveGrantSet(Evidence evidence, Int32& specialFlags, Boolean checkExecutionPermission) +60
[FileLoadException: Could not load file or assembly 'Microsoft.WebTools.BrowserLink.Runtime, Version=16.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. PolicyException thrown. (Exception from HRESULT: 0x80131416)]
System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +232
System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark) +176
System.Reflection.Assembly.LoadFrom(String assemblyFile) +53
Microsoft.VisualStudio.Web.PageInspector.Runtime.Loader.RuntimeLoader.GetRuntimeAssemblyFromSetupConfiguration(Assembly& runtime) +27
Microsoft.VisualStudio.Web.PageInspector.Runtime.Loader.RuntimeLoader.LoadRuntime() +26
Microsoft.VisualStudio.Web.PageInspector.Runtime.Loader.RuntimeLoader.PreApplicationStart() +45
[InvalidOperationException: The pre-application start initialization method PreApplicationStart on type Microsoft.VisualStudio.Web.PageInspector.Runtime.Loader.RuntimeLoader threw an exception with the following error message: Could not load file or assembly 'Microsoft.WebTools.BrowserLink.Runtime, Version=16.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. PolicyException thrown. (Exception from HRESULT: 0x80131416).]
System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures) +919
System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +169
System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +172
System.Web.Compilation.BuildManager.ExecutePreAppStart() +172
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +854
[HttpException (0x80004005): The pre-application start initialization method PreApplicationStart on type Microsoft.VisualStudio.Web.PageInspector.Runtime.Loader.RuntimeLoader threw an exception with the following error message: Could not load file or assembly 'Microsoft.WebTools.BrowserLink.Runtime, Version=16.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. PolicyException thrown. (Exception from HRESULT: 0x80131416).]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +532
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +111
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +724
This occurs under both EF6.2 and EF6.4.
If this is occurring on your remote deployment and not your local development environment after upgrading the EF version then I would suspect there is an issue with the deployment process.
Check the web.config in the deployed build to ensure that there are no EF-related runtime version dependency version overrides. (EntityFramework.dll and EntityFramework.SqlServer.dll)
Check the EntityFramework.dll assembly version between the deployed file on the remote server and your working local instance.
Copy the deployment from the remote server into a local folder, point IIS at it and then hook VS up running your project using Attach to Process on w3wp.exe. Set a breakpoint somewhere in the code and check that it remains a "hot" hit-able breakpoint and not an inactive one stating something along the lines of "The breakpoint will not currently be hit. The source line does not match..." This would indicate that the deployed code does not reflect a current, complete rebuild of what you are running in VS.
If you are using an automated build:
Check that dependency DLLs are not being checked in and that the build machine is actively resolving NuGet packages properly.
Check your references for EF, both before you upgrade the EF version (Source control revert all changes, use what was last built and deployed) Under the project explorer under References, select EntityFramework and check the path listed. It should be pointing to:
{Your solution folder}\packages\EntityFramework.6.2.0\lib\net45\EntityFramework.dll
If it is pointing to anything like a \bin\debug etc. folder, remove the reference and repair to point at the NuGet package.
If NuGet packages folder is checked in, make sure this folder is complete and up to date in source control. When checking in nuget folders (as opposed to package version locking) I find this needs to be done from Explorer / TFS as normal VS checkins won't include them in pending changes. (unlike /bin folder changes if you accommodate them.) package folder updates can be skipped when initial checkins were made but then things like .ignore files are added/updated causing newer .dll files not to be updated.
Check for any stale or mismatched project files (.csproj/.vbproj) in your local environment vs. what is in source control. Often these can get flagged at some point as "Excluded Files" resulting in the automated build using out of date references.
Have a check through these and see if that identifies anything.

sp_db_sendmail error

I am currently running SQL Server 2014 and trying to execute a stored procedure that sends out an email using sp_db_sendmail which is failing with the following error.
An error occurred in the Microsoft .NET Framework while trying to load
assembly id 65549. The server may be running out of resources, or the
assembly may not be trusted with PERMISSION_SET = EXTERNAL_ACCESS or
UNSAFE. Run the query again, or check documentation to see how to
solve the assembly trust issues. For more information about this
error: System.IO.FileLoadException: Could not load file or assembly
'sqlwebrequest, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
or one of its dependencies. An error relating to security occurred.
(Exception from HRESULT: 0x8013150A) System.IO.FileLoadException:
at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName,
String codeBase, Evidence assemblySecurity, RuntimeAssembly
locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder,
Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean
suppressSecurityChecks) at
System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName
assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly,
StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean
throwOnFileNotFound, Boolean forIntrospection, Boolean
suppressSecurityChecks) at
System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString,
Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr
pPrivHostBinder, Boolean forIntrospection) at
System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString,
Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean
forIntrospection) at System.Reflection.Assembly.Load(String
assemblyString)
Originally the sp_db_sendmail was working but since moving the database that calls the code to a new server I am getting the above message.
I have made the owner of the database the same as it was on the original server "sa" and also set the database to be "Trustworthy" which seems according to relevant googling should fix the problem, but still no luck.
Any further suggestion would be appreciated.

Trying to run EF Code first Migrate.exe tool on production environment failed

I'm using EntityFramework version 6.1.3.
I copied migrate.exe from EntityFramework version 6.1.3 package tool folder to bin folder of my website.
My web site is compiled and published to production environment with x86 CPU and target framework 4.5.1
I run the following command:
D:\Sites\MatrixPortal\bin>migrate.exe
d:\sites\MatrixPortal\bin\MatrixPortal.BL.dll
/startUpDirectory="d:\Sites\MatrixPortal\bin"
/startUpConfigurationFile="d:\Sites\MatrixPortal\Web.config"
and i get the following error:
ERROR: Could not load file or assembly
'd:\sites\MatrixPortal\bin\MatrixPortal.BL' or one of its
dependencies. The given assembly name or codebase was invalid.
(Exception from HRESULT: 0x80131047)
EDIT:
when i try this:
migrate MatrixPortal.BL.dll /verbose
i get other error:
System.BadImageFormatException: Could not load file or assembly
'MatrixPortal.BL' or one of its dependencies. An attempt was made to
load a program with an incorrect format. File name: 'MatrixPortal.BL'
at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName,
String codeBase, Evidence assemblySecurity, RuntimeAssembly
locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder,
Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean
suppressSecurityChecks) at
System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName
assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly,
StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean
throwOnFileNotFound, Boolean forIntrospection, Boolean
suppressSecurityChecks) at
System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString,
Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr
pPrivHostBinder, Boolean forIntrospection) at
System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString,
Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean
forIntrospection) at System.Reflection.Assembly.Load(String
assemblyString) at
System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.LoadAssembly(String
name) at
System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.FindConfiguration()
at
System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate
callBackDelegate) at
System.Data.Entity.Migrations.Console.Program.Run() at
System.Data.Entity.Migrations.Console.Program.Main(String[] args)
=== Pre-bind state information === LOG: DisplayName = MatrixPortal.BL (Partial) WRN: Partial binding information was supplied for an
assembly: WRN: Assembly Name: MatrixPortal.BL | Domain ID: 2 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:///D:/Sites/MatrixPortal/bin/ LOG: Initial PrivatePath = NULL
Calling assembly : EntityFramework, Version=6.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089.
=== LOG: This bind starts in default load context. LOG: Using application configuration file:
C:\Users\guy_b\AppData\Local\Temp\tmpC402.tmp LOG: Using host
configuration file: LOG: Using machine configuration file from
C:\Windows\Microsoft.NET\Framework64\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:///D:/Sites/MatrixPortal/bin/MatrixPortal.BL.DLL. ERR: Failed to
complete setup of assembly (hr = 0x8007000b). Probing terminated.
ERROR: Could not load file or assembly 'MatrixPortal.BL' or one of its
dependencies. An attempt was made to load a program with an incorrect
format.
also tried this:
http://www.azurefromthetrenches.com/command-line-entity-framework-code-first-migrations/
and created a file called Redirect.config with the following content:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
<bindingRedirect oldVersion="0.0.0-6.1.3" newVersion="6.1.3" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
but got the same error as above :(
In my case I got the error because I wrote migrate .\MyAssembly.dll instead of migrate MyAssembly.dll.
See Common Problems documentation section.
SOLVED!
I've Published the web site project with x86 target cpu, and apparently it wasn't really x86, i don't know why, maybe a bug?
After changing Publish to any cpu it worked. i was able to run migrate.exe without an error using the following arguments:
migrate.exe MatrixPortal.BL.dll /verbose /startUpDataDirectory="D:\Sites\MatrixPortal" /startUpConfigurationFile="D:\Sites\MatrixPortal\Web.config"

Format of the initialization string does not conform to specification starting at index 0 on azure

Have been with thi problem for hours, this is my connectionstring:
<connectionStrings>
<add name="OL4RENTDb"
connectionString="Server=v812xrqz2w.database.windows.net;Database=ol4rentDB;User ID=AdminOL4RENT#v812xrqz2w;Password=Grupo501TSI;Trusted_Connection=False;Encrypt=True;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
an error:
[ArgumentException: Format of the initialization string does not conform to specification starting at index 0.]
System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue) +5314705
System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey) +124
System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules) +95
System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) +59
Do you see any problem there?
I am deploying to azure..
I had the same error and I fix it by going via FTP to my Azure Website and edited the Web.Config. I noticed that a new connection string entry has been added. I removed it to keep those that I had on my PC and everything worked well. So, if you have this error when you deploy to Azure, check your connections strings.
The problem wasnt that web.config's connection string, but the one you specify in publish settings, the one that azure will use to connect to db.
Lets say you can have in the local pc the connection string to you local database, and when you publish you put the azure database connection string, and that override your local connection string at web.config.

"URI formats are not supported" exception when using |DataDirectory| in Entity Framework connection string

I have a unit test project in Visual Studio 2012 where I am storing the AdventureWorks MDF file for SQL Server 2012 (the file is named AdventureWorks2012_Data.mdf). In the Visual Studio Server Explorer, I am able to add the MDF in the Data Connections and browse the database. Right clicking on $/Data Connections/AsventureWorks2012_Data.mdf and selecting properties gives me access to the connection string as follows:
Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Projects\Common\Source\Framework\Framework.Data.Tests\AdventureWorks2012_Data.mdf;Integrated Security=True;Connect Timeout=30
I copied this into my Entity Framework connection string in the app.config file as follows:
<!-- Works :-) -->
<connectionStrings>
<add name="AdventureWorksEntities"
connectionString="metadata=res://*/Repository2Tests.AdventureWorks.csdl|res://*/Repository2Tests.AdventureWorks.ssdl|res://*/Repository2Tests.AdventureWorks.msl;provider=System.Data.SqlClient;provider connection string="Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Projects\Common\Source\Framework\Framework.Data.Tests\AdventureWorks2012_Data.mdf;Integrated Security=True;Connect Timeout=30App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
Note that the AttachDbFilename contains the full path of the MDF file as:
C:\Projects\Common\Source\Framework\Framework.Data.Tests\AdventureWorks2012_Data.mdf
When I run the unit tests, everything is fine as expected.
I changed AttachDbFilename to |DataDirectory|\AdventureWorks2012_Data.mdf as described in "ADO.NET Entity Framework Connection Strings" and I set the DataDirectory as described in "ADO.NET |DataDirectory| where is this documented?" so that my connection string now is as follows:
<!-- Doesn't work :-( -->
<connectionStrings>
<add name="AdventureWorksEntities"
connectionString="metadata=res://*/Repository2Tests.AdventureWorks.csdl|res://*/Repository2Tests.AdventureWorks.ssdl|res://*/Repository2Tests.AdventureWorks.msl;provider=System.Data.SqlClient;provider connection string="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\AdventureWorks2012_Data.mdf;Integrated Security=True;Connect Timeout=30;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
The change to using |DataDirectory| resulted in the following runtime error:
System.Data.EntityException: The underlying provider failed on ConnectionString. ---> System.ArgumentException: URI formats are not supported.
HResult: -2147024809
at System.IO.Path.NormalizePath(String path, Boolean fullCheck, Int32 maxPathLength)
at System.IO.Path.GetFullPath(String path)
at System.Data.Common.ADP.GetFullPath(String filename)
at System.Data.Common.DbConnectionOptions.ExpandDataDirectory(String keyword, String value, String& datadir)
at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous)
at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions)
at System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key)
at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
at System.Data.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString)
--- End of inner exception stack trace ---
HResult: -2146233087
at System.Data.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString)
at System.Data.Entity.Internal.LazyInternalConnection.TryInitializeFromAppConfig(String name, ConnectionStringSettingsCollection connectionStrings)
at System.Data.Entity.Internal.LazyInternalConnection.Initialize()
at System.Data.Entity.Internal.LazyInternalConnection.get_ConnectionHasModel()
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Internal.Linq.InternalSet`1.Create()
I have researched this for a couple days now and tried countless variations without success. I even debugged into Microsoft code but with compiler optimizations I am unable to see any debugging information on the stack.
Has anyone run across this specific problem?
I finally solved the problem when I set out to submit a bug report to Microsoft and worked on reproduction steps.
To make a long story short, the problem was in the code that set the DataDirectory:
AppDomain.CurrentDomain.SetData("DataDirectory", dataDirectory);
The issue was that my dataDirectory variable was getting initialized as file://C:/myfolder/etc/ instead of C:\myfolder\etc\. I corrected the code responsible for that and the problem is resolved. Incidentally, the code I used is:
// in the test assembly initializer
String dataDirectory = AppDomain.CurrentDomain.GetApplicationPath();
AppDomain.CurrentDomain.SetData("DataDirectory", dataDirectory);
// GetApplicationPath calls into the following extension method
/// <summary>
/// Defines a set of extension methods on <see cref="AppDomain"/> objects.
/// </summary>
public static class AppDomainExtensions
{
/// <summary>
/// Gets the application path (works for both ASP.NET and unit tests).
/// </summary>
/// <returns></returns>
public static string GetApplicationPath(this AppDomain appDomain)
{
string binPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
return binPath.Substring(0, binPath.LastIndexOf("bin", StringComparison.InvariantCultureIgnoreCase));
}
}