DataSet.cs 155 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673
  1. //------------------------------------------------------------------------------
  2. // <copyright file="DataSet.cs" company="Microsoft">
  3. // Copyright (c) Microsoft Corporation. All rights reserved.
  4. // </copyright>
  5. // <owner current="true" primary="true">[....]</owner>
  6. // <owner current="true" primary="false">[....]</owner>
  7. //------------------------------------------------------------------------------
  8. namespace System.Data {
  9. using System;
  10. using System.Text;
  11. using System.Runtime.Serialization;
  12. using System.ComponentModel;
  13. using System.Diagnostics;
  14. using System.Globalization;
  15. using System.IO;
  16. using System.Collections;
  17. using System.Collections.Generic;
  18. using System.Collections.Specialized;
  19. using System.Xml;
  20. using System.Xml.Serialization;
  21. #if !NO_CONFIGURATION
  22. using System.Xml.Serialization.Advanced;
  23. #endif
  24. using System.Xml.Schema;
  25. using System.Runtime.Serialization.Formatters.Binary; //Binary Formatter
  26. using System.CodeDom;
  27. using System.CodeDom.Compiler;
  28. using System.Configuration;
  29. using System.Data.Common;
  30. using System.Runtime.Versioning;
  31. using System.Runtime.CompilerServices;
  32. /// <devdoc>
  33. /// <para>
  34. /// Represents an in-memory cache of data.
  35. /// </para>
  36. /// </devdoc>
  37. [
  38. ResDescriptionAttribute(Res.DataSetDescr),
  39. DefaultProperty("DataSetName"),
  40. ToolboxItem("Microsoft.VSDesigner.Data.VS.DataSetToolboxItem, " + AssemblyRef.MicrosoftVSDesigner),
  41. Designer("Microsoft.VSDesigner.Data.VS.DataSetDesigner, " + AssemblyRef.MicrosoftVSDesigner),
  42. Serializable,
  43. XmlSchemaProvider("GetDataSetSchema"),
  44. XmlRoot("DataSet")
  45. ]
  46. public class DataSet : MarshalByValueComponent, System.ComponentModel.IListSource, IXmlSerializable, ISupportInitializeNotification, ISerializable {
  47. private DataViewManager defaultViewManager;
  48. // Public Collections
  49. private readonly DataTableCollection tableCollection;
  50. private readonly DataRelationCollection relationCollection;
  51. internal PropertyCollection extendedProperties = null;
  52. private string dataSetName = "NewDataSet";
  53. private string _datasetPrefix = String.Empty;
  54. internal string namespaceURI = string.Empty;
  55. private bool enforceConstraints = true;
  56. private const String KEY_XMLSCHEMA = "XmlSchema";
  57. private const String KEY_XMLDIFFGRAM = "XmlDiffGram";
  58. // globalization stuff
  59. private bool _caseSensitive;
  60. private CultureInfo _culture;
  61. private bool _cultureUserSet;
  62. // Internal definitions
  63. internal bool fInReadXml = false;
  64. internal bool fInLoadDiffgram = false;
  65. internal bool fTopLevelTable = false;
  66. internal bool fInitInProgress = false;
  67. internal bool fEnableCascading = true;
  68. internal bool fIsSchemaLoading = false;
  69. private bool fBoundToDocument; // for XmlDataDocument
  70. // Events
  71. private PropertyChangedEventHandler onPropertyChangingDelegate;
  72. private MergeFailedEventHandler onMergeFailed;
  73. private DataRowCreatedEventHandler onDataRowCreated; // Internal for XmlDataDocument only
  74. private DataSetClearEventhandler onClearFunctionCalled; // Internal for XmlDataDocument only
  75. private System.EventHandler onInitialized;
  76. internal readonly static DataTable[] zeroTables = new DataTable[0];
  77. internal string mainTableName = "";
  78. //default remoting format is XML
  79. private SerializationFormat _remotingFormat = SerializationFormat.Xml;
  80. private object _defaultViewManagerLock = new Object();
  81. private static int _objectTypeCount; // Bid counter
  82. private readonly int _objectID = System.Threading.Interlocked.Increment(ref _objectTypeCount);
  83. private static XmlSchemaComplexType schemaTypeForWSDL = null;
  84. internal bool UseDataSetSchemaOnly; // UseDataSetSchemaOnly , for YUKON
  85. internal bool UdtIsWrapped; // if UDT is wrapped , for YUKON
  86. /// <devdoc>
  87. /// <para>Initializes a new instance of the <see cref='System.Data.DataSet'/> class.</para>
  88. /// </devdoc>
  89. public DataSet() {
  90. GC.SuppressFinalize(this);
  91. Bid.Trace("<ds.DataSet.DataSet|API> %d#\n", ObjectID); // others will call this constr
  92. // Set default locale
  93. this.tableCollection = new DataTableCollection(this);
  94. this.relationCollection = new DataRelationCollection.DataSetRelationCollection(this);
  95. _culture = CultureInfo.CurrentCulture; // Set default locale
  96. }
  97. /// <devdoc>
  98. /// <para>Initializes a new instance of a <see cref='System.Data.DataSet'/>
  99. /// class with the given name.</para>
  100. /// </devdoc>
  101. public DataSet(string dataSetName)
  102. : this()
  103. {
  104. this.DataSetName = dataSetName;
  105. }
  106. [
  107. DefaultValue(SerializationFormat.Xml)
  108. ]
  109. public SerializationFormat RemotingFormat {
  110. get {
  111. return _remotingFormat;
  112. }
  113. set {
  114. if (value != SerializationFormat.Binary && value != SerializationFormat.Xml) {
  115. throw ExceptionBuilder.InvalidRemotingFormat(value);
  116. }
  117. _remotingFormat = value;
  118. // this property is inherited to DataTable from DataSet.So we set this value to DataTable also
  119. for (int i = 0; i < Tables.Count; i++) {
  120. Tables[i].RemotingFormat = value;
  121. }
  122. }
  123. }
  124. [BrowsableAttribute(false)]
  125. [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
  126. public virtual SchemaSerializationMode SchemaSerializationMode { //Typed DataSet calls into this
  127. get {
  128. return SchemaSerializationMode.IncludeSchema;
  129. }
  130. set {
  131. if (value != SchemaSerializationMode.IncludeSchema) {
  132. throw ExceptionBuilder.CannotChangeSchemaSerializationMode();
  133. }
  134. }
  135. }
  136. // Check whether the stream is binary serialized.
  137. // 'static' function that consumes SerializationInfo
  138. protected bool IsBinarySerialized(SerializationInfo info, StreamingContext context) {// mainly for typed DS
  139. // our default remoting format is XML
  140. SerializationFormat remotingFormat = SerializationFormat.Xml;
  141. SerializationInfoEnumerator e = info.GetEnumerator();
  142. while (e.MoveNext()) {
  143. if (e.Name == "DataSet.RemotingFormat") {//DataSet.RemotingFormat does not exist in V1/V1.1 versions
  144. remotingFormat = (SerializationFormat)e.Value;
  145. break;
  146. }
  147. }
  148. return (remotingFormat == SerializationFormat.Binary);
  149. }
  150. // Should Schema be included during Serialization
  151. // 'static' function that consumes SerializationInfo
  152. protected SchemaSerializationMode DetermineSchemaSerializationMode(SerializationInfo info, StreamingContext context) { //Typed DataSet calls into this
  153. SchemaSerializationMode schemaSerializationMode = SchemaSerializationMode.IncludeSchema;
  154. SerializationInfoEnumerator e = info.GetEnumerator();
  155. while (e.MoveNext()) {
  156. if (e.Name == "SchemaSerializationMode.DataSet") { //SchemaSerializationMode.DataSet does not exist in V1/V1.1 versions
  157. schemaSerializationMode = (SchemaSerializationMode)e.Value;
  158. break;
  159. }
  160. }
  161. return schemaSerializationMode;
  162. }
  163. protected SchemaSerializationMode DetermineSchemaSerializationMode(XmlReader reader) { //Typed DataSet calls into this
  164. SchemaSerializationMode schemaSerializationMode = SchemaSerializationMode.IncludeSchema;
  165. reader.MoveToContent();
  166. if (reader.NodeType == XmlNodeType.Element) {
  167. if (reader.HasAttributes) {
  168. string attribValue = reader.GetAttribute(Keywords.MSD_SCHEMASERIALIZATIONMODE, Keywords.MSDNS);
  169. if ((String.Compare(attribValue, Keywords.MSD_EXCLUDESCHEMA, StringComparison.OrdinalIgnoreCase) == 0)) {
  170. schemaSerializationMode = SchemaSerializationMode.ExcludeSchema;
  171. }
  172. else if ((String.Compare(attribValue, Keywords.MSD_INCLUDESCHEMA, StringComparison.OrdinalIgnoreCase) == 0)) {
  173. schemaSerializationMode = SchemaSerializationMode.IncludeSchema;
  174. }
  175. else if (attribValue != null) { // if attrib does not exist, then don't throw
  176. throw ExceptionBuilder.InvalidSchemaSerializationMode(typeof(SchemaSerializationMode), attribValue);
  177. }
  178. }
  179. }
  180. return schemaSerializationMode;
  181. }
  182. // Deserialize all the tables data of the dataset from binary/xml stream.
  183. // 'instance' method that consumes SerializationInfo
  184. protected void GetSerializationData(SerializationInfo info, StreamingContext context) {// mainly for typed DS
  185. SerializationFormat remotingFormat = SerializationFormat.Xml;
  186. SerializationInfoEnumerator e = info.GetEnumerator();
  187. while (e.MoveNext()) {
  188. if (e.Name == "DataSet.RemotingFormat") { //DataSet.RemotingFormat does not exist in V1/V1.1 versions
  189. remotingFormat = (SerializationFormat)e.Value;
  190. break;
  191. }
  192. }
  193. DeserializeDataSetData(info, context, remotingFormat);
  194. }
  195. // Deserialize all the tables schema and data of the dataset from binary/xml stream.
  196. protected DataSet(SerializationInfo info, StreamingContext context)
  197. : this(info, context, true) {
  198. }
  199. protected DataSet(SerializationInfo info, StreamingContext context, bool ConstructSchema)
  200. : this() {
  201. SerializationFormat remotingFormat = SerializationFormat.Xml;
  202. SchemaSerializationMode schemaSerializationMode = SchemaSerializationMode.IncludeSchema;
  203. SerializationInfoEnumerator e = info.GetEnumerator();
  204. while (e.MoveNext()) {
  205. switch (e.Name) {
  206. case "DataSet.RemotingFormat": //DataSet.RemotingFormat does not exist in V1/V1.1 versions
  207. remotingFormat = (SerializationFormat)e.Value;
  208. break;
  209. case "SchemaSerializationMode.DataSet": //SchemaSerializationMode.DataSet does not exist in V1/V1.1 versions
  210. schemaSerializationMode = (SchemaSerializationMode)e.Value;
  211. break;
  212. }
  213. }
  214. if (schemaSerializationMode == SchemaSerializationMode.ExcludeSchema) {
  215. InitializeDerivedDataSet();
  216. }
  217. // adding back this check will fix typed dataset XML remoting, but we have to fix case that
  218. // a class inherits from DataSet and just relies on DataSet to deserialize (see SQL BU DT 374717)
  219. // to fix that case also, we need to add a flag and add it to below check so return (no-op) will be
  220. // conditional (flag needs to be set in TypedDataSet
  221. if (remotingFormat == SerializationFormat.Xml && !ConstructSchema /* && this.GetType() != typeof(DataSet)*/) {
  222. return; //For typed dataset xml remoting, this is a no-op
  223. }
  224. DeserializeDataSet(info, context, remotingFormat, schemaSerializationMode);
  225. }
  226. [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
  227. public virtual void GetObjectData(SerializationInfo info, StreamingContext context) {
  228. SerializationFormat remotingFormat = RemotingFormat;
  229. SerializeDataSet(info, context, remotingFormat);
  230. }
  231. // Deserialize all the tables data of the dataset from binary/xml stream.
  232. protected virtual void InitializeDerivedDataSet() {
  233. return;
  234. }
  235. // Serialize all the tables.
  236. private void SerializeDataSet(SerializationInfo info, StreamingContext context, SerializationFormat remotingFormat) {
  237. Debug.Assert(info != null);
  238. info.AddValue("DataSet.RemotingVersion", new Version(2, 0));
  239. // SqlHotFix 299, SerializationFormat enumeration types don't exist in V1.1 SP1
  240. if (SerializationFormat.Xml != remotingFormat) {
  241. info.AddValue("DataSet.RemotingFormat", remotingFormat);
  242. }
  243. // SqlHotFix 299, SchemaSerializationMode enumeration types don't exist in V1.1 SP1
  244. if (SchemaSerializationMode.IncludeSchema != SchemaSerializationMode) {
  245. //SkipSchemaDuringSerialization
  246. info.AddValue("SchemaSerializationMode.DataSet", SchemaSerializationMode);
  247. }
  248. if (remotingFormat != SerializationFormat.Xml) {
  249. if (SchemaSerializationMode == SchemaSerializationMode.IncludeSchema) {
  250. //DataSet public state properties
  251. SerializeDataSetProperties(info, context);
  252. //Tables Count
  253. info.AddValue("DataSet.Tables.Count", Tables.Count);
  254. //Tables, Columns, Rows
  255. for (int i = 0; i < Tables.Count; i++) {
  256. BinaryFormatter bf = new BinaryFormatter(null, new StreamingContext(context.State, false));
  257. MemoryStream memStream = new MemoryStream();
  258. bf.Serialize(memStream, Tables[i]);
  259. memStream.Position = 0;
  260. info.AddValue(String.Format(CultureInfo.InvariantCulture, "DataSet.Tables_{0}", i), memStream.GetBuffer());
  261. }
  262. //Constraints
  263. for (int i = 0; i < Tables.Count; i++) {
  264. Tables[i].SerializeConstraints(info, context, i, true);
  265. }
  266. //Relations
  267. SerializeRelations(info, context);
  268. //Expression Columns
  269. for (int i = 0; i < Tables.Count; i++) {
  270. Tables[i].SerializeExpressionColumns(info, context, i);
  271. }
  272. }
  273. else {
  274. //Serialize DataSet public properties.
  275. SerializeDataSetProperties(info, context);
  276. }
  277. //Rows
  278. for (int i = 0; i < Tables.Count; i++) {
  279. Tables[i].SerializeTableData(info, context, i);
  280. }
  281. } else { // old behaviour
  282. String strSchema = this.GetXmlSchemaForRemoting(null);
  283. String strData = null;
  284. info.AddValue(KEY_XMLSCHEMA, strSchema);
  285. StringBuilder strBuilder;
  286. strBuilder = new StringBuilder(EstimatedXmlStringSize() * 2);
  287. StringWriter strWriter = new StringWriter(strBuilder, CultureInfo.InvariantCulture);
  288. XmlTextWriter w = new XmlTextWriter(strWriter);
  289. WriteXml(w, XmlWriteMode.DiffGram);
  290. strData = strWriter.ToString();
  291. info.AddValue(KEY_XMLDIFFGRAM, strData);
  292. }
  293. }
  294. // Deserialize all the tables - marked internal so that DataTable can call into this
  295. internal void DeserializeDataSet(SerializationInfo info, StreamingContext context, SerializationFormat remotingFormat, SchemaSerializationMode schemaSerializationMode) {
  296. // deserialize schema
  297. DeserializeDataSetSchema(info, context, remotingFormat, schemaSerializationMode);
  298. // deserialize data
  299. DeserializeDataSetData(info, context, remotingFormat);
  300. }
  301. // Deserialize schema.
  302. private void DeserializeDataSetSchema(SerializationInfo info, StreamingContext context, SerializationFormat remotingFormat, SchemaSerializationMode schemaSerializationMode) {
  303. if (remotingFormat != SerializationFormat.Xml) {
  304. if (schemaSerializationMode == SchemaSerializationMode.IncludeSchema) {
  305. //DataSet public state properties
  306. DeserializeDataSetProperties(info, context);
  307. //Tables Count
  308. int tableCount = info.GetInt32("DataSet.Tables.Count");
  309. //Tables, Columns, Rows
  310. for (int i = 0; i < tableCount; i++) {
  311. Byte[] buffer = (Byte[])info.GetValue(String.Format(CultureInfo.InvariantCulture, "DataSet.Tables_{0}", i), typeof(Byte[]));
  312. MemoryStream memStream = new MemoryStream(buffer);
  313. memStream.Position = 0;
  314. BinaryFormatter bf = new BinaryFormatter(null, new StreamingContext(context.State, false));
  315. DataTable dt = (DataTable)bf.Deserialize(memStream);
  316. Tables.Add(dt);
  317. }
  318. //Constraints
  319. for (int i = 0; i < tableCount; i++) {
  320. Tables[i].DeserializeConstraints(info, context, /* table index */i, /* serialize all constraints */ true); //
  321. }
  322. //Relations
  323. DeserializeRelations(info, context);
  324. //Expression Columns
  325. for (int i = 0; i < tableCount; i++) {
  326. Tables[i].DeserializeExpressionColumns(info, context, i);
  327. }
  328. } else {
  329. //DeSerialize DataSet public properties.[Locale, CaseSensitive and EnforceConstraints]
  330. DeserializeDataSetProperties(info, context);
  331. }
  332. } else {
  333. string strSchema = (String)info.GetValue(KEY_XMLSCHEMA, typeof(System.String));
  334. if (strSchema != null) {
  335. this.ReadXmlSchema(new XmlTextReader(new StringReader(strSchema)), true);
  336. }
  337. }
  338. }
  339. // Deserialize all data.
  340. private void DeserializeDataSetData(SerializationInfo info, StreamingContext context, SerializationFormat remotingFormat) {
  341. if (remotingFormat != SerializationFormat.Xml) {
  342. for (int i = 0; i < Tables.Count; i++) {
  343. Tables[i].DeserializeTableData(info, context, i);
  344. }
  345. }
  346. else {
  347. string strData = (String)info.GetValue(KEY_XMLDIFFGRAM, typeof(System.String));
  348. if (strData != null) {
  349. this.ReadXml(new XmlTextReader(new StringReader(strData)), XmlReadMode.DiffGram);
  350. }
  351. }
  352. }
  353. // Serialize just the dataset properties
  354. private void SerializeDataSetProperties(SerializationInfo info, StreamingContext context) {
  355. //DataSet basic properties
  356. info.AddValue("DataSet.DataSetName", DataSetName);
  357. info.AddValue("DataSet.Namespace", Namespace);
  358. info.AddValue("DataSet.Prefix", Prefix);
  359. //DataSet runtime properties
  360. info.AddValue("DataSet.CaseSensitive", CaseSensitive);
  361. info.AddValue("DataSet.LocaleLCID", Locale.LCID);
  362. info.AddValue("DataSet.EnforceConstraints", EnforceConstraints);
  363. //ExtendedProperties
  364. info.AddValue("DataSet.ExtendedProperties", ExtendedProperties);
  365. }
  366. // DeSerialize dataset properties
  367. private void DeserializeDataSetProperties(SerializationInfo info, StreamingContext context) {
  368. //DataSet basic properties
  369. dataSetName = info.GetString("DataSet.DataSetName");
  370. namespaceURI = info.GetString("DataSet.Namespace");
  371. _datasetPrefix = info.GetString("DataSet.Prefix");
  372. //DataSet runtime properties
  373. _caseSensitive = info.GetBoolean("DataSet.CaseSensitive");
  374. int lcid = (int)info.GetValue("DataSet.LocaleLCID", typeof(int));
  375. _culture = new CultureInfo(lcid);
  376. _cultureUserSet = true;
  377. enforceConstraints = info.GetBoolean("DataSet.EnforceConstraints");
  378. //ExtendedProperties
  379. extendedProperties = (PropertyCollection)info.GetValue("DataSet.ExtendedProperties", typeof(PropertyCollection));
  380. }
  381. // Gets relation info from the dataset.
  382. // ***Schema for Serializing ArrayList of Relations***
  383. // Relations -> [relationName]->[parentTableIndex, parentcolumnIndexes]->[childTableIndex, childColumnIndexes]->[Nested]->[extendedProperties]
  384. private void SerializeRelations(SerializationInfo info, StreamingContext context) {
  385. ArrayList relationList = new ArrayList();
  386. foreach (DataRelation rel in Relations) {
  387. int[] parentInfo = new int[rel.ParentColumns.Length + 1];
  388. parentInfo[0] = Tables.IndexOf(rel.ParentTable);
  389. for (int j = 1; j < parentInfo.Length; j++) {
  390. parentInfo[j] = rel.ParentColumns[j - 1].Ordinal;
  391. }
  392. int[] childInfo = new int[rel.ChildColumns.Length + 1];
  393. childInfo[0] = Tables.IndexOf(rel.ChildTable);
  394. for (int j = 1; j < childInfo.Length; j++) {
  395. childInfo[j] = rel.ChildColumns[j - 1].Ordinal;
  396. }
  397. ArrayList list = new ArrayList();
  398. list.Add(rel.RelationName);
  399. list.Add(parentInfo);
  400. list.Add(childInfo);
  401. list.Add(rel.Nested);
  402. list.Add(rel.extendedProperties);
  403. relationList.Add(list);
  404. }
  405. info.AddValue("DataSet.Relations", relationList);
  406. }
  407. /*
  408. Adds relations to the dataset.
  409. ***Schema for Serializing ArrayList of Relations***
  410. Relations -> [relationName]->[parentTableIndex, parentcolumnIndexes]->[childTableIndex, childColumnIndexes]->[Nested]->[extendedProperties]
  411. */
  412. private void DeserializeRelations(SerializationInfo info, StreamingContext context) {
  413. ArrayList relationList = (ArrayList)info.GetValue("DataSet.Relations", typeof(ArrayList));
  414. foreach (ArrayList list in relationList) {
  415. string relationName = (string)list[0];
  416. int[] parentInfo = (int[])list[1];
  417. int[] childInfo = (int[])list[2];
  418. bool isNested = (bool)list[3];
  419. PropertyCollection extendedProperties = (PropertyCollection)list[4];
  420. //ParentKey Columns.
  421. DataColumn[] parentkeyColumns = new DataColumn[parentInfo.Length - 1];
  422. for (int i = 0; i < parentkeyColumns.Length; i++) {
  423. parentkeyColumns[i] = Tables[parentInfo[0]].Columns[parentInfo[i + 1]];
  424. }
  425. //ChildKey Columns.
  426. DataColumn[] childkeyColumns = new DataColumn[childInfo.Length - 1];
  427. for (int i = 0; i < childkeyColumns.Length; i++) {
  428. childkeyColumns[i] = Tables[childInfo[0]].Columns[childInfo[i + 1]];
  429. }
  430. //Create the Relation, without any constraints[Assumption: The constraints are added earlier than the relations]
  431. DataRelation rel = new DataRelation(relationName, parentkeyColumns, childkeyColumns, false);
  432. rel.CheckMultipleNested = false; // disable the check for multiple nested parent
  433. rel.Nested = isNested;
  434. rel.extendedProperties = extendedProperties;
  435. Relations.Add(rel);
  436. rel.CheckMultipleNested = true; // enable the check for multiple nested parent
  437. }
  438. }
  439. internal void FailedEnableConstraints() {
  440. this.EnforceConstraints = false;
  441. throw ExceptionBuilder.EnforceConstraint();
  442. }
  443. /// <devdoc>
  444. /// <para>
  445. /// Gets or sets a value indicating whether string
  446. /// comparisons within <see cref='System.Data.DataTable'/>
  447. /// objects are
  448. /// case-sensitive.
  449. /// </para>
  450. /// </devdoc>
  451. [
  452. ResCategoryAttribute(Res.DataCategory_Data),
  453. DefaultValue(false),
  454. ResDescriptionAttribute(Res.DataSetCaseSensitiveDescr)
  455. ]
  456. public bool CaseSensitive {
  457. get {
  458. return _caseSensitive;
  459. }
  460. set {
  461. if (_caseSensitive != value)
  462. {
  463. bool oldValue = _caseSensitive;
  464. _caseSensitive = value;
  465. if (!ValidateCaseConstraint()) {
  466. _caseSensitive = oldValue;
  467. throw ExceptionBuilder.CannotChangeCaseLocale();
  468. }
  469. foreach (DataTable table in Tables) {
  470. table.SetCaseSensitiveValue(value, false, true);
  471. }
  472. }
  473. }
  474. }
  475. bool System.ComponentModel.IListSource.ContainsListCollection {
  476. get {
  477. return true;
  478. }
  479. }
  480. /// <devdoc>
  481. /// <para>Gets a custom view of the data contained by the <see cref='System.Data.DataSet'/> , one
  482. /// that allows filtering, searching, and navigating through the custom data view.</para>
  483. /// </devdoc>
  484. [Browsable(false), ResDescriptionAttribute(Res.DataSetDefaultViewDescr)]
  485. public DataViewManager DefaultViewManager {
  486. get {
  487. if (defaultViewManager == null) {
  488. lock (_defaultViewManagerLock) {
  489. if (defaultViewManager == null) {
  490. defaultViewManager = new DataViewManager(this, true);
  491. }
  492. }
  493. }
  494. return defaultViewManager;
  495. }
  496. }
  497. /// <devdoc>
  498. /// <para>Gets or sets a value indicating whether constraint rules are followed when
  499. /// attempting any update operation.</para>
  500. /// </devdoc>
  501. [DefaultValue(true), ResDescriptionAttribute(Res.DataSetEnforceConstraintsDescr)]
  502. public bool EnforceConstraints {
  503. get {
  504. return enforceConstraints;
  505. }
  506. set {
  507. IntPtr hscp;
  508. Bid.ScopeEnter(out hscp, "<ds.DataSet.set_EnforceConstraints|API> %d#, %d{bool}\n", ObjectID, value);
  509. try {
  510. if (this.enforceConstraints != value) {
  511. if (value)
  512. EnableConstraints();
  513. this.enforceConstraints = value;
  514. }
  515. }
  516. finally {
  517. Bid.ScopeLeave(ref hscp);
  518. }
  519. }
  520. }
  521. internal void RestoreEnforceConstraints(bool value) {
  522. this.enforceConstraints = value;
  523. }
  524. internal void EnableConstraints()
  525. {
  526. IntPtr hscp;
  527. Bid.ScopeEnter(out hscp, "<ds.DataSet.EnableConstraints|INFO> %d#\n", ObjectID);
  528. try {
  529. bool errors = false;
  530. for (ConstraintEnumerator constraints = new ConstraintEnumerator(this); constraints.GetNext(); ) {
  531. Constraint constraint = (Constraint)constraints.GetConstraint();
  532. errors |= constraint.IsConstraintViolated();
  533. }
  534. foreach (DataTable table in Tables) {
  535. foreach (DataColumn column in table.Columns) {
  536. if (!column.AllowDBNull) {
  537. errors |= column.IsNotAllowDBNullViolated();
  538. }
  539. if (column.MaxLength >= 0) {
  540. errors |= column.IsMaxLengthViolated();
  541. }
  542. }
  543. }
  544. if (errors)
  545. this.FailedEnableConstraints();
  546. }
  547. finally {
  548. Bid.ScopeLeave(ref hscp);
  549. }
  550. }
  551. /// <devdoc>
  552. /// <para>Gets or
  553. /// sets the name of this <see cref='System.Data.DataSet'/> .</para>
  554. /// </devdoc>
  555. [
  556. ResCategoryAttribute(Res.DataCategory_Data),
  557. DefaultValue(""),
  558. ResDescriptionAttribute(Res.DataSetDataSetNameDescr)
  559. ]
  560. public string DataSetName {
  561. get {
  562. return dataSetName;
  563. }
  564. set {
  565. Bid.Trace("<ds.DataSet.set_DataSetName|API> %d#, '%ls'\n", ObjectID, value);
  566. if (value != dataSetName) {
  567. if (value == null || value.Length == 0)
  568. throw ExceptionBuilder.SetDataSetNameToEmpty();
  569. DataTable conflicting = Tables[value, Namespace];
  570. if ((conflicting != null) && (!conflicting.fNestedInDataset))
  571. throw ExceptionBuilder.SetDataSetNameConflicting(value);
  572. RaisePropertyChanging("DataSetName");
  573. this.dataSetName = value;
  574. }
  575. }
  576. }
  577. /// <devdoc>
  578. /// </devdoc>
  579. [
  580. DefaultValue(""),
  581. ResCategoryAttribute(Res.DataCategory_Data),
  582. ResDescriptionAttribute(Res.DataSetNamespaceDescr)
  583. ]
  584. public string Namespace {
  585. get {
  586. return namespaceURI;
  587. }
  588. set {
  589. Bid.Trace("<ds.DataSet.set_Namespace|API> %d#, '%ls'\n", ObjectID, value);
  590. if (value == null)
  591. value = String.Empty;
  592. if (value != namespaceURI) {
  593. RaisePropertyChanging("Namespace");
  594. foreach (DataTable dt in Tables) {
  595. if (dt.tableNamespace != null)
  596. continue;
  597. if ((dt.NestedParentRelations.Length == 0) ||
  598. (dt.NestedParentRelations.Length == 1 && dt.NestedParentRelations[0].ChildTable == dt)) {
  599. // dt.SelfNestedWithOneRelation) { // this is wrong bug it was previous behavior
  600. if (Tables.Contains(dt.TableName, value, false, true))
  601. throw ExceptionBuilder.DuplicateTableName2(dt.TableName, value);
  602. dt.CheckCascadingNamespaceConflict(value);
  603. dt.DoRaiseNamespaceChange();
  604. }
  605. }
  606. namespaceURI = value;
  607. if (Common.ADP.IsEmpty(value))
  608. _datasetPrefix = String.Empty;
  609. }
  610. }
  611. }
  612. /// <devdoc>
  613. /// <para>[To be supplied.]</para>
  614. /// </devdoc>
  615. [
  616. DefaultValue(""),
  617. ResCategoryAttribute(Res.DataCategory_Data),
  618. ResDescriptionAttribute(Res.DataSetPrefixDescr)
  619. ]
  620. public string Prefix {
  621. get { return _datasetPrefix; }
  622. set {
  623. if (value == null)
  624. value = String.Empty;
  625. if ((XmlConvert.DecodeName(value) == value) &&
  626. (XmlConvert.EncodeName(value) != value))
  627. throw ExceptionBuilder.InvalidPrefix(value);
  628. if (value != _datasetPrefix) {
  629. RaisePropertyChanging("Prefix");
  630. _datasetPrefix = value;
  631. }
  632. }
  633. }
  634. /// <devdoc>
  635. /// <para>Gets the collection of custom user information.</para>
  636. /// </devdoc>
  637. [
  638. ResCategoryAttribute(Res.DataCategory_Data),
  639. Browsable(false),
  640. ResDescriptionAttribute(Res.ExtendedPropertiesDescr)
  641. ]
  642. public PropertyCollection ExtendedProperties {
  643. get {
  644. if (extendedProperties == null) {
  645. extendedProperties = new PropertyCollection();
  646. }
  647. return extendedProperties;
  648. }
  649. }
  650. /// <devdoc>
  651. /// <para>
  652. /// Gets a value indicating whether there are errors in any
  653. /// of the rows in any of the tables of this <see cref='System.Data.DataSet'/> .
  654. /// </para>
  655. /// </devdoc>
  656. [Browsable(false), ResDescriptionAttribute(Res.DataSetHasErrorsDescr)]
  657. public bool HasErrors {
  658. get {
  659. for (int i = 0; i < Tables.Count; i++) {
  660. if (Tables[i].HasErrors)
  661. return true;
  662. }
  663. return false;
  664. }
  665. }
  666. [Browsable(false)]
  667. public bool IsInitialized {
  668. get {
  669. return !fInitInProgress;
  670. }
  671. }
  672. /// <devdoc>
  673. /// <para>
  674. /// Gets or sets the locale information used to compare strings within the table.
  675. /// </para>
  676. /// </devdoc>
  677. [
  678. ResCategoryAttribute(Res.DataCategory_Data),
  679. ResDescriptionAttribute(Res.DataSetLocaleDescr)
  680. ]
  681. public CultureInfo Locale {
  682. get {
  683. // used for comparing not formating/parsing
  684. Debug.Assert(null != _culture, "DataSet.Locale: null culture");
  685. return _culture;
  686. }
  687. set {
  688. IntPtr hscp;
  689. Bid.ScopeEnter(out hscp, "<ds.DataSet.set_Locale|API> %d#\n", ObjectID);
  690. try {
  691. if (value != null) {
  692. if (!_culture.Equals(value)) {
  693. SetLocaleValue(value, true);
  694. }
  695. _cultureUserSet = true;
  696. }
  697. }
  698. finally {
  699. Bid.ScopeLeave(ref hscp);
  700. }
  701. }
  702. }
  703. internal void SetLocaleValue(CultureInfo value, bool userSet) {
  704. bool flag = false;
  705. bool exceptionThrown = false;
  706. int tableCount = 0;
  707. CultureInfo oldLocale = _culture;
  708. bool oldUserSet = _cultureUserSet;
  709. try {
  710. _culture = value;
  711. _cultureUserSet = userSet;
  712. foreach (DataTable table in Tables) {
  713. if (!table.ShouldSerializeLocale()) {
  714. bool retchk = table.SetLocaleValue(value, false, false);
  715. //Debug.Assert(retchk == table.ShouldSerializeLocale(), "unexpected setting of table locale"); may fire with Deserialize
  716. }
  717. }
  718. flag = ValidateLocaleConstraint();
  719. if (flag) {
  720. flag = false;
  721. foreach (DataTable table in Tables) {
  722. tableCount++;
  723. if (!table.ShouldSerializeLocale()) {
  724. table.SetLocaleValue(value, false, true);
  725. }
  726. }
  727. flag = true;
  728. }
  729. }
  730. catch {
  731. exceptionThrown = true;
  732. throw;
  733. }
  734. finally {
  735. if (!flag) { // reset old locale if ValidationFailed or exception thrown
  736. _culture = oldLocale;
  737. _cultureUserSet = oldUserSet;
  738. foreach (DataTable table in Tables) {
  739. if (!table.ShouldSerializeLocale()) {
  740. table.SetLocaleValue(oldLocale, false, false);
  741. }
  742. }
  743. try {
  744. for (int i = 0; i < tableCount; ++i) {
  745. if (!Tables[i].ShouldSerializeLocale()) {
  746. Tables[i].SetLocaleValue(oldLocale, false, true);
  747. }
  748. }
  749. }
  750. catch (Exception e) {
  751. if (!Common.ADP.IsCatchableExceptionType(e)) {
  752. throw;
  753. }
  754. Common.ADP.TraceExceptionWithoutRethrow(e);
  755. }
  756. if (!exceptionThrown) {
  757. throw ExceptionBuilder.CannotChangeCaseLocale(null);
  758. }
  759. }
  760. }
  761. }
  762. internal bool ShouldSerializeLocale() {
  763. // this method is used design-time scenarios via reflection
  764. // by the property grid to show the Locale property in bold or not
  765. // by the code dom for persisting the Locale property or not
  766. // we always want the locale persisted if set by user or different the current thread
  767. // but that logic should by performed by the serializion code
  768. return _cultureUserSet;
  769. }
  770. /// <devdoc>
  771. /// <para>[To be supplied.]</para>
  772. /// </devdoc>
  773. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
  774. public override ISite Site {
  775. get {
  776. return base.Site;
  777. }
  778. set {
  779. ISite oldSite = Site;
  780. if (value == null && oldSite != null) {
  781. IContainer cont = oldSite.Container;
  782. if (cont != null) {
  783. for (int i = 0; i < Tables.Count; i++) {
  784. if (Tables[i].Site != null) {
  785. cont.Remove(Tables[i]);
  786. }
  787. }
  788. }
  789. }
  790. base.Site = value;
  791. }
  792. }
  793. /// <devdoc>
  794. /// <para>
  795. /// Get the collection of relations that link tables and
  796. /// allow navigation from parent tables to child tables.
  797. /// </para>
  798. /// </devdoc>
  799. [
  800. DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
  801. ResCategoryAttribute(Res.DataCategory_Data),
  802. ResDescriptionAttribute(Res.DataSetRelationsDescr)
  803. ]
  804. public DataRelationCollection Relations {
  805. get {
  806. return relationCollection;
  807. }
  808. }
  809. /// <devdoc>
  810. /// <para>
  811. /// Indicates whether <see cref='Relations'/> property should be persisted.
  812. /// </para>
  813. /// </devdoc>
  814. protected virtual bool ShouldSerializeRelations() {
  815. return true; /*Relations.Count > 0;*/ // VS7 300569
  816. }
  817. /// <devdoc>
  818. /// <para>
  819. /// Resets the <see cref='System.Data.DataSet.Relations'/> property to its default state.
  820. /// </para>
  821. /// </devdoc>
  822. private void ResetRelations()
  823. {
  824. Relations.Clear();
  825. }
  826. /// <devdoc>
  827. /// <para>Gets the collection of tables contained in the <see cref='System.Data.DataSet'/>.</para>
  828. /// </devdoc>
  829. [
  830. DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
  831. ResCategoryAttribute(Res.DataCategory_Data),
  832. ResDescriptionAttribute(Res.DataSetTablesDescr)
  833. ]
  834. public DataTableCollection Tables {
  835. get {
  836. return tableCollection;
  837. }
  838. }
  839. /// <devdoc>
  840. /// <para>
  841. /// Indicates whether <see cref='System.Data.DataSet.Tables'/> property should be persisted.
  842. /// </para>
  843. /// </devdoc>
  844. protected virtual bool ShouldSerializeTables() {
  845. return true;/*(Tables.Count > 0);*/ // VS7 300569
  846. }
  847. /// <devdoc>
  848. /// <para>
  849. /// Resets the <see cref='System.Data.DataSet.Tables'/> property to its default state.
  850. /// </para>
  851. /// </devdoc>
  852. private void ResetTables()
  853. {
  854. Tables.Clear();
  855. }
  856. internal bool FBoundToDocument {
  857. get {
  858. return fBoundToDocument;
  859. }
  860. set {
  861. fBoundToDocument = value;
  862. }
  863. }
  864. /// <devdoc>
  865. /// <para>
  866. /// Commits all the changes made to this <see cref='System.Data.DataSet'/> since it was loaded or the last
  867. /// time <see cref='System.Data.DataSet.AcceptChanges'/> was called.
  868. /// </para>
  869. /// </devdoc>
  870. public void AcceptChanges()
  871. {
  872. IntPtr hscp;
  873. Bid.ScopeEnter(out hscp, "<ds.DataSet.AcceptChanges|API> %d#\n", ObjectID);
  874. try {
  875. for (int i = 0; i < Tables.Count; i++)
  876. Tables[i].AcceptChanges();
  877. }
  878. finally {
  879. Bid.ScopeLeave(ref hscp);
  880. }
  881. }
  882. internal event PropertyChangedEventHandler PropertyChanging {
  883. add {
  884. onPropertyChangingDelegate += value;
  885. }
  886. remove {
  887. onPropertyChangingDelegate -= value;
  888. }
  889. }
  890. /// <devdoc>
  891. /// <para>Occurs when attempting to merge schemas for two tables with the same
  892. /// name.</para>
  893. /// </devdoc>
  894. [
  895. ResCategoryAttribute(Res.DataCategory_Action),
  896. ResDescriptionAttribute(Res.DataSetMergeFailedDescr)
  897. ]
  898. public event MergeFailedEventHandler MergeFailed {
  899. add {
  900. onMergeFailed += value;
  901. }
  902. remove {
  903. onMergeFailed -= value;
  904. }
  905. }
  906. internal event DataRowCreatedEventHandler DataRowCreated {
  907. add {
  908. onDataRowCreated += value;
  909. }
  910. remove {
  911. onDataRowCreated -= value;
  912. }
  913. }
  914. internal event DataSetClearEventhandler ClearFunctionCalled {
  915. add {
  916. onClearFunctionCalled += value;
  917. }
  918. remove {
  919. onClearFunctionCalled -= value;
  920. }
  921. }
  922. [
  923. ResCategoryAttribute(Res.DataCategory_Action),
  924. ResDescriptionAttribute(Res.DataSetInitializedDescr)
  925. ]
  926. public event System.EventHandler Initialized {
  927. add {
  928. onInitialized += value;
  929. }
  930. remove {
  931. onInitialized -= value;
  932. }
  933. }
  934. public void BeginInit() {
  935. fInitInProgress = true;
  936. }
  937. public void EndInit() {
  938. Tables.FinishInitCollection();
  939. for (int i = 0; i < Tables.Count; i++) {
  940. Tables[i].Columns.FinishInitCollection();
  941. }
  942. for (int i = 0; i < Tables.Count; i++) {
  943. Tables[i].Constraints.FinishInitConstraints();
  944. }
  945. ((DataRelationCollection.DataSetRelationCollection)Relations).FinishInitRelations();
  946. fInitInProgress = false;
  947. OnInitialized();
  948. }
  949. /// <devdoc>
  950. /// <para>Clears the <see cref='System.Data.DataSet'/> of any data by removing all rows in all tables.</para>
  951. /// </devdoc>
  952. public void Clear()
  953. {
  954. IntPtr hscp;
  955. Bid.ScopeEnter(out hscp, "<ds.DataSet.Clear|API> %d#\n", ObjectID);
  956. try {
  957. OnClearFunctionCalled(null);
  958. bool fEnforce = EnforceConstraints;
  959. EnforceConstraints = false;
  960. for (int i = 0; i < Tables.Count; i++)
  961. Tables[i].Clear();
  962. EnforceConstraints = fEnforce;
  963. }
  964. finally {
  965. Bid.ScopeLeave(ref hscp);
  966. }
  967. }
  968. /// <devdoc>
  969. /// <para>Clones the structure of the <see cref='System.Data.DataSet'/>, including all <see cref='System.Data.DataTable'/> schemas, relations, and
  970. /// constraints.</para>
  971. /// </devdoc>
  972. // Prevent inlining so that reflection calls are not moved to caller that may be in a different assembly that may have a different grant set.
  973. [MethodImpl(MethodImplOptions.NoInlining)]
  974. public virtual DataSet Clone() {
  975. IntPtr hscp;
  976. Bid.ScopeEnter(out hscp, "<ds.DataSet.Clone|API> %d#\n", ObjectID);
  977. try {
  978. DataSet ds = (DataSet)Activator.CreateInstance(this.GetType(), true);
  979. if (ds.Tables.Count > 0) // [....] : To clean up all the schema in strong typed dataset.
  980. ds.Reset();
  981. //copy some original dataset properties
  982. ds.DataSetName = DataSetName;
  983. ds.CaseSensitive = CaseSensitive;
  984. ds._culture = _culture;
  985. ds._cultureUserSet = _cultureUserSet;
  986. ds.EnforceConstraints = EnforceConstraints;
  987. ds.Namespace = Namespace;
  988. ds.Prefix = Prefix;
  989. ds.RemotingFormat = RemotingFormat;
  990. ds.fIsSchemaLoading = true; //delay expression evaluation
  991. // ...Tables...
  992. DataTableCollection tbls = Tables;
  993. for (int i = 0; i < tbls.Count; i++) {
  994. DataTable dt = tbls[i].Clone(ds);
  995. dt.tableNamespace = tbls[i].Namespace; // hardcode the namespace for a second to not mess up
  996. // DataRelation cloning.
  997. ds.Tables.Add(dt);
  998. }
  999. // ...Constraints...
  1000. for (int i = 0; i < tbls.Count; i++) {
  1001. ConstraintCollection constraints = tbls[i].Constraints;
  1002. for (int j = 0; j < constraints.Count; j++) {
  1003. if (constraints[j] is UniqueConstraint)
  1004. continue;
  1005. ForeignKeyConstraint foreign = constraints[j] as ForeignKeyConstraint;
  1006. if (foreign.Table == foreign.RelatedTable)
  1007. continue;// we have already added this foreign key in while cloning the datatable
  1008. ds.Tables[i].Constraints.Add(constraints[j].Clone(ds));
  1009. }
  1010. }
  1011. // ...Relations...
  1012. DataRelationCollection rels = Relations;
  1013. for (int i = 0; i < rels.Count; i++) {
  1014. DataRelation rel = rels[i].Clone(ds);
  1015. rel.CheckMultipleNested = false; // disable the check for multiple nested parent
  1016. ds.Relations.Add(rel);
  1017. rel.CheckMultipleNested = true; // enable the check for multiple nested parent
  1018. }
  1019. // ...Extended Properties...
  1020. if (this.extendedProperties != null) {
  1021. foreach (Object key in this.extendedProperties.Keys) {
  1022. ds.ExtendedProperties[key] = this.extendedProperties[key];
  1023. }
  1024. }
  1025. foreach (DataTable table in Tables)
  1026. foreach (DataColumn col in table.Columns)
  1027. if (col.Expression.Length != 0)
  1028. ds.Tables[table.TableName, table.Namespace].Columns[col.ColumnName].Expression = col.Expression;
  1029. for (int i = 0; i < tbls.Count; i++) {
  1030. ds.Tables[i].tableNamespace = tbls[i].tableNamespace; // undo the hardcoding of the namespace
  1031. }
  1032. ds.fIsSchemaLoading = false; //reactivate column computations
  1033. return ds;
  1034. }
  1035. finally {
  1036. Bid.ScopeLeave(ref hscp);
  1037. }
  1038. }
  1039. /// <devdoc>
  1040. /// <para>Copies both the structure and data for this <see cref='System.Data.DataSet'/>.</para>
  1041. /// </devdoc>
  1042. public DataSet Copy()
  1043. {
  1044. IntPtr hscp;
  1045. Bid.ScopeEnter(out hscp, "<ds.DataSet.Copy|API> %d#\n", ObjectID);
  1046. try {
  1047. DataSet dsNew = Clone();
  1048. bool fEnforceConstraints = dsNew.EnforceConstraints;
  1049. dsNew.EnforceConstraints = false;
  1050. foreach (DataTable table in this.Tables)
  1051. {
  1052. DataTable destTable = dsNew.Tables[table.TableName, table.Namespace];
  1053. foreach (DataRow row in table.Rows)
  1054. table.CopyRow(destTable, row);
  1055. }
  1056. dsNew.EnforceConstraints = fEnforceConstraints;
  1057. return dsNew;
  1058. }
  1059. finally {
  1060. Bid.ScopeLeave(ref hscp);
  1061. }
  1062. }
  1063. internal Int32 EstimatedXmlStringSize()
  1064. {
  1065. Int32 bytes = 100;
  1066. for (int i = 0; i < Tables.Count; i++) {
  1067. Int32 rowBytes = (Tables[i].TableName.Length + 4) << 2;
  1068. DataTable table = Tables[i];
  1069. for (int j = 0; j < table.Columns.Count; j++) {
  1070. rowBytes += ((table.Columns[j].ColumnName.Length + 4) << 2);
  1071. rowBytes += 20;
  1072. }
  1073. bytes += table.Rows.Count * rowBytes;
  1074. }
  1075. return bytes;
  1076. }
  1077. /// <devdoc>
  1078. /// <para>Returns a copy of the <see cref='System.Data.DataSet'/> that contains all changes made to
  1079. /// it since it was loaded or <see cref='System.Data.DataSet.AcceptChanges'/>
  1080. /// was last called.</para>
  1081. /// </devdoc>
  1082. public DataSet GetChanges()
  1083. {
  1084. return GetChanges(DataRowState.Added | DataRowState.Deleted | DataRowState.Modified);
  1085. }
  1086. private struct TableChanges {
  1087. private BitArray _rowChanges;
  1088. private int _hasChanges;
  1089. internal TableChanges(int rowCount) {
  1090. _rowChanges = new BitArray(rowCount);
  1091. _hasChanges = 0;
  1092. }
  1093. internal int HasChanges {
  1094. get { return _hasChanges; }
  1095. set { _hasChanges = value; }
  1096. }
  1097. internal bool this[int index] {
  1098. get { return _rowChanges[index]; }
  1099. set {
  1100. Debug.Assert(value && !_rowChanges[index], "setting twice or to false");
  1101. _rowChanges[index] = value;
  1102. _hasChanges++;
  1103. }
  1104. }
  1105. }
  1106. public DataSet GetChanges(DataRowState rowStates)
  1107. {
  1108. IntPtr hscp;
  1109. Bid.ScopeEnter(out hscp, "<ds.DataSet.GetChanges|API> %d#, rowStates=%d{ds.DataRowState}\n", ObjectID, (int)rowStates);
  1110. try {
  1111. DataSet dsNew = null;
  1112. bool fEnforceConstraints = false;
  1113. if (0 != (rowStates & ~(DataRowState.Added | DataRowState.Deleted | DataRowState.Modified | DataRowState.Unchanged))) {
  1114. throw ExceptionBuilder.InvalidRowState(rowStates);
  1115. }
  1116. // Initialize all the individual table bitmaps.
  1117. TableChanges[] bitMatrix = new TableChanges[Tables.Count];
  1118. for (int i = 0; i < bitMatrix.Length; ++i) {
  1119. bitMatrix[i] = new TableChanges(Tables[i].Rows.Count);
  1120. }
  1121. // find all the modified rows and their parents
  1122. MarkModifiedRows(bitMatrix, rowStates);
  1123. // copy the changes to a cloned table
  1124. for (int i = 0; i < bitMatrix.Length; ++i) {
  1125. Debug.Assert(0 <= bitMatrix[i].HasChanges, "negative change count");
  1126. if (0 < bitMatrix[i].HasChanges) {
  1127. if (null == dsNew) {
  1128. dsNew = this.Clone();
  1129. fEnforceConstraints = dsNew.EnforceConstraints;
  1130. dsNew.EnforceConstraints = false;
  1131. }
  1132. DataTable table = this.Tables[i];
  1133. DataTable destTable = dsNew.Tables[table.TableName, table.Namespace];
  1134. Debug.Assert(bitMatrix[i].HasChanges <= table.Rows.Count, "to many changes");
  1135. for (int j = 0; 0 < bitMatrix[i].HasChanges; ++j) { // Loop through the rows.
  1136. if (bitMatrix[i][j]) {
  1137. table.CopyRow(destTable, table.Rows[j]);
  1138. bitMatrix[i].HasChanges--;
  1139. }
  1140. }
  1141. }
  1142. }
  1143. if (null != dsNew) {
  1144. dsNew.EnforceConstraints = fEnforceConstraints;
  1145. }
  1146. return dsNew;
  1147. }
  1148. finally {
  1149. Bid.ScopeLeave(ref hscp);
  1150. }
  1151. }
  1152. private void MarkModifiedRows(TableChanges[] bitMatrix, DataRowState rowStates) {
  1153. // for every table, every row & every relation find the modified rows and for non-deleted rows, their parents
  1154. for (int tableIndex = 0; tableIndex < bitMatrix.Length; ++tableIndex) {
  1155. DataRowCollection rows = Tables[tableIndex].Rows;
  1156. int rowCount = rows.Count;
  1157. for (int rowIndex = 0; rowIndex < rowCount; ++rowIndex) {
  1158. DataRow row = rows[rowIndex];
  1159. DataRowState rowState = row.RowState;
  1160. Debug.Assert(DataRowState.Added == rowState ||
  1161. DataRowState.Deleted == rowState ||
  1162. DataRowState.Modified == rowState ||
  1163. DataRowState.Unchanged == rowState,
  1164. "unexpected DataRowState");
  1165. // if bit not already set and row is modified
  1166. if ((0 != (rowStates & rowState)) && !bitMatrix[tableIndex][rowIndex]) {
  1167. bitMatrix[tableIndex][rowIndex] = true;
  1168. if (DataRowState.Deleted != rowState) {
  1169. MarkRelatedRowsAsModified(bitMatrix, row);
  1170. }
  1171. }
  1172. }
  1173. }
  1174. }
  1175. private void MarkRelatedRowsAsModified(TableChanges[] bitMatrix, DataRow row) {
  1176. DataRelationCollection relations = row.Table.ParentRelations;
  1177. int relationCount = relations.Count;
  1178. for (int relatedIndex = 0; relatedIndex < relationCount; ++relatedIndex) {
  1179. DataRow[] relatedRows = row.GetParentRows(relations[relatedIndex], DataRowVersion.Current);
  1180. foreach (DataRow relatedRow in relatedRows) {
  1181. int relatedTableIndex = this.Tables.IndexOf(relatedRow.Table);
  1182. int relatedRowIndex = relatedRow.Table.Rows.IndexOf(relatedRow);
  1183. if (!bitMatrix[relatedTableIndex][relatedRowIndex]) {
  1184. bitMatrix[relatedTableIndex][relatedRowIndex] = true;
  1185. if (DataRowState.Deleted != relatedRow.RowState) {
  1186. // recurse into related rows
  1187. MarkRelatedRowsAsModified(bitMatrix, relatedRow);
  1188. }
  1189. }
  1190. }
  1191. }
  1192. }
  1193. IList System.ComponentModel.IListSource.GetList() {
  1194. return DefaultViewManager;
  1195. }
  1196. internal string GetRemotingDiffGram(DataTable table)
  1197. {
  1198. StringWriter strWriter = new StringWriter(CultureInfo.InvariantCulture);
  1199. XmlTextWriter writer = new XmlTextWriter(strWriter);
  1200. writer.Formatting = Formatting.Indented;
  1201. if (strWriter != null) {
  1202. // Create and save the updates
  1203. new NewDiffgramGen(table, false).Save(writer, table);
  1204. }
  1205. return strWriter.ToString();
  1206. }
  1207. public string GetXml()
  1208. {
  1209. IntPtr hscp;
  1210. Bid.ScopeEnter(out hscp, "<ds.DataSet.GetXml|API> %d#\n", ObjectID);
  1211. try {
  1212. // StringBuilder strBuilder = new StringBuilder(EstimatedXmlStringSize());
  1213. // StringWriter strWriter = new StringWriter(strBuilder);
  1214. StringWriter strWriter = new StringWriter(CultureInfo.InvariantCulture);
  1215. if (strWriter != null) {
  1216. XmlTextWriter w = new XmlTextWriter(strWriter);
  1217. w.Formatting = Formatting.Indented;
  1218. new XmlDataTreeWriter(this).Save(w, false);
  1219. }
  1220. return strWriter.ToString();
  1221. }
  1222. finally {
  1223. Bid.ScopeLeave(ref hscp);
  1224. }
  1225. }
  1226. public string GetXmlSchema()
  1227. {
  1228. IntPtr hscp;
  1229. Bid.ScopeEnter(out hscp, "<ds.DataSet.GetXmlSchema|API> %d#\n", ObjectID);
  1230. try {
  1231. StringWriter strWriter = new StringWriter(CultureInfo.InvariantCulture);
  1232. XmlTextWriter writer = new XmlTextWriter(strWriter);
  1233. writer.Formatting = Formatting.Indented;
  1234. if (strWriter != null) {
  1235. (new XmlTreeGen(SchemaFormat.Public)).Save(this, writer);
  1236. }
  1237. return strWriter.ToString();
  1238. }
  1239. finally {
  1240. Bid.ScopeLeave(ref hscp);
  1241. }
  1242. }
  1243. internal string GetXmlSchemaForRemoting(DataTable table)
  1244. {
  1245. StringWriter strWriter = new StringWriter(CultureInfo.InvariantCulture);
  1246. XmlTextWriter writer = new XmlTextWriter(strWriter);
  1247. writer.Formatting = Formatting.Indented;
  1248. if (strWriter != null) {
  1249. if (table == null) {
  1250. if (this.SchemaSerializationMode == SchemaSerializationMode.ExcludeSchema)
  1251. (new XmlTreeGen(SchemaFormat.RemotingSkipSchema)).Save(this, writer);
  1252. else
  1253. (new XmlTreeGen(SchemaFormat.Remoting)).Save(this, writer);
  1254. }
  1255. else { // no skip schema support for typed datatable
  1256. (new XmlTreeGen(SchemaFormat.Remoting)).Save(table, writer);
  1257. }
  1258. }
  1259. return strWriter.ToString();
  1260. }
  1261. /// <devdoc>
  1262. /// <para>Gets a value indicating whether the <see cref='System.Data.DataSet'/> has changes, including new,
  1263. /// deleted, or modified rows.</para>
  1264. /// </devdoc>
  1265. public bool HasChanges()
  1266. {
  1267. return HasChanges(DataRowState.Added | DataRowState.Deleted | DataRowState.Modified);
  1268. }
  1269. /// <devdoc>
  1270. /// <para>Gets a value indicating whether the <see cref='System.Data.DataSet'/> has changes, including new,
  1271. /// deleted, or modified rows, filtered by <see cref='System.Data.DataRowState'/>.</para>
  1272. /// </devdoc>
  1273. public bool HasChanges(DataRowState rowStates)
  1274. {
  1275. IntPtr hscp;
  1276. Bid.ScopeEnter(out hscp, "<ds.DataSet.HasChanges|API> %d#, rowStates=%d{ds.DataRowState}\n", ObjectID, (int)rowStates);
  1277. try {
  1278. const DataRowState allRowStates = DataRowState.Detached | DataRowState.Unchanged | DataRowState.Added | DataRowState.Deleted | DataRowState.Modified;
  1279. if ((rowStates & (~allRowStates)) != 0) {
  1280. throw ExceptionBuilder.ArgumentOutOfRange("rowState");
  1281. }
  1282. for (int i = 0; i < Tables.Count; i++) {
  1283. DataTable table = Tables[i];
  1284. for (int j = 0; j < table.Rows.Count; j++) {
  1285. DataRow row = table.Rows[j];
  1286. if ((row.RowState & rowStates) != 0) {
  1287. return true;
  1288. }
  1289. }
  1290. }
  1291. return false;
  1292. }
  1293. finally {
  1294. Bid.ScopeLeave(ref hscp);
  1295. }
  1296. }
  1297. /// <devdoc>
  1298. /// <para>Infer the XML schema from the specified <see cref='System.IO.TextReader'/> into the <see cref='System.Data.DataSet'/>.</para>
  1299. /// </devdoc>
  1300. public void InferXmlSchema(XmlReader reader, string[] nsArray)
  1301. {
  1302. IntPtr hscp;
  1303. Bid.ScopeEnter(out hscp, "<ds.DataSet.InferXmlSchema|API> %d#\n", ObjectID);
  1304. try {
  1305. if (reader == null)
  1306. return;
  1307. XmlDocument xdoc = new XmlDocument();
  1308. if (reader.NodeType == XmlNodeType.Element) {
  1309. XmlNode node = xdoc.ReadNode(reader);
  1310. xdoc.AppendChild(node);
  1311. }
  1312. else
  1313. xdoc.Load(reader);
  1314. if (xdoc.DocumentElement == null)
  1315. return;
  1316. InferSchema(xdoc, nsArray, XmlReadMode.InferSchema);
  1317. }
  1318. finally {
  1319. Bid.ScopeLeave(ref hscp);
  1320. }
  1321. }
  1322. /// <devdoc>
  1323. /// <para>Infer the XML schema from the specified <see cref='System.IO.TextReader'/> into the <see cref='System.Data.DataSet'/>.</para>
  1324. /// </devdoc>
  1325. public void InferXmlSchema(Stream stream, string[] nsArray)
  1326. {
  1327. if (stream == null)
  1328. return;
  1329. InferXmlSchema(new XmlTextReader(stream), nsArray);
  1330. }
  1331. /// <devdoc>
  1332. /// <para>Infer the XML schema from the specified <see cref='System.IO.TextReader'/> into the <see cref='System.Data.DataSet'/>.</para>
  1333. /// </devdoc>
  1334. public void InferXmlSchema(TextReader reader, string[] nsArray)
  1335. {
  1336. if (reader == null)
  1337. return;
  1338. InferXmlSchema(new XmlTextReader(reader), nsArray);
  1339. }
  1340. /// <devdoc>
  1341. /// <para>Infer the XML schema from the specified file into the <see cref='System.Data.DataSet'/>.</para>
  1342. /// </devdoc>
  1343. [ResourceExposure(ResourceScope.Machine)]
  1344. [ResourceConsumption(ResourceScope.Machine)]
  1345. public void InferXmlSchema(String fileName, string[] nsArray)
  1346. {
  1347. XmlTextReader xr = new XmlTextReader(fileName);
  1348. try {
  1349. InferXmlSchema(xr, nsArray);
  1350. }
  1351. finally {
  1352. xr.Close();
  1353. }
  1354. }
  1355. /// <devdoc>
  1356. /// <para>Reads the XML schema from the specified <see cref='T:System.Xml.XMLReader'/> into the <see cref='System.Data.DataSet'/>
  1357. /// .</para>
  1358. /// </devdoc>
  1359. public void ReadXmlSchema(XmlReader reader)
  1360. {
  1361. ReadXmlSchema(reader, false);
  1362. }
  1363. internal void ReadXmlSchema(XmlReader reader, bool denyResolving)
  1364. {
  1365. IntPtr hscp;
  1366. Bid.ScopeEnter(out hscp, "<ds.DataSet.ReadXmlSchema|INFO> %d#, reader, denyResolving=%d{bool}\n", ObjectID, denyResolving);
  1367. try {
  1368. int iCurrentDepth = -1;
  1369. if (reader == null)
  1370. return;
  1371. if (reader is XmlTextReader)
  1372. ((XmlTextReader)reader).WhitespaceHandling = WhitespaceHandling.None;
  1373. XmlDocument xdoc = new XmlDocument(); // we may need this to infer the schema
  1374. if (reader.NodeType == XmlNodeType.Element)
  1375. iCurrentDepth = reader.Depth;
  1376. reader.MoveToContent();
  1377. if (reader.NodeType == XmlNodeType.Element) {
  1378. // if reader points to the schema load it...
  1379. if (reader.LocalName == Keywords.XDR_SCHEMA && reader.NamespaceURI == Keywords.XDRNS) {
  1380. // load XDR schema and exit
  1381. ReadXDRSchema(reader);
  1382. return;
  1383. }
  1384. if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI == Keywords.XSDNS) {
  1385. // load XSD schema and exit
  1386. ReadXSDSchema(reader, denyResolving);
  1387. return;
  1388. }
  1389. if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI.StartsWith(Keywords.XSD_NS_START, StringComparison.Ordinal))
  1390. throw ExceptionBuilder.DataSetUnsupportedSchema(Keywords.XSDNS);
  1391. // ... otherwise backup the top node and all its attributes
  1392. XmlElement topNode = xdoc.CreateElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
  1393. if (reader.HasAttributes) {
  1394. int attrCount = reader.AttributeCount;
  1395. for (int i = 0; i < attrCount; i++) {
  1396. reader.MoveToAttribute(i);
  1397. if (reader.NamespaceURI.Equals(Keywords.XSD_XMLNS_NS))
  1398. topNode.SetAttribute(reader.Name, reader.GetAttribute(i));
  1399. else {
  1400. XmlAttribute attr = topNode.SetAttributeNode(reader.LocalName, reader.NamespaceURI);
  1401. attr.Prefix = reader.Prefix;
  1402. attr.Value = reader.GetAttribute(i);
  1403. }
  1404. }
  1405. }
  1406. reader.Read();
  1407. while (MoveToElement(reader, iCurrentDepth)) {
  1408. // if reader points to the schema load it...
  1409. if (reader.LocalName == Keywords.XDR_SCHEMA && reader.NamespaceURI == Keywords.XDRNS) {
  1410. // load XDR schema and exit
  1411. ReadXDRSchema(reader);
  1412. return;
  1413. }
  1414. if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI == Keywords.XSDNS) {
  1415. // load XSD schema and exit
  1416. ReadXSDSchema(reader, denyResolving);
  1417. return;
  1418. }
  1419. if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI.StartsWith(Keywords.XSD_NS_START, StringComparison.Ordinal))
  1420. throw ExceptionBuilder.DataSetUnsupportedSchema(Keywords.XSDNS);
  1421. XmlNode node = xdoc.ReadNode(reader);
  1422. topNode.AppendChild(node);
  1423. }
  1424. // read the closing tag of the current element
  1425. ReadEndElement(reader);
  1426. // if we are here no schema has been found
  1427. xdoc.AppendChild(topNode);
  1428. // so we InferSchema
  1429. InferSchema(xdoc, null, XmlReadMode.Auto);
  1430. }
  1431. }
  1432. finally {
  1433. Bid.ScopeLeave(ref hscp);
  1434. }
  1435. }
  1436. internal bool MoveToElement(XmlReader reader, int depth) {
  1437. while (!reader.EOF && reader.NodeType != XmlNodeType.EndElement && reader.NodeType != XmlNodeType.Element && reader.Depth > depth) {
  1438. reader.Read();
  1439. }
  1440. return (reader.NodeType == XmlNodeType.Element);
  1441. }
  1442. private static void MoveToElement(XmlReader reader) {
  1443. while (!reader.EOF && reader.NodeType != XmlNodeType.EndElement && reader.NodeType != XmlNodeType.Element) {
  1444. reader.Read();
  1445. }
  1446. }
  1447. internal void ReadEndElement(XmlReader reader) {
  1448. while (reader.NodeType == XmlNodeType.Whitespace) {
  1449. reader.Skip();
  1450. }
  1451. if (reader.NodeType == XmlNodeType.None) {
  1452. reader.Skip();
  1453. }
  1454. else if (reader.NodeType == XmlNodeType.EndElement) {
  1455. reader.ReadEndElement();
  1456. }
  1457. }
  1458. internal void ReadXSDSchema(XmlReader reader, bool denyResolving) {
  1459. XmlSchemaSet sSet = new XmlSchemaSet();
  1460. int schemaFragmentCount = 1;
  1461. //read from current schmema element
  1462. if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI == Keywords.XSDNS) {
  1463. if (reader.HasAttributes) {
  1464. string attribValue = reader.GetAttribute(Keywords.MSD_FRAGMENTCOUNT, Keywords.MSDNS); // this must not move the position
  1465. if (!Common.ADP.IsEmpty(attribValue)) {
  1466. schemaFragmentCount = int.Parse(attribValue, null);
  1467. }
  1468. }
  1469. }
  1470. while (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI == Keywords.XSDNS) {
  1471. XmlSchema s = XmlSchema.Read(reader, null);
  1472. sSet.Add(s);
  1473. //read the end tag
  1474. ReadEndElement(reader);
  1475. if (--schemaFragmentCount > 0) {
  1476. MoveToElement(reader);
  1477. }
  1478. while (reader.NodeType == XmlNodeType.Whitespace) {
  1479. reader.Skip();
  1480. }
  1481. }
  1482. sSet.Compile();
  1483. XSDSchema schema = new XSDSchema();
  1484. schema.LoadSchema(sSet, this);
  1485. }
  1486. internal void ReadXDRSchema(XmlReader reader) {
  1487. XmlDocument xdoc = new XmlDocument(); // we may need this to infer the schema
  1488. XmlNode schNode = xdoc.ReadNode(reader);
  1489. xdoc.AppendChild(schNode);
  1490. XDRSchema schema = new XDRSchema(this, false);
  1491. this.DataSetName = xdoc.DocumentElement.LocalName;
  1492. schema.LoadSchema((XmlElement)schNode, this);
  1493. }
  1494. /// <devdoc>
  1495. /// <para>Reads the XML schema from the specified <see cref='System.IO.Stream'/> into the
  1496. /// <see cref='System.Data.DataSet'/>.</para>
  1497. /// </devdoc>
  1498. public void ReadXmlSchema(Stream stream)
  1499. {
  1500. if (stream == null)
  1501. return;
  1502. ReadXmlSchema(new XmlTextReader(stream), false);
  1503. }
  1504. /// <devdoc>
  1505. /// <para>Reads the XML schema from the specified <see cref='System.IO.TextReader'/> into the <see cref='System.Data.DataSet'/>.</para>
  1506. /// </devdoc>
  1507. public void ReadXmlSchema(TextReader reader)
  1508. {
  1509. if (reader == null)
  1510. return;
  1511. ReadXmlSchema(new XmlTextReader(reader), false);
  1512. }
  1513. /// <devdoc>
  1514. /// <para>Reads the XML schema from the specified file into the <see cref='System.Data.DataSet'/>.</para>
  1515. /// </devdoc>
  1516. [ResourceExposure(ResourceScope.Machine)]
  1517. [ResourceConsumption(ResourceScope.Machine)]
  1518. public void ReadXmlSchema(String fileName)
  1519. {
  1520. XmlTextReader xr = new XmlTextReader(fileName);
  1521. try {
  1522. ReadXmlSchema(xr, false);
  1523. }
  1524. finally {
  1525. xr.Close();
  1526. }
  1527. }
  1528. #region WriteXmlSchema
  1529. /// <summary>Writes the <see cref='DataSet'/> structure as an XML schema to using the specified <see cref='Stream'/> object.</summary>
  1530. /// <param name="stream">A <see cref='Stream'/> object used to write to a file.</param>
  1531. public void WriteXmlSchema(Stream stream)
  1532. {
  1533. this.WriteXmlSchema(stream, SchemaFormat.Public, (Converter<Type, string>)null);
  1534. }
  1535. /// <summary>Writes the <see cref='DataSet'/> structure as an XML schema to using the specified <see cref='Stream'/> object.</summary>
  1536. /// <param name="stream">A <see cref='Stream'/> object used to write to a file.</param>
  1537. /// <param name="multipleTargetConverter">A delegate used to convert <see cref='Type'/> into string.</param>
  1538. public void WriteXmlSchema(Stream stream, Converter<Type, string> multipleTargetConverter)
  1539. {
  1540. ADP.CheckArgumentNull(multipleTargetConverter, "multipleTargetConverter");
  1541. this.WriteXmlSchema(stream, SchemaFormat.Public, multipleTargetConverter);
  1542. }
  1543. /// <summary>Writes the <see cref='DataSet'/> structure as an XML schema to a file.</summary>
  1544. /// <param name="fileName">The file name (including the path) to which to write.</param>
  1545. [ResourceExposure(ResourceScope.Machine)]
  1546. [ResourceConsumption(ResourceScope.Machine)]
  1547. public void WriteXmlSchema(String fileName)
  1548. {
  1549. this.WriteXmlSchema(fileName, SchemaFormat.Public, (Converter<Type, string>)null);
  1550. }
  1551. /// <summary>Writes the <see cref='DataSet'/> structure as an XML schema to a file.</summary>
  1552. /// <param name="fileName">The file name (including the path) to which to write.</param>
  1553. /// <param name="multipleTargetConverter">A delegate used to convert <see cref='Type'/> into string.</param>
  1554. [ResourceExposure(ResourceScope.Machine)]
  1555. [ResourceConsumption(ResourceScope.Machine)]
  1556. public void WriteXmlSchema(String fileName, Converter<Type, string> multipleTargetConverter)
  1557. {
  1558. ADP.CheckArgumentNull(multipleTargetConverter, "multipleTargetConverter");
  1559. this.WriteXmlSchema(fileName, SchemaFormat.Public, multipleTargetConverter);
  1560. }
  1561. /// <summary>Writes the <see cref='DataSet'/> structure as an XML schema to a <see cref='TextWriter'/> object.</summary>
  1562. /// <param name="writer">The <see cref='TextWriter'/> object with which to write.</param>
  1563. public void WriteXmlSchema(TextWriter writer)
  1564. {
  1565. this.WriteXmlSchema(writer, SchemaFormat.Public, (Converter<Type, string>)null);
  1566. }
  1567. /// <summary>Writes the <see cref='DataSet'/> structure as an XML schema to a <see cref='TextWriter'/> object.</summary>
  1568. /// <param name="writer">The <see cref='TextWriter'/> object with which to write.</param>
  1569. /// <param name="multipleTargetConverter">A delegate used to convert <see cref='Type'/> into string.</param>
  1570. public void WriteXmlSchema(TextWriter writer, Converter<Type, string> multipleTargetConverter)
  1571. {
  1572. ADP.CheckArgumentNull(multipleTargetConverter, "multipleTargetConverter");
  1573. this.WriteXmlSchema(writer, SchemaFormat.Public, multipleTargetConverter);
  1574. }
  1575. /// <summary>Writes the <see cref='DataSet'/> structure as an XML schema to an <see cref='XmlWriter'/> object.</summary>
  1576. /// <param name="writer">The <see cref='XmlWriter'/> object with which to write.</param>
  1577. public void WriteXmlSchema(XmlWriter writer)
  1578. {
  1579. this.WriteXmlSchema(writer, SchemaFormat.Public, (Converter<Type, string>)null);
  1580. }
  1581. /// <summary>Writes the <see cref='DataSet'/> structure as an XML schema to an <see cref='XmlWriter'/> object.</summary>
  1582. /// <param name="writer">The <see cref='XmlWriter'/> object with which to write.</param>
  1583. /// <param name="multipleTargetConverter">A delegate used to convert <see cref='Type'/> into string.</param>
  1584. public void WriteXmlSchema(XmlWriter writer, Converter<Type, string> multipleTargetConverter)
  1585. {
  1586. ADP.CheckArgumentNull(multipleTargetConverter, "multipleTargetConverter");
  1587. this.WriteXmlSchema(writer, SchemaFormat.Public, multipleTargetConverter);
  1588. }
  1589. [ResourceExposure(ResourceScope.Machine)]
  1590. [ResourceConsumption(ResourceScope.Machine)]
  1591. private void WriteXmlSchema(String fileName, SchemaFormat schemaFormat, Converter<Type, string> multipleTargetConverter)
  1592. {
  1593. XmlTextWriter xw = new XmlTextWriter( fileName, null );
  1594. try {
  1595. xw.Formatting = Formatting.Indented;
  1596. xw.WriteStartDocument(true);
  1597. this.WriteXmlSchema(xw, schemaFormat, multipleTargetConverter);
  1598. xw.WriteEndDocument();
  1599. }
  1600. finally {
  1601. xw.Close();
  1602. }
  1603. }
  1604. private void WriteXmlSchema(Stream stream, SchemaFormat schemaFormat, Converter<Type, string> multipleTargetConverter)
  1605. {
  1606. if (stream == null)
  1607. return;
  1608. XmlTextWriter w = new XmlTextWriter(stream, null);
  1609. w.Formatting = Formatting.Indented;
  1610. this.WriteXmlSchema(w, schemaFormat, multipleTargetConverter);
  1611. }
  1612. private void WriteXmlSchema(TextWriter writer, SchemaFormat schemaFormat, Converter<Type, string> multipleTargetConverter)
  1613. {
  1614. if (writer == null)
  1615. return;
  1616. XmlTextWriter w = new XmlTextWriter(writer);
  1617. w.Formatting = Formatting.Indented;
  1618. this.WriteXmlSchema(w, schemaFormat, multipleTargetConverter);
  1619. }
  1620. private void WriteXmlSchema(XmlWriter writer, SchemaFormat schemaFormat, Converter<Type, string> multipleTargetConverter)
  1621. {
  1622. IntPtr hscp;
  1623. Bid.ScopeEnter(out hscp, "<ds.DataSet.WriteXmlSchema|INFO> %d#, schemaFormat=%d{ds.SchemaFormat}\n", ObjectID, (int)schemaFormat);
  1624. try {
  1625. // Generate SchemaTree and write it out
  1626. if (writer != null) {
  1627. XmlTreeGen treeGen = null;
  1628. if (schemaFormat == SchemaFormat.WebService &&
  1629. SchemaSerializationMode == SchemaSerializationMode.ExcludeSchema &&
  1630. writer.WriteState == WriteState.Element) {
  1631. treeGen = new XmlTreeGen(SchemaFormat.WebServiceSkipSchema);
  1632. }
  1633. else {
  1634. treeGen = new XmlTreeGen(schemaFormat);
  1635. }
  1636. treeGen.Save(this, (DataTable)null, writer, false, multipleTargetConverter);
  1637. }
  1638. }
  1639. finally {
  1640. Bid.ScopeLeave(ref hscp);
  1641. }
  1642. }
  1643. #endregion
  1644. /// <devdoc>
  1645. /// </devdoc>
  1646. public XmlReadMode ReadXml(XmlReader reader)
  1647. {
  1648. return ReadXml(reader, false);
  1649. }
  1650. internal XmlReadMode ReadXml(XmlReader reader, bool denyResolving)
  1651. {
  1652. IntPtr hscp;
  1653. Bid.ScopeEnter(out hscp, "<ds.DataSet.ReadXml|INFO> %d#, denyResolving=%d{bool}\n", ObjectID, denyResolving);
  1654. try {
  1655. DataTable.DSRowDiffIdUsageSection rowDiffIdUsage = new DataTable.DSRowDiffIdUsageSection();
  1656. try {
  1657. bool fDataFound = false;
  1658. bool fSchemaFound = false;
  1659. bool fDiffsFound = false;
  1660. bool fIsXdr = false;
  1661. int iCurrentDepth = -1;
  1662. XmlReadMode ret = XmlReadMode.Auto;
  1663. bool isEmptyDataSet = false;
  1664. bool topNodeIsProcessed = false; // we chanche topnode and there is just one case that we miss to process it
  1665. // it is : <elem attrib1="Attrib">txt</elem>
  1666. // clear the hashtable to avoid conflicts between diffgrams, SqlHotFix 782
  1667. rowDiffIdUsage.Prepare(this);
  1668. if (reader == null)
  1669. return ret;
  1670. if (Tables.Count == 0) {
  1671. isEmptyDataSet = true;
  1672. }
  1673. if (reader is XmlTextReader)
  1674. ((XmlTextReader)reader).WhitespaceHandling = WhitespaceHandling.Significant;
  1675. XmlDocument xdoc = new XmlDocument(); // we may need this to infer the schema
  1676. XmlDataLoader xmlload = null;
  1677. reader.MoveToContent();
  1678. if (reader.NodeType == XmlNodeType.Element)
  1679. iCurrentDepth = reader.Depth;
  1680. if (reader.NodeType == XmlNodeType.Element) {
  1681. if ((reader.LocalName == Keywords.DIFFGRAM) && (reader.NamespaceURI == Keywords.DFFNS)) {
  1682. this.ReadXmlDiffgram(reader);
  1683. // read the closing tag of the current element
  1684. ReadEndElement(reader);
  1685. return XmlReadMode.DiffGram;
  1686. }
  1687. // if reader points to the schema load it
  1688. if (reader.LocalName == Keywords.XDR_SCHEMA && reader.NamespaceURI == Keywords.XDRNS) {
  1689. // load XDR schema and exit
  1690. ReadXDRSchema(reader);
  1691. return XmlReadMode.ReadSchema; //since the top level element is a schema return
  1692. }
  1693. if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI == Keywords.XSDNS) {
  1694. // load XSD schema and exit
  1695. ReadXSDSchema(reader, denyResolving);
  1696. return XmlReadMode.ReadSchema; //since the top level element is a schema return
  1697. }
  1698. if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI.StartsWith(Keywords.XSD_NS_START, StringComparison.Ordinal))
  1699. throw ExceptionBuilder.DataSetUnsupportedSchema(Keywords.XSDNS);
  1700. // now either the top level node is a table and we load it through dataReader...
  1701. // ... or backup the top node and all its attributes because we may need to InferSchema
  1702. XmlElement topNode = xdoc.CreateElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
  1703. if (reader.HasAttributes) {
  1704. int attrCount = reader.AttributeCount;
  1705. for (int i = 0; i < attrCount; i++) {
  1706. reader.MoveToAttribute(i);
  1707. if (reader.NamespaceURI.Equals(Keywords.XSD_XMLNS_NS))
  1708. topNode.SetAttribute(reader.Name, reader.GetAttribute(i));
  1709. else {
  1710. XmlAttribute attr = topNode.SetAttributeNode(reader.LocalName, reader.NamespaceURI);
  1711. attr.Prefix = reader.Prefix;
  1712. attr.Value = reader.GetAttribute(i);
  1713. }
  1714. }
  1715. }
  1716. reader.Read();
  1717. string rootNodeSimpleContent = reader.Value;
  1718. while (MoveToElement(reader, iCurrentDepth)) {
  1719. if ((reader.LocalName == Keywords.DIFFGRAM) && (reader.NamespaceURI == Keywords.DFFNS)) {
  1720. this.ReadXmlDiffgram(reader);
  1721. // read the closing tag of the current element
  1722. // YUKON FIX ReadEndElement(reader);
  1723. // return XmlReadMode.DiffGram;
  1724. ret = XmlReadMode.DiffGram; // continue reading for multiple schemas
  1725. }
  1726. // if reader points to the schema load it...
  1727. if (!fSchemaFound && !fDataFound && reader.LocalName == Keywords.XDR_SCHEMA && reader.NamespaceURI == Keywords.XDRNS) {
  1728. // load XDR schema and exit
  1729. ReadXDRSchema(reader);
  1730. fSchemaFound = true;
  1731. fIsXdr = true;
  1732. continue;
  1733. }
  1734. if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI == Keywords.XSDNS) {
  1735. // load XSD schema and exit
  1736. ReadXSDSchema(reader, denyResolving);
  1737. fSchemaFound = true;
  1738. continue;
  1739. }
  1740. if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI.StartsWith(Keywords.XSD_NS_START, StringComparison.Ordinal))
  1741. throw ExceptionBuilder.DataSetUnsupportedSchema(Keywords.XSDNS);
  1742. if ((reader.LocalName == Keywords.DIFFGRAM) && (reader.NamespaceURI == Keywords.DFFNS)) {
  1743. this.ReadXmlDiffgram(reader);
  1744. fDiffsFound = true;
  1745. ret = XmlReadMode.DiffGram;
  1746. }
  1747. else {
  1748. // We have found data IFF the reader.NodeType == Element and reader.depth == currentDepth-1
  1749. // if reader.NodeType == whitespace, skip all white spaces.
  1750. // skip processing i.e. continue if the first non-whitespace node is not of type element.
  1751. while (!reader.EOF && reader.NodeType == XmlNodeType.Whitespace)
  1752. reader.Read();
  1753. if (reader.NodeType != XmlNodeType.Element)
  1754. continue;
  1755. // we found data here
  1756. fDataFound = true;
  1757. if (!fSchemaFound && Tables.Count == 0) {
  1758. XmlNode node = xdoc.ReadNode(reader);
  1759. topNode.AppendChild(node);
  1760. }
  1761. else {
  1762. if (xmlload == null)
  1763. xmlload = new XmlDataLoader(this, fIsXdr, topNode, false);
  1764. xmlload.LoadData(reader);
  1765. topNodeIsProcessed = true; // we process the topnode
  1766. if (fSchemaFound)
  1767. ret = XmlReadMode.ReadSchema;
  1768. else
  1769. ret = XmlReadMode.IgnoreSchema;
  1770. }
  1771. }
  1772. }
  1773. // read the closing tag of the current element
  1774. ReadEndElement(reader);
  1775. bool isfTopLevelTableSet = false;
  1776. bool tmpValue = this.fTopLevelTable;
  1777. //While inference we ignore root elements text content
  1778. if (!fSchemaFound && Tables.Count == 0 && !topNode.HasChildNodes) { //We shoule not come add SC of root elemnt to topNode if we are not infering
  1779. this.fTopLevelTable = true;
  1780. isfTopLevelTableSet = true;
  1781. if ((rootNodeSimpleContent != null && rootNodeSimpleContent.Length > 0))
  1782. topNode.InnerText = rootNodeSimpleContent;
  1783. }
  1784. if (!isEmptyDataSet) {
  1785. if ((rootNodeSimpleContent != null && rootNodeSimpleContent.Length > 0))
  1786. topNode.InnerText = rootNodeSimpleContent;
  1787. }
  1788. // now top node contains the data part
  1789. xdoc.AppendChild(topNode);
  1790. if (xmlload == null)
  1791. xmlload = new XmlDataLoader(this, fIsXdr, topNode, false);
  1792. if (!isEmptyDataSet && !topNodeIsProcessed) {
  1793. XmlElement root = xdoc.DocumentElement;
  1794. Debug.Assert(root.NamespaceURI != null, "root.NamespaceURI should not ne null, it should be empty string");
  1795. // just recognize that below given Xml represents datatable in toplevel
  1796. //<table attr1="foo" attr2="bar" table_Text="junk">text</table>
  1797. // only allow root element with simple content, if any
  1798. if (root.ChildNodes.Count == 0 ||
  1799. ((root.ChildNodes.Count == 1) && root.FirstChild.GetType() == typeof(System.Xml.XmlText))) {
  1800. bool initfTopLevelTable = this.fTopLevelTable;
  1801. // if root element maps to a datatable
  1802. // ds and dt cant have the samm name and ns at the same time, how to write to xml
  1803. if (this.DataSetName != root.Name && this.namespaceURI != root.NamespaceURI &&
  1804. Tables.Contains(root.Name, (root.NamespaceURI.Length == 0) ? null : root.NamespaceURI, false, true)) {
  1805. this.fTopLevelTable = true;
  1806. }
  1807. try {
  1808. xmlload.LoadData(xdoc);
  1809. }
  1810. finally {
  1811. this.fTopLevelTable = initfTopLevelTable; // this is not for inference, we have schema and we were skipping
  1812. // topnode where it was a datatable, We must restore the value
  1813. }
  1814. }
  1815. }// above check and below check are orthogonal
  1816. // so we InferSchema
  1817. if (!fDiffsFound) {
  1818. // Load Data
  1819. if (!fSchemaFound && Tables.Count == 0) {
  1820. InferSchema(xdoc, null, XmlReadMode.Auto);
  1821. ret = XmlReadMode.InferSchema;
  1822. xmlload.FromInference = true;
  1823. try {
  1824. xmlload.LoadData(xdoc);
  1825. }
  1826. finally {
  1827. xmlload.FromInference = false;
  1828. }
  1829. }
  1830. //We dont need this assignement. Once we set it(where we set it during inference), it won't be changed
  1831. if (isfTopLevelTableSet)
  1832. this.fTopLevelTable = tmpValue;
  1833. }
  1834. }
  1835. return ret;
  1836. }
  1837. finally {
  1838. rowDiffIdUsage.Cleanup();
  1839. }
  1840. }
  1841. finally {
  1842. Bid.ScopeLeave(ref hscp);
  1843. }
  1844. }
  1845. /// <devdoc>
  1846. /// </devdoc>
  1847. public XmlReadMode ReadXml(Stream stream)
  1848. {
  1849. if (stream == null)
  1850. return XmlReadMode.Auto;
  1851. return ReadXml(new XmlTextReader(stream), false);
  1852. }
  1853. /// <devdoc>
  1854. /// </devdoc>
  1855. public XmlReadMode ReadXml(TextReader reader)
  1856. {
  1857. if (reader == null)
  1858. return XmlReadMode.Auto;
  1859. return ReadXml(new XmlTextReader(reader), false);
  1860. }
  1861. /// <devdoc>
  1862. /// </devdoc>
  1863. [ResourceExposure(ResourceScope.Machine)]
  1864. [ResourceConsumption(ResourceScope.Machine)]
  1865. public XmlReadMode ReadXml(string fileName)
  1866. {
  1867. XmlTextReader xr = new XmlTextReader(fileName);
  1868. try {
  1869. return ReadXml(xr, false);
  1870. }
  1871. finally {
  1872. xr.Close();
  1873. }
  1874. }
  1875. internal void InferSchema(XmlDocument xdoc, string[] excludedNamespaces, XmlReadMode mode) {
  1876. IntPtr hscp;
  1877. Bid.ScopeEnter(out hscp, "<ds.DataSet.InferSchema|INFO> %d#, mode=%d{ds.XmlReadMode}\n", ObjectID, (int)mode);
  1878. try {
  1879. string ns = xdoc.DocumentElement.NamespaceURI;
  1880. if (null == excludedNamespaces) {
  1881. excludedNamespaces = new string[0];
  1882. }
  1883. XmlNodeReader xnr = new XmlIgnoreNamespaceReader(xdoc, excludedNamespaces);
  1884. System.Xml.Schema.XmlSchemaInference infer = new System.Xml.Schema.XmlSchemaInference();
  1885. infer.Occurrence = XmlSchemaInference.InferenceOption.Relaxed;
  1886. if (mode == XmlReadMode.InferTypedSchema)
  1887. infer.TypeInference = XmlSchemaInference.InferenceOption.Restricted;
  1888. else
  1889. infer.TypeInference = XmlSchemaInference.InferenceOption.Relaxed;
  1890. XmlSchemaSet schemaSet = infer.InferSchema(xnr);
  1891. schemaSet.Compile();
  1892. XSDSchema schema = new XSDSchema();
  1893. schema.FromInference = true;
  1894. try {
  1895. schema.LoadSchema(schemaSet, this);
  1896. }
  1897. finally {
  1898. schema.FromInference = false; // this is always false if you are not calling fron inference
  1899. }
  1900. }
  1901. finally {
  1902. Bid.ScopeLeave(ref hscp);
  1903. }
  1904. }
  1905. private bool IsEmpty() {
  1906. foreach (DataTable table in this.Tables)
  1907. if (table.Rows.Count > 0)
  1908. return false;
  1909. return true;
  1910. }
  1911. private void ReadXmlDiffgram(XmlReader reader) {
  1912. IntPtr hscp;
  1913. Bid.ScopeEnter(out hscp, "<ds.DataSet.ReadXmlDiffgram|INFO> %d#\n", ObjectID);
  1914. try {
  1915. int d = reader.Depth;
  1916. bool fEnforce = this.EnforceConstraints;
  1917. this.EnforceConstraints = false;
  1918. DataSet newDs;
  1919. bool isEmpty = this.IsEmpty();
  1920. if (isEmpty) {
  1921. newDs = this;
  1922. }
  1923. else {
  1924. newDs = this.Clone();
  1925. newDs.EnforceConstraints = false;
  1926. }
  1927. foreach (DataTable t in newDs.Tables) {
  1928. t.Rows.nullInList = 0;
  1929. }
  1930. reader.MoveToContent();
  1931. if ((reader.LocalName != Keywords.DIFFGRAM) && (reader.NamespaceURI != Keywords.DFFNS))
  1932. return;
  1933. reader.Read();
  1934. if (reader.NodeType == XmlNodeType.Whitespace)
  1935. MoveToElement(reader, reader.Depth - 1 /*iCurrentDepth*/); // skip over whitespaces.
  1936. newDs.fInLoadDiffgram = true;
  1937. if (reader.Depth > d) {
  1938. if ((reader.NamespaceURI != Keywords.DFFNS) && (reader.NamespaceURI != Keywords.MSDNS)) {
  1939. //we should be inside the dataset part
  1940. XmlDocument xdoc = new XmlDocument();
  1941. XmlElement node = xdoc.CreateElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
  1942. reader.Read();
  1943. if (reader.NodeType == XmlNodeType.Whitespace) {
  1944. MoveToElement(reader, reader.Depth - 1 /*iCurrentDepth*/); // skip over whitespaces.
  1945. }
  1946. if (reader.Depth - 1 > d) {
  1947. XmlDataLoader xmlload = new XmlDataLoader(newDs, false, node, false);
  1948. xmlload.isDiffgram = true; // turn on the special processing
  1949. xmlload.LoadData(reader);
  1950. }
  1951. ReadEndElement(reader);
  1952. if (reader.NodeType == XmlNodeType.Whitespace) {
  1953. MoveToElement(reader, reader.Depth - 1 /*iCurrentDepth*/); // skip over whitespaces.
  1954. }
  1955. }
  1956. Debug.Assert(reader.NodeType != XmlNodeType.Whitespace, "Should not be on Whitespace node");
  1957. if (((reader.LocalName == Keywords.SQL_BEFORE) && (reader.NamespaceURI == Keywords.DFFNS)) ||
  1958. ((reader.LocalName == Keywords.MSD_ERRORS) && (reader.NamespaceURI == Keywords.DFFNS)))
  1959. {
  1960. //this will consume the changes and the errors part
  1961. XMLDiffLoader diffLoader = new XMLDiffLoader();
  1962. diffLoader.LoadDiffGram(newDs, reader);
  1963. }
  1964. // get to the closing diff tag
  1965. while (reader.Depth > d) {
  1966. reader.Read();
  1967. }
  1968. // read the closing tag
  1969. ReadEndElement(reader);
  1970. }
  1971. foreach (DataTable t in newDs.Tables) {
  1972. if (t.Rows.nullInList > 0)
  1973. throw ExceptionBuilder.RowInsertMissing(t.TableName);
  1974. }
  1975. newDs.fInLoadDiffgram = false;
  1976. //terrible performance!
  1977. foreach (DataTable t in newDs.Tables) {
  1978. DataRelation[] nestedParentRelations = t.NestedParentRelations;
  1979. foreach (DataRelation rel in nestedParentRelations) {
  1980. if (rel.ParentTable == t) {
  1981. foreach (DataRow r in t.Rows) {
  1982. foreach (DataRelation rel2 in nestedParentRelations) {
  1983. r.CheckForLoops(rel2);
  1984. }
  1985. }
  1986. }
  1987. }
  1988. }
  1989. if (!isEmpty) {
  1990. this.Merge(newDs);
  1991. if (this.dataSetName == "NewDataSet")
  1992. this.dataSetName = newDs.dataSetName;
  1993. newDs.EnforceConstraints = fEnforce;
  1994. }
  1995. this.EnforceConstraints = fEnforce;
  1996. }
  1997. finally {
  1998. Bid.ScopeLeave(ref hscp);
  1999. }
  2000. }
  2001. /// <devdoc>
  2002. /// </devdoc>
  2003. public XmlReadMode ReadXml(XmlReader reader, XmlReadMode mode)
  2004. {
  2005. return ReadXml(reader, mode, false);
  2006. }
  2007. internal XmlReadMode ReadXml(XmlReader reader, XmlReadMode mode, bool denyResolving)
  2008. {
  2009. IntPtr hscp;
  2010. Bid.ScopeEnter(out hscp, "<ds.DataSet.ReadXml|INFO> %d#, mode=%d{ds.XmlReadMode}, denyResolving=%d{bool}\n", ObjectID, (int)mode, denyResolving);
  2011. try {
  2012. XmlReadMode ret = mode;
  2013. if (reader == null)
  2014. return ret;
  2015. if (mode == XmlReadMode.Auto) {
  2016. // Dev11 915079: nested ReadXml calls on the same DataSet must be done outside of RowDiffIdUsage scope
  2017. return ReadXml(reader);
  2018. }
  2019. DataTable.DSRowDiffIdUsageSection rowDiffIdUsage = new DataTable.DSRowDiffIdUsageSection();
  2020. try {
  2021. bool fSchemaFound = false;
  2022. bool fDataFound = false;
  2023. bool fIsXdr = false;
  2024. int iCurrentDepth = -1;
  2025. // Dev11 904428: prepare and cleanup rowDiffId hashtable
  2026. rowDiffIdUsage.Prepare(this);
  2027. if (reader is XmlTextReader)
  2028. ((XmlTextReader)reader).WhitespaceHandling = WhitespaceHandling.Significant;
  2029. XmlDocument xdoc = new XmlDocument(); // we may need this to infer the schema
  2030. if ((mode != XmlReadMode.Fragment) && (reader.NodeType == XmlNodeType.Element))
  2031. iCurrentDepth = reader.Depth;
  2032. reader.MoveToContent();
  2033. XmlDataLoader xmlload = null;
  2034. if (reader.NodeType == XmlNodeType.Element) {
  2035. XmlElement topNode = null;
  2036. if (mode == XmlReadMode.Fragment) {
  2037. xdoc.AppendChild(xdoc.CreateElement("ds_sqlXmlWraPPeR"));
  2038. topNode = xdoc.DocumentElement;
  2039. }
  2040. else { //handle the top node
  2041. if ((reader.LocalName == Keywords.DIFFGRAM) && (reader.NamespaceURI == Keywords.DFFNS)) {
  2042. if ((mode == XmlReadMode.DiffGram) || (mode == XmlReadMode.IgnoreSchema)) {
  2043. this.ReadXmlDiffgram(reader);
  2044. // read the closing tag of the current element
  2045. ReadEndElement(reader);
  2046. }
  2047. else {
  2048. reader.Skip();
  2049. }
  2050. return ret;
  2051. }
  2052. if (reader.LocalName == Keywords.XDR_SCHEMA && reader.NamespaceURI == Keywords.XDRNS) {
  2053. // load XDR schema and exit
  2054. if ((mode != XmlReadMode.IgnoreSchema) && (mode != XmlReadMode.InferSchema) &&
  2055. (mode != XmlReadMode.InferTypedSchema))
  2056. {
  2057. ReadXDRSchema(reader);
  2058. }
  2059. else {
  2060. reader.Skip();
  2061. }
  2062. return ret; //since the top level element is a schema return
  2063. }
  2064. if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI == Keywords.XSDNS) {
  2065. // load XSD schema and exit
  2066. if ((mode != XmlReadMode.IgnoreSchema) && (mode != XmlReadMode.InferSchema) &&
  2067. (mode != XmlReadMode.InferTypedSchema))
  2068. {
  2069. ReadXSDSchema(reader, denyResolving);
  2070. }
  2071. else
  2072. reader.Skip();
  2073. return ret; //since the top level element is a schema return
  2074. }
  2075. if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI.StartsWith(Keywords.XSD_NS_START, StringComparison.Ordinal))
  2076. throw ExceptionBuilder.DataSetUnsupportedSchema(Keywords.XSDNS);
  2077. // now either the top level node is a table and we load it through dataReader...
  2078. // ... or backup the top node and all its attributes
  2079. topNode = xdoc.CreateElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
  2080. if (reader.HasAttributes) {
  2081. int attrCount = reader.AttributeCount;
  2082. for (int i = 0; i < attrCount; i++) {
  2083. reader.MoveToAttribute(i);
  2084. if (reader.NamespaceURI.Equals(Keywords.XSD_XMLNS_NS))
  2085. topNode.SetAttribute(reader.Name, reader.GetAttribute(i));
  2086. else {
  2087. XmlAttribute attr = topNode.SetAttributeNode(reader.LocalName, reader.NamespaceURI);
  2088. attr.Prefix = reader.Prefix;
  2089. attr.Value = reader.GetAttribute(i);
  2090. }
  2091. }
  2092. }
  2093. reader.Read();
  2094. }
  2095. while (MoveToElement(reader, iCurrentDepth)) {
  2096. if (reader.LocalName == Keywords.XDR_SCHEMA && reader.NamespaceURI == Keywords.XDRNS) {
  2097. // load XDR schema
  2098. if (!fSchemaFound && !fDataFound && (mode != XmlReadMode.IgnoreSchema) && (mode != XmlReadMode.InferSchema) &&
  2099. (mode != XmlReadMode.InferTypedSchema))
  2100. {
  2101. ReadXDRSchema(reader);
  2102. fSchemaFound = true;
  2103. fIsXdr = true;
  2104. }
  2105. else {
  2106. reader.Skip();
  2107. }
  2108. continue;
  2109. }
  2110. if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI == Keywords.XSDNS) {
  2111. // load XSD schema and exit
  2112. if ((mode != XmlReadMode.IgnoreSchema) && (mode != XmlReadMode.InferSchema) &&
  2113. (mode != XmlReadMode.InferTypedSchema))
  2114. {
  2115. ReadXSDSchema(reader, denyResolving);
  2116. fSchemaFound = true;
  2117. }
  2118. else {
  2119. reader.Skip();
  2120. }
  2121. continue;
  2122. }
  2123. if ((reader.LocalName == Keywords.DIFFGRAM) && (reader.NamespaceURI == Keywords.DFFNS)) {
  2124. if ((mode == XmlReadMode.DiffGram) || (mode == XmlReadMode.IgnoreSchema)) {
  2125. this.ReadXmlDiffgram(reader);
  2126. ret = XmlReadMode.DiffGram;
  2127. }
  2128. else {
  2129. reader.Skip();
  2130. }
  2131. continue;
  2132. }
  2133. if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI.StartsWith(Keywords.XSD_NS_START, StringComparison.Ordinal))
  2134. throw ExceptionBuilder.DataSetUnsupportedSchema(Keywords.XSDNS);
  2135. if (mode == XmlReadMode.DiffGram) {
  2136. reader.Skip();
  2137. continue; // we do not read data in diffgram mode
  2138. }
  2139. // if we are here we found some data
  2140. fDataFound = true;
  2141. if (mode == XmlReadMode.InferSchema || mode == XmlReadMode.InferTypedSchema) { //save the node in DOM until the end;
  2142. XmlNode node = xdoc.ReadNode(reader);
  2143. topNode.AppendChild(node);
  2144. }
  2145. else {
  2146. if (xmlload == null)
  2147. xmlload = new XmlDataLoader(this, fIsXdr, topNode, mode == XmlReadMode.IgnoreSchema);
  2148. xmlload.LoadData(reader);
  2149. }
  2150. } //end of the while
  2151. // read the closing tag of the current element
  2152. ReadEndElement(reader);
  2153. // now top node contains the data part
  2154. xdoc.AppendChild(topNode);
  2155. if (xmlload == null)
  2156. xmlload = new XmlDataLoader(this, fIsXdr, mode == XmlReadMode.IgnoreSchema);
  2157. if (mode == XmlReadMode.DiffGram) {
  2158. // we already got the diffs through XmlReader interface
  2159. return ret;
  2160. }
  2161. // Load Data
  2162. if (mode == XmlReadMode.InferSchema || mode == XmlReadMode.InferTypedSchema) {
  2163. InferSchema(xdoc, null, mode);
  2164. ret = XmlReadMode.InferSchema;
  2165. xmlload.FromInference = true;
  2166. // }
  2167. try {
  2168. xmlload.LoadData(xdoc);
  2169. }
  2170. finally {
  2171. xmlload.FromInference = false;
  2172. }
  2173. }
  2174. }
  2175. return ret;
  2176. }
  2177. finally {
  2178. // Dev11 904428: prepare and cleanup rowDiffId hashtable
  2179. rowDiffIdUsage.Cleanup();
  2180. }
  2181. }
  2182. finally {
  2183. Bid.ScopeLeave(ref hscp);
  2184. }
  2185. }
  2186. /// <devdoc>
  2187. /// </devdoc>
  2188. public XmlReadMode ReadXml(Stream stream, XmlReadMode mode)
  2189. {
  2190. if (stream == null)
  2191. return XmlReadMode.Auto;
  2192. XmlTextReader reader = (mode == XmlReadMode.Fragment) ? new XmlTextReader(stream, XmlNodeType.Element, null) : new XmlTextReader(stream);
  2193. return ReadXml(reader, mode, false);
  2194. }
  2195. /// <devdoc>
  2196. /// </devdoc>
  2197. public XmlReadMode ReadXml(TextReader reader, XmlReadMode mode)
  2198. {
  2199. if (reader == null)
  2200. return XmlReadMode.Auto;
  2201. XmlTextReader xmlreader = (mode == XmlReadMode.Fragment) ? new XmlTextReader(reader.ReadToEnd(), XmlNodeType.Element, null) : new XmlTextReader(reader);
  2202. return ReadXml(xmlreader, mode, false);
  2203. }
  2204. /// <devdoc>
  2205. /// </devdoc>
  2206. [ResourceExposure(ResourceScope.Machine)]
  2207. [ResourceConsumption(ResourceScope.Machine)]
  2208. public XmlReadMode ReadXml(string fileName, XmlReadMode mode)
  2209. {
  2210. XmlTextReader xr = null;
  2211. if (mode == XmlReadMode.Fragment) {
  2212. FileStream stream = new FileStream(fileName, FileMode.Open);
  2213. xr = new XmlTextReader(stream, XmlNodeType.Element, null);
  2214. }
  2215. else
  2216. xr = new XmlTextReader(fileName);
  2217. try {
  2218. return ReadXml(xr, mode, false);
  2219. }
  2220. finally {
  2221. xr.Close();
  2222. }
  2223. }
  2224. /// <devdoc>
  2225. /// Writes schema and data for the DataSet.
  2226. /// </devdoc>
  2227. public void WriteXml(Stream stream)
  2228. {
  2229. WriteXml(stream, XmlWriteMode.IgnoreSchema);
  2230. }
  2231. /// <devdoc>
  2232. /// </devdoc>
  2233. public void WriteXml(TextWriter writer)
  2234. {
  2235. WriteXml(writer, XmlWriteMode.IgnoreSchema);
  2236. }
  2237. /// <devdoc>
  2238. /// </devdoc>
  2239. public void WriteXml(XmlWriter writer)
  2240. {
  2241. WriteXml(writer, XmlWriteMode.IgnoreSchema);
  2242. }
  2243. /// <devdoc>
  2244. /// <para>[To be supplied.]</para>
  2245. /// </devdoc>
  2246. [ResourceExposure(ResourceScope.Machine)]
  2247. [ResourceConsumption(ResourceScope.Machine)]
  2248. public void WriteXml(String fileName)
  2249. {
  2250. WriteXml(fileName, XmlWriteMode.IgnoreSchema);
  2251. }
  2252. /// <devdoc>
  2253. /// Writes schema and data for the DataSet.
  2254. /// </devdoc>
  2255. public void WriteXml(Stream stream, XmlWriteMode mode)
  2256. {
  2257. if (stream != null) {
  2258. XmlTextWriter w = new XmlTextWriter(stream, null);
  2259. w.Formatting = Formatting.Indented;
  2260. WriteXml(w, mode);
  2261. }
  2262. }
  2263. /// <devdoc>
  2264. /// </devdoc>
  2265. public void WriteXml(TextWriter writer, XmlWriteMode mode)
  2266. {
  2267. if (writer != null) {
  2268. XmlTextWriter w = new XmlTextWriter(writer);
  2269. w.Formatting = Formatting.Indented;
  2270. WriteXml(w, mode);
  2271. }
  2272. }
  2273. /// <devdoc>
  2274. /// </devdoc>
  2275. public void WriteXml(XmlWriter writer, XmlWriteMode mode)
  2276. {
  2277. IntPtr hscp;
  2278. Bid.ScopeEnter(out hscp, "<ds.DataSet.WriteXml|API> %d#, mode=%d{ds.XmlWriteMode}\n", ObjectID, (int)mode);
  2279. try {
  2280. // Generate SchemaTree and write it out
  2281. if (writer != null) {
  2282. if (mode == XmlWriteMode.DiffGram) {
  2283. // Create and save the updates
  2284. // new UpdateTreeGen(UpdateTreeGen.UPDATE, (DataRowState)(-1), this).Save(writer, null);
  2285. new NewDiffgramGen(this).Save(writer);
  2286. }
  2287. else {
  2288. // Create and save xml data
  2289. new XmlDataTreeWriter(this).Save(writer, mode == XmlWriteMode.WriteSchema);
  2290. }
  2291. }
  2292. }
  2293. finally {
  2294. Bid.ScopeLeave(ref hscp);
  2295. }
  2296. }
  2297. /// <devdoc>
  2298. /// <para>[To be supplied.]</para>
  2299. /// </devdoc>
  2300. [ResourceExposure(ResourceScope.Machine)]
  2301. [ResourceConsumption(ResourceScope.Machine)]
  2302. public void WriteXml(String fileName, XmlWriteMode mode)
  2303. {
  2304. IntPtr hscp;
  2305. Bid.ScopeEnter(out hscp, "<ds.DataSet.WriteXml|API> %d#, fileName='%ls', mode=%d{ds.XmlWriteMode}\n", ObjectID, fileName, (int)mode);
  2306. XmlTextWriter xw = new XmlTextWriter(fileName, null);
  2307. try {
  2308. xw.Formatting = Formatting.Indented;
  2309. xw.WriteStartDocument(true);
  2310. if (xw != null) {
  2311. // Create and save the updates
  2312. if (mode == XmlWriteMode.DiffGram) {
  2313. new NewDiffgramGen(this).Save(xw);
  2314. }
  2315. else {
  2316. // Create and save xml data
  2317. new XmlDataTreeWriter(this).Save(xw, mode == XmlWriteMode.WriteSchema);
  2318. }
  2319. }
  2320. xw.WriteEndDocument();
  2321. }
  2322. finally {
  2323. xw.Close();
  2324. Bid.ScopeLeave(ref hscp);
  2325. }
  2326. }
  2327. /// <devdoc>
  2328. /// <para>
  2329. /// Gets the collection of parent relations which belong to a
  2330. /// specified table.
  2331. /// </para>
  2332. /// </devdoc>
  2333. internal DataRelationCollection GetParentRelations(DataTable table)
  2334. {
  2335. return table.ParentRelations;
  2336. }
  2337. /// <devdoc>
  2338. /// <para>
  2339. /// Merges this <see cref='System.Data.DataSet'/> into a specified <see cref='System.Data.DataSet'/>.
  2340. /// </para>
  2341. /// </devdoc>
  2342. public void Merge(DataSet dataSet)
  2343. {
  2344. IntPtr hscp;
  2345. Bid.ScopeEnter(out hscp, "<ds.DataSet.Merge|API> %d#, dataSet=%d\n", ObjectID, (dataSet != null) ? dataSet.ObjectID : 0);
  2346. try {
  2347. Merge(dataSet, false, MissingSchemaAction.Add);
  2348. }
  2349. finally {
  2350. Bid.ScopeLeave(ref hscp);
  2351. }
  2352. }
  2353. /// <devdoc>
  2354. /// <para>
  2355. /// Merges this <see cref='System.Data.DataSet'/> into a specified <see cref='System.Data.DataSet'/> preserving changes according to
  2356. /// the specified argument.
  2357. /// </para>
  2358. /// </devdoc>
  2359. public void Merge(DataSet dataSet, bool preserveChanges)
  2360. {
  2361. IntPtr hscp;
  2362. Bid.ScopeEnter(out hscp, "<ds.DataSet.Merge|API> %d#, dataSet=%d, preserveChanges=%d{bool}\n", ObjectID, (dataSet != null) ? dataSet.ObjectID : 0, preserveChanges);
  2363. try {
  2364. Merge(dataSet, preserveChanges, MissingSchemaAction.Add);
  2365. }
  2366. finally {
  2367. Bid.ScopeLeave(ref hscp);
  2368. }
  2369. }
  2370. /// <devdoc>
  2371. /// <para>
  2372. /// Merges this <see cref='System.Data.DataSet'/> into a specified <see cref='System.Data.DataSet'/> preserving changes according to
  2373. /// the specified argument, and handling an incompatible schema according to the
  2374. /// specified argument.
  2375. /// </para>
  2376. /// </devdoc>
  2377. public void Merge(DataSet dataSet, bool preserveChanges, MissingSchemaAction missingSchemaAction) {
  2378. IntPtr hscp;
  2379. Bid.ScopeEnter(out hscp, "<ds.DataSet.Merge|API> %d#, dataSet=%d, preserveChanges=%d{bool}, missingSchemaAction=%d{ds.MissingSchemaAction}\n", ObjectID, (dataSet != null) ? dataSet.ObjectID : 0, preserveChanges, (int)missingSchemaAction);
  2380. try {
  2381. // Argument checks
  2382. if (dataSet == null)
  2383. throw ExceptionBuilder.ArgumentNull("dataSet");
  2384. switch (missingSchemaAction) { // @perfnote: Enum.IsDefined
  2385. case MissingSchemaAction.Add:
  2386. case MissingSchemaAction.Ignore:
  2387. case MissingSchemaAction.Error:
  2388. case MissingSchemaAction.AddWithKey:
  2389. Merger merger = new Merger(this, preserveChanges, missingSchemaAction);
  2390. merger.MergeDataSet(dataSet);
  2391. break;
  2392. default:
  2393. throw Common.ADP.InvalidMissingSchemaAction(missingSchemaAction);
  2394. }
  2395. }
  2396. finally {
  2397. Bid.ScopeLeave(ref hscp);
  2398. }
  2399. }
  2400. /// <devdoc>
  2401. /// <para>
  2402. /// Merges this <see cref='System.Data.DataTable'/> into a specified <see cref='System.Data.DataTable'/>.
  2403. /// </para>
  2404. /// </devdoc>
  2405. public void Merge(DataTable table)
  2406. {
  2407. IntPtr hscp;
  2408. Bid.ScopeEnter(out hscp, "<ds.DataSet.Merge|API> %d#, table=%d\n", ObjectID, (table != null) ? table.ObjectID : 0);
  2409. try {
  2410. Merge(table, false, MissingSchemaAction.Add);
  2411. }
  2412. finally {
  2413. Bid.ScopeLeave(ref hscp);
  2414. }
  2415. }
  2416. /// <devdoc>
  2417. /// <para>
  2418. /// Merges this <see cref='System.Data.DataTable'/> into a specified <see cref='System.Data.DataTable'/>. with a value to preserve changes
  2419. /// made to the target, and a value to deal with missing schemas.
  2420. /// </para>
  2421. /// </devdoc>
  2422. public void Merge(DataTable table, bool preserveChanges, MissingSchemaAction missingSchemaAction)
  2423. {
  2424. IntPtr hscp;
  2425. Bid.ScopeEnter(out hscp, "<ds.DataSet.Merge|API> %d#, table=%d, preserveChanges=%d{bool}, missingSchemaAction=%d{ds.MissingSchemaAction}\n", ObjectID, (table != null) ? table.ObjectID : 0, preserveChanges, (int)missingSchemaAction);
  2426. try {
  2427. // Argument checks
  2428. if (table == null)
  2429. throw ExceptionBuilder.ArgumentNull("table");
  2430. switch (missingSchemaAction) { // @perfnote: Enum.IsDefined
  2431. case MissingSchemaAction.Add:
  2432. case MissingSchemaAction.Ignore:
  2433. case MissingSchemaAction.Error:
  2434. case MissingSchemaAction.AddWithKey:
  2435. Merger merger = new Merger(this, preserveChanges, missingSchemaAction);
  2436. merger.MergeTable(table);
  2437. break;
  2438. default:
  2439. throw Common.ADP.InvalidMissingSchemaAction(missingSchemaAction);
  2440. }
  2441. }
  2442. finally {
  2443. Bid.ScopeLeave(ref hscp);
  2444. }
  2445. }
  2446. /// <devdoc>
  2447. /// <para>[To be supplied.]</para>
  2448. /// </devdoc>
  2449. public void Merge(DataRow[] rows)
  2450. {
  2451. IntPtr hscp;
  2452. Bid.ScopeEnter(out hscp, "<ds.DataSet.Merge|API> %d#, rows\n", ObjectID);
  2453. try {
  2454. Merge(rows, false, MissingSchemaAction.Add);
  2455. }
  2456. finally {
  2457. Bid.ScopeLeave(ref hscp);
  2458. }
  2459. }
  2460. /// <devdoc>
  2461. /// <para>[To be supplied.]</para>
  2462. /// </devdoc>
  2463. public void Merge(DataRow[] rows, bool preserveChanges, MissingSchemaAction missingSchemaAction)
  2464. {
  2465. IntPtr hscp;
  2466. Bid.ScopeEnter(out hscp, "<ds.DataSet.Merge|API> %d#, preserveChanges=%d{bool}, missingSchemaAction=%d{ds.MissingSchemaAction}\n", ObjectID, preserveChanges, (int)missingSchemaAction);
  2467. try {
  2468. // Argument checks
  2469. if (rows == null)
  2470. throw ExceptionBuilder.ArgumentNull("rows");
  2471. switch (missingSchemaAction) { // @perfnote: Enum.IsDefined
  2472. case MissingSchemaAction.Add:
  2473. case MissingSchemaAction.Ignore:
  2474. case MissingSchemaAction.Error:
  2475. case MissingSchemaAction.AddWithKey:
  2476. Merger merger = new Merger(this, preserveChanges, missingSchemaAction);
  2477. merger.MergeRows(rows);
  2478. break;
  2479. default:
  2480. throw Common.ADP.InvalidMissingSchemaAction(missingSchemaAction);
  2481. }
  2482. }
  2483. finally {
  2484. Bid.ScopeLeave(ref hscp);
  2485. }
  2486. }
  2487. protected virtual void OnPropertyChanging(PropertyChangedEventArgs pcevent)
  2488. {
  2489. if (onPropertyChangingDelegate != null)
  2490. onPropertyChangingDelegate(this, pcevent);
  2491. }
  2492. /// <devdoc>
  2493. /// Inheriting classes should override this method to handle this event.
  2494. /// Call base.OnMergeFailed to send this event to any registered event
  2495. /// listeners.
  2496. /// </devdoc>
  2497. internal void OnMergeFailed(MergeFailedEventArgs mfevent)
  2498. {
  2499. if (onMergeFailed != null)
  2500. onMergeFailed(this, mfevent);
  2501. else
  2502. throw ExceptionBuilder.MergeFailed(mfevent.Conflict);
  2503. }
  2504. internal void RaiseMergeFailed(DataTable table, string conflict, MissingSchemaAction missingSchemaAction)
  2505. {
  2506. if (MissingSchemaAction.Error == missingSchemaAction)
  2507. throw ExceptionBuilder.MergeFailed(conflict);
  2508. MergeFailedEventArgs mfevent = new MergeFailedEventArgs(table, conflict);
  2509. OnMergeFailed(mfevent);
  2510. return;
  2511. }
  2512. internal void OnDataRowCreated(DataRow row) {
  2513. if (onDataRowCreated != null)
  2514. onDataRowCreated(this, row);
  2515. }
  2516. internal void OnClearFunctionCalled(DataTable table) {
  2517. if (onClearFunctionCalled != null)
  2518. onClearFunctionCalled(this, table);
  2519. }
  2520. private void OnInitialized() {
  2521. if (onInitialized != null) {
  2522. onInitialized(this, EventArgs.Empty);
  2523. }
  2524. }
  2525. /// <devdoc>
  2526. /// This method should be overriden by subclasses to restrict tables being removed.
  2527. /// </devdoc>
  2528. protected internal virtual void OnRemoveTable(DataTable table) {
  2529. }
  2530. internal void OnRemovedTable(DataTable table) {
  2531. DataViewManager viewManager = defaultViewManager;
  2532. if (null != viewManager) {
  2533. viewManager.DataViewSettings.Remove(table);
  2534. }
  2535. }
  2536. /// <devdoc>
  2537. /// This method should be overriden by subclasses to restrict tables being removed.
  2538. /// </devdoc>
  2539. protected virtual void OnRemoveRelation(DataRelation relation)
  2540. {
  2541. }
  2542. //
  2543. internal void OnRemoveRelationHack(DataRelation relation)
  2544. {
  2545. OnRemoveRelation(relation);
  2546. }
  2547. protected internal void RaisePropertyChanging(string name)
  2548. {
  2549. OnPropertyChanging(new PropertyChangedEventArgs(name));
  2550. }
  2551. internal DataTable[] TopLevelTables()
  2552. {
  2553. return TopLevelTables(false);
  2554. }
  2555. internal DataTable[] TopLevelTables(bool forSchema)
  2556. {
  2557. // first let's figure out if we can represent the given dataSet as a tree using
  2558. // the fact that all connected undirected graphs with n-1 edges are trees.
  2559. List<DataTable> topTables = new List<DataTable>();
  2560. if (forSchema) {
  2561. // prepend the tables that are nested more than once
  2562. for (int i = 0; i < Tables.Count; i++)
  2563. {
  2564. DataTable table = Tables[i];
  2565. if (table.NestedParentsCount > 1 || table.SelfNested)
  2566. topTables.Add(table);
  2567. }
  2568. }
  2569. for (int i = 0; i < Tables.Count; i++)
  2570. {
  2571. DataTable table = Tables[i];
  2572. if (table.NestedParentsCount == 0 && !topTables.Contains(table))
  2573. topTables.Add(table);
  2574. }
  2575. if (topTables.Count == 0)
  2576. return zeroTables;
  2577. return topTables.ToArray();
  2578. }
  2579. /// <devdoc>
  2580. /// This method rolls back all the changes to have been made to this DataSet since
  2581. /// it was loaded or the last time AcceptChanges was called.
  2582. /// Any rows still in edit-mode cancel their edits. New rows get removed. Modified and
  2583. /// Deleted rows return back to their original state.
  2584. /// </devdoc>
  2585. public virtual void RejectChanges()
  2586. {
  2587. IntPtr hscp;
  2588. Bid.ScopeEnter(out hscp, "<ds.DataSet.RejectChanges|API> %d#\n", ObjectID);
  2589. try {
  2590. bool fEnforce = EnforceConstraints;
  2591. EnforceConstraints = false;
  2592. for (int i = 0; i < Tables.Count; i++)
  2593. Tables[i].RejectChanges();
  2594. EnforceConstraints = fEnforce;
  2595. }
  2596. finally {
  2597. Bid.ScopeLeave(ref hscp);
  2598. }
  2599. }
  2600. /// <devdoc>
  2601. /// Resets the dataSet back to it's original state. Subclasses should override
  2602. /// to restore back to it's original state.
  2603. ///
  2604. public virtual void Reset()
  2605. {
  2606. IntPtr hscp;
  2607. Bid.ScopeEnter(out hscp, "<ds.DataSet.Reset|API> %d#\n", ObjectID);
  2608. try {
  2609. for (int i = 0; i < Tables.Count; i++) {
  2610. ConstraintCollection cons = Tables[i].Constraints;
  2611. for (int j = 0; j < cons.Count; ) {
  2612. if (cons[j] is ForeignKeyConstraint) {
  2613. cons.Remove(cons[j]);
  2614. }
  2615. else
  2616. j++;
  2617. }
  2618. }
  2619. // SQLBU 502734: because of SQLBU 501916, dependent tables need to be notified when a table is cleared
  2620. // if relations are removed first, then exceptions happen
  2621. Clear();
  2622. Relations.Clear();
  2623. Tables.Clear();
  2624. }
  2625. finally {
  2626. Bid.ScopeLeave(ref hscp);
  2627. }
  2628. }
  2629. internal bool ValidateCaseConstraint() {
  2630. IntPtr hscp;
  2631. Bid.ScopeEnter(out hscp, "<ds.DataSet.ValidateCaseConstraint|INFO> %d#\n", ObjectID);
  2632. try {
  2633. DataRelation relation = null;
  2634. for (int i = 0; i < Relations.Count; i++) {
  2635. relation = Relations[i];
  2636. if (relation.ChildTable.CaseSensitive != relation.ParentTable.CaseSensitive)
  2637. return false;
  2638. }
  2639. ForeignKeyConstraint constraint = null;
  2640. ConstraintCollection constraints = null;
  2641. for (int i = 0; i < Tables.Count; i++) {
  2642. constraints = Tables[i].Constraints;
  2643. for (int j = 0; j < constraints.Count; j++) {
  2644. if (constraints[j] is ForeignKeyConstraint) {
  2645. constraint = (ForeignKeyConstraint)constraints[j];
  2646. if (constraint.Table.CaseSensitive != constraint.RelatedTable.CaseSensitive)
  2647. return false;
  2648. }
  2649. }
  2650. }
  2651. return true;
  2652. }
  2653. finally {
  2654. Bid.ScopeLeave(ref hscp);
  2655. }
  2656. }
  2657. internal bool ValidateLocaleConstraint() {
  2658. IntPtr hscp;
  2659. Bid.ScopeEnter(out hscp, "<ds.DataSet.ValidateLocaleConstraint|INFO> %d#\n", ObjectID);
  2660. try {
  2661. DataRelation relation = null;
  2662. for (int i = 0; i < Relations.Count; i++) {
  2663. relation = Relations[i];
  2664. if (relation.ChildTable.Locale.LCID != relation.ParentTable.Locale.LCID)
  2665. return false;
  2666. }
  2667. ForeignKeyConstraint constraint = null;
  2668. ConstraintCollection constraints = null;
  2669. for (int i = 0; i < Tables.Count; i++) {
  2670. constraints = Tables[i].Constraints;
  2671. for (int j = 0; j < constraints.Count; j++) {
  2672. if (constraints[j] is ForeignKeyConstraint) {
  2673. constraint = (ForeignKeyConstraint)constraints[j];
  2674. if (constraint.Table.Locale.LCID != constraint.RelatedTable.Locale.LCID)
  2675. return false;
  2676. }
  2677. }
  2678. }
  2679. return true;
  2680. }
  2681. finally {
  2682. Bid.ScopeLeave(ref hscp);
  2683. }
  2684. }
  2685. // [....]: may be better to rewrite this as nonrecursive?
  2686. internal DataTable FindTable(DataTable baseTable, PropertyDescriptor[] props, int propStart) {
  2687. if (props.Length < propStart + 1)
  2688. return baseTable;
  2689. PropertyDescriptor currentProp = props[propStart];
  2690. if (baseTable == null) {
  2691. // the accessor is the table name. if we don't find it, return null.
  2692. if (currentProp is DataTablePropertyDescriptor) {
  2693. return FindTable(((DataTablePropertyDescriptor)currentProp).Table, props, propStart + 1);
  2694. }
  2695. return null;
  2696. }
  2697. if (currentProp is DataRelationPropertyDescriptor) {
  2698. return FindTable(((DataRelationPropertyDescriptor)currentProp).Relation.ChildTable, props, propStart + 1);
  2699. }
  2700. return null;
  2701. }
  2702. protected virtual void ReadXmlSerializable(XmlReader reader) {
  2703. //WebData 96421 and 104709, this is DataSet side fix for the thrown exception
  2704. // <DataSet xsi:nil="true"> does not mean DataSet is null,but it does not have any child
  2705. // so dont do anything, ignore the attributes and just return empty DataSet;
  2706. this.UseDataSetSchemaOnly = false;
  2707. this.UdtIsWrapped = false;
  2708. if (reader.HasAttributes) {
  2709. const string xsinill = Keywords.XSI + ":" + Keywords.XSI_NIL;
  2710. if (reader.MoveToAttribute(xsinill)) {
  2711. string nilAttrib = reader.GetAttribute(xsinill);
  2712. if (string.Compare(nilAttrib, "true", StringComparison.Ordinal) == 0) {// case sensitive true comparison
  2713. MoveToElement(reader, 1);
  2714. return;
  2715. }
  2716. }
  2717. const string useDataSetSchemaOnlyString = Keywords.MSD + ":" + Keywords.USEDATASETSCHEMAONLY;
  2718. if (reader.MoveToAttribute(useDataSetSchemaOnlyString)) {
  2719. string _useDataSetSchemaOnly = reader.GetAttribute(useDataSetSchemaOnlyString);
  2720. if (string.Equals(_useDataSetSchemaOnly, "true", StringComparison.Ordinal) ||
  2721. string.Equals(_useDataSetSchemaOnly, "1", StringComparison.Ordinal))
  2722. {
  2723. this.UseDataSetSchemaOnly = true;
  2724. }
  2725. else if (!string.Equals(_useDataSetSchemaOnly, "false", StringComparison.Ordinal) &&
  2726. !string.Equals(_useDataSetSchemaOnly, "0", StringComparison.Ordinal))
  2727. {
  2728. throw ExceptionBuilder.InvalidAttributeValue(Keywords.USEDATASETSCHEMAONLY, _useDataSetSchemaOnly);
  2729. }
  2730. }
  2731. const string udtIsWrappedString = Keywords.MSD + ":" + Keywords.UDTCOLUMNVALUEWRAPPED;
  2732. if (reader.MoveToAttribute(udtIsWrappedString)) {
  2733. string _udtIsWrappedString = reader.GetAttribute(udtIsWrappedString);
  2734. if (string.Equals(_udtIsWrappedString, "true", StringComparison.Ordinal) ||
  2735. string.Equals(_udtIsWrappedString, "1", StringComparison.Ordinal))
  2736. {
  2737. this.UdtIsWrapped = true;
  2738. }
  2739. else if (!string.Equals(_udtIsWrappedString, "false", StringComparison.Ordinal) &&
  2740. !string.Equals(_udtIsWrappedString, "0", StringComparison.Ordinal))
  2741. {
  2742. throw ExceptionBuilder.InvalidAttributeValue(Keywords.UDTCOLUMNVALUEWRAPPED, _udtIsWrappedString);
  2743. }
  2744. }
  2745. }
  2746. ReadXml(reader, XmlReadMode.DiffGram, true);
  2747. }
  2748. protected virtual System.Xml.Schema.XmlSchema GetSchemaSerializable() {
  2749. return null;
  2750. }
  2751. /************************************************************************
  2752. To publish
  2753. int_tools\webserviceadmin.exe -install Application Application.dll
  2754. To test
  2755. http://localhost/application/service.asmx?wsdl
  2756. or
  2757. wsdl.exe /namespace:UserNamespace http://localhost/Application/Service.asmx?wsdl /out:Service.cs
  2758. The V1.0 & V1.1 WSDL for Untyped DataSet being returned as a result (no parameters)
  2759. <s:element name="anyUserSpecifiedMethodName">
  2760. <!-- This is where parameters go -->
  2761. <s:complexType />
  2762. </s:element>
  2763. <s:element name="anyUserSpecifiedMethodName"+"Response">
  2764. <s:complexType>
  2765. <s:sequence>
  2766. <s:element minOccurs="0" maxOccurs="1" name="anyUserSpecifiedMethodName"+"Result">
  2767. <s:complexType>
  2768. <s:sequence>
  2769. <s:element ref="s:schema" />
  2770. <s:any />
  2771. </s:sequence>
  2772. </s:complexType>
  2773. </s:element>
  2774. </s:sequence>
  2775. </s:complexType>
  2776. </s:element>
  2777. The V1.0 & V1.1 WSDL for Untyped DataSet as parameter, string for the result
  2778. <s:element name="anyUserSpecifiedMethodName">
  2779. <!-- This is where parameters go -->
  2780. <s:complexType>
  2781. <s:sequence>
  2782. <s:element minOccurs="0" maxOccurs="1" name="set">
  2783. <s:complexType>
  2784. <s:sequence>
  2785. <s:element ref="s:schema" />
  2786. <s:any />
  2787. </s:sequence>
  2788. </s:complexType>
  2789. </s:element>
  2790. </s:sequence>
  2791. </s:complexType>
  2792. </s:element>
  2793. <s:element name="anyUserSpecifiedMethodName"+"Response">
  2794. <s:complexType>
  2795. <s:sequence>
  2796. <s:element minOccurs="0" maxOccurs="1" name="anyUserSpecifiedMethodName"+"Result" type="s:string" />
  2797. </s:sequence>
  2798. </s:complexType>
  2799. </s:element>
  2800. The V2.0 WSDL for Untyped DataSet being returned as a result (no parameters)
  2801. <s:element name="anyUserSpecifiedMethodName">
  2802. <!-- This is where parameters go -->
  2803. <s:complexType />
  2804. </s:element>
  2805. <s:element name="anyUserSpecifiedMethodName"+"Response">
  2806. <s:complexType>
  2807. <s:sequence>
  2808. <s:element minOccurs="0" maxOccurs="1" name="anyUserSpecifiedMethodName"+"Result">
  2809. <s:complexType>
  2810. <s:sequence maxOccurs="unbounded">
  2811. <s:any minOccurs="0" namespace="http://www.w3.org/2001/XMLSchema" processContents="lax" />
  2812. <s:any minOccurs="0" namespace="urn:schemas-microsoft-com:xml-diffgram-v1" processContents="lax" />
  2813. </s:sequence>
  2814. </s:complexType>
  2815. </s:element>
  2816. </s:sequence>
  2817. </s:complexType>
  2818. </s:element>
  2819. The V2.0 WSDL for Untyped DataSet as a parameter, string for the result
  2820. <s:element name="anyUserSpecifiedMethodName">
  2821. <!-- This is where parameters go -->
  2822. <s:complexType>
  2823. <s:sequence>
  2824. <s:element minOccurs="0" maxOccurs="1" name="anyUserSpecifiedParameterName">
  2825. <s:complexType>
  2826. <s:sequence maxOccurs="unbounded">
  2827. <s:any minOccurs="0" namespace="http://www.w3.org/2001/XMLSchema" processContents="lax" />
  2828. <s:any minOccurs="0" namespace="urn:schemas-microsoft-com:xml-diffgram-v1" processContents="lax" />
  2829. </s:sequence>
  2830. </s:complexType>
  2831. </s:element>
  2832. </s:sequence>
  2833. </s:complexType>
  2834. </s:element>
  2835. <s:element name="anyUserSpecifiedMethodName"+"Response">
  2836. <s:complexType>
  2837. <s:sequence>
  2838. <s:element minOccurs="0" maxOccurs="1" name="anyUserSpecifiedMethodName"+"Result" type="s:string" />
  2839. </s:sequence>
  2840. </s:complexType>
  2841. </s:element>
  2842. The V1.0, V1.1 & V2.0 WSDL for Typed DataSet
  2843. <s:import schemaLocation="http://localhost/application/service.asmx?schema=typedDataSetName" namespace="typedDataSetName" />
  2844. <s:element name="anyUserSpecifiedMethodName">
  2845. <!-- This is where parameters go -->
  2846. <s:complexType />
  2847. </s:element>
  2848. <s:element name="anyUserSpecifiedMethodName"+"Response">
  2849. <s:complexType>
  2850. <s:sequence>
  2851. <s:element minOccurs="0" maxOccurs="1" name="anyUserSpecifiedMethodName"+"Result">
  2852. <s:complexType>
  2853. <s:sequence>
  2854. <s:any namespace="typedDataSetName" />
  2855. </s:sequence>
  2856. </s:complexType>
  2857. </s:element>
  2858. </s:sequence>
  2859. </s:complexType>
  2860. </s:element>
  2861. ************************************************************************/
  2862. public static XmlSchemaComplexType GetDataSetSchema(XmlSchemaSet schemaSet) {
  2863. // For performance resons we are exploiting the fact that config files content is constant
  2864. // for a given appdomain so we can safely cache the prepared schema complex type and reuse it
  2865. if (schemaTypeForWSDL == null) { // to change the config file, appdomain needs to restart; so it seems safe to cache the schema
  2866. XmlSchemaComplexType tempWSDL = new XmlSchemaComplexType();
  2867. XmlSchemaSequence sequence = new XmlSchemaSequence();
  2868. if (PublishLegacyWSDL())
  2869. { // Default is Version 1.0
  2870. XmlSchemaElement elem = new XmlSchemaElement();
  2871. elem.RefName = new XmlQualifiedName(Keywords.XSD_SCHEMA, Keywords.XSDNS);
  2872. sequence.Items.Add(elem);
  2873. XmlSchemaAny any = new XmlSchemaAny();
  2874. sequence.Items.Add(any);
  2875. }
  2876. else
  2877. { // this means Version == V2.0 or newer
  2878. XmlSchemaAny any = new XmlSchemaAny();
  2879. any.Namespace = XmlSchema.Namespace;
  2880. any.MinOccurs = 0;
  2881. any.ProcessContents = XmlSchemaContentProcessing.Lax;
  2882. sequence.Items.Add(any);
  2883. any = new XmlSchemaAny();
  2884. any.Namespace = Keywords.DFFNS;
  2885. any.MinOccurs = 0; // when recognizing WSDL - MinOccurs="0" denotes DataSet, a MinOccurs="1" for DataTable
  2886. any.ProcessContents = XmlSchemaContentProcessing.Lax;
  2887. sequence.Items.Add(any);
  2888. sequence.MaxOccurs = Decimal.MaxValue;
  2889. }
  2890. tempWSDL.Particle = sequence;
  2891. schemaTypeForWSDL = tempWSDL;
  2892. }
  2893. return schemaTypeForWSDL;
  2894. }
  2895. /********************************************
  2896. <configuration>
  2897. <configSections>
  2898. <section name="system.data.dataset" type="System.Configuration.NameValueFileSectionHandler, System, Version=%ASSEMBLY_VERSION%, Culture=neutral, PublicKeyToken=%ECMA_PUBLICKEY%" restartOnExternalChanges="false" />
  2899. </configSections>
  2900. <system.data.dataset>
  2901. <!-- if WSDL_VERSION is missing it will default to 1.0
  2902. <add key="WSDL_VERSION" value="1.0"/>
  2903. -->
  2904. <add key="WSDL_VERSION" value="2.0"/>
  2905. </system.data.dataset>
  2906. </configuration>
  2907. *******************************************/
  2908. private static bool PublishLegacyWSDL()
  2909. {
  2910. Single version = 1.0f; // Default is Version 1.0
  2911. #if !NO_CONFIGURATION
  2912. NameValueCollection settings = (NameValueCollection)PrivilegedConfigurationManager.GetSection(Keywords.WS_DATASETFULLQNAME);
  2913. if (settings != null)
  2914. {
  2915. string[] values = settings.GetValues(Keywords.WS_VERSION);
  2916. if ((null != values) && (0 < values.Length) && (null != values[0]))
  2917. { // will throw FormatException if not a valid number
  2918. version = Single.Parse(values[0], CultureInfo.InvariantCulture);
  2919. }
  2920. }
  2921. #endif
  2922. return (version < 2.0f); // if config does not exist, Default is Version 1.0
  2923. }
  2924. XmlSchema IXmlSerializable.GetSchema() {
  2925. if (GetType() == typeof(DataSet)) {
  2926. return null;
  2927. }
  2928. MemoryStream stream = new MemoryStream();
  2929. // WriteXmlSchema(new XmlTextWriter(stream, null));
  2930. XmlWriter writer = new XmlTextWriter(stream, null);
  2931. if (writer != null) {
  2932. (new XmlTreeGen(SchemaFormat.WebService)).Save(this, writer);
  2933. }
  2934. stream.Position = 0;
  2935. return XmlSchema.Read(new XmlTextReader(stream), null);
  2936. // return GetSchemaSerializable();
  2937. }
  2938. void IXmlSerializable.ReadXml(XmlReader reader) {
  2939. bool fNormalization = true;
  2940. XmlTextReader xmlTextReader = null;
  2941. IXmlTextParser xmlTextParser = reader as IXmlTextParser;
  2942. if (xmlTextParser != null) {
  2943. fNormalization = xmlTextParser.Normalized;
  2944. xmlTextParser.Normalized = false;
  2945. }
  2946. else {
  2947. xmlTextReader = reader as XmlTextReader;
  2948. if (xmlTextReader != null) {
  2949. fNormalization = xmlTextReader.Normalization;
  2950. xmlTextReader.Normalization = false;
  2951. }
  2952. }
  2953. ReadXmlSerializable(reader);
  2954. if (xmlTextParser != null)
  2955. xmlTextParser.Normalized = fNormalization;
  2956. else if (xmlTextReader != null)
  2957. xmlTextReader.Normalization = fNormalization;
  2958. }
  2959. void IXmlSerializable.WriteXml(XmlWriter writer) {
  2960. this.WriteXmlSchema(writer, SchemaFormat.WebService, (Converter<Type, string>)null);
  2961. this.WriteXml(writer, XmlWriteMode.DiffGram);
  2962. }
  2963. public virtual void Load(IDataReader reader, LoadOption loadOption, FillErrorEventHandler errorHandler, params DataTable[] tables) {
  2964. IntPtr hscp;
  2965. Bid.ScopeEnter(out hscp, "<ds.DataSet.Load|API> reader, loadOption=%d{ds.LoadOption}", (int)loadOption);
  2966. try {
  2967. foreach (DataTable dt in tables) {
  2968. Common.ADP.CheckArgumentNull(dt, "tables");
  2969. if (dt.DataSet != this) {
  2970. throw ExceptionBuilder.TableNotInTheDataSet(dt.TableName);
  2971. }
  2972. }
  2973. Common.LoadAdapter adapter = new Common.LoadAdapter();
  2974. adapter.FillLoadOption = loadOption;
  2975. adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
  2976. if (null != errorHandler) {
  2977. adapter.FillError += errorHandler;
  2978. }
  2979. adapter.FillFromReader(tables, reader, 0, 0);
  2980. if (!reader.IsClosed && !reader.NextResult()) { //
  2981. reader.Close();
  2982. }
  2983. }
  2984. finally {
  2985. Bid.ScopeLeave(ref hscp);
  2986. }
  2987. }
  2988. public void Load(IDataReader reader, LoadOption loadOption, params DataTable[] tables) {
  2989. Load(reader, loadOption, null, tables);
  2990. }
  2991. public void Load(IDataReader reader, LoadOption loadOption, params string[] tables) {
  2992. Common.ADP.CheckArgumentNull(tables, "tables");
  2993. DataTable[] dataTables = new DataTable[tables.Length];
  2994. for (int i = 0; i < tables.Length; i++) {
  2995. DataTable tempDT = this.Tables[tables[i]];
  2996. if (null == tempDT) {
  2997. tempDT = new DataTable(tables[i]);
  2998. // fxcop: new DataTable should inherit the CaseSensitive, Locale, Namespace from DataSet
  2999. Tables.Add(tempDT);
  3000. }
  3001. dataTables[i] = tempDT;
  3002. }
  3003. Load(reader, loadOption, null, dataTables);
  3004. }
  3005. public DataTableReader CreateDataReader() {
  3006. if (Tables.Count == 0)
  3007. throw ExceptionBuilder.CannotCreateDataReaderOnEmptyDataSet();
  3008. DataTable[] dataTables = new DataTable[Tables.Count];
  3009. for (int i = 0; i < Tables.Count; i++) {
  3010. dataTables[i] = Tables[i];
  3011. }
  3012. return CreateDataReader(dataTables);
  3013. }
  3014. public DataTableReader CreateDataReader(params DataTable[] dataTables) {
  3015. IntPtr hscp;
  3016. Bid.ScopeEnter(out hscp, "<ds.DataSet.GetDataReader|API> %d#\n", ObjectID);
  3017. try {
  3018. if (dataTables.Length == 0)
  3019. throw ExceptionBuilder.DataTableReaderArgumentIsEmpty();
  3020. for (int i = 0; i < dataTables.Length; i++) {
  3021. if (dataTables[i] == null)
  3022. throw ExceptionBuilder.ArgumentContainsNullValue();
  3023. }
  3024. return new DataTableReader(dataTables);
  3025. }
  3026. finally {
  3027. Bid.ScopeLeave(ref hscp);
  3028. }
  3029. }
  3030. internal string MainTableName {
  3031. get {
  3032. return mainTableName;
  3033. }
  3034. set {
  3035. this.mainTableName = value;
  3036. }
  3037. }
  3038. internal int ObjectID {
  3039. get {
  3040. return _objectID;
  3041. }
  3042. }
  3043. }
  3044. #if !NO_CODEDOM
  3045. public class DataSetSchemaImporterExtension : SchemaImporterExtension {
  3046. // DataSetSchemaImporterExtension is used for WebServices, it is used to recognize the schema of DataSet within wsdl
  3047. // If a non 2.0 enabled DataSetSchemaImporterExtension, wsdl will generate a classes that you can't cast to dataset / datatable
  3048. Hashtable importedTypes = new Hashtable();
  3049. /// <devdoc>
  3050. /// <para>[To be supplied.]</para>
  3051. /// </devdoc>
  3052. public override string ImportSchemaType(string name, string schemaNamespace, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider) {
  3053. IList values = schemas.GetSchemas(schemaNamespace);
  3054. if (values.Count != 1) {
  3055. return null;
  3056. }
  3057. XmlSchema schema = values[0] as XmlSchema;
  3058. if (schema == null)
  3059. return null;
  3060. XmlSchemaType type = (XmlSchemaType)schema.SchemaTypes[new XmlQualifiedName(name, schemaNamespace)];
  3061. return ImportSchemaType(type, context, schemas, importer, compileUnit, mainNamespace, options, codeProvider);
  3062. }
  3063. /// <devdoc>
  3064. /// <para>[To be supplied.]</para>
  3065. /// </devdoc>
  3066. public override string ImportSchemaType(XmlSchemaType type, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider) {
  3067. if (type == null) {
  3068. return null;
  3069. }
  3070. if (importedTypes[type] != null) {
  3071. mainNamespace.Imports.Add(new CodeNamespaceImport(typeof(DataSet).Namespace));
  3072. compileUnit.ReferencedAssemblies.Add("System.Data.dll");
  3073. return (string)importedTypes[type];
  3074. }
  3075. if (!(context is XmlSchemaElement))
  3076. return null;
  3077. XmlSchemaElement e = (XmlSchemaElement)context;
  3078. // recognizing the following is important, but not as part of SQLPT 120015394: Support WSI Compliant WSDL for DataSet
  3079. // <xs:element name="NewDataSet" msdata:IsDataSet="true">
  3080. // see also SQLBU 338644, 410965, 423446
  3081. //if (IsDataSet(e))
  3082. //{
  3083. // return GenerateTypedDataSet(e, schemas, mainNamespace, compileUnit.ReferencedAssemblies, codeProvider);
  3084. //}
  3085. if (type is XmlSchemaComplexType) {
  3086. XmlSchemaComplexType ct = (XmlSchemaComplexType)type;
  3087. if (ct.Particle is XmlSchemaSequence)
  3088. {
  3089. XmlSchemaObjectCollection items = ((XmlSchemaSequence)ct.Particle).Items;
  3090. if ((2 == items.Count) && (items[0] is XmlSchemaAny) && (items[1] is XmlSchemaAny))
  3091. {
  3092. XmlSchemaAny any0 = (XmlSchemaAny)items[0];
  3093. XmlSchemaAny any1 = (XmlSchemaAny)items[1];
  3094. if ((any0.Namespace == XmlSchema.Namespace) && (any1.Namespace == "urn:schemas-microsoft-com:xml-diffgram-v1"))
  3095. { // new diffgramm format
  3096. string ns = null;
  3097. foreach (XmlSchemaAttribute a in ct.Attributes)
  3098. {
  3099. if (a.Name == "namespace")
  3100. {
  3101. ns = a.FixedValue.Trim();
  3102. break;
  3103. }
  3104. }
  3105. bool isDataSet = false;
  3106. // check for DataSet or DataTable
  3107. if (((XmlSchemaSequence)ct.Particle).MaxOccurs == Decimal.MaxValue)
  3108. {
  3109. isDataSet = true;
  3110. }
  3111. else if (any0.MaxOccurs == Decimal.MaxValue)
  3112. {
  3113. isDataSet = false;
  3114. }
  3115. else
  3116. {
  3117. return null;
  3118. }
  3119. if (ns == null)
  3120. { //Un-Typed DataSet / DataTable
  3121. string typeName = isDataSet ? typeof(DataSet).FullName : typeof(DataTable).FullName;
  3122. importedTypes.Add(type, typeName);
  3123. mainNamespace.Imports.Add(new CodeNamespaceImport(typeof(DataSet).Namespace));
  3124. compileUnit.ReferencedAssemblies.Add("System.Data.dll");
  3125. return typeName;
  3126. }
  3127. else
  3128. { // Typed DataSet / DataTable
  3129. foreach (XmlSchema schema in schemas.GetSchemas(ns))
  3130. {
  3131. if ((schema != null) && (schema.Id != null))
  3132. {
  3133. XmlSchemaElement ds = FindDataSetElement(schema); // implement FindDataTableElement(schema)
  3134. if (ds != null)
  3135. {
  3136. return ImportSchemaType(ds.SchemaType, ds, schemas, importer, compileUnit, mainNamespace, options, codeProvider);
  3137. }
  3138. // else return null
  3139. }
  3140. }
  3141. return null;
  3142. }
  3143. }
  3144. }
  3145. }
  3146. if (ct.Particle is XmlSchemaSequence || ct.Particle is XmlSchemaAll) {
  3147. XmlSchemaObjectCollection items = ((XmlSchemaGroupBase)ct.Particle).Items;
  3148. if (items.Count == 2) {
  3149. if (!(items[0] is XmlSchemaElement && items[1] is XmlSchemaAny)) return null;
  3150. XmlSchemaElement schema = (XmlSchemaElement)items[0];
  3151. if (!(schema.RefName.Name == "schema" && schema.RefName.Namespace == XmlSchema.Namespace)) return null;
  3152. string typeName = typeof(DataSet).FullName;
  3153. importedTypes.Add(type, typeName);
  3154. mainNamespace.Imports.Add(new CodeNamespaceImport(typeof(DataSet).Namespace));
  3155. compileUnit.ReferencedAssemblies.Add("System.Data.dll");
  3156. return typeName;
  3157. }
  3158. else if (1 == items.Count)
  3159. {
  3160. XmlSchemaAny any = items[0] as XmlSchemaAny;
  3161. if ((null != any) &&
  3162. (null != any.Namespace) &&
  3163. (any.Namespace.IndexOfAny(new char[] { '#', ' ' }) < 0)) // special syntax (##any, ##other, ...) or more than one Uri present
  3164. {
  3165. foreach (XmlSchema schema in schemas.GetSchemas(any.Namespace))
  3166. {
  3167. if ((null != schema) &&
  3168. (null != schema.Id))
  3169. {
  3170. XmlSchemaElement ds = FindDataSetElement(schema);
  3171. if (ds != null)
  3172. {
  3173. return ImportSchemaType(ds.SchemaType, ds, schemas, importer, compileUnit, mainNamespace, options, codeProvider);
  3174. }
  3175. // else return null
  3176. }
  3177. // else return null
  3178. }
  3179. }
  3180. // else return null
  3181. }
  3182. }
  3183. }
  3184. return null;
  3185. }
  3186. internal XmlSchemaElement FindDataSetElement(XmlSchema schema) {
  3187. foreach (XmlSchemaObject item in schema.Items) {
  3188. if (item is XmlSchemaElement && IsDataSet((XmlSchemaElement)item)) {
  3189. return (XmlSchemaElement)item;
  3190. }
  3191. }
  3192. return null;
  3193. }
  3194. internal string GenerateTypedDataSet(XmlSchemaElement element, XmlSchemas schemas, CodeNamespace codeNamespace, StringCollection references, CodeDomProvider codeProvider) {
  3195. if (element == null)
  3196. return null;
  3197. if (importedTypes[element.SchemaType] != null)
  3198. return (string)importedTypes[element.SchemaType];
  3199. IList values = schemas.GetSchemas(element.QualifiedName.Namespace);
  3200. if (values.Count != 1) {
  3201. return null;
  3202. }
  3203. XmlSchema schema = values[0] as XmlSchema;
  3204. if (schema == null)
  3205. return null;
  3206. DataSet ds = new DataSet();
  3207. //
  3208. using (MemoryStream stream = new MemoryStream()) {
  3209. schema.Write(stream);
  3210. stream.Position = 0;
  3211. ds.ReadXmlSchema(stream);
  3212. }
  3213. #pragma warning disable 618 // ignore obsolete warning about TypedDataSetGenerator
  3214. CodeTypeDeclaration dsClass = new TypedDataSetGenerator().GenerateCode(ds, codeNamespace, codeProvider.CreateGenerator());
  3215. #pragma warning restore 618
  3216. string typeName = dsClass.Name;
  3217. importedTypes.Add(element.SchemaType, typeName);
  3218. references.Add("System.Data.dll");
  3219. return typeName;
  3220. }
  3221. internal static bool IsDataSet(XmlSchemaElement e) {
  3222. if (e.UnhandledAttributes != null) {
  3223. foreach (XmlAttribute a in e.UnhandledAttributes) {
  3224. if (a.LocalName == "IsDataSet" && a.NamespaceURI == Keywords.MSDNS) {
  3225. // currently the msdata:IsDataSet uses its own format for the boolean values
  3226. if (a.Value == "True" || a.Value == "true" || a.Value == "1") return true;
  3227. }
  3228. }
  3229. }
  3230. return false;
  3231. }
  3232. }
  3233. #endif
  3234. }