XmlBaseWriter.cs 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648
  1. //------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.Xml
  5. {
  6. using System.Globalization;
  7. using System.IO;
  8. using System.Runtime;
  9. using System.Runtime.Serialization;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. abstract class XmlBaseWriter : XmlDictionaryWriter, IFragmentCapableXmlDictionaryWriter
  13. {
  14. XmlNodeWriter writer;
  15. NamespaceManager nsMgr;
  16. Element[] elements;
  17. int depth;
  18. string attributeLocalName;
  19. string attributeValue;
  20. bool isXmlAttribute;
  21. bool isXmlnsAttribute;
  22. WriteState writeState;
  23. DocumentState documentState;
  24. byte[] trailBytes;
  25. int trailByteCount;
  26. XmlStreamNodeWriter nodeWriter;
  27. XmlSigningNodeWriter signingWriter;
  28. XmlUTF8NodeWriter textFragmentWriter;
  29. XmlNodeWriter oldWriter;
  30. Stream oldStream;
  31. int oldNamespaceBoundary;
  32. bool inList;
  33. const string xmlnsNamespace = "http://www.w3.org/2000/xmlns/";
  34. const string xmlNamespace = "http://www.w3.org/XML/1998/namespace";
  35. static BinHexEncoding binhexEncoding;
  36. static string[] prefixes = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
  37. XmlBaseWriterNodeWriterAsyncHelper nodeWriterAsyncHelper;
  38. protected XmlBaseWriter()
  39. {
  40. this.nsMgr = new NamespaceManager();
  41. this.writeState = WriteState.Start;
  42. this.documentState = DocumentState.None;
  43. }
  44. protected void SetOutput(XmlStreamNodeWriter writer)
  45. {
  46. this.inList = false;
  47. this.writer = writer;
  48. this.nodeWriter = writer;
  49. this.writeState = WriteState.Start;
  50. this.documentState = DocumentState.None;
  51. this.nsMgr.Clear();
  52. if (this.depth != 0)
  53. {
  54. this.elements = null;
  55. this.depth = 0;
  56. }
  57. this.attributeLocalName = null;
  58. this.attributeValue = null;
  59. this.oldWriter = null;
  60. this.oldStream = null;
  61. }
  62. public override void Flush()
  63. {
  64. if (IsClosed)
  65. ThrowClosed();
  66. writer.Flush();
  67. }
  68. public override void Close()
  69. {
  70. if (IsClosed)
  71. return;
  72. try
  73. {
  74. FinishDocument();
  75. AutoComplete(WriteState.Closed);
  76. writer.Flush();
  77. }
  78. finally
  79. {
  80. nsMgr.Close();
  81. if (depth != 0)
  82. {
  83. elements = null;
  84. depth = 0;
  85. }
  86. attributeValue = null;
  87. attributeLocalName = null;
  88. nodeWriter.Close();
  89. if (signingWriter != null)
  90. {
  91. signingWriter.Close();
  92. }
  93. if (textFragmentWriter != null)
  94. {
  95. textFragmentWriter.Close();
  96. }
  97. oldWriter = null;
  98. oldStream = null;
  99. }
  100. }
  101. protected bool IsClosed
  102. {
  103. get { return writeState == WriteState.Closed; }
  104. }
  105. protected void ThrowClosed()
  106. {
  107. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlWriterClosed)));
  108. }
  109. static BinHexEncoding BinHexEncoding
  110. {
  111. get
  112. {
  113. if (binhexEncoding == null)
  114. binhexEncoding = new BinHexEncoding();
  115. return binhexEncoding;
  116. }
  117. }
  118. public override string XmlLang
  119. {
  120. get
  121. {
  122. return nsMgr.XmlLang;
  123. }
  124. }
  125. public override XmlSpace XmlSpace
  126. {
  127. get
  128. {
  129. return nsMgr.XmlSpace;
  130. }
  131. }
  132. public override WriteState WriteState
  133. {
  134. get
  135. {
  136. return writeState;
  137. }
  138. }
  139. public override void WriteXmlnsAttribute(string prefix, string ns)
  140. {
  141. if (IsClosed)
  142. ThrowClosed();
  143. if (ns == null)
  144. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ns");
  145. if (writeState != WriteState.Element)
  146. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlInvalidWriteState, "WriteXmlnsAttribute", WriteState.ToString())));
  147. if (prefix == null)
  148. {
  149. prefix = nsMgr.LookupPrefix(ns);
  150. if (prefix == null)
  151. {
  152. GeneratePrefix(ns, null);
  153. }
  154. }
  155. else
  156. {
  157. nsMgr.AddNamespaceIfNotDeclared(prefix, ns, null);
  158. }
  159. }
  160. public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns)
  161. {
  162. if (IsClosed)
  163. ThrowClosed();
  164. if (ns == null)
  165. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ns");
  166. if (writeState != WriteState.Element)
  167. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlInvalidWriteState, "WriteXmlnsAttribute", WriteState.ToString())));
  168. if (prefix == null)
  169. {
  170. prefix = nsMgr.LookupPrefix(ns.Value);
  171. if (prefix == null)
  172. {
  173. GeneratePrefix(ns.Value, ns);
  174. }
  175. }
  176. else
  177. {
  178. nsMgr.AddNamespaceIfNotDeclared(prefix, ns.Value, ns);
  179. }
  180. }
  181. void StartAttribute(ref string prefix, string localName, string ns, XmlDictionaryString xNs)
  182. {
  183. if (IsClosed)
  184. ThrowClosed();
  185. if (writeState == WriteState.Attribute)
  186. WriteEndAttribute();
  187. if (localName == null || (localName.Length == 0 && prefix != "xmlns"))
  188. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("localName"));
  189. if (writeState != WriteState.Element)
  190. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlInvalidWriteState, "WriteStartAttribute", WriteState.ToString())));
  191. if (prefix == null)
  192. {
  193. if (ns == xmlnsNamespace && localName != "xmlns")
  194. prefix = "xmlns";
  195. else if (ns == xmlNamespace)
  196. prefix = "xml";
  197. else
  198. prefix = string.Empty;
  199. }
  200. // Normalize a (prefix,localName) of (null, "xmlns") to ("xmlns", string.Empty).
  201. if (prefix.Length == 0 && localName == "xmlns")
  202. {
  203. prefix = "xmlns";
  204. localName = string.Empty;
  205. }
  206. isXmlnsAttribute = false;
  207. isXmlAttribute = false;
  208. if (prefix == "xml")
  209. {
  210. if (ns != null && ns != xmlNamespace)
  211. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.XmlPrefixBoundToNamespace, "xml", xmlNamespace, ns), "ns"));
  212. isXmlAttribute = true;
  213. attributeValue = string.Empty;
  214. attributeLocalName = localName;
  215. }
  216. else if (prefix == "xmlns")
  217. {
  218. if (ns != null && ns != xmlnsNamespace)
  219. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.XmlPrefixBoundToNamespace, "xmlns", xmlnsNamespace, ns), "ns"));
  220. isXmlnsAttribute = true;
  221. attributeValue = string.Empty;
  222. attributeLocalName = localName;
  223. }
  224. else if (ns == null)
  225. {
  226. // A null namespace means the namespace of the given prefix.
  227. if (prefix.Length == 0)
  228. {
  229. // An empty prefix on an attribute means no namespace (not the default namespace)
  230. ns = string.Empty;
  231. }
  232. else
  233. {
  234. ns = nsMgr.LookupNamespace(prefix);
  235. if (ns == null)
  236. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.XmlUndefinedPrefix, prefix), "prefix"));
  237. }
  238. }
  239. else if (ns.Length == 0)
  240. {
  241. // An empty namespace means no namespace; prefix must be empty
  242. if (prefix.Length != 0)
  243. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.XmlEmptyNamespaceRequiresNullPrefix), "prefix"));
  244. }
  245. else if (prefix.Length == 0)
  246. {
  247. // No prefix specified - try to find a prefix corresponding to the given namespace
  248. prefix = nsMgr.LookupAttributePrefix(ns);
  249. // If we didn't find anything with the right namespace, generate one.
  250. if (prefix == null)
  251. {
  252. // Watch for special values
  253. if (ns.Length == xmlnsNamespace.Length && ns == xmlnsNamespace)
  254. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.XmlSpecificBindingNamespace, "xmlns", ns)));
  255. if (ns.Length == xmlNamespace.Length && ns == xmlNamespace)
  256. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.XmlSpecificBindingNamespace, "xml", ns)));
  257. prefix = GeneratePrefix(ns, xNs);
  258. }
  259. }
  260. else
  261. {
  262. nsMgr.AddNamespaceIfNotDeclared(prefix, ns, xNs);
  263. }
  264. writeState = WriteState.Attribute;
  265. }
  266. public override void WriteStartAttribute(string prefix, string localName, string namespaceUri)
  267. {
  268. StartAttribute(ref prefix, localName, namespaceUri, null);
  269. if (!isXmlnsAttribute)
  270. {
  271. writer.WriteStartAttribute(prefix, localName);
  272. }
  273. }
  274. public override void WriteStartAttribute(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
  275. {
  276. StartAttribute(ref prefix, (localName != null ? localName.Value : null), (namespaceUri != null ? namespaceUri.Value : null), namespaceUri);
  277. if (!isXmlnsAttribute)
  278. {
  279. writer.WriteStartAttribute(prefix, localName);
  280. }
  281. }
  282. public override void WriteEndAttribute()
  283. {
  284. if (IsClosed)
  285. ThrowClosed();
  286. if (writeState != WriteState.Attribute)
  287. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlInvalidWriteState, "WriteEndAttribute", WriteState.ToString())));
  288. FlushBase64();
  289. try
  290. {
  291. if (isXmlAttribute)
  292. {
  293. if (attributeLocalName == "lang")
  294. {
  295. nsMgr.AddLangAttribute(attributeValue);
  296. }
  297. else if (attributeLocalName == "space")
  298. {
  299. if (attributeValue == "preserve")
  300. {
  301. nsMgr.AddSpaceAttribute(XmlSpace.Preserve);
  302. }
  303. else if (attributeValue == "default")
  304. {
  305. nsMgr.AddSpaceAttribute(XmlSpace.Default);
  306. }
  307. else
  308. {
  309. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.XmlInvalidXmlSpace, attributeValue)));
  310. }
  311. }
  312. else
  313. {
  314. // XmlTextWriter specifically allows for other localNames
  315. }
  316. isXmlAttribute = false;
  317. attributeLocalName = null;
  318. attributeValue = null;
  319. }
  320. if (isXmlnsAttribute)
  321. {
  322. nsMgr.AddNamespaceIfNotDeclared(attributeLocalName, attributeValue, null);
  323. isXmlnsAttribute = false;
  324. attributeLocalName = null;
  325. attributeValue = null;
  326. }
  327. else
  328. {
  329. writer.WriteEndAttribute();
  330. }
  331. }
  332. finally
  333. {
  334. writeState = WriteState.Element;
  335. }
  336. }
  337. public override void WriteComment(string text)
  338. {
  339. if (IsClosed)
  340. ThrowClosed();
  341. if (writeState == WriteState.Attribute)
  342. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlInvalidWriteState, "WriteComment", WriteState.ToString())));
  343. if (text == null)
  344. {
  345. text = string.Empty;
  346. }
  347. else if (text.IndexOf("--", StringComparison.Ordinal) != -1 || (text.Length > 0 && text[text.Length - 1] == '-'))
  348. {
  349. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.XmlInvalidCommentChars), "text"));
  350. }
  351. StartComment();
  352. FlushBase64();
  353. writer.WriteComment(text);
  354. EndComment();
  355. }
  356. public override void WriteFullEndElement()
  357. {
  358. if (IsClosed)
  359. ThrowClosed();
  360. if (writeState == WriteState.Attribute)
  361. WriteEndAttribute();
  362. if (writeState != WriteState.Element && writeState != WriteState.Content)
  363. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlInvalidWriteState, "WriteFullEndElement", WriteState.ToString())));
  364. AutoComplete(WriteState.Content);
  365. WriteEndElement();
  366. }
  367. public override void WriteCData(string text)
  368. {
  369. if (IsClosed)
  370. ThrowClosed();
  371. if (writeState == WriteState.Attribute)
  372. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlInvalidWriteState, "WriteCData", WriteState.ToString())));
  373. if (text == null)
  374. text = string.Empty;
  375. if (text.Length > 0)
  376. {
  377. StartContent();
  378. FlushBase64();
  379. writer.WriteCData(text);
  380. EndContent();
  381. }
  382. }
  383. public override void WriteDocType(string name, string pubid, string sysid, string subset)
  384. {
  385. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.XmlMethodNotSupported, "WriteDocType")));
  386. }
  387. void StartElement(ref string prefix, string localName, string ns, XmlDictionaryString xNs)
  388. {
  389. if (IsClosed)
  390. ThrowClosed();
  391. if (this.documentState == DocumentState.Epilog)
  392. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlOnlyOneRoot)));
  393. if (localName == null)
  394. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("localName"));
  395. if (localName.Length == 0)
  396. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.InvalidLocalNameEmpty), "localName"));
  397. if (writeState == WriteState.Attribute)
  398. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlInvalidWriteState, "WriteStartElement", WriteState.ToString())));
  399. FlushBase64();
  400. AutoComplete(WriteState.Element);
  401. Element element = EnterScope();
  402. if (ns == null)
  403. {
  404. if (prefix == null)
  405. prefix = string.Empty;
  406. ns = nsMgr.LookupNamespace(prefix);
  407. if (ns == null)
  408. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.XmlUndefinedPrefix, prefix), "prefix"));
  409. }
  410. else if (prefix == null)
  411. {
  412. prefix = nsMgr.LookupPrefix(ns);
  413. if (prefix == null)
  414. {
  415. prefix = string.Empty;
  416. nsMgr.AddNamespace(string.Empty, ns, xNs);
  417. }
  418. }
  419. else
  420. {
  421. nsMgr.AddNamespaceIfNotDeclared(prefix, ns, xNs);
  422. }
  423. element.Prefix = prefix;
  424. element.LocalName = localName;
  425. }
  426. public override void WriteStartElement(string prefix, string localName, string namespaceUri)
  427. {
  428. StartElement(ref prefix, localName, namespaceUri, null);
  429. writer.WriteStartElement(prefix, localName);
  430. }
  431. public override void WriteStartElement(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
  432. {
  433. StartElement(ref prefix, (localName != null ? localName.Value : null), (namespaceUri != null ? namespaceUri.Value : null), namespaceUri);
  434. writer.WriteStartElement(prefix, localName);
  435. }
  436. public override void WriteEndElement()
  437. {
  438. if (IsClosed)
  439. ThrowClosed();
  440. if (depth == 0)
  441. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlInvalidDepth, "WriteEndElement", depth.ToString(CultureInfo.InvariantCulture))));
  442. if (writeState == WriteState.Attribute)
  443. WriteEndAttribute();
  444. FlushBase64();
  445. if (writeState == WriteState.Element)
  446. {
  447. nsMgr.DeclareNamespaces(writer);
  448. writer.WriteEndStartElement(true);
  449. }
  450. else
  451. {
  452. Element element = elements[depth];
  453. writer.WriteEndElement(element.Prefix, element.LocalName);
  454. }
  455. ExitScope();
  456. writeState = WriteState.Content;
  457. }
  458. Element EnterScope()
  459. {
  460. nsMgr.EnterScope();
  461. depth++;
  462. if (elements == null)
  463. {
  464. elements = new Element[4];
  465. }
  466. else if (elements.Length == depth)
  467. {
  468. Element[] newElementNodes = new Element[depth * 2];
  469. Array.Copy(elements, newElementNodes, depth);
  470. elements = newElementNodes;
  471. }
  472. Element element = elements[depth];
  473. if (element == null)
  474. {
  475. element = new Element();
  476. elements[depth] = element;
  477. }
  478. return element;
  479. }
  480. void ExitScope()
  481. {
  482. elements[depth].Clear();
  483. depth--;
  484. if (depth == 0 && documentState == DocumentState.Document)
  485. this.documentState = DocumentState.Epilog;
  486. nsMgr.ExitScope();
  487. }
  488. protected void FlushElement()
  489. {
  490. if (this.writeState == WriteState.Element)
  491. {
  492. AutoComplete(WriteState.Content);
  493. }
  494. }
  495. protected void StartComment()
  496. {
  497. FlushElement();
  498. }
  499. protected void EndComment()
  500. {
  501. }
  502. protected void StartContent()
  503. {
  504. FlushElement();
  505. if (depth == 0)
  506. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlIllegalOutsideRoot)));
  507. }
  508. protected void StartContent(char ch)
  509. {
  510. FlushElement();
  511. if (depth == 0)
  512. VerifyWhitespace(ch);
  513. }
  514. protected void StartContent(string s)
  515. {
  516. FlushElement();
  517. if (depth == 0)
  518. VerifyWhitespace(s);
  519. }
  520. protected void StartContent(char[] chars, int offset, int count)
  521. {
  522. FlushElement();
  523. if (depth == 0)
  524. VerifyWhitespace(chars, offset, count);
  525. }
  526. void VerifyWhitespace(char ch)
  527. {
  528. if (!IsWhitespace(ch))
  529. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlIllegalOutsideRoot)));
  530. }
  531. void VerifyWhitespace(string s)
  532. {
  533. for (int i = 0; i < s.Length; i++)
  534. if (!IsWhitespace(s[i]))
  535. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlIllegalOutsideRoot)));
  536. }
  537. void VerifyWhitespace(char[] chars, int offset, int count)
  538. {
  539. for (int i = 0; i < count; i++)
  540. if (!IsWhitespace(chars[offset + i]))
  541. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlIllegalOutsideRoot)));
  542. }
  543. bool IsWhitespace(char ch)
  544. {
  545. return (ch == ' ' || ch == '\n' || ch == '\r' || ch == 't');
  546. }
  547. protected void EndContent()
  548. {
  549. }
  550. void AutoComplete(WriteState writeState)
  551. {
  552. if (this.writeState == WriteState.Element)
  553. {
  554. EndStartElement();
  555. }
  556. this.writeState = writeState;
  557. }
  558. void EndStartElement()
  559. {
  560. nsMgr.DeclareNamespaces(writer);
  561. writer.WriteEndStartElement(false);
  562. }
  563. public override string LookupPrefix(string ns)
  564. {
  565. if (ns == null)
  566. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("ns"));
  567. if (IsClosed)
  568. ThrowClosed();
  569. return nsMgr.LookupPrefix(ns);
  570. }
  571. internal string LookupNamespace(string prefix)
  572. {
  573. if (prefix == null)
  574. return null;
  575. return nsMgr.LookupNamespace(prefix);
  576. }
  577. string GetQualifiedNamePrefix(string namespaceUri, XmlDictionaryString xNs)
  578. {
  579. string prefix = nsMgr.LookupPrefix(namespaceUri);
  580. if (prefix == null)
  581. {
  582. if (writeState != WriteState.Attribute)
  583. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.XmlNamespaceNotFound, namespaceUri), "namespaceUri"));
  584. prefix = GeneratePrefix(namespaceUri, xNs);
  585. }
  586. return prefix;
  587. }
  588. public override void WriteQualifiedName(string localName, string namespaceUri)
  589. {
  590. if (IsClosed)
  591. ThrowClosed();
  592. if (localName == null)
  593. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("localName"));
  594. if (localName.Length == 0)
  595. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.InvalidLocalNameEmpty), "localName"));
  596. if (namespaceUri == null)
  597. namespaceUri = string.Empty;
  598. string prefix = GetQualifiedNamePrefix(namespaceUri, null);
  599. if (prefix.Length != 0)
  600. {
  601. WriteString(prefix);
  602. WriteString(":");
  603. }
  604. WriteString(localName);
  605. }
  606. public override void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
  607. {
  608. if (IsClosed)
  609. ThrowClosed();
  610. if (localName == null)
  611. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("localName"));
  612. if (localName.Value.Length == 0)
  613. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.InvalidLocalNameEmpty), "localName"));
  614. if (namespaceUri == null)
  615. namespaceUri = XmlDictionaryString.Empty;
  616. string prefix = GetQualifiedNamePrefix(namespaceUri.Value, namespaceUri);
  617. FlushBase64();
  618. if (attributeValue != null)
  619. WriteAttributeText(string.Concat(prefix, ":", namespaceUri.Value));
  620. if (!isXmlnsAttribute)
  621. {
  622. StartContent();
  623. writer.WriteQualifiedName(prefix, localName);
  624. EndContent();
  625. }
  626. }
  627. public override void WriteStartDocument()
  628. {
  629. if (IsClosed)
  630. ThrowClosed();
  631. if (writeState != WriteState.Start)
  632. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlInvalidWriteState, "WriteStartDocument", WriteState.ToString())));
  633. writeState = WriteState.Prolog;
  634. documentState = DocumentState.Document;
  635. writer.WriteDeclaration();
  636. }
  637. public override void WriteStartDocument(bool standalone)
  638. {
  639. if (IsClosed)
  640. ThrowClosed();
  641. WriteStartDocument();
  642. }
  643. public override void WriteProcessingInstruction(string name, string text)
  644. {
  645. if (IsClosed)
  646. ThrowClosed();
  647. if (name != "xml")
  648. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.XmlProcessingInstructionNotSupported), "name"));
  649. if (writeState != WriteState.Start)
  650. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlInvalidDeclaration)));
  651. // The only thing the text can legitimately contain is version, encoding, and standalone.
  652. // We only support version 1.0, we can only write whatever encoding we were supplied,
  653. // and we don't support DTDs, so whatever values are supplied in the text argument are irrelevant.
  654. writer.WriteDeclaration();
  655. }
  656. void FinishDocument()
  657. {
  658. if (this.writeState == WriteState.Attribute)
  659. {
  660. WriteEndAttribute();
  661. }
  662. while (this.depth > 0)
  663. {
  664. WriteEndElement();
  665. }
  666. }
  667. public override void WriteEndDocument()
  668. {
  669. if (IsClosed)
  670. ThrowClosed();
  671. if (writeState == WriteState.Start || writeState == WriteState.Prolog)
  672. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlNoRootElement)));
  673. FinishDocument();
  674. writeState = WriteState.Start;
  675. documentState = DocumentState.End;
  676. }
  677. protected int NamespaceBoundary
  678. {
  679. get
  680. {
  681. return nsMgr.NamespaceBoundary;
  682. }
  683. set
  684. {
  685. nsMgr.NamespaceBoundary = value;
  686. }
  687. }
  688. public override void WriteEntityRef(string name)
  689. {
  690. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.XmlMethodNotSupported, "WriteEntityRef")));
  691. }
  692. public override void WriteName(string name)
  693. {
  694. if (IsClosed)
  695. ThrowClosed();
  696. WriteString(name);
  697. }
  698. public override void WriteNmToken(string name)
  699. {
  700. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.XmlMethodNotSupported, "WriteNmToken")));
  701. }
  702. public override void WriteWhitespace(string whitespace)
  703. {
  704. if (IsClosed)
  705. ThrowClosed();
  706. if (whitespace == null)
  707. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("whitespace");
  708. for (int i = 0; i < whitespace.Length; ++i)
  709. {
  710. char c = whitespace[i];
  711. if (c != ' ' &&
  712. c != '\t' &&
  713. c != '\n' &&
  714. c != '\r')
  715. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.XmlOnlyWhitespace), "whitespace"));
  716. }
  717. WriteString(whitespace);
  718. }
  719. public override void WriteString(string value)
  720. {
  721. if (IsClosed)
  722. ThrowClosed();
  723. if (value == null)
  724. value = string.Empty;
  725. if (value.Length > 0 || this.inList)
  726. {
  727. FlushBase64();
  728. if (attributeValue != null)
  729. WriteAttributeText(value);
  730. if (!isXmlnsAttribute)
  731. {
  732. StartContent(value);
  733. writer.WriteEscapedText(value);
  734. EndContent();
  735. }
  736. }
  737. }
  738. public override void WriteString(XmlDictionaryString value)
  739. {
  740. if (IsClosed)
  741. ThrowClosed();
  742. if (value == null)
  743. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
  744. if (value.Value.Length > 0)
  745. {
  746. FlushBase64();
  747. if (attributeValue != null)
  748. WriteAttributeText(value.Value);
  749. if (!isXmlnsAttribute)
  750. {
  751. StartContent(value.Value);
  752. writer.WriteEscapedText(value);
  753. EndContent();
  754. }
  755. }
  756. }
  757. public override void WriteChars(char[] chars, int offset, int count)
  758. {
  759. if (IsClosed)
  760. ThrowClosed();
  761. if (chars == null)
  762. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars"));
  763. // Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does.
  764. if (offset < 0)
  765. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.ValueMustBeNonNegative)));
  766. if (count < 0)
  767. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.ValueMustBeNonNegative)));
  768. if (count > chars.Length - offset)
  769. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.SizeExceedsRemainingBufferSpace, chars.Length - offset)));
  770. if (count > 0)
  771. {
  772. FlushBase64();
  773. if (attributeValue != null)
  774. WriteAttributeText(new string(chars, offset, count));
  775. if (!isXmlnsAttribute)
  776. {
  777. StartContent(chars, offset, count);
  778. writer.WriteEscapedText(chars, offset, count);
  779. EndContent();
  780. }
  781. }
  782. }
  783. public override void WriteRaw(string value)
  784. {
  785. if (IsClosed)
  786. ThrowClosed();
  787. if (value == null)
  788. value = string.Empty;
  789. if (value.Length > 0)
  790. {
  791. FlushBase64();
  792. if (attributeValue != null)
  793. WriteAttributeText(value);
  794. if (!isXmlnsAttribute)
  795. {
  796. StartContent(value);
  797. writer.WriteText(value);
  798. EndContent();
  799. }
  800. }
  801. }
  802. public override void WriteRaw(char[] chars, int offset, int count)
  803. {
  804. if (IsClosed)
  805. ThrowClosed();
  806. if (chars == null)
  807. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars"));
  808. // Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does.
  809. if (offset < 0)
  810. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.ValueMustBeNonNegative)));
  811. if (count < 0)
  812. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.ValueMustBeNonNegative)));
  813. if (count > chars.Length - offset)
  814. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.SizeExceedsRemainingBufferSpace, chars.Length - offset)));
  815. if (count > 0)
  816. {
  817. FlushBase64();
  818. if (attributeValue != null)
  819. WriteAttributeText(new string(chars, offset, count));
  820. if (!isXmlnsAttribute)
  821. {
  822. StartContent(chars, offset, count);
  823. writer.WriteText(chars, offset, count);
  824. EndContent();
  825. }
  826. }
  827. }
  828. public override void WriteCharEntity(char ch)
  829. {
  830. if (IsClosed)
  831. ThrowClosed();
  832. if (ch >= 0xd800 && ch <= 0xdfff)
  833. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.XmlMissingLowSurrogate), "ch"));
  834. if (attributeValue != null)
  835. WriteAttributeText(ch.ToString());
  836. if (!isXmlnsAttribute)
  837. {
  838. StartContent(ch);
  839. FlushBase64();
  840. writer.WriteCharEntity(ch);
  841. EndContent();
  842. }
  843. }
  844. public override void WriteSurrogateCharEntity(char lowChar, char highChar)
  845. {
  846. if (IsClosed)
  847. ThrowClosed();
  848. SurrogateChar ch = new SurrogateChar(lowChar, highChar);
  849. if (attributeValue != null)
  850. {
  851. char[] chars = new char[2] { highChar, lowChar };
  852. WriteAttributeText(new string(chars));
  853. }
  854. if (!isXmlnsAttribute)
  855. {
  856. StartContent();
  857. FlushBase64();
  858. writer.WriteCharEntity(ch.Char);
  859. EndContent();
  860. }
  861. }
  862. public override void WriteValue(object value)
  863. {
  864. if (IsClosed)
  865. ThrowClosed();
  866. if (value == null)
  867. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value"));
  868. else if (value is object[])
  869. {
  870. WriteValue((object[])value);
  871. }
  872. else if (value is Array)
  873. {
  874. WriteValue((Array)value);
  875. }
  876. else if (value is IStreamProvider)
  877. {
  878. WriteValue((IStreamProvider)value);
  879. }
  880. else
  881. {
  882. WritePrimitiveValue(value);
  883. }
  884. }
  885. protected void WritePrimitiveValue(object value)
  886. {
  887. if (IsClosed)
  888. ThrowClosed();
  889. if (value == null)
  890. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value"));
  891. if (value is ulong)
  892. {
  893. WriteValue((ulong)value);
  894. }
  895. else if (value is string)
  896. {
  897. WriteValue((string)value);
  898. }
  899. else if (value is int)
  900. {
  901. WriteValue((int)value);
  902. }
  903. else if (value is long)
  904. {
  905. WriteValue((long)value);
  906. }
  907. else if (value is bool)
  908. {
  909. WriteValue((bool)value);
  910. }
  911. else if (value is double)
  912. {
  913. WriteValue((double)value);
  914. }
  915. else if (value is DateTime)
  916. {
  917. WriteValue((DateTime)value);
  918. }
  919. else if (value is float)
  920. {
  921. WriteValue((float)value);
  922. }
  923. else if (value is decimal)
  924. {
  925. WriteValue((decimal)value);
  926. }
  927. else if (value is XmlDictionaryString)
  928. {
  929. WriteValue((XmlDictionaryString)value);
  930. }
  931. else if (value is UniqueId)
  932. {
  933. WriteValue((UniqueId)value);
  934. }
  935. else if (value is Guid)
  936. {
  937. WriteValue((Guid)value);
  938. }
  939. else if (value is TimeSpan)
  940. {
  941. WriteValue((TimeSpan)value);
  942. }
  943. else if (value.GetType().IsArray)
  944. {
  945. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.XmlNestedArraysNotSupported), "value"));
  946. }
  947. else
  948. {
  949. base.WriteValue(value);
  950. }
  951. }
  952. public override void WriteValue(string value)
  953. {
  954. if (IsClosed)
  955. ThrowClosed();
  956. WriteString(value);
  957. }
  958. public override void WriteValue(int value)
  959. {
  960. if (IsClosed)
  961. ThrowClosed();
  962. FlushBase64();
  963. if (attributeValue != null)
  964. WriteAttributeText(XmlConverter.ToString(value));
  965. if (!isXmlnsAttribute)
  966. {
  967. StartContent();
  968. writer.WriteInt32Text(value);
  969. EndContent();
  970. }
  971. }
  972. public override void WriteValue(long value)
  973. {
  974. if (IsClosed)
  975. ThrowClosed();
  976. FlushBase64();
  977. if (attributeValue != null)
  978. WriteAttributeText(XmlConverter.ToString(value));
  979. if (!isXmlnsAttribute)
  980. {
  981. StartContent();
  982. writer.WriteInt64Text(value);
  983. EndContent();
  984. }
  985. }
  986. void WriteValue(ulong value)
  987. {
  988. if (IsClosed)
  989. ThrowClosed();
  990. FlushBase64();
  991. if (attributeValue != null)
  992. WriteAttributeText(XmlConverter.ToString(value));
  993. if (!isXmlnsAttribute)
  994. {
  995. StartContent();
  996. writer.WriteUInt64Text(value);
  997. EndContent();
  998. }
  999. }
  1000. public override void WriteValue(bool value)
  1001. {
  1002. if (IsClosed)
  1003. ThrowClosed();
  1004. FlushBase64();
  1005. if (attributeValue != null)
  1006. WriteAttributeText(XmlConverter.ToString(value));
  1007. if (!isXmlnsAttribute)
  1008. {
  1009. StartContent();
  1010. writer.WriteBoolText(value);
  1011. EndContent();
  1012. }
  1013. }
  1014. public override void WriteValue(decimal value)
  1015. {
  1016. if (IsClosed)
  1017. ThrowClosed();
  1018. FlushBase64();
  1019. if (attributeValue != null)
  1020. WriteAttributeText(XmlConverter.ToString(value));
  1021. if (!isXmlnsAttribute)
  1022. {
  1023. StartContent();
  1024. writer.WriteDecimalText(value);
  1025. EndContent();
  1026. }
  1027. }
  1028. public override void WriteValue(float value)
  1029. {
  1030. if (IsClosed)
  1031. ThrowClosed();
  1032. FlushBase64();
  1033. if (attributeValue != null)
  1034. WriteAttributeText(XmlConverter.ToString(value));
  1035. if (!isXmlnsAttribute)
  1036. {
  1037. StartContent();
  1038. writer.WriteFloatText(value);
  1039. EndContent();
  1040. }
  1041. }
  1042. public override void WriteValue(double value)
  1043. {
  1044. if (IsClosed)
  1045. ThrowClosed();
  1046. FlushBase64();
  1047. if (attributeValue != null)
  1048. WriteAttributeText(XmlConverter.ToString(value));
  1049. if (!isXmlnsAttribute)
  1050. {
  1051. StartContent();
  1052. writer.WriteDoubleText(value);
  1053. EndContent();
  1054. }
  1055. }
  1056. public override void WriteValue(XmlDictionaryString value)
  1057. {
  1058. WriteString(value);
  1059. }
  1060. public override void WriteValue(DateTime value)
  1061. {
  1062. if (IsClosed)
  1063. ThrowClosed();
  1064. FlushBase64();
  1065. if (attributeValue != null)
  1066. WriteAttributeText(XmlConverter.ToString(value));
  1067. if (!isXmlnsAttribute)
  1068. {
  1069. StartContent();
  1070. writer.WriteDateTimeText(value);
  1071. EndContent();
  1072. }
  1073. }
  1074. public override void WriteValue(UniqueId value)
  1075. {
  1076. if (IsClosed)
  1077. ThrowClosed();
  1078. if (value == null)
  1079. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
  1080. FlushBase64();
  1081. if (attributeValue != null)
  1082. WriteAttributeText(XmlConverter.ToString(value));
  1083. if (!isXmlnsAttribute)
  1084. {
  1085. StartContent();
  1086. writer.WriteUniqueIdText(value);
  1087. EndContent();
  1088. }
  1089. }
  1090. public override void WriteValue(Guid value)
  1091. {
  1092. if (IsClosed)
  1093. ThrowClosed();
  1094. FlushBase64();
  1095. if (attributeValue != null)
  1096. WriteAttributeText(XmlConverter.ToString(value));
  1097. if (!isXmlnsAttribute)
  1098. {
  1099. StartContent();
  1100. writer.WriteGuidText(value);
  1101. EndContent();
  1102. }
  1103. }
  1104. public override void WriteValue(TimeSpan value)
  1105. {
  1106. if (IsClosed)
  1107. ThrowClosed();
  1108. FlushBase64();
  1109. if (attributeValue != null)
  1110. WriteAttributeText(XmlConverter.ToString(value));
  1111. if (!isXmlnsAttribute)
  1112. {
  1113. StartContent();
  1114. writer.WriteTimeSpanText(value);
  1115. EndContent();
  1116. }
  1117. }
  1118. public override void WriteBase64(byte[] buffer, int offset, int count)
  1119. {
  1120. if (IsClosed)
  1121. ThrowClosed();
  1122. EnsureBufferBounds(buffer, offset, count);
  1123. if (count > 0)
  1124. {
  1125. if (trailByteCount > 0)
  1126. {
  1127. while (trailByteCount < 3 && count > 0)
  1128. {
  1129. trailBytes[trailByteCount++] = buffer[offset++];
  1130. count--;
  1131. }
  1132. }
  1133. int totalByteCount = trailByteCount + count;
  1134. int actualByteCount = totalByteCount - (totalByteCount % 3);
  1135. if (trailBytes == null)
  1136. {
  1137. trailBytes = new byte[3];
  1138. }
  1139. if (actualByteCount >= 3)
  1140. {
  1141. if (attributeValue != null)
  1142. {
  1143. WriteAttributeText(XmlConverter.Base64Encoding.GetString(trailBytes, 0, trailByteCount));
  1144. WriteAttributeText(XmlConverter.Base64Encoding.GetString(buffer, offset, actualByteCount - trailByteCount));
  1145. }
  1146. if (!isXmlnsAttribute)
  1147. {
  1148. StartContent();
  1149. writer.WriteBase64Text(trailBytes, trailByteCount, buffer, offset, actualByteCount - trailByteCount);
  1150. EndContent();
  1151. }
  1152. trailByteCount = (totalByteCount - actualByteCount);
  1153. if (trailByteCount > 0)
  1154. {
  1155. int trailOffset = offset + count - trailByteCount;
  1156. for (int i = 0; i < trailByteCount; i++)
  1157. trailBytes[i] = buffer[trailOffset++];
  1158. }
  1159. }
  1160. else
  1161. {
  1162. Buffer.BlockCopy(buffer, offset, trailBytes, trailByteCount, count);
  1163. trailByteCount += count;
  1164. }
  1165. }
  1166. }
  1167. internal override IAsyncResult BeginWriteBase64(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  1168. {
  1169. if (IsClosed)
  1170. ThrowClosed();
  1171. EnsureBufferBounds(buffer, offset, count);
  1172. return new WriteBase64AsyncResult(buffer, offset, count, this, callback, state);
  1173. }
  1174. internal override void EndWriteBase64(IAsyncResult result)
  1175. {
  1176. WriteBase64AsyncResult.End(result);
  1177. }
  1178. internal override AsyncCompletionResult WriteBase64Async(AsyncEventArgs<XmlWriteBase64AsyncArguments> state)
  1179. {
  1180. if (this.nodeWriterAsyncHelper == null)
  1181. {
  1182. this.nodeWriterAsyncHelper = new XmlBaseWriterNodeWriterAsyncHelper(this);
  1183. }
  1184. this.nodeWriterAsyncHelper.SetArguments(state);
  1185. if (this.nodeWriterAsyncHelper.StartAsync() == AsyncCompletionResult.Completed)
  1186. {
  1187. return AsyncCompletionResult.Completed;
  1188. }
  1189. return AsyncCompletionResult.Queued;
  1190. }
  1191. class WriteBase64AsyncResult : AsyncResult
  1192. {
  1193. static AsyncCompletion onComplete = new AsyncCompletion(OnComplete);
  1194. XmlBaseWriter writer;
  1195. byte[] buffer;
  1196. int offset;
  1197. int count;
  1198. int actualByteCount;
  1199. int totalByteCount;
  1200. public WriteBase64AsyncResult(byte[] buffer, int offset, int count, XmlBaseWriter writer, AsyncCallback callback, object state)
  1201. : base(callback, state)
  1202. {
  1203. this.writer = writer;
  1204. this.buffer = buffer;
  1205. this.offset = offset;
  1206. this.count = count;
  1207. bool completeSelf = true;
  1208. if (this.count > 0)
  1209. {
  1210. if (writer.trailByteCount > 0)
  1211. {
  1212. while (writer.trailByteCount < 3 && this.count > 0)
  1213. {
  1214. writer.trailBytes[writer.trailByteCount++] = buffer[this.offset++];
  1215. this.count--;
  1216. }
  1217. }
  1218. this.totalByteCount = writer.trailByteCount + this.count;
  1219. this.actualByteCount = totalByteCount - (totalByteCount % 3);
  1220. if (writer.trailBytes == null)
  1221. {
  1222. writer.trailBytes = new byte[3];
  1223. }
  1224. if (actualByteCount >= 3)
  1225. {
  1226. if (writer.attributeValue != null)
  1227. {
  1228. writer.WriteAttributeText(XmlConverter.Base64Encoding.GetString(writer.trailBytes, 0, writer.trailByteCount));
  1229. writer.WriteAttributeText(XmlConverter.Base64Encoding.GetString(buffer, this.offset, actualByteCount - writer.trailByteCount));
  1230. }
  1231. // StartContent/WriteBase64Text/EndContent will be called from HandleWriteBase64 as appropriate
  1232. completeSelf = HandleWriteBase64Text(null);
  1233. }
  1234. else
  1235. {
  1236. Buffer.BlockCopy(buffer, this.offset, writer.trailBytes, writer.trailByteCount, this.count);
  1237. writer.trailByteCount += this.count;
  1238. }
  1239. }
  1240. if (completeSelf)
  1241. {
  1242. this.Complete(true);
  1243. }
  1244. }
  1245. static bool OnComplete(IAsyncResult result)
  1246. {
  1247. WriteBase64AsyncResult thisPtr = (WriteBase64AsyncResult)result.AsyncState;
  1248. return thisPtr.HandleWriteBase64Text(result);
  1249. }
  1250. bool HandleWriteBase64Text(IAsyncResult result)
  1251. {
  1252. // in this code block if count > 0 && actualByteCount >= 3
  1253. if (!writer.isXmlnsAttribute)
  1254. {
  1255. if (result == null)
  1256. {
  1257. this.writer.StartContent();
  1258. result = this.writer.writer.BeginWriteBase64Text(this.writer.trailBytes,
  1259. this.writer.trailByteCount,
  1260. this.buffer,
  1261. this.offset,
  1262. this.actualByteCount - this.writer.trailByteCount,
  1263. PrepareAsyncCompletion(onComplete),
  1264. this);
  1265. if (!result.CompletedSynchronously)
  1266. {
  1267. return false;
  1268. }
  1269. }
  1270. this.writer.writer.EndWriteBase64Text(result);
  1271. this.writer.EndContent();
  1272. }
  1273. this.writer.trailByteCount = (totalByteCount - actualByteCount);
  1274. if (this.writer.trailByteCount > 0)
  1275. {
  1276. int trailOffset = offset + count - this.writer.trailByteCount;
  1277. for (int i = 0; i < this.writer.trailByteCount; i++)
  1278. this.writer.trailBytes[i] = this.buffer[trailOffset++];
  1279. }
  1280. return true;
  1281. }
  1282. public static void End(IAsyncResult result)
  1283. {
  1284. AsyncResult.End<WriteBase64AsyncResult>(result);
  1285. }
  1286. }
  1287. public override void WriteBinHex(byte[] buffer, int offset, int count)
  1288. {
  1289. if (IsClosed)
  1290. ThrowClosed();
  1291. EnsureBufferBounds(buffer, offset, count);
  1292. WriteRaw(BinHexEncoding.GetString(buffer, offset, count));
  1293. }
  1294. public override bool CanCanonicalize
  1295. {
  1296. get
  1297. {
  1298. return true;
  1299. }
  1300. }
  1301. protected bool Signing
  1302. {
  1303. get
  1304. {
  1305. return writer == signingWriter;
  1306. }
  1307. }
  1308. public override void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes)
  1309. {
  1310. if (IsClosed)
  1311. ThrowClosed();
  1312. if (Signing)
  1313. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlCanonicalizationStarted)));
  1314. FlushElement();
  1315. if (signingWriter == null)
  1316. signingWriter = CreateSigningNodeWriter();
  1317. signingWriter.SetOutput(writer, stream, includeComments, inclusivePrefixes);
  1318. writer = signingWriter;
  1319. SignScope(signingWriter.CanonicalWriter);
  1320. }
  1321. public override void EndCanonicalization()
  1322. {
  1323. if (IsClosed)
  1324. ThrowClosed();
  1325. if (!Signing)
  1326. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlCanonicalizationNotStarted)));
  1327. signingWriter.Flush();
  1328. writer = signingWriter.NodeWriter;
  1329. }
  1330. protected abstract XmlSigningNodeWriter CreateSigningNodeWriter();
  1331. public virtual bool CanFragment
  1332. {
  1333. get
  1334. {
  1335. return true;
  1336. }
  1337. }
  1338. public void StartFragment(Stream stream, bool generateSelfContainedTextFragment)
  1339. {
  1340. if (!CanFragment)
  1341. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
  1342. if (IsClosed)
  1343. ThrowClosed();
  1344. if (stream == null)
  1345. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("stream"));
  1346. if (oldStream != null || oldWriter != null)
  1347. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException());
  1348. if (WriteState == WriteState.Attribute)
  1349. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlInvalidWriteState, "StartFragment", WriteState.ToString())));
  1350. FlushElement();
  1351. writer.Flush();
  1352. oldNamespaceBoundary = NamespaceBoundary;
  1353. XmlStreamNodeWriter fragmentWriter = null;
  1354. if (generateSelfContainedTextFragment)
  1355. {
  1356. this.NamespaceBoundary = depth + 1;
  1357. if (textFragmentWriter == null)
  1358. textFragmentWriter = new XmlUTF8NodeWriter();
  1359. textFragmentWriter.SetOutput(stream, false, Encoding.UTF8);
  1360. fragmentWriter = textFragmentWriter;
  1361. }
  1362. if (Signing)
  1363. {
  1364. if (fragmentWriter != null)
  1365. {
  1366. oldWriter = signingWriter.NodeWriter;
  1367. signingWriter.NodeWriter = fragmentWriter;
  1368. }
  1369. else
  1370. {
  1371. oldStream = ((XmlStreamNodeWriter)signingWriter.NodeWriter).Stream;
  1372. ((XmlStreamNodeWriter)signingWriter.NodeWriter).Stream = stream;
  1373. }
  1374. }
  1375. else
  1376. {
  1377. if (fragmentWriter != null)
  1378. {
  1379. oldWriter = writer;
  1380. writer = fragmentWriter;
  1381. }
  1382. else
  1383. {
  1384. oldStream = nodeWriter.Stream;
  1385. nodeWriter.Stream = stream;
  1386. }
  1387. }
  1388. }
  1389. public void EndFragment()
  1390. {
  1391. if (IsClosed)
  1392. ThrowClosed();
  1393. if (oldStream == null && oldWriter == null)
  1394. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException());
  1395. if (WriteState == WriteState.Attribute)
  1396. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlInvalidWriteState, "EndFragment", WriteState.ToString())));
  1397. FlushElement();
  1398. writer.Flush();
  1399. if (Signing)
  1400. {
  1401. if (oldWriter != null)
  1402. signingWriter.NodeWriter = oldWriter;
  1403. else
  1404. ((XmlStreamNodeWriter)signingWriter.NodeWriter).Stream = oldStream;
  1405. }
  1406. else
  1407. {
  1408. if (oldWriter != null)
  1409. writer = oldWriter;
  1410. else
  1411. nodeWriter.Stream = oldStream;
  1412. }
  1413. NamespaceBoundary = oldNamespaceBoundary;
  1414. oldWriter = null;
  1415. oldStream = null;
  1416. }
  1417. public void WriteFragment(byte[] buffer, int offset, int count)
  1418. {
  1419. if (!CanFragment)
  1420. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
  1421. if (IsClosed)
  1422. ThrowClosed();
  1423. if (buffer == null)
  1424. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("buffer"));
  1425. if (offset < 0)
  1426. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.ValueMustBeNonNegative)));
  1427. if (count < 0)
  1428. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.ValueMustBeNonNegative)));
  1429. if (count > buffer.Length - offset)
  1430. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset)));
  1431. if (WriteState == WriteState.Attribute)
  1432. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlInvalidWriteState, "WriteFragment", WriteState.ToString())));
  1433. if (writer != nodeWriter)
  1434. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException());
  1435. FlushElement();
  1436. FlushBase64();
  1437. nodeWriter.Flush();
  1438. nodeWriter.Stream.Write(buffer, offset, count);
  1439. }
  1440. void FlushBase64()
  1441. {
  1442. if (trailByteCount > 0)
  1443. {
  1444. FlushTrailBytes();
  1445. }
  1446. }
  1447. void FlushTrailBytes()
  1448. {
  1449. if (attributeValue != null)
  1450. WriteAttributeText(XmlConverter.Base64Encoding.GetString(trailBytes, 0, trailByteCount));
  1451. if (!isXmlnsAttribute)
  1452. {
  1453. StartContent();
  1454. writer.WriteBase64Text(trailBytes, trailByteCount, trailBytes, 0, 0);
  1455. EndContent();
  1456. }
  1457. trailByteCount = 0;
  1458. }
  1459. void WriteValue(object[] array)
  1460. {
  1461. FlushBase64();
  1462. StartContent();
  1463. writer.WriteStartListText();
  1464. this.inList = true;
  1465. for (int i = 0; i < array.Length; i++)
  1466. {
  1467. if (i != 0)
  1468. {
  1469. writer.WriteListSeparator();
  1470. }
  1471. WritePrimitiveValue(array[i]);
  1472. }
  1473. this.inList = false;
  1474. writer.WriteEndListText();
  1475. EndContent();
  1476. }
  1477. void WriteValue(Array array)
  1478. {
  1479. FlushBase64();
  1480. StartContent();
  1481. writer.WriteStartListText();
  1482. this.inList = true;
  1483. for (int i = 0; i < array.Length; i++)
  1484. {
  1485. if (i != 0)
  1486. {
  1487. writer.WriteListSeparator();
  1488. }
  1489. WritePrimitiveValue(array.GetValue(i));
  1490. }
  1491. this.inList = false;
  1492. writer.WriteEndListText();
  1493. EndContent();
  1494. }
  1495. protected void StartArray(int count)
  1496. {
  1497. FlushBase64();
  1498. if (this.documentState == DocumentState.Epilog)
  1499. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlOnlyOneRoot)));
  1500. if (this.documentState == DocumentState.Document && count > 1 && depth == 0)
  1501. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlOnlyOneRoot)));
  1502. if (writeState == WriteState.Attribute)
  1503. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlInvalidWriteState, "WriteStartElement", WriteState.ToString())));
  1504. AutoComplete(WriteState.Content);
  1505. }
  1506. protected void EndArray()
  1507. {
  1508. }
  1509. void EnsureBufferBounds(byte[] buffer, int offset, int count)
  1510. {
  1511. if (buffer == null)
  1512. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer");
  1513. // Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does.
  1514. if (offset < 0)
  1515. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.ValueMustBeNonNegative)));
  1516. if (count < 0)
  1517. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.ValueMustBeNonNegative)));
  1518. if (count > buffer.Length - offset)
  1519. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset)));
  1520. }
  1521. string GeneratePrefix(string ns, XmlDictionaryString xNs)
  1522. {
  1523. if (writeState != WriteState.Element && writeState != WriteState.Attribute)
  1524. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlInvalidPrefixState, WriteState.ToString())));
  1525. string prefix = nsMgr.AddNamespace(ns, xNs);
  1526. if (prefix != null)
  1527. return prefix;
  1528. while (true)
  1529. {
  1530. int prefixId = elements[depth].PrefixId++;
  1531. prefix = string.Concat("d", depth.ToString(CultureInfo.InvariantCulture), "p", prefixId.ToString(CultureInfo.InvariantCulture));
  1532. if (nsMgr.LookupNamespace(prefix) == null)
  1533. {
  1534. nsMgr.AddNamespace(prefix, ns, xNs);
  1535. return prefix;
  1536. }
  1537. }
  1538. }
  1539. protected void SignScope(XmlCanonicalWriter signingWriter)
  1540. {
  1541. nsMgr.Sign(signingWriter);
  1542. }
  1543. void WriteAttributeText(string value)
  1544. {
  1545. if (attributeValue.Length == 0)
  1546. attributeValue = value;
  1547. else
  1548. attributeValue += value;
  1549. }
  1550. class Element
  1551. {
  1552. string prefix;
  1553. string localName;
  1554. int prefixId;
  1555. public string Prefix
  1556. {
  1557. get
  1558. {
  1559. return prefix;
  1560. }
  1561. set
  1562. {
  1563. prefix = value;
  1564. }
  1565. }
  1566. public string LocalName
  1567. {
  1568. get
  1569. {
  1570. return localName;
  1571. }
  1572. set
  1573. {
  1574. localName = value;
  1575. }
  1576. }
  1577. public int PrefixId
  1578. {
  1579. get
  1580. {
  1581. return prefixId;
  1582. }
  1583. set
  1584. {
  1585. prefixId = value;
  1586. }
  1587. }
  1588. public void Clear()
  1589. {
  1590. this.prefix = null;
  1591. this.localName = null;
  1592. this.prefixId = 0;
  1593. }
  1594. }
  1595. enum DocumentState : byte
  1596. {
  1597. None, // Not inside StartDocument/EndDocument - Allows multiple root elemnts
  1598. Document, // Inside StartDocument/EndDocument
  1599. Epilog, // EndDocument must be called
  1600. End // Nothing further to write
  1601. }
  1602. class NamespaceManager
  1603. {
  1604. Namespace[] namespaces;
  1605. Namespace lastNameSpace;
  1606. int nsCount;
  1607. int depth;
  1608. XmlAttribute[] attributes;
  1609. int attributeCount;
  1610. XmlSpace space;
  1611. string lang;
  1612. int namespaceBoundary;
  1613. int nsTop;
  1614. Namespace defaultNamespace;
  1615. public NamespaceManager()
  1616. {
  1617. defaultNamespace = new Namespace();
  1618. defaultNamespace.Depth = 0;
  1619. defaultNamespace.Prefix = string.Empty;
  1620. defaultNamespace.Uri = string.Empty;
  1621. defaultNamespace.UriDictionaryString = null;
  1622. }
  1623. public string XmlLang
  1624. {
  1625. get
  1626. {
  1627. return lang;
  1628. }
  1629. }
  1630. public XmlSpace XmlSpace
  1631. {
  1632. get
  1633. {
  1634. return space;
  1635. }
  1636. }
  1637. public void Clear()
  1638. {
  1639. if (this.namespaces == null)
  1640. {
  1641. this.namespaces = new Namespace[4];
  1642. this.namespaces[0] = defaultNamespace;
  1643. }
  1644. this.nsCount = 1;
  1645. this.nsTop = 0;
  1646. this.depth = 0;
  1647. this.attributeCount = 0;
  1648. this.space = XmlSpace.None;
  1649. this.lang = null;
  1650. this.lastNameSpace = null;
  1651. this.namespaceBoundary = 0;
  1652. }
  1653. public int NamespaceBoundary
  1654. {
  1655. get
  1656. {
  1657. return namespaceBoundary;
  1658. }
  1659. set
  1660. {
  1661. int i;
  1662. for (i = 0; i < nsCount; i++)
  1663. if (namespaces[i].Depth >= value)
  1664. break;
  1665. nsTop = i;
  1666. namespaceBoundary = value;
  1667. lastNameSpace = null;
  1668. }
  1669. }
  1670. public void Close()
  1671. {
  1672. if (depth == 0)
  1673. {
  1674. if (namespaces != null && namespaces.Length > 32)
  1675. namespaces = null;
  1676. if (attributes != null && attributes.Length > 4)
  1677. attributes = null;
  1678. }
  1679. else
  1680. {
  1681. namespaces = null;
  1682. attributes = null;
  1683. }
  1684. lang = null;
  1685. }
  1686. public void DeclareNamespaces(XmlNodeWriter writer)
  1687. {
  1688. int i = this.nsCount;
  1689. while (i > 0)
  1690. {
  1691. Namespace nameSpace = namespaces[i - 1];
  1692. if (nameSpace.Depth != depth)
  1693. break;
  1694. i--;
  1695. }
  1696. while (i < this.nsCount)
  1697. {
  1698. Namespace nameSpace = namespaces[i];
  1699. if (nameSpace.UriDictionaryString != null)
  1700. writer.WriteXmlnsAttribute(nameSpace.Prefix, nameSpace.UriDictionaryString);
  1701. else
  1702. writer.WriteXmlnsAttribute(nameSpace.Prefix, nameSpace.Uri);
  1703. i++;
  1704. }
  1705. }
  1706. public void EnterScope()
  1707. {
  1708. depth++;
  1709. }
  1710. public void ExitScope()
  1711. {
  1712. while (nsCount > 0)
  1713. {
  1714. Namespace nameSpace = namespaces[nsCount - 1];
  1715. if (nameSpace.Depth != depth)
  1716. break;
  1717. if (lastNameSpace == nameSpace)
  1718. lastNameSpace = null;
  1719. nameSpace.Clear();
  1720. nsCount--;
  1721. }
  1722. while (attributeCount > 0)
  1723. {
  1724. XmlAttribute attribute = attributes[attributeCount - 1];
  1725. if (attribute.Depth != depth)
  1726. break;
  1727. space = attribute.XmlSpace;
  1728. lang = attribute.XmlLang;
  1729. attribute.Clear();
  1730. attributeCount--;
  1731. }
  1732. depth--;
  1733. }
  1734. public void AddLangAttribute(string lang)
  1735. {
  1736. AddAttribute();
  1737. this.lang = lang;
  1738. }
  1739. public void AddSpaceAttribute(XmlSpace space)
  1740. {
  1741. AddAttribute();
  1742. this.space = space;
  1743. }
  1744. void AddAttribute()
  1745. {
  1746. if (attributes == null)
  1747. {
  1748. attributes = new XmlAttribute[1];
  1749. }
  1750. else if (attributes.Length == attributeCount)
  1751. {
  1752. XmlAttribute[] newAttributes = new XmlAttribute[attributeCount * 2];
  1753. Array.Copy(attributes, newAttributes, attributeCount);
  1754. attributes = newAttributes;
  1755. }
  1756. XmlAttribute attribute = attributes[attributeCount];
  1757. if (attribute == null)
  1758. {
  1759. attribute = new XmlAttribute();
  1760. attributes[attributeCount] = attribute;
  1761. }
  1762. attribute.XmlLang = this.lang;
  1763. attribute.XmlSpace = this.space;
  1764. attribute.Depth = depth;
  1765. attributeCount++;
  1766. }
  1767. public string AddNamespace(string uri, XmlDictionaryString uriDictionaryString)
  1768. {
  1769. if (uri.Length == 0)
  1770. {
  1771. // Empty namespace can only be bound to the empty prefix
  1772. AddNamespaceIfNotDeclared(string.Empty, uri, uriDictionaryString);
  1773. return string.Empty;
  1774. }
  1775. else
  1776. {
  1777. for (int i = 0; i < prefixes.Length; i++)
  1778. {
  1779. string prefix = prefixes[i];
  1780. bool declared = false;
  1781. for (int j = nsCount - 1; j >= nsTop; j--)
  1782. {
  1783. Namespace nameSpace = namespaces[j];
  1784. if (nameSpace.Prefix == prefix)
  1785. {
  1786. declared = true;
  1787. break;
  1788. }
  1789. }
  1790. if (!declared)
  1791. {
  1792. AddNamespace(prefix, uri, uriDictionaryString);
  1793. return prefix;
  1794. }
  1795. }
  1796. }
  1797. return null;
  1798. }
  1799. public void AddNamespaceIfNotDeclared(string prefix, string uri, XmlDictionaryString uriDictionaryString)
  1800. {
  1801. if (LookupNamespace(prefix) != uri)
  1802. {
  1803. AddNamespace(prefix, uri, uriDictionaryString);
  1804. }
  1805. }
  1806. public void AddNamespace(string prefix, string uri, XmlDictionaryString uriDictionaryString)
  1807. {
  1808. if (prefix.Length >= 3)
  1809. {
  1810. // Upper and lower case letter differ by a bit.
  1811. if ((prefix[0] & ~32) == 'X' && (prefix[1] & ~32) == 'M' && (prefix[2] & ~32) == 'L')
  1812. {
  1813. if (prefix == "xml" && uri == xmlNamespace)
  1814. return;
  1815. if (prefix == "xmlns" && uri == xmlnsNamespace)
  1816. return;
  1817. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.XmlReservedPrefix), "prefix"));
  1818. }
  1819. }
  1820. Namespace nameSpace;
  1821. for (int i = nsCount - 1; i >= 0; i--)
  1822. {
  1823. nameSpace = namespaces[i];
  1824. if (nameSpace.Depth != depth)
  1825. break;
  1826. if (nameSpace.Prefix == prefix)
  1827. {
  1828. if (nameSpace.Uri == uri)
  1829. return;
  1830. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.XmlPrefixBoundToNamespace, prefix, nameSpace.Uri, uri), "prefix"));
  1831. }
  1832. }
  1833. if (prefix.Length != 0 && uri.Length == 0)
  1834. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.XmlEmptyNamespaceRequiresNullPrefix), "prefix"));
  1835. if (uri.Length == xmlnsNamespace.Length && uri == xmlnsNamespace)
  1836. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.XmlSpecificBindingNamespace, "xmlns", uri)));
  1837. // The addressing namespace and the xmlNamespace are the same length, so add a quick check to try to disambiguate
  1838. if (uri.Length == xmlNamespace.Length && uri[18] == 'X' && uri == xmlNamespace)
  1839. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.XmlSpecificBindingNamespace, "xml", uri)));
  1840. if (namespaces.Length == nsCount)
  1841. {
  1842. Namespace[] newNamespaces = new Namespace[nsCount * 2];
  1843. Array.Copy(namespaces, newNamespaces, nsCount);
  1844. namespaces = newNamespaces;
  1845. }
  1846. nameSpace = namespaces[nsCount];
  1847. if (nameSpace == null)
  1848. {
  1849. nameSpace = new Namespace();
  1850. namespaces[nsCount] = nameSpace;
  1851. }
  1852. nameSpace.Depth = depth;
  1853. nameSpace.Prefix = prefix;
  1854. nameSpace.Uri = uri;
  1855. nameSpace.UriDictionaryString = uriDictionaryString;
  1856. nsCount++;
  1857. lastNameSpace = null;
  1858. }
  1859. public string LookupPrefix(string ns)
  1860. {
  1861. if (lastNameSpace != null && lastNameSpace.Uri == ns)
  1862. return lastNameSpace.Prefix;
  1863. int nsCount = this.nsCount;
  1864. for (int i = nsCount - 1; i >= nsTop; i--)
  1865. {
  1866. Namespace nameSpace = namespaces[i];
  1867. if (object.ReferenceEquals(nameSpace.Uri, ns))
  1868. {
  1869. string prefix = nameSpace.Prefix;
  1870. // Make sure that the prefix refers to the namespace in scope
  1871. bool declared = false;
  1872. for (int j = i + 1; j < nsCount; j++)
  1873. {
  1874. if (namespaces[j].Prefix == prefix)
  1875. {
  1876. declared = true;
  1877. break;
  1878. }
  1879. }
  1880. if (!declared)
  1881. {
  1882. lastNameSpace = nameSpace;
  1883. return prefix;
  1884. }
  1885. }
  1886. }
  1887. for (int i = nsCount - 1; i >= nsTop; i--)
  1888. {
  1889. Namespace nameSpace = namespaces[i];
  1890. if (nameSpace.Uri == ns)
  1891. {
  1892. string prefix = nameSpace.Prefix;
  1893. // Make sure that the prefix refers to the namespace in scope
  1894. bool declared = false;
  1895. for (int j = i + 1; j < nsCount; j++)
  1896. {
  1897. if (namespaces[j].Prefix == prefix)
  1898. {
  1899. declared = true;
  1900. break;
  1901. }
  1902. }
  1903. if (!declared)
  1904. {
  1905. lastNameSpace = nameSpace;
  1906. return prefix;
  1907. }
  1908. }
  1909. }
  1910. if (ns.Length == 0)
  1911. {
  1912. // Make sure the default binding is still valid
  1913. bool emptyPrefixUnassigned = true;
  1914. for (int i = nsCount - 1; i >= nsTop; i--)
  1915. {
  1916. if (namespaces[i].Prefix.Length == 0)
  1917. {
  1918. emptyPrefixUnassigned = false;
  1919. break;
  1920. }
  1921. }
  1922. if (emptyPrefixUnassigned)
  1923. return string.Empty;
  1924. }
  1925. if (ns == xmlnsNamespace)
  1926. return "xmlns";
  1927. if (ns == xmlNamespace)
  1928. return "xml";
  1929. return null;
  1930. }
  1931. public string LookupAttributePrefix(string ns)
  1932. {
  1933. if (lastNameSpace != null && lastNameSpace.Uri == ns && lastNameSpace.Prefix.Length != 0)
  1934. return lastNameSpace.Prefix;
  1935. int nsCount = this.nsCount;
  1936. for (int i = nsCount - 1; i >= nsTop; i--)
  1937. {
  1938. Namespace nameSpace = namespaces[i];
  1939. if (object.ReferenceEquals(nameSpace.Uri, ns))
  1940. {
  1941. string prefix = nameSpace.Prefix;
  1942. if (prefix.Length != 0)
  1943. {
  1944. // Make sure that the prefix refers to the namespace in scope
  1945. bool declared = false;
  1946. for (int j = i + 1; j < nsCount; j++)
  1947. {
  1948. if (namespaces[j].Prefix == prefix)
  1949. {
  1950. declared = true;
  1951. break;
  1952. }
  1953. }
  1954. if (!declared)
  1955. {
  1956. lastNameSpace = nameSpace;
  1957. return prefix;
  1958. }
  1959. }
  1960. }
  1961. }
  1962. for (int i = nsCount - 1; i >= nsTop; i--)
  1963. {
  1964. Namespace nameSpace = namespaces[i];
  1965. if (nameSpace.Uri == ns)
  1966. {
  1967. string prefix = nameSpace.Prefix;
  1968. if (prefix.Length != 0)
  1969. {
  1970. // Make sure that the prefix refers to the namespace in scope
  1971. bool declared = false;
  1972. for (int j = i + 1; j < nsCount; j++)
  1973. {
  1974. if (namespaces[j].Prefix == prefix)
  1975. {
  1976. declared = true;
  1977. break;
  1978. }
  1979. }
  1980. if (!declared)
  1981. {
  1982. lastNameSpace = nameSpace;
  1983. return prefix;
  1984. }
  1985. }
  1986. }
  1987. }
  1988. if (ns.Length == 0)
  1989. return string.Empty;
  1990. return null;
  1991. }
  1992. public string LookupNamespace(string prefix)
  1993. {
  1994. int nsCount = this.nsCount;
  1995. if (prefix.Length == 0)
  1996. {
  1997. for (int i = nsCount - 1; i >= nsTop; i--)
  1998. {
  1999. Namespace nameSpace = namespaces[i];
  2000. if (nameSpace.Prefix.Length == 0)
  2001. return nameSpace.Uri;
  2002. }
  2003. return string.Empty;
  2004. }
  2005. if (prefix.Length == 1)
  2006. {
  2007. char prefixChar = prefix[0];
  2008. for (int i = nsCount - 1; i >= nsTop; i--)
  2009. {
  2010. Namespace nameSpace = namespaces[i];
  2011. if (nameSpace.PrefixChar == prefixChar)
  2012. return nameSpace.Uri;
  2013. }
  2014. return null;
  2015. }
  2016. for (int i = nsCount - 1; i >= nsTop; i--)
  2017. {
  2018. Namespace nameSpace = namespaces[i];
  2019. if (nameSpace.Prefix == prefix)
  2020. return nameSpace.Uri;
  2021. }
  2022. if (prefix == "xmlns")
  2023. return xmlnsNamespace;
  2024. if (prefix == "xml")
  2025. return xmlNamespace;
  2026. return null;
  2027. }
  2028. public void Sign(XmlCanonicalWriter signingWriter)
  2029. {
  2030. int nsCount = this.nsCount;
  2031. Fx.Assert(nsCount >= 1 && namespaces[0].Prefix.Length == 0 && namespaces[0].Uri.Length == 0, "");
  2032. for (int i = 1; i < nsCount; i++)
  2033. {
  2034. Namespace nameSpace = namespaces[i];
  2035. bool found = false;
  2036. for (int j = i + 1; j < nsCount && !found; j++)
  2037. {
  2038. found = (nameSpace.Prefix == namespaces[j].Prefix);
  2039. }
  2040. if (!found)
  2041. {
  2042. signingWriter.WriteXmlnsAttribute(nameSpace.Prefix, nameSpace.Uri);
  2043. }
  2044. }
  2045. }
  2046. class XmlAttribute
  2047. {
  2048. XmlSpace space;
  2049. string lang;
  2050. int depth;
  2051. public XmlAttribute()
  2052. {
  2053. }
  2054. public int Depth
  2055. {
  2056. get
  2057. {
  2058. return depth;
  2059. }
  2060. set
  2061. {
  2062. depth = value;
  2063. }
  2064. }
  2065. public string XmlLang
  2066. {
  2067. get
  2068. {
  2069. return lang;
  2070. }
  2071. set
  2072. {
  2073. lang = value;
  2074. }
  2075. }
  2076. public XmlSpace XmlSpace
  2077. {
  2078. get
  2079. {
  2080. return space;
  2081. }
  2082. set
  2083. {
  2084. space = value;
  2085. }
  2086. }
  2087. public void Clear()
  2088. {
  2089. this.lang = null;
  2090. }
  2091. }
  2092. class Namespace
  2093. {
  2094. string prefix;
  2095. string ns;
  2096. XmlDictionaryString xNs;
  2097. int depth;
  2098. char prefixChar;
  2099. public Namespace()
  2100. {
  2101. }
  2102. public void Clear()
  2103. {
  2104. this.prefix = null;
  2105. this.prefixChar = (char)0;
  2106. this.ns = null;
  2107. this.xNs = null;
  2108. this.depth = 0;
  2109. }
  2110. public int Depth
  2111. {
  2112. get
  2113. {
  2114. return depth;
  2115. }
  2116. set
  2117. {
  2118. depth = value;
  2119. }
  2120. }
  2121. public char PrefixChar
  2122. {
  2123. get
  2124. {
  2125. return prefixChar;
  2126. }
  2127. }
  2128. public string Prefix
  2129. {
  2130. get
  2131. {
  2132. return prefix;
  2133. }
  2134. set
  2135. {
  2136. if (value.Length == 1)
  2137. prefixChar = value[0];
  2138. else
  2139. prefixChar = (char)0;
  2140. prefix = value;
  2141. }
  2142. }
  2143. public string Uri
  2144. {
  2145. get
  2146. {
  2147. return ns;
  2148. }
  2149. set
  2150. {
  2151. ns = value;
  2152. }
  2153. }
  2154. public XmlDictionaryString UriDictionaryString
  2155. {
  2156. get
  2157. {
  2158. return xNs;
  2159. }
  2160. set
  2161. {
  2162. xNs = value;
  2163. }
  2164. }
  2165. }
  2166. }
  2167. class XmlBaseWriterNodeWriterAsyncHelper
  2168. {
  2169. static AsyncEventArgsCallback onWriteComplete;
  2170. XmlBaseWriter writer;
  2171. byte[] buffer;
  2172. int offset;
  2173. int count;
  2174. int actualByteCount;
  2175. int totalByteCount;
  2176. AsyncEventArgs<XmlNodeWriterWriteBase64TextArgs> nodeWriterAsyncState;
  2177. XmlNodeWriterWriteBase64TextArgs nodeWriterArgs;
  2178. AsyncEventArgs<XmlWriteBase64AsyncArguments> inputState;
  2179. public XmlBaseWriterNodeWriterAsyncHelper(XmlBaseWriter writer)
  2180. {
  2181. this.writer = writer;
  2182. }
  2183. public void SetArguments(AsyncEventArgs<XmlWriteBase64AsyncArguments> inputState)
  2184. {
  2185. Fx.Assert(inputState != null, "InputState cannot be null.");
  2186. this.inputState = inputState;
  2187. this.buffer = inputState.Arguments.Buffer;
  2188. this.offset = inputState.Arguments.Offset;
  2189. this.count = inputState.Arguments.Count;
  2190. }
  2191. public AsyncCompletionResult StartAsync()
  2192. {
  2193. bool completeSelf = true;
  2194. if (this.count > 0)
  2195. {
  2196. // Bytes that have been already been read.
  2197. if (this.writer.trailByteCount > 0)
  2198. {
  2199. // Copy over up to 3 trailing bytes into the trailBytes buffer.
  2200. while (this.writer.trailByteCount < 3 && this.count > 0)
  2201. {
  2202. this.writer.trailBytes[this.writer.trailByteCount++] = this.buffer[this.offset++];
  2203. this.count--;
  2204. }
  2205. }
  2206. this.totalByteCount = this.writer.trailByteCount + this.count;
  2207. this.actualByteCount = this.totalByteCount - (this.totalByteCount % 3);
  2208. if (this.writer.trailBytes == null)
  2209. {
  2210. this.writer.trailBytes = new byte[3];
  2211. }
  2212. if (actualByteCount >= 3)
  2213. {
  2214. if (this.writer.attributeValue != null)
  2215. {
  2216. this.writer.WriteAttributeText(XmlConverter.Base64Encoding.GetString(this.writer.trailBytes, 0, this.writer.trailByteCount));
  2217. this.writer.WriteAttributeText(XmlConverter.Base64Encoding.GetString(this.buffer, this.offset, actualByteCount - this.writer.trailByteCount));
  2218. }
  2219. // StartContent/WriteBase64Text/EndContent will be called from HandleWriteBase64 as appropriate
  2220. completeSelf = HandleWriteBase64Text(false);
  2221. }
  2222. else
  2223. {
  2224. Buffer.BlockCopy(this.buffer, this.offset, this.writer.trailBytes, this.writer.trailByteCount, this.count);
  2225. this.writer.trailByteCount += this.count;
  2226. }
  2227. }
  2228. if (completeSelf)
  2229. {
  2230. this.Clear();
  2231. return AsyncCompletionResult.Completed;
  2232. }
  2233. return AsyncCompletionResult.Queued;
  2234. }
  2235. static void OnWriteComplete(IAsyncEventArgs asyncEventArgs)
  2236. {
  2237. bool completeSelf = false;
  2238. Exception completionException = null;
  2239. XmlBaseWriterNodeWriterAsyncHelper thisPtr = (XmlBaseWriterNodeWriterAsyncHelper)asyncEventArgs.AsyncState;
  2240. AsyncEventArgs<XmlWriteBase64AsyncArguments> inputState = thisPtr.inputState;
  2241. try
  2242. {
  2243. if (asyncEventArgs.Exception != null)
  2244. {
  2245. completionException = asyncEventArgs.Exception;
  2246. completeSelf = true;
  2247. }
  2248. else
  2249. {
  2250. completeSelf = thisPtr.HandleWriteBase64Text(true);
  2251. }
  2252. }
  2253. catch (Exception exception)
  2254. {
  2255. if (Fx.IsFatal(exception))
  2256. {
  2257. throw;
  2258. }
  2259. completionException = exception;
  2260. completeSelf = true;
  2261. }
  2262. if (completeSelf)
  2263. {
  2264. thisPtr.Clear();
  2265. inputState.Complete(false, completionException);
  2266. }
  2267. }
  2268. bool HandleWriteBase64Text(bool isAsyncCallback)
  2269. {
  2270. Fx.Assert(this.count > 0 && this.actualByteCount >= 3, "HandleWriteBase64Text cannot be invoked with less than 3 bytes.");
  2271. if (!writer.isXmlnsAttribute)
  2272. {
  2273. if (!isAsyncCallback)
  2274. {
  2275. if (this.nodeWriterAsyncState == null)
  2276. {
  2277. this.nodeWriterAsyncState = new AsyncEventArgs<XmlNodeWriterWriteBase64TextArgs>();
  2278. this.nodeWriterArgs = new XmlNodeWriterWriteBase64TextArgs();
  2279. }
  2280. if (onWriteComplete == null)
  2281. {
  2282. onWriteComplete = new AsyncEventArgsCallback(OnWriteComplete);
  2283. }
  2284. this.writer.StartContent();
  2285. this.nodeWriterArgs.TrailBuffer = this.writer.trailBytes;
  2286. this.nodeWriterArgs.TrailCount = this.writer.trailByteCount;
  2287. this.nodeWriterArgs.Buffer = this.buffer;
  2288. this.nodeWriterArgs.Offset = this.offset;
  2289. this.nodeWriterArgs.Count = this.actualByteCount - this.writer.trailByteCount;
  2290. this.nodeWriterAsyncState.Set(onWriteComplete, this.nodeWriterArgs, this);
  2291. if (this.writer.writer.WriteBase64TextAsync(this.nodeWriterAsyncState) != AsyncCompletionResult.Completed)
  2292. {
  2293. return false;
  2294. }
  2295. this.nodeWriterAsyncState.Complete(true);
  2296. }
  2297. this.writer.EndContent();
  2298. }
  2299. this.writer.trailByteCount = (this.totalByteCount - this.actualByteCount);
  2300. if (this.writer.trailByteCount > 0)
  2301. {
  2302. int trailOffset = offset + count - this.writer.trailByteCount;
  2303. for (int i = 0; i < this.writer.trailByteCount; i++)
  2304. this.writer.trailBytes[i] = this.buffer[trailOffset++];
  2305. }
  2306. return true;
  2307. }
  2308. void Clear()
  2309. {
  2310. this.inputState = null;
  2311. this.buffer = null;
  2312. this.offset = 0;
  2313. this.count = 0;
  2314. this.actualByteCount = 0;
  2315. this.totalByteCount = 0;
  2316. }
  2317. }
  2318. }
  2319. }