XMLSchema.cs 112 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520
  1. //------------------------------------------------------------------------------
  2. // <copyright file="XMLSchema.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.Data.Common;
  11. using System.Xml;
  12. using System.Xml.Schema;
  13. using System.Diagnostics;
  14. using System.Collections;
  15. using System.Collections.Generic;
  16. using System.Globalization;
  17. using System.ComponentModel;
  18. using System.Security;
  19. using System.Security.Permissions;
  20. internal class XMLSchema {
  21. internal static TypeConverter GetConverter(Type type) {
  22. HostProtectionAttribute protAttrib = new HostProtectionAttribute();
  23. protAttrib.SharedState = true;
  24. CodeAccessPermission permission = (CodeAccessPermission)protAttrib.CreatePermission();
  25. permission.Assert();
  26. try {
  27. return TypeDescriptor.GetConverter(type);
  28. }
  29. finally {
  30. CodeAccessPermission.RevertAssert();
  31. }
  32. }
  33. internal static void SetProperties(Object instance, XmlAttributeCollection attrs) {
  34. // This is called from both XSD and XDR schemas.
  35. // Do we realy need it in XSD ???
  36. for (int i = 0; i < attrs.Count; i++) {
  37. if (attrs[i].NamespaceURI == Keywords.MSDNS) {
  38. string name = attrs[i].LocalName;
  39. string value = attrs[i].Value;
  40. if (name == "DefaultValue" || name == "RemotingFormat")
  41. continue;
  42. // Webdata 97925, skipp expressions, we will handle them after SetProperties (in xdrschema)
  43. if (name == "Expression" && instance is DataColumn)
  44. continue;
  45. PropertyDescriptor pd = TypeDescriptor.GetProperties(instance)[name];
  46. if (pd != null) {
  47. // Standard property
  48. Type type = pd.PropertyType;
  49. TypeConverter converter = XMLSchema.GetConverter(type);
  50. object propValue;
  51. if (converter.CanConvertFrom(typeof(string))) {
  52. propValue = converter.ConvertFromString(value);
  53. }else if (type == typeof(Type)) {
  54. propValue = DataStorage.GetType(value);
  55. }else if (type == typeof(CultureInfo)) {
  56. propValue = new CultureInfo(value);
  57. }else {
  58. throw ExceptionBuilder.CannotConvert(value,type.FullName);
  59. }
  60. pd.SetValue(instance, propValue);
  61. }
  62. }
  63. }
  64. }// SetProperties
  65. internal static bool FEqualIdentity(XmlNode node, String name, String ns) {
  66. if (node != null && node.LocalName == name && node.NamespaceURI == ns)
  67. return true;
  68. return false;
  69. }
  70. internal static bool GetBooleanAttribute(XmlElement element, String attrName, String attrNS, bool defVal) {
  71. string value = element.GetAttribute(attrName, attrNS);
  72. if (value == null || value.Length == 0) {
  73. return defVal;
  74. }
  75. if ((value == Keywords.TRUE) || (value == Keywords.ONE_DIGIT)){
  76. return true;
  77. }
  78. if ((value == Keywords.FALSE) || (value == Keywords.ZERO_DIGIT)){
  79. return false;
  80. }
  81. // Error processing:
  82. throw ExceptionBuilder.InvalidAttributeValue(attrName, value);
  83. }
  84. internal static string GenUniqueColumnName(string proposedName, DataTable table) {
  85. if (table.Columns.IndexOf(proposedName) >= 0) {
  86. for (int i=0; i <= table.Columns.Count; i++) {
  87. string tempName = proposedName + "_" + (i).ToString(CultureInfo.InvariantCulture);
  88. if (table.Columns.IndexOf(tempName) >= 0) {
  89. continue;
  90. }
  91. else {
  92. return tempName;
  93. }
  94. }
  95. }
  96. return proposedName;
  97. }
  98. }
  99. internal sealed class ConstraintTable {
  100. public DataTable table;
  101. public XmlSchemaIdentityConstraint constraint;
  102. public ConstraintTable(DataTable t, XmlSchemaIdentityConstraint c) {
  103. table = t;
  104. constraint = c;
  105. }
  106. }
  107. internal sealed class XSDSchema : XMLSchema
  108. {
  109. XmlSchemaSet _schemaSet = null;
  110. XmlSchemaElement dsElement = null;
  111. DataSet _ds = null;
  112. String _schemaName = null;
  113. private ArrayList ColumnExpressions;
  114. private Hashtable ConstraintNodes;
  115. private ArrayList RefTables;
  116. private ArrayList complexTypes;
  117. XmlSchemaObjectCollection annotations;
  118. XmlSchemaObjectCollection elements;
  119. Hashtable attributes;
  120. Hashtable elementsTable;
  121. Hashtable attributeGroups;
  122. Hashtable schemaTypes;
  123. Hashtable expressions;
  124. Dictionary <DataTable, List<DataTable>> tableDictionary;
  125. Hashtable udSimpleTypes;
  126. Hashtable existingSimpleTypeMap;
  127. private bool fromInference = false;
  128. internal bool FromInference {
  129. get {
  130. return fromInference;
  131. }
  132. set {
  133. fromInference = value;
  134. }
  135. }
  136. private void CollectElementsAnnotations(XmlSchema schema){
  137. ArrayList schemaList = new ArrayList();
  138. CollectElementsAnnotations(schema, schemaList);
  139. schemaList.Clear();
  140. }
  141. private void CollectElementsAnnotations(XmlSchema schema, ArrayList schemaList){
  142. if (schemaList.Contains(schema)) {
  143. return;
  144. }
  145. schemaList.Add(schema);
  146. foreach(object item in schema.Items) {
  147. if (item is XmlSchemaAnnotation) {
  148. annotations.Add((XmlSchemaAnnotation)item);
  149. }
  150. if (item is XmlSchemaElement) {
  151. XmlSchemaElement elem = (XmlSchemaElement)item;
  152. elements.Add(elem);
  153. elementsTable[elem.QualifiedName] = elem;
  154. }
  155. if (item is XmlSchemaAttribute) {
  156. XmlSchemaAttribute attr = (XmlSchemaAttribute)item;
  157. attributes[attr.QualifiedName] = attr;
  158. }
  159. if (item is XmlSchemaAttributeGroup) {
  160. XmlSchemaAttributeGroup attr = (XmlSchemaAttributeGroup)item;
  161. attributeGroups[attr.QualifiedName] = attr;
  162. }
  163. if (item is XmlSchemaType) {
  164. string MSDATATargetNamespace = null;
  165. if (item is XmlSchemaSimpleType) {
  166. MSDATATargetNamespace = XSDSchema.GetMsdataAttribute((XmlSchemaType)item, Keywords.TARGETNAMESPACE);
  167. }
  168. XmlSchemaType type = (XmlSchemaType)item;
  169. schemaTypes[type.QualifiedName] = type;
  170. // Webdata 92054 if we have a User Defined simple type, cache it so later we may need for mapping
  171. // meanwhile more convinient solution would be to directly use schemaTypes, but it would be more complex to handle
  172. XmlSchemaSimpleType xmlSimpleType = (item as XmlSchemaSimpleType );
  173. if (xmlSimpleType != null) {
  174. if (udSimpleTypes == null) {
  175. udSimpleTypes = new Hashtable();
  176. }
  177. udSimpleTypes[type.QualifiedName.ToString()] = xmlSimpleType;
  178. DataColumn dc = (DataColumn)existingSimpleTypeMap[type.QualifiedName.ToString()];
  179. // Assumption is that our simple type qualified name ihas the same output as XmlSchemaSimpleType type.QualifiedName.ToString()
  180. SimpleType tmpSimpleType = (dc != null)? dc.SimpleType: null;
  181. //
  182. if (tmpSimpleType != null) {
  183. SimpleType tmpDataSimpleType = new SimpleType(xmlSimpleType);
  184. string errorStr = tmpSimpleType.HasConflictingDefinition(tmpDataSimpleType);
  185. if (errorStr.Length != 0) {
  186. throw ExceptionBuilder.InvalidDuplicateNamedSimpleTypeDelaration(tmpDataSimpleType.SimpleTypeQualifiedName, errorStr);
  187. }
  188. }
  189. }
  190. }
  191. }
  192. foreach(XmlSchemaExternal include in schema.Includes) {
  193. if (include is XmlSchemaImport)
  194. continue;
  195. if (include.Schema != null) {
  196. CollectElementsAnnotations(include.Schema, schemaList);
  197. }
  198. }
  199. }
  200. internal static string QualifiedName(string name) {
  201. int iStart = name.IndexOf(':');
  202. if (iStart == -1)
  203. return Keywords.XSD_PREFIXCOLON + name;
  204. else
  205. return name;
  206. }
  207. internal static void SetProperties(Object instance, XmlAttribute[] attrs) {
  208. // This is called from both XSD and XDR schemas.
  209. // Do we realy need it in XSD ???
  210. if (attrs == null)
  211. return;
  212. for (int i = 0; i < attrs.Length; i++) {
  213. if (attrs[i].NamespaceURI == Keywords.MSDNS) {
  214. string name = attrs[i].LocalName;
  215. string value = attrs[i].Value;
  216. if (name == "DefaultValue" || name == "Ordinal" || name == "Locale" || name == "RemotingFormat")
  217. continue;
  218. if (name == "Expression" && instance is DataColumn) // Webdata 97925: we will handle columnexpressions at HandleColumnExpression
  219. continue;
  220. if (name == "DataType") {
  221. DataColumn col = instance as DataColumn;
  222. if (col != null) {
  223. col.DataType = DataStorage.GetType(value);
  224. }
  225. continue;
  226. }
  227. PropertyDescriptor pd = TypeDescriptor.GetProperties(instance)[name];
  228. if (pd != null) {
  229. // Standard property
  230. Type type = pd.PropertyType;
  231. TypeConverter converter = XMLSchema.GetConverter(type);
  232. object propValue;
  233. if (converter.CanConvertFrom(typeof(string))) {
  234. propValue = converter.ConvertFromString(value);
  235. }else if (type == typeof(Type)) {
  236. propValue = Type.GetType(value);
  237. }else if (type == typeof(CultureInfo)) {
  238. propValue = new CultureInfo(value);
  239. }else {
  240. throw ExceptionBuilder.CannotConvert(value,type.FullName);
  241. }
  242. pd.SetValue(instance, propValue);
  243. }
  244. }
  245. }
  246. }// SetProperties
  247. private static void SetExtProperties(Object instance, XmlAttribute[] attrs) {
  248. PropertyCollection props = null;
  249. if (attrs == null)
  250. return;
  251. for (int i = 0; i < attrs.Length; i++) {
  252. if (attrs[i].NamespaceURI == Keywords.MSPROPNS) {
  253. if(props == null) {
  254. object val = TypeDescriptor.GetProperties(instance)["ExtendedProperties"].GetValue(instance);
  255. Debug.Assert(val is PropertyCollection, "We can set values only for classes that have ExtendedProperties");
  256. props = (PropertyCollection) val;
  257. }
  258. string propName = XmlConvert.DecodeName(attrs[i].LocalName);
  259. if (instance is ForeignKeyConstraint) {
  260. if (propName.StartsWith(Keywords.MSD_FK_PREFIX, StringComparison.Ordinal))
  261. propName = propName.Substring(3);
  262. else
  263. continue;
  264. }
  265. if ((instance is DataRelation) && (propName.StartsWith(Keywords.MSD_REL_PREFIX, StringComparison.Ordinal))) {
  266. propName = propName.Substring(4);
  267. }
  268. else if ((instance is DataRelation) && (propName.StartsWith(Keywords.MSD_FK_PREFIX, StringComparison.Ordinal))) {
  269. continue;
  270. }
  271. props.Add(propName, attrs[i].Value);
  272. }
  273. }
  274. }// SetExtProperties
  275. private void HandleColumnExpression(Object instance, XmlAttribute[] attrs) {
  276. if (attrs == null)
  277. return;
  278. DataColumn dc = instance as DataColumn;
  279. Debug.Assert(dc != null, "HandleColumnExpression is supposed to be called for DataColumn");
  280. if (dc != null ) {
  281. for (int i = 0; i < attrs.Length; i++) {
  282. if (attrs[i].NamespaceURI == Keywords.MSDNS) {
  283. if (attrs[i].LocalName == "Expression"){
  284. if (this.expressions == null)
  285. this.expressions = new Hashtable();
  286. this.expressions[dc] = attrs[i].Value;
  287. ColumnExpressions.Add(dc);
  288. break;
  289. }
  290. }
  291. }
  292. }
  293. }
  294. internal static String GetMsdataAttribute(XmlSchemaAnnotated node, String ln) {
  295. XmlAttribute[] nodeAttributes = node.UnhandledAttributes;
  296. if (nodeAttributes!=null)
  297. for(int i=0; i<nodeAttributes.Length;i++)
  298. if (nodeAttributes[i].LocalName == ln && nodeAttributes[i].NamespaceURI == Keywords.MSDNS)
  299. return nodeAttributes[i].Value;
  300. return null;
  301. }
  302. private static void SetExtProperties(Object instance, XmlAttributeCollection attrs) {
  303. PropertyCollection props = null;
  304. for (int i = 0; i < attrs.Count; i++) {
  305. if (attrs[i].NamespaceURI == Keywords.MSPROPNS) {
  306. if(props == null) {
  307. object val = TypeDescriptor.GetProperties(instance)["ExtendedProperties"].GetValue(instance);
  308. Debug.Assert(val is PropertyCollection, "We can set values only for classes that have ExtendedProperties");
  309. props = (PropertyCollection) val;
  310. }
  311. string propName = XmlConvert.DecodeName(attrs[i].LocalName);
  312. props.Add(propName, attrs[i].Value);
  313. }
  314. }
  315. }// SetExtProperties
  316. internal void HandleRefTableProperties(ArrayList RefTables, XmlSchemaElement element) {
  317. string typeName = GetInstanceName(element);
  318. DataTable table = _ds.Tables.GetTable(XmlConvert.DecodeName(typeName), element.QualifiedName.Namespace);
  319. Debug.Assert(table != null, "ref table should have been already created");
  320. SetProperties(table, element.UnhandledAttributes);
  321. SetExtProperties(table, element.UnhandledAttributes);
  322. }
  323. internal void HandleRelation(XmlElement node, bool fNested) {
  324. string strName;
  325. string parentName;
  326. string childName;
  327. string [] parentNames;
  328. string [] childNames;
  329. string value;
  330. bool fCreateConstraints = false; //if we have a relation,
  331. //we do not have constraints
  332. DataRelationCollection rels = _ds.Relations;
  333. DataRelation relation;
  334. DataColumn [] parentKey;
  335. DataColumn [] childKey;
  336. DataTable parent;
  337. DataTable child;
  338. int keyLength;
  339. strName = XmlConvert.DecodeName(node.GetAttribute(Keywords.NAME));
  340. for (int i = 0; i < rels.Count; ++i) {
  341. if (0 == String.Compare(rels[i].RelationName, strName, StringComparison.Ordinal))
  342. return;
  343. }
  344. parentName = node.GetAttribute(Keywords.MSD_PARENT, Keywords.MSDNS);
  345. if (parentName == null || parentName.Length==0)
  346. throw ExceptionBuilder.RelationParentNameMissing(strName);
  347. parentName = XmlConvert.DecodeName(parentName);
  348. childName = node.GetAttribute(Keywords.MSD_CHILD, Keywords.MSDNS);
  349. if (childName == null || childName.Length==0)
  350. throw ExceptionBuilder.RelationChildNameMissing(strName);
  351. childName = XmlConvert.DecodeName(childName);
  352. value = node.GetAttribute(Keywords.MSD_PARENTKEY, Keywords.MSDNS);
  353. if (value == null || value.Length==0)
  354. throw ExceptionBuilder.RelationTableKeyMissing(strName);
  355. parentNames = value.TrimEnd(null).Split(new char[] {Keywords.MSD_KEYFIELDSEP, Keywords.MSD_KEYFIELDOLDSEP});
  356. value = node.GetAttribute(Keywords.MSD_CHILDKEY, Keywords.MSDNS);
  357. if (value == null || value.Length==0)
  358. throw ExceptionBuilder.RelationChildKeyMissing(strName);
  359. childNames = value.TrimEnd(null).Split(new char[] {Keywords.MSD_KEYFIELDSEP, Keywords.MSD_KEYFIELDOLDSEP});
  360. keyLength = parentNames.Length;
  361. if (keyLength != childNames.Length)
  362. throw ExceptionBuilder.MismatchKeyLength();
  363. parentKey = new DataColumn[keyLength];
  364. childKey = new DataColumn[keyLength];
  365. string parentNs = node.GetAttribute(Keywords.MSD_PARENTTABLENS, Keywords.MSDNS);
  366. string childNs = node.GetAttribute(Keywords.MSD_CHILDTABLENS, Keywords.MSDNS);
  367. parent = _ds.Tables.GetTableSmart(parentName,parentNs);
  368. if (parent == null)
  369. throw ExceptionBuilder.ElementTypeNotFound(parentName);
  370. child = _ds.Tables.GetTableSmart(childName,childNs);
  371. if (child == null)
  372. throw ExceptionBuilder.ElementTypeNotFound(childName);
  373. for (int i = 0; i < keyLength; i++) {
  374. parentKey[i] = parent.Columns[XmlConvert.DecodeName(parentNames[i])];
  375. if (parentKey[i] == null)
  376. throw ExceptionBuilder.ElementTypeNotFound(parentNames[i]);
  377. childKey[i] = child.Columns[XmlConvert.DecodeName(childNames[i])];
  378. if (childKey[i] == null)
  379. throw ExceptionBuilder.ElementTypeNotFound(childNames[i]);
  380. }
  381. relation = new DataRelation(strName, parentKey, childKey, fCreateConstraints);
  382. relation.Nested = fNested;
  383. SetExtProperties(relation, node.Attributes);
  384. _ds.Relations.Add(relation);
  385. if (FromInference && relation.Nested) {
  386. tableDictionary[relation.ParentTable].Add(relation.ChildTable);
  387. }
  388. }
  389. private bool HasAttributes(XmlSchemaObjectCollection attributes){
  390. foreach (XmlSchemaObject so in attributes) {
  391. if (so is XmlSchemaAttribute) {
  392. return true;
  393. }
  394. if (so is XmlSchemaAttributeGroup) {
  395. return true;
  396. }
  397. if (so is XmlSchemaAttributeGroupRef) {
  398. return true;
  399. }
  400. }
  401. return false;
  402. }
  403. private bool IsDatasetParticle(XmlSchemaParticle pt){
  404. XmlSchemaObjectCollection items = GetParticleItems(pt);
  405. if (items == null)
  406. return false; // empty element, threat it as table
  407. bool isChoice = this.FromInference && (pt is XmlSchemaChoice);// currently we add this support for choice, just for inference
  408. foreach (XmlSchemaAnnotated el in items){
  409. if (el is XmlSchemaElement) {
  410. // pushing max occur of choice element to its imidiate children of type xs:elements
  411. if (isChoice && pt.MaxOccurs > Decimal.One && (((XmlSchemaElement)el).SchemaType is XmlSchemaComplexType)) // we know frominference condition
  412. ((XmlSchemaElement)el).MaxOccurs = pt.MaxOccurs;
  413. if (((XmlSchemaElement)el).RefName.Name.Length != 0) {
  414. if (!FromInference || (((XmlSchemaElement)el).MaxOccurs != Decimal.One && !(((XmlSchemaElement)el).SchemaType is XmlSchemaComplexType)))
  415. continue;
  416. }
  417. if (!IsTable ((XmlSchemaElement)el))
  418. return false;
  419. continue;
  420. }
  421. if (el is XmlSchemaParticle) {
  422. if (!IsDatasetParticle((XmlSchemaParticle)el))
  423. return false;
  424. }
  425. }
  426. return true;
  427. }
  428. private int DatasetElementCount(XmlSchemaObjectCollection elements) {
  429. int nCount = 0;
  430. foreach(XmlSchemaElement XmlElement in elements) {
  431. if (GetBooleanAttribute(XmlElement, Keywords.MSD_ISDATASET, /*default:*/ false)) {
  432. nCount++;
  433. }
  434. }
  435. return nCount;
  436. }
  437. private XmlSchemaElement FindDatasetElement(XmlSchemaObjectCollection elements) {
  438. foreach(XmlSchemaElement XmlElement in elements) {
  439. if (GetBooleanAttribute(XmlElement, Keywords.MSD_ISDATASET, /*default:*/ false))
  440. return XmlElement;
  441. }
  442. if ((elements.Count == 1) || (this.FromInference && elements.Count > 0)) { //let's see if this element looks like a DataSet
  443. XmlSchemaElement node = (XmlSchemaElement)elements[0];
  444. if (!GetBooleanAttribute(node, Keywords.MSD_ISDATASET, /*default:*/ true))
  445. return null;
  446. XmlSchemaComplexType ct = node.SchemaType as XmlSchemaComplexType;
  447. if (ct == null)
  448. return null;
  449. while (ct != null) {
  450. if (HasAttributes(ct.Attributes))
  451. return null;
  452. if (ct.ContentModel is XmlSchemaSimpleContent){
  453. XmlSchemaAnnotated cContent = ((XmlSchemaSimpleContent) (ct.ContentModel)).Content;
  454. if (cContent is XmlSchemaSimpleContentExtension) {
  455. XmlSchemaSimpleContentExtension ccExtension = ((XmlSchemaSimpleContentExtension) cContent );
  456. if (HasAttributes(ccExtension.Attributes))
  457. return null;
  458. } else {
  459. XmlSchemaSimpleContentRestriction ccRestriction = ((XmlSchemaSimpleContentRestriction) cContent );
  460. if (HasAttributes(ccRestriction.Attributes))
  461. return null;
  462. }
  463. }
  464. XmlSchemaParticle particle = GetParticle(ct);
  465. if (particle != null) {
  466. if (!IsDatasetParticle(particle))
  467. return null; // it's a table
  468. }
  469. if (ct.BaseXmlSchemaType is XmlSchemaComplexType)
  470. ct = (XmlSchemaComplexType)ct.BaseXmlSchemaType;
  471. else
  472. break;
  473. }
  474. //if we are here there all elements are tables
  475. return node;
  476. }
  477. return null;
  478. }
  479. public void LoadSchema(XmlSchemaSet schemaSet , DataTable dt) {
  480. if (dt.DataSet != null)
  481. LoadSchema(schemaSet, dt.DataSet);
  482. }
  483. public void LoadSchema(XmlSchemaSet schemaSet , DataSet ds) { //Element schemaRoot, DataSet ds) {
  484. ConstraintNodes = new Hashtable();
  485. RefTables = new ArrayList();
  486. ColumnExpressions = new ArrayList();
  487. complexTypes = new ArrayList();
  488. bool setRootNStoDataSet = false;
  489. bool newDataSet = (ds.Tables.Count == 0);
  490. if (schemaSet == null) //
  491. return;
  492. _schemaSet = schemaSet;
  493. _ds = ds;
  494. ds.fIsSchemaLoading = true;
  495. foreach (XmlSchema schemaRoot in schemaSet.Schemas()) {
  496. _schemaName = schemaRoot.Id;
  497. if (_schemaName == null ||_schemaName.Length == 0) {
  498. _schemaName = "NewDataSet";
  499. }
  500. ds.DataSetName = XmlConvert.DecodeName(_schemaName);
  501. string ns = schemaRoot.TargetNamespace;
  502. if (ds.namespaceURI == null || ds.namespaceURI.Length == 0) {// set just one time, for backward compatibility
  503. ds.namespaceURI = (ns== null)? string.Empty : ns; // see fx\Data\XDO\ReadXml\SchemaM2.xml for more info
  504. }
  505. break; // we just need to take Name and NS from first schema [V1.0 & v1.1 semantics]
  506. }
  507. annotations = new XmlSchemaObjectCollection();
  508. elements = new XmlSchemaObjectCollection();
  509. elementsTable = new Hashtable();
  510. attributes = new Hashtable();
  511. attributeGroups = new Hashtable();
  512. schemaTypes = new Hashtable();
  513. tableDictionary = new Dictionary <DataTable, List<DataTable>>() ;
  514. existingSimpleTypeMap = new Hashtable();
  515. foreach(DataTable dt in ds.Tables){
  516. foreach(DataColumn dc in dt.Columns) {
  517. if (dc.SimpleType!= null && dc.SimpleType.Name != null && dc.SimpleType.Name.Length != 0) {
  518. existingSimpleTypeMap[dc.SimpleType.SimpleTypeQualifiedName] = dc;
  519. // existingSimpleTypeMap[dc.SimpleType.SimpleTypeQualifiedName] = dc.SimpleType;
  520. }
  521. }
  522. }
  523. foreach (XmlSchema schemaRoot in schemaSet.Schemas())
  524. CollectElementsAnnotations(schemaRoot);
  525. dsElement = FindDatasetElement(elements);
  526. if (dsElement != null) {
  527. string mainName = GetStringAttribute (dsElement, Keywords.MSD_MAINDATATABLE, "");
  528. if (null != mainName) {
  529. ds.MainTableName = XmlConvert.DecodeName (mainName);
  530. }
  531. }
  532. else {
  533. if (this.FromInference) {
  534. ds.fTopLevelTable = true; // Backward compatability: for inference, if we do not read DataSet element
  535. }
  536. // we should not write it also
  537. setRootNStoDataSet = true;
  538. //incase of Root is not mapped to DataSet and is mapped to DataTable instead; to be backward compatable
  539. // we need to set the Namespace of Root to DataSet's namespace also(it would be NS of First DataTable in collection)
  540. }
  541. List<XmlQualifiedName> qnames = new List<XmlQualifiedName>();
  542. if (ds != null && ds.UseDataSetSchemaOnly) {
  543. int dataSetElementCount = DatasetElementCount(elements);
  544. if (dataSetElementCount == 0) {
  545. throw ExceptionBuilder.IsDataSetAttributeMissingInSchema();
  546. }
  547. else if (dataSetElementCount > 1) {
  548. throw ExceptionBuilder.TooManyIsDataSetAtributeInSchema();
  549. }
  550. XmlSchemaComplexType ct = (XmlSchemaComplexType) FindTypeNode(dsElement);
  551. if (ct.Particle != null) {
  552. XmlSchemaObjectCollection items = GetParticleItems(ct.Particle);
  553. if (items != null) {
  554. foreach (XmlSchemaAnnotated el in items){
  555. XmlSchemaElement sel = el as XmlSchemaElement;
  556. if (null != sel) {
  557. if(sel.RefName.Name.Length != 0 ) {
  558. qnames.Add(sel.QualifiedName);
  559. }
  560. }
  561. }
  562. }
  563. }
  564. }
  565. // Walk all the top level Element tags.
  566. foreach (XmlSchemaElement element in elements) {
  567. if (element == dsElement)
  568. continue;
  569. if (ds != null && ds.UseDataSetSchemaOnly && dsElement != null) {
  570. if (dsElement.Parent != element.Parent) {
  571. if (!qnames.Contains(element.QualifiedName)) {
  572. continue;
  573. }
  574. }
  575. }
  576. String typeName = GetInstanceName(element);
  577. if (RefTables.Contains(element.QualifiedName.Namespace +":"+ typeName)) {
  578. HandleRefTableProperties(RefTables, element);
  579. continue;
  580. }
  581. DataTable table = HandleTable(element);
  582. }
  583. if (dsElement!=null)
  584. HandleDataSet(dsElement, newDataSet);
  585. foreach (XmlSchemaAnnotation annotation in annotations) {
  586. HandleRelations(annotation, false);
  587. }
  588. //just add Expressions, at this point and if ColumnExpressions.Count > 0, this.expressions should not be null
  589. for(int i=0; i<ColumnExpressions.Count; i++) {
  590. DataColumn dc = ((DataColumn)(ColumnExpressions[i]));
  591. dc.Expression = (string) this.expressions[dc];
  592. }
  593. foreach (DataTable dt in ds.Tables) {
  594. if (dt.NestedParentRelations.Length == 0 && dt.Namespace == ds.Namespace) {
  595. DataRelationCollection childRelations = dt.ChildRelations;// WebData 113251 if we nulling NS of parent table,
  596. for (int j = 0; j < childRelations.Count; j++) { // we need to do the same thing for nested child tables as they
  597. if (childRelations[j].Nested && dt.Namespace == childRelations[j].ChildTable.Namespace) { // take NS from Parent table
  598. childRelations[j].ChildTable.tableNamespace = null;
  599. }
  600. }
  601. dt.tableNamespace = null;
  602. }
  603. }
  604. DataTable tmpTable = ds.Tables[ds.DataSetName, ds.Namespace];
  605. if ( tmpTable != null) // this fix is done to support round-trip problem in case if there is one table with same name and NS
  606. tmpTable.fNestedInDataset = true;
  607. // this fix is for backward compatability with old inference engine
  608. if (this.FromInference && ds.Tables.Count == 0 && String.Compare(ds.DataSetName, "NewDataSet", StringComparison.Ordinal) == 0)
  609. ds.DataSetName = XmlConvert.DecodeName(((XmlSchemaElement)elements[0]).Name);
  610. ds.fIsSchemaLoading = false; //reactivate column computations
  611. //for backward compatability; we need to set NS of Root Element to DataSet, if root already does not mapped to dataSet
  612. if (setRootNStoDataSet) {
  613. if (ds.Tables.Count > 0) { // if there is table, take first one's NS
  614. ds.Namespace = ds.Tables[0].Namespace;
  615. ds.Prefix = ds.Tables[0].Prefix;
  616. }
  617. else {// otherwise, take TargetNS from first schema
  618. Debug.Assert(schemaSet.Count == 1, "there should be one schema");
  619. foreach (XmlSchema schemaRoot in schemaSet.Schemas()) { // we should have 1 schema
  620. ds.Namespace = schemaRoot.TargetNamespace;
  621. }
  622. }
  623. }
  624. }
  625. private void HandleRelations(XmlSchemaAnnotation ann, bool fNested) {
  626. foreach (object __items in ann.Items)
  627. if (__items is XmlSchemaAppInfo) {
  628. XmlNode[] relations = ((XmlSchemaAppInfo) __items).Markup;
  629. for (int i = 0; i<relations.Length; i++)
  630. if (FEqualIdentity(relations[i], Keywords.MSD_RELATION, Keywords.MSDNS))
  631. HandleRelation((XmlElement)relations[i], fNested);
  632. }
  633. }
  634. internal XmlSchemaObjectCollection GetParticleItems(XmlSchemaParticle pt){
  635. if (pt is XmlSchemaSequence)
  636. return ((XmlSchemaSequence)pt).Items;
  637. if (pt is XmlSchemaAll)
  638. return ((XmlSchemaAll)pt).Items;
  639. if (pt is XmlSchemaChoice)
  640. return ((XmlSchemaChoice)pt).Items;
  641. if (pt is XmlSchemaAny)
  642. return null;
  643. // the code below is a little hack for the SOM behavior
  644. if (pt is XmlSchemaElement) {
  645. XmlSchemaObjectCollection Items = new XmlSchemaObjectCollection();
  646. Items.Add(pt);
  647. return Items;
  648. }
  649. if (pt is XmlSchemaGroupRef)
  650. return GetParticleItems( ((XmlSchemaGroupRef)pt).Particle );
  651. // should never get here.
  652. return null;
  653. }
  654. internal void HandleParticle(XmlSchemaParticle pt, DataTable table, ArrayList tableChildren, bool isBase){
  655. XmlSchemaObjectCollection items = GetParticleItems(pt);
  656. if (items == null)
  657. return;
  658. foreach (XmlSchemaAnnotated item in items){
  659. XmlSchemaElement el = item as XmlSchemaElement;
  660. if (el != null) {
  661. if (this.FromInference && pt is XmlSchemaChoice && pt.MaxOccurs > Decimal.One && (el.SchemaType is XmlSchemaComplexType))
  662. ((XmlSchemaElement)el).MaxOccurs = pt.MaxOccurs;
  663. DataTable child = null;
  664. // to decide if element is our table, we need to match both name and ns
  665. // 286043 - SQL BU Defect Tracking
  666. if (((el.Name == null) && (el.RefName.Name == table.EncodedTableName && el.RefName.Namespace == table.Namespace)) ||
  667. (IsTable(el) && el.Name == table.TableName)) {
  668. if (this.FromInference) {
  669. child = HandleTable ((XmlSchemaElement)el);
  670. Debug.Assert(child == table, "table not the same");
  671. }
  672. else {
  673. child = table;
  674. }
  675. }
  676. else {
  677. child = HandleTable ((XmlSchemaElement)el);
  678. if (child == null && this.FromInference && el.Name == table.TableName) {
  679. child = table;
  680. }
  681. }
  682. if (child==null) {
  683. if (!this.FromInference || el.Name != table.TableName) {// check is required to support 1.1 inference behavior
  684. HandleElementColumn((XmlSchemaElement)el, table, isBase);
  685. }
  686. }
  687. else {
  688. DataRelation relation = null;
  689. if (el.Annotation != null)
  690. HandleRelations(el.Annotation, true);
  691. DataRelationCollection childRelations = table.ChildRelations;
  692. for (int j = 0; j < childRelations.Count; j++) {
  693. if (!childRelations[j].Nested)
  694. continue;
  695. if (child == childRelations[j].ChildTable)
  696. relation = childRelations[j];
  697. }
  698. if (relation == null) {
  699. tableChildren.Add(child);// how about prefix for this?
  700. if(this.FromInference && table.UKColumnPositionForInference == -1) { // this is done for Inference
  701. int ukColumnPosition = -1;
  702. foreach(DataColumn dc in table.Columns) {
  703. if (dc.ColumnMapping == MappingType.Element)
  704. ukColumnPosition++;
  705. }
  706. table.UKColumnPositionForInference = ukColumnPosition + 1; // since it starts from
  707. }
  708. }
  709. }
  710. }
  711. else {
  712. HandleParticle((XmlSchemaParticle)item, table, tableChildren, isBase);
  713. }
  714. }
  715. return ;
  716. }
  717. internal void HandleAttributes(XmlSchemaObjectCollection attributes, DataTable table, bool isBase) {
  718. foreach (XmlSchemaObject so in attributes) {
  719. if (so is XmlSchemaAttribute) {
  720. HandleAttributeColumn((XmlSchemaAttribute) so, table, isBase);
  721. }
  722. else { // XmlSchemaAttributeGroupRef
  723. XmlSchemaAttributeGroupRef groupRef = so as XmlSchemaAttributeGroupRef;
  724. XmlSchemaAttributeGroup schemaGroup = attributeGroups[groupRef.RefName] as XmlSchemaAttributeGroup;
  725. if (schemaGroup!=null) {
  726. HandleAttributeGroup(schemaGroup, table, isBase);
  727. }
  728. }
  729. }
  730. }
  731. private void HandleAttributeGroup(XmlSchemaAttributeGroup attributeGroup, DataTable table, bool isBase) {
  732. foreach (XmlSchemaObject obj in attributeGroup.Attributes) {
  733. if (obj is XmlSchemaAttribute) {
  734. HandleAttributeColumn((XmlSchemaAttribute) obj, table, isBase);
  735. }
  736. else { // XmlSchemaAttributeGroupRef
  737. XmlSchemaAttributeGroupRef attributeGroupRef = (XmlSchemaAttributeGroupRef)obj;
  738. XmlSchemaAttributeGroup attributeGroupResolved;
  739. if (attributeGroup.RedefinedAttributeGroup != null && attributeGroupRef.RefName == new XmlQualifiedName(attributeGroup.Name, attributeGroupRef.RefName.Namespace)) {
  740. attributeGroupResolved = (XmlSchemaAttributeGroup)attributeGroup.RedefinedAttributeGroup;
  741. }
  742. else {
  743. attributeGroupResolved = (XmlSchemaAttributeGroup)attributeGroups[attributeGroupRef.RefName];
  744. }
  745. if (attributeGroupResolved != null) {
  746. HandleAttributeGroup(attributeGroupResolved, table, isBase);
  747. }
  748. }
  749. }
  750. }
  751. internal void HandleComplexType(XmlSchemaComplexType ct, DataTable table, ArrayList tableChildren, bool isNillable){
  752. if (complexTypes.Contains(ct))
  753. throw ExceptionBuilder.CircularComplexType(ct.Name);
  754. bool isBase = false;
  755. complexTypes.Add(ct);
  756. if (ct.ContentModel != null) {
  757. /*
  758. HandleParticle(ct.CompiledParticle, table, tableChildren, isBase);
  759. foreach (XmlSchemaAttribute s in ct.Attributes){
  760. HandleAttributeColumn(s, table, isBase);
  761. }
  762. */
  763. if (ct.ContentModel is XmlSchemaComplexContent) {
  764. XmlSchemaAnnotated cContent = ((XmlSchemaComplexContent) (ct.ContentModel)).Content;
  765. if (cContent is XmlSchemaComplexContentExtension) {
  766. XmlSchemaComplexContentExtension ccExtension = ((XmlSchemaComplexContentExtension) cContent );
  767. if (!(ct.BaseXmlSchemaType is XmlSchemaComplexType && this.FromInference))
  768. HandleAttributes(ccExtension.Attributes, table, isBase);
  769. if (ct.BaseXmlSchemaType is XmlSchemaComplexType) {
  770. HandleComplexType((XmlSchemaComplexType)ct.BaseXmlSchemaType, table, tableChildren, isNillable);
  771. }
  772. else {
  773. Debug.Assert(ct.BaseXmlSchemaType is XmlSchemaSimpleType, "Expected SimpleType or ComplexType");
  774. if (ccExtension.BaseTypeName.Namespace != Keywords.XSDNS){
  775. // this is UDSimpleType, pass Qualified name of type
  776. HandleSimpleContentColumn(ccExtension.BaseTypeName.ToString(), table, isBase, ct.ContentModel.UnhandledAttributes, isNillable);
  777. }
  778. else { // it is built in type
  779. HandleSimpleContentColumn(ccExtension.BaseTypeName.Name, table, isBase, ct.ContentModel.UnhandledAttributes, isNillable);
  780. }
  781. }
  782. if (ccExtension.Particle != null)
  783. HandleParticle(ccExtension.Particle, table, tableChildren, isBase);
  784. if (ct.BaseXmlSchemaType is XmlSchemaComplexType && this.FromInference)
  785. HandleAttributes(ccExtension.Attributes, table, isBase);
  786. } else {
  787. Debug.Assert(cContent is XmlSchemaComplexContentRestriction, "Expected complexContent extension or restriction");
  788. XmlSchemaComplexContentRestriction ccRestriction = ((XmlSchemaComplexContentRestriction) cContent );
  789. if (!this.FromInference)
  790. HandleAttributes(ccRestriction.Attributes, table, isBase);
  791. if (ccRestriction.Particle != null)
  792. HandleParticle(ccRestriction.Particle, table, tableChildren, isBase);
  793. if (this.FromInference)
  794. HandleAttributes(ccRestriction.Attributes, table, isBase);
  795. }
  796. } else {
  797. Debug.Assert(ct.ContentModel is XmlSchemaSimpleContent, "expected simpleContent or complexContent");
  798. XmlSchemaAnnotated cContent = ((XmlSchemaSimpleContent) (ct.ContentModel)).Content;
  799. if (cContent is XmlSchemaSimpleContentExtension) {
  800. XmlSchemaSimpleContentExtension ccExtension = ((XmlSchemaSimpleContentExtension) cContent );
  801. HandleAttributes(ccExtension.Attributes, table, isBase);
  802. if (ct.BaseXmlSchemaType is XmlSchemaComplexType) {
  803. HandleComplexType((XmlSchemaComplexType)ct.BaseXmlSchemaType, table, tableChildren, isNillable);
  804. }
  805. else {
  806. Debug.Assert(ct.BaseXmlSchemaType is XmlSchemaSimpleType, "Expected SimpleType or ComplexType");
  807. HandleSimpleTypeSimpleContentColumn((XmlSchemaSimpleType)ct.BaseXmlSchemaType, ccExtension.BaseTypeName.Name, table, isBase, ct.ContentModel.UnhandledAttributes, isNillable);
  808. }
  809. } else {
  810. Debug.Assert(cContent is XmlSchemaSimpleContentRestriction, "Expected SimpleContent extension or restriction");
  811. XmlSchemaSimpleContentRestriction ccRestriction = ((XmlSchemaSimpleContentRestriction) cContent );
  812. HandleAttributes(ccRestriction.Attributes, table, isBase);
  813. }
  814. }
  815. }
  816. else {
  817. isBase = true;
  818. if (!this.FromInference)
  819. HandleAttributes(ct.Attributes, table, isBase);
  820. if (ct.Particle != null)
  821. HandleParticle(ct.Particle, table, tableChildren, isBase);
  822. if (this.FromInference) {
  823. HandleAttributes(ct.Attributes, table, isBase);
  824. if (isNillable) // this is for backward compatability to support xsi:Nill=true
  825. HandleSimpleContentColumn("string", table, isBase, null, isNillable);
  826. }
  827. }
  828. complexTypes.Remove(ct);
  829. }
  830. internal XmlSchemaParticle GetParticle(XmlSchemaComplexType ct){
  831. if (ct.ContentModel != null) {
  832. if (ct.ContentModel is XmlSchemaComplexContent) {
  833. XmlSchemaAnnotated cContent = ((XmlSchemaComplexContent) (ct.ContentModel)).Content;
  834. if (cContent is XmlSchemaComplexContentExtension) {
  835. return ((XmlSchemaComplexContentExtension) cContent ).Particle;
  836. } else {
  837. Debug.Assert(cContent is XmlSchemaComplexContentRestriction, "Expected complexContent extension or restriction");
  838. return ((XmlSchemaComplexContentRestriction) cContent ).Particle;
  839. }
  840. } else {
  841. Debug.Assert(ct.ContentModel is XmlSchemaSimpleContent, "expected simpleContent or complexContent");
  842. return null;
  843. }
  844. }
  845. else {
  846. return ct.Particle;
  847. }
  848. }
  849. internal DataColumn FindField(DataTable table, string field) {
  850. bool attribute = false;
  851. String colName = field;
  852. if (field.StartsWith("@", StringComparison.Ordinal)) {
  853. attribute = true;
  854. colName = field.Substring(1);
  855. }
  856. String [] split = colName.Split(':');
  857. colName = split [split.Length - 1];
  858. colName = XmlConvert.DecodeName(colName);
  859. DataColumn col = table.Columns[colName];
  860. if (col == null )
  861. throw ExceptionBuilder.InvalidField(field);
  862. bool _attribute = (col.ColumnMapping == MappingType.Attribute) || (col.ColumnMapping == MappingType.Hidden);
  863. if (_attribute != attribute)
  864. throw ExceptionBuilder.InvalidField(field);
  865. return col;
  866. }
  867. internal DataColumn[] BuildKey(XmlSchemaIdentityConstraint keyNode, DataTable table){
  868. ArrayList keyColumns = new ArrayList();
  869. foreach (XmlSchemaXPath node in keyNode.Fields) {
  870. keyColumns.Add(FindField(table, node.XPath));
  871. }
  872. DataColumn [] key = new DataColumn[keyColumns.Count];
  873. keyColumns.CopyTo(key, 0);
  874. return key;
  875. }
  876. internal bool GetBooleanAttribute(XmlSchemaAnnotated element, String attrName, bool defVal) {
  877. string value = GetMsdataAttribute(element, attrName);
  878. if (value == null || value.Length == 0) {
  879. return defVal;
  880. }
  881. if ((value == Keywords.TRUE) || (value == Keywords.ONE_DIGIT)){
  882. return true;
  883. }
  884. if ((value == Keywords.FALSE) || (value == Keywords.ZERO_DIGIT)){
  885. return false;
  886. }
  887. // Error processing:
  888. throw ExceptionBuilder.InvalidAttributeValue(attrName, value);
  889. }
  890. internal String GetStringAttribute(XmlSchemaAnnotated element, String attrName, String defVal) {
  891. string value = GetMsdataAttribute(element, attrName);
  892. if (value == null || value.Length == 0) {
  893. return defVal;
  894. }
  895. return value;
  896. }
  897. /*
  898. <key name="fk">
  899. <selector>../Customers</selector>
  900. <field>ID</field>
  901. </key>
  902. <keyref refer="fk">
  903. <selector>.</selector>
  904. <field>CustID</field>
  905. </keyref>
  906. */
  907. internal static AcceptRejectRule TranslateAcceptRejectRule( string strRule ) {
  908. if (strRule == "Cascade")
  909. return AcceptRejectRule.Cascade;
  910. else if (strRule == "None")
  911. return AcceptRejectRule.None;
  912. else
  913. return ForeignKeyConstraint.AcceptRejectRule_Default;
  914. }
  915. internal static Rule TranslateRule( string strRule ) {
  916. if (strRule == "Cascade")
  917. return Rule.Cascade;
  918. else if (strRule == "None")
  919. return Rule.None;
  920. else if (strRule == "SetDefault")
  921. return Rule.SetDefault;
  922. else if (strRule == "SetNull")
  923. return Rule.SetNull;
  924. else
  925. return ForeignKeyConstraint.Rule_Default;
  926. }
  927. internal void HandleKeyref(XmlSchemaKeyref keyref) {
  928. string refer = XmlConvert.DecodeName(keyref.Refer.Name); // check here!!!
  929. string name = XmlConvert.DecodeName(keyref.Name);
  930. name = GetStringAttribute( keyref, "ConstraintName", /*default:*/ name);
  931. // we do not process key defined outside the current node
  932. String tableName = GetTableName(keyref);
  933. string tableNs = GetMsdataAttribute(keyref,Keywords.MSD_TABLENS);
  934. DataTable table = _ds.Tables.GetTableSmart(tableName,tableNs);
  935. if (table == null)
  936. return;
  937. if (refer == null || refer.Length == 0)
  938. throw ExceptionBuilder.MissingRefer(name);
  939. ConstraintTable key = (ConstraintTable) ConstraintNodes[refer];
  940. if (key == null) {
  941. throw ExceptionBuilder.InvalidKey(name);
  942. }
  943. DataColumn[] pKey = BuildKey(key.constraint, key.table);
  944. DataColumn[] fKey = BuildKey(keyref, table);
  945. ForeignKeyConstraint fkc = null;
  946. if (GetBooleanAttribute(keyref, Keywords.MSD_CONSTRAINTONLY, /*default:*/ false)) {
  947. int iExisting = fKey[0].Table.Constraints.InternalIndexOf(name);
  948. if (iExisting > -1) {
  949. if (fKey[0].Table.Constraints[iExisting].ConstraintName != name)
  950. iExisting = -1;
  951. }
  952. if (iExisting < 0) {
  953. fkc = new ForeignKeyConstraint( name, pKey, fKey );
  954. fKey[0].Table.Constraints.Add(fkc);
  955. }
  956. }
  957. else {
  958. string relName = XmlConvert.DecodeName(GetStringAttribute( keyref, Keywords.MSD_RELATIONNAME, keyref.Name));
  959. if (relName == null || relName.Length == 0)
  960. relName = name;
  961. int iExisting = fKey[0].Table.DataSet.Relations.InternalIndexOf(relName);
  962. if (iExisting > -1) {
  963. if (fKey[0].Table.DataSet.Relations[iExisting].RelationName != relName)
  964. iExisting = -1;
  965. }
  966. DataRelation relation = null;
  967. if (iExisting < 0) {
  968. relation = new DataRelation(relName, pKey, fKey);
  969. SetExtProperties(relation, keyref.UnhandledAttributes);
  970. pKey[0].Table.DataSet.Relations.Add(relation);
  971. if (FromInference && relation.Nested) {
  972. if (tableDictionary.ContainsKey(relation.ParentTable)) {
  973. tableDictionary[relation.ParentTable].Add(relation.ChildTable);
  974. }
  975. }
  976. fkc = relation.ChildKeyConstraint;
  977. fkc.ConstraintName = name;
  978. }
  979. else {
  980. relation = fKey[0].Table.DataSet.Relations[iExisting];
  981. }
  982. if (GetBooleanAttribute(keyref, Keywords.MSD_ISNESTED, /*default:*/ false)) {
  983. relation.Nested = true;
  984. }
  985. }
  986. string acceptRejectRule = GetMsdataAttribute(keyref, Keywords.MSD_ACCEPTREJECTRULE);
  987. string updateRule = GetMsdataAttribute(keyref, Keywords.MSD_UPDATERULE);
  988. string deleteRule = GetMsdataAttribute(keyref, Keywords.MSD_DELETERULE);
  989. if (fkc != null) {
  990. if (acceptRejectRule != null)
  991. fkc.AcceptRejectRule = TranslateAcceptRejectRule(acceptRejectRule);
  992. if (updateRule != null)
  993. fkc.UpdateRule = TranslateRule(updateRule);
  994. if (deleteRule != null)
  995. fkc.DeleteRule = TranslateRule(deleteRule);
  996. SetExtProperties(fkc, keyref.UnhandledAttributes);
  997. }
  998. }
  999. internal void HandleConstraint(XmlSchemaIdentityConstraint keyNode){
  1000. String name = null;
  1001. name = XmlConvert.DecodeName(keyNode.Name);
  1002. if (name==null || name.Length==0)
  1003. throw ExceptionBuilder.MissingAttribute(Keywords.NAME);
  1004. if (ConstraintNodes.ContainsKey(name))
  1005. throw ExceptionBuilder.DuplicateConstraintRead(name);
  1006. // we do not process key defined outside the current node
  1007. String tableName = GetTableName(keyNode);
  1008. string tableNs = GetMsdataAttribute(keyNode,Keywords.MSD_TABLENS);
  1009. DataTable table = _ds.Tables.GetTableSmart(tableName,tableNs);
  1010. if (table == null)
  1011. return;
  1012. ConstraintNodes.Add(name, new ConstraintTable(table, keyNode));
  1013. bool fPrimaryKey = GetBooleanAttribute(keyNode, Keywords.MSD_PRIMARYKEY, /*default:*/ false);
  1014. name = GetStringAttribute(keyNode, "ConstraintName", /*default:*/ name);
  1015. DataColumn[] key = BuildKey(keyNode, table);
  1016. if (0 < key.Length) {
  1017. UniqueConstraint found = (UniqueConstraint) key[0].Table.Constraints.FindConstraint(new UniqueConstraint(name, key));
  1018. if (found == null) {
  1019. key[0].Table.Constraints.Add(name, key, fPrimaryKey);
  1020. SetExtProperties(key[0].Table.Constraints[name], keyNode.UnhandledAttributes);
  1021. }
  1022. else {
  1023. key = found.ColumnsReference;
  1024. SetExtProperties(found, keyNode.UnhandledAttributes);
  1025. if (fPrimaryKey)
  1026. key[0].Table.PrimaryKey = key;
  1027. }
  1028. if (keyNode is XmlSchemaKey) {
  1029. for (int i=0; i<key.Length; i++)
  1030. key[i].AllowDBNull = false;
  1031. }
  1032. }
  1033. }
  1034. internal DataTable InstantiateSimpleTable(XmlSchemaElement node) {
  1035. DataTable table;
  1036. String typeName = XmlConvert.DecodeName(GetInstanceName(node));
  1037. String _TableUri;
  1038. _TableUri = node.QualifiedName.Namespace;
  1039. table = _ds.Tables.GetTable(typeName, _TableUri);
  1040. //
  1041. /* if (table!=null) {
  1042. throw ExceptionBuilder.DuplicateDeclaration(typeName);
  1043. }
  1044. */
  1045. if (!FromInference && table!=null) {
  1046. throw ExceptionBuilder.DuplicateDeclaration(typeName);
  1047. }
  1048. if (table == null) {
  1049. table = new DataTable( typeName);
  1050. table.Namespace = _TableUri;
  1051. // If msdata:targetNamespace node on element, then use it to override table.Namespace.
  1052. table.Namespace = GetStringAttribute(node, "targetNamespace", _TableUri);
  1053. if (!this.FromInference) {
  1054. table.MinOccurs = node.MinOccurs;
  1055. table.MaxOccurs = node.MaxOccurs;
  1056. }
  1057. else {
  1058. string prefix = GetPrefix(_TableUri);
  1059. if (prefix != null)
  1060. table.Prefix = prefix;
  1061. }
  1062. SetProperties(table, node.UnhandledAttributes);
  1063. SetExtProperties(table, node.UnhandledAttributes);
  1064. }
  1065. XmlSchemaComplexType ct = node.SchemaType as XmlSchemaComplexType;
  1066. // We assume node.ElementSchemaType.BaseSchemaType to be null for
  1067. // <xs:element name="foo"/> and not null for <xs:element name="foo" type="xs:string"/>
  1068. bool isSimpleContent = ((node.ElementSchemaType.BaseXmlSchemaType != null) ||(ct != null && ct.ContentModel is XmlSchemaSimpleContent));
  1069. if (!FromInference ||(isSimpleContent && table.Columns.Count == 0 )) {// for inference backward compatability
  1070. HandleElementColumn(node, table, false);
  1071. string colName;
  1072. if (this.FromInference) {
  1073. int i = 0;
  1074. colName = typeName + "_Text";
  1075. while (table.Columns[colName] != null)
  1076. colName = colName + i++;
  1077. }
  1078. else {
  1079. colName = typeName + "_Column";
  1080. }
  1081. table.Columns[0].ColumnName = colName;
  1082. table.Columns[0].ColumnMapping = MappingType.SimpleContent;
  1083. }
  1084. if (!this.FromInference ||_ds.Tables.GetTable(typeName, _TableUri) == null) { // for inference; special case: add table if doesnot exists in collection
  1085. _ds.Tables.Add(table);
  1086. if (this.FromInference) {
  1087. tableDictionary.Add(table, new List<DataTable>());
  1088. }
  1089. }
  1090. // handle all the unique and key constraints related to this table
  1091. if ((dsElement != null) && (dsElement.Constraints!=null)) {
  1092. foreach (XmlSchemaIdentityConstraint key in dsElement.Constraints) {
  1093. if (key is XmlSchemaKeyref)
  1094. continue;
  1095. if (GetTableName(key) == table.TableName)
  1096. HandleConstraint(key);
  1097. }
  1098. }
  1099. table.fNestedInDataset = false;
  1100. return (table);
  1101. }
  1102. internal string GetInstanceName(XmlSchemaAnnotated node) {
  1103. string instanceName = null;
  1104. Debug.Assert( (node is XmlSchemaElement) || (node is XmlSchemaAttribute), "GetInstanceName should only be called on attribute or elements");
  1105. if (node is XmlSchemaElement) {
  1106. XmlSchemaElement el = (XmlSchemaElement) node;
  1107. instanceName = el.Name != null ? el.Name : el.RefName.Name;
  1108. }
  1109. else if (node is XmlSchemaAttribute) {
  1110. XmlSchemaAttribute el = (XmlSchemaAttribute) node;
  1111. instanceName = el.Name != null ? el.Name : el.RefName.Name;
  1112. }
  1113. Debug.Assert((instanceName != null) && (instanceName.Length != 0), "instanceName cannot be null or empty. There's an error in the XSD compiler");
  1114. return instanceName;
  1115. }
  1116. // Sequences of handling Elements, Attributes and Text-only column should be the same as in InferXmlSchema
  1117. internal DataTable InstantiateTable(XmlSchemaElement node, XmlSchemaComplexType typeNode, bool isRef) {
  1118. DataTable table;
  1119. String typeName = GetInstanceName(node);
  1120. ArrayList tableChildren = new ArrayList();
  1121. String _TableUri;
  1122. _TableUri = node.QualifiedName.Namespace;
  1123. table = _ds.Tables.GetTable(XmlConvert.DecodeName(typeName), _TableUri);
  1124. // TOD: Do not do this fix
  1125. // if (table == null && node.RefName.IsEmpty && !IsTopLevelElement(node) && _TableUri != null && _TableUri.Length > 0) {
  1126. // _TableUri = null; // it means form="qualified", so child element inherits namespace. [....]
  1127. // }
  1128. if (!FromInference || (FromInference && table == null))
  1129. {
  1130. if (table!=null)
  1131. {
  1132. if (isRef)
  1133. return table;
  1134. else
  1135. throw ExceptionBuilder.DuplicateDeclaration(typeName);
  1136. }
  1137. if (isRef)
  1138. RefTables.Add(_TableUri+":"+typeName);
  1139. table = new DataTable(XmlConvert.DecodeName(typeName) );
  1140. table.TypeName = node.SchemaTypeName;
  1141. table.Namespace = _TableUri;
  1142. table.Namespace = GetStringAttribute(node, "targetNamespace", _TableUri);
  1143. //table.Prefix = node.Prefix;
  1144. String value= GetStringAttribute(typeNode, Keywords.MSD_CASESENSITIVE, "") ;
  1145. if (value.Length ==0)
  1146. {
  1147. value= GetStringAttribute(node, Keywords.MSD_CASESENSITIVE, "") ;
  1148. }
  1149. if (0 < value.Length) {
  1150. if ((value == Keywords.TRUE) || (value == "True"))
  1151. table.CaseSensitive = true;
  1152. if ((value == Keywords.FALSE) || (value == "False"))
  1153. table.CaseSensitive = false;
  1154. }
  1155. value = GetMsdataAttribute(node, Keywords.MSD_LOCALE);
  1156. if (null != value) { // set by user
  1157. if (0 < value.Length) {
  1158. // <... msdata:Locale="en-US"/>
  1159. table.Locale = new CultureInfo(value);
  1160. }
  1161. else {
  1162. // everett bug behavior before <... msdata:Locale=""/> inherit from DataSet
  1163. table.Locale = CultureInfo.InvariantCulture;
  1164. }
  1165. }
  1166. // else inherit from DataSet, not set by user
  1167. if (!this.FromInference)
  1168. {
  1169. table.MinOccurs = node.MinOccurs;
  1170. table.MaxOccurs = node.MaxOccurs;
  1171. }
  1172. else
  1173. {
  1174. string prefix = GetPrefix(_TableUri);
  1175. if (prefix != null)
  1176. table.Prefix = prefix;
  1177. }
  1178. _ds.Tables.Add(table);
  1179. if (FromInference) {
  1180. tableDictionary.Add(table, new List<DataTable>());
  1181. }
  1182. }
  1183. HandleComplexType(typeNode, table, tableChildren, node.IsNillable);
  1184. for (int i=0; i < table.Columns.Count ; i++)
  1185. table.Columns[i].SetOrdinalInternal(i);
  1186. /*
  1187. if (xmlContent == XmlContent.Mixed) {
  1188. string textColumn = GenUniqueColumnName(table.TableName+ "_Text", table);
  1189. table.XmlText = new DataColumn(textColumn, typeof(string), null, MappingType.Text);
  1190. } */
  1191. SetProperties(table, node.UnhandledAttributes);
  1192. SetExtProperties(table, node.UnhandledAttributes);
  1193. // handle all the unique and key constraints related to this table
  1194. if ((dsElement != null) && (dsElement.Constraints!=null)) {
  1195. foreach (XmlSchemaIdentityConstraint key in dsElement.Constraints) {
  1196. if (key is XmlSchemaKeyref)
  1197. continue;
  1198. if (GetTableName(key) == table.TableName) {
  1199. // respect the NS if it is specified for key, otherwise just go with table name check
  1200. if( GetTableNamespace(key) == table.Namespace || GetTableNamespace(key) == null)
  1201. HandleConstraint(key);
  1202. /* if (GetTableNamespace(key) != null) {
  1203. if (GetTableNamespace(key) == table.Namespace)
  1204. HandleConstraint(key);
  1205. }
  1206. else {
  1207. HandleConstraint(key);
  1208. }
  1209. */
  1210. }
  1211. }
  1212. }
  1213. foreach(DataTable _tableChild in tableChildren) {
  1214. if (_tableChild != table && table.Namespace == _tableChild.Namespace)
  1215. _tableChild.tableNamespace = null;
  1216. if ((dsElement != null) && (dsElement.Constraints!=null)) {
  1217. foreach (XmlSchemaIdentityConstraint key in dsElement.Constraints) {
  1218. XmlSchemaKeyref keyref = key as XmlSchemaKeyref;
  1219. if (keyref == null)
  1220. continue;
  1221. bool isNested = GetBooleanAttribute(keyref, Keywords.MSD_ISNESTED, /*default:*/ false);
  1222. if (!isNested)
  1223. continue;
  1224. if (GetTableName(keyref) == _tableChild.TableName) {
  1225. if (_tableChild.DataSet.Tables.InternalIndexOf(_tableChild.TableName) < -1) { // if we have multiple tables with the same name
  1226. if (GetTableNamespace(keyref) == _tableChild.Namespace) {
  1227. HandleKeyref(keyref);
  1228. }
  1229. }
  1230. else {
  1231. HandleKeyref(keyref);
  1232. }
  1233. }
  1234. }
  1235. }
  1236. DataRelation relation = null;
  1237. DataRelationCollection childRelations = table.ChildRelations;
  1238. for (int j = 0; j < childRelations.Count; j++) {
  1239. if (!childRelations[j].Nested)
  1240. continue;
  1241. if (_tableChild == childRelations[j].ChildTable)
  1242. relation = childRelations[j];
  1243. }
  1244. if (relation!=null)
  1245. continue;
  1246. DataColumn parentKey;
  1247. if (this.FromInference) {
  1248. int position = table.UKColumnPositionForInference;// we keep posiotion of unique key column here, for inference
  1249. if (position == -1)
  1250. foreach (DataColumn dc in table.Columns) {
  1251. if (dc.ColumnMapping == MappingType.Attribute) {
  1252. position = dc.Ordinal;
  1253. break;
  1254. }
  1255. }
  1256. parentKey = table.AddUniqueKey(position);
  1257. }
  1258. else {
  1259. parentKey = table.AddUniqueKey();
  1260. }
  1261. // foreign key in the child table
  1262. DataColumn childKey = _tableChild.AddForeignKey(parentKey);
  1263. // when we add unique key, we do set prefix; but for Fk we do not do . So for backward compatability
  1264. if (this.FromInference)
  1265. childKey.Prefix = _tableChild.Prefix;
  1266. // childKey.Prefix = GetPrefix(childKey.Namespace);
  1267. // create relationship
  1268. // setup relationship between parent and this table
  1269. relation = new DataRelation(table.TableName + "_" + _tableChild.TableName, parentKey, childKey, true);
  1270. relation.Nested = true;
  1271. _tableChild.DataSet.Relations.Add(relation);
  1272. if (FromInference && relation.Nested) {
  1273. if (tableDictionary.ContainsKey(relation.ParentTable)) {
  1274. tableDictionary[relation.ParentTable].Add(relation.ChildTable);
  1275. }
  1276. }
  1277. }
  1278. return (table);
  1279. }
  1280. private sealed class NameType : IComparable {
  1281. public readonly String name;
  1282. public readonly Type type;
  1283. public NameType(String n, Type t) {
  1284. name = n;
  1285. type = t;
  1286. }
  1287. public int CompareTo(object obj) { return String.Compare(name, (string)obj, StringComparison.Ordinal); }
  1288. };
  1289. public static Type XsdtoClr(string xsdTypeName) {
  1290. #if DEBUG
  1291. for(int i = 1; i < mapNameTypeXsd.Length; ++i) {
  1292. Debug.Assert((mapNameTypeXsd[i-1].CompareTo(mapNameTypeXsd[i].name)) < 0, "incorrect sorting " + mapNameTypeXsd[i].name);
  1293. }
  1294. #endif
  1295. int index = Array.BinarySearch(mapNameTypeXsd, xsdTypeName);
  1296. if (index < 0) {
  1297. throw ExceptionBuilder.UndefinedDatatype(xsdTypeName);
  1298. }
  1299. return mapNameTypeXsd[index].type;
  1300. }
  1301. // XSD spec: http://www.w3.org/TR/xmlschema-2/
  1302. // April: http://www.w3.org/TR/2000/WD-xmlschema-2-20000407/datatypes.html
  1303. // Fabr: http://www.w3.org/TR/2000/WD-xmlschema-2-20000225/
  1304. private static readonly NameType[] mapNameTypeXsd = {
  1305. new NameType("ENTITIES" , typeof(string) ), /* XSD Apr */
  1306. new NameType("ENTITY" , typeof(string) ), /* XSD Apr */
  1307. new NameType("ID" , typeof(string) ), /* XSD Apr */
  1308. new NameType("IDREF" , typeof(string) ), /* XSD Apr */
  1309. new NameType("IDREFS" , typeof(string) ), /* XSD Apr */
  1310. new NameType("NCName" , typeof(string) ), /* XSD Apr */
  1311. new NameType("NMTOKEN" , typeof(string) ), /* XSD Apr */
  1312. new NameType("NMTOKENS" , typeof(string) ), /* XSD Apr */
  1313. new NameType("NOTATION" , typeof(string) ), /* XSD Apr */
  1314. new NameType("Name" , typeof(string) ), /* XSD Apr */
  1315. new NameType("QName" , typeof(string) ), /* XSD Apr */
  1316. new NameType("anyType" , typeof(System.Object) ), /* XSD Apr */
  1317. new NameType("anyURI" , typeof(System.Uri) ), /* XSD Apr */
  1318. new NameType("base64Binary" , typeof(Byte[]) ), /* XSD Apr : abstruct */
  1319. new NameType("boolean" , typeof(bool) ), /* XSD Apr */
  1320. new NameType("byte" , typeof(SByte) ), /* XSD Apr */
  1321. new NameType("date" , typeof(DateTime)), /* XSD Apr */
  1322. new NameType("dateTime" , typeof(DateTime)), /* XSD Apr */
  1323. new NameType("decimal" , typeof(decimal) ), /* XSD 2001 [....] */
  1324. new NameType("double" , typeof(double) ), /* XSD Apr */
  1325. new NameType("duration" , typeof(TimeSpan)), /* XSD Apr */
  1326. new NameType("float" , typeof(Single) ), /* XSD Apr */
  1327. new NameType("gDay" , typeof(DateTime)), /* XSD Apr */
  1328. new NameType("gMonth" , typeof(DateTime)), /* XSD Apr */
  1329. new NameType("gMonthDay" , typeof(DateTime)), /* XSD Apr */
  1330. new NameType("gYear" , typeof(DateTime)), /* XSD Apr */
  1331. new NameType("gYearMonth" , typeof(DateTime)), /* XSD Apr */
  1332. new NameType("hexBinary" , typeof(Byte[]) ), /* XSD Apr : abstruct */
  1333. new NameType("int" , typeof(Int32) ), /* XSD Apr */
  1334. new NameType("integer" , typeof(Int64) ), /* XSD Apr */ // <xs:element name="" msdata:DataType="System.Numerics.BigInteger" type="xs:integer" minOccurs="0" />
  1335. new NameType("language" , typeof(string) ), /* XSD Apr */
  1336. new NameType("long" , typeof(Int64) ), /* XSD Apr */
  1337. new NameType("negativeInteger" , typeof(Int64) ), /* XSD Apr */
  1338. new NameType("nonNegativeInteger" , typeof(UInt64) ), /* XSD Apr */
  1339. new NameType("nonPositiveInteger" , typeof(Int64) ), /* XSD Apr */
  1340. new NameType("normalizedString" , typeof(string) ), /* XSD Apr */
  1341. new NameType("positiveInteger" , typeof(UInt64) ), /* XSD Apr */
  1342. new NameType("short" , typeof(Int16) ), /* XSD Apr */
  1343. new NameType("string" , typeof(string) ), /* XSD Apr */
  1344. new NameType("time" , typeof(DateTime)), /* XSD Apr */
  1345. new NameType("unsignedByte" , typeof(Byte) ), /* XSD Apr */
  1346. new NameType("unsignedInt" , typeof(UInt32) ), /* XSD Apr */
  1347. new NameType("unsignedLong" , typeof(UInt64) ), /* XSD Apr */
  1348. new NameType("unsignedShort" , typeof(UInt16) ), /* XSD Apr */
  1349. };
  1350. private static NameType FindNameType(string name) {
  1351. #if DEBUG
  1352. for(int i = 1; i < mapNameTypeXsd.Length; ++i) {
  1353. Debug.Assert((mapNameTypeXsd[i-1].CompareTo(mapNameTypeXsd[i].name)) < 0, "incorrect sorting " + mapNameTypeXsd[i].name);
  1354. }
  1355. #endif
  1356. int index = Array.BinarySearch(mapNameTypeXsd, name);
  1357. if (index < 0) {
  1358. throw ExceptionBuilder.UndefinedDatatype(name);
  1359. }
  1360. return mapNameTypeXsd[index];
  1361. }
  1362. // input param dt is a "qName" for UDSimpleType else it assumes it's a XSD builtin simpleType
  1363. private Type ParseDataType(string dt) {
  1364. if (!IsXsdType(dt)) {
  1365. if (udSimpleTypes != null) {
  1366. XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType) udSimpleTypes[dt];
  1367. if (simpleType == null) { // it is not named simple type, it is not XSD type, it should be unsupported type like xs:token
  1368. throw ExceptionBuilder.UndefinedDatatype(dt);
  1369. }
  1370. SimpleType rootType = new SimpleType(simpleType);
  1371. while (rootType.BaseSimpleType != null) {
  1372. rootType = rootType.BaseSimpleType;
  1373. }
  1374. return ParseDataType(rootType.BaseType);
  1375. }
  1376. }
  1377. NameType nt = FindNameType(dt);
  1378. return nt.type;
  1379. }
  1380. /* later we may need such a function
  1381. private Boolean IsUDSimpleType(string qname) {
  1382. if (udSimpleTypes == null)
  1383. return false;
  1384. return (udSimpleTypes.Contains(qname));
  1385. }
  1386. */
  1387. internal static Boolean IsXsdType(string name) {
  1388. #if DEBUG
  1389. for(int i = 1; i < mapNameTypeXsd.Length; ++i) {
  1390. Debug.Assert((mapNameTypeXsd[i-1].CompareTo(mapNameTypeXsd[i].name)) < 0, "incorrect sorting " + mapNameTypeXsd[i].name);
  1391. }
  1392. #endif
  1393. int index = Array.BinarySearch(mapNameTypeXsd, name);
  1394. if (index < 0) {
  1395. #if DEBUG
  1396. // Let's check that we realy don't have this name:
  1397. foreach (NameType nt in mapNameTypeXsd) {
  1398. Debug.Assert(nt.name != name, "FindNameType('" + name + "') -- failed. Existed name not found");
  1399. }
  1400. #endif
  1401. return false;
  1402. }
  1403. Debug.Assert(mapNameTypeXsd[index].name == name, "FindNameType('" + name + "') -- failed. Wrong name found");
  1404. return true;
  1405. }
  1406. internal XmlSchemaAnnotated FindTypeNode(XmlSchemaAnnotated node) {
  1407. // this function is returning null
  1408. // if the typeNode for node is in the XSD namespace.
  1409. XmlSchemaAttribute attr = node as XmlSchemaAttribute;
  1410. XmlSchemaElement el = node as XmlSchemaElement;
  1411. bool isAttr = false;
  1412. if (attr != null) {
  1413. isAttr = true;
  1414. }
  1415. String _type = isAttr ? attr.SchemaTypeName.Name : el.SchemaTypeName.Name;
  1416. String _typeNs = isAttr ? attr.SchemaTypeName.Namespace : el.SchemaTypeName.Namespace;
  1417. if (_typeNs == Keywords.XSDNS)
  1418. return null;
  1419. XmlSchemaAnnotated typeNode;
  1420. if (_type == null || _type.Length == 0) {
  1421. _type = isAttr ? attr.RefName.Name : el.RefName.Name;
  1422. if (_type == null || _type.Length == 0)
  1423. typeNode = (XmlSchemaAnnotated) (isAttr ? attr.SchemaType : el.SchemaType);
  1424. else
  1425. typeNode = isAttr ? FindTypeNode((XmlSchemaAnnotated)attributes[attr.RefName]) :FindTypeNode((XmlSchemaAnnotated)elementsTable[el.RefName]);
  1426. }
  1427. else
  1428. typeNode = (XmlSchemaAnnotated)schemaTypes[isAttr ? ((XmlSchemaAttribute)node).SchemaTypeName : ((XmlSchemaElement)node).SchemaTypeName];
  1429. return typeNode;
  1430. }
  1431. internal void HandleSimpleTypeSimpleContentColumn(XmlSchemaSimpleType typeNode, string strType, DataTable table, bool isBase, XmlAttribute[] attrs, bool isNillable){
  1432. // disallow multiple simple content columns for the table
  1433. if(FromInference && table.XmlText != null) { // backward compatability for inference
  1434. return;
  1435. }
  1436. Type type = null;
  1437. SimpleType xsdType = null;
  1438. // if (typeNode.QualifiedName.Namespace != Keywords.XSDNS) { // this means UDSimpleType
  1439. if (typeNode.QualifiedName.Name != null && typeNode.QualifiedName.Name.Length != 0 && typeNode.QualifiedName.Namespace != Keywords.XSDNS) { // this means UDSimpleType
  1440. xsdType = new SimpleType(typeNode);
  1441. strType = typeNode.QualifiedName.ToString(); // use qualifed name
  1442. type = ParseDataType(typeNode.QualifiedName.ToString());
  1443. }
  1444. else {// previous code V 1.1
  1445. XmlSchemaSimpleType ancestor = typeNode.BaseXmlSchemaType as XmlSchemaSimpleType;
  1446. if ((ancestor != null) && (ancestor.QualifiedName.Namespace != Keywords.XSDNS)) {
  1447. xsdType = new SimpleType(typeNode);
  1448. SimpleType rootType = xsdType;
  1449. while (rootType.BaseSimpleType != null) {
  1450. rootType = rootType.BaseSimpleType;
  1451. }
  1452. type = ParseDataType(rootType.BaseType);
  1453. strType = xsdType.Name;
  1454. }
  1455. else {
  1456. type = ParseDataType(strType);
  1457. }
  1458. }
  1459. DataColumn column;
  1460. string colName;
  1461. if (this.FromInference) {
  1462. int i = 0;
  1463. colName = table.TableName + "_Text";
  1464. while (table.Columns[colName] != null) {
  1465. colName = colName + i++;
  1466. }
  1467. }
  1468. else
  1469. colName = table.TableName + "_text";
  1470. string columnName = colName;
  1471. bool isToAdd = true;
  1472. if ((!isBase) && (table.Columns.Contains(columnName, true))){
  1473. column = table.Columns[columnName];
  1474. isToAdd = false;
  1475. }
  1476. else {
  1477. column = new DataColumn(columnName, type, null, MappingType.SimpleContent);
  1478. }
  1479. SetProperties(column, attrs);
  1480. HandleColumnExpression(column, attrs);
  1481. SetExtProperties(column, attrs);
  1482. String tmp = (-1).ToString(CultureInfo.CurrentCulture);
  1483. string defValue = null;
  1484. //try to see if attributes contain allownull
  1485. column.AllowDBNull = isNillable;
  1486. if(attrs!=null)
  1487. for(int i=0; i< attrs.Length;i++) {
  1488. if ( attrs[i].LocalName == Keywords.MSD_ALLOWDBNULL && attrs[i].NamespaceURI == Keywords.MSDNS)
  1489. if ( attrs[i].Value == Keywords.FALSE)
  1490. column.AllowDBNull = false;
  1491. if ( attrs[i].LocalName == Keywords.MSD_ORDINAL && attrs[i].NamespaceURI == Keywords.MSDNS)
  1492. tmp = attrs[i].Value;
  1493. if ( attrs[i].LocalName == Keywords.MSD_DEFAULTVALUE && attrs[i].NamespaceURI == Keywords.MSDNS)
  1494. defValue = attrs[i].Value;
  1495. }
  1496. int ordinal = (int)Convert.ChangeType(tmp, typeof(int), null);
  1497. //SetExtProperties(column, attr.UnhandledAttributes);
  1498. if ((column.Expression!=null)&&(column.Expression.Length!=0)) {
  1499. ColumnExpressions.Add(column);
  1500. }
  1501. // Update XSD type to point to simple types actual namespace instead of normalized default namespace in case of remoting
  1502. if (xsdType != null && xsdType.Name != null && xsdType.Name.Length > 0) {
  1503. if (XSDSchema.GetMsdataAttribute(typeNode, Keywords.TARGETNAMESPACE)!= null) {
  1504. column.XmlDataType = xsdType.SimpleTypeQualifiedName;
  1505. }
  1506. }
  1507. else {
  1508. column.XmlDataType = strType;
  1509. }
  1510. column.SimpleType = xsdType;
  1511. //column.Namespace = typeNode.SourceUri;
  1512. if (isToAdd) {
  1513. if (this.FromInference) {
  1514. column.Prefix = GetPrefix(table.Namespace);
  1515. column.AllowDBNull = true;
  1516. }
  1517. if(ordinal>-1 && ordinal<table.Columns.Count)
  1518. table.Columns.AddAt(ordinal, column);
  1519. else
  1520. table.Columns.Add(column);
  1521. }
  1522. if (defValue != null)
  1523. try {
  1524. column.DefaultValue = column.ConvertXmlToObject(defValue);
  1525. }
  1526. catch (System.FormatException) {
  1527. throw ExceptionBuilder.CannotConvert(defValue, type.FullName);
  1528. }
  1529. }
  1530. internal void HandleSimpleContentColumn(String strType, DataTable table, bool isBase, XmlAttribute[] attrs, bool isNillable){
  1531. // for Named Simple type support : We should not recieved anything here other than string.
  1532. // there can not be typed simple content
  1533. // disallow multiple simple content columns for the table
  1534. if(this.FromInference && table.XmlText != null) // backward compatability for inference
  1535. return;
  1536. Type type = null;
  1537. if (strType == null) {
  1538. return;
  1539. }
  1540. type = ParseDataType(strType); // we pass it correctly when we call the method, no need to special check.
  1541. DataColumn column;
  1542. string colName;
  1543. if (this.FromInference) {
  1544. int i = 0;
  1545. colName = table.TableName + "_Text";
  1546. while (table.Columns[colName] != null) {
  1547. colName = colName + i++;
  1548. }
  1549. }
  1550. else
  1551. colName = table.TableName + "_text";
  1552. string columnName = colName;
  1553. bool isToAdd = true;
  1554. if ((!isBase) && (table.Columns.Contains(columnName, true))){
  1555. column = table.Columns[columnName];
  1556. isToAdd = false;
  1557. }
  1558. else {
  1559. column = new DataColumn(columnName, type, null, MappingType.SimpleContent);
  1560. }
  1561. SetProperties(column, attrs);
  1562. HandleColumnExpression(column, attrs);
  1563. SetExtProperties(column, attrs);
  1564. String tmp = (-1).ToString(CultureInfo.CurrentCulture);
  1565. string defValue = null;
  1566. //try to see if attributes contain allownull
  1567. column.AllowDBNull = isNillable;
  1568. if(attrs!=null)
  1569. for(int i=0; i< attrs.Length;i++) {
  1570. if ( attrs[i].LocalName == Keywords.MSD_ALLOWDBNULL && attrs[i].NamespaceURI == Keywords.MSDNS)
  1571. if ( attrs[i].Value == Keywords.FALSE)
  1572. column.AllowDBNull = false;
  1573. if ( attrs[i].LocalName == Keywords.MSD_ORDINAL && attrs[i].NamespaceURI == Keywords.MSDNS)
  1574. tmp = attrs[i].Value;
  1575. if ( attrs[i].LocalName == Keywords.MSD_DEFAULTVALUE && attrs[i].NamespaceURI == Keywords.MSDNS)
  1576. defValue = attrs[i].Value;
  1577. }
  1578. int ordinal = (int)Convert.ChangeType(tmp, typeof(int), null);
  1579. //SetExtProperties(column, attr.UnhandledAttributes);
  1580. if ((column.Expression!=null)&&(column.Expression.Length!=0)) {
  1581. ColumnExpressions.Add(column);
  1582. }
  1583. column.XmlDataType = strType;
  1584. column.SimpleType = null;
  1585. //column.Namespace = typeNode.SourceUri;
  1586. if(this.FromInference)
  1587. column.Prefix = GetPrefix(column.Namespace);
  1588. if (isToAdd) {
  1589. if (this.FromInference) // move this setting to SetProperties
  1590. column.AllowDBNull = true;
  1591. if(ordinal>-1 && ordinal<table.Columns.Count)
  1592. table.Columns.AddAt(ordinal, column);
  1593. else
  1594. table.Columns.Add(column);
  1595. }
  1596. if (defValue != null)
  1597. try {
  1598. column.DefaultValue = column.ConvertXmlToObject(defValue);
  1599. }
  1600. catch (System.FormatException) {
  1601. throw ExceptionBuilder.CannotConvert(defValue, type.FullName);
  1602. }
  1603. }
  1604. internal void HandleAttributeColumn(XmlSchemaAttribute attrib, DataTable table, bool isBase){
  1605. Type type = null;
  1606. XmlSchemaAttribute attr = attrib.Name != null ? attrib : (XmlSchemaAttribute) attributes[attrib.RefName];
  1607. XmlSchemaAnnotated typeNode = FindTypeNode(attr);
  1608. String strType = null;
  1609. SimpleType xsdType = null;
  1610. if (typeNode == null) {
  1611. strType = attr.SchemaTypeName.Name;
  1612. if (Common.ADP.IsEmpty(strType)) {
  1613. strType = "";
  1614. type = typeof(string);
  1615. }
  1616. else {
  1617. if (attr.SchemaTypeName.Namespace != Keywords.XSDNS) // it is UD Simple Type, can it be?
  1618. //
  1619. type = ParseDataType(attr.SchemaTypeName.ToString());
  1620. else
  1621. type = ParseDataType(attr.SchemaTypeName.Name);
  1622. }
  1623. }
  1624. else if (typeNode is XmlSchemaSimpleType) {
  1625. //
  1626. XmlSchemaSimpleType node = typeNode as XmlSchemaSimpleType;
  1627. xsdType = new SimpleType(node);
  1628. if (node.QualifiedName.Name != null && node.QualifiedName.Name.Length != 0 && node.QualifiedName.Namespace != Keywords.XSDNS) { // this means UDSimpleType
  1629. strType = node.QualifiedName.ToString(); // use qualifed name
  1630. type = ParseDataType(node.QualifiedName.ToString());// search with QName
  1631. }
  1632. else {
  1633. type = ParseDataType(xsdType.BaseType);
  1634. strType = xsdType.Name;
  1635. if(xsdType.Length == 1 && type == typeof(string)) {
  1636. type = typeof(Char);
  1637. }
  1638. }
  1639. }
  1640. else if (typeNode is XmlSchemaElement) {
  1641. strType = ((XmlSchemaElement)typeNode).SchemaTypeName.Name;
  1642. type = ParseDataType(strType);
  1643. }
  1644. else {
  1645. if (typeNode.Id == null)
  1646. throw ExceptionBuilder.DatatypeNotDefined();
  1647. else
  1648. throw ExceptionBuilder.UndefinedDatatype(typeNode.Id);
  1649. }
  1650. DataColumn column;
  1651. string columnName = XmlConvert.DecodeName(GetInstanceName(attr));
  1652. bool isToAdd = true;
  1653. if ((!isBase || FromInference) && (table.Columns.Contains(columnName, true))) {
  1654. column = table.Columns[columnName];
  1655. isToAdd = false;
  1656. if (FromInference) { // for backward compatability with old inference
  1657. // throw eception if same column is being aded with different mapping
  1658. if (column.ColumnMapping != MappingType.Attribute)
  1659. throw ExceptionBuilder.ColumnTypeConflict(column.ColumnName);
  1660. // in previous inference , if we have incoming column with different NS, we think as different column and
  1661. //while adding , since there is no NS concept for datacolumn, we used to throw exception
  1662. // simulate the same behavior.
  1663. if ((Common.ADP.IsEmpty(attrib.QualifiedName.Namespace) && Common.ADP.IsEmpty(column._columnUri)) || // backward compatability :SQL BU DT 310912
  1664. (string.Compare(attrib.QualifiedName.Namespace, column.Namespace, StringComparison.Ordinal) == 0))
  1665. {
  1666. return; // backward compatability
  1667. }
  1668. column = new DataColumn(columnName, type, null, MappingType.Attribute); // this is to fix issue with Exception we used to throw for old inference engine if column
  1669. //exists with different namespace; while adding it to columncollection
  1670. isToAdd = true;
  1671. }
  1672. }
  1673. else {
  1674. column = new DataColumn(columnName, type, null, MappingType.Attribute);
  1675. }
  1676. SetProperties(column, attr.UnhandledAttributes);
  1677. HandleColumnExpression(column, attr.UnhandledAttributes);
  1678. SetExtProperties(column, attr.UnhandledAttributes);
  1679. if ((column.Expression!=null)&&(column.Expression.Length!=0)) {
  1680. ColumnExpressions.Add(column);
  1681. }
  1682. if (xsdType != null && xsdType.Name != null && xsdType.Name.Length > 0) {
  1683. if (XSDSchema.GetMsdataAttribute(typeNode, Keywords.TARGETNAMESPACE)!= null) {
  1684. column.XmlDataType = xsdType.SimpleTypeQualifiedName;
  1685. }
  1686. }
  1687. else {
  1688. column.XmlDataType = strType;
  1689. }
  1690. column.SimpleType = xsdType;
  1691. column.AllowDBNull = !(attrib.Use == XmlSchemaUse.Required);
  1692. column.Namespace = attrib.QualifiedName.Namespace;
  1693. column.Namespace = GetStringAttribute(attrib, "targetNamespace", column.Namespace);
  1694. if (isToAdd) {
  1695. if (this.FromInference) { // move this setting to SetProperties
  1696. column.AllowDBNull = true;
  1697. column.Prefix = GetPrefix(column.Namespace);
  1698. }
  1699. table.Columns.Add(column);
  1700. }
  1701. if (attrib.Use == XmlSchemaUse.Prohibited) {
  1702. column.ColumnMapping = MappingType.Hidden;
  1703. column.AllowDBNull = GetBooleanAttribute(attr, Keywords.MSD_ALLOWDBNULL, true) ;
  1704. String defValue = GetMsdataAttribute(attr, Keywords.MSD_DEFAULTVALUE);
  1705. if (defValue != null)
  1706. try {
  1707. column.DefaultValue = column.ConvertXmlToObject(defValue);
  1708. }
  1709. catch (System.FormatException) {
  1710. throw ExceptionBuilder.CannotConvert(defValue, type.FullName);
  1711. }
  1712. }
  1713. // XDR [....] change
  1714. string strDefault = (attrib.Use == XmlSchemaUse.Required) ? GetMsdataAttribute(attr, Keywords.MSD_DEFAULTVALUE) : attr.DefaultValue;
  1715. if ((attr.Use == XmlSchemaUse.Optional) && (strDefault == null ))
  1716. strDefault = attr.FixedValue;
  1717. if (strDefault != null)
  1718. try {
  1719. column.DefaultValue = column.ConvertXmlToObject(strDefault);
  1720. }
  1721. catch (System.FormatException) {
  1722. throw ExceptionBuilder.CannotConvert(strDefault, type.FullName);
  1723. }
  1724. }
  1725. internal void HandleElementColumn(XmlSchemaElement elem, DataTable table, bool isBase){
  1726. Type type = null;
  1727. XmlSchemaElement el = elem.Name != null ? elem : (XmlSchemaElement) elementsTable[elem.RefName];
  1728. if (el == null) // it's possible due to some XSD compiler optimizations
  1729. return; // do nothing
  1730. XmlSchemaAnnotated typeNode = FindTypeNode(el);
  1731. String strType = null;
  1732. SimpleType xsdType = null;
  1733. if (typeNode == null) {
  1734. strType = el.SchemaTypeName.Name;
  1735. if (Common.ADP.IsEmpty(strType)) {
  1736. strType = "";
  1737. type = typeof(string);
  1738. }
  1739. else {
  1740. type = ParseDataType(el.SchemaTypeName.Name);
  1741. }
  1742. }
  1743. else if (typeNode is XmlSchemaSimpleType) {
  1744. //
  1745. XmlSchemaSimpleType simpleTypeNode = typeNode as XmlSchemaSimpleType;
  1746. xsdType = new SimpleType(simpleTypeNode);
  1747. // ((XmlSchemaSimpleType)typeNode).Name != null && ((XmlSchemaSimpleType)typeNode).Name.Length != 0 check is for annonymos simple type,
  1748. // it should be user defined Named simple type
  1749. if (((XmlSchemaSimpleType)typeNode).Name != null && ((XmlSchemaSimpleType)typeNode).Name.Length != 0 && ((XmlSchemaSimpleType)typeNode).QualifiedName.Namespace != Keywords.XSDNS) {
  1750. string targetNamespace = XSDSchema.GetMsdataAttribute(typeNode, Keywords.TARGETNAMESPACE);
  1751. strType = ((XmlSchemaSimpleType)typeNode).QualifiedName.ToString(); // use qualifed name
  1752. type = ParseDataType(strType);
  1753. }
  1754. else {
  1755. simpleTypeNode = (xsdType.XmlBaseType!= null && xsdType.XmlBaseType.Namespace != Keywords.XSDNS) ?
  1756. schemaTypes[xsdType.XmlBaseType] as XmlSchemaSimpleType :
  1757. null;
  1758. while (simpleTypeNode != null) {
  1759. xsdType.LoadTypeValues(simpleTypeNode);
  1760. simpleTypeNode = (xsdType.XmlBaseType!= null && xsdType.XmlBaseType.Namespace != Keywords.XSDNS) ?
  1761. schemaTypes[xsdType.XmlBaseType] as XmlSchemaSimpleType :
  1762. null;
  1763. }
  1764. type = ParseDataType(xsdType.BaseType);
  1765. strType = xsdType.Name;
  1766. if(xsdType.Length == 1 && type == typeof(string)) {
  1767. type = typeof(Char);
  1768. }
  1769. }
  1770. }
  1771. else if (typeNode is XmlSchemaElement) { // theoratically no named simpletype should come here
  1772. strType = ((XmlSchemaElement)typeNode).SchemaTypeName.Name;
  1773. type = ParseDataType(strType);
  1774. }
  1775. else if (typeNode is XmlSchemaComplexType) {
  1776. if (ADP.IsEmpty(XSDSchema.GetMsdataAttribute(elem, Keywords.MSD_DATATYPE))) {
  1777. throw ExceptionBuilder.DatatypeNotDefined();
  1778. }
  1779. else {
  1780. type = typeof(object);
  1781. }
  1782. }
  1783. else {
  1784. if (typeNode.Id == null)
  1785. throw ExceptionBuilder.DatatypeNotDefined();
  1786. else
  1787. throw ExceptionBuilder.UndefinedDatatype(typeNode.Id);
  1788. }
  1789. DataColumn column;
  1790. string columnName = XmlConvert.DecodeName(GetInstanceName(el));
  1791. bool isToAdd = true;
  1792. if (((!isBase) || FromInference) && (table.Columns.Contains(columnName, true))) {
  1793. column = table.Columns[columnName];
  1794. isToAdd = false;
  1795. if (FromInference) { // for backward compatability with old inference
  1796. if (column.ColumnMapping != MappingType.Element)
  1797. throw ExceptionBuilder.ColumnTypeConflict(column.ColumnName);
  1798. // in previous inference , if we have incoming column with different NS, we think as different column and
  1799. //while adding , since there is no NS concept for datacolumn, we used to throw exception
  1800. // simulate the same behavior.
  1801. if ((Common.ADP.IsEmpty(elem.QualifiedName.Namespace) && Common.ADP.IsEmpty(column._columnUri)) || // backward compatability :SQL BU DT 310912
  1802. (string.Compare(elem.QualifiedName.Namespace, column.Namespace, StringComparison.Ordinal) == 0))
  1803. {
  1804. return; // backward compatability
  1805. }
  1806. column = new DataColumn(columnName, type, null, MappingType.Element);// this is to fix issue with Exception we used to throw for old inference engine if column
  1807. //exists with different namespace; while adding it to columncollection
  1808. isToAdd = true;
  1809. }
  1810. }
  1811. else {
  1812. column = new DataColumn(columnName, type, null, MappingType.Element);
  1813. }
  1814. SetProperties(column, el.UnhandledAttributes);
  1815. HandleColumnExpression(column, el.UnhandledAttributes);
  1816. SetExtProperties(column, el.UnhandledAttributes);
  1817. if (!Common.ADP.IsEmpty(column.Expression)) {
  1818. ColumnExpressions.Add(column);
  1819. }
  1820. // Update XSD type to point to simple types actual namespace instead of normalized default namespace in case of remoting
  1821. if (xsdType != null && xsdType.Name != null && xsdType.Name.Length > 0) {
  1822. if (XSDSchema.GetMsdataAttribute(typeNode, Keywords.TARGETNAMESPACE)!= null) {
  1823. column.XmlDataType = xsdType.SimpleTypeQualifiedName;
  1824. }
  1825. }
  1826. else {
  1827. column.XmlDataType = strType;
  1828. }
  1829. column.SimpleType = xsdType;
  1830. column.AllowDBNull = this.FromInference ||(elem.MinOccurs == 0 ) || elem.IsNillable;
  1831. if (!elem.RefName.IsEmpty || elem.QualifiedName.Namespace != table.Namespace)
  1832. { // if ref element (or in diferent NS) it is global element, so form MUST BE Qualified
  1833. column.Namespace = elem.QualifiedName.Namespace;
  1834. column.Namespace = GetStringAttribute(el, "targetNamespace", column.Namespace);
  1835. }
  1836. else { // it is local, hence check for 'form' on local element, if not specified, check for 'elemenfformdefault' on schema element
  1837. if (elem.Form == XmlSchemaForm.Unqualified) {
  1838. column.Namespace = String.Empty;
  1839. }
  1840. else if (elem.Form == XmlSchemaForm.None) {
  1841. XmlSchemaObject e = (XmlSchemaObject)elem.Parent;
  1842. while (e.Parent != null) {
  1843. e = e.Parent;
  1844. }
  1845. if (((XmlSchema)e).ElementFormDefault == XmlSchemaForm.Unqualified) {
  1846. column.Namespace = String.Empty;
  1847. }
  1848. }
  1849. else {
  1850. column.Namespace = elem.QualifiedName.Namespace;
  1851. column.Namespace = GetStringAttribute(el, "targetNamespace", column.Namespace);
  1852. }
  1853. }
  1854. String tmp = GetStringAttribute(elem, Keywords.MSD_ORDINAL, (-1).ToString(CultureInfo.CurrentCulture));
  1855. int ordinal = (int)Convert.ChangeType(tmp, typeof(int), null);
  1856. if(isToAdd) {
  1857. if(ordinal>-1 && ordinal<table.Columns.Count)
  1858. table.Columns.AddAt(ordinal, column);
  1859. else
  1860. table.Columns.Add(column);
  1861. }
  1862. if (column.Namespace == table.Namespace)
  1863. column._columnUri = null; // to not raise a column change namespace again
  1864. if(this.FromInference) {// search for prefix after adding to table, so NS has its final value, and
  1865. column.Prefix = GetPrefix(column.Namespace); // it can inherit its NS from DataTable, if it is null
  1866. }
  1867. string strDefault = el.DefaultValue;
  1868. if (strDefault != null )
  1869. try {
  1870. column.DefaultValue = column.ConvertXmlToObject(strDefault);
  1871. }
  1872. catch (System.FormatException) {
  1873. throw ExceptionBuilder.CannotConvert(strDefault, type.FullName);
  1874. }
  1875. }
  1876. internal void HandleDataSet(XmlSchemaElement node, bool isNewDataSet) {
  1877. string dsName = node.Name;
  1878. string dsNamespace = node.QualifiedName.Namespace;
  1879. int initialTableCount = _ds.Tables.Count; // just use for inference backward compatablity
  1880. List<DataTable> tableSequenceList = new List<DataTable>();
  1881. String value = GetMsdataAttribute(node, Keywords.MSD_LOCALE);
  1882. if (null != value) { // set by user
  1883. if (0 != value.Length) {
  1884. // <... msdata:Locale="en-US"/>
  1885. _ds.Locale = new CultureInfo(value);
  1886. }
  1887. else {
  1888. // everett bug behavior before <... msdata:Locale=""/> becoming CultureInfo(0x409)
  1889. _ds.Locale = CultureInfo.InvariantCulture;
  1890. }
  1891. }
  1892. else { // not set by user
  1893. // MSD_LOCALE overrides MSD_USECURRENTLOCALE
  1894. if (GetBooleanAttribute(node, Keywords.MSD_USECURRENTLOCALE, false)) {
  1895. _ds.SetLocaleValue(CultureInfo.CurrentCulture, false);
  1896. }
  1897. else {
  1898. // everett behavior before <... msdata:UseCurrentLocale="true"/>
  1899. _ds.SetLocaleValue(new CultureInfo(0x409), false);
  1900. }
  1901. }
  1902. // reuse variable
  1903. value = GetMsdataAttribute(node, Keywords.MSD_DATASETNAME);
  1904. if (value!=null && value.Length != 0) {
  1905. dsName = value;
  1906. }
  1907. value = GetMsdataAttribute(node, Keywords.MSD_DATASETNAMESPACE);
  1908. if (value!=null && value.Length != 0) {
  1909. dsNamespace = value;
  1910. }
  1911. SetProperties(_ds, node.UnhandledAttributes);
  1912. SetExtProperties(_ds, node.UnhandledAttributes);
  1913. if (dsName != null && dsName.Length != 0)
  1914. _ds.DataSetName = XmlConvert.DecodeName(dsName);
  1915. // _ds.Namespace = node.QualifiedName.Namespace;
  1916. _ds.Namespace = dsNamespace;
  1917. if (this.FromInference)
  1918. _ds.Prefix = GetPrefix(_ds.Namespace);
  1919. XmlSchemaComplexType ct = (XmlSchemaComplexType) FindTypeNode(node);
  1920. if (ct.Particle != null) {
  1921. XmlSchemaObjectCollection items = GetParticleItems(ct.Particle);
  1922. if (items == null) {
  1923. return;
  1924. }
  1925. foreach (XmlSchemaAnnotated el in items){
  1926. if (el is XmlSchemaElement) {
  1927. if(((XmlSchemaElement)el).RefName.Name.Length != 0) {
  1928. if (!FromInference) {
  1929. continue;
  1930. }
  1931. else {
  1932. DataTable tempTable = _ds.Tables.GetTable(XmlConvert.DecodeName(GetInstanceName((XmlSchemaElement)el)), node.QualifiedName.Namespace);
  1933. if (tempTable != null) {
  1934. tableSequenceList.Add(tempTable); // if ref table is created, add it
  1935. }
  1936. bool isComplexTypeOrValidElementType = false;
  1937. if (node.ElementSchemaType != null || !(((XmlSchemaElement)el).SchemaType is XmlSchemaComplexType)) {
  1938. isComplexTypeOrValidElementType = true;
  1939. }
  1940. // bool isComplexTypeOrValidElementType = (node.ElementType != null || !(((XmlSchemaElement)el).SchemaType is XmlSchemaComplexType));
  1941. if ((((XmlSchemaElement)el).MaxOccurs != Decimal.One ) && (!isComplexTypeOrValidElementType)) {
  1942. continue;
  1943. }
  1944. }
  1945. }
  1946. DataTable child = HandleTable ((XmlSchemaElement)el);
  1947. if (child!=null) {
  1948. child.fNestedInDataset = true;
  1949. }
  1950. if (FromInference) {
  1951. tableSequenceList.Add(child);
  1952. }
  1953. }
  1954. else if (el is XmlSchemaChoice){ // should we check for inference?
  1955. XmlSchemaObjectCollection choiceItems = ((XmlSchemaChoice)el).Items;
  1956. if (choiceItems == null)
  1957. continue;
  1958. foreach (XmlSchemaAnnotated choiceEl in choiceItems) {
  1959. if (choiceEl is XmlSchemaElement) {
  1960. if (((XmlSchemaParticle)el).MaxOccurs > Decimal.One && (((XmlSchemaElement)choiceEl).SchemaType is XmlSchemaComplexType)) // amir
  1961. ((XmlSchemaElement)choiceEl).MaxOccurs = ((XmlSchemaParticle)el).MaxOccurs;
  1962. if ((((XmlSchemaElement)choiceEl).RefName.Name.Length != 0) && (!FromInference && ((XmlSchemaElement)choiceEl).MaxOccurs != Decimal.One && !(((XmlSchemaElement)choiceEl).SchemaType is XmlSchemaComplexType)))
  1963. continue;
  1964. DataTable child = HandleTable ((XmlSchemaElement)choiceEl);
  1965. if (FromInference) {
  1966. tableSequenceList.Add(child);
  1967. }
  1968. if (child != null)
  1969. {
  1970. child.fNestedInDataset = true;
  1971. }
  1972. }
  1973. }
  1974. }
  1975. }
  1976. }
  1977. // Handle the non-nested keyref constraints
  1978. if (node.Constraints != null) {
  1979. foreach (XmlSchemaIdentityConstraint key in node.Constraints) {
  1980. XmlSchemaKeyref keyref = key as XmlSchemaKeyref;
  1981. if (keyref == null)
  1982. continue;
  1983. bool isNested = GetBooleanAttribute(keyref, Keywords.MSD_ISNESTED, /*default:*/ false);
  1984. if (isNested)
  1985. continue;
  1986. HandleKeyref(keyref);
  1987. }
  1988. }
  1989. if (FromInference && isNewDataSet) {
  1990. List<DataTable> _tableList = new List<DataTable>(_ds.Tables.Count);
  1991. foreach(DataTable dt in tableSequenceList) {
  1992. AddTablesToList(_tableList, dt);
  1993. }
  1994. _ds.Tables.ReplaceFromInference(_tableList); // replace the list with the one in correct order: BackWard compatability for inference
  1995. }
  1996. }
  1997. private void AddTablesToList(List<DataTable> tableList, DataTable dt) { // kind of depth _first travarsal
  1998. if (!tableList.Contains(dt)) {
  1999. tableList.Add(dt);
  2000. foreach(DataTable childTable in tableDictionary[dt]) {
  2001. AddTablesToList(tableList, childTable);
  2002. }
  2003. }
  2004. }
  2005. private string GetPrefix(string ns) {
  2006. if (ns == null)
  2007. return null;
  2008. foreach (XmlSchema schemaRoot in _schemaSet.Schemas()) {
  2009. XmlQualifiedName[] qualifiedNames = schemaRoot.Namespaces.ToArray();
  2010. for(int i = 0; i < qualifiedNames.Length; i++) {
  2011. if (qualifiedNames[i].Namespace == ns)
  2012. return qualifiedNames[i].Name;
  2013. }
  2014. }
  2015. return null;
  2016. }
  2017. private string GetNamespaceFromPrefix(string prefix) {
  2018. if ((prefix == null) ||(prefix.Length == 0))
  2019. return null;
  2020. foreach (XmlSchema schemaRoot in _schemaSet.Schemas()) {
  2021. XmlQualifiedName[] qualifiedNames = schemaRoot.Namespaces.ToArray();
  2022. for(int i = 0; i < qualifiedNames.Length; i++) {
  2023. if (qualifiedNames[i].Name == prefix)
  2024. return qualifiedNames[i].Namespace;
  2025. }
  2026. }
  2027. return null;
  2028. }
  2029. private String GetTableNamespace(XmlSchemaIdentityConstraint key) {
  2030. string xpath = key.Selector.XPath;
  2031. string [] split = xpath.Split('/');
  2032. string prefix =string.Empty;
  2033. string QualifiedTableName = split[split.Length - 1]; //get the last string after '/' and ':'
  2034. if ((QualifiedTableName == null) || (QualifiedTableName.Length == 0))
  2035. throw ExceptionBuilder.InvalidSelector(xpath);
  2036. if (QualifiedTableName.IndexOf(':') != -1)
  2037. prefix = QualifiedTableName.Substring(0, QualifiedTableName.IndexOf(':'));
  2038. else
  2039. return GetMsdataAttribute(key, Keywords.MSD_TABLENS);
  2040. prefix = XmlConvert.DecodeName(prefix );
  2041. return GetNamespaceFromPrefix(prefix);
  2042. }
  2043. private String GetTableName(XmlSchemaIdentityConstraint key) {
  2044. string xpath = key.Selector.XPath;
  2045. string [] split = xpath.Split('/',':');
  2046. String tableName = split[split.Length - 1]; //get the last string after '/' and ':'
  2047. if ((tableName == null) || (tableName.Length == 0))
  2048. throw ExceptionBuilder.InvalidSelector(xpath);
  2049. tableName = XmlConvert.DecodeName(tableName);
  2050. return tableName;
  2051. }
  2052. internal bool IsTable(XmlSchemaElement node) {
  2053. if (node.MaxOccurs == decimal.Zero)
  2054. return false;
  2055. XmlAttribute[] attribs = node.UnhandledAttributes;
  2056. if (attribs != null) {
  2057. for(int i = 0; i < attribs.Length; i++) {
  2058. XmlAttribute attrib = attribs[i];
  2059. if (attrib.LocalName == Keywords.MSD_DATATYPE &&
  2060. attrib.Prefix == Keywords.MSD &&
  2061. attrib.NamespaceURI == Keywords.MSDNS)
  2062. return false;
  2063. }
  2064. }
  2065. Object typeNode = FindTypeNode(node);
  2066. if ( (node.MaxOccurs > decimal.One) && typeNode == null ){
  2067. return true;
  2068. }
  2069. if ((typeNode==null) || !(typeNode is XmlSchemaComplexType)) {
  2070. return false;
  2071. }
  2072. XmlSchemaComplexType ctNode = (XmlSchemaComplexType) typeNode;
  2073. if (ctNode.IsAbstract)
  2074. throw ExceptionBuilder.CannotInstantiateAbstract(node.Name);
  2075. return true;
  2076. }
  2077. // internal bool IsTopLevelElement (XmlSchemaElement node) {
  2078. // return (elements.IndexOf(node) != -1);
  2079. // }
  2080. internal DataTable HandleTable(XmlSchemaElement node) {
  2081. if (!IsTable(node))
  2082. return null;
  2083. Object typeNode = FindTypeNode(node);
  2084. if ( (node.MaxOccurs > decimal.One) && typeNode == null ){
  2085. return InstantiateSimpleTable(node);
  2086. }
  2087. DataTable table = InstantiateTable(node,(XmlSchemaComplexType)typeNode, (node.RefName != null)); // this is wrong , correct check should be node.RefName.IsEmpty
  2088. table.fNestedInDataset = false;
  2089. return table;
  2090. }
  2091. }
  2092. internal sealed class XmlIgnoreNamespaceReader : XmlNodeReader {
  2093. private List<string> namespacesToIgnore;
  2094. //
  2095. // Constructor
  2096. //
  2097. internal XmlIgnoreNamespaceReader(XmlDocument xdoc, string[] namespacesToIgnore) : base(xdoc) {
  2098. this.namespacesToIgnore = new List<string>(namespacesToIgnore);
  2099. }
  2100. //
  2101. // XmlReader implementation
  2102. //
  2103. public override bool MoveToFirstAttribute() {
  2104. if (base.MoveToFirstAttribute()) {
  2105. if ( namespacesToIgnore.Contains(this.NamespaceURI) ||
  2106. (this.NamespaceURI == Keywords.XML_XMLNS && this.LocalName != "lang")) { //try next one
  2107. return MoveToNextAttribute();
  2108. }
  2109. else {
  2110. return true;
  2111. }
  2112. }
  2113. return false;
  2114. }
  2115. public override bool MoveToNextAttribute() {
  2116. bool moved, flag;
  2117. do {
  2118. moved = false;
  2119. flag = false;
  2120. if (base.MoveToNextAttribute()) {
  2121. moved = true;
  2122. if ( namespacesToIgnore.Contains(this.NamespaceURI) ||
  2123. (this.NamespaceURI == Keywords.XML_XMLNS && this.LocalName != "lang")) {
  2124. flag = true;
  2125. }
  2126. }
  2127. } while(flag);
  2128. return moved;
  2129. }
  2130. }
  2131. }