XmlSerializer.cs 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. //
  5. // Purpose:
  6. // :
  7. // Chart serializer allows persisting of all chart data and
  8. // settings into the stream or file using XML or binary format.
  9. // This data can be later loaded back into the chart completely
  10. // restoring its state. Serialize can also be used to reset chart
  11. // control state to its default values.
  12. // Both XML and Binary serialization methods use reflection to
  13. // discover class properties which need to be serialized. Only
  14. // properties with non-default values are persisted. Full Trust
  15. // is required to use chartserialization.
  16. // SerializeBase class implements all the chart serializer
  17. // properties and methods to reset chart content. XmlFormatSerializer
  18. // and BinaryFormatSerializer classes derive from the SerializeBase
  19. // class and provide saving and loading functionality for XML and
  20. // binary format.
  21. // By default, all chart content is Saved, Loaded or Reset, but
  22. // this can be changed using serializer Content, SerializableContent
  23. // and NonSerializableContent properties. Content property allows a
  24. // simple way to serialize everything, appearance or just chart data.
  25. // SerializableContent and NonSerializableContent properties provide
  26. // more control over what is beign persisted and they override the
  27. // Content property settings. Each of the properties is a string
  28. // which is a comma-separated listing of all chart properties to be
  29. // serialized. The syntax of this property is "Class.Property[,Class.Property]",
  30. // and wildcards may be used (represented by an asterisk). For example,
  31. // to serialize all chart BackColor properties set this property to
  32. // "*.BackColor".
  33. //
  34. using System;
  35. using System.Collections;
  36. using System.Collections.Specialized;
  37. using System.ComponentModel;
  38. using System.Diagnostics.CodeAnalysis;
  39. using System.Drawing;
  40. using System.Drawing.Imaging;
  41. using System.Globalization;
  42. using System.IO;
  43. using System.Reflection;
  44. using System.Security;
  45. using System.Text;
  46. using System.Xml;
  47. #if NETSTANDARD || !NETCOREWIN
  48. using FastReport.TypeConverters;
  49. using FontConverter = FastReport.TypeConverters.FontConverter;
  50. #endif
  51. namespace FastReport.DataVisualization.Charting.Utilities
  52. {
  53. using Size = System.Drawing.Size;
  54. #region Serialization enumerations
  55. /// <summary>
  56. /// Enumeration which describes how to persist property during the serialization
  57. /// </summary>
  58. internal enum SerializationVisibility
  59. {
  60. /// <summary>
  61. /// Do not serialize
  62. /// </summary>
  63. Hidden,
  64. /// <summary>
  65. /// Serialize as XML attribute
  66. /// </summary>
  67. Attribute,
  68. /// <summary>
  69. /// Serialize as XML element
  70. /// </summary>
  71. Element
  72. }
  73. /// <summary>
  74. /// Determines chart current serialization status.
  75. /// </summary>
  76. internal enum SerializationStatus
  77. {
  78. /// <summary>
  79. /// Chart is not serializing
  80. /// </summary>
  81. None,
  82. /// <summary>
  83. /// Chart is loading
  84. /// </summary>
  85. Loading,
  86. /// <summary>
  87. /// Chart is saving
  88. /// </summary>
  89. Saving,
  90. /// <summary>
  91. /// Chart is resetting
  92. /// </summary>
  93. Resetting
  94. }
  95. #endregion
  96. /// <summary>
  97. /// Attribute which describes how to persist property during the serialization.
  98. /// </summary>
  99. [AttributeUsage(AttributeTargets.All)]
  100. internal sealed class SerializationVisibilityAttribute : System.Attribute
  101. {
  102. #region Fields
  103. // Visibility style
  104. private SerializationVisibility _visibility = SerializationVisibility.Attribute;
  105. #endregion
  106. #region Constructor
  107. /// <summary>
  108. /// Public constructor
  109. /// </summary>
  110. /// <param name="visibility">Serialization visibility.</param>
  111. internal SerializationVisibilityAttribute(SerializationVisibility visibility)
  112. {
  113. this._visibility = visibility;
  114. }
  115. #endregion
  116. #region Properties
  117. /// <summary>
  118. /// Serialization visibility property
  119. /// </summary>
  120. public SerializationVisibility Visibility
  121. {
  122. get
  123. {
  124. return _visibility;
  125. }
  126. //set
  127. //{
  128. // _visibility = value;
  129. //}
  130. }
  131. #endregion
  132. }
  133. /// <summary>
  134. /// Base class of the serializers. Common properties and methods for all serializers.
  135. /// </summary>
  136. internal abstract class SerializerBase
  137. {
  138. #region Fields
  139. /// <summary>
  140. /// Indicates that unknown properties and elements are ignored
  141. /// </summary>
  142. private bool _isUnknownAttributeIgnored = false;
  143. /// <summary>
  144. /// Indicates that serializer works in template creation mode
  145. /// </summary>
  146. private bool _isTemplateMode = false;
  147. /// <summary>
  148. /// Indicates that object properties are reset before loading
  149. /// </summary>
  150. private bool _isResetWhenLoading = true;
  151. /// <summary>
  152. /// Comma separated list of serializable (Save/Load/Reset) properties. "ClassName.PropertyName"
  153. /// </summary>
  154. private string _serializableContent = "";
  155. /// <summary>
  156. /// Comma separated list of NON serializable (Save/Load/Reset) properties. "ClassName.PropertyName"
  157. /// </summary>
  158. private string _nonSerializableContent = "";
  159. /// <summary>
  160. /// Font converters used while serializing/deserializing
  161. /// </summary>
  162. internal static FontConverter fontConverter = new FontConverter();
  163. /// <summary>
  164. /// Color converters used while serializing/deserializing
  165. /// </summary>
  166. internal static ColorConverter colorConverter = new ColorConverter();
  167. /// <summary>
  168. /// Hash code provider.
  169. /// </summary>
  170. protected static StringComparer hashCodeProvider = StringComparer.OrdinalIgnoreCase;
  171. /// <summary>
  172. /// Contains chart specific converters
  173. /// </summary>
  174. HybridDictionary _converterDict = new HybridDictionary();
  175. #endregion
  176. #region Public properties
  177. /// <summary>
  178. /// Indicates that unknown properties and elements will be
  179. /// ignored without throwing an exception.
  180. /// </summary>
  181. internal bool IsUnknownAttributeIgnored
  182. {
  183. get
  184. {
  185. return _isUnknownAttributeIgnored;
  186. }
  187. set
  188. {
  189. _isUnknownAttributeIgnored = value;
  190. }
  191. }
  192. /// <summary>
  193. /// Indicates that serializer works in template creation mode
  194. /// </summary>
  195. internal bool IsTemplateMode
  196. {
  197. get
  198. {
  199. return _isTemplateMode;
  200. }
  201. set
  202. {
  203. _isTemplateMode = value;
  204. }
  205. }
  206. /// <summary>
  207. /// Indicates that object properties are reset to default
  208. /// values before loading.
  209. /// </summary>
  210. internal bool IsResetWhenLoading
  211. {
  212. get
  213. {
  214. return _isResetWhenLoading;
  215. }
  216. set
  217. {
  218. _isResetWhenLoading = value;
  219. }
  220. }
  221. /// <summary>
  222. /// Comma separated list of serializable (Save/Load/Reset) properties.
  223. /// "ClassName.PropertyName,[ClassName.PropertyName]".
  224. /// </summary>
  225. internal string SerializableContent
  226. {
  227. get
  228. {
  229. return _serializableContent;
  230. }
  231. set
  232. {
  233. _serializableContent = value;
  234. // Reset list
  235. serializableContentList = null;
  236. }
  237. }
  238. /// <summary>
  239. /// Comma separated list of serializable (Save/Load/Reset) properties.
  240. /// "ClassName.PropertyName,[ClassName.PropertyName]".
  241. /// </summary>
  242. internal string NonSerializableContent
  243. {
  244. get
  245. {
  246. return _nonSerializableContent;
  247. }
  248. set
  249. {
  250. _nonSerializableContent = value;
  251. // Reset list
  252. nonSerializableContentList = null;
  253. }
  254. }
  255. #endregion
  256. #region Resetting methods
  257. /// <summary>
  258. /// Reset properties of the object to default values.
  259. /// </summary>
  260. /// <param name="objectToReset">Object to be reset.</param>
  261. virtual internal void ResetObjectProperties(object objectToReset)
  262. {
  263. // Reset object properties
  264. ResetObjectProperties(objectToReset, null, GetObjectName(objectToReset));
  265. }
  266. /// <summary>
  267. /// Reset properties of the object to default values.
  268. /// Method is called recursively to reset child objects properties.
  269. /// </summary>
  270. /// <param name="objectToReset">Object to be reset.</param>
  271. /// <param name="parent">Parent of the reset object.</param>
  272. /// <param name="elementName">Object element name.</param>
  273. virtual internal void ResetObjectProperties(object objectToReset, object parent, string elementName)
  274. {
  275. // Check input parameters
  276. if(objectToReset == null)
  277. {
  278. return;
  279. }
  280. IList list = objectToReset as IList;
  281. // Check if object is a list
  282. if(list != null && IsSerializableContent(elementName, parent))
  283. {
  284. // Reset list by clearing all the items
  285. list.Clear();
  286. return;
  287. }
  288. // Retrive properties list of the object
  289. PropertyInfo[] properties = objectToReset.GetType().GetProperties();
  290. if(properties != null)
  291. {
  292. // Loop through all properties and reset public properties
  293. foreach(PropertyInfo pi in properties)
  294. {
  295. // Get property descriptor
  296. PropertyDescriptor pd = TypeDescriptor.GetProperties(objectToReset)[pi.Name];
  297. // Check XmlFormatSerializerStyle attribute
  298. if(pd != null)
  299. {
  300. SerializationVisibilityAttribute styleAttribute = (SerializationVisibilityAttribute)pd.Attributes[typeof(SerializationVisibilityAttribute)];
  301. if(styleAttribute != null)
  302. {
  303. // Hidden property
  304. if(styleAttribute.Visibility == SerializationVisibility.Hidden)
  305. {
  306. continue;
  307. }
  308. }
  309. }
  310. // Check if this property should be reset
  311. bool resetProperty = IsSerializableContent(pi.Name, objectToReset);
  312. // Skip inherited properties from the root object
  313. if(IsChartBaseProperty(objectToReset, parent, pi))
  314. {
  315. continue;
  316. }
  317. // Reset list
  318. if(pi.CanRead && pi.PropertyType.GetInterface("IList", true) != null)
  319. {
  320. if(resetProperty)
  321. {
  322. // Check if collection has "Reset" method
  323. bool resetComplete = false;
  324. MethodInfo mi = objectToReset.GetType().GetMethod("Reset" + pi.Name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
  325. if(mi != null)
  326. {
  327. mi.Invoke(objectToReset, null);
  328. resetComplete = true;
  329. }
  330. // Reset list by clearing all the items
  331. if(!resetComplete)
  332. {
  333. ((IList)pi.GetValue(objectToReset, null)).Clear();
  334. }
  335. }
  336. else
  337. {
  338. // Reset objects of the list
  339. foreach(object listObject in ((IList)pi.GetValue(objectToReset, null)))
  340. {
  341. ResetObjectProperties(listObject, objectToReset, this.GetObjectName(listObject));
  342. }
  343. }
  344. }
  345. // Reset public properties with Get and Set methods
  346. else if(pi.CanRead && pi.CanWrite)
  347. {
  348. // Skip indexes
  349. if(pi.Name == "Item")
  350. {
  351. continue;
  352. }
  353. // Skip Names
  354. if (pi.Name == "Name")
  355. {
  356. continue;
  357. }
  358. // Reset inner properies
  359. if(ShouldSerializeAsAttribute(pi, objectToReset))
  360. {
  361. if(resetProperty)
  362. {
  363. // Reset the property using property descriptor
  364. if(pd != null)
  365. {
  366. // Get property object
  367. object objectProperty = pi.GetValue(objectToReset, null);
  368. // Get default value of the property
  369. DefaultValueAttribute defValueAttribute = (DefaultValueAttribute)pd.Attributes[typeof(DefaultValueAttribute)];
  370. if(defValueAttribute != null)
  371. {
  372. if(objectProperty == null)
  373. {
  374. if(defValueAttribute.Value != null)
  375. {
  376. pd.SetValue(objectToReset, defValueAttribute.Value);
  377. }
  378. }
  379. else if(! objectProperty.Equals(defValueAttribute.Value))
  380. {
  381. pd.SetValue(objectToReset, defValueAttribute.Value);
  382. }
  383. }
  384. else
  385. {
  386. // Check if property has "Reset" method
  387. MethodInfo mi = objectToReset.GetType().GetMethod("Reset" + pi.Name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
  388. if(mi != null)
  389. {
  390. mi.Invoke(objectToReset, null);
  391. }
  392. }
  393. }
  394. }
  395. }
  396. else
  397. {
  398. // Reset inner object
  399. ResetObjectProperties(pi.GetValue(objectToReset, null), objectToReset, pi.Name);
  400. }
  401. }
  402. }
  403. }
  404. return;
  405. }
  406. #endregion
  407. #region Abstract Serialization/Deserialization methods
  408. /// <summary>
  409. /// Serialize specified object into the destination object.
  410. /// </summary>
  411. /// <param name="objectToSerialize">Object to be serialized.</param>
  412. /// <param name="destination">Destination of the serialization.</param>
  413. internal abstract void Serialize(object objectToSerialize, object destination);
  414. /// <summary>
  415. /// Deserialize specified object from the source object.
  416. /// </summary>
  417. /// <param name="objectToDeserialize">Object to be deserialized.</param>
  418. /// <param name="source">Source of the deserialization.</param>
  419. internal abstract void Deserialize(object objectToDeserialize, object source);
  420. #endregion
  421. #region Protected helper methods
  422. /// <summary>
  423. /// Converts specified font object into a string.
  424. /// </summary>
  425. /// <param name="font">Font object to convert.</param>
  426. /// <returns>String that contains font data.</returns>
  427. internal static string FontToString(Font font)
  428. {
  429. // Save basic properties persisted by font converter
  430. string fontData = (string)SerializerBase.fontConverter.ConvertToInvariantString(font);
  431. // Persist properties not serialiazed by the converter
  432. if(font.GdiCharSet != 1)
  433. {
  434. fontData += ", GdiCharSet=" + font.GdiCharSet.ToString(System.Globalization.CultureInfo.InvariantCulture);
  435. }
  436. if(font.GdiVerticalFont)
  437. {
  438. fontData += ", GdiVerticalFont";
  439. }
  440. return fontData;
  441. }
  442. /// <summary>
  443. /// Converts string data into a font object.
  444. /// </summary>
  445. /// <param name="fontString">String with font data.</param>
  446. /// <returns>Newly created font object.</returns>
  447. internal static Font FontFromString(string fontString)
  448. {
  449. // Check if string contains non-standard values "GdiCharSet" or "GdiVerticalFont"
  450. string standardData = fontString;
  451. byte gdiCharSet = 1;
  452. bool gdiVerticalFont = false;
  453. int charIndex = fontString.IndexOf(", GdiCharSet=", StringComparison.Ordinal);
  454. if(charIndex >= 0)
  455. {
  456. // Read value
  457. string val = fontString.Substring(charIndex + 13);
  458. int commaIndex = val.IndexOf(",", StringComparison.Ordinal);
  459. if(commaIndex >= 0)
  460. {
  461. val = val.Substring(0, commaIndex);
  462. }
  463. gdiCharSet = (byte)Int32.Parse(val, System.Globalization.CultureInfo.InvariantCulture);
  464. // Truncate standard data string
  465. if(standardData.Length > charIndex)
  466. {
  467. standardData = standardData.Substring(0, charIndex);
  468. }
  469. }
  470. charIndex = fontString.IndexOf(", GdiVerticalFont", StringComparison.Ordinal);
  471. if(charIndex >= 0)
  472. {
  473. gdiVerticalFont = true;
  474. // Truncate standard data string
  475. if(standardData.Length > charIndex)
  476. {
  477. standardData = standardData.Substring(0, charIndex);
  478. }
  479. }
  480. // Create Font object from standard parameters
  481. Font font = (Font)SerializerBase.fontConverter.ConvertFromInvariantString(standardData);
  482. // check if non-standard parameters provided
  483. if(gdiVerticalFont || gdiCharSet != 1)
  484. {
  485. Font newFont = new Font(
  486. font.Name,
  487. font.SizeInPoints,
  488. font.Style,
  489. GraphicsUnit.Point,
  490. gdiCharSet,
  491. gdiVerticalFont);
  492. font.Dispose();
  493. return newFont;
  494. }
  495. return font;
  496. }
  497. /// <summary>
  498. /// Returns a hash code of a specified string.
  499. /// </summary>
  500. /// <param name="str">String to get the hash code for.</param>
  501. /// <returns>String hash code.</returns>
  502. internal static short GetStringHashCode(string str)
  503. {
  504. return (short)(hashCodeProvider.GetHashCode(str) + str.Length * 2);
  505. }
  506. /// <summary>
  507. /// Reads hash ID from the specified binary reader.
  508. /// </summary>
  509. /// <param name="reader">Binary reader to get the data from.</param>
  510. /// <returns>Property name or collection member type ID.</returns>
  511. internal Int16 ReadHashID(BinaryReader reader)
  512. {
  513. // For later versions return ID without transformations
  514. return reader.ReadInt16();
  515. }
  516. /// <summary>
  517. /// Checks if property belongs to the base class of the chart "Control".
  518. /// </summary>
  519. /// <param name="objectToSerialize">Serializable object.</param>
  520. /// <param name="parent">Object parent.</param>
  521. /// <param name="pi">Serializable property information.</param>
  522. /// <returns>True if property belongs to the base class.</returns>
  523. internal bool IsChartBaseProperty(object objectToSerialize, object parent, PropertyInfo pi)
  524. {
  525. bool result = false;
  526. // Check only for the root object
  527. if(parent == null)
  528. {
  529. Type currentType = objectToSerialize.GetType();
  530. while(currentType != null)
  531. {
  532. if(pi.DeclaringType == currentType)
  533. {
  534. result = false;
  535. break;
  536. }
  537. // Check if it's a chart class
  538. if( currentType == typeof(Chart))
  539. {
  540. result = true;
  541. break;
  542. }
  543. // Get base class type
  544. currentType = currentType.BaseType;
  545. }
  546. }
  547. return result;
  548. }
  549. /// <summary>
  550. /// Converts Image object into the BASE64 encoded string
  551. /// </summary>
  552. /// <param name="image">Image to convert.</param>
  553. /// <returns>BASE64 encoded image data.</returns>
  554. internal static string ImageToString(System.Drawing.Image image)
  555. {
  556. // Save image into the stream using BASE64 encoding
  557. MemoryStream imageStream = new MemoryStream();
  558. image.Save(imageStream, ImageFormat.Png);
  559. imageStream.Seek(0, SeekOrigin.Begin);
  560. // Create XmlTextWriter and save image in BASE64
  561. StringBuilder stringBuilder = new StringBuilder();
  562. XmlTextWriter textWriter = new XmlTextWriter(new StringWriter(stringBuilder, CultureInfo.InvariantCulture));
  563. byte[] imageByteData = imageStream.ToArray();
  564. textWriter.WriteBase64(imageByteData, 0, imageByteData.Length);
  565. // Close image stream
  566. textWriter.Close();
  567. imageStream.Close();
  568. return stringBuilder.ToString();
  569. }
  570. /// <summary>
  571. /// Converts BASE64 encoded string to image.
  572. /// </summary>
  573. /// <param name="data">BASE64 encoded data.</param>
  574. /// <returns>Image.</returns>
  575. internal static System.Drawing.Image ImageFromString(string data)
  576. {
  577. // Create XML text reader
  578. byte[] buffer = new byte[1000];
  579. MemoryStream imageStream = new MemoryStream();
  580. XmlTextReader textReader = new XmlTextReader(new StringReader("<base64>" + data + "</base64>"))
  581. {
  582. DtdProcessing = DtdProcessing.Ignore
  583. };
  584. // Read tags and BASE64 encoded data
  585. textReader.Read();
  586. int bytesRead = 0;
  587. while((bytesRead = textReader.ReadBase64(buffer, 0, 1000)) > 0)
  588. {
  589. imageStream.Write(buffer, 0, bytesRead);
  590. }
  591. textReader.Read();
  592. // Create image from stream
  593. imageStream.Seek(0, SeekOrigin.Begin);
  594. System.Drawing.Image tempImage = System.Drawing.Image.FromStream(imageStream);
  595. System.Drawing.Bitmap image = new Bitmap(tempImage); // !!! .Net bug when image source stream is closed - can create brush using the image
  596. image.SetResolution(tempImage.HorizontalResolution, tempImage.VerticalResolution); //The bitmap created using the constructor does not copy the resolution of the image
  597. // Close image stream
  598. textReader.Close();
  599. imageStream.Close();
  600. return image;
  601. }
  602. /// <summary>
  603. /// Get the name of the object class
  604. /// </summary>
  605. /// <param name="obj">Object to get the name of.</param>
  606. /// <returns>Name of the object class (without namespace).</returns>
  607. internal string GetObjectName(object obj)
  608. {
  609. string name = obj.GetType().ToString();
  610. return name.Substring(name.LastIndexOf('.') + 1);
  611. }
  612. /// <summary>
  613. /// Create new empty item for the list.
  614. /// AxisName of the objects is determined by the return type of the indexer.
  615. /// </summary>
  616. /// <param name="list">List used to detect type of the item objects.</param>
  617. /// <param name="itemTypeName">Name of collection type.</param>
  618. /// <param name="itemName">Optional item name to return.</param>
  619. /// <param name="reusedObject">Indicates that object with specified name was already in the collection and it being reused.</param>
  620. /// <returns>New list item object.</returns>
  621. internal object GetListNewItem(IList list, string itemTypeName, ref string itemName, ref bool reusedObject)
  622. {
  623. // Get type of item in collection
  624. Type itemType = null;
  625. if(itemTypeName.Length > 0)
  626. {
  627. itemType = Type.GetType(typeof(Chart).Namespace + "." + itemTypeName, false, true);
  628. }
  629. reusedObject = false;
  630. PropertyInfo pi = list.GetType().GetProperty("Item", itemType, new Type[] {typeof(string)} );
  631. MethodInfo mi = list.GetType().GetMethod("IndexOf", new Type[] { typeof(String) });
  632. ConstructorInfo ci = null;
  633. if(pi != null)
  634. {
  635. // Try to get object by name using the indexer
  636. if(itemName != null && itemName.Length > 0)
  637. {
  638. bool itemChecked = false;
  639. if (mi != null)
  640. {
  641. try
  642. {
  643. int index = -1;
  644. object oindex = mi.Invoke(list, new object[] { itemName });
  645. if (oindex is int)
  646. {
  647. index = (int)oindex;
  648. itemChecked = true;
  649. }
  650. if (index != -1)
  651. {
  652. object objByName = list[index];
  653. if (objByName != null)
  654. {
  655. // Remove found object from the list
  656. list.Remove(objByName);
  657. // Return found object
  658. reusedObject = true;
  659. return objByName;
  660. }
  661. }
  662. }
  663. catch (ArgumentException)
  664. {
  665. }
  666. catch (TargetException)
  667. {
  668. }
  669. catch (TargetInvocationException)
  670. {
  671. }
  672. }
  673. if (!itemChecked)
  674. {
  675. object objByName = null;
  676. try
  677. {
  678. objByName = pi.GetValue(list, new object[] { itemName });
  679. }
  680. catch (ArgumentException)
  681. {
  682. objByName = null;
  683. }
  684. catch (TargetException)
  685. {
  686. objByName = null;
  687. }
  688. catch (TargetInvocationException)
  689. {
  690. objByName = null;
  691. }
  692. if (objByName != null)
  693. {
  694. try
  695. {
  696. // Remove found object from the list
  697. list.Remove(objByName);
  698. }
  699. catch (NotSupportedException)
  700. {
  701. }
  702. // Return found object
  703. reusedObject = true;
  704. return objByName;
  705. }
  706. }
  707. itemName = null;
  708. }
  709. }
  710. // Get the constructor of the type returned by indexer
  711. if (itemType != null)
  712. {
  713. ci = itemType.GetConstructor(Type.EmptyTypes);
  714. }
  715. else
  716. {
  717. ci = pi.PropertyType.GetConstructor(Type.EmptyTypes);
  718. }
  719. if (ci == null)
  720. {
  721. throw (new InvalidOperationException(SR.ExceptionChartSerializerDefaultConstructorUndefined(pi.PropertyType.ToString())));
  722. }
  723. return ci.Invoke(null);
  724. }
  725. /// <summary>
  726. /// Returns true if the object property should be serialized as
  727. /// parent element attribute. Otherwise as a child element.
  728. /// </summary>
  729. /// <param name="pi">Property information.</param>
  730. /// <param name="parent">Object that the property belongs to.</param>
  731. /// <returns>True if property should be serialized as attribute.</returns>
  732. internal bool ShouldSerializeAsAttribute(PropertyInfo pi, object parent)
  733. {
  734. // Check if SerializationVisibilityAttribute is set
  735. if(parent != null)
  736. {
  737. PropertyDescriptor pd = TypeDescriptor.GetProperties(parent)[pi.Name];
  738. if(pd != null)
  739. {
  740. SerializationVisibilityAttribute styleAttribute = (SerializationVisibilityAttribute)pd.Attributes[typeof(SerializationVisibilityAttribute)];
  741. if(styleAttribute != null)
  742. {
  743. if(styleAttribute.Visibility == SerializationVisibility.Attribute)
  744. {
  745. return true;
  746. }
  747. else if(styleAttribute.Visibility == SerializationVisibility.Element)
  748. {
  749. return false;
  750. }
  751. }
  752. }
  753. }
  754. // If a simple type - serialize as property
  755. if(!pi.PropertyType.IsClass)
  756. {
  757. return true;
  758. }
  759. // Some classes are serialized as properties
  760. if(pi.PropertyType == typeof(string) ||
  761. pi.PropertyType == typeof(Font) ||
  762. pi.PropertyType == typeof(Color) ||
  763. pi.PropertyType == typeof(System.Drawing.Image))
  764. {
  765. return true;
  766. }
  767. return false;
  768. }
  769. /// <summary>
  770. /// Determines if this property should be serialized as attribute
  771. /// </summary>
  772. /// <param name="pi">Property information.</param>
  773. /// <param name="objectToSerialize">Object that the property belongs to.</param>
  774. /// <returns>True if should be serialized as attribute</returns>
  775. internal bool SerializeICollAsAtribute(PropertyInfo pi, object objectToSerialize)
  776. {
  777. if (objectToSerialize != null)
  778. {
  779. PropertyDescriptor pd = TypeDescriptor.GetProperties(objectToSerialize)[pi.Name];
  780. if (pd != null)
  781. {
  782. SerializationVisibilityAttribute styleAttribute = (SerializationVisibilityAttribute)pd.Attributes[typeof(SerializationVisibilityAttribute)];
  783. if (styleAttribute != null)
  784. {
  785. if (styleAttribute.Visibility == SerializationVisibility.Attribute)
  786. {
  787. return true;
  788. }
  789. }
  790. }
  791. }
  792. return false;
  793. }
  794. /// <summary>
  795. /// Returns true if the object property is serializable.
  796. /// </summary>
  797. /// <param name="propertyName">Property name.</param>
  798. /// <param name="parent">Object that the property belongs to.</param>
  799. /// <returns>True if property is serializable.</returns>
  800. internal bool IsSerializableContent(string propertyName, object parent)
  801. {
  802. bool serializable = true;
  803. if(_serializableContent.Length > 0 || _nonSerializableContent.Length > 0)
  804. {
  805. int serialzableClassFitType = 0; // 0 - undefined; 1 - '*'; 2 - 'Back*'; 3 - Exact
  806. int serialzablePropertyFitType = 0; // 0 - undefined; 1 - '*'; 2 - 'Back*'; 3 - Exact
  807. string ownerClassName = GetObjectName(parent);
  808. // Check if property in this class is part of the serializable content
  809. serializable = IsPropertyInList(GetSerializableContentList(), ownerClassName, propertyName, out serialzableClassFitType, out serialzablePropertyFitType);
  810. // Check if property in this class is part of the NON serializable content
  811. if(serializable)
  812. {
  813. int nonSerialzableClassFitType = 0; // 0 - undefined; 1 - '*'; 2 - 'Back*'; 3 - Exact
  814. int nonSerialzablePropertyFitType = 0; // 0 - undefined; 1 - '*'; 2 - 'Back*'; 3 - Exact
  815. bool nonSerializable = IsPropertyInList(GetNonSerializableContentList(), ownerClassName, propertyName, out nonSerialzableClassFitType, out nonSerialzablePropertyFitType);
  816. // If property was found in non serializable content list - check the type priority
  817. // Priority order: Exact match, 'Back*' mask match, '*' all mask match
  818. if(nonSerializable)
  819. {
  820. // Check priority
  821. if((nonSerialzableClassFitType + nonSerialzablePropertyFitType) >
  822. (serialzableClassFitType + serialzablePropertyFitType))
  823. {
  824. serializable = false;
  825. }
  826. }
  827. }
  828. }
  829. return serializable;
  830. }
  831. /// <summary>
  832. /// Checks if property belongs is defined in the mask list.
  833. /// </summary>
  834. /// <param name="contentList">Array list of class/property items.</param>
  835. /// <param name="className">Class name.</param>
  836. /// <param name="propertyName">Property name.</param>
  837. /// <param name="classFitType">Return class mask fit type.</param>
  838. /// <param name="propertyFitType">Return property mask fit type.</param>
  839. /// <returns>True if property was found in the list.</returns>
  840. private bool IsPropertyInList(ArrayList contentList, string className, string propertyName, out int classFitType, out int propertyFitType)
  841. {
  842. // Initialize result values
  843. classFitType = 0;
  844. propertyFitType = 0;
  845. if(contentList != null)
  846. {
  847. // Loop through all items in the list using step 2
  848. for(int itemIndex = 0; itemIndex < contentList.Count; itemIndex += 2)
  849. {
  850. // Initialize result values
  851. classFitType = 0;
  852. propertyFitType = 0;
  853. // Check if object class and property name match the mask
  854. if(NameMatchMask((ItemInfo)contentList[itemIndex], className, out classFitType))
  855. {
  856. if(NameMatchMask((ItemInfo)contentList[itemIndex + 1], propertyName, out propertyFitType))
  857. {
  858. return true;
  859. }
  860. }
  861. }
  862. }
  863. return false;
  864. }
  865. /// <summary>
  866. /// Compares class/property name with the specified mask
  867. /// </summary>
  868. /// <param name="itemInfo">Class/Property item information.</param>
  869. /// <param name="objectName">Class/Property name.</param>
  870. /// <param name="type">AxisName of matching. 0-No Match; 1-'*' any wild card; 2-'Back*' contain wild card; 3-exact match</param>
  871. /// <returns>True if name match the mask.</returns>
  872. private bool NameMatchMask(ItemInfo itemInfo, string objectName, out int type)
  873. {
  874. // Initialize type
  875. type = 0;
  876. // Any class mask
  877. if(itemInfo.any)
  878. {
  879. type = 1;
  880. return true;
  881. }
  882. // Ends with class mask
  883. if(itemInfo.endsWith)
  884. {
  885. if(itemInfo.name.Length <= objectName.Length)
  886. {
  887. if(objectName.Substring(0, itemInfo.name.Length) == itemInfo.name)
  888. {
  889. type = 2;
  890. return true;
  891. }
  892. }
  893. }
  894. // Starts with class mask
  895. if(itemInfo.startsWith)
  896. {
  897. if(itemInfo.name.Length <= objectName.Length)
  898. {
  899. if(objectName.Substring(objectName.Length - itemInfo.name.Length, itemInfo.name.Length) == itemInfo.name)
  900. {
  901. type = 2;
  902. return true;
  903. }
  904. }
  905. }
  906. // Exact name is specified
  907. if(itemInfo.name == objectName)
  908. {
  909. type = 3;
  910. return true;
  911. }
  912. return false;
  913. }
  914. /// <summary>
  915. /// Finds a converter by property descriptor.
  916. /// </summary>
  917. /// <param name="pd">Property descriptor.</param>
  918. /// <returns>A converter registered in TypeConverterAttribute or by property type</returns>
  919. internal TypeConverter FindConverter(PropertyDescriptor pd)
  920. {
  921. TypeConverter result;
  922. TypeConverterAttribute typeConverterAttrib = (TypeConverterAttribute)pd.Attributes[typeof(TypeConverterAttribute)];
  923. if (typeConverterAttrib != null && typeConverterAttrib.ConverterTypeName.Length > 0)
  924. {
  925. result = this.FindConverterByType(typeConverterAttrib);
  926. if (result != null)
  927. {
  928. return result;
  929. }
  930. try
  931. {
  932. return pd.Converter;
  933. }
  934. catch (SecurityException)
  935. {
  936. }
  937. catch (MethodAccessException)
  938. {
  939. }
  940. }
  941. return TypeDescriptor.GetConverter(pd.PropertyType);
  942. }
  943. /// <summary>
  944. /// Finds a converter by TypeConverterAttribute.
  945. /// </summary>
  946. /// <param name="attr">TypeConverterAttribute.</param>
  947. /// <returns>TypeConvetrer or null</returns>
  948. internal TypeConverter FindConverterByType( TypeConverterAttribute attr)
  949. {
  950. // In default Inranet zone (partial trust) ConsrtuctorInfo.Invoke (PropertyDescriptor.Converter)
  951. // throws SecurityException or MethodAccessException when the converter class is internal.
  952. // Thats why we have this giant if - elseif here - to create type converters whitout reflection.
  953. if (_converterDict.Contains(attr.ConverterTypeName))
  954. {
  955. return (TypeConverter)_converterDict[attr.ConverterTypeName];
  956. }
  957. String typeStr = attr.ConverterTypeName;
  958. if (attr.ConverterTypeName.Contains(",") )
  959. {
  960. typeStr = attr.ConverterTypeName.Split(',')[0];
  961. }
  962. TypeConverter result = null;
  963. if (typeStr.EndsWith(".CustomPropertiesTypeConverter", StringComparison.OrdinalIgnoreCase)) { result = new CustomPropertiesTypeConverter(); }
  964. else if (typeStr.EndsWith(".DoubleNanValueConverter", StringComparison.OrdinalIgnoreCase)) { result = new DoubleNanValueConverter(); }
  965. else if (typeStr.EndsWith(".DoubleDateNanValueConverter", StringComparison.OrdinalIgnoreCase)) { result = new DoubleDateNanValueConverter(); }
  966. else if (typeStr.EndsWith(".ElementPositionConverter", StringComparison.OrdinalIgnoreCase)) { result = new ElementPositionConverter(); }
  967. else if (typeStr.EndsWith(".SeriesAreaNameConverter", StringComparison.OrdinalIgnoreCase)) { result = new SeriesAreaNameConverter(); }
  968. else if (typeStr.EndsWith(".ChartDataSourceConverter", StringComparison.OrdinalIgnoreCase)) { result = new ChartDataSourceConverter(); }
  969. else if (typeStr.EndsWith(".SeriesDataSourceMemberConverter", StringComparison.OrdinalIgnoreCase)) { result = new SeriesDataSourceMemberConverter(); }
  970. else if (typeStr.EndsWith(".SeriesLegendNameConverter", StringComparison.OrdinalIgnoreCase)) { result = new SeriesLegendNameConverter(); }
  971. else if (typeStr.EndsWith(".ChartTypeConverter", StringComparison.OrdinalIgnoreCase)) { result = new ChartTypeConverter(); }
  972. else if (typeStr.EndsWith(".SeriesNameConverter", StringComparison.OrdinalIgnoreCase)) { result = new SeriesNameConverter(); }
  973. else if (typeStr.EndsWith(".NoNameExpandableObjectConverter", StringComparison.OrdinalIgnoreCase)) { result = new NoNameExpandableObjectConverter(); }
  974. else if (typeStr.EndsWith(".DoubleArrayConverter", StringComparison.OrdinalIgnoreCase)) { result = new DoubleArrayConverter(); }
  975. else if (typeStr.EndsWith(".DataPointValueConverter", StringComparison.OrdinalIgnoreCase)) { result = new DataPointValueConverter(); }
  976. else if (typeStr.EndsWith(".SeriesYValueTypeConverter", StringComparison.OrdinalIgnoreCase)) { result = new SeriesYValueTypeConverter(typeof(ChartValueType)); }
  977. else if (typeStr.EndsWith(".ColorArrayConverter", StringComparison.OrdinalIgnoreCase)) { result = new ColorArrayConverter(); }
  978. else if (typeStr.EndsWith(".LegendAreaNameConverter", StringComparison.OrdinalIgnoreCase)) { result = new LegendAreaNameConverter(); }
  979. else if (typeStr.EndsWith(".LegendConverter", StringComparison.OrdinalIgnoreCase)) { result = new LegendConverter(); }
  980. else if (typeStr.EndsWith(".SizeEmptyValueConverter", StringComparison.OrdinalIgnoreCase)) { result = new SizeEmptyValueConverter(); }
  981. else if (typeStr.EndsWith(".MarginExpandableObjectConverter", StringComparison.OrdinalIgnoreCase)) { result = new MarginExpandableObjectConverter(); }
  982. else if (typeStr.EndsWith(".IntNanValueConverter", StringComparison.OrdinalIgnoreCase)) { result = new IntNanValueConverter(); }
  983. else if (typeStr.EndsWith(".AxesArrayConverter", StringComparison.OrdinalIgnoreCase)) { result = new AxesArrayConverter(); }
  984. else if (typeStr.EndsWith(".AxisLabelDateValueConverter", StringComparison.OrdinalIgnoreCase)) { result = new AxisLabelDateValueConverter(); }
  985. else if (typeStr.EndsWith(".AxisMinMaxValueConverter", StringComparison.OrdinalIgnoreCase)) { result = new AxisMinMaxValueConverter(); }
  986. else if (typeStr.EndsWith(".AxisCrossingValueConverter", StringComparison.OrdinalIgnoreCase)) { result = new AxisCrossingValueConverter(); }
  987. else if (typeStr.EndsWith(".AxisMinMaxAutoValueConverter", StringComparison.OrdinalIgnoreCase)) { result = new AxisMinMaxAutoValueConverter(); }
  988. else if (typeStr.EndsWith(".StripLineTitleAngleConverter", StringComparison.OrdinalIgnoreCase)) { result = new StripLineTitleAngleConverter(); }
  989. else if (typeStr.EndsWith(".AxisIntervalValueConverter", StringComparison.OrdinalIgnoreCase)) { result = new AxisIntervalValueConverter(); }
  990. else if (typeStr.EndsWith(".AxisElementIntervalValueConverter", StringComparison.OrdinalIgnoreCase)) { result = new AxisElementIntervalValueConverter(); }
  991. else if (typeStr.EndsWith(".AnchorPointValueConverter", StringComparison.OrdinalIgnoreCase)) { result = new AnchorPointValueConverter(); }
  992. else if (typeStr.EndsWith(".AnnotationAxisValueConverter", StringComparison.OrdinalIgnoreCase)) { result = new AnnotationAxisValueConverter(); }
  993. if (result != null) _converterDict[attr.ConverterTypeName] = result;
  994. return result;
  995. }
  996. #endregion
  997. #region Serializable content list managment fields, methods and classes
  998. /// <summary>
  999. /// Stores information about content item (class or property)
  1000. /// </summary>
  1001. private class ItemInfo
  1002. {
  1003. public string name = "";
  1004. public bool any = false;
  1005. public bool startsWith = false;
  1006. public bool endsWith = false;
  1007. }
  1008. // Storage for serializable content items
  1009. private ArrayList serializableContentList = null;
  1010. // Storage for non serializable content items
  1011. private ArrayList nonSerializableContentList = null;
  1012. /// <summary>
  1013. /// Return serializable content list.
  1014. /// </summary>
  1015. /// <returns>Serializable content list.</returns>
  1016. private ArrayList GetSerializableContentList()
  1017. {
  1018. if(serializableContentList == null)
  1019. {
  1020. serializableContentList = new ArrayList();
  1021. FillContentList(
  1022. serializableContentList,
  1023. (this.SerializableContent.Length > 0 ) ? this.SerializableContent : "*.*");
  1024. }
  1025. return serializableContentList;
  1026. }
  1027. /// <summary>
  1028. /// Return non serializable content list.
  1029. /// </summary>
  1030. /// <returns>Non serializable content list.</returns>
  1031. private ArrayList GetNonSerializableContentList()
  1032. {
  1033. if(nonSerializableContentList == null)
  1034. {
  1035. nonSerializableContentList = new ArrayList();
  1036. FillContentList(nonSerializableContentList, this.NonSerializableContent);
  1037. }
  1038. return nonSerializableContentList;
  1039. }
  1040. /// <summary>
  1041. /// Fill content list from the string.
  1042. /// </summary>
  1043. /// <param name="list">Array list class.</param>
  1044. /// <param name="content">Content string.</param>
  1045. private void FillContentList(ArrayList list, string content)
  1046. {
  1047. if(content.Length > 0)
  1048. {
  1049. string[] classPropertyPairs = content.Split(',');
  1050. foreach(string item in classPropertyPairs)
  1051. {
  1052. // Create two content items: one for the class and one for the property
  1053. ItemInfo classInfo = new ItemInfo();
  1054. ItemInfo propertyInfo = new ItemInfo();
  1055. // Find class and property name
  1056. int pointIndex = item.IndexOf('.');
  1057. if(pointIndex == -1)
  1058. {
  1059. throw (new ArgumentException(SR.ExceptionChartSerializerContentStringFormatInvalid));
  1060. }
  1061. classInfo.name = item.Substring(0, pointIndex).Trim();
  1062. propertyInfo.name = item.Substring(pointIndex + 1).Trim();
  1063. if(classInfo.name.Length == 0)
  1064. {
  1065. throw (new ArgumentException(SR.ExceptionChartSerializerClassNameUndefined));
  1066. }
  1067. if(propertyInfo.name.Length == 0)
  1068. {
  1069. throw (new ArgumentException(SR.ExceptionChartSerializerPropertyNameUndefined));
  1070. }
  1071. // Make sure property name do not have point character
  1072. if(propertyInfo.name.IndexOf('.') != -1)
  1073. {
  1074. throw (new ArgumentException(SR.ExceptionChartSerializerContentStringFormatInvalid));
  1075. }
  1076. // Check for wildcards in names
  1077. CheckWildCars(classInfo);
  1078. CheckWildCars(propertyInfo);
  1079. // Add class & property items into the array
  1080. list.Add(classInfo);
  1081. list.Add(propertyInfo);
  1082. }
  1083. }
  1084. }
  1085. /// <summary>
  1086. /// Checks wildcards in the name of the item.
  1087. /// Possible values:
  1088. /// "*"
  1089. /// "*Name"
  1090. /// "Name*"
  1091. /// </summary>
  1092. /// <param name="info">Item information class.</param>
  1093. private void CheckWildCars(ItemInfo info)
  1094. {
  1095. // Any class mask
  1096. if(info.name == "*")
  1097. {
  1098. info.any = true;
  1099. }
  1100. // Ends with class mask
  1101. else if(info.name[info.name.Length - 1] == '*')
  1102. {
  1103. info.endsWith = true;
  1104. info.name = info.name.TrimEnd('*');
  1105. }
  1106. // Starts with class mask
  1107. else if(info.name[0] == '*')
  1108. {
  1109. info.startsWith = true;
  1110. info.name = info.name.TrimStart('*');
  1111. }
  1112. }
  1113. #endregion
  1114. }
  1115. /// <summary>
  1116. /// Utility class which serialize object using XML format
  1117. /// </summary>
  1118. internal class XmlFormatSerializer : SerializerBase
  1119. {
  1120. #region Serialization public methods
  1121. /// <summary>
  1122. /// Serialize specified object into the stream.
  1123. /// </summary>
  1124. /// <param name="objectToSerialize">Object to be serialized.</param>
  1125. /// <param name="stream">The stream used to write the XML document.</param>
  1126. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
  1127. internal void Serialize(object objectToSerialize, Stream stream)
  1128. {
  1129. Serialize(objectToSerialize, (object)stream);
  1130. }
  1131. /// <summary>
  1132. /// Serialize specified object into the XML writer.
  1133. /// </summary>
  1134. /// <param name="objectToSerialize">Object to be serialized.</param>
  1135. /// <param name="xmlWriter">The XmlWriter used to write the XML document.</param>
  1136. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
  1137. internal void Serialize(object objectToSerialize, XmlWriter xmlWriter)
  1138. {
  1139. Serialize(objectToSerialize, (object)xmlWriter);
  1140. }
  1141. /// <summary>
  1142. /// Serialize specified object into the text writer.
  1143. /// </summary>
  1144. /// <param name="objectToSerialize">Object to be serialized.</param>
  1145. /// <param name="textWriter">The TextWriter used to write the XML document.</param>
  1146. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
  1147. internal void Serialize(object objectToSerialize, TextWriter textWriter)
  1148. {
  1149. Serialize(objectToSerialize, (object)textWriter);
  1150. }
  1151. /// <summary>
  1152. /// Serialize specified object into the file.
  1153. /// </summary>
  1154. /// <param name="objectToSerialize">Object to be serialized.</param>
  1155. /// <param name="fileName">The file name used to write the XML document.</param>
  1156. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
  1157. internal void Serialize(object objectToSerialize, string fileName)
  1158. {
  1159. Serialize(objectToSerialize, (object)fileName);
  1160. }
  1161. #endregion
  1162. #region Serialization private methods
  1163. /// <summary>
  1164. /// Serialize specified object into different types of writers using XML format.
  1165. /// Here is what is serialized in the object:
  1166. /// - all public properties with Set and Get methods
  1167. /// - all public properties with Get method which derived from ICollection
  1168. /// </summary>
  1169. /// <param name="objectToSerialize">Object to be serialized.</param>
  1170. /// <param name="writer">Defines the serialization destination. Can be Stream, TextWriter, XmlWriter or String (file name).</param>
  1171. internal override void Serialize(object objectToSerialize, object writer)
  1172. {
  1173. // the possible writer types
  1174. Stream stream = writer as Stream;
  1175. TextWriter textWriter = writer as TextWriter;
  1176. XmlWriter xmlWriter = writer as XmlWriter;
  1177. string writerStr = writer as string;
  1178. // Check input parameters
  1179. if(objectToSerialize == null)
  1180. {
  1181. throw(new ArgumentNullException("objectToSerialize"));
  1182. }
  1183. if(writer == null)
  1184. {
  1185. throw(new ArgumentNullException("writer"));
  1186. }
  1187. if(stream == null && textWriter == null && xmlWriter == null && writerStr == null)
  1188. {
  1189. throw (new ArgumentException(SR.ExceptionChartSerializerWriterObjectInvalid, "writer"));
  1190. }
  1191. // Create XML document
  1192. XmlDocument xmlDocument = new XmlDocument();
  1193. // Create document fragment
  1194. XmlDocumentFragment docFragment = xmlDocument.CreateDocumentFragment();
  1195. // Serialize object
  1196. SerializeObject(objectToSerialize, null, GetObjectName(objectToSerialize), docFragment, xmlDocument);
  1197. // Append document fragment
  1198. xmlDocument.AppendChild(docFragment);
  1199. // Remove empty child nodes
  1200. RemoveEmptyChildNodes(xmlDocument);
  1201. // Save XML document into the writer
  1202. if(stream != null)
  1203. {
  1204. xmlDocument.Save(stream);
  1205. // Flush stream and seek to the beginning
  1206. stream.Flush();
  1207. stream.Seek(0, SeekOrigin.Begin);
  1208. }
  1209. if(writerStr != null)
  1210. {
  1211. xmlDocument.Save(writerStr);
  1212. }
  1213. if(xmlWriter != null)
  1214. {
  1215. xmlDocument.Save(xmlWriter);
  1216. }
  1217. if(textWriter != null)
  1218. {
  1219. xmlDocument.Save(textWriter);
  1220. }
  1221. }
  1222. /// <summary>
  1223. /// Serialize specified object into the XML format.
  1224. /// Method is called recursively to serialize child objects.
  1225. /// </summary>
  1226. /// <param name="objectToSerialize">Object to be serialized.</param>
  1227. /// <param name="parent">Parent of the serialized object.</param>
  1228. /// <param name="elementName">Object element name.</param>
  1229. /// <param name="xmlParentNode">The XmlNode of the parent object to serialize the data in.</param>
  1230. /// <param name="xmlDocument">The XmlDocument the parent node belongs to.</param>
  1231. virtual protected void SerializeObject(object objectToSerialize, object parent, string elementName, XmlNode xmlParentNode, XmlDocument xmlDocument)
  1232. {
  1233. // Check input parameters
  1234. if(objectToSerialize == null)
  1235. {
  1236. return;
  1237. }
  1238. // Check if object should be serialized
  1239. if(parent != null)
  1240. {
  1241. PropertyDescriptor pd = TypeDescriptor.GetProperties(parent)[elementName];
  1242. if(pd != null)
  1243. {
  1244. SerializationVisibilityAttribute styleAttribute = (SerializationVisibilityAttribute)pd.Attributes[typeof(SerializationVisibilityAttribute)];
  1245. if(styleAttribute != null)
  1246. {
  1247. // Hidden property
  1248. if(styleAttribute.Visibility == SerializationVisibility.Hidden)
  1249. {
  1250. return;
  1251. }
  1252. }
  1253. }
  1254. }
  1255. // Check if object is a collection
  1256. if(objectToSerialize is ICollection)
  1257. {
  1258. // Serialize collection
  1259. SerializeCollection(objectToSerialize, elementName, xmlParentNode, xmlDocument);
  1260. return;
  1261. }
  1262. // Create object element inside the parents node
  1263. XmlNode xmlNode = xmlDocument.CreateElement(elementName);
  1264. xmlParentNode.AppendChild(xmlNode);
  1265. // Write template data into collection items
  1266. bool templateListItem = false;
  1267. IList parentList = parent as IList;
  1268. if(this.IsTemplateMode && parentList != null)
  1269. {
  1270. // Create "_Template_" attribute
  1271. XmlAttribute attrib = xmlDocument.CreateAttribute("_Template_");
  1272. // Check number of items in collection
  1273. if (parentList.Count == 1)
  1274. {
  1275. // If only one iten in collection, set "All" value.
  1276. // This means that style of this object should be applied to all
  1277. // existing items of the collection.
  1278. attrib.Value = "All";
  1279. }
  1280. else
  1281. {
  1282. // If there is more than one item, use it's index.
  1283. // When loading, style of these items will be applied to existing
  1284. // items in collection in the loop.
  1285. int itemIndex = parentList.IndexOf(objectToSerialize);
  1286. attrib.Value = itemIndex.ToString(CultureInfo.InvariantCulture);
  1287. }
  1288. // Add "_Template_" attribute into the XML node
  1289. xmlNode.Attributes.Append(attrib);
  1290. templateListItem = true;
  1291. }
  1292. // Retrive properties list of the object
  1293. PropertyInfo[] properties = objectToSerialize.GetType().GetProperties();
  1294. if (properties != null)
  1295. {
  1296. // Loop through all properties and serialize public properties
  1297. foreach(PropertyInfo pi in properties)
  1298. {
  1299. // Skip "Name" property from collection items in template mode
  1300. if(templateListItem && pi.Name == "Name")
  1301. {
  1302. continue;
  1303. }
  1304. // Skip inherited properties from the root object
  1305. if(IsChartBaseProperty(objectToSerialize, parent, pi))
  1306. {
  1307. continue;
  1308. }
  1309. // Check if this property is serializable content
  1310. if (!IsSerializableContent(pi.Name, objectToSerialize))
  1311. {
  1312. continue;
  1313. }
  1314. // Serialize collection
  1315. if (pi.CanRead && pi.PropertyType.GetInterface("ICollection", true) != null && !this.SerializeICollAsAtribute(pi, objectToSerialize))
  1316. {
  1317. // Check if SerializationVisibilityAttribute is set
  1318. bool serialize = true;
  1319. if(objectToSerialize != null)
  1320. {
  1321. PropertyDescriptor pd = TypeDescriptor.GetProperties(objectToSerialize)[pi.Name];
  1322. if(pd != null)
  1323. {
  1324. SerializationVisibilityAttribute styleAttribute = (SerializationVisibilityAttribute)pd.Attributes[typeof(SerializationVisibilityAttribute)];
  1325. if(styleAttribute != null)
  1326. {
  1327. if(styleAttribute.Visibility == SerializationVisibility.Hidden)
  1328. {
  1329. serialize = false;
  1330. }
  1331. }
  1332. }
  1333. }
  1334. // Check if collection has "ShouldSerialize" method
  1335. MethodInfo mi = objectToSerialize.GetType().GetMethod("ShouldSerialize" + pi.Name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public );
  1336. if(mi != null)
  1337. {
  1338. object result = mi.Invoke(objectToSerialize, null);
  1339. if(result is bool && ((bool)result) == false)
  1340. {
  1341. // Do not serialize collection
  1342. serialize = false;
  1343. }
  1344. }
  1345. // Serialize collection
  1346. if(serialize)
  1347. {
  1348. SerializeCollection(pi.GetValue(objectToSerialize, null), pi.Name, xmlNode, xmlDocument);
  1349. }
  1350. }
  1351. // Serialize public properties with Get and Set methods
  1352. else if(pi.CanRead && pi.CanWrite)
  1353. {
  1354. // Skip indexes
  1355. if(pi.Name == "Item")
  1356. {
  1357. continue;
  1358. }
  1359. // Check if an object should be serialized as a property or as a class
  1360. if(ShouldSerializeAsAttribute(pi, objectToSerialize))
  1361. {
  1362. // Serialize property
  1363. SerializeProperty(pi.GetValue(objectToSerialize, null), objectToSerialize, pi.Name, xmlNode, xmlDocument);
  1364. }
  1365. else
  1366. {
  1367. // Serialize inner object
  1368. SerializeObject(pi.GetValue(objectToSerialize, null), objectToSerialize, pi.Name, xmlNode, xmlDocument);
  1369. }
  1370. }
  1371. }
  1372. }
  1373. return;
  1374. }
  1375. /// <summary>
  1376. /// Serializes the data point.
  1377. /// </summary>
  1378. /// <param name="objectToSerialize">The object to serialize.</param>
  1379. /// <param name="xmlParentNode">The XML parent node.</param>
  1380. /// <param name="xmlDocument">The XML document.</param>
  1381. internal void SerializeDataPoint(object objectToSerialize, XmlNode xmlParentNode, XmlDocument xmlDocument)
  1382. {
  1383. // Create object element inside the parents node
  1384. XmlNode xmlNode = xmlDocument.CreateElement(GetObjectName(objectToSerialize));
  1385. xmlParentNode.AppendChild(xmlNode);
  1386. DataPoint dataPoint = objectToSerialize as DataPoint;
  1387. if (dataPoint.XValue != 0d && IsSerializableContent("XValue", objectToSerialize))
  1388. {
  1389. XmlAttribute attrib = xmlDocument.CreateAttribute("XValue");
  1390. attrib.Value = GetXmlValue(dataPoint.XValue, dataPoint, "XValue");
  1391. xmlNode.Attributes.Append(attrib);
  1392. }
  1393. if (dataPoint.YValues.Length > 0 && IsSerializableContent("YValues", objectToSerialize))
  1394. {
  1395. XmlAttribute attrib = xmlDocument.CreateAttribute("YValues");
  1396. attrib.Value = GetXmlValue(dataPoint.YValues, dataPoint, "YValues");
  1397. xmlNode.Attributes.Append(attrib);
  1398. }
  1399. if (dataPoint.IsEmpty && IsSerializableContent("IsEmpty", objectToSerialize))
  1400. {
  1401. XmlAttribute attrib = xmlDocument.CreateAttribute("IsEmpty");
  1402. attrib.Value = GetXmlValue(dataPoint.isEmptyPoint, dataPoint, "IsEmpty");
  1403. xmlNode.Attributes.Append(attrib);
  1404. }
  1405. bool hasCustomProperties = false;
  1406. foreach (DictionaryEntry entry in dataPoint.properties)
  1407. {
  1408. if (entry.Key is int)
  1409. {
  1410. CommonCustomProperties propertyType = (CommonCustomProperties)((int)entry.Key);
  1411. String properyName = propertyType.ToString();
  1412. if (IsSerializableContent(properyName, objectToSerialize))
  1413. {
  1414. XmlAttribute attrib = xmlDocument.CreateAttribute(properyName);
  1415. attrib.Value = GetXmlValue(entry.Value, dataPoint, properyName);
  1416. xmlNode.Attributes.Append(attrib);
  1417. }
  1418. }
  1419. else
  1420. {
  1421. hasCustomProperties = true;
  1422. }
  1423. }
  1424. if (hasCustomProperties && !String.IsNullOrEmpty(dataPoint.CustomProperties) && IsSerializableContent("CustomProperties", objectToSerialize))
  1425. {
  1426. XmlAttribute attrib = xmlDocument.CreateAttribute("CustomProperties");
  1427. attrib.Value = GetXmlValue(dataPoint.CustomProperties, dataPoint, "CustomProperties");
  1428. xmlNode.Attributes.Append(attrib);
  1429. }
  1430. }
  1431. /// <summary>
  1432. /// Serialize specified object into the XML text writer.
  1433. /// Method is called recursively to serialize child objects.
  1434. /// </summary>
  1435. /// <param name="objectToSerialize">Object to be serialized.</param>
  1436. /// <param name="elementName">Object element name.</param>
  1437. /// <param name="xmlParentNode">The XmlNode of the parent object to serialize the data in.</param>
  1438. /// <param name="xmlDocument">The XmlDocument the parent node belongs to.</param>
  1439. virtual protected void SerializeCollection(object objectToSerialize, string elementName, XmlNode xmlParentNode, XmlDocument xmlDocument)
  1440. {
  1441. ICollection collection = objectToSerialize as ICollection;
  1442. if(collection != null)
  1443. {
  1444. // Create object element inside the parents node
  1445. XmlNode xmlNode = xmlDocument.CreateElement(elementName);
  1446. xmlParentNode.AppendChild(xmlNode);
  1447. // Enumerate through all objects in collection and serialize them
  1448. foreach(object obj in collection)
  1449. {
  1450. if (obj is DataPoint)
  1451. {
  1452. SerializeDataPoint(obj, xmlNode, xmlDocument);
  1453. continue;
  1454. }
  1455. SerializeObject(obj, objectToSerialize, GetObjectName(obj), xmlNode, xmlDocument);
  1456. }
  1457. }
  1458. }
  1459. /// <summary>
  1460. /// Serialize specified object into the XML text writer.
  1461. /// Method is called recursively to serialize child objects.
  1462. /// </summary>
  1463. /// <param name="objectToSerialize">Object to be serialized.</param>
  1464. /// <param name="parent">Parent of the serialized object.</param>
  1465. /// <param name="elementName">Object element name.</param>
  1466. /// <param name="xmlParentNode">The XmlNode of the parent object to serialize the data in.</param>
  1467. /// <param name="xmlDocument">The XmlDocument the parent node belongs to.</param>
  1468. virtual protected void SerializeProperty(object objectToSerialize, object parent, string elementName, XmlNode xmlParentNode, XmlDocument xmlDocument)
  1469. {
  1470. // Check input parameters
  1471. if(objectToSerialize == null || parent == null)
  1472. {
  1473. return;
  1474. }
  1475. // Check if property has non-default value
  1476. PropertyDescriptor pd = TypeDescriptor.GetProperties(parent)[elementName];
  1477. if(pd != null)
  1478. {
  1479. DefaultValueAttribute defValueAttribute = (DefaultValueAttribute)pd.Attributes[typeof(DefaultValueAttribute)];
  1480. if(defValueAttribute != null)
  1481. {
  1482. if(objectToSerialize.Equals(defValueAttribute.Value))
  1483. {
  1484. // Do not serialize properties with default values
  1485. return;
  1486. }
  1487. }
  1488. else
  1489. {
  1490. // Check if property has "ShouldSerialize" method
  1491. MethodInfo mi = parent.GetType().GetMethod("ShouldSerialize" + elementName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
  1492. if(mi != null)
  1493. {
  1494. object result = mi.Invoke(parent, null);
  1495. if(result is bool && ((bool)result) == false)
  1496. {
  1497. // Do not serialize properties with default values
  1498. return;
  1499. }
  1500. }
  1501. }
  1502. // Check XmlFormatSerializerStyle attribute
  1503. SerializationVisibilityAttribute styleAttribute = (SerializationVisibilityAttribute)pd.Attributes[typeof(SerializationVisibilityAttribute)];
  1504. if(styleAttribute != null)
  1505. {
  1506. // Hidden property
  1507. if(styleAttribute.Visibility == SerializationVisibility.Hidden)
  1508. {
  1509. return;
  1510. }
  1511. }
  1512. }
  1513. // Serialize property as a parents node attribute
  1514. XmlAttribute attrib = xmlDocument.CreateAttribute(elementName);
  1515. attrib.Value = GetXmlValue(objectToSerialize, parent, elementName);
  1516. xmlParentNode.Attributes.Append(attrib);
  1517. }
  1518. /// <summary>
  1519. /// Converts object value into the string.
  1520. /// </summary>
  1521. /// <param name="obj">Object to convert.</param>
  1522. /// <param name="parent">Object parent.</param>
  1523. /// <param name="elementName">Object name.</param>
  1524. /// <returns>Object value as strig.</returns>
  1525. protected string GetXmlValue(object obj, object parent, string elementName)
  1526. {
  1527. string objStr = obj as string;
  1528. if(objStr != null)
  1529. {
  1530. return objStr;
  1531. }
  1532. Font font = obj as Font;
  1533. if(font != null)
  1534. {
  1535. return SerializerBase.FontToString(font);
  1536. }
  1537. if(obj is Color)
  1538. {
  1539. return colorConverter.ConvertToString(null, System.Globalization.CultureInfo.InvariantCulture, obj);
  1540. }
  1541. Color[] colors = obj as Color[];
  1542. if(colors != null)
  1543. {
  1544. return ColorArrayConverter.ColorArrayToString(colors);
  1545. }
  1546. System.Drawing.Image image = obj as System.Drawing.Image;
  1547. if(image != null)
  1548. {
  1549. return ImageToString(image);
  1550. }
  1551. // Look for the converter set with the attibute
  1552. PropertyDescriptor pd = TypeDescriptor.GetProperties(parent)[elementName];
  1553. if(pd != null)
  1554. {
  1555. TypeConverter converter = this.FindConverter(pd);
  1556. if (converter != null && converter.CanConvertTo(typeof(string)))
  1557. {
  1558. return converter.ConvertToString(null, System.Globalization.CultureInfo.InvariantCulture, obj);
  1559. }
  1560. }
  1561. // Try using default string convertion
  1562. return obj.ToString();
  1563. }
  1564. /// <summary>
  1565. /// Removes all empty nodes from the XML document.
  1566. /// Method is called recursively to remove empty child nodes first.
  1567. /// </summary>
  1568. /// <param name="xmlNode">The node where to start the removing.</param>
  1569. private void RemoveEmptyChildNodes(XmlNode xmlNode)
  1570. {
  1571. // Loop through all child nodes
  1572. for(int nodeIndex = 0; nodeIndex < xmlNode.ChildNodes.Count; nodeIndex++)
  1573. {
  1574. // Remove empty child nodes of the child
  1575. RemoveEmptyChildNodes(xmlNode.ChildNodes[nodeIndex]);
  1576. // Check if there are any non-empty nodes left
  1577. XmlNode currentNode = xmlNode.ChildNodes[nodeIndex];
  1578. if( currentNode.ParentNode != null &&
  1579. !(currentNode.ParentNode is XmlDocument) )
  1580. {
  1581. if(!currentNode.HasChildNodes &&
  1582. (currentNode.Attributes == null ||
  1583. currentNode.Attributes.Count == 0))
  1584. {
  1585. // Remove node
  1586. xmlNode.RemoveChild(xmlNode.ChildNodes[nodeIndex]);
  1587. --nodeIndex;
  1588. }
  1589. }
  1590. // Remove node with one "_Template_" attribute
  1591. if(!currentNode.HasChildNodes &&
  1592. currentNode.Attributes.Count == 1 &&
  1593. currentNode.Attributes["_Template_"] != null)
  1594. {
  1595. // Remove node
  1596. xmlNode.RemoveChild(xmlNode.ChildNodes[nodeIndex]);
  1597. --nodeIndex;
  1598. }
  1599. }
  1600. }
  1601. #endregion
  1602. #region Deserialization public methods
  1603. /// <summary>
  1604. /// Deserialize specified object from the stream.
  1605. /// </summary>
  1606. /// <param name="objectToDeserialize">Object to be deserialized.</param>
  1607. /// <param name="stream">The stream used to read the XML document from.</param>
  1608. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
  1609. internal void Deserialize(object objectToDeserialize, Stream stream)
  1610. {
  1611. Deserialize(objectToDeserialize, (object)stream);
  1612. }
  1613. /// <summary>
  1614. /// Deserialize specified object from the XML reader.
  1615. /// </summary>
  1616. /// <param name="objectToDeserialize">Object to be deserialized.</param>
  1617. /// <param name="xmlReader">The XmlReader used to read the XML document from.</param>
  1618. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
  1619. internal void Deserialize(object objectToDeserialize, XmlReader xmlReader)
  1620. {
  1621. Deserialize(objectToDeserialize, (object)xmlReader);
  1622. }
  1623. /// <summary>
  1624. /// Deserialize specified object from the text reader.
  1625. /// </summary>
  1626. /// <param name="objectToDeserialize">Object to be deserialized.</param>
  1627. /// <param name="textReader">The TextReader used to write the XML document from.</param>
  1628. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
  1629. internal void Deserialize(object objectToDeserialize, TextReader textReader)
  1630. {
  1631. Deserialize(objectToDeserialize, (object)textReader);
  1632. }
  1633. /// <summary>
  1634. /// Deserialize specified object from the file.
  1635. /// </summary>
  1636. /// <param name="objectToDeserialize">Object to be deserialized.</param>
  1637. /// <param name="fileName">The file name used to read the XML document from.</param>
  1638. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
  1639. internal void Deserialize(object objectToDeserialize, string fileName)
  1640. {
  1641. Deserialize(objectToDeserialize, (object)fileName);
  1642. }
  1643. #endregion
  1644. #region Deserialization private methods
  1645. /// <summary>
  1646. /// Deserialize object from different types of readers using XML format.
  1647. /// </summary>
  1648. /// <param name="objectToDeserialize">Object to be deserialized.</param>
  1649. /// <param name="reader">Defines the deserialization data source. Can be Stream, TextReader, XmlReader or String (file name).</param>
  1650. internal override void Deserialize(object objectToDeserialize, object reader)
  1651. {
  1652. // the four possible types of readers
  1653. Stream stream = reader as Stream;
  1654. TextReader textReader = reader as TextReader;
  1655. XmlReader xmlReader = reader as XmlReader;
  1656. string readerStr = reader as string;
  1657. // Check input parameters
  1658. if(objectToDeserialize == null)
  1659. {
  1660. throw(new ArgumentNullException("objectToDeserialize"));
  1661. }
  1662. if(reader == null)
  1663. {
  1664. throw(new ArgumentNullException("reader"));
  1665. }
  1666. if(stream == null && textReader == null && xmlReader == null && readerStr == null)
  1667. {
  1668. throw (new ArgumentException(SR.ExceptionChartSerializerReaderObjectInvalid, "reader"));
  1669. }
  1670. // Create XML document
  1671. XmlDocument xmlDocument = new XmlDocument();
  1672. XmlReader xmlBaseReader = null;
  1673. try
  1674. {
  1675. // process files without DTD
  1676. XmlReaderSettings settings = new XmlReaderSettings();
  1677. // settings.ProhibitDtd is obsolete inn NetFx 4.0, the #ifdef stays for compilation under NetFx 3.5.
  1678. #if OLD_DTD
  1679. settings.ProhibitDtd = true;
  1680. #else
  1681. settings.DtdProcessing = DtdProcessing.Prohibit; //don't allow DTD
  1682. #endif
  1683. // Load XML document from the reader
  1684. if (stream != null)
  1685. {
  1686. xmlBaseReader = XmlReader.Create(stream, settings);
  1687. }
  1688. if (readerStr != null)
  1689. {
  1690. xmlBaseReader = XmlReader.Create(readerStr, settings);
  1691. }
  1692. if (xmlReader != null)
  1693. {
  1694. xmlBaseReader = XmlReader.Create(xmlReader, settings);
  1695. }
  1696. if (textReader != null)
  1697. {
  1698. xmlBaseReader = XmlReader.Create(textReader, settings);
  1699. }
  1700. xmlDocument.Load(xmlBaseReader);
  1701. // Reset properties of the root object
  1702. if (IsResetWhenLoading)
  1703. {
  1704. ResetObjectProperties(objectToDeserialize);
  1705. }
  1706. // Deserialize object
  1707. DeserializeObject(objectToDeserialize, null, GetObjectName(objectToDeserialize), xmlDocument.DocumentElement, xmlDocument);
  1708. }
  1709. finally
  1710. {
  1711. if (xmlBaseReader != null)
  1712. {
  1713. ((IDisposable)xmlBaseReader).Dispose();
  1714. }
  1715. }
  1716. }
  1717. /// <summary>
  1718. /// Deserialize object from the XML format.
  1719. /// Method is called recursively to deserialize child objects.
  1720. /// </summary>
  1721. /// <param name="objectToDeserialize">Object to be deserialized.</param>
  1722. /// <param name="parent">Parent of the deserialized object.</param>
  1723. /// <param name="elementName">Object element name.</param>
  1724. /// <param name="xmlParentNode">The XmlNode of the parent object to deserialize the data from.</param>
  1725. /// <param name="xmlDocument">The XmlDocument the parent node belongs to.</param>
  1726. /// <returns>Number of properties set.</returns>
  1727. virtual internal int DeserializeObject(object objectToDeserialize, object parent, string elementName, XmlNode xmlParentNode, XmlDocument xmlDocument)
  1728. {
  1729. int setPropertiesNumber = 0;
  1730. // Check input parameters
  1731. if(objectToDeserialize == null)
  1732. {
  1733. return setPropertiesNumber;
  1734. }
  1735. // Loop through all node properties
  1736. foreach(XmlAttribute attr in xmlParentNode.Attributes)
  1737. {
  1738. // Skip template collection item attribute
  1739. if(attr.Name == "_Template_")
  1740. {
  1741. continue;
  1742. }
  1743. // Check if this property is serializable content
  1744. if(IsSerializableContent(attr.Name, objectToDeserialize))
  1745. {
  1746. SetXmlValue(objectToDeserialize, attr.Name, attr.Value);
  1747. ++setPropertiesNumber;
  1748. }
  1749. }
  1750. // Read template data into the collection
  1751. IList list = objectToDeserialize as IList;
  1752. if(this.IsTemplateMode &&
  1753. list != null &&
  1754. xmlParentNode.FirstChild.Attributes["_Template_"] != null)
  1755. {
  1756. // Loop through all items in collection
  1757. int itemIndex = 0;
  1758. foreach(object listItem in list)
  1759. {
  1760. // Find XML node appropriate for the item from the collection
  1761. XmlNode listItemNode = null;
  1762. // Loop through all child nodes
  1763. foreach(XmlNode childNode in xmlParentNode.ChildNodes)
  1764. {
  1765. string templateString = childNode.Attributes["_Template_"].Value;
  1766. if(templateString != null && templateString.Length > 0)
  1767. {
  1768. if(templateString == "All")
  1769. {
  1770. listItemNode = childNode;
  1771. break;
  1772. }
  1773. else
  1774. {
  1775. // If there is more items in collection than XML node in template
  1776. // apply items in a loop
  1777. int loopItemIndex = itemIndex;
  1778. while(loopItemIndex > xmlParentNode.ChildNodes.Count - 1)
  1779. {
  1780. loopItemIndex -= xmlParentNode.ChildNodes.Count;
  1781. }
  1782. // Convert attribute value to index
  1783. int nodeIndex = int.Parse(templateString, CultureInfo.InvariantCulture);
  1784. if(nodeIndex == loopItemIndex)
  1785. {
  1786. listItemNode = childNode;
  1787. break;
  1788. }
  1789. }
  1790. }
  1791. }
  1792. // Load data from the node
  1793. if(listItemNode != null)
  1794. {
  1795. // Load object data
  1796. DeserializeObject(listItem, objectToDeserialize, "", listItemNode, xmlDocument);
  1797. }
  1798. // Increase item index
  1799. ++itemIndex;
  1800. }
  1801. // No futher loading required
  1802. return 0;
  1803. }
  1804. // Loop through all child elements
  1805. int listItemIndex = 0;
  1806. foreach(XmlNode childNode in xmlParentNode.ChildNodes)
  1807. {
  1808. // Special handling for the collections
  1809. // Bug VSTS #235707 - The collections IsSerializableContent are already checked as a property in the else statement.
  1810. if (list != null)
  1811. {
  1812. // Create new item object
  1813. string itemName = null;
  1814. if (childNode.Attributes["Name"] != null)
  1815. {
  1816. itemName = childNode.Attributes["Name"].Value;
  1817. }
  1818. bool reusedObject = false;
  1819. object listItem = GetListNewItem(list, childNode.Name, ref itemName, ref reusedObject);
  1820. // Deserialize list item object
  1821. int itemSetProperties = DeserializeObject(listItem, objectToDeserialize, "", childNode, xmlDocument);
  1822. setPropertiesNumber += itemSetProperties;
  1823. // Add item object into the list
  1824. if (itemSetProperties > 0 || reusedObject)
  1825. {
  1826. list.Insert(listItemIndex++, listItem);
  1827. }
  1828. }
  1829. else
  1830. {
  1831. // Check if this property is serializable content
  1832. if (IsSerializableContent(childNode.Name, objectToDeserialize))
  1833. {
  1834. // Deserialize the property using property descriptor
  1835. PropertyDescriptor pd = TypeDescriptor.GetProperties(objectToDeserialize)[childNode.Name];
  1836. if (pd != null)
  1837. {
  1838. object innerObject = pd.GetValue(objectToDeserialize);
  1839. // Deserialize list item object
  1840. setPropertiesNumber += DeserializeObject(innerObject, objectToDeserialize, childNode.Name, childNode, xmlDocument);
  1841. }
  1842. else if (!IsUnknownAttributeIgnored)
  1843. {
  1844. throw (new InvalidOperationException(SR.ExceptionChartSerializerPropertyNameUnknown(childNode.Name, objectToDeserialize.GetType().ToString())));
  1845. }
  1846. }
  1847. }
  1848. }
  1849. return setPropertiesNumber;
  1850. }
  1851. /// <summary>
  1852. /// Sets a property of an object using name and value as string.
  1853. /// </summary>
  1854. /// <param name="obj">Object to set.</param>
  1855. /// <param name="attrName">Attribute (property) name.</param>
  1856. /// <param name="attrValue">Object value..</param>
  1857. /// <returns>Object value as strig.</returns>
  1858. private void SetXmlValue(object obj, string attrName, string attrValue)
  1859. {
  1860. PropertyInfo pi = obj.GetType().GetProperty(attrName);
  1861. if(pi != null)
  1862. {
  1863. // Convert string to object value
  1864. object objValue = attrValue;
  1865. if(pi.PropertyType == typeof(string))
  1866. {
  1867. objValue = attrValue;
  1868. }
  1869. else if(pi.PropertyType == typeof(Font))
  1870. {
  1871. objValue = SerializerBase.FontFromString(attrValue);
  1872. }
  1873. else if(pi.PropertyType == typeof(Color))
  1874. {
  1875. objValue = (Color)colorConverter.ConvertFromString(null, System.Globalization.CultureInfo.InvariantCulture, attrValue);
  1876. }
  1877. else if(pi.PropertyType == typeof(System.Drawing.Image))
  1878. {
  1879. objValue = ImageFromString(attrValue);
  1880. }
  1881. else
  1882. {
  1883. // Look for the converter set with the attibute
  1884. PropertyDescriptor pd = TypeDescriptor.GetProperties(obj)[attrName];
  1885. if(pd != null)
  1886. {
  1887. TypeConverter converter = this.FindConverter(pd);
  1888. if (converter != null && converter.CanConvertFrom(typeof(string)))
  1889. {
  1890. objValue = converter.ConvertFromString(null, System.Globalization.CultureInfo.InvariantCulture, attrValue);
  1891. }
  1892. }
  1893. }
  1894. // Set object value
  1895. pi.SetValue(obj, objValue, null);
  1896. }
  1897. else if(!IsUnknownAttributeIgnored)
  1898. {
  1899. throw(new InvalidOperationException(SR.ExceptionChartSerializerPropertyNameUnknown( attrName,obj.GetType().ToString())));
  1900. }
  1901. }
  1902. #endregion
  1903. }
  1904. /// <summary>
  1905. /// Utility class which serialize object using binary format
  1906. /// </summary>
  1907. internal class BinaryFormatSerializer : SerializerBase
  1908. {
  1909. #region Serialization methods
  1910. /// <summary>
  1911. /// Serialize specified object into the destination using binary format.
  1912. /// </summary>
  1913. /// <param name="objectToSerialize">Object to be serialized.</param>
  1914. /// <param name="destination">Serialization destination.</param>
  1915. internal override void Serialize(object objectToSerialize, object destination)
  1916. {
  1917. // Check input parameters
  1918. if (objectToSerialize == null)
  1919. {
  1920. throw (new ArgumentNullException("objectToSerialize"));
  1921. }
  1922. if (destination == null)
  1923. {
  1924. throw (new ArgumentNullException("destination"));
  1925. }
  1926. string destinationStr = destination as string;
  1927. if (destinationStr != null)
  1928. {
  1929. Serialize(objectToSerialize, destinationStr);
  1930. return;
  1931. }
  1932. Stream stream = destination as Stream;
  1933. if (stream != null)
  1934. {
  1935. Serialize(objectToSerialize, stream);
  1936. return;
  1937. }
  1938. BinaryWriter binaryWriter = destination as BinaryWriter;
  1939. if (binaryWriter != null)
  1940. {
  1941. Serialize(objectToSerialize, binaryWriter);
  1942. return;
  1943. }
  1944. throw (new ArgumentException(SR.ExceptionChartSerializerDestinationObjectInvalid, "destination"));
  1945. }
  1946. /// <summary>
  1947. /// Serialize specified object into the file using binary format.
  1948. /// </summary>
  1949. /// <param name="objectToSerialize">Object to be serialized.</param>
  1950. /// <param name="fileName">File name to serialize the data in.</param>
  1951. internal void Serialize(object objectToSerialize, string fileName)
  1952. {
  1953. FileStream stream = new FileStream(fileName, FileMode.Create);
  1954. Serialize(objectToSerialize, new BinaryWriter(stream));
  1955. stream.Close();
  1956. }
  1957. /// <summary>
  1958. /// Serialize specified object into the stream using binary format.
  1959. /// </summary>
  1960. /// <param name="objectToSerialize">Object to be serialized.</param>
  1961. /// <param name="stream">Defines the serialization destination.</param>
  1962. internal void Serialize(object objectToSerialize, Stream stream)
  1963. {
  1964. Serialize(objectToSerialize, new BinaryWriter(stream));
  1965. }
  1966. /// <summary>
  1967. /// Serialize specified object into different types of writers using binary format.
  1968. /// Here is what is serialized in the object:
  1969. /// - all public properties with Set and Get methods
  1970. /// - all public properties with Get method which derived from ICollection
  1971. /// </summary>
  1972. /// <param name="objectToSerialize">Object to be serialized.</param>
  1973. /// <param name="writer">Defines the serialization destination.</param>
  1974. internal void Serialize(object objectToSerialize, BinaryWriter writer)
  1975. {
  1976. // Check input parameters
  1977. if(objectToSerialize == null)
  1978. {
  1979. throw(new ArgumentNullException("objectToSerialize"));
  1980. }
  1981. if(writer == null)
  1982. {
  1983. throw(new ArgumentNullException("writer"));
  1984. }
  1985. // Write bnary format header into the stream, which consist of 15 characters
  1986. char[] header = new char[15] {'D', 'C', 'B', 'F', '4', '0', '0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0'};
  1987. writer.Write(header);
  1988. // Serialize object
  1989. SerializeObject(objectToSerialize, null, GetObjectName(objectToSerialize), writer);
  1990. // Flush the writer stream
  1991. writer.Flush();
  1992. // Reset stream position
  1993. writer.Seek(0, SeekOrigin.Begin);
  1994. }
  1995. /// <summary>
  1996. /// Serialize specified object into the binary format.
  1997. /// Method is called recursively to serialize child objects.
  1998. /// </summary>
  1999. /// <param name="objectToSerialize">Object to be serialized.</param>
  2000. /// <param name="parent">Parent of the serialized object.</param>
  2001. /// <param name="elementName">Object element name.</param>
  2002. /// <param name="writer">Binary writer object.</param>
  2003. virtual internal void SerializeObject(object objectToSerialize, object parent, string elementName, BinaryWriter writer)
  2004. {
  2005. // Check input parameters
  2006. if(objectToSerialize == null)
  2007. {
  2008. return;
  2009. }
  2010. // Check if object should be serialized
  2011. if(parent != null)
  2012. {
  2013. PropertyDescriptor pd = TypeDescriptor.GetProperties(parent)[elementName];
  2014. if(pd != null)
  2015. {
  2016. SerializationVisibilityAttribute styleAttribute = (SerializationVisibilityAttribute)pd.Attributes[typeof(SerializationVisibilityAttribute)];
  2017. if(styleAttribute != null)
  2018. {
  2019. // Hidden property
  2020. if(styleAttribute.Visibility == SerializationVisibility.Hidden)
  2021. {
  2022. return;
  2023. }
  2024. }
  2025. }
  2026. }
  2027. // Check if object is a collection
  2028. if(objectToSerialize is ICollection)
  2029. {
  2030. // Serialize collection
  2031. SerializeCollection(objectToSerialize, elementName, writer);
  2032. return;
  2033. }
  2034. // Write object ID (hash of the name) into the writer
  2035. writer.Write(SerializerBase.GetStringHashCode(elementName));
  2036. // Remember position where object data is started
  2037. long elementStartPosition = writer.Seek(0, SeekOrigin.Current);
  2038. // Retrive properties list of the object
  2039. ArrayList propNamesList = new ArrayList();
  2040. PropertyInfo[] properties = objectToSerialize.GetType().GetProperties();
  2041. if(properties != null)
  2042. {
  2043. // Loop through all properties and serialize public properties
  2044. foreach(PropertyInfo pi in properties)
  2045. {
  2046. // Skip inherited properties from the root object
  2047. if(IsChartBaseProperty(objectToSerialize, parent, pi))
  2048. {
  2049. continue;
  2050. }
  2051. // Serialize collection
  2052. if (pi.CanRead && pi.PropertyType.GetInterface("ICollection", true) != null && !this.SerializeICollAsAtribute(pi, objectToSerialize))
  2053. {
  2054. bool serialize = IsSerializableContent(pi.Name, objectToSerialize);
  2055. // fixing Axes Array Framework 2.0 side effect
  2056. // fixed by:DT
  2057. if (serialize && objectToSerialize != null)
  2058. {
  2059. PropertyDescriptor pd = TypeDescriptor.GetProperties(objectToSerialize)[pi.Name];
  2060. if (pd != null)
  2061. {
  2062. SerializationVisibilityAttribute styleAttribute = (SerializationVisibilityAttribute)pd.Attributes[typeof(SerializationVisibilityAttribute)];
  2063. if (styleAttribute != null)
  2064. {
  2065. if (styleAttribute.Visibility == SerializationVisibility.Hidden)
  2066. {
  2067. serialize = false;
  2068. }
  2069. }
  2070. }
  2071. }
  2072. MethodInfo mi = objectToSerialize.GetType().GetMethod("ShouldSerialize" + pi.Name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
  2073. if( serialize && mi != null)
  2074. {
  2075. object result = mi.Invoke(objectToSerialize, null);
  2076. if(result is bool && ((bool)result) == false)
  2077. {
  2078. // Do not serialize collection
  2079. serialize = false;
  2080. }
  2081. }
  2082. // Serialize collection
  2083. if(serialize)
  2084. {
  2085. propNamesList.Add(pi.Name);
  2086. SerializeCollection(pi.GetValue(objectToSerialize, null), pi.Name, writer);
  2087. }
  2088. }
  2089. // Serialize public properties with Get and Set methods
  2090. else if(pi.CanRead && pi.CanWrite)
  2091. {
  2092. // Skip indexes
  2093. if(pi.Name == "Item")
  2094. {
  2095. continue;
  2096. }
  2097. // Check if this property is serializable content
  2098. if (IsSerializableContent(pi.Name, objectToSerialize))
  2099. {
  2100. // Check if an object should be serialized as a property or as a class
  2101. if (ShouldSerializeAsAttribute(pi, objectToSerialize))
  2102. {
  2103. // Serialize property
  2104. SerializeProperty(pi.GetValue(objectToSerialize, null), objectToSerialize, pi.Name, writer);
  2105. }
  2106. else
  2107. {
  2108. // Serialize inner object
  2109. SerializeObject(pi.GetValue(objectToSerialize, null), objectToSerialize, pi.Name, writer);
  2110. }
  2111. }
  2112. propNamesList.Add(pi.Name);
  2113. }
  2114. }
  2115. // Check that all properties have unique IDs
  2116. CheckPropertiesID(propNamesList);
  2117. }
  2118. // If position of the writer did not change - nothing was written
  2119. if(writer.Seek(0, SeekOrigin.Current) == elementStartPosition)
  2120. {
  2121. // Remove object ID from the stream
  2122. writer.Seek(-2, SeekOrigin.Current);
  2123. writer.Write((short)0);
  2124. writer.Seek(-2, SeekOrigin.Current);
  2125. }
  2126. else
  2127. {
  2128. // Write the end objectTag
  2129. writer.Write((short)0);
  2130. }
  2131. return;
  2132. }
  2133. /// <summary>
  2134. /// Serializes the data point.
  2135. /// </summary>
  2136. /// <param name="objectToSerialize">The object to serialize.</param>
  2137. /// <param name="elementName">Name of the element.</param>
  2138. /// <param name="writer">The writer.</param>
  2139. private void SerializeDataPoint(object objectToSerialize, string elementName, BinaryWriter writer)
  2140. {
  2141. // Write object ID (hash of the name) into the writer
  2142. writer.Write(SerializerBase.GetStringHashCode(elementName));
  2143. // Remember position where object data is started
  2144. long elementStartPosition = writer.Seek(0, SeekOrigin.Current);
  2145. DataPoint dataPoint = objectToSerialize as DataPoint;
  2146. if (dataPoint.XValue != 0d && IsSerializableContent("XValue", objectToSerialize))
  2147. {
  2148. SerializeProperty(dataPoint.XValue, dataPoint, "XValue", writer);
  2149. }
  2150. if (dataPoint.YValues.Length > 0 && IsSerializableContent("YValues", objectToSerialize))
  2151. {
  2152. SerializeProperty(dataPoint.YValues, dataPoint, "YValues", writer);
  2153. }
  2154. if (dataPoint.IsEmpty && IsSerializableContent("IsEmpty", objectToSerialize))
  2155. {
  2156. SerializeProperty(dataPoint.IsEmpty, dataPoint, "IsEmpty", writer);
  2157. }
  2158. bool hasCustomProperties = false;
  2159. foreach (DictionaryEntry entry in dataPoint.properties)
  2160. {
  2161. if (entry.Key is int)
  2162. {
  2163. CommonCustomProperties propertyType = (CommonCustomProperties)((int)entry.Key);
  2164. String properyName = propertyType.ToString();
  2165. if (IsSerializableContent(properyName, objectToSerialize))
  2166. {
  2167. SerializeProperty(entry.Value, dataPoint, properyName, writer);
  2168. }
  2169. }
  2170. else
  2171. {
  2172. hasCustomProperties = true;
  2173. }
  2174. }
  2175. if (hasCustomProperties && !String.IsNullOrEmpty(dataPoint.CustomProperties) && IsSerializableContent("CustomProperties", objectToSerialize))
  2176. {
  2177. SerializeProperty(dataPoint.CustomProperties, dataPoint, "CustomProperties", writer);
  2178. }
  2179. // If position of the writer did not change - nothing was written
  2180. if (writer.Seek(0, SeekOrigin.Current) == elementStartPosition)
  2181. {
  2182. // Remove object ID from the stream
  2183. writer.Seek(-2, SeekOrigin.Current);
  2184. writer.Write((short)0);
  2185. writer.Seek(-2, SeekOrigin.Current);
  2186. }
  2187. else
  2188. {
  2189. // Write the end objectTag
  2190. writer.Write((short)0);
  2191. }
  2192. }
  2193. /// <summary>
  2194. /// Serialize specified object into the binary writer.
  2195. /// Method is called recursively to serialize child objects.
  2196. /// </summary>
  2197. /// <param name="objectToSerialize">Object to be serialized.</param>
  2198. /// <param name="elementName">Object element name.</param>
  2199. /// <param name="writer">Binary writer.</param>
  2200. virtual internal void SerializeCollection(object objectToSerialize, string elementName, BinaryWriter writer)
  2201. {
  2202. ICollection collection = objectToSerialize as ICollection;
  2203. if(collection != null)
  2204. {
  2205. // Write object ID (hash of the name) into the writer
  2206. writer.Write(SerializerBase.GetStringHashCode(elementName));
  2207. // Remember position where object data is started
  2208. long elementStartPosition = writer.Seek(0, SeekOrigin.Current);
  2209. // Enumerate through all objects in collection and serialize them
  2210. foreach (object obj in collection)
  2211. {
  2212. if (obj is DataPoint)
  2213. {
  2214. SerializeDataPoint(obj, GetObjectName(obj), writer);
  2215. continue;
  2216. }
  2217. SerializeObject(obj, objectToSerialize, GetObjectName(obj), writer);
  2218. }
  2219. // If position of the writer did not change - nothing was written
  2220. if(writer.Seek(0, SeekOrigin.Current) == elementStartPosition)
  2221. {
  2222. // Remove object ID from the stream
  2223. writer.Seek(-2, SeekOrigin.Current);
  2224. writer.Write((short)0);
  2225. writer.Seek(-2, SeekOrigin.Current);
  2226. }
  2227. else
  2228. {
  2229. // Write the end objectTag
  2230. writer.Write((short)0);
  2231. }
  2232. }
  2233. }
  2234. /// <summary>
  2235. /// Serialize specified object into the binary writer.
  2236. /// Method is called recursively to serialize child objects.
  2237. /// </summary>
  2238. /// <param name="objectToSerialize">Object to be serialized.</param>
  2239. /// <param name="parent">Parent of the serialized object.</param>
  2240. /// <param name="elementName">Object element name.</param>
  2241. /// <param name="writer">Binary writer.</param>
  2242. virtual internal void SerializeProperty(object objectToSerialize, object parent, string elementName, BinaryWriter writer)
  2243. {
  2244. // Check input parameters
  2245. if(objectToSerialize == null || parent == null)
  2246. {
  2247. return;
  2248. }
  2249. // Check if property has non-default value
  2250. PropertyDescriptor pd = TypeDescriptor.GetProperties(parent)[elementName];
  2251. if(pd != null)
  2252. {
  2253. DefaultValueAttribute defValueAttribute = (DefaultValueAttribute)pd.Attributes[typeof(DefaultValueAttribute)];
  2254. if(defValueAttribute != null)
  2255. {
  2256. if(objectToSerialize.Equals(defValueAttribute.Value))
  2257. {
  2258. // Do not serialize properties with default values
  2259. return;
  2260. }
  2261. }
  2262. else
  2263. {
  2264. // Check if property has "ShouldSerialize" method
  2265. MethodInfo mi = parent.GetType().GetMethod("ShouldSerialize" + elementName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public );
  2266. if(mi != null)
  2267. {
  2268. object result = mi.Invoke(parent, null);
  2269. if(result is bool && ((bool)result) == false)
  2270. {
  2271. // Do not serialize properties with default values
  2272. return;
  2273. }
  2274. }
  2275. }
  2276. // Check XmlFormatSerializerStyle attribute
  2277. SerializationVisibilityAttribute styleAttribute = (SerializationVisibilityAttribute)pd.Attributes[typeof(SerializationVisibilityAttribute)];
  2278. if(styleAttribute != null)
  2279. {
  2280. // Hidden property
  2281. if(styleAttribute.Visibility == SerializationVisibility.Hidden)
  2282. {
  2283. return;
  2284. }
  2285. }
  2286. }
  2287. // Write property
  2288. WritePropertyValue(objectToSerialize, elementName, writer);
  2289. }
  2290. /// <summary>
  2291. /// Converts object value into the string.
  2292. /// </summary>
  2293. /// <param name="obj">Object to convert.</param>
  2294. /// <param name="elementName">Object name.</param>
  2295. /// <param name="writer">Binary writer.</param>
  2296. /// <returns>Object value as strig.</returns>
  2297. [SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily",
  2298. Justification = "Too large of a code change to justify making this change")]
  2299. internal void WritePropertyValue(object obj, string elementName, BinaryWriter writer)
  2300. {
  2301. // Write property ID (hash of the name) into the writer
  2302. writer.Write(SerializerBase.GetStringHashCode(elementName));
  2303. if(obj is bool)
  2304. {
  2305. writer.Write(((bool)obj));
  2306. }
  2307. else if(obj is double)
  2308. {
  2309. writer.Write(((double)obj));
  2310. }
  2311. else if(obj is string)
  2312. {
  2313. writer.Write(((string)obj));
  2314. }
  2315. else if(obj is int)
  2316. {
  2317. writer.Write(((int)obj));
  2318. }
  2319. else if(obj is long)
  2320. {
  2321. writer.Write(((long)obj));
  2322. }
  2323. else if(obj is float)
  2324. {
  2325. writer.Write(((float)obj));
  2326. }
  2327. else if(obj.GetType().IsEnum)
  2328. {
  2329. // NOTE: Using 'ToString' method instead of the 'Enum.GetName' fixes
  2330. // an issue (#4314 & #4424) with flagged enumerations when there are
  2331. // more then 1 values set.
  2332. string enumValue = obj.ToString();
  2333. writer.Write(enumValue);
  2334. }
  2335. else if(obj is byte)
  2336. {
  2337. // Write as long
  2338. writer.Write((byte)obj);
  2339. }
  2340. else if(obj is Font)
  2341. {
  2342. // Write as string
  2343. writer.Write(SerializerBase.FontToString((Font)obj));
  2344. }
  2345. else if(obj is Color)
  2346. {
  2347. // Write as int
  2348. writer.Write(((Color)obj).ToArgb());
  2349. }
  2350. else if(obj is DateTime)
  2351. {
  2352. // Write as long
  2353. writer.Write(((DateTime)obj).Ticks);
  2354. }
  2355. else if(obj is Size)
  2356. {
  2357. // Write as two integers
  2358. writer.Write(((Size)obj).Width);
  2359. writer.Write(((Size)obj).Height);
  2360. }
  2361. else if(obj is double[])
  2362. {
  2363. double[] arr = (double[])obj;
  2364. // Write the size of the array (int)
  2365. writer.Write(arr.Length);
  2366. // Write each element of the array
  2367. foreach(double d in arr)
  2368. {
  2369. writer.Write(d);
  2370. }
  2371. }
  2372. else if(obj is Color[])
  2373. {
  2374. Color[] arr = (Color[])obj;
  2375. // Write the size of the array (int)
  2376. writer.Write(arr.Length);
  2377. // Write each element of the array
  2378. foreach(Color color in arr)
  2379. {
  2380. writer.Write(color.ToArgb());
  2381. }
  2382. }
  2383. else if(obj is System.Drawing.Image)
  2384. {
  2385. // Save image into the memory stream
  2386. MemoryStream imageStream = new MemoryStream();
  2387. ((System.Drawing.Image)obj).Save(imageStream, ((System.Drawing.Image)obj).RawFormat);
  2388. // Write the size of the data
  2389. int imageSize = (int)imageStream.Seek(0, SeekOrigin.End);
  2390. imageStream.Seek(0, SeekOrigin.Begin);
  2391. writer.Write(imageSize);
  2392. // Write the data
  2393. writer.Write(imageStream.ToArray());
  2394. imageStream.Close();
  2395. }
  2396. else if(obj is Margins)
  2397. {
  2398. // Write as 4 integers
  2399. writer.Write(((Margins)obj).Top);
  2400. writer.Write(((Margins)obj).Bottom);
  2401. writer.Write(((Margins)obj).Left);
  2402. writer.Write(((Margins)obj).Right);
  2403. }
  2404. else
  2405. {
  2406. throw (new InvalidOperationException(SR.ExceptionChartSerializerBinaryTypeUnsupported(obj.GetType().ToString())));
  2407. }
  2408. }
  2409. /// <summary>
  2410. /// Checks if all properties will have a unique ID.
  2411. /// Property ID is a hash of it's name.
  2412. /// !!!USED IN DEBUG BUILD ONLY!!!
  2413. /// </summary>
  2414. /// <param name="propNames">Array of properties names.</param>
  2415. internal void CheckPropertiesID(ArrayList propNames)
  2416. {
  2417. #if DEBUG
  2418. if(propNames != null)
  2419. {
  2420. // Loop through all properties and check the hash values
  2421. foreach(string name1 in propNames)
  2422. {
  2423. foreach(string name2 in propNames)
  2424. {
  2425. if(name1 != name2)
  2426. {
  2427. if( SerializerBase.GetStringHashCode(name1) == SerializerBase.GetStringHashCode(name2) )
  2428. {
  2429. throw (new InvalidOperationException(SR.ExceptionChartSerializerBinaryHashCodeDuplicate(name1,name2)));
  2430. }
  2431. }
  2432. }
  2433. }
  2434. }
  2435. #endif
  2436. }
  2437. #endregion
  2438. #region Deserialization methods
  2439. /// <summary>
  2440. /// Deserialize specified object from the source using binary format.
  2441. /// </summary>
  2442. /// <param name="objectToDeserialize">Object to be deserialized.</param>
  2443. /// <param name="source">Deserialization source.</param>
  2444. internal override void Deserialize(object objectToDeserialize, object source)
  2445. {
  2446. // Check input parameters
  2447. if (objectToDeserialize == null)
  2448. {
  2449. throw (new ArgumentNullException("objectToDeserialize"));
  2450. }
  2451. if (source == null)
  2452. {
  2453. throw (new ArgumentNullException("source"));
  2454. }
  2455. string sourceStr = source as string;
  2456. if (sourceStr != null)
  2457. {
  2458. Deserialize(objectToDeserialize, sourceStr);
  2459. return;
  2460. }
  2461. Stream stream = source as Stream;
  2462. if (stream != null)
  2463. {
  2464. Deserialize(objectToDeserialize, stream);
  2465. return;
  2466. }
  2467. BinaryWriter binaryWriter = source as BinaryWriter;
  2468. if (binaryWriter != null)
  2469. {
  2470. Deserialize(objectToDeserialize, binaryWriter);
  2471. return;
  2472. }
  2473. throw (new ArgumentException(SR.ExceptionChartSerializerSourceObjectInvalid, "source"));
  2474. }
  2475. /// <summary>
  2476. /// Deserialize object from the file using binary format.
  2477. /// </summary>
  2478. /// <param name="objectToDeserialize">Object to be deserialized.</param>
  2479. /// <param name="fileName">File name to read the data from.</param>
  2480. public void Deserialize(object objectToDeserialize, string fileName)
  2481. {
  2482. FileStream stream = new FileStream(fileName, FileMode.Open);
  2483. Deserialize(objectToDeserialize, new BinaryReader(stream));
  2484. stream.Close();
  2485. }
  2486. /// <summary>
  2487. /// Deserialize object from the stream using binary format.
  2488. /// </summary>
  2489. /// <param name="objectToDeserialize">Object to be deserialized.</param>
  2490. /// <param name="stream">Stream to read the data from.</param>
  2491. public void Deserialize(object objectToDeserialize, Stream stream)
  2492. {
  2493. Deserialize(objectToDeserialize, new BinaryReader(stream));
  2494. }
  2495. /// <summary>
  2496. /// Deserialize object from different types of readers using binary format.
  2497. /// </summary>
  2498. /// <param name="objectToDeserialize">Object to be deserialized.</param>
  2499. /// <param name="reader">Binary reader.</param>
  2500. public void Deserialize(object objectToDeserialize, BinaryReader reader)
  2501. {
  2502. // Check input parameters
  2503. if(objectToDeserialize == null)
  2504. {
  2505. throw(new ArgumentNullException("objectToDeserialize"));
  2506. }
  2507. if(reader == null)
  2508. {
  2509. throw(new ArgumentNullException("reader"));
  2510. }
  2511. // Binary deserializer do not support IsUnknownAttributeIgnored property
  2512. if(base.IsUnknownAttributeIgnored)
  2513. {
  2514. throw (new InvalidOperationException(SR.ExceptionChartSerializerBinaryIgnoreUnknownAttributesUnsupported));
  2515. }
  2516. // Read 15 characters of file header
  2517. char[] header = reader.ReadChars(15);
  2518. if(header[0] != 'D' || header[1] != 'C' || header[2] != 'B' || header[3] != 'F')
  2519. {
  2520. throw (new InvalidOperationException(SR.ExceptionChartSerializerBinaryFromatInvalid));
  2521. }
  2522. // Get ID of the root object
  2523. this.ReadHashID(reader);
  2524. // Reset properties of the root object
  2525. if(IsResetWhenLoading)
  2526. {
  2527. ResetObjectProperties(objectToDeserialize);
  2528. }
  2529. // Deserialize object
  2530. DeserializeObject(objectToDeserialize, null, GetObjectName(objectToDeserialize), reader, false);
  2531. }
  2532. /// <summary>
  2533. /// Deserialize object from the binary format.
  2534. /// Method is called recursively to deserialize child objects.
  2535. /// </summary>
  2536. /// <param name="objectToDeserialize">Object to be deserialized.</param>
  2537. /// <param name="parent">Parent of the deserialized object.</param>
  2538. /// <param name="elementName">Object element name.</param>
  2539. /// <param name="reader">Binary reader object.</param>
  2540. /// <param name="skipElement">if set to <c>true</c> the element will not be set.</param>
  2541. /// <returns>Number of properties set.</returns>
  2542. virtual protected int DeserializeObject(object objectToDeserialize, object parent, string elementName, BinaryReader reader, bool skipElement)
  2543. {
  2544. int setPropertiesNumber = 0;
  2545. // Check input parameters
  2546. if(objectToDeserialize == null)
  2547. {
  2548. return setPropertiesNumber;
  2549. }
  2550. // Special handling for the collections
  2551. Type[] assemblyTypes = null;
  2552. int listItemIndex = 0;
  2553. IList list = objectToDeserialize as IList;
  2554. if(list != null)
  2555. {
  2556. // Loop through all list items
  2557. Int16 typeHash = 0;
  2558. PropertyInfo listItemPI = objectToDeserialize.GetType().GetProperty("Item", new Type[] { typeof(int) });
  2559. while ((typeHash = this.ReadHashID(reader)) != 0)
  2560. {
  2561. // Get collection item type from hashed type name
  2562. string typeName = String.Empty;
  2563. if(listItemPI != null)
  2564. {
  2565. if ((SerializerBase.GetStringHashCode(listItemPI.PropertyType.Name)) == typeHash)
  2566. {
  2567. typeName = listItemPI.PropertyType.Name;
  2568. }
  2569. else
  2570. {
  2571. Assembly assembly = listItemPI.PropertyType.Assembly;
  2572. if (assembly != null)
  2573. {
  2574. // Find all classes derived from this type
  2575. if (assemblyTypes == null)
  2576. {
  2577. assemblyTypes = assembly.GetExportedTypes();
  2578. }
  2579. foreach (Type type in assemblyTypes)
  2580. {
  2581. if (type.IsSubclassOf(listItemPI.PropertyType))
  2582. {
  2583. if ((SerializerBase.GetStringHashCode(type.Name)) == typeHash)
  2584. {
  2585. typeName = type.Name;
  2586. break;
  2587. }
  2588. }
  2589. }
  2590. }
  2591. }
  2592. }
  2593. // Create new item object
  2594. string itemName = null;
  2595. bool reusedObject = false;
  2596. object listItem = GetListNewItem(list, typeName, ref itemName, ref reusedObject);
  2597. // Deserialize list item object
  2598. int itemSetProperties = DeserializeObject(listItem, objectToDeserialize, "", reader, skipElement);
  2599. // Add item object into the list
  2600. if (!skipElement && (itemSetProperties > 0 || reusedObject))
  2601. {
  2602. list.Insert(listItemIndex++, listItem);
  2603. }
  2604. // TD: here was removed a code which doesn't work but cause heavy workload: GetListNewItem removes the reusedObject from the list.
  2605. // Add properties set for collection item
  2606. setPropertiesNumber += itemSetProperties;
  2607. }
  2608. return setPropertiesNumber;
  2609. }
  2610. // Get list of object's properties
  2611. PropertyInfo[] properties = objectToDeserialize.GetType().GetProperties();
  2612. if(properties == null)
  2613. {
  2614. return setPropertiesNumber;
  2615. }
  2616. // Get property information by reading the ID
  2617. PropertyInfo pi = null;
  2618. while ( (pi = ReadPropertyInfo(objectToDeserialize, parent, properties, reader)) != null)
  2619. {
  2620. // Read simple properties
  2621. if(ShouldSerializeAsAttribute(pi, objectToDeserialize))
  2622. {
  2623. if(SetPropertyValue(objectToDeserialize, pi, reader, skipElement))
  2624. {
  2625. ++setPropertiesNumber;
  2626. }
  2627. }
  2628. else
  2629. {
  2630. // Get property descriptor
  2631. PropertyDescriptor pd = TypeDescriptor.GetProperties(objectToDeserialize)[pi.Name];
  2632. if(pd != null)
  2633. {
  2634. object innerObject = pd.GetValue(objectToDeserialize);
  2635. // Deserialize inner item object
  2636. setPropertiesNumber += DeserializeObject(innerObject, objectToDeserialize, pi.Name, reader, !IsSerializableContent(pi.Name, objectToDeserialize));
  2637. }
  2638. else if(!IsUnknownAttributeIgnored)
  2639. {
  2640. throw(new InvalidOperationException(SR.ExceptionChartSerializerPropertyNameUnknown( pi.Name,objectToDeserialize.GetType().ToString())));
  2641. }
  2642. }
  2643. }
  2644. return setPropertiesNumber;
  2645. }
  2646. /// <summary>
  2647. /// Reads and sets a property of an object.
  2648. /// </summary>
  2649. /// <param name="obj">Object to set.</param>
  2650. /// <param name="pi">Property information.</param>
  2651. /// <param name="reader">Binary reader.</param>
  2652. /// <param name="skipElement">if set to <c>true</c> the property will not be set.</param>
  2653. /// <returns>True if property was set.</returns>
  2654. private bool SetPropertyValue(object obj, PropertyInfo pi, BinaryReader reader, bool skipElement)
  2655. {
  2656. if(pi != null)
  2657. {
  2658. object objValue = null;
  2659. if(pi.PropertyType == typeof(bool))
  2660. {
  2661. objValue = reader.ReadBoolean();
  2662. }
  2663. else if(pi.PropertyType == typeof(double))
  2664. {
  2665. objValue = reader.ReadDouble();
  2666. }
  2667. else if(pi.PropertyType == typeof(string))
  2668. {
  2669. objValue = reader.ReadString();
  2670. }
  2671. else if(pi.PropertyType == typeof(int))
  2672. {
  2673. objValue = reader.ReadInt32();
  2674. }
  2675. else if(pi.PropertyType == typeof(long))
  2676. {
  2677. objValue = reader.ReadInt64();
  2678. }
  2679. else if(pi.PropertyType == typeof(float))
  2680. {
  2681. objValue = reader.ReadSingle();
  2682. }
  2683. else if(pi.PropertyType.IsEnum)
  2684. {
  2685. // Read as string
  2686. objValue = Enum.Parse(pi.PropertyType, reader.ReadString());
  2687. }
  2688. else if(pi.PropertyType == typeof(byte))
  2689. {
  2690. objValue = reader.ReadByte();
  2691. }
  2692. else if(pi.PropertyType == typeof(Font))
  2693. {
  2694. // Read as string
  2695. objValue = SerializerBase.FontFromString(reader.ReadString());
  2696. }
  2697. else if(pi.PropertyType == typeof(Color))
  2698. {
  2699. // Read as int
  2700. objValue = Color.FromArgb(reader.ReadInt32());
  2701. }
  2702. else if(pi.PropertyType == typeof(DateTime))
  2703. {
  2704. // Read as long
  2705. objValue = new DateTime(reader.ReadInt64());
  2706. }
  2707. else if(pi.PropertyType == typeof(Size))
  2708. {
  2709. // Read as two integers
  2710. objValue = new Size(reader.ReadInt32(), reader.ReadInt32());
  2711. }
  2712. else if(pi.PropertyType == typeof(Margins) )
  2713. {
  2714. // Read as 4 integers
  2715. objValue = new Margins(
  2716. reader.ReadInt32(),
  2717. reader.ReadInt32(),
  2718. reader.ReadInt32(),
  2719. reader.ReadInt32());
  2720. }
  2721. else if(pi.PropertyType == typeof(double[]))
  2722. {
  2723. // Allocate array
  2724. double[] array = new double[reader.ReadInt32()];
  2725. // Read each element of the array
  2726. for(int arrayIndex = 0; arrayIndex < array.Length; arrayIndex++)
  2727. {
  2728. array[arrayIndex] = reader.ReadDouble();
  2729. }
  2730. objValue = array;
  2731. }
  2732. else if(pi.PropertyType == typeof(Color[]))
  2733. {
  2734. // Allocate array
  2735. Color[] array = new Color[reader.ReadInt32()];
  2736. // Read each element of the array
  2737. for(int arrayIndex = 0; arrayIndex < array.Length; arrayIndex++)
  2738. {
  2739. array[arrayIndex] = Color.FromArgb(reader.ReadInt32());
  2740. }
  2741. objValue = array;
  2742. }
  2743. else if(pi.PropertyType == typeof(System.Drawing.Image))
  2744. {
  2745. // Get image data size
  2746. int imageSize = reader.ReadInt32();
  2747. // Create image stream
  2748. MemoryStream imageStream = new MemoryStream(imageSize + 10);
  2749. // Copy image data into separate stream
  2750. imageStream.Write(reader.ReadBytes(imageSize), 0, imageSize);
  2751. // Create image object
  2752. objValue = new Bitmap(System.Drawing.Image.FromStream(imageStream)); // !!! .Net bug when image source stream is closed - can create brush using the image
  2753. // Close image stream
  2754. imageStream.Close();
  2755. }
  2756. else
  2757. {
  2758. throw(new InvalidOperationException(SR.ExceptionChartSerializerBinaryTypeUnsupported( obj.GetType().ToString() )));
  2759. }
  2760. // Check if this property is serializable content
  2761. if (!skipElement && IsSerializableContent(pi.Name, obj))
  2762. {
  2763. // Set object value
  2764. pi.SetValue(obj, objValue, null);
  2765. return true;
  2766. }
  2767. }
  2768. return false;
  2769. }
  2770. /// <summary>
  2771. /// Reads property ID and return property information
  2772. /// </summary>
  2773. /// <param name="objectToDeserialize">Object to be deserialized.</param>
  2774. /// <param name="parent">Parent of the deserialized object.</param>
  2775. /// <param name="properties">List of properties information.</param>
  2776. /// <param name="reader">Binary reader.</param>
  2777. /// <returns>Property information.</returns>
  2778. private PropertyInfo ReadPropertyInfo(object objectToDeserialize, object parent, PropertyInfo[] properties, BinaryReader reader)
  2779. {
  2780. // Read property ID
  2781. short propertyID = this.ReadHashID(reader);
  2782. // End objectTag reached
  2783. if(propertyID == 0)
  2784. {
  2785. return null;
  2786. }
  2787. // Loop through all properties and check properties IDs (hash code of name)
  2788. foreach(PropertyInfo pi in properties)
  2789. {
  2790. // Skip inherited properties from the root object
  2791. if(IsChartBaseProperty(objectToDeserialize, parent, pi))
  2792. {
  2793. continue;
  2794. }
  2795. // Check collection
  2796. if (pi.CanRead && pi.PropertyType.GetInterface("ICollection", true) != null)
  2797. {
  2798. if((SerializerBase.GetStringHashCode(pi.Name)) == propertyID)
  2799. {
  2800. return pi;
  2801. }
  2802. }
  2803. // Check public properties with Get and Set methods
  2804. else if(pi.CanRead && pi.CanWrite)
  2805. {
  2806. // Skip indexes
  2807. if(pi.Name == "Item")
  2808. {
  2809. continue;
  2810. }
  2811. if((SerializerBase.GetStringHashCode(pi.Name)) == propertyID)
  2812. {
  2813. return pi;
  2814. }
  2815. }
  2816. }
  2817. // Property was not found
  2818. throw (new InvalidOperationException(SR.ExceptionChartSerializerPropertyNotFound));
  2819. }
  2820. #endregion
  2821. }
  2822. }