Deserializing List<IList> - c#

I'm migrating a set of applications from .Net Framework 4.7 to .Net 5.0, but I'm running into some issues with deserializion.
The example below illustrates the problem I'm facing. If both applications are .Net framework, it works fine. If both are .Net 5.0, it works fine. But if one application is .Net 4.7 and the other is 5.0, I get an exception when deserializing the type List<IList>.
.Net 5.0 application CreateData:
using System;
using System.Collections;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Test;
namespace CreateData
{
class Program
{
static void Main()
{
DataStructure dataStructure = new DataStructure();
ArrayList arrayList = new ArrayList();
arrayList.Add(42);
dataStructure.data.Add(arrayList);
// Open a stream for writing
FileStream fs = new FileStream(#"C:\DataFile.dat", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, dataStructure);
fs.Close();
Console.WriteLine("Data file created, press Enter to exit");
Console.ReadLine();
}
}
}
.Net Standard 2.0 library Lib:
using System;
using System.Collections;
using System.Collections.Generic;
namespace Test
{
[Serializable]
public class DataStructure
{
public DataStructure()
{
data = new List<IList>();
}
public List<IList> data;
}
}
.Net 4.7 application ReadData:
using System;
using System.Linq;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Test;
namespace ReadData
{
class Program
{
static void Main()
{
DataStructure dataStructure = new DataStructure();
// Open the data file
FileStream fs = new FileStream(#"C:\DataFile.dat",FileMode.Open);
// Construct the binary formatter
BinaryFormatter bf = new BinaryFormatter();
// deserialize
dataStructure = (DataStructure) bf.Deserialize(fs);
fs.Close();
// Announce success
Console.WriteLine("Value = {0}", dataStructure.data.First()[0]);
Console.WriteLine("Press enter to exit");
Console.ReadLine();
}
}
}
System.Runtime.Serialization.SerializationException: Unable to load
type System.Collections.Generic.List`1[[System.Collections.IList,
System.Private.CoreLib, Version=5.0.0.0, Culture=neutral,
PublicKeyToken=7cec85d7bea7798e]] required for deserialization. at
System.Runtime.Serialization.ObjectManager.CompleteObject(ObjectHolder
holder, Boolean bObjectFullyComplete) at
System.Runtime.Serialization.ObjectManager.DoNewlyRegisteredObjectFixups(ObjectHolder
holder) at
System.Runtime.Serialization.ObjectManager.RegisterObject(Object obj,
Int64 objectID, SerializationInfo info, Int64 idOfContainingObj,
MemberInfo member, Int32[] arrayIndex) at
System.Runtime.Serialization.Formatters.Binary.ObjectReader.RegisterObject(Object
obj, ParseRecord pr, ParseRecord objectPr, Boolean bIsString) at
System.Runtime.Serialization.Formatters.Binary.ObjectReader.RegisterObject(Object
obj, ParseRecord pr, ParseRecord objectPr) at
System.Runtime.Serialization.Formatters.Binary.ObjectReader.ParseObjectEnd(ParseRecord
pr) at
System.Runtime.Serialization.Formatters.Binary.ObjectReader.Parse(ParseRecord
pr) 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, HeaderHandler handler, Boolean fCheck,
IMethodCallMessage methodCallMessage) at
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream
serializationStream, HeaderHandler handler, Boolean fCheck) at
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream
serializationStream, HeaderHandler handler) at
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream
serializationStream) at ReadData.Program.Main() in
Is there any way to load the type System.Collections.Generic.List1[[System.Collections.IList, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]? What can I do to resolve this?
If at all possible, I would like to migrate one application at a time instead of migrating the entire code base in one go.
Thanks!

Congratulations! You have found one of the reason not to use BinaryFormatter. Other reasons include safety, performance and size. I would recommend to switch to just about anything else as soon as possible.
The recommended way to manage serialization is to separate the types used for serialization from the types that contain actual logic. This allow the respective types to be adapted for the respective purpose. Things like backward compatibility is simpler since things like adding properties are usually possible, and you have the option to keep multiple versions of the same type in case there are larger changes in the type structure.
I would also highly recommend setting up unit tests, to test that different types serializes/deserializes correctly. But unit tests are often also a very useful tool to learn what is possible or not with a serialization library.
You might be able to do something like type-mapping, but that is a huge cludge in my opinion. It might also help to change types to something like arrays instead of lists, but if you are changing the serialization format you are probably better of switching to something better. It might be possible to write a converter in .net 4.7 to convert between the old format and a newer format.

Related

BinaryFormatter used in Interop assemblies throws UnsupportedException

Microsoft discourages the use of BinaryFormatter because it poses security problems. See: BinaryFormatter Obsoletion Strategy.
I have a .NET 6.0 WinForms code which uses the Microsoft.Office.Interop.Access.Dao interop assembly. I need it to insert an image into the Data field the Microsoft Access' system table MSysResources. This field has an Attachment Data Type. This is a multi-valued field. Using DAO is the only way of writing to this field. My (somewhat shortened) code goes like this (note: this code did work before I migrated to .NET 6.0):
using Microsoft.Office.Interop.Access.Dao;
namespace CySoft.RibbonPro.Services;
public class AccessImageResourceLoader : IAccessImageResourceLoader
{
public void UpdateImages(string accdbFile, IEnumerable<KeyValuePair<string, Image>> images)
{
var dbe = new DBEngine(); // <====== This line throws the UnsupportedException =====
Database db = dbe.OpenDatabase(accdbFile);
Recordset rs = rs = db.OpenRecordset("SELECT * FROM MSysResources WHERE 0=1", R
ecordsetTypeEnum.dbOpenDynaset, 0, LockTypeEnum.dbOptimistic);
rs.AddNew();
rs.Fields["Type"].Value = "img";
rs.Fields["Name"].Value = name;
rs.Fields["Extension"].Value = ext;
Recordset2 rsAttachment = (Recordset2)rs.Fields["Data"].Value;
rsAttachment.AddNew();
Field2 dataField = (Field2)rsAttachment.Fields["FileData"];
dataField.LoadFromFile(imageInfo.Key);
rsAttachment.Update();
rs.Update();
rs.Close();
db.Close();
}
}
The details are for illustration only. The first code line creating the DBEngine throws the exception:
BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information.
The call stack is:
at System.ComponentModel.Design.DesigntimeLicenseContextSerializer.DeserializeUsingBinaryFormatter(StreamWrapper wrappedStream, String cryptoKey, RuntimeLicenseContext context)
at System.ComponentModel.Design.DesigntimeLicenseContextSerializer.Deserialize(Stream o, String cryptoKey, RuntimeLicenseContext context)
at System.ComponentModel.Design.RuntimeLicenseContext.GetSavedLicenseKey(Type type, Assembly resourceAssembly)
at System.ComponentModel.LicenseManager.LicenseInteropHelper.GetCurrentContextInfo(Type type, Boolean& isDesignTime, String& key)
at System.RuntimeMethodHandle.InvokeMethod(Object target, Span`1& arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Internal.Runtime.InteropServices.LicenseInteropProxy.GetCurrentContextInfo(RuntimeTypeHandle rth, Boolean& isDesignTime, IntPtr& bstrKey)
at CySoft.RibbonPro.Services.AccessImageResourceLoader.UpdateImages(String accdbFile, IEnumerable`1 images) in C:\Users\Oli\Documents\Proj\CySoft\CySoft.RibbonPro\CySoft.RibbonPro\Services\AccessImageResourceLoader.cs:line 21
Where AccessImageResourceLoader.cs:line 21 is var dbe = new DBEngine();
Microsoft wants people to use another type of serialization like JSON or XML. This is not an option in this case, because I am not using it directly. It is Microsoft's own COM library which uses it.
Question:
How can I insert or update a record using Access' Attachment data type in .NET 6+?
My Attempts
I have tried to do it with System.Data.OleDb. I can read the Attachment with OleDb. But any attempt to write to this field using OleDb throws an exception.
Setting the <EnableUnsafeBinaryFormatterSerialization>true</EnableUnsafeBinaryFormatterSerialization> tag in the project file does not help.
Settings the same configuration property in runtimeConfig.template.json does not help either.
I know that I could solve the problem by using Access automtation via an interop assembly. But it has the disadvantage to open the Microsoft Access application. Inserting the image through a database connection is much more elegant and did work before I migrated to .NET 6.0.
You can see here there is a switch to allow the binary serializer for the licenses file
https://github.com/dotnet/runtime/blob/main/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesigntimeLicenseContextSerializer.cs#L20
which is being read by the GetSavedLicenseKey method here
https://github.com/dotnet/runtime/blob/main/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesigntimeLicenseContext.cs#L84-L89
You can set this switch earlier on before initializing the DBEngine object by calling this:
AppContext.SetSwitch("System.ComponentModel.TypeConverter.EnableUnsafeBinaryFormatterInDesigntimeLicenseContextSerialization", true);
I haven't tried it myself but it should work.
This runtime switch might also be settable in the csproj file as described here
https://github.com/dotnet/runtime/blob/main/docs/workflow/trimming/feature-switches.md
Any feature-switch which defines property can be set in csproj file or on the command line as any other MSBuild property. Those without predefined property name the value can be set with following XML tag in csproj file.
<RuntimeHostConfigurationOption Include="<AppContext-Setting>"
Value="false"
Trim="true" />
Final words: There is even more detail on upgrading to .NET 6.0 at this blog which has another method for this flag explained.
https://www.textcontrol.com/blog/2021/12/21/migrate-a-windows-forms-desktop-application-to-dotnet-6/?hmsr=joyk.com&utm_source=joyk.com&utm_medium=referral

Using reflection to instantiate a class from an external assembly

I am currently trying to develop a method of running test classes in external projects programmatically using reflection. Here is a simplified chunk of code that should showcase my problem.
string pathToDLL = #"C:\Path\To\Test\Project\UnitTests.dll";
IEnumerable<Type> testClasses = assembly.GetExportedTypes();
Type testClass = testClasses.First();
object testClassInstance = assembly.CreateInstance(testClass.FullName);
This code throws the following exception:
'assembly.CreateInstance(testClass.FullName)' threw an exception of type 'System.Reflection.TargetInvocationException'
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146232828
HelpLink: null
InnerException: {System.IO.FileNotFoundException: Could not load file or assembly 'Project.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.
File name: 'Project.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'
at Project.UnitTests.TestClass..ctor()}
Message: "Exception has been thrown by the target of an invocation."
Source: "System.Private.CoreLib"
StackTrace: " at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)\r\n at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)\r\n at System.Activator.CreateInstance(Type type, Boolean nonPublic)\r\n at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark)\r\n at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)\r\n at System.Reflection.Assembly.CreateInstance(String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)\r\n at System.Reflection.Assembly.CreateInstance(String typeName)"
In the stack trace it states that it "Could not load file or assembly 'Project.Core...'".
This project is one that the target DLL references directly (one that it tests). Does anyone know why this won't be able to pick up these DLLs automatically?
I've investigated ways of solving this problem:
It could be the way that the dlls have been compiled - this can be changed as I am in control of this - which is currently by running dotnet build */*/project.json at solution level. This successfully compiles everything, and all of the relevant DLLs seem to be populated in the bin folder. I've also investigated whether or not changing to dotnet publish or dotnet build */*/project.json --configuration Release though neither seem to have helped.
I've also looked into using different methods of compilation like Activator.CreateInstance again no dice.
I don't seem to see a way to load multiple DLLs into the same Assembly class so that I can control the references. Since AppDomains have been removed from .NET Core this doesn't look like it is possible, though I may be mistaken/looking in the wrong area.
If what I'm doing doesn't seem like it will be possible, does anyone know if this kind of functionality can be achieved using a different method? I.e. Roslyn?
I just thought that I would update this question with the solution that I managed to find, just in case someone else was having the same problem as I was. Though I would like to thank #Emrah Süngü for pointing me in the right direction.
Emrah drew my attention to the fact that I needed to import the dependencies of the DLL that I wanted to load in order to invoke the classes stored within it. One way to do this is to extend your app.config in order to import those dependencies - however I wanted to do this at runtime (with projects that I didn't know I was going to run prior starting the program) so I needed to look for another solution.
If you aren't using .NET Core this is relatively simple since AppDomains can be used to load all of the dependencies and execute your code. However, since this has been removed from .NET Core I needed to find another solution that would be compatible.
I toyed with the idea of running a separate process (or Powershell), and changing the working directory so that the process was running in the directory that stored all of the dependencies it needed. However, I couldn't find a way of doing this that allowed me to react to the outcome of running the methods.
Later I investigated manipulating the AssemblyLoadContext class, but (at the time of writing) there is little to no documentation on how this class. I did find this answer which was able to helped significantly... https://stackoverflow.com/a/37896162/6012159
In order for it to work I did have to make a slight change, instead of creating a new AssemblyLoader every time (which would cause exceptions to be thrown when trying to invoke methods within the Assembly), I reused the AssemblyLoader each time (Which removed this problem).
public class AssemblyLoader : AssemblyLoadContext
{
private string folderPath;
public AssemblyLoader(string folderPath)
{
this.folderPath = folderPath;
}
protected override Assembly Load(AssemblyName assemblyName)
{
var deps = DependencyContext.Default;
var res = deps.CompileLibraries.Where(d => d.Name.Contains(assemblyName.Name)).ToList();
if (res.Count > 0)
{
return Assembly.Load(new AssemblyName(res.First().Name));
}
else
{
var apiApplicationFileInfo = new FileInfo($"{folderPath}{Path.DirectorySeparatorChar}{assemblyName.Name}.dll");
if (File.Exists(apiApplicationFileInfo.FullName))
{
return this.LoadFromAssemblyPath(apiApplicationFileInfo.FullName);
}
}
return Assembly.Load(assemblyName);
}
}
Which can be use to load assemblies like this:
string directory = #"C:\Path\To\Project\bin\Debug\netcoreapp1.0\publish\";
string pathToDLL = #"C:\Path\To\Project\bin\Debug\netcoreapp1.0\publish\project.dll";
AssemblyLoader al = new AssemblyLoader(directory);
Assembly assembly = al.LoadFromAssemblyPath(pathToDLL);
I am assuming that "UnitTests.dll" depends on (references) other dll(s) and your program does not know where to look for those referenced dll(s). You should (in fact have to) tell it to where to look for those dll(s) as well. By default is the same directory as your EXE. You can use app.config for telling where else to look. For Load() to succeed dependant dll(s) must be stored in your app's probing path.
That is the reason why you are getting an error.
Here you can find related article.
https://msdn.microsoft.com/en-us/library/823z9h8w.aspx

Encrypting executable causes exception in BinaryAssemblyInfo.GetAssembly

I use a dongle to protect my executable. The dongle protects the software in two ways:
inside the code with calls to read/write the dongle memory (for example to store functional data), to encrypt/decrypt data with an algorithm resident in the dongle. The encryption key is writable only.
Encrypting the EXE file and using a loader that decrypts it through the dongle. If any debugger like softice is running, the software either terminates or does not start.
It would work well and make cheaper to buy the license than to crack my software and this is my only goal.
The problem is that I cannot serialize anymore! If I try, I get the following exception:
SerializationException
Source = mscorlib
Message = Unable to find assembly 'MyApp, Version=1.0.0.3, Culture=neutral, PublicKeyToken=null'.
TargetSite = System.Reflection.Assembly GetAssembly()
Stack =
System.Runtime.Serialization.Formatters.Binary.BinaryAssemblyInfo.GetAssembly()
System.Runtime.Serialization.Formatters.Binary.ObjectReader.GetType(BinaryAssemblyInfo assemblyInfo, String name)
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)
System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadObjectWithMapTyped(BinaryObjectWithMapTyped record)
System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadObjectWithMapTyped(BinaryHeaderEnum binaryHeaderEnum)
System.Runtime.Serialization.Formatters.Binary.__BinaryParser.Run()
System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
I must use Binary Serialization due to the nature of the data to be persistent.
How can a solve this problem?
I dedicate an enormous amount of time to this problem and I got to a workaround, more than a true solution.
I share what I learned. The serialization needs to load the assembly that generated the permanent stream in order to know exactly the structure of the saved data. With "black-box" EXE encryption systems, the assembly is not available. One possible solution could be to write a custom BynaryFormatter: for sure it's not worth the effort.
The workaround is to put the classes to be serialized in a DLL that is not encrypted and then decrypted in memory at run time by the dongle. This idea derive from the suggestions that I have found for a similar problem: one wants to deserialize in application A data written from application B.

Compiler Issue in Windows 7: A generic error occurred in GDI+

We have an application that we need to begin testing and developing in Windows 7 environment. It works fine compiling under WinXP in VS2008, no problems. However when I went to compile it on a windows 7 machine using VS2008 today I get the following error:
Error 12 The "GenerateResource" task failed unexpectedly.
System.Runtime.InteropServices.ExternalException (0x80004005): A generic error occurred in GDI+.
at System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams)
at System.Drawing.Image.Save(MemoryStream stream)
at System.Drawing.Image.System.Runtime.Serialization.ISerializable.GetObjectData(SerializationInfo si, StreamingContext context)
at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder)
at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder)
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.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph)
at System.Resources.ResourceWriter.WriteValue(ResourceTypeCode typeCode, Object value, BinaryWriter writer, IFormatter objFormatter)
at System.Resources.ResourceWriter.Generate()
at System.Resources.ResourceWriter.Dispose(Boolean disposing)
at System.Resources.ResourceWriter.Close()
at Microsoft.Build.Tasks.ProcessResourceFiles.WriteResources(IResourceWriter writer)
at Microsoft.Build.Tasks.ProcessResourceFiles.WriteResources(String filename)
at Microsoft.Build.Tasks.ProcessResourceFiles.ProcessFile(String inFile, String outFile)
at Microsoft.Build.Tasks.ProcessResourceFiles.Run(TaskLoggingHelper log, ITaskItem[] assemblyFilesList, List`1 inputs, List`1 outputs, Boolean sourcePath, String language, String namespacename, String resourcesNamespace, String filename, String classname, Boolean publicClass)
at Microsoft.Build.Tasks.ProcessResourceFiles.Run(TaskLoggingHelper log, ITaskItem[] assemblyFilesList, List`1 inputs, List`1 outputs, Boolean sourcePath, String language, String namespacename, String resourcesNamespace, String filename, String classname, Boolean publicClass)
at Microsoft.Build.Tasks.GenerateResource.Execute()
at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
at Microsoft.Build.BackEnd.TaskBuilder.ExecuteInstantiatedTask(ITaskExecutionHost taskExecutionHost, TaskLoggingContext taskLoggingContext, TaskHost taskHost, ItemBucket bucket, TaskExecutionMode howToExecuteTask, Boolean& taskResult)
I cannot for the life of me run this one down. I have visited the msdn forums and find that it is an issue for a lot of people, but no consistent solution has been provided by MS or anyone else.
Has anyone seen this before and fixed it? Please advise is needed!
Thanks
I compiled using the command line msbuild and that identified the problem location.
It was a resx file in a class which had one unused image in it. I removed that and all was good again. Can build fine now.
After hours of troubleshooting, I opened and built the project using the VS 2010 command line prompt using MSBUILD "my solution file path here". This provided a more visible sequence of build events, and I found my project was failing just after it compiled form 16. The forms compiling appeared to be going in order of the objects in the solution explorer. So I checked the next form and found it contained a picture box. I also checked the form after that one and found I could not open the designer without errors(object reference not set to instance of object). So apparently, the problem was now two-fold.
To resolve I had to remove the picture box object from the first form I identified as problematic (it was not being used any way) as it appeared to be corrupted. I found the second form with the null reference exception was using a user control. The code for the constructor of the user control was attempting to pass an object to a container before calling InitializeComponent(). This created the null reference since the container hadn't event been created in InitializeComponent when the problematic code was called.
After resolving the issues in the above paragraph my solution compiled under Windows 7.
There is a GDI update for Windows 7, I think, if I'm not mistaken. Maybe that will solve the issue. Does your solution build using Msbuild on the commsnd line?
Do you use TIFF images in your app?
Some time ago, I also had a problem with TIFF images as part of reports that wouldn't compile under Win7 x64 although it compiled like a charm under Vista x86. The error message also involved GDI+. I saved the images under a different format (PNG) and the problem vanished.
At the time (around March 2011), I first ensured that my Windows was up-to-date but it didn't solve the problem. So maybe there is such an update as mentionned by Erik but it didn't come through Windows Update back then (Maybe it's newer).
Delete the resources from the resource manager (right click on each and delete) then add them back. for me it solve the problem.
i had same problem.
i just used msbuild myProject.sln command and it fixed and built successfully with no errors! now i can manually build my solution.
no need to reAdding my resources

Serialization does work in sample project, but not in app

In an app I am developing, I found a problem when serializing a custom class.It's a class derived from a Generic Tree class, so let's call it DerivedFromTree. The Tree class is in another assembly.
[Serializable]
class DerivedFromTree : Tree<UnderlyingTreeType>
{
...
}
To isolate my problem I created a new console project, added the DerivedFromTree files and its dependencies and added a reference to the DLL in which Tree resides. Then added the following code:
DerivedFromTree dft = new DerivedFromTree("label");
UnderlyingTreeType utt = new UnderlyingTreeType(...);
dft.AddChild(utt);
utt = new UnderlyingTreeType(...);
dft.AddChild(utt);
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, dft);
ms.Position = 0; // position stream to 0
DerivedFromTree dft_result = (DerivedFromTree)bf.Deserialize(ms);
After running this code in the sample project, dft_result contains a valid DerivedFromTree with its children. However, if I put the same code in my original application, I get an exception when calling bf.Serialize:
{System.Runtime.Serialization.SerializationException: Type 'MyAssembly.Tree`1[[UnderlyingTreeType, Assembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' from assembly 'Assembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
in System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type)
in System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context)
in System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo()
in System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder)
in System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder)
in System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck)
in System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck)
in System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph)
in Class.Function() in C:\...\FileName.cs:line XXX}
Any idea about what could be happening there?
Update: The classes Tree, DerivedFromTree, UnderlyingTreeType and all its dependencies are marked as [Serializable]. Failing to do so would result in the small console project throwing an exception. If I remove the [Serializable] attribute from Tree class, the console project throws the exact same error as the original app.
Perhaps your object has delegate fields which may or may not throw an exception when being serialized.
Make sure you mark delegates nonserializable:
[Serializable]
public class MyClass
{
[NonSerialized]
EventHandler m_MyEvent;
}
For events, you should specify field attribute qualifier when applying NonSerialized:
[Serializable]
public class MyPublisher
{
[field:NonSerialized]
public event EventHandler MyEvent;
}
Don't forget that SerializibleAttribute has it's IsInherited property set to false. If your code looked exactly as posted above (without decorating DerivedFromTree by [Serializible]) it would not work...
Request you to go through the section of
Steps in the Serialization Process
Serialization Guidelines
of article Object Serialization
http://msdn.microsoft.com/en-us/library/ms973893.aspx
and check if you haven't missed anything
The problem is fixed now. I removed the reference to the DLL containing the Tree class and added it again, and suddenly everything worked.
I think I'm going to delete the question, as it doesn't seem very useful...
Thank you all for your help.

Categories