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!
Related
I need to be able to switch between Vista DB and SQL Server. I generated my edmx using SQL Server and created a separated SSDL file for Vista DB. When I update my connection string to use my Vista DB SSDL I get the following error:
DataModel.msl(3,4) : error 2002: The EntityContainer 'MyEntities' for the conceptual model specified as part of this MSL does not exist in MetadataWorkspace.
at System.Data.Entity.Core.Mapping.StorageMappingItemCollection.Init(EdmItemCollection edmCollection, StoreItemCollection storeCollection, IEnumerable`1 xmlReaders, IList`1 filePaths, Boolean throwOnError)
at System.Data.Entity.Core.Mapping.StorageMappingItemCollection..ctor(EdmItemCollection edmCollection, StoreItemCollection storeCollection, IEnumerable`1 xmlReaders, IList`1 filePaths)
at System.Data.Entity.Core.Metadata.Edm.MetadataCache.LoadStoreCollection(EdmItemCollection edmItemCollection, MetadataArtifactLoader loader)
at System.Data.Entity.Core.Metadata.Edm.MetadataCache.<>c__DisplayClass5.<>c__DisplayClass7.<GetMetadataWorkspace>b__1()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Lazy`1.get_Value()
at System.Data.Entity.Core.Metadata.Edm.MetadataCache.<>c__DisplayClass5.<>c__DisplayClass7.<GetMetadataWorkspace>b__4()
at System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.LoadAndCheckItemCollection[T](Func`1 itemCollectionLoader)
at System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.<>c__DisplayClass16.<.ctor>b__f()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Lazy`1.get_Value()
at System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.GetItemCollection(DataSpace dataSpace, Boolean required)
at System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.GetItemCollection(DataSpace dataSpace)
at System.Data.Entity.Core.Objects.ObjectContext.InitializeMappingViewCacheFactory(DbContext owner)
at System.Data.Entity.Core.Objects.ObjectContext..ctor(EntityConnection connection, Boolean isConnectionConstructor, ObjectQueryExecutionPlanFactory objectQueryExecutionPlanFactory, Translator translator, ColumnMapFactory columnMapFactory)
at System.Data.Entity.Core.Objects.ObjectContext..ctor(EntityConnection connection)
at System.Data.Entity.Internal.InternalConnection.CreateObjectContextFromConnectionModel()
at System.Data.Entity.Internal.LazyInternalConnection.CreateObjectContextFromConnectionModel()
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
I've tried creating a separate MSL (its just a copy of the MSL used by SQL Server, It didn't seem like there was anything provider specific in there), but that did not fix the problem. I am referencing the required VistaDB dlls, in fact if I recreate my edmx for Vista DB everything works fine, but it's really annoying switching back and forth that way.
Is there something else I'm missing?
This was an embarrassing problem. It looks like I accidentally deleted the csdl part of my connection string. Added it back fixed the problem
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.
Taking my very first babysteps with Entity Framework 5.0, I run into an exception with the very first Entity I create.
Please note that every table created after that works just fine. Also, do note that I've taken the usual steps of regenerating the database and/or restarting the Visual Studio IDE.
Using Model-First, I created a trivial table called Contacts, defined as
<EntityType Name="Contacts">
<Key>
<PropertyRef Name="ContactID" />
</Key>
<Property Name="ContactID" Type="int" StoreGeneratedPattern="Identity" Nullable="false" />
<Property Name="Name" Type="nvarchar(max)" Nullable="false" />
</EntityType>
I then tried to run the following code (from the Page_Load of an ASP.NET page)
var contact = new DataContext.Contact { Name = aName };
context.Contacts.Add(contact);
context.SaveChanges();
(with aName != null)
Exception:
System.NullReferenceException was unhandled by user code
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=System.Web
StackTrace:
at System.Web.UI.ParseChildrenAttribute.GetHashCode()
at System.Collections.Generic.ObjectEqualityComparer`1.GetHashCode(T obj)
at System.Collections.Generic.HashSet`1.InternalGetHashCode(T item)
at System.Collections.Generic.HashSet`1.AddIfNotPresent(T value)
at System.Collections.Generic.HashSet`1.UnionWith(IEnumerable`1 other)
at System.Collections.Generic.HashSet`1..ctor(IEnumerable`1 collection, IEqualityComparer`1 comparer)
at System.Collections.Generic.HashSet`1..ctor(IEnumerable`1 collection)
at System.Data.Entity.ModelConfiguration.Utilities.AttributeProvider.GetAttributes(Type type)
at System.Data.Entity.ModelConfiguration.Utilities.AttributeProvider.GetAttributes(PropertyInfo propertyInfo)
at System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildPropertyValidator(PropertyInfo clrProperty)
at System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildValidatorsForProperties(IEnumerable`1 clrProperties, IEnumerable`1 edmProperties, IEnumerable`1 navigationProperties)
at System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildTypeValidator[T](Type clrType, IEnumerable`1 edmProperties, IEnumerable`1 navigationProperties, Func`3 validatorFactoryFunc)
at System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildEntityValidator(InternalEntityEntry entityEntry)
at System.Data.Entity.Internal.Validation.ValidationProvider.GetEntityValidator(InternalEntityEntry entityEntry)
at System.Data.Entity.Internal.InternalEntityEntry.GetValidationResult(IDictionary`2 items)
at System.Data.Entity.DbContext.ValidateEntity(DbEntityEntry entityEntry, IDictionary`2 items)
at System.Data.Entity.DbContext.GetValidationErrors()
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at Contactisch._Default.AddContact(String aName) in c:\Projects\Contactisch\Contactisch\Contactisch\Default.aspx.cs:line 32
at Contactisch._Default.Page_Load(Object sender, EventArgs e) in c:\Projects\Contactisch\Contactisch\Contactisch\Default.aspx.cs:line 14
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:
Can someone explain the cause of this exception ? Especially, what is that call to ParseChildrenAttribute.GetHashCode doing there?
I did find someone running into the same issue here, but no satisfactory explanation was given.
Problem solved.
The cause was a bit silly. I was using the default ASP.NET Web Forms Application project from VS Web Express to perform my testing. This project contains a web form called Contact.aspx, so it already includes a partial class Contact in the same namespace as my Contact entity.
Understandably, this didn't play well with Entity Framework, leading to the rather obscure error above. Deleting the aspx page solved the problem.
This happens when you create an ASP.NET webpage with the same name as a table in your database, after generating your edmx and EF classes from your database Visual Studio will place them in the default namespace for your project which causes a conflict with the generated partial class of the web pages .aspx.cs file
You do not need to remove or rename the the .aspx file of your webpage just change the name of the partial public class declared in the pages code behind (myPage.aspx.cs) and adjust the Inherits property of the page appropriately like so.
<%#Page Title="MyPage" ... Inherts="namespace.newClassName" >
Alternatively you could always declare your webpages under a different namespace.
I'm writing a plugin for a CMS that loads plugin assemblies dynamically using Assembly.load.
Note: For reasons that are irrelevant to go into, the frontend loads the assembly statically, whilst the admin environment loads it dynamically.
My plugin has its own xml configuration file that loads the first time the plugin class is used. The config file is deserialized into an object object using XmlSerializer.
This deserialization works fine when I load the assembly statically through the frontend, however when the admin tries to load it dynamically I get a NullReferenceException from the reader.
I have tried pre-generating the serialization assembly using Sgen and adding it to the "Bin" directory of the admin environment, but this seems to have no effect.
Stack trace:
[NullReferenceException: Object reference not set to an instance of an object.]
Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderAccessibilityConfig..cctor() +1156
[TypeInitializationException: The type initializer for 'Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderAccessibilityConfig' threw an exception.]
Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderAccessibilityConfig..ctor() +0
Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializerContract.get_Reader() +44
System.Xml.Serialization.TempAssembly.InvokeReader(XmlMapping mapping, XmlReader xmlReader, XmlDeserializationEvents events, String encodingStyle) +69
System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events) +101
[InvalidOperationException: There is an error in XML document (0, 0).]
System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events) +613
System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader) +30
CoA.WebUI.Controls.AccessibilityObjects.AccessibilityConfigBase`1.Deserialize(String xml) +196
CoA.WebUI.Controls.AccessibilityObjects.AccessibilityConfigBase`1.LoadFromFile(String fileName) +256
CoA.WebUI.Controls.Accessibility.Configure(Boolean isAdmin) +725
CoA.WebUI.Controls.Accessibility.GetProperties() +118
CMS.Admin.WebUI.CustomControlCreator.GetCustomControlProperties() +194
CMS.Admin.WebUI.CustomControlCreator.BindPropertyControls() +146
CMS.Admin.WebUI.CustomControlCreator.PageLoad() +164
CMS.Admin.WebUI.CustomControlCreator.Page_Load(Object sender, EventArgs e) +47
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
Oddly, the stack trace seems to indicate that the XML document is empty, but I'm passing in a StringReader which I have debugged and confirmed is populated with the correct document - it isn't empty.
I figured it out!!!
If anyone else comes across this problem, here is a way of solving it.
Take your serializable object and put it in its own assembly (i.e. its own project in VS). Now you have two dlls. One with your assembly to be dynamically loaded and the other containing your serializable object.
Take the one with your serializeable object and put it in the bin directory of any application that dynamically loads your plugin assembly.
Now when your dynamically loaded assembly tries to create an object, the assembly for creating that object is already available in memory - having been loaded statically.
I don't know why XmlSerializer doesn't like to work when working with a dynamically loaded assembly, but this workaround seems to work well.
Hope this helps someone some day.
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.