-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathSQLConnectivityTestMultiDriver.ps1
745 lines (644 loc) · 27.4 KB
/
SQLConnectivityTestMultiDriver.ps1
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
## Copyright (c) Microsoft Corporation.
#Licensed under the MIT license.
#Azure Connection and Execution Time Spent
#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.
#------------------------------------------------------------------------------
#About this PowerShell Script
#
#We usually have service requests that our customers using different drivers need to know the connection latency, execution time spent or validate the connection.
#For this reason, I developed this small PowerShell script (based on initiative of AzureSQLConnectivityChecker in multiple languages) which will basically connect to the database using 4 drivers/providers and test this.
#-------------------------------------------------------------------------------
Param($DatabaseServer = "",
$Database = "",
$Username = "",
$passwordSecure = "" ,
$NumberExecutions ="200",
$InputFile = "",
$LogFile="",
$Driver = "")
#--------------------------------
#Obtain the TCP Connection Info
#--------------------------------
function Get-TcpConnectionInfo($Portcheck,$CXWantDetailedPort)
{
Try
{
$StateDesc = [System.Collections.ArrayList]@()
$StateTmp = [System.Collections.ArrayList]@()
$PortSQL = 0
$Port11s = 0
$PortOther = 0
$PortTmp = 0
$bFound = $false
logMsg("Review the ports workload") (1) -SaveFile $false
$TcpConnections = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties().GetActiveTcpConnections()
ForEach($TcpConnection in $TcpConnections)
{
if($CXWantDetailedPort -eq 1 ) { logMsg("LocalEndPoint:" + $TcpConnection.LocalEndPoint + " - RemoteEndPoint:" + $TcpConnection.RemoteEndPoint + " - State:" + $TcpConnection.State) (1) }
#Review the port opened
$PortTmp = [int]$TcpConnection.RemoteEndPoint.Port
$PortOther++
If($PortTmp -eq $Portcheck) {$PortSQL++}
elseif( $PortTmp -ge 11000 -And $PortTmp -le 12000 ) {$Port11s++}
#Review the state
$bFound=$false
for ($i=1; $i -lt $StateDesc.Count; $i++)
{
if($StateDesc[$i] -eq $TcpConnection.State)
{
$StateTmp[$i]++
$bFound=$true
break
}
}
If($bFound -eq $false)
{
$StateDesc.Add($TcpConnection.State) | Out-Null
$StateTmp.Add(1) | Out-Null
}
}
$PortOther=$PortOther-($PortSQL+$Port11S) #Calculate the total.
logMsg("Ports Count : " +$Portcheck + " (" + $PortSQL + ") 11xx: (" + $Port11s + ") Others:(" + $PortOther+ ")") (1)
logMsg("Ports Status: " ) (1)
for ($i=1; $i -lt $StateDesc.Count; $i++)
{
logMsg( "---->" + $StateDesc[$i] + " (" + $StateTmp[$i].ToString() + ")") (1)
}
logMsg("Reviewed the ports workload") (1) -SaveFile $false
}
catch
{
logMsg("Imposible to review the ports workload - Error: " + $Error[0].Exception) (2)
}
}
#-------------------------------
#Delete the file
#-------------------------------
Function DeleteFile{
Param( [Parameter(Mandatory)]$FileName )
try
{
logMsg("Checking if the file..." + $FileName + " exists.") -SaveFile $false
if( FileExist($FileName))
{
logMsg("Removing the file..." + $FileName) -SaveFile $false
$Null = Remove-Item -Path $FileName -Force
logMsg("Removed the file..." + $FileName) -SaveFile $false
}
return $true
}
catch
{
logMsg("Remove the file..." + $FileName + " - " + $Error[0].Exception) (2)
return $false
}
}
#-----------------------------------------------------------
# Identify if the value is empty or not
#-----------------------------------------------------------
function TestEmpty($s)
{
if ([string]::IsNullOrWhitespace($s))
{
return $true;
}
else
{
return $false;
}
}
#-------------------------------
#File Exists
#-------------------------------
Function FileExist{
Param( [Parameter(Mandatory)]$FileName )
try
{
$return=$false
$FileExists = Test-Path $FileName
if($FileExists -eq $True)
{
$return=$true
}
return $return
}
catch
{
return $false
}
}
#--------------------------------
#Obtain the DNS details resolution.
#--------------------------------
function CheckDns($sReviewServer)
{
try
{
$IpAddress = [System.Net.Dns]::GetHostAddresses($sReviewServer)
foreach ($Address in $IpAddress)
{
$sAddress = $sAddress + $Address.IpAddressToString + " ";
}
return $sAddress
break;
}
catch
{
return ""
}
}
#----------------------------------------------------------------
#Function to connect to the database using a retry-logic
#----------------------------------------------------------------
Function GiveMeConnectionSource($DriverParam)
{
$lNumRetries=10
for ($i=1; $i -le $lNumRetries; $i++)
{
try
{
logMsg( "---------------------------------------------------------------------------------------------------------------")
logMsg( "Connecting to the database: " + $DatabaseServer + " - DB: " + $Database + "...Attempt #" + $i + " of " + $lNumRetries.ToString() + " - IP:" + $(CheckDns($DatabaseServer)))
if($DriverParam.Trim().ToUpper() -eq "SQLCLIENT")
{
$SQLConnection = New-Object System.Data.SqlClient.SqlConnection
$SQLConnection.ConnectionString = "data source=tcp:"+$DatabaseServer +",1433"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";Initial Catalog="+$Database
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";Connection Timeout=30"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";User ID="+ $Username
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";Password="+ $password
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";Application Name=Test SQLCLIENT Connection"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";Persist Security Info=False"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";ConnectRetryInterval=3"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";ConnectRetryInterval=10"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";Max Pool Size=100"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";Min Pool Size=1"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";MultipleActiveResultSets=False"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";Pooling=True"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";Encrypt=True"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";TrustServerCertificate=False"
$SQLConnection.StatisticsEnabled = 1
}
if($DriverParam.Trim().ToUpper() -eq "ODBC")
{
$SQLConnection = New-Object System.Data.Odbc.OdbcConnection
$SQLConnection.ConnectionString = "Driver={ODBC Driver 17 for SQL Server}"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";Server=tcp:"+$DatabaseServer +",1433"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";Database="+$Database
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";Connection Timeout=30"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";UID="+ $Username
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";PWD="+ $password
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";Application Name=Test ODBC Connection"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";Persist Security Info=False"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";SQL_ATTR_CONNECTION_POOLING = SQL_CP_ONE_PER_HENV"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";ConnectRetryInterval=3"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";ConnectRetryInterval=10"
}
if($DriverParam.Trim().ToUpper() -eq "MSOLEDBSQL")
{
$SQLConnection = New-Object System.Data.OleDb.OleDbConnection
$SQLConnection.ConnectionString = "Provider=MSOLEDBSQL"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";Server=tcp:"+$DatabaseServer +",1433"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";Database="+$Database
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";Timeout=30"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";UID="+ $Username
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";PWD="+ $password
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";Application Name=Test MSOLEDBSQL Connection"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";Persist Security Info=False"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";OLE DB Services =-1"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";MARSConn=no"
}
if($DriverParam.Trim().ToUpper() -eq "SQLOLEDB")
{
$SQLConnection = New-Object System.Data.OleDb.OleDbConnection
$SQLConnection.ConnectionString = "Provider=SQLOLEDB"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";Server=tcp:"+$DatabaseServer +",1433"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";Database="+$Database
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";Timeout=30"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";UID="+ $Username
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";PWD="+ $password
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";Application Name=Test SQLOLEDB Connection"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";Persist Security Info=False"
$SQLConnection.ConnectionString = $SQLConnection.ConnectionString + ";OLE DB Services =-1"
}
$start = get-date
$SQLConnection.Open()
$end = get-date
if($DriverParam.Trim().ToUpper() -eq "SQLCLIENT")
{
$sAdditionalInformation = " - ID:" + $SQLConnection.ClientConnectionId.ToString() + " -- HostName: " + $SQLConnection.WorkstationId + " Server Version:" + $SQLConnection.ServerVersion
}
if($DriverParam.Trim().ToUpper() -eq "ODBC")
{
$sAdditionalInformation = " - Driver:" + $SQLConnection.Driver.ToString() + " -- HostName: " + $SQLConnection.WorkstationId + " Server Version:" + $SQLConnection.ServerVersion
}
if($DriverParam.Trim().ToUpper() -eq "MSOLEDBSQL")
{
$sAdditionalInformation = " - Provider:" + $SQLConnection.Provider.ToString() + " -- HostName: " + $SQLConnection.WorkstationId + " Server Version:" + $SQLConnection.ServerVersion
}
if($DriverParam.Trim().ToUpper() -eq "SQLOLEDB")
{
$sAdditionalInformation = " - Provider:" + $SQLConnection.Provider.ToString() + " -- HostName: " + $SQLConnection.WorkstationId + " Server Version:" + $SQLConnection.ServerVersion
}
$LatencyAndOthers.ConnectionsDone_Number_Success = $LatencyAndOthers.ConnectionsDone_Number_Success+1
$LatencyAndOthers.ConnectionsDone_MS = $LatencyAndOthers.ConnectionsDone_MS+(New-TimeSpan -Start $start -End $end).TotalMilliseconds
logMsg("Connected to the database in (ms):" +(New-TimeSpan -Start $start -End $end).TotalMilliseconds + " " + $sAdditionalInformation ) (3)
logMsg("Total Connections Failed : " + $LatencyAndOthers.ConnectionsDone_Number_Failed.ToString())
logMsg("Total Connections Success: " + $LatencyAndOthers.ConnectionsDone_Number_Success.ToString())
logMsg("Total Connections ms : " + ($LatencyAndOthers.ConnectionsDone_MS / $LatencyAndOthers.ConnectionsDone_Number_Success).ToString())
$Null = Get-TcpConnectionInfo("1433","0") #TCP ports opened
return $SQLConnection
break;
}
catch
{
$LatencyAndOthers.ConnectionsDone_Number_Failed = $LatencyAndOthers.ConnectionsDone_Number_Failed +1
logMsg("Not able to connect - Retrying the connection..." + $Error[0].Exception.ErrorRecord + "-" + $Error[0].Exception.ToString().Replace("\t"," ").Replace("\n"," ").Replace("\r"," ").Replace("\r\n","").Trim()) (2)
$WaitTime = (5*($i+1))
logMsg("Waiting for next retry in " + $WaitTime.ToString() + " seconds ..") -SaveFile $false
Start-Sleep -s $WaitTime
if($Driver -eq "SQLCLIENT") { [System.Data.SqlClient.SqlConnection]::ClearAllPools() }
}
}
}
#--------------------------------
#Verify if the value is able to convert to integer
#--------------------------------
Function IsInteger([string]$vInteger)
{
Try
{
$null = [convert]::ToInt32($vInteger)
return $True
}
Catch
{
return $False
}
}
#--------------------------------
#Log the operations
#--------------------------------
function logMsg
{
Param
(
[Parameter(Mandatory=$false, Position=0)]
[string] $msg,
[Parameter(Mandatory=$false, Position=1)]
[int] $Color,
[Parameter(Mandatory=$false, Position=2)]
[boolean] $Show=$true,
[Parameter(Mandatory=$false, Position=3)]
[boolean] $ShowDate=$true,
[Parameter(Mandatory=$false, Position=4)]
[boolean] $SaveFile=$true,
[Parameter(Mandatory=$false, Position=5)]
[boolean] $NewLine=$true
)
try
{
If(TestEmpty($msg))
{
$msg = " "
}
if($ShowDate -eq $true)
{
$Fecha = Get-Date -format "yyyy-MM-dd HH:mm:ss"
}
$msg = $Fecha + " " + $msg
If($SaveFile -eq $true)
{
Write-Output $msg | Out-File -FilePath $LogFile -Append
}
$Colores="White"
If($Color -eq 1 )
{
$Colores ="Cyan"
}
If($Color -eq 3 )
{
$Colores ="Yellow"
}
If($Color -eq 4 )
{
$Colores ="Green"
}
If($Color -eq 5 )
{
$Colores ="Magenta"
}
if($Color -eq 2 -And $Show -eq $true)
{
if($NewLine)
{
Write-Host -ForegroundColor White -BackgroundColor Red $msg
}
else
{
Write-Host -ForegroundColor White -BackgroundColor Red $msg -NoNewline
}
}
else
{
if($Show -eq $true)
{
if($NewLine)
{
Write-Host -ForegroundColor $Colores $msg
}
else
{
Write-Host -ForegroundColor $Colores $msg -NoNewline
}
}
}
}
catch
{
Write-Host $msg
}
}
Class LatencyAndOthers #Class to manage the connection latency
{
[long]$ConnectionsDone_MS = 0
[long]$ConnectionsDone_Number_Success = 0
[long]$ConnectionsDone_Number_Failed = 0
[long]$ExecutionsDone_MS = 0
[long]$ExecutionsDone_Number_Success = 0
[long]$ExecutionsDone_Number_Failed = 0
}
$LatencyAndOthers = [LatencyAndOthers]::new()
[System.Collections.ArrayList]$IPArrayConnection = @()
[System.Collections.ArrayList]$Query = @()
[System.Collections.ArrayList]$CommandArray = @()
[System.Collections.ArrayList]$QueryMetrics = @()
cls
if (TestEmpty($DatabaseServer))
{ $DatabaseServer = read-host -Prompt "Please enter a Server Name" }
if (TestEmpty($DatabaseServer))
{
logMsg ("Server Name is empty. Closing the application.")
exit;
}
if (TestEmpty($Database))
{ $Database = read-host -Prompt "Please enter a Database Name" }
if (TestEmpty($Database))
{
logMsg ("DatabaseName Name is empty. Closing the application.")
exit;
}
if (TestEmpty($Username))
{ $Username = read-host -Prompt "Please enter a User Name" }
if (TestEmpty($Username))
{
logMsg ("User Name is empty. Closing the application.")
exit;
}
if (TestEmpty($passwordSecure))
{
$passwordSecure = read-host -Prompt "Please enter a password" -assecurestring
$password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwordSecure))
}
else
{$password = $passwordSecure}
if (TestEmpty($Password))
{
logMsg ("Password is empty. Closing the application.")
exit;
}
if (TestEmpty($NumberExecutions))
{
$NumberExecutions = read-host -Prompt "Please enter the number of test to run (1-2000) - Leave this field empty and press enter for default value 10."
}
if (TestEmpty($NumberExecutions))
{
$NumberExecutions="10"
}
if( -not (IsInteger([string]$NumberExecutions)))
{
logMsg("Please, specify a correct number of process to run, the value is not integer") (2)
exit;
}
$IntegerNumberExecutions = [int]::Parse($NumberExecutions)
if($integerNumberExecutions -lt 1 -or $integerNumberExecutions -gt 2000)
{
logMsg("Please, specify a correct number of process to run, it is a value between 1 and 2000") (2)
exit;
}
if(TestEmpty($InputFile))
{
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{
InitialDirectory = [Environment]::GetFolderPath("Desktop")
Title = "Please choose the file that has the queries to run, press cancel for **SELECT 1** ONLY"
Filter = 'TSQL File (TSQL*.TXT)|TSQL*.TXT'}
$null = $FileBrowser.ShowDialog()
$InputFile = $FileBrowser.FileName
}
if(TestEmpty($InputFile))
{
$query = @("SELECT 1")
logMsg ("Using the default one - SELECT 1 -- File has not been selected")
}
else
{
If( FileExist($InputFile) )
{
$query = @(Get-Content $InputFile)
}
else
{
$query = @("SELECT 1")
logMsg ("Using the default one - SELECT 1 - File doesn't exist")
}
}
if(TestEmpty($LogFile))
{
$FileBrowserAnalysis = New-Object System.Windows.Forms.SaveFileDialog -Property @{
InitialDirectory = [Environment]::GetFolderPath("Desktop")
Title = 'Please choose the Log File to save the content of this process'
Filter = 'Log File to save the content (*.*)|*.*'}
$null = $FileBrowserAnalysis.ShowDialog()
$LogFile = $FileBrowserAnalysis.FileName
if(TestEmpty($LogFile))
{
logMsg -msg "File log was not selected" -Color 2 -bSaveOnFile $false
exit;
}
}
if (TestEmpty($Driver))
{
$listBox = New-Object System.Windows.Forms.ListBox
$listBox.Location = New-Object System.Drawing.Point(10,40)
$listBox.Size = New-Object System.Drawing.Size(260,20)
$listBox.Height = 80
[void] $listBox.Items.Add('SQLCLIENT')
[void] $listBox.Items.Add('ODBC')
[void] $listBox.Items.Add('MSOLEDBSQL')
[void] $listBox.Items.Add('SQLOLEDB')
$okButton = New-Object System.Windows.Forms.Button
$okButton.Location = New-Object System.Drawing.Point(75,120)
$okButton.Size = New-Object System.Drawing.Size(75,23)
$okButton.Text = 'OK'
$okButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$cancelButton = New-Object System.Windows.Forms.Button
$cancelButton.Location = New-Object System.Drawing.Point(150,120)
$cancelButton.Size = New-Object System.Drawing.Size(75,23)
$cancelButton.Text = 'Cancel'
$cancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$listbox.SelectedItem = $listBox.Items.item(0)
$form = New-Object System.Windows.Forms.Form
$form.Text = 'Select the scenario to execute'
$form.Size = New-Object System.Drawing.Size(300,200)
$form.StartPosition = 'CenterScreen'
$form.Controls.Add($listBox)
$form.CancelButton = $cancelButton
$form.Controls.Add($cancelButton)
$form.AcceptButton = $okButton
$form.Controls.Add($okButton)
$form.Topmost = $true
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
$Driver = $listBox.SelectedItem
}
else
{
logMsg("Driver type has not been selected.") (2)
exit
}
}
if(TestEmpty($Driver))
{
logMsg ("Driver has not been selected") (2)
exit;
}
$Null = DeleteFile($LogFile)
logMsg("Driver chosen: " + $Driver)
foreach($Tmp in $Query) ##Create the same number of command that queries that we need.
{
$QueryMetricTmp = [LatencyAndOthers]::new()
$Null = $QueryMetrics.add($QueryMetricTmp)
if($Driver.Trim().ToUpper() -eq "SQLCLIENT")
{
$command = New-Object -TypeName System.Data.SqlClient.SqlCommand
$command.CommandTimeout = 60
$command.Prepare()
$command.CommandText = $Tmp
$Null = $CommandArray.Add($command)
}
if($Driver.Trim().ToUpper() -eq "ODBC")
{
$command = New-Object -TypeName System.Data.Odbc.OdbcCommand
$command.CommandTimeout = 60
$command.CommandText = $Tmp
$Null = $CommandArray.Add($command)
}
if($Driver.Trim().ToUpper() -eq "MSOLEDBSQL")
{
$command = New-Object -TypeName System.Data.OleDb.OleDbCommand
$command.CommandTimeout = 60
$command.CommandText = $Tmp
$Null = $CommandArray.Add($command)
}
if($Driver.Trim().ToUpper() -eq "SQLOLEDB")
{
$command = New-Object -TypeName System.Data.OleDb.OleDbCommand
$command.CommandTimeout = 60
$command.CommandText = $Tmp
$Null = $CommandArray.Add($command)
}
}
$sw = [diagnostics.stopwatch]::StartNew() ##Take the time.
for ($i=1; $i -le $IntegerNumberExecutions; $i++) ##For every number of process open a new connection and close it at the end.
{
try
{
$Null = $IPArrayConnection.Add($(GiveMeConnectionSource $Driver)) #Connecting to the database.
if($IPArrayConnection[$i-1] -eq $null)
{
LogMsg("Not able to connect. Closing the application...") (2)
exit;
}
for ($iQuery=0; $iQuery -lt $query.Count; $iQuery++) #for Every query run it.
{
$CommandArray[$iQuery].Connection = $IPArrayConnection[$i-1]
Try
{
$lDiff=0
LogMsg( "-------------------------------------------------------------------------------------" )
LogMsg( "Query : " + $query[$iQuery])
LogMsg( "Iteration : " + $i + " Query " + ($iQuery+1).ToString() + " / " + $query.Count)
$start = get-date
$Null = $CommandArray[$iQuery].ExecuteNonQuery()
$end = get-date
$lDiff=(New-TimeSpan -Start $start -End $end).TotalMilliseconds
$QueryMetrics[$iQuery].ExecutionsDone_Number_Success = $QueryMetrics[$iQuery].ExecutionsDone_Number_Success+1
$QueryMetrics[$iQuery].ExecutionsDone_MS = $QueryMetrics[$iQuery].ExecutionsDone_MS+$lDiff
$LatencyAndOthers.ExecutionsDone_Number_Success = $LatencyAndOthers.ExecutionsDone_Number_Success+1
$LatencyAndOthers.ExecutionsDone_MS = $LatencyAndOthers.ExecutionsDone_MS+$lDiff
LogMsg( "Time required (ms) : " + $lDiff.ToString())
}
catch
{
$LatencyAndOthers.ExecutionsDone_Number_Failed = $LatencyAndOthers.ExecutionsDone_Number_Failed+1
$QueryMetrics[$iQuery].ExecutionsDone_Number_Failed = $QueryMetrics[$iQuery].ExecutionsDone_Number_Failed+1
LogMsg( "Error: " + $Error[0].Exception) (2)
}
if($Driver.Trim().ToUpper() -eq "SQLCLIENT")
{
$data = $IPArrayConnection[$i-1].RetrieveStatistics()
}
if($Driver.Trim().ToUpper() -eq "SQLCLIENT")
{
LogMsg( "NetworkServerTime (ms): " +$data.NetworkServerTime)
LogMsg( "Execution Time (ms) : " +$data.ExecutionTime)
LogMsg( "Connection Time : " +$data.ConnectionTime)
LogMsg( "ServerRoundTrips : " +$data.ServerRoundtrips)
LogMsg( "BuffersReceived : " +$data.BuffersReceived)
LogMsg( "SelectRows : " +$data.SelectRows)
LogMsg( "SelectCount : " +$data.SelectCount)
LogMsg( "BytesSent : " +$data.BytesSent)
LogMsg( "BytesReceived : " +$data.BytesReceived)
}
logMsg( "Query Commands Failed : " + $QueryMetrics[$iQuery].ExecutionsDone_Number_Failed.ToString())
logMsg( "Query Commands Success: " + $QueryMetrics[$iQuery].ExecutionsDone_Number_Success.ToString())
logMsg( "Query Commands ms : " + ($QueryMetrics[$iQuery].ExecutionsDone_MS / $QueryMetrics[$iQuery].ExecutionsDone_Number_Success).ToString())
logMsg( "Total Commands Failed : " + $LatencyAndOthers.ExecutionsDone_Number_Failed.ToString())
logMsg( "Total Commands Success: " + $LatencyAndOthers.ExecutionsDone_Number_Success.ToString())
logMsg( "TotalCommands ms : " + ($LatencyAndOthers.ExecutionsDone_MS / $LatencyAndOthers.ExecutionsDone_Number_Success).ToString())
LogMsg( "--------------------------------------------------------------------------------------" ) -SaveFile $false
}
$IPArrayConnection[$i-1].Close() ##Close the connection.
}
catch
{
LogMsg( "Error: " + $Error[0].Exception) (2)
}
}
logMsg("-------------------------------------- SUMMARY -----------------------------------------------------------------")
logMsg("Total Connections Failed :" + $LatencyAndOthers.ConnectionsDone_Number_Failed.ToString())
logMsg("Total Connections Success:" + $LatencyAndOthers.ConnectionsDone_Number_Success.ToString())
logMsg("Total Connections Avg ms :" + ($LatencyAndOthers.ConnectionsDone_MS / $LatencyAndOthers.ConnectionsDone_Number_Success).ToString())
LogMsg("Total Number Executions :" + $IntegerNumberExecutions)
LogMsg("Total Number Queries :" + $query.Count)
LogMsg("Total Number Process :" + ($IntegerNumberExecutions*$query.Count))
logMsg("Total Commands Failed :" + $LatencyAndOthers.ExecutionsDone_Number_Failed.ToString())
logMsg("Total Commands Success :" + $LatencyAndOthers.ExecutionsDone_Number_Success.ToString())
logMsg("Total Commands ms :" + ($LatencyAndOthers.ExecutionsDone_MS / $LatencyAndOthers.ExecutionsDone_Number_Success).ToString())
$i=0
LogMsg("------------------- Queries Summary" + $Tmp)
foreach($Tmp in $Query) ##Create the same number of command that queries that we need.
{
LogMsg("Query # :" + $Tmp)
logMsg("Total Commands Failed :" + $QueryMetrics[$i].ExecutionsDone_Number_Failed.ToString())
logMsg("Total Commands Success:" + $QueryMetrics[$i].ExecutionsDone_Number_Success.ToString())
logMsg("Total Commands ms :" + ($QueryMetrics[$i].ExecutionsDone_MS / $QueryMetrics[$i].ExecutionsDone_Number_Success).ToString())
$i=$i+1
}
LogMsg( "Review: https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/provider-statistics-for-sql-server")
logMsg("-------------------------------------- SUMMARY -----------------------------------------------------------------")
Remove-Variable passwordSecure
Remove-Variable password