Unable to find assembly with BinaryFormatter.Deserialize - c#

i hope you can help me.
i'm de-serializing a custom object and i'm getting this error.
the type is in a dll which is loaded using a windows hook - thus, running under explorer.exe
i understand why this error occurs, this because the DLL doesnt reside "explorer.exe" process.
there are 2 solutions for this:
1. install the assembly in GAC
2. use the "Binder" of the binary formatter.
i don't want to use any of those, as the DLL is actually loaded in explorer.exe (when i'm attaching, i see that the DLL is indeed loaded).
i'm serializing a custom object - created in the same DLL that does the de-serializing
this is my code:
BinaryFormatter binaryFormatter = new BinaryFormatter();
byte[] serializedObject;
using (MemoryStream memoryStream = new MemoryStream())
{
binaryFormatter.Serialize(memoryStream, new MyCustomObject());
serializedObject = memoryStream.ToArray();
}
BinaryFormatter binaryFormatter2 = new BinaryFormatter();
object deserializedObject;
using (MemoryStream memoryStream2 = new MemoryStream(serializedObject))
{
deserializedObject = binaryFormatte2r.Deserialize(memoryStream2); // Unable to find this assembly
}
by the way. i've looked a bit in the binary formatter code, somehow it does tries to load the DLL.. but it's already loaded to the process..
error:
Unable to find assembly 'AssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=Key'.
stack trace:
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.BinaryConverter.TypeFromInfo(BinaryTypeEnum binaryTypeEnum, Object typeInformation, ObjectReader objectReader, BinaryAssemblyInfo assemblyInfo, InternalPrimitiveTypeE& primitiveTypeEnum, String& typeString, Type& type, Boolean& isVariant)
at
System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadArray(BinaryHeaderEnum binaryHeaderEnum)
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.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream)
-- edit--
i'm using namespace extensions (so the OS hooks to my dlls)

It's too late, but my solution is shown below. The implementation of BindToType is overridden to solve your issue.
[Serializable]
public class YourClass : SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
Type tyType = null;
string sShortAssemblyName = assemblyName.Split(',')[0];
Assembly[] ayAssemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly ayAssembly in ayAssemblies)
{
if (sShortAssemblyName == ayAssembly.FullName.Split(',')[0])
{
tyType = ayAssembly.GetType(typeName);
break;
}
}
return tyType;
}
...
This link helped me

Related

extent reports not generating reports

