log4net: error could not create appender [RollingLogFileAppender] - c#

So, I have a project in git repo, and 2 branches: master and fix-master.
I've not changed code associated with log4net in fix-master. But every time, when I've started master - I don't have this problem, if I checkout to fix-master, I have this error after this line:
private static readonly ILog Log = LogManager.GetLogger(typeof(Program));

Aside from the obvious candidates (illegal filepath, permissions error), the problem could even be mutex locking:
https://issues.apache.org/jira/browse/LOG4NET-506
RollingFileAppender locking log folder in some cases
Abstract:
In some configuration cases, the rolling file appender may
issue a mutex lock on the folder name. If more than one processes try
to do that with different executing identity, only one will be able to
log to its specific logs file. The others will no more be able to do
it.
SUGGESTION:
Add this line to your app.config/web.config, under appSettings, to enable internal debugging:
<add key="log4net.Internal.Debug" value="true"/>
This will give you output like this, to both the system console and to System.Diagnostics.Trace
log4net:ERROR Could not create Appender [RollingLogFileAppender] of type [log4net.Appender.RollingFileAppender]. Reported error follows.
System.UnauthorizedAccessException: Access to path 'D__Logs_' denied. (Translated from french)
à System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
à System.Threading.Mutex.MutexTryCodeHelper.MutexTryCode(Object userData)
à System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
à System.Threading.Mutex.CreateMutexWithGuaranteedCleanup(Boolean initiallyOwned, String name, Boolean& createdNew, SECURITY_ATTRIBUTES secAttrs)
à System.Threading.Mutex..ctor(Boolean initiallyOwned, String name, Boolean& createdNew, MutexSecurity mutexSecurity)
à System.Threading.Mutex..ctor(Boolean initiallyOwned, String name, Boolean& createdNew)
à log4net.Appender.RollingFileAppender.ActivateOptions()
à log4net.Repository.Hierarchy.XmlHierarchyConfigurator.ParseAppender(XmlElement appenderElement)
log4net:ERROR Appender named [RollingLogFileAppender] not found.
Please try this, and post back what you find!

Related

Azure Cloud Service Web Role not starting - Unhandled exception - Unable to find Assembly

I have an ASP.NET Web API hosted in a cloud service web role. I have added a WebRole class extending RoleEntryPoint which is attempting to retrieve an IoC castle Windsor container which has dependencies setup in the StartUp.cs of my web API. I want to then retrieve a logger instance I have registered and use that in my WebRole.
public class WebRole : RoleEntryPoint
{
private ICancellationTokenSourceProvider _cancellationTokenSourceProvider;
public override bool OnStart()
{
try
{
var container = IoC.GetContainer();
_cancellationTokenSourceProvider = container.Resolve<ICancellationTokenSourceProvider>();
}
catch (Exception)
{
throw;
}
return base.OnStart();
}
However when I try to deploy this to the cloud service I get the following exception:
Unhandled Exception: Unable to find assembly 'Castle.Windsor,
Version=3.2.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc'. at
System.Runtime.Serialization.Formatters.Binary.BinaryAssemblyInfo.GetAssembly()
at
System.Runtime.Serialization.Formatters.Binary.ObjectReader.GetType(BinaryAssemblyInfo
assemblyInfo, String name) at
System.Runtime.Serialization.Formatters.Binary.ObjectMap..ctor(String
objectName, String[] memberNames, BinaryTypeEnum[] binaryTypeEnumA,
Object[] typeInformationA, Int32[] memberAssemIds, ObjectReader
objectReader, Int32 objectId, BinaryAssemblyInfo assemblyInfo,
SizedArray assemIdToAssemblyTable) at
System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadObjectWithMapTyped(BinaryObjectWithMapTyped
record) at
System.Runtime.Serialization.Formatters.Binary.__BinaryParser.Run() at
System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler
handler, __BinaryParser serParser, Boolean fCheck, Boolean
isCrossAppDomain, IMethodCallMessage methodCallMessage) at
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream
serializationStream, HeaderHandler handler, Boolean fCheck, Boolean
isCrossAppDomain, IMethodCallMessage methodCallMessage) at
System.Runtime.Remoting.Channels.CrossAppDomainSerializer.DeserializeObject(MemoryStream
stm) at System.AppDomain.Deserialize(Byte[] blob) at
System.AppDomain.UnmarshalObject(Byte[] blob) ' [2020-06-19T16:48:01Z]
Last exit time: [2020/06/19, 16:48:05.617]. Last exit code: 0.
I have tried to find the cause and solution to this extensively.
I have tried to add binding redirects to the missing assembly in
MyApi.dll.config and ensuring it is set to copy always.
I have also
ensured the assembly has Copy Local set to true as well.
However, I still get this error every time and the web role keeps restarting trying to recover from this exception.
Read your problem description carefully, I think the problem should be in the problem of loading assembly such as MyApi.dll.
First, because of the limitations of Azure's cloud environment, it may not be possible to load some third-party assemblies. You can refer to this post.
After the Azure Cloud Services service is created, you can get a virtual machine, and you can log in using RDP. So I suggest that you create your application first, do not contain the code that references the third-party .dll , to ensure the successful deployment. Then log in with RDP method to the virtual machine, open cmd, use the regsvr32 xxx.dll related command to register the third-party .dll file in the registry, and then redeploy your complete project now. Check if the problem is solved.

