| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689 |
- //------------------------------------------------------------------------------
- // <copyright file="XmlConvert.cs" company="Microsoft">
- // Copyright (c) Microsoft Corporation. All rights reserved.
- // </copyright>
- // <owner current="true" primary="true">Microsoft</owner>
- //------------------------------------------------------------------------------
- namespace System.Xml {
- using System.IO;
- using System.Text;
- using System.Globalization;
- using System.Xml.Schema;
- using System.Diagnostics;
- using System.Collections;
- using System.Text.RegularExpressions;
- // ExceptionType enum is used inside XmlConvert to specify which type of exception should be thrown at some of the verification and exception creating methods
- internal enum ExceptionType {
- ArgumentException,
- XmlException,
- }
- // Options for serializing and deserializing DateTime
- public enum XmlDateTimeSerializationMode {
- Local,
- Utc,
- Unspecified,
- RoundtripKind,
- }
- /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert"]/*' />
- /// <devdoc>
- /// Encodes and decodes XML names according to
- /// the "Encoding of arbitrary Unicode Characters in XML Names" specification.
- /// </devdoc>
- public class XmlConvert {
- //
- // Static fields with implicit initialization
- //
- static XmlCharType xmlCharType = XmlCharType.Instance;
- #if !SILVERLIGHT
- internal static char[] crt = new char[] {'\n', '\r', '\t'};
- #endif
- /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.EncodeName"]/*' />
- /// <devdoc>
- /// <para>
- /// Converts names, such
- /// as DataTable or
- /// DataColumn names, that contain characters that are not permitted in
- /// XML names to valid names.</para>
- /// </devdoc>
- public static string EncodeName(string name) {
- return EncodeName(name, true/*Name_not_NmToken*/, false/*Local?*/);
- }
- /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.EncodeNmToken"]/*' />
- /// <devdoc>
- /// <para> Verifies the name is valid
- /// according to production [7] in the XML spec.</para>
- /// </devdoc>
- public static string EncodeNmToken(string name) {
- return EncodeName(name, false/*Name_not_NmToken*/, false/*Local?*/);
- }
- /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.EncodeLocalName"]/*' />
- /// <devdoc>
- /// <para>Converts names, such as DataTable or DataColumn names, that contain
- /// characters that are not permitted in XML names to valid names.</para>
- /// </devdoc>
- public static string EncodeLocalName(string name) {
- return EncodeName(name, true/*Name_not_NmToken*/, true/*Local?*/);
- }
- /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.DecodeName"]/*' />
- /// <devdoc>
- /// <para>
- /// Transforms an XML name into an object name (such as DataTable or DataColumn).</para>
- /// </devdoc>
- public static string DecodeName(string name) {
- if (name == null || name.Length == 0)
- return name;
- StringBuilder bufBld = null;
- int length = name.Length;
- int copyPosition = 0;
- int underscorePos = name.IndexOf('_');
- MatchCollection mc = null;
- IEnumerator en = null;
- if (underscorePos >= 0)
- {
- if ( c_DecodeCharPattern == null ) {
- c_DecodeCharPattern = new Regex("_[Xx]([0-9a-fA-F]{4}|[0-9a-fA-F]{8})_");
- }
- mc = c_DecodeCharPattern.Matches(name, underscorePos);
- en = mc.GetEnumerator();
- } else {
- return name;
- }
- int matchPos = -1;
- if (en != null && en.MoveNext())
- {
- Match m = (Match)en.Current;
- matchPos = m.Index;
- }
- for (int position = 0; position < length - c_EncodedCharLength + 1; position ++) {
- if (position == matchPos) {
- if (en.MoveNext())
- {
- Match m = (Match)en.Current;
- matchPos = m.Index;
- }
- if (bufBld == null) {
- bufBld = new StringBuilder(length + 20);
- }
- bufBld.Append(name, copyPosition, position - copyPosition);
- if (name[position + 6]!='_') { //_x1234_
- Int32 u =
- FromHex(name[position + 2]) * 0x10000000 +
- FromHex(name[position + 3]) * 0x1000000 +
- FromHex(name[position + 4]) * 0x100000 +
- FromHex(name[position + 5]) * 0x10000 +
- FromHex(name[position + 6]) * 0x1000 +
- FromHex(name[position + 7]) * 0x100 +
- FromHex(name[position + 8]) * 0x10 +
- FromHex(name[position + 9]);
- if (u >= 0x00010000) {
- if (u <= 0x0010ffff) { //convert to two chars
- copyPosition = position + c_EncodedCharLength + 4;
- char lowChar, highChar;
- XmlCharType.SplitSurrogateChar(u, out lowChar, out highChar);
- bufBld.Append(highChar);
- bufBld.Append(lowChar);
- }
- //else bad ucs-4 char dont convert
- }
- else { //convert to single char
- copyPosition = position + c_EncodedCharLength + 4;
- bufBld.Append((char)u);
- }
- position += c_EncodedCharLength - 1 + 4; //just skip
- }
- else {
- copyPosition = position + c_EncodedCharLength;
- bufBld.Append((char)(
- FromHex(name[position + 2]) * 0x1000 +
- FromHex(name[position + 3]) * 0x100 +
- FromHex(name[position + 4]) * 0x10 +
- FromHex(name[position + 5])));
- position += c_EncodedCharLength - 1;
- }
- }
- }
- if (copyPosition == 0) {
- return name;
- }
- else {
- if (copyPosition < length) {
- bufBld.Append(name, copyPosition, length - copyPosition);
- }
- return bufBld.ToString();
- }
- }
- private static string EncodeName(string name, /*Name_not_NmToken*/ bool first, bool local) {
- if (string.IsNullOrEmpty(name)) {
- return name;
- }
- StringBuilder bufBld = null;
- int length = name.Length;
- int copyPosition = 0;
- int position = 0;
- int underscorePos = name.IndexOf('_');
- MatchCollection mc = null;
- IEnumerator en = null;
- if (underscorePos >= 0)
- {
- if ( c_EncodeCharPattern == null ) {
- c_EncodeCharPattern = new Regex("(?<=_)[Xx]([0-9a-fA-F]{4}|[0-9a-fA-F]{8})_");
- }
- mc = c_EncodeCharPattern.Matches(name, underscorePos);
- en = mc.GetEnumerator();
- }
- int matchPos = -1;
- if (en != null && en.MoveNext())
- {
- Match m = (Match)en.Current;
- matchPos = m.Index - 1;
- }
- if (first) {
- if ( ( !xmlCharType.IsStartNCNameCharXml4e( name[0] ) && (local || (!local && name[0] != ':'))) ||
- matchPos == 0) {
- if (bufBld == null) {
- bufBld = new StringBuilder(length + 20);
- }
- bufBld.Append("_x");
- if (length > 1 && XmlCharType.IsHighSurrogate(name[0]) && XmlCharType.IsLowSurrogate(name[1]) ) {
- int x = name[0];
- int y = name[1];
- Int32 u = XmlCharType.CombineSurrogateChar(y, x);
- bufBld.Append(u.ToString("X8", CultureInfo.InvariantCulture));
- position ++;
- copyPosition = 2;
- }
- else {
- bufBld.Append(((Int32)name[0]).ToString("X4", CultureInfo.InvariantCulture));
- copyPosition = 1;
- }
- bufBld.Append("_");
- position ++;
- if (matchPos == 0)
- if (en.MoveNext())
- {
- Match m = (Match)en.Current;
- matchPos = m.Index - 1;
- }
- }
- }
- for (; position < length; position ++) {
- if ((local && !xmlCharType.IsNCNameCharXml4e(name[position])) ||
- (!local && !xmlCharType.IsNameCharXml4e(name[position])) ||
- (matchPos == position))
- {
- if (bufBld == null) {
- bufBld = new StringBuilder(length + 20);
- }
- if (matchPos == position)
- if (en.MoveNext())
- {
- Match m = (Match)en.Current;
- matchPos = m.Index - 1;
- }
- bufBld.Append(name, copyPosition, position - copyPosition);
- bufBld.Append("_x");
- if ((length > position + 1) && XmlCharType.IsHighSurrogate(name[position]) && XmlCharType.IsLowSurrogate(name[position + 1])) {
- int x = name[position];
- int y = name[position + 1];
- Int32 u = XmlCharType.CombineSurrogateChar(y, x);
- bufBld.Append(u.ToString("X8", CultureInfo.InvariantCulture));
- copyPosition = position + 2;
- position ++;
- }
- else {
- bufBld.Append(((Int32)name[position]).ToString("X4", CultureInfo.InvariantCulture));
- copyPosition = position + 1;
- }
- bufBld.Append("_");
- }
- }
- if (copyPosition == 0) {
- return name;
- }
- else {
- if (copyPosition < length) {
- bufBld.Append(name, copyPosition, length - copyPosition);
- }
- return bufBld.ToString();
- }
- }
- private static readonly int c_EncodedCharLength = 7; // ("_xFFFF_".Length);
- private static volatile Regex c_EncodeCharPattern;
- private static volatile Regex c_DecodeCharPattern;
- private static int FromHex(char digit) {
- return(digit <= '9')
- ? ((int)digit - (int)'0')
- : (((digit <= 'F')
- ? ((int)digit - (int)'A')
- : ((int)digit - (int)'a'))
- + 10);
- }
- internal static byte[] FromBinHexString(string s) {
- return FromBinHexString(s, true);
- }
- internal static byte[] FromBinHexString(string s, bool allowOddCount ) {
- if (s == null) {
- throw new ArgumentNullException("s");
- }
- return BinHexDecoder.Decode(s.ToCharArray(), allowOddCount);
- }
- internal static string ToBinHexString(byte[] inArray) {
- if (inArray == null) {
- throw new ArgumentNullException("inArray");
- }
- return BinHexEncoder.Encode(inArray, 0, inArray.Length);
- }
- //
- // Verification methods for strings
- //
- /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.VerifyName"]/*' />
- /// <devdoc>
- /// <para>
- /// </para>
- /// </devdoc>
- public static string VerifyName(string name) {
- if (name == null) {
- throw new ArgumentNullException("name");
- }
- if (name.Length == 0) {
- throw new ArgumentNullException("name", Res.GetString(Res.Xml_EmptyName));
- }
- // parse name
- int endPos = ValidateNames.ParseNameNoNamespaces(name, 0);
- if (endPos != name.Length) {
- // did not parse to the end -> there is invalid character at endPos
- throw CreateInvalidNameCharException(name, endPos, ExceptionType.XmlException);
- }
- return name;
- }
- #if !SILVERLIGHT
- internal static Exception TryVerifyName(string name) {
- if (name == null || name.Length == 0) {
- return new XmlException(Res.Xml_EmptyName, string.Empty);
- }
- int endPos = ValidateNames.ParseNameNoNamespaces(name, 0);
- if (endPos != name.Length) {
- return new XmlException(endPos == 0 ? Res.Xml_BadStartNameChar : Res.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos));
- }
- return null;
- }
- internal static string VerifyQName(string name) {
- return VerifyQName(name, ExceptionType.XmlException);
- }
- #endif
- #if SILVERLIGHT
- internal static string VerifyQName(string name, ExceptionType exceptionType) {
- #else
- internal static unsafe string VerifyQName(string name, ExceptionType exceptionType) {
- #endif
- if (name == null || name.Length == 0) {
- throw new ArgumentNullException("name");
- }
- int colonPosition = -1;
- int endPos = ValidateNames.ParseQName(name, 0, out colonPosition);
- if (endPos != name.Length) {
- throw CreateException(Res.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos), exceptionType, 0, endPos + 1);
- }
- return name;
- }
- /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.VerifyNCName"]/*' />
- /// <devdoc>
- /// <para>
- /// </para>
- /// </devdoc>
- public static string VerifyNCName(string name) {
- return VerifyNCName(name, ExceptionType.XmlException);
- }
- internal static string VerifyNCName(string name, ExceptionType exceptionType) {
- if (name == null) {
- throw new ArgumentNullException("name");
- }
- if (name.Length == 0) {
- throw new ArgumentNullException("name", Res.GetString(Res.Xml_EmptyLocalName));
- }
- int end = ValidateNames.ParseNCName(name, 0);
-
- if (end != name.Length) {
- // If the string is not a valid NCName, then throw or return false
- throw CreateInvalidNameCharException(name, end, exceptionType);
- }
- return name;
- }
- #if !SILVERLIGHT
- internal static Exception TryVerifyNCName(string name) {
- int len = ValidateNames.ParseNCName(name);
- if (len == 0 || len != name.Length) {
- return ValidateNames.GetInvalidNameException(name, 0, len);
- }
- return null;
- }
- /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.VerifyTOKEN"]/*' />
- /// <devdoc>
- /// <para>
- /// </para>
- /// </devdoc>
- public static string VerifyTOKEN(string token) {
- if (token == null || token.Length == 0) {
- return token;
- }
- if (token[0] == ' ' || token[token.Length - 1] == ' ' || token.IndexOfAny(crt) != -1 || token.IndexOf(" ", StringComparison.Ordinal) != -1) {
- throw new XmlException(Res.Sch_NotTokenString, token);
- }
- return token;
- }
- internal static Exception TryVerifyTOKEN(string token) {
- if (token == null || token.Length == 0) {
- return null;
- }
- if (token[0] == ' ' || token[token.Length - 1] == ' ' || token.IndexOfAny(crt) != -1 || token.IndexOf(" ", StringComparison.Ordinal) != -1) {
- return new XmlException(Res.Sch_NotTokenString, token);
- }
- return null;
- }
- #endif
- /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.VerifyNMTOKEN"]/*' />
- /// <devdoc>
- /// <para>
- /// </para>
- /// </devdoc>
- public static string VerifyNMTOKEN(string name) {
- return VerifyNMTOKEN(name, ExceptionType.XmlException);
- }
- internal static string VerifyNMTOKEN(string name, ExceptionType exceptionType) {
- if (name == null) {
- throw new ArgumentNullException("name");
- }
- if (name.Length == 0) {
- throw CreateException(Res.Xml_InvalidNmToken, name, exceptionType);
- }
- int endPos = ValidateNames.ParseNmtokenNoNamespaces(name, 0);
- if (endPos != name.Length) {
- throw CreateException(Res.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos), exceptionType, 0, endPos + 1);
- }
- return name;
- }
- #if !SILVERLIGHT
- internal static Exception TryVerifyNMTOKEN(string name) {
- if (name == null || name.Length == 0) {
- return new XmlException(Res.Xml_EmptyName, string.Empty);
- }
- int endPos = ValidateNames.ParseNmtokenNoNamespaces(name, 0);
- if (endPos != name.Length) {
- return new XmlException(Res.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos));
- }
- return null;
- }
- internal static string VerifyNormalizedString(string str) {
- if (str.IndexOfAny(crt) != -1) {
- throw new XmlSchemaException(Res.Sch_NotNormalizedString, str);
- }
- return str;
- }
- internal static Exception TryVerifyNormalizedString(string str) {
- if (str.IndexOfAny(crt) != -1) {
- return new XmlSchemaException(Res.Sch_NotNormalizedString, str);
- }
- return null;
- }
- #endif
- // Verification method for XML characters as defined in XML spec production [2] Char.
- // Throws XmlException if invalid character is found, otherwise returns the input string.
- public static string VerifyXmlChars(string content) {
- if (content == null) {
- throw new ArgumentNullException("content");
- }
- VerifyCharData(content, ExceptionType.XmlException);
- return content;
- }
- // Verification method for XML public ID characters as defined in XML spec production [13] PubidChar.
- // Throws XmlException if invalid character is found, otherwise returns the input string.
- public static string VerifyPublicId(string publicId) {
- if (publicId == null) {
- throw new ArgumentNullException("publicId");
- }
- // returns the position of invalid character or -1
- int pos = xmlCharType.IsPublicId(publicId);
- if (pos != -1) {
- throw CreateInvalidCharException(publicId, pos, ExceptionType.XmlException);
- }
- return publicId;
- }
- // Verification method for XML whitespace characters as defined in XML spec production [3] S.
- // Throws XmlException if invalid character is found, otherwise returns the input string.
- public static string VerifyWhitespace(string content) {
- if (content == null) {
- throw new ArgumentNullException("content");
- }
- // returns the position of invalid character or -1
- int pos = xmlCharType.IsOnlyWhitespaceWithPos(content);
- if (pos != -1) {
- throw new XmlException(Res.Xml_InvalidWhitespaceCharacter, XmlException.BuildCharExceptionArgs(content, pos), 0, pos + 1);
- }
- return content;
- }
- //
- // Verification methods for single characters and surrogates
- //
- // In cases where the direct call into XmlCharType would not get automatically inlined (because of the use of byte* field),
- // direct access to the XmlCharType.charProperties is used instead (= manual inlining).
- //
- // Start name character types - as defined in Namespaces XML 1.0 spec (second edition) production [6] NCNameStartChar
- // combined with the production [4] NameStartChar of XML 1.0 spec
- public static unsafe bool IsStartNCNameChar(char ch) {
- #if SILVERLIGHT
- return xmlCharType.IsStartNCNameSingleChar(ch);
- #else
- return (xmlCharType.charProperties[ch] & XmlCharType.fNCStartNameSC) != 0;
- #endif
- }
- #if XML10_FIFTH_EDITION
- public static bool IsStartNCNameSurrogatePair(char lowChar, char highChar) {
- return xmlCharType.IsNCNameSurrogateChar(lowChar, highChar);
- }
- #endif
- // Name character types - as defined in Namespaces XML 1.0 spec (second edition) production [6] NCNameStartChar
- // combined with the production [4] NameChar of XML 1.0 spec
- public static unsafe bool IsNCNameChar(char ch) {
- #if SILVERLIGHT
- return xmlCharType.IsNCNameSingleChar(ch);
- #else
- return (xmlCharType.charProperties[ch] & XmlCharType.fNCNameSC) != 0;
- #endif
- }
- #if XML10_FIFTH_EDITION
- public static bool IsNCNameSurrogatePair(char lowChar, char highChar) {
- return xmlCharType.IsNCNameSurrogateChar(lowChar, highChar);
- }
- #endif
- // Valid XML character – as defined in XML 1.0 spec (fifth edition) production [2] Char
- public static unsafe bool IsXmlChar(char ch) {
- #if SILVERLIGHT
- return xmlCharType.IsCharData(ch);
- #else
- return (xmlCharType.charProperties[ch] & XmlCharType.fCharData) != 0;
- #endif
- }
- public static bool IsXmlSurrogatePair(char lowChar, char highChar) {
- return XmlCharType.IsHighSurrogate(highChar) && XmlCharType.IsLowSurrogate(lowChar);
- }
- // Valid PUBLIC ID character – as defined in XML 1.0 spec (fifth edition) production [13] PublidChar
- public static bool IsPublicIdChar(char ch) {
- return xmlCharType.IsPubidChar(ch);
- }
- // Valid Xml white space – as defined in XML 1.0 spec (fifth edition) production [3] S
- public static unsafe bool IsWhitespaceChar(char ch) {
- #if SILVERLIGHT
- return xmlCharType.IsWhiteSpace(ch);
- #else
- return (xmlCharType.charProperties[ch] & XmlCharType.fWhitespace) != 0;
- #endif
- }
- // Value convertors:
- //
- // String representation of Base types in XML (xsd) sometimes differ from
- // one common language runtime offer and for all types it has to be locale independent.
- // o -- means that XmlConvert pass through to common language runtime converter with InvariantInfo FormatInfo
- // x -- means we doing something special to make a convertion.
- //
- // From: To: Bol Chr SBy Byt I16 U16 I32 U32 I64 U64 Sgl Dbl Dec Dat Tim Str uid
- // ------------------------------------------------------------------------------
- // Boolean x
- // Char o
- // SByte o
- // Byte o
- // Int16 o
- // UInt16 o
- // Int32 o
- // UInt32 o
- // Int64 o
- // UInt64 o
- // Single x
- // Double x
- // Decimal o
- // DateTime x
- // String x o o o o o o o o o o x x o o x
- // Guid x
- // -----------------------------------------------------------------------------
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static string ToString(Boolean value) {
- return value ? "true" : "false";
- }
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString1"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static string ToString(Char value) {
- return value.ToString(null);
- }
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString2"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static string ToString(Decimal value) {
- return value.ToString(null, NumberFormatInfo.InvariantInfo);
- }
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString3"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- [CLSCompliant(false)]
- public static string ToString(SByte value) {
- return value.ToString(null, NumberFormatInfo.InvariantInfo);
- }
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString4"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static string ToString(Int16 value) {
- return value.ToString(null, NumberFormatInfo.InvariantInfo);
- }
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString5"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static string ToString(Int32 value) {
- return value.ToString(null, NumberFormatInfo.InvariantInfo);
- }
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString15"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static string ToString(Int64 value) {
- return value.ToString(null, NumberFormatInfo.InvariantInfo);
- }
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString6"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static string ToString(Byte value) {
- return value.ToString(null, NumberFormatInfo.InvariantInfo);
- }
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString7"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- [CLSCompliant(false)]
- public static string ToString(UInt16 value) {
- return value.ToString(null, NumberFormatInfo.InvariantInfo);
- }
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString8"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- [CLSCompliant(false)]
- public static string ToString(UInt32 value) {
- return value.ToString(null, NumberFormatInfo.InvariantInfo);
- }
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString16"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- [CLSCompliant(false)]
- public static string ToString(UInt64 value) {
- return value.ToString(null, NumberFormatInfo.InvariantInfo);
- }
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString9"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static string ToString(Single value) {
- if (Single.IsNegativeInfinity(value)) return "-INF";
- if (Single.IsPositiveInfinity(value)) return "INF";
- if (IsNegativeZero((double)value)) {
- return("-0");
- }
- return value.ToString("R", NumberFormatInfo.InvariantInfo);
- }
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString10"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static string ToString(Double value) {
- if (Double.IsNegativeInfinity(value)) return "-INF";
- if (Double.IsPositiveInfinity(value)) return "INF";
- if (IsNegativeZero(value)) {
- return("-0");
- }
- return value.ToString("R", NumberFormatInfo.InvariantInfo);
- }
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString11"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static string ToString(TimeSpan value) {
- return new XsdDuration(value).ToString();
- }
- #if !SILVERLIGHT
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString12"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- [Obsolete("Use XmlConvert.ToString() that takes in XmlDateTimeSerializationMode")]
- public static string ToString(DateTime value) {
- return ToString(value, "yyyy-MM-ddTHH:mm:ss.fffffffzzzzzz");
- }
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString13"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static string ToString(DateTime value, string format) {
- return value.ToString(format, DateTimeFormatInfo.InvariantInfo);
- }
- #endif
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString14"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static string ToString(DateTime value, XmlDateTimeSerializationMode dateTimeOption) {
- switch(dateTimeOption) {
- case XmlDateTimeSerializationMode.Local:
- value = SwitchToLocalTime(value);
- break;
- case XmlDateTimeSerializationMode.Utc:
- value = SwitchToUtcTime(value);
- break;
- case XmlDateTimeSerializationMode.Unspecified:
- value = new DateTime(value.Ticks, DateTimeKind.Unspecified);
- break;
- case XmlDateTimeSerializationMode.RoundtripKind:
- break;
-
- default:
- throw new ArgumentException(Res.GetString(Res.Sch_InvalidDateTimeOption, dateTimeOption, "dateTimeOption"));
- }
- XsdDateTime xsdDateTime = new XsdDateTime(value, XsdDateTimeFlags.DateTime);
- return xsdDateTime.ToString();
- }
- public static string ToString(DateTimeOffset value) {
- XsdDateTime xsdDateTime = new XsdDateTime(value);
- return xsdDateTime.ToString();
- }
- public static string ToString(DateTimeOffset value, string format) {
- return value.ToString( format, DateTimeFormatInfo.InvariantInfo );
- }
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString15"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static string ToString(Guid value) {
- return value.ToString();
- }
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToBoolean"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static Boolean ToBoolean (string s) {
- s = TrimString(s);
- if (s == "1" || s == "true" ) return true;
- if (s == "0" || s == "false") return false;
- throw new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Boolean"));
- }
- #if !SILVERLIGHT
- internal static Exception TryToBoolean(string s, out Boolean result) {
- s = TrimString(s);
- if (s == "0" || s == "false") {
- result = false;
- return null;
- }
- else if (s == "1" || s == "true") {
- result = true;
- return null;
- }
- result = false;
- return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Boolean"));
- }
- #endif
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToChar"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static Char ToChar (string s) {
- if (s == null) {
- throw new ArgumentNullException("s");
- }
- if (s.Length != 1) {
- throw new FormatException(Res.GetString(Res.XmlConvert_NotOneCharString));
- }
- return s[0];
- }
- #if !SILVERLIGHT
- internal static Exception TryToChar(string s, out Char result) {
- if (!Char.TryParse(s, out result)) {
- return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Char"));
- }
- return null;
- }
- #endif
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToDecimal"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static Decimal ToDecimal (string s) {
- return Decimal.Parse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowDecimalPoint|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
- }
- #if !SILVERLIGHT
- internal static Exception TryToDecimal(string s, out Decimal result) {
- if (!Decimal.TryParse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowDecimalPoint|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) {
- return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Decimal"));
- }
- return null;
- }
- internal static Decimal ToInteger (string s) {
- return Decimal.Parse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
- }
- internal static Exception TryToInteger(string s, out Decimal result) {
- if (!Decimal.TryParse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) {
- return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Integer"));
- }
- return null;
- }
- #endif
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToSByte"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- [CLSCompliant(false)]
- public static SByte ToSByte (string s) {
- return SByte.Parse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
- }
- #if !SILVERLIGHT
- internal static Exception TryToSByte(string s, out SByte result) {
- if (!SByte.TryParse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) {
- return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "SByte"));
- }
- return null;
- }
- #endif
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToInt16"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static Int16 ToInt16 (string s) {
- return Int16.Parse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
- }
- #if !SILVERLIGHT
- internal static Exception TryToInt16(string s, out Int16 result) {
- if (!Int16.TryParse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) {
- return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Int16"));
- }
- return null;
- }
- #endif
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToInt32"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static Int32 ToInt32 (string s) {
- return Int32.Parse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
- }
- #if !SILVERLIGHT
- internal static Exception TryToInt32(string s, out Int32 result) {
- if (!Int32.TryParse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) {
- return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Int32"));
- }
- return null;
- }
- #endif
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToInt64"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static Int64 ToInt64 (string s) {
- return Int64.Parse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
- }
- #if !SILVERLIGHT
- internal static Exception TryToInt64(string s, out Int64 result) {
- if (!Int64.TryParse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) {
- return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Int64"));
- }
- return null;
- }
- #endif
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToByte"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static Byte ToByte (string s) {
- return Byte.Parse(s, NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
- }
- #if !SILVERLIGHT
- internal static Exception TryToByte(string s, out Byte result) {
- if (!Byte.TryParse(s, NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) {
- return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Byte"));
- }
- return null;
- }
- #endif
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToUInt16"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- [CLSCompliant(false)]
- public static UInt16 ToUInt16 (string s) {
- return UInt16.Parse(s, NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
- }
- #if !SILVERLIGHT
- internal static Exception TryToUInt16(string s, out UInt16 result) {
- if (!UInt16.TryParse(s, NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) {
- return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "UInt16"));
- }
- return null;
- }
- #endif
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToUInt32"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- [CLSCompliant(false)]
- public static UInt32 ToUInt32 (string s) {
- return UInt32.Parse(s, NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
- }
-
- #if !SILVERLIGHT
- internal static Exception TryToUInt32(string s, out UInt32 result) {
- if (!UInt32.TryParse(s, NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) {
- return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "UInt32"));
- }
- return null;
- }
- #endif
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToUInt64"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- [CLSCompliant(false)]
- public static UInt64 ToUInt64 (string s) {
- return UInt64.Parse(s, NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
- }
- #if !SILVERLIGHT
- internal static Exception TryToUInt64(string s, out UInt64 result) {
- if (!UInt64.TryParse(s, NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) {
- return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "UInt64"));
- }
- return null;
- }
- #endif
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToSingle"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static Single ToSingle (string s) {
- s = TrimString(s);
- if(s == "-INF") return Single.NegativeInfinity;
- if(s == "INF") return Single.PositiveInfinity;
- float f = Single.Parse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowDecimalPoint|NumberStyles.AllowExponent, NumberFormatInfo.InvariantInfo);
- if (f == 0 && s[0] == '-') {
- return -0f;
- }
- return f;
- }
- #if !SILVERLIGHT
- internal static Exception TryToSingle(string s, out Single result) {
- s = TrimString(s);
- if (s == "-INF") {
- result = Single.NegativeInfinity;
- return null;
- }
- else if (s == "INF") {
- result = Single.PositiveInfinity;
- return null;
- }
- else if (!Single.TryParse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowDecimalPoint|NumberStyles.AllowExponent, NumberFormatInfo.InvariantInfo, out result)) {
- return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Single"));
- }
- if (result == 0 && s[0] == '-') {
- result = -0f;
- }
- return null;
- }
- #endif
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToDouble"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static Double ToDouble(string s) {
- s = TrimString(s);
- if(s == "-INF") return Double.NegativeInfinity;
- if(s == "INF") return Double.PositiveInfinity;
- double dVal = Double.Parse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowDecimalPoint|NumberStyles.AllowExponent|NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
- if (dVal == 0 && s[0] == '-') {
- return -0d;
- }
- return dVal;
- }
- #if !SILVERLIGHT
- internal static Exception TryToDouble (string s, out double result) {
- s = TrimString(s);
- if (s == "-INF") {
- result = Double.NegativeInfinity;
- return null;
- }
- else if (s == "INF") {
- result = Double.PositiveInfinity;
- return null;
- }
- else if (!Double.TryParse(s, NumberStyles.AllowLeadingSign|NumberStyles.AllowDecimalPoint|NumberStyles.AllowExponent, NumberFormatInfo.InvariantInfo, out result)) {
- return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Double"));
- }
- if (result == 0 && s[0] == '-') {
- result = -0d;
- }
- return null;
- }
- #endif
- #if !SILVERLIGHT
- internal static Double ToXPathDouble (Object o) {
- string str = o as string;
- if (str != null) {
- str = TrimString(str);
- if (str.Length != 0 && str[0] != '+') {
- double d;
- if (Double.TryParse(str, NumberStyles.AllowLeadingSign|NumberStyles.AllowDecimalPoint|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out d)) {
- return d;
- }
- }
- return Double.NaN;
- }
- if (o is double) {
- return (double) o;
- }
- if (o is bool) {
- return ((bool) o) ? 1.0 : 0.0;
- }
- try {
- return Convert.ToDouble(o, NumberFormatInfo.InvariantInfo);
- } catch ( FormatException ) {
- } catch ( OverflowException ) {
- } catch ( ArgumentNullException ) {}
- return Double.NaN;
- }
- internal static String ToXPathString(Object value){
- string s = value as string;
- if ( s != null ) {
- return s;
- }
- else if ( value is double ) {
- return ((double)value).ToString("R", NumberFormatInfo.InvariantInfo);
- }
- else if ( value is bool ) {
- return (bool)value ? "true" : "false";
- }
- else {
- return Convert.ToString(value, NumberFormatInfo.InvariantInfo);
- }
- }
- internal static Double XPathRound(Double value) {
- double temp = Math.Round(value);
- return (value - temp == 0.5) ? temp + 1 : temp;
- }
- #endif
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToTimeSpan"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static TimeSpan ToTimeSpan(string s) {
- XsdDuration duration;
- TimeSpan timeSpan;
- try {
- duration = new XsdDuration(s);
- }
- catch (Exception) {
- // Remap exception for v1 compatibility
- throw new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "TimeSpan"));
- }
- timeSpan = duration.ToTimeSpan();
- return timeSpan;
- }
- #if !SILVERLIGHT
- internal static Exception TryToTimeSpan(string s, out TimeSpan result) {
- XsdDuration duration;
- Exception exception;
- exception = XsdDuration.TryParse(s, out duration);
- if (exception != null) {
- result = TimeSpan.MinValue;
- return exception;
- }
- else {
- return duration.TryToTimeSpan(out result);
- }
- }
- #endif
- #if !SILVERLIGHT
- // use AllDateTimeFormats property to access the formats
- static volatile string[] s_allDateTimeFormats;
- // NOTE: Do not use this property for reference comparison. It may not be unique.
- static string[] AllDateTimeFormats {
- get {
- if ( s_allDateTimeFormats == null ) {
- CreateAllDateTimeFormats();
- }
- return s_allDateTimeFormats;
- }
- }
- static void CreateAllDateTimeFormats() {
- if ( s_allDateTimeFormats == null ) {
- // no locking; the array is immutable so it's not a problem that it may get initialized more than once
- s_allDateTimeFormats = new string[] {
- "yyyy-MM-ddTHH:mm:ss.FFFFFFFzzzzzz", //dateTime
- "yyyy-MM-ddTHH:mm:ss.FFFFFFF",
- "yyyy-MM-ddTHH:mm:ss.FFFFFFFZ",
- "HH:mm:ss.FFFFFFF", //time
- "HH:mm:ss.FFFFFFFZ",
- "HH:mm:ss.FFFFFFFzzzzzz",
- "yyyy-MM-dd", // date
- "yyyy-MM-ddZ",
- "yyyy-MM-ddzzzzzz",
- "yyyy-MM", // yearMonth
- "yyyy-MMZ",
- "yyyy-MMzzzzzz",
- "yyyy", // year
- "yyyyZ",
- "yyyyzzzzzz",
- "--MM-dd", // monthDay
- "--MM-ddZ",
- "--MM-ddzzzzzz",
- "---dd", // day
- "---ddZ",
- "---ddzzzzzz",
- "--MM--", // month
- "--MM--Z",
- "--MM--zzzzzz",
- };
- }
- }
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToDateTime"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- [Obsolete("Use XmlConvert.ToDateTime() that takes in XmlDateTimeSerializationMode")]
- public static DateTime ToDateTime(string s) {
- return ToDateTime(s, AllDateTimeFormats);
- }
- #endif
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToDateTime1"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static DateTime ToDateTime(string s, string format) {
- return DateTime.ParseExact(s, format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite|DateTimeStyles.AllowTrailingWhite);
- }
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToDateTime2"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static DateTime ToDateTime(string s, string[] formats) {
- return DateTime.ParseExact(s, formats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite|DateTimeStyles.AllowTrailingWhite);
- }
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToDateTime3"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static DateTime ToDateTime(string s, XmlDateTimeSerializationMode dateTimeOption) {
- XsdDateTime xsdDateTime = new XsdDateTime(s, XsdDateTimeFlags.AllXsd);
- DateTime dt = (DateTime)xsdDateTime;
- switch (dateTimeOption) {
- case XmlDateTimeSerializationMode.Local:
- dt = SwitchToLocalTime(dt);
- break;
- case XmlDateTimeSerializationMode.Utc:
- dt = SwitchToUtcTime(dt);
- break;
- case XmlDateTimeSerializationMode.Unspecified:
- dt = new DateTime(dt.Ticks, DateTimeKind.Unspecified);
- break;
- case XmlDateTimeSerializationMode.RoundtripKind:
- break;
- default:
- throw new ArgumentException(Res.GetString(Res.Sch_InvalidDateTimeOption, dateTimeOption, "dateTimeOption"));
- }
- return dt;
- }
- public static DateTimeOffset ToDateTimeOffset(string s) {
- if (s == null) {
- throw new ArgumentNullException("s");
- }
- XsdDateTime xsdDateTime = new XsdDateTime(s, XsdDateTimeFlags.AllXsd);
- DateTimeOffset dateTimeOffset = (DateTimeOffset)xsdDateTime;
- return dateTimeOffset;
- }
- public static DateTimeOffset ToDateTimeOffset(string s, string format) {
- if ( s == null ) {
- throw new ArgumentNullException( "s" );
- }
- return DateTimeOffset.ParseExact( s, format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite );
- }
- public static DateTimeOffset ToDateTimeOffset(string s, string[] formats) {
- if ( s == null ) {
- throw new ArgumentNullException( "s" );
- }
- return DateTimeOffset.ParseExact( s, formats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite );
- }
- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToGuid"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public static Guid ToGuid (string s) {
- return new Guid(s);
- }
- #if !SILVERLIGHT
- internal static Exception TryToGuid(string s, out Guid result) {
- Exception exception = null;
- result = Guid.Empty;
- try {
- result = new Guid(s);
- }
- catch (ArgumentException) {
- exception = new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Guid"));
- }
- catch (FormatException) {
- exception = new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Guid"));
- }
- return exception;
- }
- #endif
- private static DateTime SwitchToLocalTime(DateTime value) {
- switch (value.Kind) {
- case DateTimeKind.Local:
- return value;
- case DateTimeKind.Unspecified:
- return new DateTime(value.Ticks, DateTimeKind.Local);
- case DateTimeKind.Utc:
- return value.ToLocalTime();
- }
- return value;
- }
- private static DateTime SwitchToUtcTime(DateTime value) {
- switch (value.Kind) {
- case DateTimeKind.Utc:
- return value;
- case DateTimeKind.Unspecified:
- return new DateTime(value.Ticks, DateTimeKind.Utc);
- case DateTimeKind.Local:
- return value.ToUniversalTime();
- }
- return value;
- }
-
- internal static Uri ToUri(string s) {
- if (s != null && s.Length > 0) { //string.Empty is a valid uri but not " "
- s = TrimString(s);
- if (s.Length == 0 || s.IndexOf("##", StringComparison.Ordinal) != -1) {
- throw new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Uri"));
- }
- }
- Uri uri;
- if (!Uri.TryCreate(s, UriKind.RelativeOrAbsolute, out uri)) {
- throw new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Uri"));
- }
- return uri;
- }
- #if !SILVERLIGHT
- internal static Exception TryToUri(string s, out Uri result) {
- result = null;
- if (s != null && s.Length > 0) { //string.Empty is a valid uri but not " "
- s = TrimString(s);
- if (s.Length == 0 || s.IndexOf("##", StringComparison.Ordinal) != -1) {
- return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Uri"));
- }
- }
- if (!Uri.TryCreate(s, UriKind.RelativeOrAbsolute, out result)) {
- return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Uri"));
- }
- return null;
- }
- #endif
- // Compares the given character interval and string and returns true if the characters are identical
- internal static bool StrEqual( char[] chars, int strPos1, int strLen1, string str2 ) {
- if ( strLen1 != str2.Length ) {
- return false;
- }
- int i = 0;
- while ( i < strLen1 && chars[strPos1+i] == str2[i] ) {
- i++;
- }
- return i == strLen1;
- }
- // XML whitespace characters, <spec>http://www.w3.org/TR/REC-xml#NT-S</spec>
- internal static readonly char[] WhitespaceChars = new char[] { ' ', '\t', '\n', '\r' };
- // Trim a string using XML whitespace characters
- internal static string TrimString(string value) {
- return value.Trim(WhitespaceChars);
- }
- // Trim beginning of a string using XML whitespace characters
- internal static string TrimStringStart(string value) {
- return value.TrimStart(WhitespaceChars);
- }
- // Trim end of a string using XML whitespace characters
- internal static string TrimStringEnd(string value) {
- return value.TrimEnd(WhitespaceChars);
- }
- // Split a string into a whitespace-separated list of tokens
- internal static string[] SplitString(string value) {
- return value.Split(WhitespaceChars, StringSplitOptions.RemoveEmptyEntries);
- }
- internal static string[] SplitString(string value, StringSplitOptions splitStringOptions) {
- return value.Split(WhitespaceChars, splitStringOptions);
- }
- internal static bool IsNegativeZero(double value) {
- // Simple equals function will report that -0 is equal to +0, so compare bits instead
- if (value == 0 && DoubleToInt64Bits(value) == DoubleToInt64Bits(-0e0)) {
- return true;
- }
- return false;
- }
- #if SILVERLIGHT && !SILVERLIGHT_DISABLE_SECURITY
- [System.Security.SecuritySafeCritical]
- #endif
- private static unsafe long DoubleToInt64Bits(double value) {
- // NOTE: BitConverter.DoubleToInt64Bits is missing in Silverlight
- return *((long*)&value);
- }
- internal static void VerifyCharData(string data, ExceptionType exceptionType) {
- VerifyCharData(data, exceptionType, exceptionType);
- }
- #if SILVERLIGHT
- internal static void VerifyCharData( string data, ExceptionType invCharExceptionType, ExceptionType invSurrogateExceptionType ) {
- #else
- internal static unsafe void VerifyCharData( string data, ExceptionType invCharExceptionType, ExceptionType invSurrogateExceptionType ) {
- #endif
- if ( data == null || data.Length == 0 ) {
- return;
- }
- int i = 0;
- int len = data.Length;
- for (;;) {
- #if SILVERLIGHT
- while (i < len && xmlCharType.IsCharData(data[i])) {
- #else
- while ( i < len && ( xmlCharType.charProperties[data[i]] & XmlCharType.fCharData ) != 0 ) {
- #endif
- i++;
- }
- if ( i == len ) {
- return;
- }
- char ch = data[i];
- if ( XmlCharType.IsHighSurrogate( ch ) ) {
- if ( i + 1 == len ) {
- throw CreateException( Res.Xml_InvalidSurrogateMissingLowChar, invSurrogateExceptionType, 0, i + 1 );
- }
- ch = data[i+1];
- if ( XmlCharType.IsLowSurrogate( ch ) ) {
- i += 2;
- continue;
- }
- else {
- throw CreateInvalidSurrogatePairException( data[i+1], data[i], invSurrogateExceptionType, 0, i + 1 );
- }
- }
- throw CreateInvalidCharException( data, i, invCharExceptionType );
- }
- }
- #if SILVERLIGHT
- internal static void VerifyCharData(char[] data, int offset, int len, ExceptionType exceptionType) {
- #else
- internal static unsafe void VerifyCharData( char[] data, int offset, int len, ExceptionType exceptionType ) {
- #endif
- if ( data == null || len == 0 ) {
- return;
- }
- int i = offset;
- int endPos = offset + len;
- for (;;) {
- #if SILVERLIGHT
- while ( i < endPos && xmlCharType.IsCharData(data[i])) {
- #else
- while ( i < endPos && ( xmlCharType.charProperties[data[i]] & XmlCharType.fCharData ) != 0 ) {
- #endif
- i++;
- }
- if ( i == endPos ) {
- return;
- }
- char ch = data[i];
- if ( XmlCharType.IsHighSurrogate( ch ) ) {
- if ( i + 1 == endPos ) {
- throw CreateException(Res.Xml_InvalidSurrogateMissingLowChar, exceptionType, 0, offset - i + 1);
- }
- ch = data[i+1];
- if ( XmlCharType.IsLowSurrogate( ch ) ) {
- i += 2;
- continue;
- }
- else {
- throw CreateInvalidSurrogatePairException(data[i + 1], data[i], exceptionType, 0, offset - i + 1);
- }
- }
- throw CreateInvalidCharException( data, len, i, exceptionType );
- }
- }
- #if !SILVERLIGHT
- internal static string EscapeValueForDebuggerDisplay( string value ) {
- StringBuilder sb = null;
- int i = 0;
- int start = 0;
- while ( i < value.Length ) {
- char ch = value[i];
- if ( (int)ch < 0x20 || ch == '"' ) {
- if ( sb == null ) {
- sb = new StringBuilder( value.Length + 4 );
- }
- if ( i - start > 0 ) {
- sb.Append( value, start, i - start );
- }
- start = i + 1;
- switch ( ch ) {
- case '"':
- sb.Append( "\\\"" );
- break;
- case '\r':
- sb.Append( "\\r" );
- break;
- case '\n':
- sb.Append( "\\n" );
- break;
- case '\t':
- sb.Append( "\\t" );
- break;
- default:
- sb.Append( ch );
- break;
- }
- }
- i++;
- }
- if ( sb == null ) {
- return value;
- }
- if ( i - start > 0 ) {
- sb.Append( value, start, i - start );
- }
- return sb.ToString();
- }
- #endif
- internal static Exception CreateException( string res, ExceptionType exceptionType ) {
- return CreateException( res, exceptionType, 0, 0 );
- }
- internal static Exception CreateException( string res, ExceptionType exceptionType, int lineNo, int linePos ) {
- switch ( exceptionType ) {
- case ExceptionType.ArgumentException:
- return new ArgumentException( Res.GetString( res ) );
- case ExceptionType.XmlException:
- default:
- return new XmlException( res, string.Empty, lineNo, linePos );
- }
- }
- internal static Exception CreateException( string res, string arg, ExceptionType exceptionType ) {
- return CreateException( res, arg, exceptionType, 0, 0 );
- }
- internal static Exception CreateException( string res, string arg, ExceptionType exceptionType, int lineNo, int linePos ) {
- switch ( exceptionType ) {
- case ExceptionType.ArgumentException:
- return new ArgumentException( Res.GetString( res, arg ) );
- case ExceptionType.XmlException:
- default:
- return new XmlException( res, arg, lineNo, linePos );
- }
- }
- internal static Exception CreateException( string res, string[] args, ExceptionType exceptionType ) {
- return CreateException(res, args, exceptionType, 0, 0);
- }
- internal static Exception CreateException(string res, string[] args, ExceptionType exceptionType, int lineNo, int linePos) {
- switch ( exceptionType ) {
- case ExceptionType.ArgumentException:
- return new ArgumentException( Res.GetString( res, args ) );
- case ExceptionType.XmlException:
- default:
- return new XmlException( res, args, lineNo, linePos );
- }
- }
- internal static Exception CreateInvalidSurrogatePairException( char low, char hi ) {
- return CreateInvalidSurrogatePairException( low, hi, ExceptionType.ArgumentException );
- }
- internal static Exception CreateInvalidSurrogatePairException(char low, char hi, ExceptionType exceptionType) {
- return CreateInvalidSurrogatePairException(low, hi, exceptionType, 0, 0);
- }
- internal static Exception CreateInvalidSurrogatePairException( char low, char hi, ExceptionType exceptionType, int lineNo, int linePos ) {
- string[] args = new string[] {
- ((uint)hi).ToString( "X", CultureInfo.InvariantCulture ),
- ((uint)low).ToString( "X", CultureInfo.InvariantCulture )
- } ;
- return CreateException( Res.Xml_InvalidSurrogatePairWithArgs, args, exceptionType, lineNo, linePos );
- }
- internal static Exception CreateInvalidHighSurrogateCharException( char hi ) {
- return CreateInvalidHighSurrogateCharException( hi, ExceptionType.ArgumentException );
- }
- internal static Exception CreateInvalidHighSurrogateCharException( char hi, ExceptionType exceptionType ) {
- return CreateInvalidHighSurrogateCharException( hi, exceptionType, 0, 0);
- }
- internal static Exception CreateInvalidHighSurrogateCharException(char hi, ExceptionType exceptionType, int lineNo, int linePos) {
- return CreateException( Res.Xml_InvalidSurrogateHighChar, ((uint)hi).ToString( "X", CultureInfo.InvariantCulture ), exceptionType, lineNo, linePos );
- }
- internal static Exception CreateInvalidCharException(char[] data, int length, int invCharPos) {
- return CreateInvalidCharException(data, length, invCharPos, ExceptionType.ArgumentException);
- }
- internal static Exception CreateInvalidCharException(char[] data, int length, int invCharPos, ExceptionType exceptionType) {
- return CreateException(Res.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(data, length, invCharPos), exceptionType, 0, invCharPos + 1);
- }
- internal static Exception CreateInvalidCharException( string data, int invCharPos ) {
- return CreateInvalidCharException( data, invCharPos, ExceptionType.ArgumentException );
- }
- internal static Exception CreateInvalidCharException( string data, int invCharPos, ExceptionType exceptionType ) {
- return CreateException(Res.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(data, invCharPos), exceptionType, 0, invCharPos + 1);
- }
- internal static Exception CreateInvalidCharException( char invChar, char nextChar ) {
- return CreateInvalidCharException(invChar, nextChar, ExceptionType.ArgumentException);
- }
- internal static Exception CreateInvalidCharException( char invChar, char nextChar, ExceptionType exceptionType) {
- return CreateException(Res.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(invChar, nextChar), exceptionType);
- }
- internal static Exception CreateInvalidNameCharException(string name, int index, ExceptionType exceptionType) {
- return CreateException(index == 0 ? Res.Xml_BadStartNameChar : Res.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, index), exceptionType, 0, index + 1);
- }
- internal static ArgumentException CreateInvalidNameArgumentException(string name, string argumentName) {
- return ( name == null ) ? new ArgumentNullException( argumentName ) : new ArgumentException( Res.GetString( Res.Xml_EmptyName ), argumentName );
- }
- }
- }
|