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;
40 using System.Security;
42 using Mono.Security.Protocol.Ntlm;
44 namespace Mono.Data.Tds.Protocol
46 public class Tds70 : Tds
50 //public readonly static TdsVersion Version = TdsVersion.tds70;
51 static readonly decimal SMALLMONEY_MIN = -214748.3648m;
52 static readonly decimal SMALLMONEY_MAX = 214748.3647m;
58 [Obsolete ("Use the constructor that receives a lifetime parameter")]
59 public Tds70 (string server, int port)
60 : this (server, port, 512, 15, 0)
64 [Obsolete ("Use the constructor that receives a lifetime parameter")]
65 public Tds70 (string server, int port, int packetSize, int timeout)
66 : this (server, port, packetSize, timeout, 0, TdsVersion.tds70)
70 [Obsolete ("Use the constructor that receives a lifetime parameter")]
71 public Tds70 (string server, int port, int packetSize, int timeout, TdsVersion version)
72 : this (server, port, packetSize, timeout, 0, version)
76 public Tds70 (string server, int port, int lifetime)
77 : this (server, port, 512, 15, lifetime)
81 public Tds70 (string server, int port, int packetSize, int timeout, int lifeTime)
82 : base (server, port, packetSize, timeout, lifeTime, TdsVersion.tds70)
86 public Tds70 (string server, int port, int packetSize, int timeout, int lifeTime, TdsVersion version)
87 : base (server, port, packetSize, timeout, lifeTime, version)
91 #endregion // Constructors
95 protected virtual byte[] ClientVersion {
96 get { return new byte[] {0x00, 0x0, 0x0, 0x70};}
99 // Default precision is 28 for a 7.0 server. Unless and
100 // otherwise the server is started with /p option - which would be 38
101 protected virtual byte Precision {
105 #endregion // Properties
109 protected string BuildExec (string sql)
111 string esql = sql.Replace ("'", "''"); // escape single quote
112 if (Parameters != null && Parameters.Count > 0)
113 return BuildProcedureCall (String.Format ("sp_executesql N'{0}', N'{1}', ", esql, BuildPreparedParameters ()));
115 return BuildProcedureCall (String.Format ("sp_executesql N'{0}'", esql));
118 private string BuildParameters ()
120 if (Parameters == null || Parameters.Count == 0)
123 StringBuilder result = new StringBuilder ();
124 foreach (TdsMetaParameter p in Parameters) {
125 string parameterName = p.ParameterName;
126 if (parameterName [0] == '@') {
127 parameterName = parameterName.Substring (1);
129 if (p.Direction != TdsParameterDirection.ReturnValue) {
130 if (result.Length > 0)
131 result.Append (", ");
132 if (p.Direction == TdsParameterDirection.InputOutput)
133 result.AppendFormat ("@{0}={0} output", parameterName);
135 result.Append (FormatParameter (p));
138 return result.ToString ();
141 private string BuildPreparedParameters ()
143 StringBuilder parms = new StringBuilder ();
144 foreach (TdsMetaParameter p in Parameters) {
145 if (parms.Length > 0)
148 // Set default precision according to the TdsVersion
149 // Current default is 29 for Tds80
150 if (p.TypeName == "decimal")
151 p.Precision = (p.Precision !=0 ? p.Precision : (byte) Precision);
153 parms.Append (p.Prepare ());
154 if (p.Direction == TdsParameterDirection.Output)
155 parms.Append (" output");
157 return parms.ToString ();
160 private string BuildPreparedQuery (string id)
162 return BuildProcedureCall (String.Format ("sp_execute {0},", id));
165 private string BuildProcedureCall (string procedure)
167 string exec = String.Empty;
169 StringBuilder declare = new StringBuilder ();
170 StringBuilder select = new StringBuilder ();
171 StringBuilder set = new StringBuilder ();
174 if (Parameters != null) {
175 foreach (TdsMetaParameter p in Parameters) {
176 string parameterName = p.ParameterName;
177 if (parameterName [0] == '@') {
178 parameterName = parameterName.Substring (1);
181 if (p.Direction != TdsParameterDirection.Input) {
183 select.Append ("select ");
185 select.Append (", ");
186 select.Append ("@" + parameterName);
188 if (p.TypeName == "decimal")
189 p.Precision = (p.Precision !=0 ? p.Precision : (byte) Precision);
191 declare.Append (String.Format ("declare {0}\n", p.Prepare ()));
193 if (p.Direction != TdsParameterDirection.ReturnValue) {
194 if (p.Direction == TdsParameterDirection.InputOutput)
195 set.Append (String.Format ("set {0}\n", FormatParameter(p)));
197 set.Append (String.Format ("set @{0}=NULL\n", parameterName));
202 if (p.Direction == TdsParameterDirection.ReturnValue)
203 exec = "@" + parameterName + "=";
206 exec = "exec " + exec;
208 return String.Format ("{0}{1}{2}{3} {4}\n{5}",
209 declare.ToString (), set.ToString (), exec,
210 procedure, BuildParameters (), select.ToString ());
213 public override bool Connect (TdsConnectionParameters connectionParameters)
216 throw new InvalidOperationException ("The connection is already open.");
218 connectionParms = connectionParameters;
220 SetLanguage (connectionParameters.Language);
221 SetCharset ("utf-8");
223 byte[] empty = new byte[0];
227 byte[] domainMagic = { 6, 0x7d, 0x0f, 0xfd, 0xff, 0x0, 0x0, 0x0,
228 0x0, 0xe0, 0x83, 0x0, 0x0,
229 0x68, 0x01, 0x00, 0x00, 0x09, 0x04, 0x00, 0x00 };
230 byte[] sqlserverMagic = { 6, 0x0, 0x0, 0x0,
232 0x0, 0xe0, 0x03, 0x0,
233 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
237 if (connectionParameters.DomainLogin)
240 magic = sqlserverMagic;
242 string username = connectionParameters.User;
243 string domain = null;
245 int idx = username.IndexOf ("\\");
247 domain = username.Substring (0, idx);
248 username = username.Substring (idx + 1);
250 connectionParameters.DefaultDomain = domain;
251 connectionParameters.User = username;
253 domain = Environment.UserDomainName;
254 connectionParameters.DefaultDomain = domain;
257 short partialPacketSize = (short) (86 + (
258 connectionParameters.Hostname.Length +
259 connectionParameters.ApplicationName.Length +
261 connectionParameters.LibraryName.Length +
263 connectionParameters.Database.Length +
264 connectionParameters.AttachDBFileName.Length) * 2);
266 if (connectionParameters.DomainLogin) {
267 authLen = ((short) (32 + (connectionParameters.Hostname.Length +
269 partialPacketSize += authLen;
271 partialPacketSize += ((short) ((username.Length + connectionParameters.Password.Length) * 2));
273 int totalPacketSize = partialPacketSize;
275 Comm.StartPacket (TdsPacketType.Logon70);
277 Comm.Append (totalPacketSize);
279 //Comm.Append (empty, 3, pad);
280 //byte[] version = {0x00, 0x0, 0x0, 0x71};
281 //Console.WriteLine ("Version: {0}", ClientVersion[3]);
282 Comm.Append (ClientVersion); // TDS Version 7
283 Comm.Append ((int)this.PacketSize); // Set the Block Size
284 Comm.Append (empty, 3, pad);
290 Comm.Append (curPos);
291 Comm.Append ((short) connectionParameters.Hostname.Length);
292 curPos += (short) (connectionParameters.Hostname.Length * 2);
294 if (connectionParameters.DomainLogin) {
295 Comm.Append((short)0);
296 Comm.Append((short)0);
297 Comm.Append((short)0);
298 Comm.Append((short)0);
301 Comm.Append (curPos);
302 Comm.Append ((short) username.Length);
303 curPos += ((short) (username.Length * 2));
306 Comm.Append (curPos);
307 Comm.Append ((short) connectionParameters.Password.Length);
308 curPos += (short) (connectionParameters.Password.Length * 2);
312 Comm.Append (curPos);
313 Comm.Append ((short) connectionParameters.ApplicationName.Length);
314 curPos += (short) (connectionParameters.ApplicationName.Length * 2);
317 Comm.Append (curPos);
318 Comm.Append ((short) DataSource.Length);
319 curPos += (short) (DataSource.Length * 2);
322 Comm.Append ((short) curPos);
323 Comm.Append ((short) 0);
326 Comm.Append (curPos);
327 Comm.Append ((short) connectionParameters.LibraryName.Length);
328 curPos += (short) (connectionParameters.LibraryName.Length * 2);
331 Comm.Append (curPos);
332 Comm.Append ((short) Language.Length);
333 curPos += (short) (Language.Length * 2);
336 Comm.Append (curPos);
337 Comm.Append ((short) connectionParameters.Database.Length);
338 curPos += (short) (connectionParameters.Database.Length * 2);
341 Comm.Append((byte) 0);
342 Comm.Append((byte) 0);
343 Comm.Append((byte) 0);
344 Comm.Append((byte) 0);
345 Comm.Append((byte) 0);
346 Comm.Append((byte) 0);
348 // Authentication Stuff
349 Comm.Append ((short) curPos);
350 if (connectionParameters.DomainLogin) {
351 Comm.Append ((short) authLen);
352 curPos += (short) authLen;
354 Comm.Append ((short) 0);
357 Comm.Append (curPos);
358 Comm.Append ((short)( connectionParameters.AttachDBFileName.Length));
359 curPos += (short)(connectionParameters.AttachDBFileName.Length*2);
361 // Connection Parameters
362 Comm.Append (connectionParameters.Hostname);
363 if (!connectionParameters.DomainLogin) {
364 // SQL Server Authentication
365 Comm.Append (connectionParameters.User);
366 string scrambledPwd = EncryptPassword (connectionParameters.Password);
367 Comm.Append (scrambledPwd);
369 Comm.Append (connectionParameters.ApplicationName);
370 Comm.Append (DataSource);
371 Comm.Append (connectionParameters.LibraryName);
372 Comm.Append (Language);
373 Comm.Append (connectionParameters.Database);
375 if (connectionParameters.DomainLogin) {
376 // the rest of the packet is NTLMSSP authentication
377 Type1Message msg = new Type1Message ();
379 msg.Host = connectionParameters.Hostname;
380 msg.Flags = NtlmFlags.NegotiateUnicode |
381 NtlmFlags.NegotiateNtlm |
382 NtlmFlags.NegotiateDomainSupplied |
383 NtlmFlags.NegotiateWorkstationSupplied |
384 NtlmFlags.NegotiateAlwaysSign; // 0xb201
385 Comm.Append (msg.GetBytes ());
388 Comm.Append (connectionParameters.AttachDBFileName);
396 private static string EncryptPassword (SecureString secPass)
398 int xormask = 0x5a5a;
399 int len = secPass.Length;
400 char[] chars = new char[len];
401 string pass = GetPlainPassword(secPass);
403 for (int i = 0; i < len; ++i) {
404 int c = ((int) (pass[i])) ^ xormask;
405 int m1 = (c >> 4) & 0x0f0f;
406 int m2 = (c << 4) & 0xf0f0;
407 chars[i] = (char) (m1 | m2);
410 return new String (chars);
413 public override bool Reset ()
415 // Check validity of the connection - a false removes
416 // the connection from the pool
417 // NOTE: MS implementation will throw a connection-reset error as it will
418 // try to use the same connection
419 if (!Comm.IsConnected ())
422 // Set "reset-connection" bit for the next message packet
423 Comm.ResetConnection = true;
428 public override void ExecPrepared (string commandText, TdsMetaParameterCollection parameters, int timeout, bool wantResults)
430 Parameters = parameters;
431 ExecuteQuery (BuildPreparedQuery (commandText), timeout, wantResults);
434 public override void ExecProc (string commandText, TdsMetaParameterCollection parameters, int timeout, bool wantResults)
436 Parameters = parameters;
437 ExecRPC (commandText, parameters, timeout, wantResults);
440 private void WriteRpcParameterInfo (TdsMetaParameterCollection parameters)
442 if (parameters != null) {
443 foreach (TdsMetaParameter param in parameters) {
444 if (param.Direction == TdsParameterDirection.ReturnValue)
446 string pname = param.ParameterName;
447 if (pname != null && pname.Length > 0 && pname [0] == '@') {
448 Comm.Append ( (byte) pname.Length);
451 Comm.Append ( (byte) (pname.Length + 1));
452 Comm.Append ("@" + pname);
454 short status = 0; // unused
455 if (param.Direction != TdsParameterDirection.Input)
456 status |= 0x01; // output
457 Comm.Append ( (byte) status);
458 WriteParameterInfo (param);
463 private void WritePreparedParameterInfo (TdsMetaParameterCollection parameters)
465 if (parameters == null)
468 string param = BuildPreparedParameters ();
469 Comm.Append ((byte) 0x00); // no param meta data name
470 Comm.Append ((byte) 0x00); // no status flags
472 // Type_info - parameter info
473 WriteParameterInfo (new TdsMetaParameter ("prep_params",
474 param.Length > 4000 ? "ntext" : "nvarchar",
478 protected void ExecRPC (TdsRpcProcId rpcId, string sql,
479 TdsMetaParameterCollection parameters,
480 int timeout, bool wantResults)
484 Comm.StartPacket (TdsPacketType.RPC);
486 Comm.Append ((ushort) 0xFFFF);
487 Comm.Append ((ushort) rpcId);
488 Comm.Append ((short) 0x02); // no meta data
490 Comm.Append ((byte) 0x00); // no param meta data name
491 Comm.Append ((byte) 0x00); // no status flags
493 // Write sql as a parameter value - UCS2
494 TdsMetaParameter param = new TdsMetaParameter ("sql",
495 sql.Length > 4000 ? "ntext":"nvarchar",
497 WriteParameterInfo (param);
499 // Write Parameter infos - name and type
500 WritePreparedParameterInfo (parameters);
502 // Write parameter/value info
503 WriteRpcParameterInfo (parameters);
505 CheckForData (timeout);
510 protected override void ExecRPC (string rpcName, TdsMetaParameterCollection parameters,
511 int timeout, bool wantResults)
515 Comm.StartPacket (TdsPacketType.RPC);
517 Comm.Append ( (short) rpcName.Length);
518 Comm.Append (rpcName);
519 Comm.Append ( (short) 0); //no meta data
520 WriteRpcParameterInfo (parameters);
522 CheckForData (timeout);
527 private void WriteParameterInfo (TdsMetaParameter param)
530 Ms.net send non-nullable datatypes as nullable and allows setting null values
531 to int/float etc.. So, using Nullable form of type for all data
533 param.IsNullable = true;
534 TdsColumnType colType = param.GetMetaType ();
535 param.IsNullable = false;
537 bool partLenType = false;
538 int size = param.Size;
542 size = param.GetActualSize ();
546 * If the value is null, not setting the size to 0 will cause varchar
547 * fields to get inserted as an empty string rather than an null.
549 if (param.Value == null || param.Value == DBNull.Value)
552 // Change colType according to the following table
554 * Original Type Maxlen New Type
556 * NVarChar 4000 UCS2 NText
557 * BigVarChar 8000 ASCII Text
558 * BigVarBinary 8000 bytes Image
561 TdsColumnType origColType = colType;
562 if (colType == TdsColumnType.BigNVarChar) {
563 // param.GetActualSize() returns len*2
564 if (size == param.Size)
566 if ((size >> 1) > 4000)
567 colType = TdsColumnType.NText;
568 } else if (colType == TdsColumnType.BigVarChar) {
570 colType = TdsColumnType.Text;
571 } else if (colType == TdsColumnType.BigVarBinary) {
573 colType = TdsColumnType.Image;
575 // Calculation of TypeInfo field
577 * orig size value TypeInfo field
579 * >= 0 <= Maxlen origColType + content len
580 * > Maxlen NewType as per above table + content len
581 * -1 origColType + USHORTMAXLEN (0xFFFF) + content len (TDS 9)
584 // Write updated colType, iff partLenType == false
585 if (TdsVersion > TdsVersion.tds81 && partLenType) {
586 Comm.Append ((byte)origColType);
587 Comm.Append ((short)-1);
588 } else if (ServerTdsVersion > TdsVersion.tds70
589 && origColType == TdsColumnType.Decimal) {
590 Comm.Append ((byte)TdsColumnType.Numeric);
592 Comm.Append ((byte)colType);
595 if (IsLargeType (colType))
596 Comm.Append ((short)size); // Parameter size passed in SqlParameter
597 else if (IsBlobType (colType))
598 Comm.Append (size); // Parameter size passed in SqlParameter
600 Comm.Append ((byte)size);
602 // Precision and Scale are non-zero for only decimal/numeric
603 if ( param.TypeName == "decimal" || param.TypeName == "numeric") {
604 Comm.Append ((param.Precision !=0 ) ? param.Precision : Precision);
605 Comm.Append (param.Scale);
606 // Convert the decimal value according to Scale
607 if (param.Value != null && param.Value != DBNull.Value &&
608 ((decimal)param.Value) != Decimal.MaxValue &&
609 ((decimal)param.Value) != Decimal.MinValue &&
610 ((decimal)param.Value) != long.MaxValue &&
611 ((decimal)param.Value) != long.MinValue &&
612 ((decimal)param.Value) != ulong.MaxValue &&
613 ((decimal)param.Value) != ulong.MinValue) {
614 long expo = (long)new Decimal (System.Math.Pow (10, (double)param.Scale));
615 long pVal = (long)(((decimal)param.Value) * expo);
621 /* VARADHAN: TDS 8 Debugging */
623 if (Collation != null) {
624 Console.WriteLine ("Collation is not null");
625 Console.WriteLine ("Column Type: {0}", colType);
626 Console.WriteLine ("Collation bytes: {0} {1} {2} {3} {4}", Collation[0], Collation[1], Collation[2],
627 Collation[3], Collation[4]);
629 Console.WriteLine ("Collation is null");
633 // Tds > 7.0 uses collation
634 if (Collation != null &&
635 (colType == TdsColumnType.BigChar || colType == TdsColumnType.BigNVarChar ||
636 colType == TdsColumnType.BigVarChar || colType == TdsColumnType.NChar ||
637 colType == TdsColumnType.NVarChar || colType == TdsColumnType.Text ||
638 colType == TdsColumnType.NText))
639 Comm.Append (Collation);
641 // LAMESPEC: size should be 0xFFFF for any bigvarchar, bignvarchar and bigvarbinary
642 // types if param value is NULL
643 if ((colType == TdsColumnType.BigVarChar ||
644 colType == TdsColumnType.BigNVarChar ||
645 colType == TdsColumnType.BigVarBinary ||
646 colType == TdsColumnType.Image) &&
647 (param.Value == null || param.Value == DBNull.Value))
650 size = param.GetActualSize ();
652 if (IsLargeType (colType))
653 Comm.Append ((short)size);
654 else if (IsBlobType (colType))
657 Comm.Append ((byte)size);
660 switch (param.TypeName) {
662 // 4 == SqlMoney::MoneyFormat.NumberDecimalDigits
663 Decimal val = Decimal.Round ((decimal) param.Value, 4);
664 int[] arr = Decimal.GetBits (val);
667 Comm.Append (arr[1]);
668 Comm.Append (arr[0]);
670 Comm.Append (~arr[1]);
671 Comm.Append (~arr[0] + 1);
676 // 4 == SqlMoney::MoneyFormat.NumberDecimalDigits
677 Decimal val = Decimal.Round ((decimal) param.Value, 4);
678 if (val < SMALLMONEY_MIN || val > SMALLMONEY_MAX)
679 throw new OverflowException (string.Format (
680 CultureInfo.InvariantCulture,
681 "Value '{0}' is not valid for SmallMoney."
682 + " Must be between {1:N4} and {2:N4}.",
686 val.ToString (CultureInfo.CurrentCulture),
688 SMALLMONEY_MIN, SMALLMONEY_MAX));
690 int[] arr = Decimal.GetBits (val);
691 int sign = (val>0 ? 1: -1);
692 Comm.Append (sign * arr[0]);
696 Comm.Append ((DateTime)param.Value, 8);
698 case "smalldatetime":
699 Comm.Append ((DateTime)param.Value, 4);
707 byte [] tmp = param.GetBytes ();
710 case "uniqueidentifier" :
711 Comm.Append (((Guid)param.Value).ToByteArray());
714 Comm.Append (param.Value);
721 public override void Execute (string commandText, TdsMetaParameterCollection parameters, int timeout, bool wantResults)
723 Parameters = parameters;
724 string sql = commandText;
725 if (wantResults || (Parameters != null && Parameters.Count > 0))
726 sql = BuildExec (commandText);
727 ExecuteQuery (sql, timeout, wantResults);
730 private string FormatParameter (TdsMetaParameter parameter)
732 string parameterName = parameter.ParameterName;
733 if (parameterName [0] == '@') {
734 parameterName = parameterName.Substring (1);
736 if (parameter.Direction == TdsParameterDirection.Output)
737 return String.Format ("@{0}=@{0} output", parameterName);
738 if (parameter.Value == null || parameter.Value == DBNull.Value)
739 return String.Format ("@{0}=NULL", parameterName);
742 switch (parameter.TypeName) {
743 case "smalldatetime":
745 DateTime d = Convert.ToDateTime (parameter.Value);
746 value = String.Format (base.Locale,
747 "'{0:MMM dd yyyy hh:mm:ss.fff tt}'", d);
758 object paramValue = parameter.Value;
759 Type paramType = paramValue.GetType ();
760 if (paramType.IsEnum)
761 paramValue = Convert.ChangeType (paramValue,
762 Type.GetTypeCode (paramType));
763 value = paramValue.ToString ();
767 value = String.Format ("N'{0}'", parameter.Value.ToString ().Replace ("'", "''"));
769 case "uniqueidentifier":
770 value = String.Format ("'{0}'", ((Guid) parameter.Value).ToString (string.Empty));
773 if (parameter.Value.GetType () == typeof (bool))
774 value = (((bool) parameter.Value) ? "0x1" : "0x0");
776 value = parameter.Value.ToString ();
781 byte[] byteArray = (byte[]) parameter.Value;
782 // In 1.0 profile, BitConverter.ToString() throws ArgumentOutOfRangeException when passed a 0-length
783 // array, so handle that as a special case.
784 if (byteArray.Length == 0)
787 value = String.Format ("0x{0}", BitConverter.ToString (byteArray).Replace ("-", string.Empty).ToLower ());
790 value = String.Format ("'{0}'", parameter.Value.ToString ().Replace ("'", "''"));
794 return "@" + parameterName + "=" + value;
797 public override string Prepare (string commandText, TdsMetaParameterCollection parameters)
799 Parameters = parameters;
801 TdsMetaParameterCollection parms = new TdsMetaParameterCollection ();
802 // Tested with MS SQL 2008 RC2 Express and MS SQL 2012 Express:
803 // You may pass either -1 or 0, but not null as initial value of @Handle,
804 // which is an output parameter.
805 TdsMetaParameter parm = new TdsMetaParameter ("@Handle", "int", -1);
806 parm.Direction = TdsParameterDirection.Output;
809 parms.Add (new TdsMetaParameter ("@VarDecl", "nvarchar", BuildPreparedParameters ()));
810 parms.Add (new TdsMetaParameter ("@Query", "nvarchar", commandText));
812 ExecProc ("sp_prepare", parms, 0, true);
814 return OutputParameters[0].ToString () ;
815 //if (ColumnValues == null || ColumnValues [0] == null || ColumnValues [0] == DBNull.Value)
816 // throw new TdsInternalException ();
817 //return string.Empty;
818 //return ColumnValues [0].ToString ();
821 protected override void ProcessColumnInfo ()
823 int numColumns = Comm.GetTdsShort ();
824 for (int i = 0; i < numColumns; i += 1) {
825 byte[] flagData = new byte[4];
826 for (int j = 0; j < 4; j += 1)
827 flagData[j] = Comm.GetByte ();
829 bool nullable = (flagData[2] & 0x01) > 0;
830 //bool caseSensitive = (flagData[2] & 0x02) > 0;
831 bool writable = (flagData[2] & 0x0c) > 0;
832 bool autoIncrement = (flagData[2] & 0x10) > 0;
833 bool isIdentity = (flagData[2] & 0x10) > 0;
835 TdsColumnType columnType = (TdsColumnType) ((Comm.GetByte () & 0xff));
837 byte xColumnType = 0;
838 if (IsLargeType (columnType)) {
839 xColumnType = (byte) columnType;
840 if (columnType != TdsColumnType.NChar)
845 string tableName = null;
847 if (IsBlobType (columnType)) {
848 columnSize = Comm.GetTdsInt ();
849 tableName = Comm.GetString (Comm.GetTdsShort ());
850 } else if (IsFixedSizeColumn (columnType)) {
851 columnSize = LookupBufferSize (columnType);
852 } else if (IsLargeType ((TdsColumnType) xColumnType)) {
853 columnSize = Comm.GetTdsShort ();
855 columnSize = Comm.GetByte () & 0xff;
858 if (IsWideType ((TdsColumnType) columnType))
864 if (columnType == TdsColumnType.Decimal || columnType == TdsColumnType.Numeric) {
865 precision = Comm.GetByte ();
866 scale = Comm.GetByte ();
868 precision = GetPrecision (columnType, columnSize);
869 scale = GetScale (columnType, columnSize);
872 string columnName = Comm.GetString (Comm.GetByte ());
874 TdsDataColumn col = new TdsDataColumn ();
877 col.ColumnType = columnType;
878 col.ColumnName = columnName;
879 col.IsAutoIncrement = autoIncrement;
880 col.IsIdentity = isIdentity;
881 col.ColumnSize = columnSize;
882 col.NumericPrecision = precision;
883 col.NumericScale = scale;
884 col.IsReadOnly = !writable;
885 col.AllowDBNull = nullable;
886 col.BaseTableName = tableName;
887 col.DataTypeName = Enum.GetName (typeof (TdsColumnType), xColumnType);
889 col ["ColumnType"] = columnType;
890 col ["ColumnName"] = columnName;
891 col ["IsAutoIncrement"] = autoIncrement;
892 col ["IsIdentity"] = isIdentity;
893 col ["ColumnSize"] = columnSize;
894 col ["NumericPrecision"] = precision;
895 col ["NumericScale"] = scale;
896 col ["IsReadOnly"] = !writable;
897 col ["AllowDBNull"] = nullable;
898 col ["BaseTableName"] = tableName;
899 col ["DataTypeName"] = Enum.GetName (typeof (TdsColumnType), xColumnType);
904 public override void Unprepare (string statementId)
906 TdsMetaParameterCollection parms = new TdsMetaParameterCollection ();
907 parms.Add (new TdsMetaParameter ("@P1", "int", Int32.Parse (statementId)));
908 ExecProc ("sp_unprepare", parms, 0, false);
911 protected override bool IsValidRowCount (byte status, byte op)
913 if ((status & (byte)0x10) == 0 || op == (byte)0xc1)
918 protected override void ProcessReturnStatus ()
920 int result = Comm.GetTdsInt ();
921 if (Parameters != null) {
922 foreach (TdsMetaParameter param in Parameters) {
923 if (param.Direction == TdsParameterDirection.ReturnValue) {
924 param.Value = result;
931 byte GetScale (TdsColumnType type, int columnSize)
934 case TdsColumnType.DateTime:
936 case TdsColumnType.DateTime4:
938 case TdsColumnType.DateTimeN:
939 switch (columnSize) {
950 throw new NotSupportedException (string.Format (
951 CultureInfo.InvariantCulture,
952 "Fixed scale not defined for column " +
953 "type '{0}' with size {1}.", type, columnSize));
956 byte GetPrecision (TdsColumnType type, int columnSize)
959 case TdsColumnType.Binary:
961 case TdsColumnType.Bit:
963 case TdsColumnType.Char:
965 case TdsColumnType.DateTime:
967 case TdsColumnType.DateTime4:
969 case TdsColumnType.DateTimeN:
970 switch (columnSize) {
977 case TdsColumnType.Real:
979 case TdsColumnType.Float8:
981 case TdsColumnType.FloatN:
982 switch (columnSize) {
989 case TdsColumnType.Image:
991 case TdsColumnType.Int1:
993 case TdsColumnType.Int2:
995 case TdsColumnType.Int4:
997 case TdsColumnType.IntN:
998 switch (columnSize) {
1007 case TdsColumnType.Void:
1009 case TdsColumnType.Text:
1011 case TdsColumnType.UniqueIdentifier:
1013 case TdsColumnType.VarBinary:
1015 case TdsColumnType.VarChar:
1017 case TdsColumnType.Money:
1019 case TdsColumnType.NText:
1021 case TdsColumnType.NVarChar:
1023 case TdsColumnType.BitN:
1025 case TdsColumnType.MoneyN:
1026 switch (columnSize) {
1033 case TdsColumnType.Money4:
1035 case TdsColumnType.NChar:
1037 case TdsColumnType.BigBinary:
1039 case TdsColumnType.BigVarBinary:
1041 case TdsColumnType.BigVarChar:
1043 case TdsColumnType.BigNVarChar:
1045 case TdsColumnType.BigChar:
1047 case TdsColumnType.SmallMoney:
1049 case TdsColumnType.Variant:
1051 case TdsColumnType.BigInt:
1055 throw new NotSupportedException (string.Format (
1056 CultureInfo.InvariantCulture,
1057 "Fixed precision not defined for column " +
1058 "type '{0}' with size {1}.", type, columnSize));
1061 #endregion // Methods
1064 #region Asynchronous Methods
1066 public override IAsyncResult BeginExecuteNonQuery (string cmdText,
1067 TdsMetaParameterCollection parameters,
1068 AsyncCallback callback,
1071 Parameters = parameters;
1072 string sql = cmdText;
1073 if (Parameters != null && Parameters.Count > 0)
1074 sql = BuildExec (cmdText);
1076 IAsyncResult ar = BeginExecuteQueryInternal (sql, false, callback, state);
1080 public override void EndExecuteNonQuery (IAsyncResult ar)
1082 EndExecuteQueryInternal (ar);
1085 public override IAsyncResult BeginExecuteQuery (string cmdText,
1086 TdsMetaParameterCollection parameters,
1087 AsyncCallback callback,
1090 Parameters = parameters;
1091 string sql = cmdText;
1092 if (Parameters != null && Parameters.Count > 0)
1093 sql = BuildExec (cmdText);
1095 IAsyncResult ar = BeginExecuteQueryInternal (sql, true, callback, state);
1099 public override void EndExecuteQuery (IAsyncResult ar)
1101 EndExecuteQueryInternal (ar);
1104 public override IAsyncResult BeginExecuteProcedure (string prolog,
1108 TdsMetaParameterCollection parameters,
1109 AsyncCallback callback,
1112 Parameters = parameters;
1113 string pcall = BuildProcedureCall (cmdText);
1114 string sql = String.Format ("{0};{1};{2};", prolog, pcall, epilog);
1116 IAsyncResult ar = BeginExecuteQueryInternal (sql, !IsNonQuery, callback, state);
1120 public override void EndExecuteProcedure (IAsyncResult ar)
1122 EndExecuteQueryInternal (ar);
1125 #endregion // Asynchronous Methods