WebTestPlugins.cs
45.8 KB
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
/************************************************************************************************
* All code in this file is under the MS-RL License (https://opensource.org/licenses/MS-RL) *
* By using the code in this file in any way, you agree to the above license terms. *
* Copyright (C) LIGHTS IN LINE AB (https://www.lightsinline.se) *
* Repository, Wiki, Issue tracker and more at https://git.lightsinline.se/products/VSTT-Plugins *
* *
* Contributors *
* LIGHTS IN LINE AB *
* SWEDBANK AB *
* SKATTEVERKET *
************************************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using Microsoft.VisualStudio.TestTools.WebTesting;
using Microsoft.VisualStudio.TestTools.LoadTesting;
using System.IO;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Security.Cryptography.X509Certificates;
using System.Diagnostics;
namespace LIL_VSTT_Plugins
{
/// <summary>
/// Datasource Unique Once
/// </summary>
[DisplayName("Datasource Unique Once")]
[Description("(C) Copyright 2011 LIGHTS IN LINE AB\r\nOBS! Läs hela! Styr datasource selection till att endast göras en gång per VU. Du måste ändra i din datasource Access Metod till Do Not Move Automatically! WebTestUserId används för att välja rad. Använder de datasources som finns definerade i webtestet. Använd test mix based on users starting tests samt 0 percent new users.")]
public class UniqueOnce : WebTestPlugin
{
string dataSourceName;
string dataTableName;
int offset;
[DisplayName("Datakällans namn")]
[Description("Ange namnet på datakällan i ditt webtest, tex DataSource1")]
[DefaultValue("DataSource1")]
public string DataSourceName
{
get { return dataSourceName; }
set { dataSourceName = value; }
}
[DisplayName("Tabellens namn")]
[Description("Ange namnet på den tabell som ska användas, tex Userdata#csv")]
public string DataSourceTableName
{
get { return dataTableName; }
set { dataTableName = value; }
}
[DisplayName("Offset")]
[Description("Används för att hoppa över ett visst antal rader från början på datakällan så de inte används.")]
[DefaultValue(0)]
public int Offset
{
get { return offset; }
set { offset = value; }
}
public override void PreWebTest(object sender, PreWebTestEventArgs e)
{
base.PreWebTest(sender, e);
int index = e.WebTest.Context.WebTestUserId + offset;
e.WebTest.MoveDataTableCursor(dataSourceName, dataTableName, index);
e.WebTest.AddCommentToResult("Selected row number " + index + " from datasource " + dataSourceName + " and table " + dataTableName + ".");
}
}
/// <summary>
/// Filtrar bort oönskade objekt från sidor.
/// Samtliga objekt vars URL börjar med den angivna strängen kommer ignoreras och inte laddas ner.
/// </summary>
[DisplayName("Dynamisk URL Regex filter")]
[Description("(C) Copyright 2011 LIGHTS IN LINE AB\r\nFilter för att ignorera vissa objekt på websidor så de inte laddas ner automatiskt.")]
public class WebTestDependentRegexFilter : WebTestPlugin
{
string m_regex;
bool m_exclude = true;
/// <summary>
/// Fullständig URL (inkl http://) som börjar med FilterString kommer att ignoreras.
[DisplayName("RegEx")]
[Description("Dynamiska (dependent) request kommer att filtreras om de matchar detta uttryck.\r\nTex: www.adsite.com eller *.png")]
public string FilterString
{
get { return m_regex; }
set { m_regex = value; }
}
[DisplayName("Exclude")]
[DefaultValue(true)]
[Description("Om satt till true kommer matchande requests att tas bort/exkluderas. Om satt till false kommer alla request utom de som matchar att tas bort/exkluderas")]
public bool Exclude
{
get { return m_exclude; }
set { m_exclude = value; }
}
public override void PostRequest(object sender, PostRequestEventArgs e)
{
if (!string.IsNullOrEmpty(m_regex))
{
WebTestRequestCollection depsToRemove = new WebTestRequestCollection();
Regex regex = new Regex(m_regex);
foreach (WebTestRequest r in e.Request.DependentRequests)
{
// Disable parsing on dependents since we cannot filter those
r.ParseDependentRequests = false;
if (m_exclude)
{
if (regex.IsMatch(r.Url))
{
depsToRemove.Add(r);
}
}
else
{
if (!regex.IsMatch(r.Url))
{
depsToRemove.Add(r);
}
}
}
foreach (WebTestRequest r in depsToRemove)
{
e.Request.DependentRequests.Remove(r);
}
}
}
}
/// <summary>
/// Filtrar bort oönskade objekt från sidor.
/// Samtliga objekt vars URL börjar med den angivna strängen kommer ignoreras och inte laddas ner.
/// </summary>
[DisplayName("Dynamisk URL exclude filter")]
[Description("(C) Copyright 2011 LIGHTS IN LINE AB\r\nFilter för att ignorera vissa objekt på websidor så de inte laddas ner automatiskt.")]
public class WebTestDependentFilter : WebTestPlugin
{
string m_startsWith;
/// <summary>
/// Fullständig URL (inkl http://) som börjar med FilterString kommer att ignoreras.
[DisplayName("URL börjar med")]
[Description("Dynamiska (dependent) objekt som hittas kommer endast att laddas ner om de INTE börjar med denna sträng.\r\nTex: https://www.excludedsite.com")]
public string FilterString
{
get { return m_startsWith; }
set { m_startsWith = value; }
}
public override void PostRequest(object sender, PostRequestEventArgs e)
{
WebTestRequestCollection depsToRemove = new WebTestRequestCollection();
Boolean hasRun = false;
foreach (WebTestRequest r in e.Request.DependentRequests)
{
// Disable parsing on dependents since we cannot filter those
r.ParseDependentRequests = false;
if (!string.IsNullOrEmpty(m_startsWith) &&
r.Url.StartsWith(m_startsWith))
{
depsToRemove.Add(r);
hasRun = true;
}
}
foreach (WebTestRequest r in depsToRemove)
{
e.Request.DependentRequests.Remove(r);
}
if (hasRun)
{
//e.WebTest.AddCommentToResult("WebTestDependentFilter has run");
}
}
}
/// <summary>
/// Filtrar bort oönskade objekt från sidor.
/// Samtliga objekt vars URL börjar med den angivna strängen kommer ignoreras och inte laddas ner.
/// </summary>
[DisplayName("Dynamisk URL include filter")]
[Description("(C) Copyright 2011 LIGHTS IN LINE AB\r\nFilter för att ignorera vissa objekt på websidor så de inte laddas ner automatiskt.")]
public class WebTestDependentIncludeFilter : WebTestPlugin
{
string m_startsWith;
/// <summary>
/// Fullständig URL (inkl http://) som börjar med FilterString kommer att ignoreras.
[DisplayName("URL börjar med")]
[Description("Alla dynamiska (dependent) objekt som hittas kommer endast att laddas ner OM DE BÖRJAR med denna sträng.\r\nTex: https://www.onlythissite.com")]
public string FilterString
{
get { return m_startsWith; }
set { m_startsWith = value; }
}
public override void PostRequest(object sender, PostRequestEventArgs e)
{
WebTestRequestCollection depsToRemove = new WebTestRequestCollection();
Boolean hasRun = false;
foreach (WebTestRequest r in e.Request.DependentRequests)
{
// Disable parsing on dependents since we cannot filter those
r.ParseDependentRequests = false;
if (!string.IsNullOrEmpty(m_startsWith) &&
!r.Url.StartsWith(m_startsWith))
{
depsToRemove.Add(r);
hasRun = true;
}
}
foreach (WebTestRequest r in depsToRemove)
{
e.Request.DependentRequests.Remove(r);
}
if (hasRun)
{
//e.WebTest.AddCommentToResult("WebTestDependentFilter has run");
}
}
}
/// <summary>
/// Slå på URL encode på query string parametrar
/// </summary>
[DisplayName("URL Encode Query String Parameter")]
[Description("(C) Copyright 2011 LIGHTS IN LINE AB\r\nTvingar en URL Encode på angiven Query String parameter i alla request")]
public class URLEncodeQueryStringParameter : WebTestPlugin
{
[DisplayName("Query String Parameter Name")]
[Description("Name of the query string parameter to URL encode before each request")]
public String paramName { get; set; }
public override void PreRequest(object sender, PreRequestEventArgs e)
{
if (e.Request.HasQueryStringParameters)
{
if (e.Request.QueryStringParameters.Contains(paramName))
{
foreach (QueryStringParameter qsp in e.Request.QueryStringParameters) {
if (qsp.Name.Equals(paramName))
{
qsp.UrlEncode = true;
}
}
}
}
}
}
/// <summary>
/// Loggar alla transaktioners svarstider som context parametrar
/// </summary>
[DisplayName("Transaction Response Times to Context")]
[Description("(C) Copyright 2016 LIGHTS IN LINE AB\r\nLoggar alla transaktioners svarstider som context parametrar")]
public class TransactionsToContext : WebTestPlugin
{
public override void PostTransaction(object sender, PostTransactionEventArgs e)
{
base.PostTransaction(sender, e);
if (!e.WebTest.Context.ContainsKey(e.TransactionName))
{
e.WebTest.Context.Add(e.TransactionName, e.Duration.TotalMilliseconds.ToString());
}
else
{
e.WebTest.Context[e.TransactionName] = e.Duration.TotalMilliseconds.ToString();
}
}
}
/// <summary>
/// Loggar alla transaktioners svarstider som context parametrar
/// </summary>
[DisplayName("Set Test Info As Header")]
[Description("(C) Copyright 2017 LIGHTS IN LINE AB\r\nAdds name information from transactions, pages, tests into a header in requests so that it can be used to group upon in tools like AppDynamics, DynaTrace, etc.")]
public class SetTestInfoAsHeader : WebTestPlugin
{
[DisplayName("Header Prefix")]
[Description("Prefix of the header to be added on requests")]
[DefaultValue("X-Sipoz")]
public String HeaderName { get; set; }
[DisplayName("Tests")]
[Description("Add the Test name as a header with <prefix>-TestName")]
[DefaultValue(true)]
public bool onTransaction { get; set; }
[DisplayName("Transactions")]
[Description("Add the transaction name as a header with <prefix>-TransactionName")]
[DefaultValue(true)]
public bool onTest { get; set; }
List<String> transactionPath = new List<string>();
public override void PreRequest(object sender, PreRequestEventArgs e)
{
base.PreRequest(sender, e);
if (onTest) e.Request.Headers.Add(HeaderName + "-TestName", e.WebTest.Name);
if (onTransaction && transactionPath.Count > 0)
{
String value = String.Empty;
foreach (string trans in transactionPath) {
if (value.Equals(String.Empty)) value = trans;
else value += "." + trans;
}
e.Request.Headers.Add(HeaderName + "-TransactionName", value);
}
}
public override void PreTransaction(object sender, PreTransactionEventArgs e)
{
base.PreTransaction(sender, e);
transactionPath.Add(e.TransactionName);
}
public override void PostTransaction(object sender, PostTransactionEventArgs e)
{
base.PostTransaction(sender, e);
transactionPath.Remove(e.TransactionName);
}
}
/// <summary>
/// Ignorerar status koder under 500.
/// </summary>
[DisplayName("Ignore 4xx status codes")]
[Description("(C) Copyright 2011 LIGHTS IN LINE AB\r\nDetta plugin ändrar alla request så de inte går fel på grund av 4xx status koder i svaret samt ignorerar statuskoden helt på alla dependent requests")]
public class WebTestIgnore4xx : WebTestPlugin
{
public override void PostRequest(object sender, PostRequestEventArgs e)
{
if (e.ResponseExists && (int)e.Response.StatusCode >= 500) e.Request.Outcome = Outcome.Fail;
WebTestRequestCollection depsToRemove = new WebTestRequestCollection();
foreach (WebTestRequest r in e.Request.DependentRequests)
{
r.IgnoreHttpStatusCode = true;
}
}
public override void PreRequest(object sender, PreRequestEventArgs e)
{
e.Request.IgnoreHttpStatusCode = true;
}
}
/// <summary>
/// Ignorerar status koder under 500.
/// </summary>
[DisplayName("Ignore Dependent Results")]
[Description("(C) Copyright 2011 LIGHTS IN LINE AB\r\nDependent requests kommer laddas ner men ej mätas individuellt. Alla kommer enbart mätas gemensamt som [dependent]")]
public class WebTestIgnoreDependentResults : WebTestPlugin
{
public override void PostRequest(object sender, PostRequestEventArgs e)
{
foreach (WebTestRequest r in e.Request.DependentRequests)
{
r.ReportingName = "[dependent request]";
}
}
}
/// <summary>
/// Service Manager Plugin
/// </summary>
[DisplayName("Service Manager Config")]
[Description("(C) Copyright 2015 LIGHTS IN LINE AB\r\nSätter config värden i Service Manager instansen för hela testet, finns även som loadtest plugin och gäller då hela loadtestet.")]
public class ServiceManagerWebTestPlugin : WebTestPlugin
{
[DisplayName("Use Expect 100 Behaviour"), DefaultValue(false)]
[Description("Default i .NET är att detta är påslaget, default i webbläsare är dock att detta inte är påslaget. Detta plugin stänger default därför av detta (false).")]
public bool exp100 { get; set; }
[DisplayName("Max Connection Idle Time (s)"), DefaultValue(100)]
[Description("Anger hur länge connections får ligga kvar i poolen innan de aktivt stängs ner. VS default är 100 sekunder men många webbservrar stänger ner tidigare utan att meddela klienten, vilket ger felmeddelanden under loadtests av typen att en connection oväntat stängts ner.")]
public int maxIdle { get; set; }
[DisplayName("TCP Keep Alive"), DefaultValue(false)]
[Description("Keepalive på TCP nivå är default avstängt både i webbläsare och i .NET men vissa rika/feta klienter kan slå på detta, tex webservice klienter")]
public bool keepAlive { get; set; }
[DisplayName("TCP Keep Alive Timeout (ms)"), DefaultValue(5000)]
public int timeOut { get; set; }
[DisplayName("TCP Keep Alive Interval"), DefaultValue(1000)]
public int interVal { get; set; }
[DisplayName("Use Nagle Algorithm"), DefaultValue(false)]
[Description("Buffring av paket på TCP nivå, är normalt sätt inte påslaget för HTTP men för tex SSH eller Telnet. Buffrar små paket och slår ihop dem till större för att minska antalet paket på långsamma nätverk.")]
public bool useNagle { get; set; }
[DisplayName("Force TLS 1.2"), DefaultValue(false)]
[Description("Default inte påslaget. Om servern inte stödjer TLS1.2 kommer SSL handskakningen att avbrytas och requestet failar. Kräver .NET 4.5 samt att TLS1.2 är aktiverat i SChannel (använd bifogad schannel_high.reg om det inte är påslaget på äldre windows versioner)")]
public bool useTls12 { get; set; }
[DisplayName("Apply Override"), DefaultValue(false)]
[Description("Ändrar proxy inställningarna för detta webtest enligt detta plugin")]
[Category("Web Proxy")]
public bool proxyOverride { get; set; }
[DisplayName("Proxy URI"), DefaultValue("http://host:port")]
[Description("Anger proxyserverns URI (http://host:port)")]
[Category("Web Proxy")]
public string proxyURI { get; set; }
[DisplayName("Bypass Local"), DefaultValue(false)]
[Description("True för att inte använda proxy på lokala hostnamn, i.e. utan domännamn")]
[Category("Web Proxy")]
public bool proxyBypassLocal { get; set; }
[DisplayName("Bypass RegExp"), DefaultValue("")]
[Description("Sätter ett reguljärt uttryck för URI (hostnamn) som INTE ska gå via proxyn")]
[Category("Web Proxy")]
public string proxyBypass { get; set; }
[DisplayName("User Name"), DefaultValue("")]
[Description("Sätter användarnamn för proxyn")]
[Category("Web Proxy")]
public string proxyUser { get; set; }
[DisplayName("User Password"), DefaultValue("")]
[Description("Sätter swedbanks proxy (temp lösning)")]
[Category("Web Proxy")]
public string proxyPass { get; set; }
System.Net.WebProxy myProxy = null;
public override void PreWebTest(object sender, PreWebTestEventArgs e)
{
base.PreWebTest(sender, e);
if (proxyOverride)
{
if (myProxy == null)
{
myProxy = new System.Net.WebProxy();
if(!String.IsNullOrWhiteSpace(proxyURI)) myProxy.Address = new Uri(proxyURI);
myProxy.BypassProxyOnLocal = proxyBypassLocal;
if (!String.IsNullOrWhiteSpace(proxyBypass)) myProxy.BypassList = new string[] { proxyBypass };
if (!String.IsNullOrWhiteSpace(proxyUser)) myProxy.Credentials = new System.Net.NetworkCredential(proxyUser, proxyPass);
}
// Change the webtests proxy setting
e.WebTest.Proxy = "lil";
e.WebTest.WebProxy = myProxy;
// Set context parameters
e.WebTest.Context["proxyOverride"] = proxyOverride;
e.WebTest.Context["proxyURI"] = proxyURI;
e.WebTest.Context["proxyBypassLocal"] = proxyBypassLocal;
e.WebTest.Context["proxyBypass"] = proxyBypass;
e.WebTest.Context["proxyUser"] = proxyUser;
e.WebTest.Context["proxyPass"] = proxyPass;
}
System.Net.ServicePointManager.Expect100Continue = exp100;
System.Net.ServicePointManager.MaxServicePointIdleTime = maxIdle;
System.Net.ServicePointManager.SetTcpKeepAlive(keepAlive, timeOut, interVal);
System.Net.ServicePointManager.UseNagleAlgorithm = useNagle;
if(useTls12) System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
}
}
/// <summary>
/// WebTest Plugin Template
/// </summary>
[DisplayName("Randomize each page")]
[Description("(C) Copyright 2011 LIGHTS IN LINE AB\r\nVäljer en ny slumpmässig rad i din datasource vid varje sida/page i skriptet.")]
public class randomOnEachPage : WebTestPlugin
{
string dataSourceName;
string dataTableName;
int datasourceSize = 0;
Random RandomNumber = new Random(System.DateTime.Now.Millisecond);
[DisplayName("Datakällans namn")]
[Description("Ange namnet på datakällan i ditt webtest, tex DataSource1")]
[DefaultValue("DataSource1")]
public string DataSourceName
{
get { return dataSourceName; }
set { dataSourceName = value; }
}
[DisplayName("Tabellens namn")]
[Description("Ange namnet på den tabell som ska användas, tex Userdata#csv")]
public string DataSourceTableName
{
get { return dataTableName; }
set { dataTableName = value; }
}
public override void PrePage(object sender, PrePageEventArgs e)
{
base.PrePage(sender, e);
if (datasourceSize == 0) {
int size = e.WebTest.GetDataTableRowCount(dataSourceName, dataTableName);
if(size > 0)
datasourceSize = size;
else
return;
}
if (datasourceSize > 0)
{
int index = RandomNumber.Next(0, datasourceSize - 1);
e.WebTest.MoveDataTableCursor(dataSourceName, dataTableName, index);
//e.WebTest.AddCommentToResult("Selected row number " + index + " from datasource " + dataSourceName + " and table " + dataTableName + ".");
}
}
}
///<summary>
///WebTest Plugin Data Generator
///</summary>
[DisplayName("Data Generator Integer")]
[Description("(C) Copyright 2016 LIGHTS IN LINE AB\r\nGenererar en slumpad integer som context parameter")]
public class dataGenInteger : WebTestPlugin
{
Random RandomNumber = new Random(System.DateTime.Now.Millisecond);
private string paramName;
[DisplayName("Parameter namn")]
[Description("Ange namnet på parametern i ditt webtest, tex IntParameter1")]
[DefaultValue("IntegerParameter1")]
public string ParamNameVal
{
get { return paramName; }
set { paramName = value; }
}
private int intMin;
[DisplayName("Integer Min")]
[Description("Ange minsta värdet för parametern i ditt webtest, tex 0")]
[DefaultValue(0)]
public int IntegerMin
{
get { return intMin; }
set { intMin = value; }
}
private int intMax;
[DisplayName("Integer Max")]
[Description("Ange högsta värdet för parametern i ditt webtest, tex 100")]
[DefaultValue(100)]
public int IntegerMax
{
get { return intMax; }
set { intMax = value; }
}
private bool prePage = false;
[DisplayName("Uppdatera på varje Page")]
[Description("Sätt till true om du vill ha värdet uppdaterat inför varje ny sida som laddas i testet.")]
[DefaultValue(false)]
public bool PrePageVal
{
get { return prePage; }
set { prePage = value; }
}
private bool preTrans = false;
[DisplayName("Uppdatera på varje Transaktion")]
[Description("Sätt till true om du vill ha värdet uppdaterat inför varje ny transaktion i testet.")]
[DefaultValue(false)]
public bool PreTransactionVal
{
get { return preTrans; }
set { preTrans = value; }
}
private bool preReq = false;
[DisplayName("Uppdatera på varje Request")]
[Description("Sätt till true om du vill ha värdet uppdaterat inför varje nytt request i testet.")]
[DefaultValue(false)]
public bool PreRequestVal
{
get { return preReq; }
set { preReq = value; }
}
public override void PreWebTest(object sender, PreWebTestEventArgs e)
{
update(e.WebTest.Context);
base.PreWebTest(sender, e);
}
public override void PrePage(object sender, PrePageEventArgs e)
{
if (prePage) update(e.WebTest.Context);
base.PrePage(sender, e);
}
public override void PreRequestDataBinding(object sender, PreRequestDataBindingEventArgs e)
{
if (preReq) update(e.WebTest.Context);
base.PreRequestDataBinding(sender, e);
}
public override void PreTransaction(object sender, PreTransactionEventArgs e)
{
if (preTrans) update(e.WebTest.Context);
base.PreTransaction(sender, e);
}
private void update(WebTestContext context)
{
context[paramName] = RandomNumber.Next(intMin, intMax);
}
}
///<summary>
///WebTest Plugin Data Generator
///</summary>
[DisplayName("Data Generator Timestamp")]
[Description("(C) Copyright 2011 LIGHTS IN LINE AB\r\nGenererar en timestamp som context parameter")]
public class dataGenTimestamp : WebTestPlugin
{
private string paramName;
[DisplayName("Parameter namn")]
[Description("Ange namnet på parametern i ditt webtest, tex TimeStampParameter1")]
[DefaultValue("TimeStampParameter1")]
public string ParamNameVal
{
get { return paramName; }
set { paramName = value; }
}
private bool millis = false;
[DisplayName("Använd millisekunder")]
[Description("Sätt till true om du vill ha värdet i millisekunder istället för sekunder.")]
[DefaultValue(false)]
public bool MillisecondsVal
{
get { return millis; }
set { millis = value; }
}
private bool prePage = false;
[DisplayName("Uppdatera på varje Page")]
[Description("Sätt till true om du vill ha värdet uppdaterat inför varje ny sida som laddas i testet.")]
[DefaultValue(false)]
public bool PrePageVal
{
get { return prePage; }
set { prePage = value; }
}
private bool preTrans = false;
[DisplayName("Uppdatera på varje Transaktion")]
[Description("Sätt till true om du vill ha värdet uppdaterat inför varje ny transaktion i testet.")]
[DefaultValue(false)]
public bool PreTransactionVal
{
get { return preTrans; }
set { preTrans = value; }
}
private bool preReq = false;
[DisplayName("Uppdatera på varje Request")]
[Description("Sätt till true om du vill ha värdet uppdaterat inför varje nytt request i testet.")]
[DefaultValue(false)]
public bool PreRequestVal
{
get { return preReq; }
set { preReq = value; }
}
public override void PreWebTest(object sender, PreWebTestEventArgs e)
{
update(e.WebTest.Context);
base.PreWebTest(sender, e);
}
public override void PrePage(object sender, PrePageEventArgs e)
{
if (prePage) update(e.WebTest.Context);
base.PrePage(sender, e);
}
public override void PreRequestDataBinding(object sender, PreRequestDataBindingEventArgs e)
{
if (preReq) update(e.WebTest.Context);
base.PreRequestDataBinding(sender, e);
}
public override void PreTransaction(object sender, PreTransactionEventArgs e)
{
if (preTrans) update(e.WebTest.Context);
base.PreTransaction(sender, e);
}
private void update(WebTestContext context)
{
TimeSpan span = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));
if (millis) context[paramName] = ((Int64) span.TotalMilliseconds).ToString();
else context[paramName] = ((Int64) span.TotalSeconds).ToString();
}
}
/// <summary>
/// WebTest Client Certificate
/// </summary>
[DisplayName("Client Certificate")]
[Description("(C) Copyright 2016 LIGHTS IN LINE AB\r\nSätter webtestet att använda ett specifikt client cert för SSL. Certifikatet installeras automatiskt i Windows User Certificate Store.")]
public class ClientCertificatePlugin : WebTestPlugin
{
[DisplayName("Certificate Path")]
[Description("Sökvägen till certifikatfilen (P12/PFX/PEM med privat nyckel eller CER/DER utan privat nyckel)")]
[DefaultValue("")]
public string pCertificatePath { get; set; }
[DisplayName("Certificate Path Parameter")]
[Description("Ange namn på parameter som ska användas för sökvägen till certifikatfilen. Om parametern saknas eller är tom används Certificate Path")]
[DefaultValue("")]
public string pCertificatePathParameter { get; set; }
[DisplayName("Certificate Password")]
[Description("Ange lösenordet för att öppna skyddade/krypterade filer")]
[DefaultValue("")]
public string pCertificatePassword { get; set; }
[DisplayName("Certificate Password Parameter")]
[Description("Ange namn på parameter som ska användas för lösenordet till certifikatfilen. Om parametern saknas eller är tom används Certificate Password")]
[DefaultValue("")]
public string pCertificatePasswordParameter { get; set; }
[DisplayName("Log Debug Info")]
[Description("Sätt till True om extra info ska loggas i början av varje test")]
[DefaultValue(false)]
public bool pDebug { get; set; }
[DisplayName("Install trusted certificates")]
[Description("Sätt till True om certifikat ska installeras automatiskt om det är giltigt")]
[DefaultValue(false)]
public bool pInstallTrusted { get; set; }
[DisplayName("Install untrusted certificates")]
[Description("Sätt till True om ogiltiga som giltiga certifikat ska installeras automatiskt")]
[DefaultValue(false)]
public bool pInstallUntrusted { get; set; }
private bool haveCert = false;
private X509Certificate2 myClientCertAndKey;
private Regex p12RegExp = new Regex(@"p12$|pfx$",RegexOptions.IgnoreCase);
private Regex cerRegExp = new Regex(@"cer$|der$", RegexOptions.IgnoreCase);
private Regex pemRegExp = new Regex(@"pem$", RegexOptions.IgnoreCase);
public override void PreWebTest(object sender, PreWebTestEventArgs e)
{
Stopwatch sw = new Stopwatch();
sw.Start();
base.PreWebTest(sender, e);
String certPath, certPass;
// Ladda in certifikatet och sätt CertPolicy
if (!String.IsNullOrWhiteSpace(pCertificatePathParameter) && e.WebTest.Context.ContainsKey(pCertificatePathParameter) && !String.IsNullOrWhiteSpace(e.WebTest.Context[pCertificatePathParameter].ToString()) )
{
certPath = e.WebTest.Context[pCertificatePathParameter].ToString().Trim();
} else
{
certPath = pCertificatePath.Trim();
}
if (!String.IsNullOrWhiteSpace(pCertificatePasswordParameter) && e.WebTest.Context.ContainsKey(pCertificatePasswordParameter) && !String.IsNullOrWhiteSpace(e.WebTest.Context[pCertificatePasswordParameter].ToString()))
{
certPass = e.WebTest.Context[pCertificatePasswordParameter].ToString();
}
else
{
certPass = pCertificatePassword;
}
if(string.IsNullOrWhiteSpace(certPath))
{
// Cant continue, cert is missing
if (pDebug) e.WebTest.AddCommentToResult("No certificate loaded, since both Certificate Path and Certificate Path Parameter are empty");
return;
}
// Check what type of container we have. All files are treated as PEM unless the extension matches our winX509regExp regular expression (see above)
// Read certificate and private key depending on type
if (p12RegExp.IsMatch(certPath))
{
if (pDebug) e.WebTest.AddCommentToResult("Certificate file is treated as PFX/P12");
try
{
myClientCertAndKey = new X509Certificate2(certPath, certPass, X509KeyStorageFlags.PersistKeySet);
}
catch (Exception ex)
{
e.WebTest.AddCommentToResult("Error during loading of certificate: " + certPath + " Message: " + ex.Message);
return;
}
} else if (cerRegExp.IsMatch(certPath))
{
if (pDebug) e.WebTest.AddCommentToResult("Certificate file is treated as CER/DER without private key");
try
{
myClientCertAndKey = new X509Certificate2(certPath, certPass);
}
catch (Exception ex)
{
e.WebTest.AddCommentToResult("Error during loading of certificate: " + certPath + " Message: " + ex.Message);
return;
}
} else if (pemRegExp.IsMatch(certPath))
{
if (pDebug) e.WebTest.AddCommentToResult("Certificate file is treated as OpenSSL encoded PEM");
// Use Bouncy Castle to read the certificate and key, then convert to .NET X509Certificate2 and X509Certificate
String text;
try {
text = File.ReadAllText(certPath);
} catch (Exception ex)
{
e.WebTest.AddCommentToResult("Error opening PEM file: " + certPath + " Message: " + ex.Message);
return;
}
// Find the key and certificate in file and load them
int keyTextBeginPos = text.IndexOf("-----BEGIN");
int keyTextEndPos = text.IndexOf("-----END");
Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair bcKey = null;
Org.BouncyCastle.X509.X509Certificate bcCert = null;
while (keyTextBeginPos != -1 && keyTextEndPos != -1)
{
object obj;
try
{
Org.BouncyCastle.OpenSsl.PemReader bc = new Org.BouncyCastle.OpenSsl.PemReader(new StringReader(text), new PasswordHelper(certPass));
obj = bc.ReadObject();
}
catch (Org.BouncyCastle.Crypto.InvalidCipherTextException ex)
{
e.WebTest.AddCommentToResult("Error during reading of PEM file: " + certPath + " Wrong password? Message: " + ex.Message);
return;
}
catch (Exception ex)
{
e.WebTest.AddCommentToResult("Error during reading of PEM file: " + certPath + " Message: " + ex.GetType().FullName + ":" + ex.Message);
return;
}
if (obj != null)
{
if (pDebug) e.WebTest.AddCommentToResult("Found PEM Object of type " + obj.GetType().FullName);
if(obj is Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair)
{
// We have a keypair
bcKey = (Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair)obj;
}
if(obj is Org.BouncyCastle.X509.X509Certificate)
{
// We have a certificate
bcCert = (Org.BouncyCastle.X509.X509Certificate)obj;
}
}
keyTextBeginPos = text.IndexOf("-----BEGIN", keyTextEndPos);
if(keyTextBeginPos >= 0) text = text.Substring(keyTextBeginPos);
keyTextEndPos = text.IndexOf("-----END");
}
if (bcCert == null)
{
e.WebTest.AddCommentToResult("Error: PEM file has to contain an x509 certificate");
return;
}
try {
myClientCertAndKey = new X509Certificate2(Org.BouncyCastle.Security.DotNetUtilities.ToX509Certificate(bcCert));
if(bcKey != null) myClientCertAndKey.PrivateKey = Org.BouncyCastle.Security.DotNetUtilities.ToRSA(bcKey.Private as Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters);
} catch (Exception ex)
{
e.WebTest.AddCommentToResult("Error during loading of PEM file: " + certPath + " Message: " + ex.Message);
return;
}
} else
{
// Unknown or unsuported format
e.WebTest.AddCommentToResult("Error during loading of file: " + certPath + " Message: Unsupported format");
return;
}
// Check that we have a certificate
if (myClientCertAndKey == null)
{
if (pDebug) e.WebTest.AddCommentToResult("Certificate File " + certPath + " could not be loaded.");
return;
}
else
{
if (pDebug) e.WebTest.AddCommentToResult("Certificate File " + certPath + " loaded successfully in " + sw.ElapsedMilliseconds + "ms");
}
// Check that it seems okey
if (string.IsNullOrWhiteSpace(myClientCertAndKey.Thumbprint))
{
if (pDebug) e.WebTest.AddCommentToResult("Certificate File " + certPath + " contains no Thumbprint. Not using it.");
return;
}
if (pDebug) e.WebTest.AddCommentToResult("Subject: [" + myClientCertAndKey.Subject + "]");
if (pDebug) e.WebTest.AddCommentToResult("Issued by: [" + myClientCertAndKey.Issuer + "] Expires: [" + myClientCertAndKey.GetExpirationDateString() + "]");
// Check if the certificate is trusted (i.e. chain can be validated)
bool myCertTrusted = false;
if (myClientCertAndKey.Verify())
{
if (pDebug) e.WebTest.AddCommentToResult("Certificate is TRUSTED");
myCertTrusted = true;
} else
{
e.WebTest.AddCommentToResult("Warning: Certificate is NOT TRUSTED by client. Might not be trusted on server either. Check that the Issuer/CA root and intermediary certificates are installed on the client and server.");
myCertTrusted = false;
}
// Check if it is expired or about to expire
if(myClientCertAndKey.NotAfter < DateTime.Now)
{
e.WebTest.AddCommentToResult("Warning: Client Certificate has expired. Might not be trusted on server.");
} else if (myClientCertAndKey.NotBefore > DateTime.Now)
{
e.WebTest.AddCommentToResult("Warning: Client Certificate is not valid yet. Might not be trusted on server. Valid on " + myClientCertAndKey.NotBefore.ToString());
} else if (myClientCertAndKey.NotAfter < DateTime.Now.AddDays(14))
{
e.WebTest.AddCommentToResult("Warning: Client Certificate will expire in less than 14 days. Better renew it soon.");
}
// Check if we have a private key
if (myClientCertAndKey.HasPrivateKey)
{
if (pDebug) e.WebTest.AddCommentToResult("Certificate HAS PRIVATE KEY in file");
}
// Check that the certificate exists in the cert store
X509Store cuStore = new X509Store();
cuStore.Open(OpenFlags.ReadWrite);
if(cuStore.Certificates.Contains(myClientCertAndKey)) {
if (pDebug) e.WebTest.AddCommentToResult("Certificate already INSTALLED in Current User Windows Certificate Store");
// Try to load the key from store if we dont have it and verify that it belongs to the certificate
if(!myClientCertAndKey.HasPrivateKey)
{
X509Certificate2Collection certCol = cuStore.Certificates.Find(X509FindType.FindByThumbprint, myClientCertAndKey.Thumbprint, false);
if(certCol == null || certCol.Count == 0)
{
e.WebTest.AddCommentToResult("Error: Certificate could not be loaded from store using it's thumbprint which is very strange. Aborting");
return;
} else
{
if(certCol.Count > 1)
{
if (pDebug) e.WebTest.AddCommentToResult("Certificates thumbprint has more than one match in the Windows User Certificate Store, using the first one.");
}
X509Certificate2 cert = certCol[0];
if (!cert.HasPrivateKey)
{
e.WebTest.AddCommentToResult("Error: Certificate does not have a corresponding private key in the Windows User Certificate Store. Can not use it for SSL.");
return;
} else
{
if (pDebug) e.WebTest.AddCommentToResult("Certificate was found in Windows User Certificate Store using thumbprint and HAS a corresponding PRIVATE KEY");
}
}
}
} else
{
if (pDebug) e.WebTest.AddCommentToResult("Certificate is NOT INSTALLED");
if (myClientCertAndKey.HasPrivateKey)
{
if (pInstallTrusted && myCertTrusted || pInstallUntrusted)
{
// Try to install certificate
// Install in user store
try
{
myClientCertAndKey.FriendlyName = "VSTT";
cuStore.Add(myClientCertAndKey);
if (pDebug) e.WebTest.AddCommentToResult("Certificate HAS BEEN INSTALLED in the Current User Windows Certificate Store with Friendly Name: VSTT");
}
catch (Exception ex)
{
e.WebTest.AddCommentToResult("Error: COULD NOT INSTALL in the Current User Windows Certificate Store, Message: " + ex.Message);
return;
}
}
else
{
e.WebTest.AddCommentToResult("Error: COULD NOT INSTALL the certificate since you selected NOT to install untrusted certificates.");
return;
}
} else
{
e.WebTest.AddCommentToResult("Error: COULD NOT INSTALL the certificate since the file did not contain a private key and cannot be used without one.");
return;
}
}
// Set the PreRequest method to add the certificate on requests
haveCert = true;
if (pDebug) e.WebTest.AddCommentToResult("Certificate will be ADDED TO REQUESTS");
sw.Stop();
if (pDebug) e.WebTest.AddCommentToResult("Certificate processing done in " + sw.ElapsedMilliseconds + "ms");
}
public override void PreRequest(object sender, PreRequestEventArgs e)
{
base.PreRequest(sender, e);
if (haveCert)
{
if (!e.Request.ClientCertificates.Contains(myClientCertAndKey))
{
e.Request.ClientCertificates.Add(myClientCertAndKey);
}
e.WebTest.Context["Client Certificate"] = myClientCertAndKey.Subject;
} else
{
e.WebTest.Context["Client Certificate"] = "No certificate was specified in this request. Windows will try to automatically choose an installed client certificate if requested by the server.";
}
}
}
public class PasswordHelper : Org.BouncyCastle.OpenSsl.IPasswordFinder
{
private string pwd = "";
public PasswordHelper(String password)
{
this.pwd = password;
}
public char[] GetPassword()
{
return pwd.ToArray();
}
}
/*
/// <summary>
/// WebTest Plugin Template
/// </summary>
[DisplayName("Plugin Namn")]
[Description("(C) Copyright 2011 LIGHTS IN LINE AB\r\nFörklaring")]
public class myPlugin : WebTestPlugin
{
private string paramName;
[DisplayName("Parameter namn")]
[Description("Ange namnet på parametern i ditt webtest, tex TimeStampParameter1")]
[DefaultValue("TimeStampParameter1")]
public string ParamNameVal
{
get { return paramName; }
set { paramName = value; }
}
public override void PreWebTest(object sender, PreWebTestEventArgs e)
{
base.PreWebTest(sender, e);
e.WebTest.Context.CookieContainer = new myCookieContainer();
}
}
*/
}