-
Notifications
You must be signed in to change notification settings - Fork 38
/
ConnectionDetail.cs
1336 lines (1134 loc) · 51.4 KB
/
ConnectionDetail.cs
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
using McTools.Xrm.Connection.AppCode;
using McTools.Xrm.Connection.Forms;
using McTools.Xrm.Connection.Utils;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Metadata.Query;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Tooling.Connector;
using Newtonsoft.Json;
using System;
using System.ComponentModel;
using System.Data.Common;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Reflection;
using System.ServiceModel;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using AuthenticationType = Microsoft.Xrm.Tooling.Connector.AuthenticationType;
namespace McTools.Xrm.Connection
{
public enum BrowserEnum
{
Edge,
Chrome,
Firefox,
None
}
public enum SensitiveDataNotFoundReason
{
NotAllowedByUser,
NotAccessible,
None
}
public static class ConnectionDetailExtensions
{
public static void OpenUrlWithBrowserProfile(this ConnectionDetail detail, Uri uri)
{
var process = new Process();
if (detail == null)
{
Process.Start(uri.ToString());
return;
}
switch (detail.BrowserName)
{
case BrowserEnum.Chrome:
process.StartInfo = new ProcessStartInfo("chrome.exe");
process.StartInfo.Arguments = uri.ToString();
process.StartInfo.Arguments += $" --profile-directory=\"{detail.BrowserProfile}\"";
break;
case BrowserEnum.Edge:
process.StartInfo = new ProcessStartInfo("msedge.exe");
process.StartInfo.Arguments = uri.ToString();
process.StartInfo.Arguments += $" --profile-directory=\"{detail.BrowserProfile}\"";
break;
case BrowserEnum.Firefox:
process.StartInfo = new ProcessStartInfo("firefox.exe");
process.StartInfo.Arguments = uri.ToString();
process.StartInfo.Arguments += $" -P \"{detail.BrowserProfile}\"";
break;
default:
Process.Start(uri.ToString());
return;
break;
}
process.Start();
}
}
public class CertificateInfo
{
public string Issuer { get; set; }
public string Name { get; set; }
public string Thumbprint { get; set; }
}
/// <summary>
/// Stores data regarding a specific connection to Crm server
/// </summary>
[XmlInclude(typeof(CertificateInfo))]
[XmlInclude(typeof(EnvironmentHighlighting))]
public class ConnectionDetail : IComparable, ICloneable
{
private bool? canImpersonate;
private string clientSecret;
private Guid impersonatedUserId;
private string impersonatedUserName;
private string userPassword;
#region Constructeur
static ConnectionDetail()
{
// Generate the contracts used by JSON.NET to serialize the metadata cache in the background.
// This saves about 0.5 seconds on the first connection.
Task.Run(() =>
{
MetadataCacheContractResolver.Instance.PreloadContracts(typeof(MetadataCache));
});
}
public ConnectionDetail()
{
}
public ConnectionDetail(bool createNewId = false)
{
if (createNewId)
{
ConnectionId = Guid.NewGuid();
}
}
#endregion Constructeur
#region Propriétés
private MetadataCache _metadataCache;
[XmlIgnore]
private CrmServiceClient crmSvc;
[XmlIgnore]
public bool AllowPasswordSharing { get; set; }
public AuthenticationProviderType AuthType { get; set; }
public Guid AzureAdAppId { get; set; }
public BrowserEnum BrowserName { get; set; } = BrowserEnum.None;
public string BrowserProfile { get; set; }
[XmlIgnore]
public bool CanImpersonate { get; private set; }
[XmlElement("CertificateInfo")]
public CertificateInfo Certificate { get; set; }
[XmlElement("ClientSecret")]
public string ClientSecretEncrypted
{
get => clientSecret;
set => clientSecret = value;
}
[XmlIgnore]
public bool ClientSecretIsEmpty => string.IsNullOrEmpty(clientSecret);
/// <summary>
/// Gets or sets the connection unique identifier
/// </summary>
public Guid? ConnectionId { get; set; }
/// <summary>
/// Gets or sets the name of the connection
/// </summary>
public string ConnectionName { get; set; }
public string ConnectionString { get; set; }
[XmlIgnore]
public Color? EnvironmentColor { get; set; }
///// <summary>
///// Gets or sets custom information for use by consuming application
///// </summary>
//public Dictionary<string, string> CustomInformation { get; set; }
public EnvironmentHighlighting EnvironmentHighlightingInfo { get; set; }
public string EnvironmentId { get; set; }
[XmlIgnore]
public string EnvironmentText { get; set; }
[XmlIgnore]
public Color? EnvironmentTextColor { get; set; }
/// <summary>
/// Gets or sets the Home realm url for ADFS authentication
/// </summary>
public string HomeRealmUrl { get; set; }
[XmlIgnore]
public Guid ImpersonatedUserId => impersonatedUserId;
[XmlIgnore]
public string ImpersonatedUserName => impersonatedUserName;
/// <summary>
/// Get or set flag to know if custom authentication
/// </summary>
public bool IsCustomAuth { get; set; }
[XmlIgnore] public bool IsEnvironmentHighlightSet => EnvironmentHighlightingInfo != null;
public bool IsFromSdkLoginCtrl { get; set; }
[XmlIgnore]
public DateTime LastUsedOn { get; set; }
[XmlElement("LastUsedOn")]
public string LastUsedOnString
{
get => LastUsedOn.ToString("yyyy-MM-dd HH:mm:ss");
set
{
//if (DateTime.TryParse(value, CultureInfo.CurrentUICulture, DateTimeStyles.AssumeLocal, out DateTime parsed))
if (DateTime.TryParseExact(value, "MM/dd/yyyy HH:mm:ss", CultureInfo.CurrentUICulture, DateTimeStyles.AssumeLocal, out DateTime parsed))
{
LastUsedOn = parsed;
}
else
{
LastUsedOn = DateTime.Parse(value);
}
}
}
/// <summary>
/// Returns a cached version of the metadata for this connection.
/// </summary>
/// <remarks>
/// This cache is updated at the start of each connection, or by calling <see cref="UpdateMetadataCache(bool)"/>
/// </remarks>
[XmlIgnore]
public EntityMetadata[] MetadataCache => _metadataCache?.EntityMetadata;
/// <summary>
/// Returns a task that provides access to the <see cref="MetadataCache"/> once it has finished loading
/// </summary>
[XmlIgnore]
public Task<MetadataCache> MetadataCacheLoader { get; private set; } = Task.FromResult<MetadataCache>(null);
public AuthenticationType NewAuthType { get; set; }
/// <summary>
/// Get or set the organization name
/// </summary>
public string Organization { get; set; }
public string OrganizationDataServiceUrl { get; set; }
/// <summary>
/// Get or set the organization friendly name
/// </summary>
public string OrganizationFriendlyName { get; set; }
public int OrganizationMajorVersion => OrganizationVersion != null ? int.Parse(OrganizationVersion.Split('.')[0]) : -1;
public int OrganizationMinorVersion => OrganizationVersion != null ? int.Parse(OrganizationVersion.Split('.')[1]) : -1;
/// <summary>
/// Gets or sets the Crm Service Url
/// </summary>
public string OrganizationServiceUrl { get; set; }
/// <summary>
/// Get or set the organization name
/// </summary>
public string OrganizationUrlName { get; set; }
public string OrganizationVersion { get; set; }
public string OriginalUrl { get; set; }
/// <summary>
/// Gets an information if the password is empty
/// </summary>
public bool PasswordIsEmpty => string.IsNullOrEmpty(userPassword);
/// <summary>
/// OAuth Refresh Token
/// </summary>
public string RefreshToken { get; set; }
public string ReplyUrl { get; set; }
/// <summary>
/// Client Secret used for S2S Auth
/// </summary>
public string S2SClientSecret
{
get => clientSecret;
set => clientSecret = value;
}
/// <summary>
/// Gets or sets the information if the password must be saved
/// </summary>
public bool SavePassword { get; set; }
/// <summary>
/// Get or set the server name
/// </summary>
public string ServerName { get; set; }
/// <summary>
/// Get or set the server port
/// </summary>
[DefaultValue(80)]
[XmlIgnore]
public int? ServerPort { get; set; }
[XmlElement("ServerPort")]
public string ServerPortString
{
get => ServerPort.ToString();
set => ServerPort = string.IsNullOrEmpty(value) ? 80 : int.Parse(value);
}
[XmlIgnore]
public CrmServiceClient ServiceClient
{
get => GetCrmServiceClient();
set
{
crmSvc = value;
SetImpersonationCapability();
}
}
public Guid TenantId { get; set; }
public TimeSpan Timeout { get; set; }
public long TimeoutTicks
{
get { return Timeout.Ticks; }
set { Timeout = new TimeSpan(value); }
}
[XmlIgnore]
public bool UseConnectionString => !string.IsNullOrEmpty(ConnectionString);
/// <summary>
/// Get or set flag to know if we use IFD
/// </summary>
public bool UseIfd { get; set; }
/// <summary>
/// Get or set flag to know if we use Multi Factor Authentication
/// </summary>
public bool UseMfa { get; set; }
/// <summary>
/// Get or set flag to know if we use CRM Online
/// </summary>
[XmlIgnore]
public bool UseOnline => OriginalUrl.IndexOf(".dynamics.com", StringComparison.InvariantCultureIgnoreCase) > 0;
/// <summary>
/// Get or set the user domain name
/// </summary>
public string UserDomain { get; set; }
/// <summary>
/// Get or set flag to know if we use Online Services
/// </summary>
//public bool UseOsdp { get; set; }
/// <summary>
/// Get or set user login
/// </summary>
public string UserName { get; set; }
[XmlElement("UserPassword")]
public string UserPasswordEncrypted
{
get => userPassword;
set => userPassword = value;
}
/// <summary>
/// Get or set the use of SSL connection
/// </summary>
[XmlIgnore]
public bool UseSsl => WebApplicationUrl?.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase) ?? OriginalUrl.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase);
public string WebApplicationUrl
{
get;
set;
}
#endregion Propriétés
#region Méthodes
public void ErasePassword()
{
userPassword = null;
clientSecret = null;
}
public CrmServiceClient GetCrmServiceClient(bool forceNewService = false)
{
if (forceNewService == false && crmSvc != null)
{
SetImpersonationCapability();
return crmSvc;
}
if (Timeout.Ticks == 0)
{
Timeout = new TimeSpan(0, 2, 0);
}
CrmServiceClient.MaxConnectionTimeout = Timeout;
if (IsFromSdkLoginCtrl)
{
if (crmSvc != null)
{
SetImpersonationCapability();
return crmSvc;
}
throw new ApplicationException("Connections using the SDK Login Control cannot be created automatically");
}
else if (Certificate != null)
{
var cs = HandleConnectionString($"AuthType=Certificate;url={OriginalUrl};thumbprint={Certificate.Thumbprint};ClientId={AzureAdAppId};");
crmSvc = new CrmServiceClient(cs);
}
else if (!string.IsNullOrEmpty(ConnectionString))
{
var cs = HandleConnectionString(ConnectionString);
crmSvc = new CrmServiceClient(cs);
}
else if (NewAuthType == AuthenticationType.ClientSecret)
{
var cs = HandleConnectionString($"AuthType=ClientSecret;url={OriginalUrl};ClientId={AzureAdAppId};ClientSecret={clientSecret}");
crmSvc = new CrmServiceClient(cs);
}
else if (NewAuthType == AuthenticationType.OAuth && UseMfa)
{
var path = Path.Combine(Path.GetTempPath(), ConnectionId.Value.ToString("B"));
var cs = HandleConnectionString($"AuthType=OAuth;Username={UserName};Url={OriginalUrl};AppId={AzureAdAppId};RedirectUri={ReplyUrl};TokenCacheStorePath={path};LoginPrompt=Auto");
crmSvc = new CrmServiceClient(cs);
}
else if (!string.IsNullOrEmpty(clientSecret))
{
ConnectOAuth();
}
else if (UseOnline)
{
ConnectOnline();
//var path = Path.Combine(Path.GetTempPath(), ConnectionId.Value.ToString("B"));
//var cs = HandleConnectionString($"AuthType=OAuth;Username={UserName};Password={userPassword};Url={OriginalUrl};AppId={(AzureAdAppId != Guid.Empty ? AzureAdAppId : new Guid("51f81489-12ee-4a9e-aaae-a2591f45987d"))};RedirectUri={(string.IsNullOrEmpty(ReplyUrl) ? "app://58145B91-0C36-4500-8554-080854F2AC97" : ReplyUrl)};TokenCacheStorePath={path};LoginPrompt=Auto");
//crmSvc = new CrmServiceClient(cs);
}
else if (UseIfd)
{
ConnectIfd();
}
else
{
ConnectOnprem();
}
if (!crmSvc.IsReady)
{
var error = crmSvc.LastCrmError;
crmSvc = null;
throw new Exception(error);
}
SetImpersonationCapability();
OrganizationFriendlyName = crmSvc.ConnectedOrgFriendlyName;
OrganizationDataServiceUrl = crmSvc.ConnectedOrgPublishedEndpoints[EndpointType.OrganizationDataService];
OrganizationServiceUrl = crmSvc.ConnectedOrgPublishedEndpoints[EndpointType.OrganizationService];
WebApplicationUrl = crmSvc.ConnectedOrgPublishedEndpoints[EndpointType.WebApplication];
Organization = crmSvc.ConnectedOrgUniqueName;
OrganizationVersion = crmSvc.ConnectedOrgVersion.ToString();
TenantId = crmSvc.TenantId;
EnvironmentId = crmSvc.EnvironmentId;
var webAppURi = new Uri(WebApplicationUrl);
ServerName = webAppURi.Host;
ServerPort = webAppURi.Port;
//UseIfd = crmSvc.ActiveAuthenticationType == AuthenticationType.IFD;
switch (crmSvc.ActiveAuthenticationType)
{
case AuthenticationType.AD:
case AuthenticationType.Claims:
AuthType = AuthenticationProviderType.ActiveDirectory;
break;
case AuthenticationType.IFD:
AuthType = AuthenticationProviderType.Federation;
break;
case AuthenticationType.Live:
AuthType = AuthenticationProviderType.LiveId;
break;
case AuthenticationType.OAuth:
// TODO add new property in ConnectionDetail class?
break;
case AuthenticationType.Office365:
AuthType = AuthenticationProviderType.OnlineFederation;
break;
}
return crmSvc;
}
public void SetClientSecret(string secret, bool isEncrypted = false)
{
if (!string.IsNullOrEmpty(secret))
{
if (isEncrypted)
{
clientSecret = secret;
}
else
{
clientSecret = CryptoManager.Encrypt(secret, ConnectionManager.CryptoPassPhrase,
ConnectionManager.CryptoSaltValue,
ConnectionManager.CryptoHashAlgorythm,
ConnectionManager.CryptoPasswordIterations,
ConnectionManager.CryptoInitVector,
ConnectionManager.CryptoKeySize);
}
}
}
public void SetConnectionString(string connectionString)
{
var csb = new DbConnectionStringBuilder { ConnectionString = connectionString };
OriginalUrl = (csb.ContainsKey("ServiceUri") ? csb["ServiceUri"] :
csb.ContainsKey("Service Uri") ? csb["Service Uri"] :
csb.ContainsKey("Url") ? csb["Url"] :
csb.ContainsKey("Server") ? csb["Server"] : "").ToString();
if (csb.ContainsKey("Password"))
{
csb["Password"] = CryptoManager.Encrypt(csb["Password"].ToString(), ConnectionManager.CryptoPassPhrase,
ConnectionManager.CryptoSaltValue,
ConnectionManager.CryptoHashAlgorythm,
ConnectionManager.CryptoPasswordIterations,
ConnectionManager.CryptoInitVector,
ConnectionManager.CryptoKeySize);
}
if (csb.ContainsKey("ClientSecret"))
{
csb["ClientSecret"] = CryptoManager.Encrypt(csb["ClientSecret"].ToString(), ConnectionManager.CryptoPassPhrase,
ConnectionManager.CryptoSaltValue,
ConnectionManager.CryptoHashAlgorythm,
ConnectionManager.CryptoPasswordIterations,
ConnectionManager.CryptoInitVector,
ConnectionManager.CryptoKeySize);
}
ConnectionString = csb.ToString();
}
public void SetPassword(string password, bool isEncrypted = false)
{
if (!string.IsNullOrEmpty(password))
{
string newPassword;
if (isEncrypted)
{
newPassword = password;
}
else
{
newPassword = CryptoManager.Encrypt(password, ConnectionManager.CryptoPassPhrase,
ConnectionManager.CryptoSaltValue,
ConnectionManager.CryptoHashAlgorythm,
ConnectionManager.CryptoPasswordIterations,
ConnectionManager.CryptoInitVector,
ConnectionManager.CryptoKeySize);
}
if (NewAuthType == AuthenticationType.ClientSecret)
{
clientSecret = newPassword;
}
else
{
userPassword = newPassword;
}
}
}
/// <summary>
/// Retourne le nom de la connexion
/// </summary>
/// <returns>Nom de la connexion</returns>
public override string ToString()
{
return ConnectionName;
}
public bool TryRequestClientSecret(Control parent, string secretUsageDescription, out string secret, out SensitiveDataNotFoundReason notFoundReason)
{
var prd = new PasswordRequestDialog(secretUsageDescription, this, "client secret");
if (AllowPasswordSharing || prd.ShowDialog(parent) == DialogResult.OK && prd.Accepted)
{
if (string.IsNullOrEmpty(clientSecret))
{
secret = string.Empty;
notFoundReason = SensitiveDataNotFoundReason.NotAccessible;
return false;
}
secret = CryptoManager.Decrypt(clientSecret, ConnectionManager.CryptoPassPhrase,
ConnectionManager.CryptoSaltValue,
ConnectionManager.CryptoHashAlgorythm,
ConnectionManager.CryptoPasswordIterations,
ConnectionManager.CryptoInitVector,
ConnectionManager.CryptoKeySize);
notFoundReason = SensitiveDataNotFoundReason.None;
return true;
}
notFoundReason = SensitiveDataNotFoundReason.NotAllowedByUser;
secret = string.Empty;
return false;
}
public bool TryRequestPassword(Control parent, string passwordUsageDescription, out string password, out SensitiveDataNotFoundReason notFoundReason)
{
var prd = new PasswordRequestDialog(passwordUsageDescription, this, "password");
if (AllowPasswordSharing || prd.ShowDialog(parent) == DialogResult.OK && prd.Accepted)
{
if (string.IsNullOrEmpty(userPassword))
{
password = string.Empty;
notFoundReason = SensitiveDataNotFoundReason.NotAccessible;
return false;
}
password = CryptoManager.Decrypt(userPassword, ConnectionManager.CryptoPassPhrase,
ConnectionManager.CryptoSaltValue,
ConnectionManager.CryptoHashAlgorythm,
ConnectionManager.CryptoPasswordIterations,
ConnectionManager.CryptoInitVector,
ConnectionManager.CryptoKeySize);
notFoundReason = SensitiveDataNotFoundReason.None;
return true;
}
notFoundReason = SensitiveDataNotFoundReason.NotAllowedByUser;
password = string.Empty;
return false;
}
public void UpdateAfterEdit(ConnectionDetail editedConnection)
{
ConnectionName = editedConnection.ConnectionName;
ConnectionString = editedConnection.ConnectionString;
OrganizationServiceUrl = editedConnection.OrganizationServiceUrl;
OrganizationDataServiceUrl = editedConnection.OrganizationDataServiceUrl;
Organization = editedConnection.Organization;
OrganizationFriendlyName = editedConnection.OrganizationFriendlyName;
ServerName = editedConnection.ServerName;
ServerPort = editedConnection.ServerPort;
UseIfd = editedConnection.UseIfd;
UserDomain = editedConnection.UserDomain;
UserName = editedConnection.UserName;
userPassword = editedConnection.userPassword;
HomeRealmUrl = editedConnection.HomeRealmUrl;
Timeout = editedConnection.Timeout;
UseMfa = editedConnection.UseMfa;
ReplyUrl = editedConnection.ReplyUrl;
AzureAdAppId = editedConnection.AzureAdAppId;
clientSecret = editedConnection.clientSecret;
RefreshToken = editedConnection.RefreshToken;
EnvironmentText = editedConnection.EnvironmentText;
EnvironmentColor = editedConnection.EnvironmentColor;
EnvironmentTextColor = editedConnection.EnvironmentTextColor;
TenantId = editedConnection.TenantId;
EnvironmentId = editedConnection.EnvironmentId;
AllowPasswordSharing = editedConnection.AllowPasswordSharing;
BrowserName = editedConnection.BrowserName;
BrowserProfile = editedConnection.BrowserProfile;
IsCustomAuth = editedConnection.IsCustomAuth;
NewAuthType = editedConnection.NewAuthType;
}
private void ConnectIfd()
{
AuthType = AuthenticationProviderType.Federation;
if (!IsCustomAuth)
{
crmSvc = new CrmServiceClient(CredentialCache.DefaultNetworkCredentials,
AuthenticationType.IFD,
ServerName,
ServerPort.ToString(),
OrganizationUrlName,
true,
UseSsl);
}
else
{
var password = CryptoManager.Decrypt(userPassword, ConnectionManager.CryptoPassPhrase,
ConnectionManager.CryptoSaltValue,
ConnectionManager.CryptoHashAlgorythm,
ConnectionManager.CryptoPasswordIterations,
ConnectionManager.CryptoInitVector,
ConnectionManager.CryptoKeySize);
crmSvc = new CrmServiceClient(UserName, CrmServiceClient.MakeSecureString(password), UserDomain,
HomeRealmUrl,
ServerName,
ServerPort.ToString(),
OrganizationUrlName,
true,
UseSsl);
}
}
private void ConnectOAuth()
{
if (!string.IsNullOrEmpty(RefreshToken))
{
CrmServiceClient.AuthOverrideHook = new RefreshTokenAuthOverride(this);
crmSvc = new CrmServiceClient(new Uri($"https://{ServerName}:{ServerPort}"), true);
CrmServiceClient.AuthOverrideHook = null;
}
else
{
var secret = CryptoManager.Decrypt(clientSecret, ConnectionManager.CryptoPassPhrase,
ConnectionManager.CryptoSaltValue,
ConnectionManager.CryptoHashAlgorythm,
ConnectionManager.CryptoPasswordIterations,
ConnectionManager.CryptoInitVector,
ConnectionManager.CryptoKeySize);
var path = Path.Combine(Path.GetTempPath(), ConnectionId.Value.ToString("B"), "oauth-cache.txt");
crmSvc = new CrmServiceClient(new Uri($"https://{ServerName}:{ServerPort}"), AzureAdAppId.ToString(), CrmServiceClient.MakeSecureString(secret), true, path);
}
}
private void ConnectOnline()
{
AuthType = AuthenticationProviderType.OnlineFederation;
if (string.IsNullOrEmpty(userPassword))
{
throw new Exception("Unable to read user password");
}
var password = CryptoManager.Decrypt(userPassword, ConnectionManager.CryptoPassPhrase,
ConnectionManager.CryptoSaltValue,
ConnectionManager.CryptoHashAlgorythm,
ConnectionManager.CryptoPasswordIterations,
ConnectionManager.CryptoInitVector,
ConnectionManager.CryptoKeySize);
Utilities.GetOrgnameAndOnlineRegionFromServiceUri(new Uri(OriginalUrl), out var region, out var orgName, out _);
var path = Path.Combine(Path.GetTempPath(), ConnectionId.Value.ToString("B"), "oauth-cache.txt");
crmSvc = new CrmServiceClient(UserName, CrmServiceClient.MakeSecureString(password),
region,
orgName,
true,
null,
null,
AzureAdAppId != Guid.Empty ? AzureAdAppId.ToString() : "51f81489-12ee-4a9e-aaae-a2591f45987d",
new Uri(string.IsNullOrEmpty(ReplyUrl) ? "app://58145B91-0C36-4500-8554-080854F2AC97" : ReplyUrl),
path,
null);
}
private void ConnectOnprem()
{
AuthType = AuthenticationProviderType.ActiveDirectory;
NetworkCredential credential;
if (!IsCustomAuth)
{
credential = CredentialCache.DefaultNetworkCredentials;
}
else
{
var password = CryptoManager.Decrypt(userPassword, ConnectionManager.CryptoPassPhrase,
ConnectionManager.CryptoSaltValue,
ConnectionManager.CryptoHashAlgorythm,
ConnectionManager.CryptoPasswordIterations,
ConnectionManager.CryptoInitVector,
ConnectionManager.CryptoKeySize);
credential = new NetworkCredential(UserName, password, UserDomain);
}
crmSvc = new CrmServiceClient(credential,
AuthenticationType.AD,
ServerName,
ServerPort.ToString(),
OrganizationUrlName,
true,
UseSsl);
}
private string HandleConnectionString(string connectionString)
{
var csb = new DbConnectionStringBuilder { ConnectionString = connectionString };
if (csb.ContainsKey("timeout"))
{
var csTimeout = TimeSpan.Parse(csb["timeout"].ToString());
csb.Remove("timeout");
CrmServiceClient.MaxConnectionTimeout = csTimeout;
}
OriginalUrl = csb["Url"].ToString();
UserName = csb.ContainsKey("username") ? csb["username"].ToString() :
csb.ContainsKey("clientid") ? csb["clientid"].ToString() : null;
if (csb.ContainsKey("Password"))
{
csb["Password"] = CryptoManager.Decrypt(csb["Password"].ToString(), ConnectionManager.CryptoPassPhrase,
ConnectionManager.CryptoSaltValue,
ConnectionManager.CryptoHashAlgorythm,
ConnectionManager.CryptoPasswordIterations,
ConnectionManager.CryptoInitVector,
ConnectionManager.CryptoKeySize);
}
if (csb.ContainsKey("ClientSecret"))
{
csb["ClientSecret"] = CryptoManager.Decrypt(csb["ClientSecret"].ToString(), ConnectionManager.CryptoPassPhrase,
ConnectionManager.CryptoSaltValue,
ConnectionManager.CryptoHashAlgorythm,
ConnectionManager.CryptoPasswordIterations,
ConnectionManager.CryptoInitVector,
ConnectionManager.CryptoKeySize);
}
var cs = csb.ToString();
if (cs.IndexOf("RequireNewInstance=", StringComparison.Ordinal) < 0)
{
if (!cs.EndsWith(";"))
{
cs += ";";
}
cs += "RequireNewInstance=True;";
}
return cs;
}
private void SetImpersonationCapability()
{
if (canImpersonate == null)
{
var query = new QueryExpression("systemuserroles")
{
Criteria = new FilterExpression
{
Conditions =
{
new ConditionExpression("systemuserid", ConditionOperator.EqualUserId)
}
},
LinkEntities =
{
new LinkEntity
{
LinkFromEntityName = "systemuserroles",
LinkFromAttributeName = "roleid",
LinkToAttributeName = "roleid",
LinkToEntityName = "role",
LinkEntities =
{
new LinkEntity
{
LinkFromEntityName = "role",
LinkFromAttributeName = "roleid",
LinkToAttributeName = "roleid",
LinkToEntityName = "roleprivileges",
EntityAlias = "priv",
Columns = new ColumnSet("privilegedepthmask"),
LinkEntities =
{
new LinkEntity
{
LinkFromEntityName = "roleprivileges",
LinkFromAttributeName = "privilegeid",
LinkToAttributeName = "privilegeid",
LinkToEntityName = "privilege", LinkCriteria = new FilterExpression
{
Conditions =
{
new ConditionExpression("name", ConditionOperator.Equal, "prvActOnBehalfOfAnotherUser"),
}
}
}
}
}
}
}
}
};
try
{
var privileges = crmSvc.RetrieveMultiple(query).Entities;
canImpersonate = privileges.Any(p =>
(int)p.GetAttributeValue<AliasedValue>("priv.privilegedepthmask").Value == 8);
}
catch
{
canImpersonate = false;
}
}
CanImpersonate = canImpersonate.Value;
}
#endregion Méthodes
public object Clone()
{
var cd = new ConnectionDetail
{
AuthType = AuthType,
ConnectionId = Guid.NewGuid(),
ConnectionName = ConnectionName,
ConnectionString = ConnectionString,
HomeRealmUrl = HomeRealmUrl,
Organization = Organization,
OrganizationFriendlyName = OrganizationFriendlyName,
OrganizationServiceUrl = OrganizationServiceUrl,
OrganizationDataServiceUrl = OrganizationDataServiceUrl,
OrganizationUrlName = OrganizationUrlName,
OrganizationVersion = OrganizationVersion,
SavePassword = SavePassword,
ServerName = ServerName,
ServerPort = ServerPort,
TimeoutTicks = TimeoutTicks,
UseIfd = UseIfd,
UserDomain = UserDomain,
UserName = UserName,
userPassword = userPassword,
WebApplicationUrl = WebApplicationUrl,
OriginalUrl = OriginalUrl,
Timeout = Timeout,
UseMfa = UseMfa,
AzureAdAppId = AzureAdAppId,
ReplyUrl = ReplyUrl,
EnvironmentText = EnvironmentText,
EnvironmentColor = EnvironmentColor,
EnvironmentTextColor = EnvironmentTextColor,
RefreshToken = RefreshToken,
S2SClientSecret = S2SClientSecret,
IsFromSdkLoginCtrl = IsFromSdkLoginCtrl,
TenantId = TenantId,
EnvironmentId = EnvironmentId,
AllowPasswordSharing = AllowPasswordSharing,
BrowserName = BrowserName,
BrowserProfile = BrowserProfile,
IsCustomAuth = IsCustomAuth,
NewAuthType = NewAuthType,
Certificate = Certificate,
ClientSecretEncrypted = ClientSecretEncrypted,
UserPasswordEncrypted = UserPasswordEncrypted,
clientSecret = clientSecret
};
if (Certificate != null)
{
cd.Certificate = new CertificateInfo
{
Issuer = Certificate.Issuer,
Thumbprint = Certificate.Thumbprint,
Name = Certificate.Name