Error when embedding report viewer dll using costura

I am creating a winform apps in vs2019, create report via Report viewer and it's work well. However, when i embed the dll using Fody/Costura, somehow the report viewer give an error.
I also try manually embed the dll, but the same error still occur.
The error message appear in report viewer,
An error occured during local report processing.
The definition of the report " is invalid.
An unexpected error occured in Report Processing.
The type initializer for "Microsoft.Reporting.Services.ReportIntermediateFormat.Persistence.IntermediateFormatVersion" threw an exception.
The path is not a legal form.
Any help would be very appreciated. Thanks.
I encounter the same problem today. Base on the inner exception, it seems report viewer need to get the version of it's related dll to work correctly. If the dll is embeded, report viewer couldn't locate it.
System.ArgumentException: The path is not of a legal form.
at System.IO.Path.NewNormalizePath(String path, Int32 maxPathLength, Boolean expandShortPaths)
at System.IO.Path.NormalizePath(String path, Boolean fullCheck, Int32 maxPathLength, Boolean expandShortPaths)
at System.IO.Path.GetFullPathInternal(String path)
at System.IO.Path.GetFullPath(String path)
at System.Diagnostics.FileVersionInfo.GetFullPathWithAssert(String fileName)
at System.Diagnostics.FileVersionInfo.GetVersionInfo(String fileName)
at Microsoft.ReportingServices.ReportIntermediateFormat.Persistence.IntermediateFormatVersion.<>c__DisplayClass2_0.<.cctor>b__0()
at Microsoft.ReportingServices.Diagnostics.RevertImpersonationContext.<>c__DisplayClass1_0.<Run>b__0(Object state)
at System.Security.SecurityContext.Run(SecurityContext securityContext, ContextCallback callback, Object state)
at Microsoft.ReportingServices.Diagnostics.RevertImpersonationContext.Run(ContextBody callback)
at Microsoft.ReportingServices.ReportIntermediateFormat.Persistence.IntermediateFormatVersion..cctor()
--- End of inner exception stack trace ---
After some trial and error, I found that for report viewer working correctly, 'Microsoft.ReportViewer.ProcessingObjectModel' and 'Microsoft.ReportViewer.Common' need to be exclude from Fody/Costura. Following is the FodyWeavers.xml I'm using.
<?xml version="1.0" encoding="utf-8"?>
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
<Costura>
<ExcludeAssemblies>
Microsoft.ReportViewer.ProcessingObjectModel
Microsoft.ReportViewer.Common
</ExcludeAssemblies>
</Costura>
</Weavers>

How to resolve "Could not load file or assembly 'Microsoft.Practices.Prism' " error?

