I have an ASP MVC application that is hosted in a medium trust environment. This means that the only code that can execute is what is defined in the code permissions of the applications trust file. I am seeing that in the newer MVC applications a method ExecutePreAppStart() is called. This method then tries to execute LoadAllAssembliesFromAppDomainBinDirectory(). When this occurs a permissions error is generated
[PolicyException: Execution permission cannot be acquired.]
If the app has not been granted the explicit permission to execute that assembly. This is the expected outcome.
The issue here is that prior to PreApplicationStartMethod's implementation this error would bubble up to Application_Error in the global.asax. With PreApplicationStartMethod this is no longer the case. Since the PreApplicationStartMethod is not in code that I control, how can I trap for an error that may occur?
I have tried to create my own PreApplicationStartMethod to catch the exception but, it never reached the break point because the application is never fully loaded.
So, is there a way to catch errors for someone else's PreApplicationStartMethod? My end goal is to just be able to publish the exception.
Attempt at catching error:
[assembly: System.Web.PreApplicationStartMethod(typeof(mynamespace.Initializer), "Initialize")]
namespace mynamespace
{
public static class Initializer
{
public static void Initialize()
{
//Do something here to catch errors/bind event? but I never get this far at runtime
}
}
}
Stack Trace:
System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String
assemblyName, Boolean starDirective) +772
System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory()
+259 System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo
ai) +163
System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection
compConfig) +230
System.Web.Compilation.BuildManager.GetPreStartInitMethodsFromReferencedAssemblies()
+76 System.Web.Compilation.BuildManager.CallPreStartInitMethods(String
preStartInitListPath, Boolean& isRefAssemblyLoaded) +343
System.Web.Compilation.BuildManager.ExecutePreAppStart() +176
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager
appManager, IApplicationHost appHost, IConfigMapPathFactory
configMapPathFactory, HostingEnvironmentParameters hostingParameters,
PolicyLevel policyLevel, Exception appDomainCreationException) +734
I am not sure why you need to run your application in a medium trust environment. The preapplicationstart method always worked for me and was able to catch exceptions when an error occurred. Usually, i would run an infinite while loop and execute operations every x amount of minutes. The only difference between your code and mine is that i usually define the Initializer class as public class without being static, i only set the initialize method as static.
This works for me even in azure web apps environment. So, make ways to elevate the trust level of your environment, but before test this on your development machine and make sure it works so you are sure that the error is thrown from server security policy.
Related
We have multiple servers on which we are hosting an ASP.NET website on IIS. In the website we are trying to fetch values from Azure KeyVault.
In one server for some reason it fails to read the values from Azure KeyVault with an error 'The specified user does not have a valid profile'. We have done investigation, double-checked configuration, permission rights on files - everything looks okay. Also tried to adjust profile in IIS, nothing helped.
Here is the stack trace:
Exception information:
Exception type: ConfigurationErrorsException
Exception message: An error occurred loading a configuration file: The specified user does not have a valid profile. Unable to load 'Microsoft.Configuration.ConfigurationBuilders.Azure, Version=2.0.0.0, Culture=neutral'. (D:\<website_path> line 77)
at System.Configuration.BaseConfigurationRecord.EvaluateOne(String[] keys, SectionInput input, Boolean isTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult)
at System.Configuration.BaseConfigurationRecord.Evaluate(FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult, Boolean getLkg, Boolean getRuntimeObject, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSection(String configKey, Boolean getLkg, Boolean checkPermission)
at System.Web.Util.AppSettings.GetAppSettingsSection()
at System.Web.Util.AppSettings.EnsureSettingsLoaded()
at System.Web.Util.AppSettings.get_PortableCompilationOutput()
at System.Web.Compilation.BuildManager.RestorePortableCompilationOutputSnapshot()
at System.Web.Compilation.BuildManager.ExecutePreAppStart()
at System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException)
The specified user does not have a valid profile. Unable to load 'Microsoft.Configuration.ConfigurationBuilders.Azure, Version=2.0.0.0, Culture=neutral'.
at System.Configuration.TypeUtil.GetTypeImpl(String typeString, Boolean throwOnError)
at System.Configuration.ConfigurationBuildersSection.InstantiateBuilder(ProviderSettings ps)
at System.Configuration.ConfigurationBuildersSection.GetBuilderFromName(String builderName)
at System.Configuration.BaseConfigurationRecord.GetSectionXmlReader(String[] keys, SectionInput input)
Has anyone experienced a similar issue?
Any help will be appreciated.
I have answered a similar question here: Function app in Azure could not load file or assembly 'Microsoft.Extensions.Logging.Abstractions'
Do check out - it can be because of same reasons. There may be a nuget package which requires different version of Microsoft.Configuration.ConfigurationBuilders.Azure: 2.0.0. But, you have a version installed which is incompatible.
After doing some debugging we have found the issue. It turned out that under Environment variables for the user we had everything correct, but under environment variables for system we mistyped AZURE_TENTANT_ID. Explains why it was working as a console application (run as current user) and not as a Windows Service (run as system)
I keep getting this error, usually after changing the web.config on a running ASP.NET MVC azure web service app. It will run fine the first time but after it recompiles after changing the web.config this is usually appearing. I think it happens sometimes by just starting and stopping the web app. The only way I can make it go away is by publishing the app again from visual studio to azure.
Method not found: 'Microsoft.Practices.Unity.IUnityContainer MyProject.Core.ContainerManager.GetConfiguredContainer()'.
The pre-application start initialization method Run on type WebActivatorEx.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation
Source File: D:\MyProject-master\src\MyProject.Web\App_Start\UnityMvcActivator.cs Line: 73
StackTrace
MissingMethodException: Method not found:
'Microsoft.Practices.Unity.IUnityContainer
MyProject.Core.ContainerManager.GetConfiguredContainer()'.]
MyProject.Web.App_Start.UnityWebActivator.Start() in D:\MyProject-master\src\MyProject.Web\App_Start\UnityMvcActivator.cs:73
[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) +87
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +101
WebActivatorEx.BaseActivationMethodAttribute.InvokeMethod() +73
WebActivatorEx.ActivationManager.RunActivationMethods(Boolean designerMode) +350
WebActivatorEx.ActivationManager.Run() +78
[InvalidOperationException: The pre-application start initialization method Run on type WebActivatorEx.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures) +615
System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +141
System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +102
System.Web.Compilation.BuildManager.ExecutePreAppStart() +157
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +549
[HttpException (0x80004005): The pre-application start initialization method Run on type WebActivatorEx.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +10075124
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +95
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254
This question seems very close to my issue but I haven't gotten this solution to work, there are two projects in my solution that use the RegisterTypes method:
interface and cannot be constructed on Unity config
These questions were related but not exactly this issue:
https://stackoverflow.com/questions/21078380/webactivatorex-dll-unity-bootstrap-is-firing-on-a-different-project
ActivationManager Exception during build process?
Unity Bootstrapper from NuGet is throwing error on App_Start
EDIT: If I merge the application into single assemblies during deployment the issue doesn't seem to happen anymore.
Install-Package Microsoft.AspNet.WebHelpers
For me, this turned out to be a problem where I was trying to inject something null into something that required a value -- didn't actually have anything to do with the error. For instance, I had a configuration setting that was missing, and it was trying to inject that missing setting somewhere. Once I realized which injection was going awry and fixed it, the error went away.
Can somebody please help me?
After receiving an email from Google yesterday that advised a couple of links in my site (www.bigint.biz) were broken, I repaired them. Then I made a change to the sitemap.
Afterwards, when accessing the site I received the message: Server Error in '/' Application, Runtime Error, This tag should then have its "mode" attribute set to "Off".
So, I put the site exactly back how it was before the changes to the sitemap; but, I received
an internal server error 500 error message.
Then, I removed the whole site from the host provider and uploaded it again with the original version that worked fine with no joy.
Since, I have set the customErrors tag "mode" attribute to "Off" to get a more detailed error message - below:
Server Error in '/' Application.
Unspecified error [ 5,sqlcese40.dll ]
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.Data.SqlServerCe.SqlCeException: Unspecified error [ 5,sqlcese40.dll ]
Source Error: Line 2: #{ Line 3: Line 4: WebSecurity.InitializeDatabaseConnection("PhotoGallery", "UserProfile", "UserId", "Email", true);
Source File: \web-123win\winpackage22\XXX.COM\web\content_AppStart.cshtml Line: 4
Stack Trace:
[SqlCeException (0x80004005): Unspecified error [ 5,sqlcese40.dll ]]
System.Data.SqlServerCe.SqlCeConnection.Open(Boolean silent) +2182
System.Data.SqlServerCe.SqlCeConnection.Open() +47
WebMatrix.Data.Database.EnsureConnectionOpen() +44
WebMatrix.Data.<QueryInternal>d__0.MoveNext() +66
System.Linq.Enumerable.FirstOrDefault(IEnumerable`1 source) +164
WebMatrix.Data.Database.QuerySingle(String commandText, Object[] args) +103
WebMatrix.WebData.DatabaseWrapper.QuerySingle(String commandText, Object[] parameters) +14
WebMatrix.WebData.SimpleMembershipProvider.CheckTableExists(IDatabase db, String tableName) +57
WebMatrix.WebData.SimpleMembershipProvider.CreateTablesIfNeeded() +49
WebMatrix.WebData.WebSecurity.InitializeMembershipProvider(SimpleMembershipProvider simpleMembership, DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean createTables) +73
WebMatrix.WebData.WebSecurity.InitializeProviders(DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +51
WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection(String connectionStringName, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +51
ASP._Page__appstart_cshtml.Execute() in \\web-123win\winpackage22\bigint.biz\www.bigint.biz\web\content\_AppStart.cshtml:4
System.Web.WebPages.ApplicationStartPage.<ExecuteInternal>b__0() +65
System.Web.WebPages.ApplicationStartPage.<GetSafeExecuteStartPageThunk>b__3(Action action) +7
System.Web.WebPages.ApplicationStartPage.ExecuteInternal() +78
System.Web.WebPages.ApplicationStartPage.ExecuteStartPageInternal(HttpApplication application, Action`1 monitorFile, IVirtualPathFactory virtualPathFactory, IEnumerable`1 supportedExtensions) +184
System.Web.WebPages.ApplicationStartPage.ExecuteStartPage(HttpApplication application, Action`1 monitorFile, IVirtualPathFactory virtualPathFactory, IEnumerable`1 supportedExtensions) +30
[HttpException (0x80004005): Exception of type 'System.Web.HttpException' was thrown.]
System.Web.WebPages.ApplicationStartPage.ExecuteStartPage(HttpApplication application, Action`1 monitorFile, IVirtualPathFactory virtualPathFactory, IEnumerable`1 supportedExtensions) +96
System.Web.WebPages.ApplicationStartPage.ExecuteStartPage(HttpApplication application) +170
System.Web.WebPages.WebPageHttpModule.StartApplication(HttpApplication application, Action`1 executeStartPage, EventHandler applicationStart) +126
System.Web.WebPages.WebPageHttpModule.StartApplication(HttpApplication application) +71
System.Web.WebPages.WebPageHttpModule.Init(HttpApplication application) +127
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +418
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +336
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +296
[HttpException (0x80004005): Exception of type 'System.Web.HttpException' was thrown.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9874568
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254
I noticed that when I was uploading the site again using FileZilla Client that 4 files failed to copy to the host; however, the same files are in the host bin directory as they did not originally delete for some reason - access rights I think. The files are:
web/content/bin/X86/sqlceer40ENN.dll
web/content/bin/X86/sqlceqp40.dll
web/content/bin/X86/sqlcese40.dll
web/content/bin/X86/sqlceme40.dll
Is this just coincidence, as the error message references one of these files?
Any help would be really appreciated.
Thank you.
EDIT - I have found a little more info here but I am struggling to understand how it can help me: http://www.blakepell.com/Blog/?p=227
I have got the site back up and running for the minute by removing: WebSecurity.InitializeDatabaseConnection("PhotoGallery", "UserProfile", "UserId", "Email", true);
But the issue still exists
I picked this problem up again today all this time later and found the solution with research. This is how I got there.
Replacing the dll files as recommended above didn't work before.
So, I started again by switching off my custom errors page which enabled me to get to get to the error code again.
I Googled the error and research pointed to a connection string issue or a folder permissions issue.
It's a good job I checked the permissions again because I previously set the folder permissions in the App_Data folder where the .sdf database was to enable read and write access using FileZilla but nothing actually changed. It seemed to work because changes appeared to cascade down through all the sub directories, but it didn't work.
The permissions were not actually changed using the FTP method although it looked like it had happened. I only found out because another post that I saw today suggested changing permissions through the control panel so I went back there to check them only to see a padlock by the folders.
So, I unlocked the folder permissions on App_Data correctly this time in the control panel file manager. I then un-commented the web security code below in the _AppStart page again and tried the site online and it worked.
Finally, I set custom errors back to on.
The moral is use the control panel and not FTP client to change folder permissions on hosted folders. I hope this helps someone else.
I'm trying to use the .NET port of Yahoo's YUI compressor in my web site, running on my local Windows 7 development machine.
The web application is running in Full Trust mode. Also, in my web.config, I have this set:
<system.web>
<trust level="Full" />
</system.web>
When I call this code, it throws a Security Exception
string output = "{someJavaScriptCode:true}";
output = JavaScriptCompressor.Compress(output);
The exception details:
Description: The application
attempted to perform an operation not
allowed by the security policy. To
grant this application the required
permission please contact your system
administrator or change the
application's trust level in the
configuration file.
Exception Details:
System.Security.SecurityException:
Request for the permission of type
'System.Security.Permissions.SecurityPermission,
mscorlib, Version=2.0.0.0,
Culture=neutral,
PublicKeyToken=b77a5c561934e089'
failed.
Since this is my local development machine, I have full control over the server settings and have everything set to full trust as far as I can tell.
I've found one possible solution on Google, but I don't understand where the solution's code should go.
The solution was not very detailed and didn't provide any explanation as for why the solution worked.
Does anyone know a good solution to fix this? Preferably with complete code examples or a good explanation of what would be needed to make this work in my web app?
edit Here's the stack trace of the exception, in case it helps.
[SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
System.Threading.Thread.set_CurrentCulture(CultureInfo value) +38
Yahoo.Yui.Compressor.JavaScriptCompressor..ctor(String javaScript, Boolean isVerboseLogging, Encoding encoding, CultureInfo threadCulture, Boolean isEvalIgnored, ErrorReporter errorReporter) +196
Yahoo.Yui.Compressor.JavaScriptCompressor.Compress(String javaScript, Boolean isVerboseLogging, Boolean isObfuscateJavascript, Boolean preserveAllSemicolons, Boolean disableOptimizations, Int32 lineBreakPosition, Encoding encoding, CultureInfo threadCulture, Boolean isEvalIgnored) +119
Yahoo.Yui.Compressor.JavaScriptCompressor.Compress(String javaScript, Boolean isVerboseLogging, Boolean isObfuscateJavascript, Boolean preserveAllSemicolons, Boolean disableOptimizations, Int32 lineBreakPosition, Encoding encoding, CultureInfo threadCulture) +67
Yahoo.Yui.Compressor.JavaScriptCompressor.Compress(String javaScript, Boolean isVerboseLogging, Boolean isObfuscateJavascript, Boolean preserveAllSemicolons, Boolean disableOptimizations, Int32 lineBreakPosition) +112
VideoSync.Js.Script.GetOutput(Boolean compress) in [REDACTED]\Script.ashx.cs:78
VideoSync.Core.CombinerBase.ProcessRequest(HttpContext c) in [REDACTED]\CombinerBase.cs:28
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +599
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +171
You should add the PermissionSet Attribute to your method that tries to call the JavaScriptCompressor.Compress method.
So it would look like this:
[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
void CompressSomething()
{
// ...
var result = JavaScriptCompressor.Compress(output);
// ...
}
This basically tells the CLR to assume that the code in this method has already passed any required security check, so it should allow it to make inner calls.
You should be aware that this code may have some security consequences, and it's recommended to read in more depth about .NET's Code Access Security. Here's a useful link:
http://msdn.microsoft.com/en-us/library/930b76w0(v=vs.71).aspx
EDIT - Another suggestion, having seen the stack trace:
The problem seems to be that setting the current CultureInfo requires SecurityPermission on the current stack.
Maybe try the following:
var cas = new SecurityPermission(PermissionState.Unrestricted);
try
{
cas.Assert();
// ...
var result = JavaScriptCompressor.Compress(output);
// ...
}
finally
{
CodeAccessPermission.RevertAssert();
}
If it doesn't work, try to play with the parameter you send to the SecurityPermission constructor. Maybe some bits are needed on a SecurityPermissionsFlag enum you can send to it.
I have a big problem. When I'm running asp SOMETIMES the application is craching with the following error message:
Schema specified is not valid. Errors:
The types in the assembly 'Data.EF,
Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null' cannot be loaded
because the assembly contains the
EdmSchemaAttribute, and the closure of
types is being loaded by name.
Loading by both name and attribute is
not allowed.
Stack Trace:
[MetadataException: Schema specified
is not valid. Errors: The types in
the assembly 'Data.EF,
Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null' cannot be loaded
because the assembly contains the
EdmSchemaAttribute, and the closure of
types is being loaded by name.
Loading by both name and attribute is
not allowed.]
System.Data.Metadata.Edm.ObjectItemCollection.LoadAssemblyFromCache(ObjectItemCollection
objectItemCollection, Assembly
assembly, Boolean
loadReferencedAssemblies,
EdmItemCollection edmItemCollection,
Action1 logLoadMessage) +480
System.Data.Metadata.Edm.ObjectItemCollection.ExplicitLoadFromAssembly(Assembly
assembly, EdmItemCollection
edmItemCollection, Action1
logLoadMessage) +53
System.Data.Metadata.Edm.MetadataWorkspace.ExplicitLoadFromAssembly(Assembly
assembly, ObjectItemCollection
collection, Action1 logLoadMessage)
+93 System.Data.Metadata.Edm.MetadataWorkspace.LoadFromAssembly(Assembly
assembly, Action1 logLoadMessage)
+130 System.Web.UI.WebControls.EntityDataSourceView.ConstructContext()
+585 System.Web.UI.WebControls.EntityDataSourceView.ExecuteSelect(DataSourceSelectArguments
arguments) +76
System.Web.UI.DataSourceView.Select(DataSourceSelectArguments
arguments,
DataSourceViewSelectCallback callback)
+21 System.Web.UI.WebControls.DataBoundControl.PerformSelect()
+143 Telerik.Web.UI.GridTableView.PerformSelect()
+38 System.Web.UI.WebControls.BaseDataBoundControl.DataBind()
+74 Telerik.Web.UI.GridTableView.DataBind()
+363 Telerik.Web.UI.RadGrid.DataBind() +173
System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound()
+66 System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls()
+75 System.Web.UI.Control.EnsureChildControls()
+102 Telerik.Web.UI.GridBaseDataList.get_Controls()
+33 Telerik.Web.UI.RadAjaxControl.PopulatePlainPanels(Control
parent, List`1 list, Control root)
+119 Telerik.Web.UI.RadAjaxControl.OnPagePreRender(Object
sender, EventArgs e) +1802
System.EventHandler.Invoke(Object
sender, EventArgs e) +0
System.Web.UI.Control.OnPreRender(EventArgs
e) +8864486
System.Web.UI.Control.PreRenderRecursiveInternal()
+103 System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) +2496
I also added LoadFromAssembly before every context call and still the same problem.
context.MetadataWorkspace.LoadFromAssembly(context.GetType().Assembly);
Enviroment: VS 2010, .NET 4.0, C#, EF
Could please somebody help me, to fix this issue?
Thanks in advance,
Best regards.
I was receiving the same error on pages where there was a mixture of EntityDataSource objects and other data access such as ObjectDataSource and/or imperative code.
I took the advice of the MSDN article referenced in the other answer to your question. I.e. to use context.MetadataWorkspace.LoadFromAssembly(...). I actually didn't know how to get a reference to the context instance used by EntityDataSource, and I figured I should DRY it up anyway, so I created a partial class eg:
public partial class YourTypeNameEntities
{
partial void OnContextCreated()
{
this.MetadataWorkspace.LoadFromAssembly(typeof(Full.Namespace.Of.YourTypeNameEntities).Assembly);
}
It still didn't work, but I noticed fairly quickly that when calling DataBind() on a control bound to an EntityDataSource that my OnContextCreated() implementation was not firing!
That was a different issue to which I found a solution... replace the ConnectionString and DefaultContainerName attributes in the EntityDataSource declaration with ContextTypeName. For example:
<asp:EntityDataSource ID="CountrySource" runat="server"
ContextTypeName="Full.Namespace.Of.YourTypeNameEntities" EntitySetName="Country"
OrderBy="it.Name" Where="it.Active==true">
That made sure my OnContextCreated implementation would fire and POOF, the "Loading by both name and attribute is not allowed" problem went away!
It's an old post but I've ran throught this problem twice this week and it seems to, in my case at least, to be related about the fact that I opened a VPN (for a complete other task with no link to this entity projet) and then, this error happened.
I've tried to close my VPN... then close my projet and re-open, completly close my VS without any success. But, restarting my computer make it works back.
Hope this helps if someone get this in same circonstences.
I was seeing the same error message, using EF 5.0 and WCF Data Services 5.2.0. This was a data service using a DbContext-derived class.
The fix for me was to separate code-first EF code from model-first EF code. By moving the code-first code into a separate assembly, the error message went away and things are working. The only way I was able to figure out to try this, is that the [EdmSchema] attribute exists on the code generated from our EDMX; but it doesn't exist on our model (code-first) code.
Hope that helps someone...
I was getting the same error for days. I using was a mixture of EntityDataSource objects and other data access such as ObjectDataSource in the same page. Replaced the EntityDataSource objects with ObjectDataSource. Problem went away!