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
|
//
// System.Data.SqlClient.SqlConnection.cs
//
// Authors:
// Rodrigo Moya (rodrigo@ximian.com)
// Daniel Morgan (danmorg@sc.rr.com)
// Tim Coleman (tim@timcoleman.com)
// Phillip Jerkins (Phillip.Jerkins@morgankeegan.com)
// Diego Caravana (diego@toth.it)
//
// Copyright (C) Ximian, Inc 2002
// Copyright (C) Daniel Morgan 2002, 2003
// Copyright (C) Tim Coleman, 2002, 2003
// Copyright (C) Phillip Jerkins, 2003
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using Mono.Data.Tds;
using Mono.Data.Tds.Protocol;
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
#if NET_2_0
using System.Data.ProviderBase;
#endif // NET_2_0
using System.EnterpriseServices;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Xml;
namespace System.Data.SqlClient {
[DefaultEvent ("InfoMessage")]
#if NET_2_0
public sealed class SqlConnection : DbConnectionBase, IDbConnection, ICloneable
#else
public sealed class SqlConnection : Component, IDbConnection, ICloneable
#endif // NET_2_0
{
#region Fields
bool disposed = false;
// The set of SQL connection pools
static TdsConnectionPoolManager sqlConnectionPools = new TdsConnectionPoolManager (TdsVersion.tds70);
// The current connection pool
TdsConnectionPool pool;
// The connection string that identifies this connection
string connectionString = null;
// The transaction object for the current transaction
SqlTransaction transaction = null;
// Connection parameters
TdsConnectionParameters parms = new TdsConnectionParameters ();
NameValueCollection connStringParameters = null;
bool connectionReset;
bool pooling;
string dataSource;
int connectionTimeout;
int minPoolSize;
int maxPoolSize;
int packetSize;
int port = 1433;
// The current state
ConnectionState state = ConnectionState.Closed;
SqlDataReader dataReader = null;
XmlReader xmlReader = null;
// The TDS object
ITds tds;
#endregion // Fields
#region Constructors
public SqlConnection ()
: this (String.Empty)
{
}
public SqlConnection (string connectionString)
{
Init (connectionString);
}
#if NET_2_0
internal SqlConnection (DbConnectionFactory connectionFactory) : base (connectionFactory)
{
Init (String.Empty);
}
#endif //NET_2_0
private void Init (string connectionString)
{
connectionTimeout = 15; // default timeout
dataSource = ""; // default datasource
packetSize = 8192; // default packetsize
ConnectionString = connectionString;
}
#endregion // Constructors
#region Properties
[DataCategory ("Data")]
#if !NET_2_0
[DataSysDescription ("Information used to connect to a DataSource, such as 'Data Source=x;Initial Catalog=x;Integrated Security=SSPI'.")]
#endif
[DefaultValue ("")]
[EditorAttribute ("Microsoft.VSDesigner.Data.SQL.Design.SqlConnectionStringEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
[RecommendedAsConfigurable (true)]
[RefreshProperties (RefreshProperties.All)]
[MonoTODO("persist security info, encrypt, enlist and , attachdbfilename keyword not implemented")]
public
#if NET_2_0
override
#endif // NET_2_0
string ConnectionString {
get { return connectionString; }
set {
if (state == ConnectionState.Open)
throw new InvalidOperationException ("Not Allowed to change ConnectionString property while Connection state is OPEN");
SetConnectionString (value);
}
}
#if !NET_2_0
[DataSysDescription ("Current connection timeout value, 'Connect Timeout=X' in the ConnectionString.")]
#endif
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public
#if NET_2_0
override
#endif // NET_2_0
int ConnectionTimeout {
get { return connectionTimeout; }
}
#if !NET_2_0
[DataSysDescription ("Current SQL Server database, 'Initial Catalog=X' in the connection string.")]
#endif
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public
#if NET_2_0
override
#endif // NET_2_0
string Database {
get {
if (State == ConnectionState.Open)
return tds.Database;
return parms.Database ;
}
}
internal SqlDataReader DataReader {
get { return dataReader; }
set { dataReader = value; }
}
#if !NET_2_0
[DataSysDescription ("Current SqlServer that the connection is opened to, 'Data Source=X' in the connection string. ")]
#endif
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public
#if NET_2_0
override
#endif // NET_2_0
string DataSource {
get { return dataSource; }
}
#if !NET_2_0
[DataSysDescription ("Network packet size, 'Packet Size=x' in the connection string.")]
#endif
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public int PacketSize {
get {
if (State == ConnectionState.Open)
return ((Tds)tds).PacketSize ;
return packetSize;
}
}
[Browsable (false)]
#if !NET_2_0
[DataSysDescription ("Version of the SQL Server accessed by the SqlConnection.")]
#endif
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public
#if NET_2_0
override
#endif // NET_2_0
string ServerVersion {
get {
if (state == ConnectionState.Closed)
throw new InvalidOperationException ("Invalid Operation.The Connection is Closed");
else
return tds.ServerVersion;
}
}
[Browsable (false)]
#if !NET_2_0
[DataSysDescription ("The ConnectionState indicating whether the connection is open or closed.")]
#endif
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public
#if NET_2_0
override
#endif // NET_2_0
ConnectionState State {
get { return state; }
}
internal ITds Tds {
get { return tds; }
}
internal SqlTransaction Transaction {
get { return transaction; }
set { transaction = value; }
}
#if !NET_2_0
[DataSysDescription ("Workstation Id, 'Workstation ID=x' in the connection string.")]
#endif
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public string WorkstationId {
get { return parms.Hostname; }
}
internal XmlReader XmlReader {
get { return xmlReader; }
set { xmlReader = value; }
}
#endregion // Properties
#region Events
[DataCategory ("InfoMessage")]
#if !NET_2_0
[DataSysDescription ("Event triggered when messages arrive from the DataSource.")]
#endif
public event SqlInfoMessageEventHandler InfoMessage;
[DataCategory ("StateChange")]
#if !NET_2_0
[DataSysDescription ("Event triggered when the connection changes state.")]
#endif
public
#if NET_2_0
override
#endif // NET_2_0
event StateChangeEventHandler StateChange;
#endregion // Events
#region Delegates
private void ErrorHandler (object sender, TdsInternalErrorMessageEventArgs e)
{
throw new SqlException (e.Class, e.LineNumber, e.Message, e.Number, e.Procedure, e.Server, "Mono SqlClient Data Provider", e.State);
}
private void MessageHandler (object sender, TdsInternalInfoMessageEventArgs e)
{
OnSqlInfoMessage (CreateSqlInfoMessageEvent (e.Errors));
}
#endregion // Delegates
#region Methods
internal string GetConnStringKeyValue (params string [] keys)
{
if (connStringParameters == null || connStringParameters.Count == 0)
return "";
foreach (string key in keys) {
string value = connStringParameters [key];
if (value != null)
return value;
}
return "";
}
public new SqlTransaction BeginTransaction ()
{
return BeginTransaction (IsolationLevel.ReadCommitted, String.Empty);
}
public new SqlTransaction BeginTransaction (IsolationLevel iso)
{
return BeginTransaction (iso, String.Empty);
}
public SqlTransaction BeginTransaction (string transactionName)
{
return BeginTransaction (IsolationLevel.ReadCommitted, transactionName);
}
public SqlTransaction BeginTransaction (IsolationLevel iso, string transactionName)
{
if (state == ConnectionState.Closed)
throw new InvalidOperationException ("The connection is not open.");
if (transaction != null)
throw new InvalidOperationException ("SqlConnection does not support parallel transactions.");
if (iso == IsolationLevel.Chaos)
throw new ArgumentException ("Invalid IsolationLevel parameter: must be ReadCommitted, ReadUncommitted, RepeatableRead, or Serializable.");
string isolevel = String.Empty;
switch (iso) {
case IsolationLevel.ReadCommitted:
isolevel = "READ COMMITTED";
break;
case IsolationLevel.ReadUncommitted:
isolevel = "READ UNCOMMITTED";
break;
case IsolationLevel.RepeatableRead:
isolevel = "REPEATABLE READ";
break;
case IsolationLevel.Serializable:
isolevel = "SERIALIZABLE";
break;
}
tds.Execute (String.Format ("SET TRANSACTION ISOLATION LEVEL {0};BEGIN TRANSACTION {1}", isolevel, transactionName));
transaction = new SqlTransaction (this, iso);
return transaction;
}
public
#if NET_2_0
override
#endif // NET_2_0
void ChangeDatabase (string database)
{
if (!IsValidDatabaseName (database))
throw new ArgumentException (String.Format ("The database name {0} is not valid.", database));
if (state != ConnectionState.Open)
throw new InvalidOperationException ("The connection is not open.");
tds.Execute (String.Format ("use [{0}]", database));
}
private void ChangeState (ConnectionState currentState)
{
ConnectionState originalState = state;
state = currentState;
OnStateChange (CreateStateChangeEvent (originalState, currentState));
}
public
#if NET_2_0
override
#endif // NET_2_0
void Close ()
{
if (transaction != null && transaction.IsOpen)
transaction.Rollback ();
if (dataReader != null || xmlReader != null) {
if(tds != null) tds.SkipToEnd ();
dataReader = null;
xmlReader = null;
}
if (pooling) {
if(pool != null) pool.ReleaseConnection (tds);
}else
if(tds != null) tds.Disconnect ();
if(tds != null) {
tds.TdsErrorMessage -= new TdsInternalErrorMessageEventHandler (ErrorHandler);
tds.TdsInfoMessage -= new TdsInternalInfoMessageEventHandler (MessageHandler);
}
ChangeState (ConnectionState.Closed);
}
public new SqlCommand CreateCommand ()
{
SqlCommand command = new SqlCommand ();
command.Connection = this;
return command;
}
private SqlInfoMessageEventArgs CreateSqlInfoMessageEvent (TdsInternalErrorCollection errors)
{
return new SqlInfoMessageEventArgs (errors);
}
private StateChangeEventArgs CreateStateChangeEvent (ConnectionState originalState, ConnectionState currentState)
{
return new StateChangeEventArgs (originalState, currentState);
}
protected override void Dispose (bool disposing)
{
if (!disposed) {
try {
if (disposing) {
if (State == ConnectionState.Open)
Close ();
parms.Reset ();
ConnectionString = "";
SetDefaultConnectionParameters (this.connStringParameters);
}
} finally {
disposed = true;
base.Dispose (disposing);
}
}
}
[MonoTODO ("Not sure what this means at present.")]
public
#if NET_2_0
override
#endif // NET_2_0
void EnlistDistributedTransaction (ITransaction transaction)
{
throw new NotImplementedException ();
}
object ICloneable.Clone ()
{
return new SqlConnection (ConnectionString);
}
IDbTransaction IDbConnection.BeginTransaction ()
{
return BeginTransaction ();
}
IDbTransaction IDbConnection.BeginTransaction (IsolationLevel iso)
{
return BeginTransaction (iso);
}
IDbCommand IDbConnection.CreateCommand ()
{
return CreateCommand ();
}
void IDisposable.Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
~SqlConnection ()
{
Dispose (false);
}
public
#if NET_2_0
override
#endif // NET_2_0
void Open ()
{
string serverName = "";
if (state == ConnectionState.Open)
throw new InvalidOperationException ("The Connection is already Open (State=Open)");
if (connectionString == null)
throw new InvalidOperationException ("Connection string has not been initialized.");
try {
if (!pooling) {
if(!ParseDataSource (dataSource, out port, out serverName))
throw new SqlException(20, 0, "SQL Server does not exist or access denied.", 17, "ConnectionOpen (Connect()).", dataSource, parms.ApplicationName, 0);
tds = new Tds70 (serverName, port, PacketSize, ConnectionTimeout);
}
else {
if(!ParseDataSource (dataSource, out port, out serverName))
throw new SqlException(20, 0, "SQL Server does not exist or access denied.", 17, "ConnectionOpen (Connect()).", dataSource, parms.ApplicationName, 0);
TdsConnectionInfo info = new TdsConnectionInfo (serverName, port, packetSize, ConnectionTimeout, minPoolSize, maxPoolSize);
pool = sqlConnectionPools.GetConnectionPool (connectionString, info);
tds = pool.GetConnection ();
}
} catch (TdsTimeoutException e) {
throw SqlException.FromTdsInternalException ((TdsInternalException) e);
}catch (TdsInternalException e) {
throw SqlException.FromTdsInternalException (e);
}
tds.TdsErrorMessage += new TdsInternalErrorMessageEventHandler (ErrorHandler);
tds.TdsInfoMessage += new TdsInternalInfoMessageEventHandler (MessageHandler);
if (!tds.IsConnected) {
try {
tds.Connect (parms);
}
catch {
if (pooling)
pool.ReleaseConnection (tds);
throw;
}
} else if (connectionReset) {
tds.Reset ();
}
disposed = false; // reset this, so using () would call Close ().
ChangeState (ConnectionState.Open);
}
private bool ParseDataSource (string theDataSource, out int thePort, out string theServerName)
{
theServerName = "";
string theInstanceName = "";
if (theDataSource == null)
throw new ArgumentException("Format of initialization string doesnot conform to specifications");
thePort = 1433; // default TCP port for SQL Server
bool success = true;
int idx = 0;
if ((idx = theDataSource.IndexOf (",")) > -1) {
theServerName = theDataSource.Substring (0, idx);
string p = theDataSource.Substring (idx + 1);
thePort = Int32.Parse (p);
}
else if ((idx = theDataSource.IndexOf ("\\")) > -1) {
theServerName = theDataSource.Substring (0, idx);
theInstanceName = theDataSource.Substring (idx + 1);
// do port discovery via UDP port 1434
port = DiscoverTcpPortViaSqlMonitor (theServerName, theInstanceName);
if (port == -1)
success = false;
}
else if (theDataSource == "" || theDataSource == "(local)")
theServerName = "localhost";
else
theServerName = theDataSource;
return success;
}
private bool ConvertIntegratedSecurity (string value)
{
if (value.ToUpper() == "SSPI")
{
return true;
}
return ConvertToBoolean("integrated security", value);
}
private bool ConvertToBoolean(string key, string value)
{
string upperValue = value.ToUpper();
if (upperValue == "TRUE" ||upperValue == "YES")
{
return true;
}
else if (upperValue == "FALSE" || upperValue == "NO")
{
return false;
}
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
"Invalid value \"{0}\" for key '{1}'.", value, key));
}
private int ConvertToInt32(string key, string value)
{
try
{
return int.Parse(value);
}
catch (Exception ex)
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
"Invalid value \"{0}\" for key '{1}'.", value, key));
}
}
private int DiscoverTcpPortViaSqlMonitor(string ServerName, string InstanceName)
{
SqlMonitorSocket msock;
msock = new SqlMonitorSocket (ServerName, InstanceName);
int SqlServerPort = msock.DiscoverTcpPort ();
msock = null;
return SqlServerPort;
}
void SetConnectionString (string connectionString)
{
NameValueCollection parameters = new NameValueCollection ();
SetDefaultConnectionParameters (parameters);
if ((connectionString == null) || (connectionString.Length == 0)) {
this.connectionString = connectionString;
return;
}
connectionString += ";";
bool inQuote = false;
bool inDQuote = false;
bool inName = true;
string name = String.Empty;
string value = String.Empty;
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < connectionString.Length; i += 1) {
char c = connectionString [i];
char peek;
if (i == connectionString.Length - 1)
peek = '\0';
else
peek = connectionString [i + 1];
switch (c) {
case '\'':
if (inDQuote)
sb.Append (c);
else if (peek.Equals (c)) {
sb.Append (c);
i += 1;
}
else
inQuote = !inQuote;
break;
case '"':
if (inQuote)
sb.Append (c);
else if (peek.Equals (c)) {
sb.Append (c);
i += 1;
}
else
inDQuote = !inDQuote;
break;
case ';':
if (inDQuote || inQuote)
sb.Append (c);
else {
if (name != String.Empty && name != null) {
value = sb.ToString ();
SetProperties (name.ToUpper ().Trim() , value);
parameters [name.ToUpper ().Trim ()] = value.Trim ();
}
else if (sb.Length != 0)
throw new ArgumentException ("Format of initialization string doesnot conform to specifications");
inName = true;
name = String.Empty;
value = String.Empty;
sb = new StringBuilder ();
}
break;
case '=':
if (inDQuote || inQuote || !inName)
sb.Append (c);
else if (peek.Equals (c)) {
sb.Append (c);
i += 1;
}
else {
name = sb.ToString ();
sb = new StringBuilder ();
inName = false;
}
break;
case ' ':
if (inQuote || inDQuote)
sb.Append (c);
else if (sb.Length > 0 && !peek.Equals (';'))
sb.Append (c);
break;
default:
sb.Append (c);
break;
}
}
connectionString = connectionString.Substring (0 , connectionString.Length-1);
this.connectionString = connectionString;
this.connStringParameters = parameters;
}
void SetDefaultConnectionParameters (NameValueCollection parameters)
{
parms.Reset ();
dataSource = "";
connectionTimeout= 15;
connectionReset = true;
pooling = true;
maxPoolSize = 100;
minPoolSize = 0;
packetSize = 8192;
parameters["APPLICATION NAME"] = "Mono SqlClient Data Provider";
parameters["CONNECT TIMEOUT"] = "15";
parameters["CONNECTION LIFETIME"] = "0";
parameters["CONNECTION RESET"] = "true";
parameters["ENLIST"] = "true";
parameters["INTEGRATED SECURITY"] = "false";
parameters["INITIAL CATALOG"] = "";
parameters["MAX POOL SIZE"] = "100";
parameters["MIN POOL SIZE"] = "0";
parameters["NETWORK LIBRARY"] = "dbmssocn";
parameters["PACKET SIZE"] = "8192";
parameters["PERSIST SECURITY INFO"] = "false";
parameters["POOLING"] = "true";
parameters["WORKSTATION ID"] = Dns.GetHostName();
#if NET_2_0
async = false;
parameters ["ASYNCHRONOUS PROCESSING"] = "false";
#endif
}
private void SetProperties (string name , string value)
{
switch (name)
{
case "APP" :
case "APPLICATION NAME" :
parms.ApplicationName = value;
break;
case "ATTACHDBFILENAME" :
case "EXTENDED PROPERTIES" :
case "INITIAL FILE NAME" :
parms.AttachDBFileName = value;
break;
case "TIMEOUT" :
case "CONNECT TIMEOUT" :
case "CONNECTION TIMEOUT" :
int tmpTimeout = ConvertToInt32 ("connection timeout", value);
if (tmpTimeout < 0)
throw new ArgumentException ("Invalid CONNECTION TIMEOUT .. Must be an integer >=0 ");
else
connectionTimeout = tmpTimeout;
break;
case "CONNECTION LIFETIME" :
break;
case "CONNECTION RESET" :
connectionReset = ConvertToBoolean ("connection reset", value);
break;
case "LANGUAGE" :
case "CURRENT LANGUAGE" :
parms.Language = value;
break;
case "DATA SOURCE" :
case "SERVER" :
case "ADDRESS" :
case "ADDR" :
case "NETWORK ADDRESS" :
dataSource = value;
break;
case "ENCRYPT":
if (ConvertToBoolean("encrypt", value))
{
throw new NotImplementedException("SSL encryption for"
+ " data sent between client and server is not"
+ " implemented.");
}
break;
case "ENLIST" :
if (!ConvertToBoolean("enlist", value))
{
throw new NotImplementedException("Disabling the automatic"
+ " enlistment of connections in the thread's current"
+ " transaction context is not implemented.");
}
break;
case "INITIAL CATALOG" :
case "DATABASE" :
parms.Database = value;
break;
case "INTEGRATED SECURITY" :
case "TRUSTED_CONNECTION" :
parms.DomainLogin = ConvertIntegratedSecurity(value);
break;
case "MAX POOL SIZE" :
int tmpMaxPoolSize = ConvertToInt32 ("max pool size" , value);
if (tmpMaxPoolSize < 0)
throw new ArgumentException ("Invalid MAX POOL SIZE. Must be a intger >= 0");
else
maxPoolSize = tmpMaxPoolSize;
break;
case "MIN POOL SIZE" :
int tmpMinPoolSize = ConvertToInt32 ("min pool size" , value);
if (tmpMinPoolSize < 0)
throw new ArgumentException ("Invalid MIN POOL SIZE. Must be a intger >= 0");
else
minPoolSize = tmpMinPoolSize;
break;
#if NET_2_0
case "MULTIPLEACTIVERESULTSETS":
break;
case "ASYNCHRONOUS PROCESSING" :
case "ASYNC" :
async = ConvertToBoolean (name, value);
break;
#endif
case "NET" :
case "NETWORK" :
case "NETWORK LIBRARY" :
if (!value.ToUpper ().Equals ("DBMSSOCN"))
throw new ArgumentException ("Unsupported network library.");
break;
case "PACKET SIZE" :
int tmpPacketSize = ConvertToInt32 ("packet size", value);
if (tmpPacketSize < 512 || tmpPacketSize > 32767)
throw new ArgumentException ("Invalid PACKET SIZE. The integer must be between 512 and 32767");
else
packetSize = tmpPacketSize;
break;
case "PASSWORD" :
case "PWD" :
parms.Password = value;
break;
case "PERSISTSECURITYINFO" :
case "PERSIST SECURITY INFO" :
// FIXME : not implemented
// throw new NotImplementedException ();
break;
case "POOLING" :
pooling = ConvertToBoolean("pooling", value);
break;
case "UID" :
case "USER" :
case "USER ID" :
parms.User = value;
break;
case "WSID" :
case "WORKSTATION ID" :
parms.Hostname = value;
break;
default :
throw new ArgumentException("Keyword not supported :"+name);
}
}
static bool IsValidDatabaseName (string database)
{
if ( database == null || database.Trim() == String.Empty || database.Length > 128)
return false ;
if (database[0] == '"' && database[database.Length] == '"')
database = database.Substring (1, database.Length - 2);
else if (Char.IsDigit (database[0]))
return false;
if (database[0] == '_')
return false;
foreach (char c in database.Substring (1, database.Length - 1))
if (!Char.IsLetterOrDigit (c) && c != '_' && c != '-')
return false;
return true;
}
private void OnSqlInfoMessage (SqlInfoMessageEventArgs value)
{
if (InfoMessage != null)
InfoMessage (this, value);
}
private void OnStateChange (StateChangeEventArgs value)
{
if (StateChange != null)
StateChange (this, value);
}
private sealed class SqlMonitorSocket : UdpClient
{
// UDP port that the SQL Monitor listens
private static readonly int SqlMonitorUdpPort = 1434;
private static readonly string SqlServerNotExist = "SQL Server does not exist or access denied";
private string server;
private string instance;
internal SqlMonitorSocket (string ServerName, string InstanceName)
: base (ServerName, SqlMonitorUdpPort)
{
server = ServerName;
instance = InstanceName;
}
internal int DiscoverTcpPort ()
{
int SqlServerTcpPort;
Client.Blocking = false;
// send command to UDP 1434 (SQL Monitor) to get
// the TCP port to connect to the MS SQL server
ASCIIEncoding enc = new ASCIIEncoding ();
Byte[] rawrq = new Byte [instance.Length + 1];
rawrq[0] = 4;
enc.GetBytes (instance, 0, instance.Length, rawrq, 1);
int bytes = Send (rawrq, rawrq.Length);
if (!Active)
return -1; // Error
bool result;
result = Client.Poll (100, SelectMode.SelectRead);
if (result == false)
return -1; // Error
if (Client.Available <= 0)
return -1; // Error
IPEndPoint endpoint = new IPEndPoint (Dns.GetHostByName ("localhost").AddressList [0], 0);
Byte [] rawrs;
rawrs = Receive (ref endpoint);
string rs = Encoding.ASCII.GetString (rawrs);
string[] rawtokens = rs.Split (';');
Hashtable data = new Hashtable ();
for (int i = 0; i < rawtokens.Length / 2 && i < 256; i++) {
data [rawtokens [i * 2]] = rawtokens [ i * 2 + 1];
}
if (!data.ContainsKey ("tcp"))
throw new NotImplementedException ("Only TCP/IP is supported.");
SqlServerTcpPort = int.Parse ((string) data ["tcp"]);
Close ();
return SqlServerTcpPort;
}
}
#endregion // Methods
#if NET_2_0
#region Fields Net 2
bool async = false;
#endregion // Fields Net 2
#region Properties Net 2
#if !NET_2_0
[DataSysDescription ("Enable Asynchronous processing, 'Asynchrouse Processing=true/false' in the ConnectionString.")]
#endif
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
internal bool AsyncProcessing {
get { return async; }
}
#endregion // Properties Net 2
#endif // NET_2_0
}
}
|