SHARE
TWEET

VisualStudioWorkaroundSerializer (C#)

a guest Jun 15th, 2016 320 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.     using System.ComponentModel;
  2.     using System.ComponentModel.Design.Serialization;
  3.     using System.Reflection;
  4.     using System.Windows.Forms;
  5.     public class VisualStudioWorkaroundSerializer : CodeDomSerializer
  6.     {
  7.         private CodeDomSerializer GetNormalSerializer(IDesignerSerializationManager manager, object codeObject)
  8.         {
  9.             // TODO examine codeObject's ancestors to get the right serializer?
  10.             if (codeObject is Control)
  11.             {
  12.                 return (CodeDomSerializer)manager.GetSerializer(typeof(Control), typeof(CodeDomSerializer));
  13.             }
  14.             return (CodeDomSerializer)manager.GetSerializer(typeof(Component), typeof(CodeDomSerializer));
  15.         }
  16.  
  17.         public override object Deserialize(IDesignerSerializationManager manager, object codeObject)
  18.         {
  19.             return GetNormalSerializer(manager, codeObject).Deserialize(manager, codeObject);
  20.         }
  21.  
  22.         public override object Serialize(IDesignerSerializationManager manager, object value)
  23.         {
  24.             var componentSerialiser = (CodeDomSerializer)manager.GetSerializer(typeof(Component), typeof(CodeDomSerializer));
  25.             var fieldInfo = componentSerialiser.GetType().GetField("_containerConstructor", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance);
  26.  
  27.             if (fieldInfo != null)
  28.             {
  29.                 Type[] values = (Type[])fieldInfo.GetValue(componentSerialiser);
  30.                 if (values != null && values.Length > 0)
  31.                 {
  32.                     var reflectContType = GetReflectionTypeFromTypeHelper(manager, typeof(IContainer));
  33.                     var cachedType = values[0];
  34.  
  35.                     if (!reflectContType.Equals(cachedType))
  36.                     {
  37.                         fieldInfo.SetValue(componentSerialiser, null);
  38.                         throw new Exception("Visual Studio was about to save this object without a component collection.\nI've fixed the problem and you should be able to save this object now.");
  39.                     }
  40.                 }
  41.             }
  42.  
  43.             return GetNormalSerializer(manager, value).Serialize(manager, value);
  44.         }
  45.     }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top