2 // Mono.Data.Tds.Protocol.Tds70.cs
5 // Tim Coleman (tim@timcoleman.com)
6 // Diego Caravana (diego@toth.it)
7 // Sebastien Pouliot (sebastien@ximian.com)
8 // Daniel Morgan (danielmorgan@verizon.net)
9 // Gert Driesen (drieseng@users.sourceforge.net)
10 // Veerapuram Varadhan (vvaradhan@novell.com)
12 // Copyright (C) 2002 Tim Coleman
13 // Portions (C) 2003 Motus Technologies Inc. (http://www.motus.com)
14 // Portions (C) 2003 Daniel Morgan
17 // Permission is hereby granted, free of charge, to any person obtaining
18 // a copy of this software and associated documentation files (the
19 // "Software"), to deal in the Software without restriction, including
20 // without limitation the rights to use, copy, modify, merge, publish,
21 // distribute, sublicense, and/or sell copies of the Software, and to
22 // permit persons to whom the Software is furnished to do so, subject to
23 // the following conditions:
25 // The above copyright notice and this permission notice shall be
26 // included in all copies or substantial portions of the Software.
28 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
29 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
30 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
31 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
32 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
33 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
34 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
38 using System.Globalization;
41 using Mono.Security.Protocol.Ntlm;
43 namespace Mono.Data.Tds.Protocol
45 public class Tds70 : Tds
49 //public readonly static TdsVersion Version = TdsVersion.tds70;
50 static readonly decimal SMALLMONEY_MIN = -214748.3648m;
51 static readonly decimal SMALLMONEY_MAX = 214748.3647m;
57 public Tds70 (string server, int port)
58 : this (server, port, 512, 15)
62 public Tds70 (string server, int port, int packetSize, int timeout)
63 : base (server, port, packetSize, timeout, TdsVersion.tds70)
67 public Tds70 (string server, int port, int packetSize, int timeout, TdsVersion version)
68 : base (server, port, packetSize, timeout, version)
72 #endregion // Constructors
76 protected virtual byte[] ClientVersion {
77 get { return new byte[] {0x00, 0x0, 0x0, 0x70};}
80 // Default precision is 28 for a 7.0 server. Unless and
81 // otherwise the server is started with /p option - which would be 38
82 protected virtual byte Precision {
86 #endregion // Properties
90 protected string BuildExec (string sql)
92 string esql = sql.Replace ("'", "''"); // escape single quote
93 if (Parameters != null && Parameters.Count > 0)
94 return BuildProcedureCall (String.Format ("sp_executesql N'{0}', N'{1}', ", esql, BuildPreparedParameters ()));
96 return BuildProcedureCall (String.Format ("sp_executesql N'{0}'", esql));
99 private string BuildParameters ()
101 if (Parameters == null || Parameters.Count == 0)
104 StringBuilder result = new StringBuilder ();
105 foreach (TdsMetaParameter p in Parameters) {
106 string parameterName = p.ParameterName;
107 if (parameterName [0] == '@') {
108 parameterName = parameterName.Substring (1);
110 if (p.Direction != TdsParameterDirection.ReturnValue) {
111 if (result.Length > 0)
112 result.Append (", ");
113 if (p.Direction == TdsParameterDirection.InputOutput)
114 result.AppendFormat ("@{0}={0} output", parameterName);
116 result.Append (FormatParameter (p));
119 return result.ToString ();
122 private string BuildPreparedParameters ()
124 StringBuilder parms = new StringBuilder ();
125 foreach (TdsMetaParameter p in Parameters) {
126 if (parms.Length > 0)
129 // Set default precision according to the TdsVersion
130 // Current default is 29 for Tds80
131 if (p.TypeName == "decimal")
132 p.Precision = (p.Precision !=0 ? p.Precision : (byte) Precision);
134 parms.Append (p.Prepare ());
135 if (p.Direction == TdsParameterDirection.Output)
136 parms.Append (" output");
138 return parms.ToString ();
141 private string BuildPreparedQuery (string id)
143 return BuildProcedureCall (String.Format ("sp_execute {0},", id));
146 private string BuildProcedureCall (string procedure)
148 string exec = String.Empty;
150 StringBuilder declare = new StringBuilder ();
151 StringBuilder select = new StringBuilder ();
152 StringBuilder set = new StringBuilder ();
155 if (Parameters != null) {
156 foreach (TdsMetaParameter p in Parameters) {
157 string parameterName = p.ParameterName;
158 if (parameterName [0] == '@') {
159 parameterName = parameterName.Substring (1);
162 if (p.Direction != TdsParameterDirection.Input) {
164 select.Append ("select ");
166 select.Append (", ");
167 select.Append ("@" + parameterName);
169 if (p.TypeName == "decimal")
170 p.Precision = (p.Precision !=0 ? p.Precision : (byte) Precision);
172 declare.Append (String.Format ("declare {0}\n", p.Prepare ()));
174 if (p.Direction != TdsParameterDirection.ReturnValue) {
175 if (p.Direction == TdsParameterDirection.InputOutput)
176 set.Append (String.Format ("set {0}\n", FormatParameter(p)));
178 set.Append (String.Format ("set @{0}=NULL\n", parameterName));
183 if (p.Direction == TdsParameterDirection.ReturnValue)
184 exec = "@" + parameterName + "=";
187 exec = "exec " + exec;
189 return String.Format ("{0}{1}{2}{3} {4}\n{5}",
190 declare.ToString (), set.ToString (), exec,
191 procedure, BuildParameters (), select.ToString ());
194 public override bool Connect (TdsConnectionParameters connectionParameters)
197 throw new InvalidOperationException ("The connection is already open.");
199 connectionParms = connectionParameters;
201 SetLanguage (connectionParameters.Language);
202 SetCharset ("utf-8");
204 byte[] empty = new byte[0];
208 byte[] domainMagic = { 6, 0x7d, 0x0f, 0xfd, 0xff, 0x0, 0x0, 0x0,
209 0x0, 0xe0, 0x83, 0x0, 0x0,
210 0x68, 0x01, 0x00, 0x00, 0x09, 0x04, 0x00, 0x00 };
211 byte[] sqlserverMagic = { 6, 0x0, 0x0, 0x0,
213 0x0, 0xe0, 0x03, 0x0,
214 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
218 if (connectionParameters.DomainLogin)
221 magic = sqlserverMagic;
223 string username = connectionParameters.User;
224 string domain = null;
226 int idx = username.IndexOf ("\\");
228 domain = username.Substring (0, idx);
229 username = username.Substring (idx + 1);
231 connectionParameters.DefaultDomain = domain;
232 connectionParameters.User = username;
234 domain = Environment.UserDomainName;
235 connectionParameters.DefaultDomain = domain;
238 short partialPacketSize = (short) (86 + (
239 connectionParameters.Hostname.Length +
240 connectionParameters.ApplicationName.Length +
242 connectionParameters.LibraryName.Length +
244 connectionParameters.Database.Length +
245 connectionParameters.AttachDBFileName.Length) * 2);
247 if (connectionParameters.DomainLogin) {
248 authLen = ((short) (32 + (connectionParameters.Hostname.Length +
250 partialPacketSize += authLen;
252 partialPacketSize += ((short) ((username.Length + connectionParameters.Password.Length) * 2));
254 int totalPacketSize = partialPacketSize;
256 Comm.StartPacket (TdsPacketType.Logon70);
258 Comm.Append (totalPacketSize);
260 //Comm.Append (empty, 3, pad);
261 //byte[] version = {0x00, 0x0, 0x0, 0x71};
262 //Console.WriteLine ("Version: {0}", ClientVersion[3]);
263 Comm.Append (ClientVersion); // TDS Version 7
264 Comm.Append ((int)this.PacketSize); // Set the Block Size
265 Comm.Append (empty, 3, pad);
271 Comm.Append (curPos);
272 Comm.Append ((short) connectionParameters.Hostname.Length);
273 curPos += (short) (connectionParameters.Hostname.Length * 2);
275 if (connectionParameters.DomainLogin) {
276 Comm.Append((short)0);
277 Comm.Append((short)0);
278 Comm.Append((short)0);
279 Comm.Append((short)0);
282 Comm.Append (curPos);
283 Comm.Append ((short) username.Length);
284 curPos += ((short) (username.Length * 2));
287 Comm.Append (curPos);
288 Comm.Append ((short) connectionParameters.Password.Length);
289 curPos += (short) (connectionParameters.Password.Length * 2);
293 Comm.Append (curPos);
294 Comm.Append ((short) connectionParameters.ApplicationName.Length);
295 curPos += (short) (connectionParameters.ApplicationName.Length * 2);
298 Comm.Append (curPos);
299 Comm.Append ((short) DataSource.Length);
300 curPos += (short) (DataSource.Length * 2);
303 Comm.Append ((short) curPos);
304 Comm.Append ((short) 0);
307 Comm.Append (curPos);
308 Comm.Append ((short) connectionParameters.LibraryName.Length);
309 curPos += (short) (connectionParameters.LibraryName.Length * 2);
312 Comm.Append (curPos);
313 Comm.Append ((short) Language.Length);
314 curPos += (short) (Language.Length * 2);
317 Comm.Append (curPos);
318 Comm.Append ((short) connectionParameters.Database.Length);
319 curPos += (short) (connectionParameters.Database.Length * 2);
322 Comm.Append((byte) 0);
323 Comm.Append((byte) 0);
324 Comm.Append((byte) 0);
325 Comm.Append((byte) 0);
326 Comm.Append((byte) 0);
327 Comm.Append((byte) 0);
329 // Authentication Stuff
330 Comm.Append ((short) curPos);
331 if (connectionParameters.DomainLogin) {
332 Comm.Append ((short) authLen);
333 curPos += (short) authLen;
335 Comm.Append ((short) 0);
338 Comm.Append (curPos);
339 Comm.Append ((short)( connectionParameters.AttachDBFileName.Length));
340 curPos += (short)(connectionParameters.AttachDBFileName.Length*2);
342 // Connection Parameters
343 Comm.Append (connectionParameters.Hostname);
344 if (!connectionParameters.DomainLogin) {
345 // SQL Server Authentication
346 Comm.Append (connectionParameters.User);
347 string scrambledPwd = EncryptPassword (connectionParameters.Password);
348 Comm.Append (scrambledPwd);
350 Comm.Append (connectionParameters.ApplicationName);
351 Comm.Append (DataSource);
352 Comm.Append (connectionParameters.LibraryName);
353 Comm.Append (Language);
354 Comm.Append (connectionParameters.Database);
356 if (connectionParameters.DomainLogin) {
357 // the rest of the packet is NTLMSSP authentication
358 Type1Message msg = new Type1Message ();
360 msg.Host = connectionParameters.Hostname;
361 msg.Flags = NtlmFlags.NegotiateUnicode |
362 NtlmFlags.NegotiateNtlm |
363 NtlmFlags.NegotiateDomainSupplied |
364 NtlmFlags.NegotiateWorkstationSupplied |
365 NtlmFlags.NegotiateAlwaysSign; // 0xb201
366 Comm.Append (msg.GetBytes ());
369 Comm.Append (connectionParameters.AttachDBFileName);
377 private static string EncryptPassword (string pass)
379 int xormask = 0x5a5a;
380 int len = pass.Length;
381 char[] chars = new char[len];
383 for (int i = 0; i < len; ++i) {
384 int c = ((int) (pass[i])) ^ xormask;
385 int m1 = (c >> 4) & 0x0f0f;
386 int m2 = (c << 4) & 0xf0f0;
387 chars[i] = (char) (m1 | m2);
390 return new String (chars);
393 public override bool Reset ()
395 // Check validity of the connection - a false removes
396 // the connection from the pool
397 // NOTE: MS implementation will throw a connection-reset error as it will
398 // try to use the same connection
399 if (!Comm.IsConnected ())
402 // Set "reset-connection" bit for the next message packet
403 Comm.ResetConnection = true;
408 public override void ExecPrepared (string commandText, TdsMetaParameterCollection parameters, int timeout, bool wantResults)
410 Parameters = parameters;
411 ExecuteQuery (BuildPreparedQuery (commandText), timeout, wantResults);
414 public override void ExecProc (string commandText, TdsMetaParameterCollection parameters, int timeout, bool wantResults)
416 Parameters = parameters;
417 ExecRPC (commandText, parameters, timeout, wantResults);
420 private void WriteRpcParameterInfo (TdsMetaParameterCollection parameters)
422 if (parameters != null) {
423 foreach (TdsMetaParameter param in parameters) {
424 if (param.Direction == TdsParameterDirection.ReturnValue)
426 string pname = param.ParameterName;
427 if (pname != null && pname.Length > 0 && pname [0] == '@') {
428 Comm.Append ( (byte) pname.Length);
431 Comm.Append ( (byte) (pname.Length + 1));
432 Comm.Append ("@" + pname);
434 short status = 0; // unused
435 if (param.Direction != TdsParameterDirection.Input)
436 status |= 0x01; // output
437 Comm.Append ( (byte) status);
438 WriteParameterInfo (param);
443 private void WritePreparedParameterInfo (TdsMetaParameterCollection parameters)
445 if (parameters == null)
448 string param = BuildPreparedParameters ();
449 Comm.Append ((byte) 0x00); // no param meta data name
450 Comm.Append ((byte) 0x00); // no status flags
452 // Type_info - parameter info
453 WriteParameterInfo (new TdsMetaParameter ("prep_params",
454 param.Length > 4000 ? "ntext" : "nvarchar",
458 protected void ExecRPC (TdsRpcProcId rpcId, string sql,
459 TdsMetaParameterCollection parameters,
460 int timeout, bool wantResults)
464 Comm.StartPacket (TdsPacketType.RPC);
466 Comm.Append ((ushort) 0xFFFF);
467 Comm.Append ((ushort) rpcId);
468 Comm.Append ((short) 0x02); // no meta data
470 Comm.Append ((byte) 0x00); // no param meta data name
471 Comm.Append ((byte) 0x00); // no status flags
473 // Write sql as a parameter value - UCS2
474 TdsMetaParameter param = new TdsMetaParameter ("sql",
475 sql.Length > 4000 ? "ntext":"nvarchar",
477 WriteParameterInfo (param);
479 // Write Parameter infos - name and type
480 WritePreparedParameterInfo (parameters);
482 // Write parameter/value info
483 WriteRpcParameterInfo (parameters);
485 CheckForData (timeout);
490 protected override void ExecRPC (string rpcName, TdsMetaParameterCollection parameters,
491 int timeout, bool wantResults)
495 Comm.StartPacket (TdsPacketType.RPC);
497 Comm.Append ( (short) rpcName.Length);
498 Comm.Append (rpcName);
499 Comm.Append ( (short) 0); //no meta data
500 WriteRpcParameterInfo (parameters);
502 CheckForData (timeout);
507 private void WriteParameterInfo (TdsMetaParameter param)
510 Ms.net send non-nullable datatypes as nullable and allows setting null values
511 to int/float etc.. So, using Nullable form of type for all data
513 param.IsNullable = true;
514 TdsColumnType colType = param.GetMetaType ();
515 param.IsNullable = false;
517 bool partLenType = false;
518 int size = param.Size;
522 size = param.GetActualSize ();
526 * If the value is null, not setting the size to 0 will cause varchar
527 * fields to get inserted as an empty string rather than an null.
529 if (param.Value == null || param.Value == DBNull.Value)
532 // Change colType according to the following table
534 * Original Type Maxlen New Type
536 * NVarChar 4000 UCS2 NText
537 * BigVarChar 8000 ASCII Text
538 * BigVarBinary 8000 bytes Image
541 TdsColumnType origColType = colType;
542 if (colType == TdsColumnType.BigNVarChar) {
543 // param.GetActualSize() returns len*2
544 if (size == param.Size)
546 if ((size >> 1) > 4000)
547 colType = TdsColumnType.NText;
548 } else if (colType == TdsColumnType.BigVarChar) {
550 colType = TdsColumnType.Text;
551 } else if (colType == TdsColumnType.BigVarBinary) {
553 colType = TdsColumnType.Image;
555 // Calculation of TypeInfo field
557 * orig size value TypeInfo field
559 * >= 0 <= Maxlen origColType + content len
560 * > Maxlen NewType as per above table + content len
561 * -1 origColType + USHORTMAXLEN (0xFFFF) + content len (TDS 9)
564 // Write updated colType, iff partLenType == false
565 if (TdsVersion > TdsVersion.tds81 && partLenType) {
566 Comm.Append ((byte)origColType);
567 Comm.Append ((short)-1);
568 } else if (ServerTdsVersion > TdsVersion.tds70
569 && origColType == TdsColumnType.Decimal) {
570 Comm.Append ((byte)TdsColumnType.Numeric);
572 Comm.Append ((byte)colType);
575 if (IsLargeType (colType))
576 Comm.Append ((short)size); // Parameter size passed in SqlParameter
577 else if (IsBlobType (colType))
578 Comm.Append (size); // Parameter size passed in SqlParameter
580 Comm.Append ((byte)size);
582 // Precision and Scale are non-zero for only decimal/numeric
583 if ( param.TypeName == "decimal" || param.TypeName == "numeric") {
584 Comm.Append ((param.Precision !=0 ) ? param.Precision : Precision);
585 Comm.Append (param.Scale);
586 // Convert the decimal value according to Scale
587 if (param.Value != null && param.Value != DBNull.Value &&
588 ((decimal)param.Value) != Decimal.MaxValue &&
589 ((decimal)param.Value) != Decimal.MinValue &&
590 ((decimal)param.Value) != long.MaxValue &&
591 ((decimal)param.Value) != long.MinValue &&
592 ((decimal)param.Value) != ulong.MaxValue &&
593 ((decimal)param.Value) != ulong.MinValue) {
594 long expo = (long)new Decimal (System.Math.Pow (10, (double)param.Scale));
595 long pVal = (long)(((decimal)param.Value) * expo);
601 /* VARADHAN: TDS 8 Debugging */
603 if (Collation != null) {
604 Console.WriteLine ("Collation is not null");
605 Console.WriteLine ("Column Type: {0}", colType);
606 Console.WriteLine ("Collation bytes: {0} {1} {2} {3} {4}", Collation[0], Collation[1], Collation[2],
607 Collation[3], Collation[4]);
609 Console.WriteLine ("Collation is null");
613 // Tds > 7.0 uses collation
614 if (Collation != null &&
615 (colType == TdsColumnType.BigChar || colType == TdsColumnType.BigNVarChar ||
616 colType == TdsColumnType.BigVarChar || colType == TdsColumnType.NChar ||
617 colType == TdsColumnType.NVarChar || colType == TdsColumnType.Text ||
618 colType == TdsColumnType.NText))
619 Comm.Append (Collation);
621 // LAMESPEC: size should be 0xFFFF for any bigvarchar, bignvarchar and bigvarbinary
622 // types if param value is NULL
623 if ((colType == TdsColumnType.BigVarChar ||
624 colType == TdsColumnType.BigNVarChar ||
625 colType == TdsColumnType.BigVarBinary ||
626 colType == TdsColumnType.Image) &&
627 (param.Value == null || param.Value == DBNull.Value))
630 size = param.GetActualSize ();
632 if (IsLargeType (colType))
633 Comm.Append ((short)size);
634 else if (IsBlobType (colType))
637 Comm.Append ((byte)size);
640 switch (param.TypeName) {
642 // 4 == SqlMoney::MoneyFormat.NumberDecimalDigits
643 Decimal val = Decimal.Round ((decimal) param.Value, 4);
644 int[] arr = Decimal.GetBits (val);
647 Comm.Append (arr[1]);
648 Comm.Append (arr[0]);
650 Comm.Append (~arr[1]);
651 Comm.Append (~arr[0] + 1);
656 // 4 == SqlMoney::MoneyFormat.NumberDecimalDigits
657 Decimal val = Decimal.Round ((decimal) param.Value, 4);
658 if (val < SMALLMONEY_MIN || val > SMALLMONEY_MAX)
659 throw new OverflowException (string.Format (
660 CultureInfo.InvariantCulture,
661 "Value '{0}' is not valid for SmallMoney."
662 + " Must be between {1:N4} and {2:N4}.",
666 val.ToString (CultureInfo.CurrentCulture),
668 SMALLMONEY_MIN, SMALLMONEY_MAX));
670 int[] arr = Decimal.GetBits (val);
671 int sign = (val>0 ? 1: -1);
672 Comm.Append (sign * arr[0]);
676 Comm.Append ((DateTime)param.Value, 8);
678 case "smalldatetime":
679 Comm.Append ((DateTime)param.Value, 4);
687 byte [] tmp = param.GetBytes ();
690 case "uniqueidentifier" :
691 Comm.Append (((Guid)param.Value).ToByteArray());
694 Comm.Append (param.Value);
701 public override void Execute (string commandText, TdsMetaParameterCollection parameters, int timeout, bool wantResults)
703 Parameters = parameters;
704 string sql = commandText;
705 if (wantResults || (Parameters != null && Parameters.Count > 0))
706 sql = BuildExec (commandText);
707 ExecuteQuery (sql, timeout, wantResults);
710 private string FormatParameter (TdsMetaParameter parameter)
712 string parameterName = parameter.ParameterName;
713 if (parameterName [0] == '@') {
714 parameterName = parameterName.Substring (1);
716 if (parameter.Direction == TdsParameterDirection.Output)
717 return String.Format ("@{0}=@{0} output", parameterName);
718 if (parameter.Value == null || parameter.Value == DBNull.Value)
719 return String.Format ("@{0}=NULL", parameterName);
722 switch (parameter.TypeName) {
723 case "smalldatetime":
725 DateTime d = Convert.ToDateTime (parameter.Value);
726 value = String.Format (base.Locale,
727 "'{0:MMM dd yyyy hh:mm:ss.fff tt}'", d);
738 object paramValue = parameter.Value;
739 Type paramType = paramValue.GetType ();
740 if (paramType.IsEnum)
741 paramValue = Convert.ChangeType (paramValue,
742 Type.GetTypeCode (paramType));
743 value = paramValue.ToString ();
747 value = String.Format ("N'{0}'", parameter.Value.ToString ().Replace ("'", "''"));
749 case "uniqueidentifier":
750 value = String.Format ("'{0}'", ((Guid) parameter.Value).ToString (string.Empty));
753 if (parameter.Value.GetType () == typeof (bool))
754 value = (((bool) parameter.Value) ? "0x1" : "0x0");
756 value = parameter.Value.ToString ();
761 byte[] byteArray = (byte[]) parameter.Value;
762 // In 1.0 profile, BitConverter.ToString() throws ArgumentOutOfRangeException when passed a 0-length
763 // array, so handle that as a special case.
764 if (byteArray.Length == 0)
767 value = String.Format ("0x{0}", BitConverter.ToString (byteArray).Replace ("-", string.Empty).ToLower ());
770 value = String.Format ("'{0}'", parameter.Value.ToString ().Replace ("'", "''"));
774 return "@" + parameterName + "=" + value;
777 public override string Prepare (string commandText, TdsMetaParameterCollection parameters)
779 Parameters = parameters;
781 TdsMetaParameterCollection parms = new TdsMetaParameterCollection ();
782 // Tested with MS SQL 2008 RC2 Express and MS SQL 2012 Express:
783 // You may pass either -1 or 0, but not null as initial value of @Handle,
784 // which is an output parameter.
785 TdsMetaParameter parm = new TdsMetaParameter ("@Handle", "int", -1);
786 parm.Direction = TdsParameterDirection.Output;
789 parms.Add (new TdsMetaParameter ("@VarDecl", "nvarchar", BuildPreparedParameters ()));
790 parms.Add (new TdsMetaParameter ("@Query", "nvarchar", commandText));
792 ExecProc ("sp_prepare", parms, 0, true);
794 return OutputParameters[0].ToString () ;
795 //if (ColumnValues == null || ColumnValues [0] == null || ColumnValues [0] == DBNull.Value)
796 // throw new TdsInternalException ();
797 //return string.Empty;
798 //return ColumnValues [0].ToString ();
801 protected override void ProcessColumnInfo ()
803 int numColumns = Comm.GetTdsShort ();
804 for (int i = 0; i < numColumns; i += 1) {
805 byte[] flagData = new byte[4];
806 for (int j = 0; j < 4; j += 1)
807 flagData[j] = Comm.GetByte ();
809 bool nullable = (flagData[2] & 0x01) > 0;
810 //bool caseSensitive = (flagData[2] & 0x02) > 0;
811 bool writable = (flagData[2] & 0x0c) > 0;
812 bool autoIncrement = (flagData[2] & 0x10) > 0;
813 bool isIdentity = (flagData[2] & 0x10) > 0;
815 TdsColumnType columnType = (TdsColumnType) ((Comm.GetByte () & 0xff));
817 byte xColumnType = 0;
818 if (IsLargeType (columnType)) {
819 xColumnType = (byte) columnType;
820 if (columnType != TdsColumnType.NChar)
825 string tableName = null;
827 if (IsBlobType (columnType)) {
828 columnSize = Comm.GetTdsInt ();
829 tableName = Comm.GetString (Comm.GetTdsShort ());
830 } else if (IsFixedSizeColumn (columnType)) {
831 columnSize = LookupBufferSize (columnType);
832 } else if (IsLargeType ((TdsColumnType) xColumnType)) {
833 columnSize = Comm.GetTdsShort ();
835 columnSize = Comm.GetByte () & 0xff;
838 if (IsWideType ((TdsColumnType) columnType))
844 if (columnType == TdsColumnType.Decimal || columnType == TdsColumnType.Numeric) {
845 precision = Comm.GetByte ();
846 scale = Comm.GetByte ();
848 precision = GetPrecision (columnType, columnSize);
849 scale = GetScale (columnType, columnSize);
852 string columnName = Comm.GetString (Comm.GetByte ());
854 TdsDataColumn col = new TdsDataColumn ();
857 col.ColumnType = columnType;
858 col.ColumnName = columnName;
859 col.IsAutoIncrement = autoIncrement;
860 col.IsIdentity = isIdentity;
861 col.ColumnSize = columnSize;
862 col.NumericPrecision = precision;
863 col.NumericScale = scale;
864 col.IsReadOnly = !writable;
865 col.AllowDBNull = nullable;
866 col.BaseTableName = tableName;
867 col.DataTypeName = Enum.GetName (typeof (TdsColumnType), xColumnType);
869 col ["ColumnType"] = columnType;
870 col ["ColumnName"] = columnName;
871 col ["IsAutoIncrement"] = autoIncrement;
872 col ["IsIdentity"] = isIdentity;
873 col ["ColumnSize"] = columnSize;
874 col ["NumericPrecision"] = precision;
875 col ["NumericScale"] = scale;
876 col ["IsReadOnly"] = !writable;
877 col ["AllowDBNull"] = nullable;
878 col ["BaseTableName"] = tableName;
879 col ["DataTypeName"] = Enum.GetName (typeof (TdsColumnType), xColumnType);
884 public override void Unprepare (string statementId)
886 TdsMetaParameterCollection parms = new TdsMetaParameterCollection ();
887 parms.Add (new TdsMetaParameter ("@P1", "int", Int32.Parse (statementId)));
888 ExecProc ("sp_unprepare", parms, 0, false);
891 protected override bool IsValidRowCount (byte status, byte op)
893 if ((status & (byte)0x10) == 0 || op == (byte)0xc1)
898 protected override void ProcessReturnStatus ()
900 int result = Comm.GetTdsInt ();
901 if (Parameters != null) {
902 foreach (TdsMetaParameter param in Parameters) {
903 if (param.Direction == TdsParameterDirection.ReturnValue) {
904 param.Value = result;
911 byte GetScale (TdsColumnType type, int columnSize)
914 case TdsColumnType.DateTime:
916 case TdsColumnType.DateTime4:
918 case TdsColumnType.DateTimeN:
919 switch (columnSize) {
930 throw new NotSupportedException (string.Format (
931 CultureInfo.InvariantCulture,
932 "Fixed scale not defined for column " +
933 "type '{0}' with size {1}.", type, columnSize));
936 byte GetPrecision (TdsColumnType type, int columnSize)
939 case TdsColumnType.Binary:
941 case TdsColumnType.Bit:
943 case TdsColumnType.Char:
945 case TdsColumnType.DateTime:
947 case TdsColumnType.DateTime4:
949 case TdsColumnType.DateTimeN:
950 switch (columnSize) {
957 case TdsColumnType.Real:
959 case TdsColumnType.Float8:
961 case TdsColumnType.FloatN:
962 switch (columnSize) {
969 case TdsColumnType.Image:
971 case TdsColumnType.Int1:
973 case TdsColumnType.Int2:
975 case TdsColumnType.Int4:
977 case TdsColumnType.IntN:
978 switch (columnSize) {
987 case TdsColumnType.Void:
989 case TdsColumnType.Text:
991 case TdsColumnType.UniqueIdentifier:
993 case TdsColumnType.VarBinary:
995 case TdsColumnType.VarChar:
997 case TdsColumnType.Money:
999 case TdsColumnType.NText:
1001 case TdsColumnType.NVarChar:
1003 case TdsColumnType.BitN:
1005 case TdsColumnType.MoneyN:
1006 switch (columnSize) {
1013 case TdsColumnType.Money4:
1015 case TdsColumnType.NChar:
1017 case TdsColumnType.BigBinary:
1019 case TdsColumnType.BigVarBinary:
1021 case TdsColumnType.BigVarChar:
1023 case TdsColumnType.BigNVarChar:
1025 case TdsColumnType.BigChar:
1027 case TdsColumnType.SmallMoney:
1029 case TdsColumnType.Variant:
1031 case TdsColumnType.BigInt:
1035 throw new NotSupportedException (string.Format (
1036 CultureInfo.InvariantCulture,
1037 "Fixed precision not defined for column " +
1038 "type '{0}' with size {1}.", type, columnSize));
1041 #endregion // Methods
1044 #region Asynchronous Methods
1046 public override IAsyncResult BeginExecuteNonQuery (string cmdText,
1047 TdsMetaParameterCollection parameters,
1048 AsyncCallback callback,
1051 Parameters = parameters;
1052 string sql = cmdText;
1053 if (Parameters != null && Parameters.Count > 0)
1054 sql = BuildExec (cmdText);
1056 IAsyncResult ar = BeginExecuteQueryInternal (sql, false, callback, state);
1060 public override void EndExecuteNonQuery (IAsyncResult ar)
1062 EndExecuteQueryInternal (ar);
1065 public override IAsyncResult BeginExecuteQuery (string cmdText,
1066 TdsMetaParameterCollection parameters,
1067 AsyncCallback callback,
1070 Parameters = parameters;
1071 string sql = cmdText;
1072 if (Parameters != null && Parameters.Count > 0)
1073 sql = BuildExec (cmdText);
1075 IAsyncResult ar = BeginExecuteQueryInternal (sql, true, callback, state);
1079 public override void EndExecuteQuery (IAsyncResult ar)
1081 EndExecuteQueryInternal (ar);
1084 public override IAsyncResult BeginExecuteProcedure (string prolog,
1088 TdsMetaParameterCollection parameters,
1089 AsyncCallback callback,
1092 Parameters = parameters;
1093 string pcall = BuildProcedureCall (cmdText);
1094 string sql = String.Format ("{0};{1};{2};", prolog, pcall, epilog);
1096 IAsyncResult ar = BeginExecuteQueryInternal (sql, !IsNonQuery, callback, state);
1100 public override void EndExecuteProcedure (IAsyncResult ar)
1102 EndExecuteQueryInternal (ar);
1105 #endregion // Asynchronous Methods