1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
|
//
// Mono.Data.Tds.Protocol.Tds.cs
//
// Author:
// Tim Coleman (tim@timcoleman.com)
// Sebastien Pouliot (spouliot@motus.com)
// Daniel Morgan (danielmorgan@verizon.net)
//
// Copyright (C) 2002 Tim Coleman
// Portions (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Portions (C) 2003 Daniel Morgan
//
using Mono.Security.Protocol.Ntlm;
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Net.Sockets;
using System.Text;
namespace Mono.Data.Tds.Protocol {
public abstract class Tds : Component, ITds
{
#region Fields
TdsComm comm;
TdsVersion tdsVersion;
protected internal TdsConnectionParameters connectionParms;
protected readonly byte[] NTLMSSP_ID = new byte[] {0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00};
int packetSize;
string dataSource;
string database;
string databaseProductName;
string databaseProductVersion;
int databaseMajorVersion;
string charset;
string language;
bool connected = false;
bool moreResults;
Encoding encoder;
// bool autoCommit;
bool doneProc;
TdsDataRow currentRow = null;
TdsDataColumnCollection columns;
ArrayList tableNames;
ArrayList columnNames;
TdsMetaParameterCollection parameters;
bool queryInProgress;
int cancelsRequested;
int cancelsProcessed;
// bool isDone;
// bool isDoneInProc;
ArrayList outputParameters = new ArrayList ();
protected TdsInternalErrorCollection messages = new TdsInternalErrorCollection ();
int recordsAffected = 0;
#endregion // Fields
#region Properties
protected string Charset {
get { return charset; }
}
public bool DoneProc {
get { return doneProc; }
}
protected string Language {
get { return language; }
}
protected ArrayList ColumnNames {
get { return columnNames; }
}
public TdsDataRow ColumnValues {
get { return currentRow; }
}
internal TdsComm Comm {
get { return comm; }
}
public string Database {
get { return database; }
}
public string DataSource {
get { return dataSource; }
}
public bool IsConnected {
get { return connected; }
set { connected = value; }
}
public bool MoreResults {
get { return moreResults; }
set { moreResults = value; }
}
public int PacketSize {
get { return packetSize; }
}
public int RecordsAffected {
get { return recordsAffected; }
set { recordsAffected = value; }
}
public string ServerVersion {
get { return databaseProductVersion; }
}
public TdsDataColumnCollection Columns {
get { return columns; }
}
public TdsVersion TdsVersion {
get { return tdsVersion; }
}
public ArrayList OutputParameters {
get { return outputParameters; }
set { outputParameters = value; }
}
protected TdsMetaParameterCollection Parameters {
get { return parameters; }
set { parameters = value; }
}
#endregion // Properties
#region Events
public event TdsInternalErrorMessageEventHandler TdsErrorMessage;
public event TdsInternalInfoMessageEventHandler TdsInfoMessage;
#endregion // Events
#region Constructors
public Tds (string dataSource, int port, int packetSize, int timeout, TdsVersion tdsVersion)
{
this.tdsVersion = tdsVersion;
this.packetSize = packetSize;
this.dataSource = dataSource;
comm = new TdsComm (dataSource, port, packetSize, timeout, tdsVersion);
}
#endregion // Constructors
#region Public Methods
public void Cancel ()
{
if (queryInProgress) {
if (cancelsRequested == cancelsProcessed) {
comm.StartPacket (TdsPacketType.Cancel);
comm.SendPacket ();
cancelsRequested += 1;
}
}
}
public abstract bool Connect (TdsConnectionParameters connectionParameters);
public static TdsTimeoutException CreateTimeoutException (string dataSource, string method)
{
string message = "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.";
return new TdsTimeoutException (0, 0, message, -2, method, dataSource, "Mono TdsClient Data Provider", 0);
}
public void Disconnect ()
{
comm.StartPacket (TdsPacketType.Logoff);
comm.Append ((byte) 0);
comm.SendPacket ();
comm.Close ();
connected = false;
}
public virtual bool Reset ()
{
return true;
}
public void Execute (string sql)
{
Execute (sql, null, 0, false);
}
public void ExecProc (string sql)
{
ExecProc (sql, null, 0, false);
}
public virtual void Execute (string sql, TdsMetaParameterCollection parameters, int timeout, bool wantResults)
{
ExecuteQuery (sql, timeout, wantResults);
}
public virtual void ExecProc (string sql, TdsMetaParameterCollection parameters, int timeout, bool wantResults)
{
ExecuteQuery (String.Format ("exec {0}", sql), timeout, wantResults);
}
public virtual void ExecPrepared (string sql, TdsMetaParameterCollection parameters, int timeout, bool wantResults)
{
throw new NotSupportedException ();
}
protected void ExecuteQuery (string sql, int timeout, bool wantResults)
{
moreResults = true;
doneProc = false;
messages.Clear ();
outputParameters.Clear ();
Comm.StartPacket (TdsPacketType.Query);
Comm.Append (sql);
Comm.SendPacket ();
CheckForData (timeout);
if (!wantResults)
SkipToEnd ();
}
public bool NextResult ()
{
if (!moreResults)
return false;
TdsPacketSubType subType;
bool done = false;
bool outputParams = false;
while (!done) {
subType = ProcessSubPacket ();
if (outputParams) {
moreResults = false;
break;
}
switch (subType) {
case TdsPacketSubType.ColumnInfo:
case TdsPacketSubType.ColumnMetadata:
case TdsPacketSubType.RowFormat:
byte peek = Comm.Peek ();
done = (peek != (byte) TdsPacketSubType.TableName);
if (done && doneProc && peek == (byte) TdsPacketSubType.Row) {
outputParams = true;
done = false;
}
break;
case TdsPacketSubType.TableName:
done = true;
break;
default:
done = !moreResults;
break;
}
}
return moreResults;
}
public bool NextRow ()
{
TdsPacketSubType subType;
bool done = false;
bool result = false;
do {
subType = ProcessSubPacket ();
switch (subType) {
case TdsPacketSubType.Row:
result = true;
done = true;
break;
case TdsPacketSubType.Done:
case TdsPacketSubType.DoneProc:
case TdsPacketSubType.DoneInProc:
result = false;
done = true;
break;
}
} while (!done);
return result;
}
public virtual string Prepare (string sql, TdsMetaParameterCollection parameters)
{
throw new NotSupportedException ();
}
public void SkipToEnd ()
{
while (NextResult ()) { /* DO NOTHING */ }
}
public virtual void Unprepare (string statementId)
{
throw new NotSupportedException ();
}
#endregion // Public Methods
#region // Private Methods
[MonoTODO ("Is cancel enough, or do we need to drop the connection?")]
protected void CheckForData (int timeout)
{
if (timeout > 0 && !comm.Poll (timeout, SelectMode.SelectRead)) {
Cancel ();
throw CreateTimeoutException (dataSource, "CheckForData()");
}
}
protected TdsInternalInfoMessageEventArgs CreateTdsInfoMessageEvent (TdsInternalErrorCollection errors)
{
return new TdsInternalInfoMessageEventArgs (errors);
}
protected TdsInternalErrorMessageEventArgs CreateTdsErrorMessageEvent (byte theClass, int lineNumber, string message, int number, string procedure, string server, string source, byte state)
{
return new TdsInternalErrorMessageEventArgs (new TdsInternalError (theClass, lineNumber, message, number, procedure, server, source, state));
}
private object GetColumnValue (TdsColumnType colType, bool outParam)
{
return GetColumnValue (colType, outParam, -1);
}
private object GetColumnValue (TdsColumnType colType, bool outParam, int ordinal)
{
int len;
object element = null;
switch (colType) {
case TdsColumnType.IntN :
if (outParam)
comm.Skip (1);
element = GetIntValue (colType);
break;
case TdsColumnType.Int1 :
case TdsColumnType.Int2 :
case TdsColumnType.Int4 :
element = GetIntValue (colType);
break;
case TdsColumnType.Image :
if (outParam)
comm.Skip (1);
element = GetImageValue ();
break;
case TdsColumnType.Text :
if (outParam)
comm.Skip (1);
element = GetTextValue (false);
break;
case TdsColumnType.NText :
if (outParam)
comm.Skip (1);
element = GetTextValue (true);
break;
case TdsColumnType.Char :
case TdsColumnType.VarChar :
if (outParam)
comm.Skip (1);
element = GetStringValue (false, false);
break;
case TdsColumnType.BigVarBinary :
comm.GetTdsShort ();
len = comm.GetTdsShort ();
element = comm.GetBytes (len, true);
break;
case TdsColumnType.BigVarChar :
comm.Skip (2);
element = GetStringValue (false, false);
break;
case TdsColumnType.NChar :
case TdsColumnType.NVarChar :
if (outParam)
comm.Skip (1);
element = GetStringValue (true, false);
break;
case TdsColumnType.Real :
case TdsColumnType.Float8 :
element = GetFloatValue (colType);
break;
case TdsColumnType.FloatN :
if (outParam)
comm.Skip (1);
element = GetFloatValue (colType);
break;
case TdsColumnType.SmallMoney :
case TdsColumnType.Money :
element = GetMoneyValue (colType);
break;
case TdsColumnType.MoneyN :
if (outParam)
comm.Skip (1);
element = GetMoneyValue (colType);
break;
case TdsColumnType.Numeric :
case TdsColumnType.Decimal :
byte precision;
byte scale;
if (outParam) {
comm.Skip (1);
precision = comm.GetByte ();
scale = comm.GetByte ();
}
else {
precision = (byte) columns[ordinal]["NumericPrecision"];
scale = (byte) columns[ordinal]["NumericScale"];
}
element = GetDecimalValue (precision, scale);
break;
case TdsColumnType.DateTimeN :
if (outParam)
comm.Skip (1);
element = GetDateTimeValue (colType);
break;
case TdsColumnType.DateTime4 :
case TdsColumnType.DateTime :
element = GetDateTimeValue (colType);
break;
case TdsColumnType.VarBinary :
case TdsColumnType.Binary :
if (outParam)
comm.Skip (1);
element = GetBinaryValue ();
break;
case TdsColumnType.BitN :
if (outParam)
comm.Skip (1);
if (comm.GetByte () == 0)
element = DBNull.Value;
else
element = (comm.GetByte() != 0);
break;
case TdsColumnType.Bit :
int columnSize = comm.GetByte ();
element = (columnSize != 0);
break;
case TdsColumnType.UniqueIdentifier :
if (comm.Peek () != 16) // If it's null, then what to do?
break;
len = comm.GetByte () & 0xff;
if (len > 0) {
byte[] guidBytes = comm.GetBytes (len, true);
element = new Guid (guidBytes);
}
break;
default :
return DBNull.Value;
}
return element;
}
private object GetBinaryValue ()
{
int len;
object result = DBNull.Value;
if (tdsVersion == TdsVersion.tds70) {
len = comm.GetTdsShort ();
if (len != 0xffff && len > 0)
result = comm.GetBytes (len, true);
}
else {
len = (comm.GetByte () & 0xff);
if (len != 0)
result = comm.GetBytes (len, true);
}
return result;
}
private object GetDateTimeValue (TdsColumnType type)
{
int len = 0;
object result;
switch (type) {
case TdsColumnType.DateTime4:
len = 4;
break;
case TdsColumnType.DateTime:
len = 8;
break;
case TdsColumnType.DateTimeN:
byte tmp = comm.Peek ();
if (tmp != 0 && tmp != 4 && tmp != 8)
break;
len = comm.GetByte ();
break;
}
DateTime epoch = new DateTime (1900, 1, 1);
switch (len) {
case 8 :
result = epoch.AddDays (comm.GetTdsInt ());
int seconds = comm.GetTdsInt ();
long millis = ((((long) seconds) % 300L) * 1000L) / 300L;
if (seconds != 0 || millis != 0) {
result = ((DateTime) result).AddSeconds (seconds / 300);
result = ((DateTime) result).AddMilliseconds (millis);
}
break;
case 4 :
result = epoch.AddDays ((int) comm.GetTdsShort ());
short minutes = comm.GetTdsShort ();
if (minutes != 0)
result = ((DateTime) result).AddMinutes ((int) minutes);
break;
default:
result = DBNull.Value;
break;
}
return result;
}
private object GetDecimalValue (byte precision, byte scale)
{
int[] bits = new int[4] {0,0,0,0};
int len = (comm.GetByte() & 0xff) - 1;
if (len < 0)
return DBNull.Value;
bool positive = (comm.GetByte () == 1);
if (len > 16)
throw new OverflowException ();
for (int i = 0, index = 0; i < len && i < 16; i += 4, index += 1)
bits[index] = comm.GetTdsInt ();
if (bits [3] != 0)
return new TdsBigDecimal (precision, scale, !positive, bits);
else
return new Decimal (bits[0], bits[1], bits[2], !positive, scale);
}
private object GetFloatValue (TdsColumnType columnType)
{
int columnSize = 0;
switch (columnType) {
case TdsColumnType.Real:
columnSize = 4;
break;
case TdsColumnType.Float8:
columnSize = 8;
break;
case TdsColumnType.FloatN:
columnSize = comm.GetByte ();
break;
}
switch (columnSize) {
case 8 :
return BitConverter.Int64BitsToDouble (comm.GetTdsInt64 ());
case 4 :
return BitConverter.ToSingle (BitConverter.GetBytes (comm.GetTdsInt ()), 0);
default :
return DBNull.Value;
}
}
private object GetImageValue ()
{
byte hasValue = comm.GetByte ();
if (hasValue == 0)
return DBNull.Value;
comm.Skip (24);
int len = comm.GetTdsInt ();
if (len < 0)
return DBNull.Value;
return (comm.GetBytes (len, true));
}
private object GetIntValue (TdsColumnType type)
{
int len;
switch (type) {
case TdsColumnType.IntN :
len = comm.GetByte ();
break;
case TdsColumnType.Int4 :
len = 4;
break;
case TdsColumnType.Int2 :
len = 2;
break;
case TdsColumnType.Int1 :
len = 1;
break;
default:
return DBNull.Value;
}
switch (len) {
case 4 :
return (comm.GetTdsInt ());
case 2 :
return (comm.GetTdsShort ());
case 1 :
return (comm.GetByte ());
default:
return DBNull.Value;
}
}
[MonoTODO]
private object GetMoneyValue (TdsColumnType type)
{
int len;
object result = null;
switch (type) {
case TdsColumnType.SmallMoney :
case TdsColumnType.Money4 :
len = 4;
break;
case TdsColumnType.Money :
len = 8;
break;
case TdsColumnType.MoneyN :
len = comm.GetByte ();
break;
default:
return DBNull.Value;
}
long rawValue = 0;
switch (len) {
case 4:
rawValue = comm.GetTdsInt ();
break;
case 8:
byte[] bits = new byte[8];
bits[4] = comm.GetByte ();
bits[5] = comm.GetByte ();
bits[6] = comm.GetByte ();
bits[7] = comm.GetByte ();
bits[0] = comm.GetByte ();
bits[1] = comm.GetByte ();
bits[2] = comm.GetByte ();
bits[3] = comm.GetByte ();
rawValue = BitConverter.ToInt64 (bits, 0);
break;
default:
return DBNull.Value;
}
result = new Decimal (rawValue);
return (((decimal) result) / 10000);
}
private object GetStringValue (bool wideChars, bool outputParam)
{
bool shortLen = (tdsVersion == TdsVersion.tds70) && (wideChars || !outputParam);
int len = shortLen ? comm.GetTdsShort () : (comm.GetByte () & 0xff);
if (tdsVersion < TdsVersion.tds70 && len == 0)
return DBNull.Value;
else if (len >= 0) {
object result;
if (wideChars)
result = comm.GetString (len / 2);
else
result = comm.GetString (len, false);
if (tdsVersion < TdsVersion.tds70 && ((string) result).Equals (" "))
result = "";
return result;
}
else
return DBNull.Value;
}
protected int GetSubPacketLength ()
{
return comm.GetTdsShort ();
}
private object GetTextValue (bool wideChars)
{
string result = null;
byte hasValue = comm.GetByte ();
if (hasValue != 16)
return DBNull.Value;
// 16 Byte TEXTPTR, 8 Byte TIMESTAMP
comm.Skip (24);
int len = comm.GetTdsInt ();
if (len == 0)
return DBNull.Value;
if (wideChars)
result = comm.GetString (len / 2);
else
result = comm.GetString (len, false);
len /= 2;
if ((byte) tdsVersion < (byte) TdsVersion.tds70 && result == " ")
result = "";
return result;
}
internal static bool IsFixedSizeColumn (TdsColumnType columnType)
{
switch (columnType) {
case TdsColumnType.Int1 :
case TdsColumnType.Int2 :
case TdsColumnType.Int4 :
case TdsColumnType.Float8 :
case TdsColumnType.DateTime :
case TdsColumnType.Bit :
case TdsColumnType.Money :
case TdsColumnType.Money4 :
case TdsColumnType.SmallMoney :
case TdsColumnType.Real :
case TdsColumnType.DateTime4 :
return true;
case TdsColumnType.IntN :
case TdsColumnType.MoneyN :
case TdsColumnType.VarChar :
case TdsColumnType.NVarChar :
case TdsColumnType.DateTimeN :
case TdsColumnType.FloatN :
case TdsColumnType.Char :
case TdsColumnType.NChar :
case TdsColumnType.NText :
case TdsColumnType.Image :
case TdsColumnType.VarBinary :
case TdsColumnType.Binary :
case TdsColumnType.Decimal :
case TdsColumnType.Numeric :
case TdsColumnType.BitN :
case TdsColumnType.UniqueIdentifier :
return false;
default :
return false;
}
}
protected void LoadRow ()
{
currentRow = new TdsDataRow ();
int i = 0;
foreach (TdsDataColumn column in columns) {
object o = GetColumnValue ((TdsColumnType) column["ColumnType"], false, i);
currentRow.Add (o);
if (doneProc)
outputParameters.Add (o);
if (o is TdsBigDecimal && currentRow.BigDecimalIndex < 0)
currentRow.BigDecimalIndex = i;
i += 1;
}
}
internal static int LookupBufferSize (TdsColumnType columnType)
{
switch (columnType) {
case TdsColumnType.Int1 :
case TdsColumnType.Bit :
return 1;
case TdsColumnType.Int2 :
return 2;
case TdsColumnType.Int4 :
case TdsColumnType.Real :
case TdsColumnType.DateTime4 :
case TdsColumnType.Money4 :
case TdsColumnType.SmallMoney :
return 4;
case TdsColumnType.Float8 :
case TdsColumnType.DateTime :
case TdsColumnType.Money :
return 8;
default :
return 0;
}
}
private int LookupDisplaySize (TdsColumnType columnType)
{
switch (columnType) {
case TdsColumnType.Int1 :
return 3;
case TdsColumnType.Int2 :
return 6;
case TdsColumnType.Int4 :
return 11;
case TdsColumnType.Real :
return 14;
case TdsColumnType.Float8 :
return 24;
case TdsColumnType.DateTime :
return 23;
case TdsColumnType.DateTime4 :
return 16;
case TdsColumnType.Bit :
return 1;
case TdsColumnType.Money :
return 21;
case TdsColumnType.Money4 :
case TdsColumnType.SmallMoney :
return 12;
default:
return 0;
}
}
protected internal int ProcessAuthentication ()
{
int pdu_size = Comm.GetTdsShort ();
byte[] msg2 = Comm.GetBytes (pdu_size, true);
Type2Message t2 = new Type2Message (msg2);
// 0x0001 Negotiate Unicode
// 0x0200 Negotiate NTLM
// 0x8000 Negotiate Always Sign
Type3Message t3 = new Type3Message ();
t3.Challenge = t2.Nonce;
t3.Domain = this.connectionParms.DefaultDomain;
t3.Host = this.connectionParms.Hostname;
t3.Username = this.connectionParms.User;
t3.Password = this.connectionParms.Password;
Comm.StartPacket (TdsPacketType.SspAuth); // 0x11
Comm.Append (t3.GetBytes ());
Comm.SendPacket ();
return 1; // TDS_SUCCEED
}
protected void ProcessColumnDetail ()
{
int len = GetSubPacketLength ();
byte[] values = new byte[3];
int columnNameLength;
string baseColumnName = String.Empty;
int position = 0;
while (position < len) {
for (int j = 0; j < 3; j += 1)
values[j] = comm.GetByte ();
position += 3;
if ((values[2] & (byte) TdsColumnStatus.Rename) != 0) {
if (tdsVersion == TdsVersion.tds70) {
columnNameLength = comm.GetByte ();
position += 2 * len + 1;
}
else {
columnNameLength = comm.GetByte ();
position += len + 1;
}
baseColumnName = comm.GetString (columnNameLength);
}
if ((values[2] & (byte) TdsColumnStatus.Hidden) == 0) {
byte index = (byte) (values[0] - (byte) 1);
byte tableIndex = (byte) (values[1] - (byte) 1);
columns [index]["IsExpression"] = ((values[2] & (byte) TdsColumnStatus.IsExpression) != 0);
columns [index]["IsKey"] = ((values[2] & (byte) TdsColumnStatus.IsKey) != 0);
if ((values[2] & (byte) TdsColumnStatus.Rename) != 0)
columns [index]["BaseColumnName"] = baseColumnName;
columns [index]["BaseTableName"] = tableNames [tableIndex];
}
}
}
protected abstract TdsDataColumnCollection ProcessColumnInfo ();
protected void ProcessColumnNames ()
{
columnNames = new ArrayList ();
int totalLength = comm.GetTdsShort ();
int bytesRead = 0;
int i = 0;
while (bytesRead < totalLength) {
int columnNameLength = comm.GetByte ();
string columnName = comm.GetString (columnNameLength);
bytesRead = bytesRead + 1 + columnNameLength;
columnNames.Add (columnName);
i += 1;
}
}
[MonoTODO ("Make sure counting works right, especially with multiple resultsets.")]
protected void ProcessEndToken (TdsPacketSubType type)
{
byte status = Comm.GetByte ();
Comm.Skip (1);
byte op = comm.GetByte ();
Comm.Skip (1);
int rowCount = comm.GetTdsInt ();
if (op == (byte) 0xc1)
rowCount = 0;
if (type == TdsPacketSubType.DoneInProc)
rowCount = -1;
moreResults = ((status & 0x01) != 0);
bool cancelled = ((status & 0x20) != 0);
switch (type) {
case TdsPacketSubType.DoneProc:
doneProc = true;
goto case TdsPacketSubType.Done;
case TdsPacketSubType.Done:
if (rowCount > 0)
recordsAffected += rowCount;
break;
}
if (moreResults)
queryInProgress = false;
if (cancelled)
cancelsProcessed += 1;
if (messages.Count > 0 && !moreResults)
OnTdsInfoMessage (CreateTdsInfoMessageEvent (messages));
}
protected void ProcessEnvironmentChange ()
{
int len = GetSubPacketLength ();
TdsEnvPacketSubType type = (TdsEnvPacketSubType) comm.GetByte ();
int cLen;
switch (type) {
case TdsEnvPacketSubType.BlockSize :
string blockSize;
cLen = comm.GetByte () & 0xff;
blockSize = comm.GetString (cLen);
if (tdsVersion == TdsVersion.tds70)
comm.Skip (len - 2 - cLen * 2);
else
comm.Skip (len - 2 - cLen);
comm.ResizeOutBuf (Int32.Parse (blockSize));
break;
case TdsEnvPacketSubType.CharSet :
cLen = comm.GetByte () & 0xff;
if (tdsVersion == TdsVersion.tds70) {
//this.language = comm.GetString (cLen); // FIXME
comm.GetString (cLen);
comm.Skip (len - 2 - cLen * 2);
}
else {
SetCharset (comm.GetString (cLen));
comm.Skip (len - 2 - cLen);
}
break;
case TdsEnvPacketSubType.Database :
cLen = comm.GetByte () & 0xff;
string newDB = comm.GetString (cLen);
cLen = comm.GetByte () & 0xff;
string oldDB = comm.GetString (cLen);
database = newDB;
break;
default:
comm.Skip (len - 1);
break;
}
}
protected void ProcessLoginAck ()
{
GetSubPacketLength ();
if (tdsVersion == TdsVersion.tds70) {
comm.Skip (5);
int nameLength = comm.GetByte ();
databaseProductName = comm.GetString (nameLength);
databaseMajorVersion = comm.GetByte ();
databaseProductVersion = String.Format ("0{0}.0{1}.0{2}", databaseMajorVersion, comm.GetByte (), ((256 * (comm.GetByte () + 1)) + comm.GetByte ()));
}
else {
comm.Skip (5);
short nameLength = comm.GetByte ();
databaseProductName = comm.GetString (nameLength);
comm.Skip (1);
databaseMajorVersion = comm.GetByte ();
databaseProductVersion = String.Format ("{0}.{1}", databaseMajorVersion, comm.GetByte ());
comm.Skip (1);
}
if (databaseProductName.Length > 1 && -1 != databaseProductName.IndexOf ('\0')) {
int last = databaseProductName.IndexOf ('\0');
databaseProductName = databaseProductName.Substring (0, last);
}
connected = true;
}
protected void OnTdsErrorMessage (TdsInternalErrorMessageEventArgs e)
{
if (TdsErrorMessage != null)
TdsErrorMessage (this, e);
}
protected void OnTdsInfoMessage (TdsInternalInfoMessageEventArgs e)
{
if (TdsInfoMessage != null)
TdsInfoMessage (this, e);
messages.Clear ();
}
protected void ProcessMessage (TdsPacketSubType subType)
{
GetSubPacketLength ();
int number = comm.GetTdsInt ();
byte state = comm.GetByte ();
byte theClass = comm.GetByte ();
string message;
string server;
string procedure;
byte lineNumber;
string source;
bool isError = false;
if (subType == TdsPacketSubType.EED) {
isError = (theClass > 10);
comm.Skip (comm.GetByte ()); // SQL State
comm.Skip (1); // Status
comm.Skip (2); // TranState
} else
isError = (subType == TdsPacketSubType.Error);
message = comm.GetString (comm.GetTdsShort ());
server = comm.GetString (comm.GetByte ());
procedure = comm.GetString (comm.GetByte ());
lineNumber = comm.GetByte ();
comm.Skip (1);
source = String.Empty; // FIXME
if (isError)
OnTdsErrorMessage (CreateTdsErrorMessageEvent (theClass, lineNumber, message, number, procedure, server, source, state));
else
messages.Add (new TdsInternalError (theClass, lineNumber, message, number, procedure, server, source, state));
}
protected void ProcessOutputParam ()
{
GetSubPacketLength ();
comm.GetString (comm.GetByte () & 0xff);
comm.Skip (5);
TdsColumnType colType = (TdsColumnType) comm.GetByte ();
object value = GetColumnValue (colType, true);
outputParameters.Add (value);
}
protected void ProcessDynamic ()
{
Comm.Skip (2);
byte type = Comm.GetByte ();
byte status = Comm.GetByte ();
string id = Comm.GetString (Comm.GetByte ());
}
protected virtual TdsPacketSubType ProcessSubPacket ()
{
TdsPacketSubType subType = (TdsPacketSubType) comm.GetByte ();
switch (subType) {
case TdsPacketSubType.Dynamic2:
comm.Skip (comm.GetTdsInt ());
break;
case TdsPacketSubType.AltName:
case TdsPacketSubType.AltFormat:
case TdsPacketSubType.Capability:
case TdsPacketSubType.ParamFormat:
comm.Skip (comm.GetTdsShort ());
break;
case TdsPacketSubType.Dynamic:
ProcessDynamic ();
break;
case TdsPacketSubType.EnvironmentChange:
ProcessEnvironmentChange ();
break;
case TdsPacketSubType.Info: // TDS 4.2/7.0
case TdsPacketSubType.EED: // TDS 5.0
case TdsPacketSubType.Error: // TDS 4.2/7.0
ProcessMessage (subType);
break;
case TdsPacketSubType.Param:
ProcessOutputParam ();
break;
case TdsPacketSubType.LoginAck:
ProcessLoginAck ();
break;
case TdsPacketSubType.Authentication: // TDS 7.0
ProcessAuthentication ();
break;
case TdsPacketSubType.ReturnStatus :
Comm.Skip (4);
break;
case TdsPacketSubType.ProcId:
Comm.Skip (8);
break;
case TdsPacketSubType.Done:
case TdsPacketSubType.DoneProc:
case TdsPacketSubType.DoneInProc:
ProcessEndToken (subType);
break;
case TdsPacketSubType.ColumnName:
Comm.Skip (8);
ProcessColumnNames ();
break;
case TdsPacketSubType.ColumnInfo: // TDS 4.2
case TdsPacketSubType.ColumnMetadata: // TDS 7.0
case TdsPacketSubType.RowFormat: // TDS 5.0
columns = ProcessColumnInfo ();
break;
case TdsPacketSubType.ColumnDetail:
ProcessColumnDetail ();
break;
case TdsPacketSubType.TableName:
ProcessTableName ();
break;
case TdsPacketSubType.ColumnOrder:
comm.Skip (comm.GetTdsShort ());
break;
case TdsPacketSubType.Control:
comm.Skip (comm.GetTdsShort ());
break;
case TdsPacketSubType.Row:
LoadRow ();
break;
}
return subType;
}
protected void ProcessTableName ()
{
tableNames = new ArrayList ();
int totalLength = comm.GetTdsShort ();
int position = 0;
int len;
while (position < totalLength) {
if (tdsVersion == TdsVersion.tds70) {
len = comm.GetTdsShort ();
position += 2 * (len + 1);
}
else {
len = comm.GetByte ();
position += len + 1;
}
tableNames.Add (comm.GetString (len));
}
}
protected void SetCharset (string charset)
{
if (charset == null || charset.Length > 30)
charset = "iso_1";
if (this.charset != null && this.charset != charset)
return;
if (charset.StartsWith ("cp")) {
encoder = Encoding.GetEncoding (Int32.Parse (charset.Substring (2)));
this.charset = charset;
}
else {
encoder = Encoding.GetEncoding ("iso-8859-1");
this.charset = "iso_1";
}
comm.Encoder = encoder;
}
protected void SetLanguage (string language)
{
if (language == null || language.Length > 30)
language = "us_english";
this.language = language;
}
#endregion // Private Methods
}
}
|