CodeDomDesignerLoader.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. //
  2. // System.ComponentModel.Design.Serialization.CodeDomDesignerLoader
  3. //
  4. // Authors:
  5. // Ivan N. Zlatev (contact i-nZ.net)
  6. //
  7. // (C) 2007 Ivan N. Zlatev
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. #if NET_2_0
  29. using System;
  30. using System.Collections;
  31. using System.ComponentModel;
  32. using System.ComponentModel.Design;
  33. using System.CodeDom;
  34. using System.CodeDom.Compiler;
  35. namespace System.ComponentModel.Design.Serialization
  36. {
  37. public abstract class CodeDomDesignerLoader : BasicDesignerLoader, INameCreationService, IDesignerSerializationService
  38. {
  39. private CodeDomSerializer _rootSerializer;
  40. protected CodeDomDesignerLoader ()
  41. {
  42. }
  43. protected override void Initialize ()
  44. {
  45. base.Initialize ();
  46. base.LoaderHost.AddService (typeof (IDesignerSerializationService), this);
  47. base.LoaderHost.AddService (typeof (INameCreationService), this);
  48. base.LoaderHost.AddService (typeof (ComponentSerializationService), new
  49. CodeDomComponentSerializationService (base.LoaderHost));
  50. IDesignerSerializationManager manager = base.LoaderHost.GetService (typeof (IDesignerSerializationManager)) as IDesignerSerializationManager;
  51. if (manager != null)
  52. manager.AddSerializationProvider (new CodeDomSerializationProvider ());
  53. }
  54. protected override bool IsReloadNeeded ()
  55. {
  56. if (this.CodeDomProvider is ICodeDomDesignerReload)
  57. return ((ICodeDomDesignerReload) CodeDomProvider).ShouldReloadDesigner (Parse ());
  58. return base.IsReloadNeeded ();
  59. }
  60. protected override void PerformLoad (IDesignerSerializationManager manager)
  61. {
  62. if (manager == null)
  63. throw new ArgumentNullException ("manager");
  64. CodeCompileUnit document = this.Parse ();
  65. if (document == null)
  66. throw new NotSupportedException ("The language did not provide a code parser for this file");
  67. string namespaceName = null;
  68. CodeTypeDeclaration rootDocument = GetFirstCodeTypeDecl (document, out namespaceName);
  69. if (rootDocument == null)
  70. throw new InvalidOperationException ("Cannot find a declaration in a namespace to load.");
  71. _rootSerializer = manager.GetSerializer (manager.GetType (rootDocument.BaseTypes[0].BaseType),
  72. typeof (RootCodeDomSerializer)) as CodeDomSerializer;
  73. if (_rootSerializer == null)
  74. throw new InvalidOperationException ("Serialization not supported for this class");
  75. _rootSerializer.Deserialize (manager, rootDocument);
  76. base.SetBaseComponentClassName (namespaceName + "." + rootDocument.Name);
  77. }
  78. private CodeTypeDeclaration GetFirstCodeTypeDecl (CodeCompileUnit document, out string namespaceName)
  79. {
  80. namespaceName = null;
  81. foreach (CodeNamespace namesp in document.Namespaces) {
  82. foreach (CodeTypeDeclaration declaration in namesp.Types) {
  83. if (declaration.IsClass) {
  84. namespaceName = namesp.Name;
  85. return declaration;
  86. }
  87. }
  88. }
  89. return null;
  90. }
  91. protected override void PerformFlush (IDesignerSerializationManager manager)
  92. {
  93. if (_rootSerializer != null) {
  94. CodeTypeDeclaration typeDecl = (CodeTypeDeclaration) _rootSerializer.Serialize (manager,
  95. base.LoaderHost.RootComponent);
  96. this.Write (MergeTypeDeclWithCompileUnit (typeDecl, this.Parse ()));
  97. }
  98. }
  99. // Will either add the class or replace an existing class
  100. // with the one from GenerateClass ()
  101. //
  102. private CodeCompileUnit MergeTypeDeclWithCompileUnit (CodeTypeDeclaration typeDecl, CodeCompileUnit unit)
  103. {
  104. CodeNamespace namespac = null;
  105. int typeIndex = -1;
  106. foreach (CodeNamespace namesp in unit.Namespaces) {
  107. for (int i=0; i< namesp.Types.Count; i++) {
  108. if (namesp.Types[i].Name == typeDecl.Name) {
  109. typeIndex = i;
  110. namespac = namesp;
  111. }
  112. }
  113. }
  114. if (typeIndex != -1)
  115. namespac.Types.RemoveAt (typeIndex);
  116. namespac.Types.Add (typeDecl);
  117. return unit;
  118. }
  119. protected override void OnBeginLoad ()
  120. {
  121. base.OnBeginLoad ();
  122. IComponentChangeService service = base.GetService (typeof (IComponentChangeService)) as IComponentChangeService;
  123. if (service != null)
  124. service.ComponentRename += this.OnComponentRename_EventHandler;
  125. }
  126. protected override void OnBeginUnload ()
  127. {
  128. base.OnBeginUnload ();
  129. IComponentChangeService service = base.GetService (typeof (IComponentChangeService)) as IComponentChangeService;
  130. if (service != null)
  131. service.ComponentRename -= this.OnComponentRename_EventHandler;
  132. }
  133. protected override void OnEndLoad (bool successful, ICollection errors)
  134. {
  135. base.OnEndLoad (successful, errors);
  136. // XXX: msdn says overriden
  137. }
  138. private void OnComponentRename_EventHandler (object sender, ComponentRenameEventArgs args)
  139. {
  140. this.OnComponentRename (args.Component, args.OldName, args.NewName);
  141. }
  142. // MSDN says that here one should raise ComponentRename event and that's nonsense.
  143. //
  144. protected virtual void OnComponentRename (object component, string oldName, string newName)
  145. {
  146. // What shall we do with the drunken sailor,
  147. // what shall we do with the drunken sailor early in the morning?
  148. }
  149. protected abstract CodeDomProvider CodeDomProvider { get; }
  150. protected abstract ITypeResolutionService TypeResolutionService { get; }
  151. protected abstract CodeCompileUnit Parse ();
  152. protected abstract void Write (CodeCompileUnit unit);
  153. public override void Dispose ()
  154. {
  155. base.Dispose ();
  156. }
  157. #region INameCreationService implementation
  158. // very simplistic implementation to generate names like "button1", "someControl2", etc
  159. //
  160. string INameCreationService.CreateName (IContainer container, Type dataType)
  161. {
  162. if (dataType == null)
  163. throw new ArgumentNullException ("dataType");
  164. string name = dataType.Name;
  165. char lower = Char.ToLower (name[0]);
  166. name = name.Remove (0, 1);
  167. name = name.Insert (0, Char.ToString (lower));
  168. int uniqueId = 1;
  169. bool unique = false;
  170. while (!unique) {
  171. if (container != null && container.Components[name + uniqueId] != null) {
  172. uniqueId++;
  173. } else {
  174. unique = true;
  175. name = name + uniqueId;
  176. }
  177. }
  178. if (this.CodeDomProvider != null)
  179. name = CodeDomProvider.CreateValidIdentifier (name);
  180. return name;
  181. }
  182. bool INameCreationService.IsValidName (string name)
  183. {
  184. if (name == null)
  185. throw new ArgumentNullException ("name");
  186. bool valid = true;
  187. if (this.CodeDomProvider != null) {
  188. valid = CodeDomProvider.IsValidIdentifier (name);
  189. } else {
  190. if (name.Trim().Length == 0)
  191. valid = false;
  192. foreach (char c in name) {
  193. if (!Char.IsLetterOrDigit (c)) {
  194. valid = false;
  195. break;
  196. }
  197. }
  198. }
  199. return valid;
  200. }
  201. void INameCreationService.ValidateName (string name)
  202. {
  203. if (!((INameCreationService) this).IsValidName (name))
  204. throw new ArgumentException ("Only digits and numbers allows in the name");
  205. }
  206. #endregion
  207. #region IDesignerSerializationService implementation
  208. ICollection IDesignerSerializationService.Deserialize (object serializationData)
  209. {
  210. IDesignerSerializationService service = LoaderHost.GetService (typeof (IDesignerSerializationService)) as IDesignerSerializationService;
  211. if (service != null)
  212. return service.Deserialize (serializationData);
  213. return new object[0];
  214. }
  215. object IDesignerSerializationService.Serialize (ICollection objects)
  216. {
  217. IDesignerSerializationService service = LoaderHost.GetService (typeof (IDesignerSerializationService)) as IDesignerSerializationService;
  218. if (service != null)
  219. return service.Serialize (objects);
  220. return null;
  221. }
  222. #endregion
  223. }
  224. }
  225. #endif