I've been searching the past few days trying to get an error fixed in a WPF application using Prism, but haven't had any luck and thought I'd see if Stackoverflow had any ideas. Please note, I'm definitely a noob when it comes to Prism in general :)
I'm in the process of learning how to create an application using Prism, with Unity being my dependency injection container of choice. I'm trying to load modules using a modified App.config file, but I'm getting a runtime error related to the bootstrapper. The error messages will be more accurate than any explanation I can provide, so I've included the App.config file, App.xaml.cs file where the error is appearing, and the error information below.
Thank you in advance for any insight you can provide, and let me know if there's any additional information you might need!
EDIT: This file directory referenced in the error (C:\Users\Roger\Documents\TestPrismProject\WpfApplication1\WpfApplication1\bin\Debug\WpfApplication1.exe.Config line 4) refers to the fourth line of App.config file (section name= ...). All the tutorials and references I've found are the same as what I have, but this is still the line that's causing issues it seems.
EDIT 2: The line referenced in the first edit is actually exactly the same as what's on the official Microsoft Prism guide.
EDIT 3: So I never did figure out the root of what was causing this, but in my frustration I restarted the example project I was working through and am not getting the error in the new project. Still not sure what the root of the problem was though.
EDIT 4: Just kidding, the same error is back in the new program.
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="modules" type="Microsoft.Practices.Prism.Modularity.ModulesConfigurationSection, Microsoft.Practices.Prism"/>
</configSections>
<modules>
<module assemblyFile="EmailModule.dll" moduleType="EmailService.ModuleDefinitions.Module, EmailService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" moduleName="EmailModule" startupLoaded="true" />
</modules>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
App.xaml.cs (error appears on the "bootstrapper.Run()" line):
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace EmailClient
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
MyBootstrapper bootstrapper = new MyBootstrapper();
bootstrapper.Run();
}
}
}
Error Message:
System.Configuration.ConfigurationErrorsException was unhandled
HResult=-2146232062
Message=An error occurred creating the configuration section handler for modules: Could not load file or assembly 'Microsoft.Practices.Prism' or one of its dependencies. The system cannot find the file specified. (C:\Users\Roger\Documents\TestPrismProject\WpfApplication1\WpfApplication1\bin\Debug\WpfApplication1.exe.Config line 4)
Source=System.Configuration
BareMessage=An error occurred creating the configuration section handler for modules: Could not load file or assembly 'Microsoft.Practices.Prism' or one of its dependencies. The system cannot find the file specified.
Filename=C:\Users\Roger\Documents\TestPrismProject\WpfApplication1\WpfApplication1\bin\Debug\WpfApplication1.exe.Config
Line=4
StackTrace:
at System.Configuration.BaseConfigurationRecord.FindAndEnsureFactoryRecord(String configKey, Boolean& isRootDeclaredHere)
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)
at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at Microsoft.Practices.Prism.Modularity.ConfigurationStore.RetrieveModuleConfigurationSection()
at Microsoft.Practices.Prism.Modularity.ConfigurationModuleCatalog.EnsureModulesDiscovered()
at Microsoft.Practices.Prism.Modularity.ConfigurationModuleCatalog.InnerLoad()
at Microsoft.Practices.Prism.Modularity.ModuleCatalog.Load()
at Microsoft.Practices.Prism.Modularity.ModuleCatalog.Initialize()
at Microsoft.Practices.Prism.Modularity.ModuleManager.Run()
at Microsoft.Practices.Prism.UnityExtensions.UnityBootstrapper.InitializeModules()
at Microsoft.Practices.Prism.UnityExtensions.UnityBootstrapper.Run(Boolean runWithDefaultConfiguration)
at Microsoft.Practices.Prism.Bootstrapper.Run()
at EmailClient.App.OnStartup(StartupEventArgs e) in c:\Users\Roger\Documents\TestPrismProject\WpfApplication1\WpfApplication1\App.xaml.cs:line 21
at System.Windows.Application.<.ctor>b__1(Object unused)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.ProcessQueue()
at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.Run()
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at EmailClient.App.Main() in c:\Users\Roger\Documents\TestPrismProject\WpfApplication1\WpfApplication1\obj\Debug\App.g.cs:line 50
InnerException: System.IO.FileNotFoundException
HResult=-2147024894
Message=Could not load file or assembly 'Microsoft.Practices.Prism' or one of its dependencies. The system cannot find the file specified.
Source=System.Configuration
FileName=Microsoft.Practices.Prism
FusionLog==== Pre-bind state information ===
LOG: DisplayName = Microsoft.Practices.Prism
(Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: Microsoft.Practices.Prism | Domain ID: 1
WRN: A partial bind occurs when only part of the assembly display name is provided.
WRN: This might result in the binder loading an incorrect assembly.
WRN: It is recommended to provide a fully specified textual identity for the assembly,
WRN: that consists of the simple name, version, culture, and public key token.
WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue.
LOG: Appbase = file:///C:/Users/Roger/Documents/TestPrismProject/WpfApplication1/WpfApplication1/bin/Debug/
LOG: Initial PrivatePath = NULL
Calling assembly : System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a.
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Users\Roger\Documents\TestPrismProject\WpfApplication1\WpfApplication1\bin\Debug\WpfApplication1.exe.Config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Users/Roger/Documents/TestPrismProject/WpfApplication1/WpfApplication1/bin/Debug/Microsoft.Practices.Prism.DLL.
LOG: Attempting download of new URL file:///C:/Users/Roger/Documents/TestPrismProject/WpfApplication1/WpfApplication1/bin/Debug/Microsoft.Practices.Prism/Microsoft.Practices.Prism.DLL.
LOG: Attempting download of new URL file:///C:/Users/Roger/Documents/TestPrismProject/WpfApplication1/WpfApplication1/bin/Debug/Microsoft.Practices.Prism.EXE.
LOG: Attempting download of new URL file:///C:/Users/Roger/Documents/TestPrismProject/WpfApplication1/WpfApplication1/bin/Debug/Microsoft.Practices.Prism/Microsoft.Practices.Prism.EXE.
StackTrace:
at System.Configuration.TypeUtil.GetTypeWithReflectionPermission(IInternalConfigHost host, String typeString, Boolean throwOnError)
at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.Init(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord)
at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.InitWithRestrictedPermissions(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord)
at System.Configuration.RuntimeConfigurationRecord.CreateSectionFactory(FactoryRecord factoryRecord)
at System.Configuration.BaseConfigurationRecord.FindAndEnsureFactoryRecord(String configKey, Boolean& isRootDeclaredHere)
InnerException:
The solution ended up being simple, as these things often are... I hadn't changed my App.config file's Build Action to "Resource" (can be found by clicking on the App.config file and looking at the properties section).
In the newer versions of Prism (I'm using 6.3.0), the ModulesConfigurationSection class is in Prism.Wpf.dll.
Change your configuration to this:
<configSections>
<section name="modules" type="Prism.Modularity.ModulesConfigurationSection, Prism.Wpf"/>
</configSections>
I had the same exception (Prism 5.0) and my solution was to set the type of the config section to Microsoft.Practices.Prism.Composition instead of Microsoft.Practices.Prism which I found in many examples.
Add reference Microsoft.Practices.ServiceLocation to your Test Project to resolve this issue.
StackTrace: at
System.Configuration.BaseConfigurationRecord.FindAndEnsureFactoryRecord(String
configKey, Boolean& isRootDeclaredHere) 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) at
System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String
sectionName) at
System.Configuration.ConfigurationManager.GetSection(String
sectionName) at
Microsoft.Practices.Prism.Modularity.ConfigurationStore.RetrieveModuleConfigurationSection()
at
The call stack itself indicates that Prism is already loaded, but when it tries to parse the .config file, an exception happens in RetrieveModuleConfigurationSection.
You might start from there to check what might be the cause.
I changed Prism.Core version 6.2.1 to 6.2.0 and it works for me.
I've encountered similar issue last time. My solution was different and very specific but error was same. If you are sending you binaries and target PC uses Windows 10 make sure that you unblock all files.

