Error when embedding report viewer dll using costura - c#

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>

Related

log4net: error could not create appender [RollingLogFileAppender]

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!

Unable to open designer form

I recently had problems opening my Designer View of a form hat acts as launcher for all the other forms.
The solutions I found according to that suggest to delete the .RESX files which helped for some days now (always had to delete RESX before debuging the program) today, after trying to debug another time I got stuck with this screen:
This seems to be caused by me deleting the resx files.
I can not find anything according to this online.
I tried to rebuild the project, getting the deleted file(s) back from the paperbin but nothing seems to help right here and I just do not understand what this error message is supposed to tell me...
bei System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
bei Microsoft.VisualStudio.NativeMethods.ThrowOnFailure(Int32 hr, Int32[] expectedHRFailure)
bei Microsoft.VisualStudio.Shell.Design.Serialization.DesignerDocDataService.GetFileDocData(String fileName, FileAccess access, String createTemplate, Boolean addToHostList, Boolean nestedItem)
bei Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomProvider.OnParseBegin(TextReader reader)
bei Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomParser.Parse(TextReader codeStream)
bei Microsoft.VisualStudio.Design.Serialization.CodeDom.MergedCodeDomParser.System.CodeDom.Compiler.ICodeParser.Parse(TextReader stream)
bei System.CodeDom.Compiler.CodeDomProvider.Parse(TextReader codeStream)
bei Microsoft.VisualStudio.Shell.Design.Serialization.CodeDom.CodeDomDocDataAdapter.get_CompileUnit()
bei Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager serializationManager)
bei System.ComponentModel.Design.Serialization.BasicDesignerLoader.BeginLoad(IDesignerLoaderHost host)
(Nothing in Errorlist)

issue with reference to .dll

currently making a small program by using WinForms and 7zip unpacker. To make it easier added reference to "SevenZipSharp.dll" everything work good, untill i wanted to publish(debug) project. When i move the ".exe" file in Desktop got error :
System.IO.FileNotFoundException: Could not load file or
assembly 'X' or one of its dependencies".
I embedded resource set in .dll file + Copy Local: set to true
How i can make this programs to work without .dll in Current directory.
EDIT
I did it by use
System.Reflections
Solution here
But i got now another problem with
System.TypeInitializationException: 'The type initializer for 'SevenZip.SevenZipLibraryManager' threw an exception.. ---> System.ArgumentException: Path has an illegal format
w System.IO.Path.LegacyNormalizePath(String path, Boolean fullCheck, Int32 maxPathLength, Boolean expandShortPaths)
w System.IO.Path.NormalizePath(String path, Boolean fullCheck, Int32 maxPathLength, Boolean expandShortPaths)
w System.IO.Path.InternalGetDirectoryName(String path)
w System.IO.Path.GetDirectoryName(String path)
w SevenZip.SevenZipLibraryManager..cctor()
--- End of inner exception stack trace ---
w SevenZip.SevenZipLibraryManager.SetLibraryPath(String libraryPath)
w SevenZip.SevenZipBase.SetLibraryPath(String libraryPath)
You would want to have the referenced libraries in the same folder or else you can also register them in GAC.

NullReferenceException on XML Deserialization in dynamically loaded assembly

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.

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