I am using extentent reports to generate report but the test excution fails on extent.flush() method. I am using
extentreports 3.1.3
Specflow.xunit 2.2.1
This code use to work previously but not working anymore. Error returned :
System.IO.FileNotFoundException
HResult=0x80070002
Message=Could not load file or assembly 'System.Web.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified.
Source=RazorEngine
StackTrace:
at RazorEngine.Compilation.CSharp.CSharpDirectCompilerService..ctor(Boolean strictMode, Func1 markupParserFactory)
at RazorEngine.Compilation.DefaultCompilerServiceFactory.CreateCompilerService(Language language)
at RazorEngine.Templating.RazorEngineCore.CreateTemplateType(ITemplateSource razorTemplate, Type modelType)
at RazorEngine.Templating.RazorEngineCore.Compile(ITemplateKey key, Type modelType)
at RazorEngine.Templating.RazorEngineService.CompileAndCacheInternal(ITemplateKey key, Type modelType)
at RazorEngine.Templating.RazorEngineService.GetCompiledTemplate(ITemplateKey key, Type modelType, Boolean compileOnCacheMiss)
at RazorEngine.Templating.RazorEngineService.RunCompile(ITemplateKey key, TextWriter writer, Type modelType, Object model, DynamicViewBag viewBag)
at RazorEngine.Templating.RazorEngineServiceExtensions.<>c__DisplayClass16_0.<RunCompile>b__0(TextWriter writer)
at RazorEngine.Templating.RazorEngineServiceExtensions.WithWriter(Action1 withWriter)
at AventStack.ExtentReports.Reporter.ExtentHtmlReporter.Flush()
at AventStack.ExtentReports.Model.Report.<>c.b__29_1(IExtentReporter x)
at System.Collections.Generic.List1.ForEach(Action1 action)
at AventStack.ExtentReports.Model.Report.NotifyReporters()
at AventStack.ExtentReports.Model.Report.Flush()
at AventStack.ExtentReports.ExtentReports.Flush()
at XUnitTestProject5.UnitTest1.Test1() in C:\Users\kotar\source\repos\XUnitTestProject5\XUnitTestProject5\UnitTest1.cs:line 25
var HTMLReporter = new ExtentHtmlReporter(#"C:\test\TestReport.html");
HTMLReporter.Configuration().Theme = AventStack.ExtentReports.Reporter.Configuration.Theme.Dark;
var extent = new ExtentReports();
extent.AttachReporter(HTMLReporter);
var featurename = extent.CreateTest<Feature>("login feature");
var scenario= featurename.CreateNode<Scenario>("Login as a user ");
scenario.CreateNode<Given>("user has access to the methos ");
extent.Flush();
If you are using .net core, you have to use "ExtentReports.Core" NuGet package instead of "ExtentReports" and initialize your extent object like this :
public AventStack.ExtentReports.ExtentReports _extent = new
AventStack.ExtentReports.ExtentReports();

xaml parse exception issue only on win7

I have an issue where I got error
id 1000 (KERNELBASE.dll)
and
error id 1026 System.IO.FileNotFoundException
When I try to run my program on Win 7 (witch had run fine before), but it runs perfectly on win 8/8.1/10. I am running .Net Framework 4.5.
I had been trying to deleting the code, but then the error just appears on other lines off my code and thats keeps going on, so does anyone know how to fix it or know how to find out what actually are causing that issue
Binding Failure occurred
Message : Managed Debugging Assistant ' Binding Failure ' has detected a problem in ' F: \ Omini \ Omini Dækberegner.exe ' .
Additional information : the assembly with the display name ' PresentationFramework.Aero2 ' could not be loaded into the binding context '
C#
InitializeComponent();
bredebox_nu.Focus();
textBoxes = new List<TextBox> { bredebox_nu, profilbox_nu, Fælgestr_nu, bredebox_ny, profilbox_ny, Fælgestr_ny, oprofilbox, obredebox, oFælgestr };
win.SourceInitialized += new EventHandler(win_SourceInitialized);
List<biler> items = new List<biler>();
the other error
System.Windows.Markup.XamlParseException occurred
HResult=-2146233087
Line Number = 616
Line Position = 48
Message = ' There were triggered an exception at setting the property ' System.Windows.FrameworkElement.Style ' . ' Line number ' 616 ' and line position ' 48' .
Source = Presentation Framework
Stack Trace :
by System.Windows.Markup.WpfXamlLoader.Load ( XamlReader xamlReader , IXamlObjectWriterFactory writer factory , Boolean skipJournaledProperties , Object rootObject , XamlObjectWriterSettings settings , Uri baseUri )
by System.Windows.Markup.WpfXamlLoader.LoadBaml ( XamlReader xamlReader , Boolean skipJournaledProperties , Object rootObject , XamlAccessLevel access level , Uri baseUri )
by System.Windows.Markup.XamlReader.LoadBaml ( Stream stream , ParserContext parserContext , Object parent , Boolean close stream)
by System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
by Omini_Tires_And_rims.MainWindow.InitializeComponent() i C:\Users\Sindakewin\documents\visual studio 2015\Projects\omini_dækberegner\omini_dækberegner\MainWindow.xaml:linje 1
by Omini_Tires_And_rims.MainWindow..ctor() i C:\Users\Sindakewin\documents\visual studio 2015\Projects\omini_dækberegner\omini_dækberegner\MainWindow.xaml.cs:linje 210
InnerException:
FileName=PresentationFramework.Aero2, PublicKeyToken=31bf3856ad364e35
FusionLog ==== state information prior binding ===
LOG: Display Name = PresentationFramework.Aero2, PublicKeyToken = 31bf3856ad364e35
(Partial)
WRN: There was delivered about a partial binding for assembly:
WRN: Assemblyname: PresentationFramework.Aero2, PublicKeyToken = 31bf3856ad364e35 | Domain ID: 1
WRN: A partial binding Occurs tabloid is only given part of assemblyens display name.
WRN This may cause the binder inputting a wrong assembly.
WRN: It is recommended to give up fully specified text ID for the Assembly,
WRN: consisting of the simple name, version, culture and token for the public key.
WRN: For more information and common solutions to this problem in the white paper http://go.microsoft.com/fwlink/?LinkId=109270.
LOG: Appbase = file: /// F: / Omini /
LOG: First PrivatePath = NULL
Calling assembly: Presentation Framework, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = 31bf3856ad364e35.
LOG: This binding initiates in loadingcontex default.
LOG: User application configuration file: F: \ Omini \ Omini Dækberegner.exe.Config
LOG: User host configuration file:
LOG: User machineconfigurationsfile from C: \ Windows \ Microsoft.NET \ Framework \ v4.0.30319 \ config \ machine.config.
LOG: Policy not applied to reference at this time (private, custom, partial, or location-based assemblybinding).
LOG: Attempting to download new URL file: /// F: /Omini/PresentationFramework.Aero2.DLL.
LOG: Attempting to download new URL file: /// F: /Omini/PresentationFramework.Aero2/PresentationFramework.Aero2.DLL.
LOG: Attempting to download new URL file: /// F: /Omini/PresentationFramework.Aero2.EXE.
LOG: Attempting to download new URL file: /// F: /Omini/PresentationFramework.Aero2/PresentationFramework.Aero2.EXE.
)
HRESULT = -2147024894
Message = The file or the assembly ' PresentationFramework.Aero2 , PublicKeyToken = 31bf3856ad364e35 ' or one of its dependencies could not be loaded . The specified file was not found.
Source = mscorlib
StackTrace:
by System.Reflection.RuntimeAssembly._nLoad (AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly location hint, Stack Crawl Mark & ​​stack field, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
by System.Reflection.RuntimeAssembly.nLoad (AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly location hint, Stack Crawl Mark & ​​stack field, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
by System.Reflection.RuntimeAssembly.InternalLoadAssemblyName (AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, Stack Crawl Mark & ​​stack field, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
by System.Reflection.Assembly.Load (AssemblyName assemblyRef)
by System.Windows.Baml2006.Baml2006SchemaContext.ResolveAssembly (BamlAssembly bamlAssembly)
by System.Windows.Baml2006.Baml2006SchemaContext.ResolveBamlTypeToType (BamlType bamlType)
by System.Windows.Baml2006.Baml2006SchemaContext.ResolveBamlType (BamlType bamlType, int16 typeid)
by System.Windows.Baml2006.Baml2006SchemaContext.GetXamlType (int16 typeid)
by System.Windows.Baml2006.Baml2006Reader.Process_ElementStart ()
by System.Windows.Baml2006.Baml2006Reader.Process_OneBamlRecord ()
by System.Windows.Baml2006.Baml2006Reader.ReadObject (KeyRecord record)
by System.Windows.ResourceDictionary.CreateObject (KeyRecord key)
by System.Windows.ResourceDictionary.OnGettingValue (Object key, Object & value, Boolean & canCache)
by System.Windows.ResourceDictionary.OnGettingValuePrivate (Object key, Object & value, Boolean & canCache)
by System.Windows.ResourceDictionary.GetValueWithoutLock (Object key, Boolean & canCache)
by System.Windows.ResourceDictionary.GetValue (Object key, Boolean & canCache)
by System.Windows.DeferredResourceReference.GetValue (Base Value Source Internal value source)
by System.Windows.DependencyPropertyChangedEventArgs.get_NewValue ()
by System.Windows.Controls.Control.OnTemplateChanged (DependencyObject d, DependencyPropertyChangedEventArgs e)
by System.Windows.DependencyObject.OnPropertyChanged (DependencyPropertyChangedEventArgs e)
by System.Windows.FrameworkElement.OnPropertyChanged (DependencyPropertyChangedEventArgs e)
by System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
by System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
by System.Windows.StyleHelper.ApplyStyleOrTemplateValue(FrameworkObject fo, DependencyProperty dp)
by System.Windows.StyleHelper.InvalidateContainerDependents(DependencyObject container, FrugalStructList`1& exclusionContainerDependents, FrugalStructList`1& oldContainerDependents, FrugalStructList`1& newContainerDependents)
by System.Windows.StyleHelper.DoStyleInvalidations(FrameworkElement fe, FrameworkContentElement fce, Style oldStyle, Style newStyle)
by System.Windows.StyleHelper.UpdateStyleCache(FrameworkElement fe, FrameworkContentElement fce, Style oldStyle, Style newStyle, Style& styleCache)
by System.Windows.FrameworkElement.OnStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
by System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
by System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
by System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
by System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
by System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal)
by System.Windows.Baml2006.WpfKnownMemberInvoker.SetValue(Object instance, Object value)
by MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(XamlMember member, Object obj, Object value)
by MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(Object inst, XamlMember property, Object value)
InnerException:
Xaml <GridViewColumn Header="Model" Width="140" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock x:Name="Txt" Text="{Binding Model}" Foreground="#FF00FB0B" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
i removed PresentationFramework.Aero2 from the references in visual studio and replaced it with PresentationFramework.Aero and deleted some of the themes and replaced the namespaces and now it runs fine on win 7 and win vista without any issues

There was an error in serializing body of message

I am getting exception on trying to consume a service (3rd party), below is the stack trace for the exception.
StackTrace " at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)\r\n at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle)\r\n at System.ServiceModel.Dispatcher.XmlSerializerOperationFormatter.SerializeBody(XmlDictionaryWriter writer, MessageVersion version, XmlSerializer serializer, MessagePartDescription returnPart, MessagePartDescriptionCollection bodyParts, Object returnValue, Object[] parameters)\r\n at System.ServiceModel.Dispatcher.XmlSerializerOperationFormatter.SerializeBody(XmlDictionaryWriter writer, MessageVersion version, String action, MessageDescription messageDescription, Object returnValue, Object[] parameters, Boolean isRequest)" string
Earlier it was working fine, but after updating the service reference it started throwing the above exception.
Also tried the solution described in the below link, but was of no help.
There was an error in serializing body of message
Appreciate your kind help in resolving the same.
Below is the code that i am using
//reportContent is having xml data as string.
XmlDocument xmlReportDocument = new XmlDocument();
xmlReportDocument.LoadXml(reportContent);
RequestHandlerProcessSoapClient ws = new RequestHandlerProcessSoapClient();
ws.ClientCredentials.UserName.UserName = _reportFormatData.User;
ws.ClientCredentials.UserName.Password = _reportFormatData.Password;
///Create the request
myRequest request = new myRequest();
request.Requestor = new Requestor();
request.Requestor.ApplicationID = _reportFormatData.ApplicationId;
request.Requestor.Stylesheet = template;
request.Requestor.Environment = _reportFormatData.Environment;
request.Payload = xmlReportDocument;
///Setup the attachements
myAttachmentRequest attachmentrequest = new myAttachmentRequest();
attachmentrequest.setRequest = request;
myResponse serResp = ws.renderDocument(attachmentrequest)//Error shows up in this line.
Finally found the solution to this question. After adding a service reference, by default payload property in Reference.cs was returning a value of type 'Object', and this i changed it to return System.Xml and it clicked.

ASP.NET SessionState SQLServer mode - System.Xml.XmlBoundElement is not marked as serializable

I am currently modifying an ASP.NET (3.5) application to run in SQLServer SessionState
mode. In the existing code, we have a serialized dataset that is currently stored in
the Session using C#. I have a property that I use to extract this serialized dataset
and load it into a XmlDataDocument. My property is "something" like this:
public abstract class TransCommand
{
public static XmlDataDocument TransDoc
{
get
{
XmlDataDocument doc = null;
if (Session["DataSetStore"] != null)
{
DataSet tds3 = new DataSet();
MemoryStream tms3 = new MemoryStream(HttpContext.Current.Session["DataSetStore"] as byte[]);
doc = new XmlDataDocument();
doc.LoadXml(System.Text.Encoding.UTF8.GetString(tms3.ToArray()));
}
return doc;
}
set
{
Session["DataSetStore"] = System.Text.Encoding.UTF8.GetBytes(value.OuterXml);
}
}
This works great except when I try to append an XmlNode to a node created from this
TransDoc method.
public class AddChildren
{
XmlDataDocument doc = TransactionCommand.TransactionDoc;
doc.DataSet.EnforceConstraints = false;
XmlNode dataNode = doc.SelectSingleNode("//WebServiceResponse/Data");
......
ArrayList lstNewInfants = new ArrayList();
1stNewInfants.add(newInfants); //Adding new Infants XmlNodes into an arraylist.
foreach (XmlNode nodInfant in lstNewInfants)
{
dataNode.AppendChild(nodInfant);
}
doc.DataSet.EnforceConstraints = true;
TransactionCommand.TransactionDoc = doc; //Adds the modified doc back into the session
After appending this node, I receive the following exception after the Databind of the
next page aspx page encountered:
Error Message:Type 'System.Xml.XmlBoundElement' in Assembly 'System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
Stack Trace: at System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type)
at System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context)
at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo()
at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter)
at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter)
at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck)
at System.Web.Util.AltSerialization.WriteValueToStream(Object value, BinaryWriter writer)
Any Ideas?

Intermittent errors while de-serializing object from XML

I have a program that takes objects stored as XML in a database (basicly a message queue) and de-serializes them. Intermittently, I will get one of the following errors:
System.Runtime.InteropServices.ExternalException: Cannot execute a program. The command being executed was "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\csc.exe" /noconfig /fullpaths #"C:\Documents and Settings\useraccount\Local Settings\Temp\lh21vp3m.cmdline".
at System.CodeDom.Compiler.Executor.ExecWaitWithCaptureUnimpersonated(SafeUserTokenHandle userToken, String cmd, String currentDir, TempFileCollection tempFiles, String& outputName, String& errorName, String trueCmdLine)
at System.CodeDom.Compiler.Executor.ExecWaitWithCapture(SafeUserTokenHandle userToken, String cmd, String currentDir, TempFileCollection tempFiles, String& outputName, String& errorName, String trueCmdLine)
at Microsoft.CSharp.CSharpCodeGenerator.Compile(CompilerParameters options, String compilerDirectory, String compilerExe, String arguments, String& outputFile, Int32& nativeReturnValue, String trueArgs)
at Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch(CompilerParameters options, String[] fileNames)
at Microsoft.CSharp.CSharpCodeGenerator.FromSourceBatch(CompilerParameters options, String[] sources)
at Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options, String[] sources)
at System.CodeDom.Compiler.CodeDomProvider.CompileAssemblyFromSource(CompilerParameters options, String[] sources)
at System.Xml.Serialization.Compiler.Compile(Assembly parent, String ns, XmlSerializerCompilerParameters xmlParameters, Evidence evidence)
at System.Xml.Serialization.TempAssembly.GenerateAssembly(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, Evidence evidence, XmlSerializerCompilerParameters parameters, Assembly assembly, Hashtable assemblies)
at System.Xml.Serialization.TempAssembly..ctor(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, String location, Evidence evidence)
at System.Xml.Serialization.XmlSerializer.GenerateTempAssembly(XmlMapping xmlMapping, Type type, String defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type)
.....
Or I'll get this one:
System.InvalidOperationException: Unable to generate a temporary class (result=1).
error CS0016: Could not write to output file 'c:\Documents and Settings\useraccount\Local Settings\Temp\nciktsd7.dll' -- 'Could not execute CVTRES.EXE.'
at System.Xml.Serialization.Compiler.Compile(Assembly parent, String ns, XmlSerializerCompilerParameters xmlParameters, Evidence evidence)
at System.Xml.Serialization.TempAssembly.GenerateAssembly(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, Evidence evidence, XmlSerializerCompilerParameters parameters, Assembly assembly, Hashtable assemblies)
at System.Xml.Serialization.TempAssembly..ctor(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, String location, Evidence evidence)
at System.Xml.Serialization.XmlSerializer.GenerateTempAssembly(XmlMapping xmlMapping, Type type, String defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type)
....
The program process thousands of messages a day successfully, but I only get these errors maybe 2 or 3 times a day. They don't appear to be correlated to any specific kind of message, just completely random.
Any idea what causes those errors and how to fix it?
ETA - Here's the code that is causing the errors, in case that helps:
public class MessageContextBuilder<T> where T : MessageContextBase
{
private static IDictionary<string, XmlSerializer> SerializerCache { get; set; }
public ILog Logger { get; set; }
public MessageContextBuilder() {
if (SerializerCache == null) SerializerCache = new Dictionary<string, XmlSerializer>();
Logger = LogContextManager.Context.GetLogger<MessageContextBuilder<T>>();
}
public T BuildContextFromMessage(IEmailQueueMessage msg) {
XmlSerializer serializer = GetSerializer(typeof(T));
XmlReader r = XmlReader.Create(new StringReader(msg.MessageDetails));
if (serializer.CanDeserialize(r)) {
T rval = (T)serializer.Deserialize(r);
rval.EmailAddress = msg.EmailAddress;
rval.LocaleID = msg.LocaleID;
rval.StoreID = msg.StoreID;
rval.MessageID = msg.UniqueKey;
return rval;
} else {
throw new ArgumentException("Cannot deserialize XML in message details for message #" + msg.UniqueKey);
}
}
public XmlSerializer GetSerializer(Type t) {
if (!SerializerCache.ContainsKey(t.FullName)) {
SerializerCache.Add(t.FullName, new XmlSerializer(t)); // Error occurs here, in XmlSerializer constructor, intermittently
}
return SerializerCache[t.FullName];
}
}
You can pre-create serializers: http://msdn.microsoft.com/en-us/library/bk3w6240%28v=VS.100%29.aspx Just give it a try. The next canonical candidate for such problems is your virus scanner. Your tool is writing to disc while creating serializers. I have seen virus scanner producing all kind of strange errors in such situations.
XmlSerializer is supposed to be thread safe.
Even if that's the case, you can notice the behavior you are getting is in both cases failing at: XmlSerializer..ctor(Type type)
Given that, it seriously look like a multi-threading limitation trying to create serializers.
I suggest to take this code you have:
public XmlSerializer GetSerializer(Type t) {
if (!SerializerCache.ContainsKey(t.FullName)) {
SerializerCache.Add(t.FullName, new XmlSerializer(t)); // Error occurs here, intermittently
}
return SerializerCache[t.FullName];
}
And implement a lock on the Add. This way you are only creating 1 serializer at a time. The hit is small if you aren't processing tons of different types.
Note that you need the lock anyway, as the way it is you could get duplicate exceptions when 2 types try to be added at the same time.
static object serializerCacheLock = new object();
public XmlSerializer GetSerializer(Type t) {
if (!SerializerCache.ContainsKey(t.FullName))
lock(serializerCacheLock)
if (!SerializerCache.ContainsKey(t.FullName)) {
SerializerCache.Add(t.FullName, new XmlSerializer(t));
}
return SerializerCache[t.FullName];
}
If the above still isn't enough, I'd try with a read/write lock on serializer constructor vs. serializers usage. Line of thought being that maybe the multi-threading issue is worth than 2 ctors running at the same time.
All above is a Huge guess, but if it were me I'd definitely confirm is not that.
For the first error (cannot execute a program), you might be running into the same XmlSerializer bug that we ran into. It turns out XmlSerlializer throws that exception when Directory.CurrentDirectory is set to a folder that no longer exists.
Our specific situation is different than yours, but I'll give the details in case it helps shed light on what might be happening for you, or it helps anyone else. In our case, a small number of our customers would get that error after launching our WinForms application directly from the installer, i.e. they chose the "run now" option after installing or upgrading. (Unclear why it happened to some but not others). What we suspect is happening is that our installer (InstallAware) occasionally starts our application with the current directory set to a folder that no longer exists, or is about to be deleted. To test this theory, I wrote a test app which simulates launching from the installer:
string dir = #"C:\Users\me\Documents\Temp\WillBeDeleted";
Directory.CreateDirectory(dir);
Directory.SetCurrentDirectory(dir);
Process.Start(#"C:\Program Files (x86)\...\our.exe");
Directory.SetCurrentDirectory(#"C:\"); // otherwise, won't be able to delete
Directory.Delete(dir);
Sure enough, as soon as the launched application created a new instance of XmlSerializer, the exception would be thrown. I put in trace statements to show the result of GetCurrentDirectory(), and indeed it was set to the WillBeDeleted folder. The fix was to SetCurrentDirectory to a valid location during application initialization, before any serialization took place.
This is a sign that you are not caching your serialisers which is not good at all => it leads to memory leak and I suspect you will experience this.
Remember that .NET generates code and compiles them into assemblies every time you create a serialiser.
Always create your serialisers and then cache them.
Here is a sample:
public class SerialiserCache
{
private static readonly SerialiserCache _current = new SerialiserCache();
private Dictionary<Type, XmlSerializer> _cache = new Dictionary<Type, XmlSerializer>();
private SerialiserCache()
{
}
public static SerialiserCache Current
{
get { return _current; }
}
public XmlSerializer this[Type t]
{
get
{
LoadIfNecessary(t);
return _cache[t];
}
}
private void LoadIfNecessary(Type t)
{
// double if to prevent race conditions
if (!_cache.ContainsKey(t))
{
lock (_cache)
{
if (!_cache.ContainsKey(t))
{
_cache[t] = new XmlSerializer(typeof(T));
}
}
}
}
}

Categories

Resources