Error only occurs after publishing: "Unable to connect to any of the specified MySQL hosts."

During development the program runs fine, but once published I noticed my elements weren't populating properly. I thought at first it was a problem with the update panels, but someone told me to use Firebug, and this is the error I see being thrown.
Again:
"Unable to connect to any of the specified MySQL hosts."
My code(This part is from the web.config):
<connectionStrings>
<add name="MySQLConnection" connectionString="[myServer];[myDatabase];UID= [myID];PWD=[myPassword];"
providerName="MySql.Data.SqlClient" />
</connectionStrings>
In C#, I call the connection string thusly:
string connstring = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["MySQLConnection"].ConnectionString;
MySqlConnection myConnection = new MySqlConnection(connstring);
Any input on why this isn't working, or why it works in development and not once published, would be greatly appreciated.
Thanks.
EDIT: New information
Oh my god, this is maddening.
So my program had a second web.config file, and I had previously put a connection string in that one with incorrect data. When the program ran that's what it was trying to use, and that's why it wasn't working. Or so I thought.
I found this out, of course, after thinking it was the same file, and simply trying to update it. Finally I removed the connection string from the old file altogether, and what do you know, I now know that it's using the proper connection string.
Hoo-ray for me, right? Nope.
I now know that it is using the correct connection string, and yet it is still somehow not working.
That being said, I added some better troubleshooting in, so now I have this:
MySql.Data.MySqlClient.MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts. ---> System.Security.SecurityException: Request for the permission of type 'System.Net.SocketPermission, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
at System.Security.CodeAccessSecurityEngine.Check(Obj ect demand, StackCrawlMark& stackMark, Boolean isPermSet)
at System.Security.CodeAccessSecurityEngine.Check(Cod eAccessPermission cap, StackCrawlMark& stackMark)
at System.Security.CodeAccessPermission.Demand()
at System.Net.Sockets.Socket.CheckCacheRemote(EndPoin t& remoteEP, Boolean isOverwrite)
at System.Net.Sockets.Socket.BeginConnectEx(EndPoint remoteEP, Boolean flowContext, AsyncCallback callback, Object state)
at System.Net.Sockets.Socket.BeginConnect(EndPoint remoteEP, AsyncCallback callback, Object state)
at MySql.Data.Common.StreamCreator.CreateSocketStream (IPAddress ip, Boolean unix)
at MySql.Data.Common.StreamCreator.GetStream(UInt32 timeout)
at MySql.Data.MySqlClient.NativeDriver.Open()
The action that failed was:
Demand
The type of the first permission that failed was:
System.Net.SocketPermission
The Zone of the assembly that failed was:
MyComputer
at MySql.Data.MySqlClient.NativeDriver.Open()
at MySql.Data.MySqlClient.Driver.Create(MySqlConnecti onStringBuilder settings)
at MySql.Data.MySqlClient.MySqlPool.GetPooledConnecti on()
at MySql.Data.MySqlClient.MySqlPool.TryToGetDriver()
at MySql.Data.MySqlClient.MySqlPool.GetConnection()
at MySql.Data.MySqlClient.MySqlConnection.Open()
at WordsOfPower.testing.update_words() in C:\Users\AJ\documents\visual studio 2010\Projects\WordsOfPower\WordsOfPower\WordsOfPow er.aspx.cs:line 39
Final Edit: I updated my web.config to use full trust.
http://support.winhost.com/KB/a657/changing-the-default-aspnet-trust-level.aspx
Make sure the connection string in the web.config file is correct
<add name="STRING_CONNECTION" connectionString="Server=[SERVER];Database=[DATA BASE NAME];Uid=[USER];Pwd=[PASSWORD];" providerName="MySql.Data.MySqlClient"/>
That is a trust issue.
See http://www.marthijnvandenheuvel.com/2011/04/14/fix-net-4-socketpermission-for-mysql-driver-in-medium-trust/

How can I stop this third-party DLL from throwing Security Exceptions in my full trust web application

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.

Categories

Resources