Skip to content

Commit 33b6089

Browse files
authored
Merge pull request #426 from microsoft/release/update/240108092744
Resync Updates from Master Codebase.
2 parents 284c3c2 + 920182b commit 33b6089

16 files changed

+265
-127
lines changed

src/GeneralTools/DataverseClient/Client/Auth/AuthProcessor.cs

+2-4
Original file line numberDiff line numberDiff line change
@@ -327,15 +327,13 @@ internal async static Task<AuthenticationResult> ObtainAccessTokenAsync(
327327
case PromptBehavior.Auto:
328328
break;
329329
case PromptBehavior.Always:
330-
userPrompt = Microsoft.Identity.Client.Prompt.ForceLogin;
330+
case PromptBehavior.SelectAccount:
331+
userPrompt = Microsoft.Identity.Client.Prompt.SelectAccount;
331332
break;
332333
case PromptBehavior.Never:
333334
case PromptBehavior.RefreshSession:
334335
userPrompt = Microsoft.Identity.Client.Prompt.NoPrompt;
335336
break;
336-
case PromptBehavior.SelectAccount:
337-
userPrompt = Microsoft.Identity.Client.Prompt.SelectAccount;
338-
break;
339337
default:
340338
break;
341339
}

src/GeneralTools/DataverseClient/Client/Auth/OnPremises_Auth.cs

+8-6
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,8 @@ internal static object CreateAndAuthenticateProxy<T>(IServiceManagement<T> servi
3535
DataverseTraceLogger logSink = null)
3636
{
3737
bool createdLogSource = false;
38-
Stopwatch dtProxyCreate = new Stopwatch();
39-
dtProxyCreate.Start();
40-
Stopwatch dtConnectTimeCheck = new Stopwatch();
38+
Stopwatch dtProxyCreate = Stopwatch.StartNew();
39+
Stopwatch dtConnectTimeCheck = Stopwatch.StartNew();
4140
try
4241
{
4342
if (logSink == null)
@@ -54,7 +53,8 @@ internal static object CreateAndAuthenticateProxy<T>(IServiceManagement<T> servi
5453
logSink.Log(string.Format(CultureInfo.InvariantCulture, "{0} - attempting to connect to On-Premises Dataverse server @ {1}", LogString, ServiceUri.ToString()), TraceEventType.Verbose);
5554

5655
// Create the Service configuration for that URL
57-
dtConnectTimeCheck.Restart();
56+
dtConnectTimeCheck.Stop();
57+
dtConnectTimeCheck = Stopwatch.StartNew();
5858
servicecfg = ServiceConfigurationFactoryAsync.CreateManagement<T>(ServiceUri);
5959
dtConnectTimeCheck.Stop();
6060
if (servicecfg == null)
@@ -73,7 +73,8 @@ internal static object CreateAndAuthenticateProxy<T>(IServiceManagement<T> servi
7373
{
7474
// Connect via anything other then AD.
7575
// Setup for Auth Check Performance.
76-
dtConnectTimeCheck.Restart();
76+
dtConnectTimeCheck.Stop();
77+
dtConnectTimeCheck = Stopwatch.StartNew();
7778

7879
// Deal with IFD QurikyNess in ADFS configuration, where ADFS can be configured to fall though to Kerb Auth.
7980
AuthenticationCredentials authCred = ClaimsIFDFailOverAuth<T>(servicecfg, homeRealm, userCredentials);
@@ -89,7 +90,8 @@ internal static object CreateAndAuthenticateProxy<T>(IServiceManagement<T> servi
8990
{
9091
logSink.Log(string.Format(CultureInfo.InvariantCulture, "{0} - Initial Authenticated via {1} {3} . Auth Elapsed:{2}", LogString, servicecfg.AuthenticationType, dtConnectTimeCheck.Elapsed.ToString(), homeRealm.ToString()), TraceEventType.Verbose);
9192
logSink.Log(string.Format(CultureInfo.InvariantCulture, "{0} - Relaying Auth to Resource Server: From {1} to {2}", LogString, homeRealm.ToString(), servicecfg.PolicyConfiguration.SecureTokenServiceIdentifier), TraceEventType.Verbose);
92-
dtConnectTimeCheck.Restart();
93+
dtConnectTimeCheck.Stop();
94+
dtConnectTimeCheck = Stopwatch.StartNew();
9395
// Auth token against the correct server.
9496
AuthenticationCredentials authCred2 = servicecfg.Authenticate(new AuthenticationCredentials()
9597
{

src/GeneralTools/DataverseClient/Client/Auth/TokenCache/FileBackedTokenCacheHints.cs

+3-10
Original file line numberDiff line numberDiff line change
@@ -36,25 +36,18 @@ public FileBackedTokenCacheHints(string tokenPathAndFileName)
3636
string hostName = "DvBaseClient";
3737
if (AppDomain.CurrentDomain != null)
3838
{
39-
hostName = Path.GetFileNameWithoutExtension(AppDomain.CurrentDomain.FriendlyName);
40-
if (hostName.IndexOfAny(Path.GetInvalidFileNameChars()) < 0)
41-
{
42-
foreach (var c in Path.GetInvalidFileNameChars())
43-
{
44-
hostName = hostName.Replace(c, '_');
45-
}
46-
}
39+
hostName = Path.GetFileNameWithoutExtension(Utilities.CleanUpPotentialFileName(AppDomain.CurrentDomain.FriendlyName));
4740
}
4841
string hostVersion = Environs.XrmSdkFileVersion;
49-
string companyName = typeof(OrganizationDetail).Assembly.GetCustomAttribute<AssemblyCompanyAttribute>().Company;
42+
string companyName = Utilities.CleanUpPotentialFileName(typeof(OrganizationDetail).Assembly.GetCustomAttribute<AssemblyCompanyAttribute>().Company);
5043

5144

5245
if (string.IsNullOrEmpty(tokenPathAndFileName))
5346
{
5447
tokenPathAndFileName = Path.Combine(MsalCacheHelper.UserRootDirectory, companyName?.Replace(" ", "_"), hostName, hostVersion, "dvtokens.dat");
5548
}
5649

57-
System.Diagnostics.Trace.WriteLine($"TokenCacheFilePath: {tokenPathAndFileName}");
50+
Trace.WriteLine($"TokenCacheFilePath: {tokenPathAndFileName}");
5851

5952
cacheFileDirectory = Path.GetDirectoryName(tokenPathAndFileName);
6053
cacheFileName = Path.GetFileName(tokenPathAndFileName);

src/GeneralTools/DataverseClient/Client/ConnectionService.cs

+30-41
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,6 @@ internal sealed class ConnectionService : IConnectionService, IDisposable
117117
private PromptBehavior _promptBehavior; // prompt behavior
118118
private string _tokenCachePath; // user specified token cache file path
119119
private bool _isOnPremOAuth = false; // Identifies whether the connection is for OnPrem or Online Deployment for OAuth
120-
private static string _userId = null; //cached userid reading from config file
121120
private bool _isCalledbyExecuteRequest = false; //Flag indicating that the an request called by Execute_Command
122121
private bool _isDefaultCredsLoginForOAuth = false; //Flag indicating that the user is trying to login with the current user id.
123122

@@ -342,7 +341,7 @@ internal sealed class ConnectionService : IConnectionService, IDisposable
342341
/// <summary>
343342
/// Cached userid
344343
/// </summary>
345-
internal string UserId { get { return _userId; } }
344+
internal string UserId { get { return _userAccount != null ? _userAccount.Username : string.Empty; } }
346345

347346
/// <summary>
348347
/// Flag indicating that the an request called by Execute_Command used for OAuth
@@ -957,7 +956,6 @@ private void GenerateCacheKeys(bool useUniqueCacheName)
957956
{
958957
//unqueInstance = true; // this instance is unique.
959958
_authority = string.Empty;
960-
_userId = null;
961959
Guid guID = Guid.NewGuid();
962960
_ServiceCACHEName = _ServiceCACHEName + guID.ToString(); // Creating a unique instance name for the cache object.
963961
}
@@ -1064,7 +1062,7 @@ private async Task<IOrganizationService> InitServiceAsync()
10641062
{
10651063
// Dataverse Service Endpoint to work with
10661064
IOrganizationService dvService = null;
1067-
Stopwatch dtQueryTimer = new Stopwatch();
1065+
Stopwatch dtQueryTimer = Stopwatch.StartNew();
10681066
try
10691067
{
10701068
if (!IsAClone)
@@ -1406,21 +1404,6 @@ private async Task<IOrganizationService> InitServiceAsync()
14061404
return null;
14071405
}
14081406

1409-
//// Do a WHO AM I request to make sure the connection is good.
1410-
//if (!UseExternalConnection)
1411-
//{
1412-
// Guid guIntialTrackingID = Guid.NewGuid();
1413-
// logEntry.Log(string.Format("Beginning Validation of Dataverse Connection. RequestID: {0}", guIntialTrackingID.ToString()));
1414-
// dtQueryTimer.Restart();
1415-
// user = await GetWhoAmIDetails(dvService, guIntialTrackingID).ConfigureAwait(false);
1416-
// dtQueryTimer.Stop();
1417-
// logEntry.Log(string.Format(CultureInfo.InvariantCulture, "Validation of Dataverse Connection Complete, total duration: {0}", dtQueryTimer.Elapsed.ToString()));
1418-
//}
1419-
//else
1420-
//{
1421-
// logEntry.Log("External Dataverse Connection Provided, Skipping Validation");
1422-
//}
1423-
14241407
return (IOrganizationService)dvService;
14251408

14261409
}
@@ -1483,8 +1466,7 @@ private async Task<IOrganizationService> InitServiceAsync()
14831466
private async Task<IOrganizationService> DoDirectLoginAsync(bool IsOnPrem = false)
14841467
{
14851468
logEntry.Log("Direct Login Process Started", TraceEventType.Verbose);
1486-
Stopwatch sw = new Stopwatch();
1487-
sw.Start();
1469+
Stopwatch sw = Stopwatch.StartNew();
14881470

14891471
IOrganizationService dvService = null;
14901472
Uri OrgWorkingURI = null;
@@ -1600,8 +1582,7 @@ private async Task GetServerVersion(IOrganizationService dvService, Uri uriOfIns
16001582
{
16011583
Guid trackingID = Guid.NewGuid();
16021584
logEntry.Log(string.Format("Querying Organization Version. Request ID: {0}", trackingID));
1603-
Stopwatch dtQueryTimer = new Stopwatch();
1604-
dtQueryTimer.Restart();
1585+
Stopwatch dtQueryTimer = Stopwatch.StartNew();
16051586

16061587
RetrieveVersionResponse getVersionResp = null;
16071588
var request = new RetrieveVersionRequest() { RequestId = trackingID };
@@ -1680,8 +1661,7 @@ private async Task RefreshInstanceDetails(IOrganizationService dvService, Uri ur
16801661
//TODO:// Add Logic here to improve perf by connecting to global disco.
16811662
Guid trackingID = Guid.NewGuid();
16821663
logEntry.Log(string.Format("Querying Organization Instance Details. Request ID: {0}", trackingID));
1683-
Stopwatch dtQueryTimer = new Stopwatch();
1684-
dtQueryTimer.Restart();
1664+
Stopwatch dtQueryTimer = Stopwatch.StartNew();
16851665

16861666
var request = new RetrieveCurrentOrganizationRequest() { AccessType = 0, RequestId = trackingID };
16871667
RetrieveCurrentOrganizationResponse resp;
@@ -1795,8 +1775,7 @@ internal async Task<WhoAmIResponse> GetWhoAmIDetails(IOrganizationService dvServ
17951775
{
17961776
if (dvService != null)
17971777
{
1798-
Stopwatch dtQueryTimer = new Stopwatch();
1799-
dtQueryTimer.Restart();
1778+
Stopwatch dtQueryTimer = Stopwatch.StartNew();
18001779
try
18011780
{
18021781
if (trackingID == Guid.Empty)
@@ -1894,6 +1873,8 @@ internal void SetClonedProperties(ServiceClient sourceClient)
18941873
debugingCloneStateFilter++;
18951874
EnableCookieRelay = sourceClient._connectionSvc.EnableCookieRelay;
18961875
debugingCloneStateFilter++;
1876+
RequestAdditionalHeadersAsync = sourceClient._connectionSvc.RequestAdditionalHeadersAsync;
1877+
debugingCloneStateFilter++;
18971878
}
18981879
catch (Exception ex)
18991880
{
@@ -2098,8 +2079,15 @@ internal async Task<OrganizationResponse> Command_WebAPIProcess_ExecuteAsync(Org
20982079
{
20992080
postUri = $"{postUri}?{addedQueryParams}";
21002081
}
2082+
2083+
Guid userProvidedRequestId = Guid.Empty;
2084+
if (req.RequestId.HasValue && req.RequestId != Guid.Empty )
2085+
{
2086+
userProvidedRequestId = req.RequestId.Value;
2087+
}
2088+
21012089
// Execute request
2102-
var sResp = await Command_WebExecuteAsync(postUri, bodyOfRequest, methodToExecute, headers, "application/json", logMessageTag, callerId, disableConnectionLocking, maxRetryCount, retryPauseTime, uriOfInstance, cancellationToken: cancellationToken).ConfigureAwait(false);
2090+
var sResp = await Command_WebExecuteAsync(postUri, bodyOfRequest, methodToExecute, headers, "application/json", logMessageTag, callerId, disableConnectionLocking, maxRetryCount, retryPauseTime, uriOfInstance, cancellationToken: cancellationToken, requestTrackingId: userProvidedRequestId).ConfigureAwait(false);
21032091
if (sResp != null && sResp.IsSuccessStatusCode)
21042092
{
21052093
if (req is CreateRequest)
@@ -2182,7 +2170,7 @@ internal async Task<OrganizationResponse> Command_WebAPIProcess_ExecuteAsync(Org
21822170
internal async Task<HttpResponseMessage> Command_WebExecuteAsync(string queryString, string body, HttpMethod method, Dictionary<string, List<string>> customHeaders,
21832171
string contentType, string errorStringCheck, Guid callerId, bool disableConnectionLocking, int maxRetryCount, TimeSpan retryPauseTime, Uri uriOfInstance = null, Guid requestTrackingId = default, CancellationToken cancellationToken = default)
21842172
{
2185-
Stopwatch logDt = new Stopwatch();
2173+
Stopwatch logDt = Stopwatch.StartNew();
21862174
int retryCount = 0;
21872175
bool retry = false;
21882176

@@ -2350,8 +2338,8 @@ internal async Task<HttpResponseMessage> Command_WebExecuteAsync(string queryStr
23502338
// Add authorization header. - Here to catch the situation where a token expires during retry.
23512339
if (!customHeaders.ContainsKey(Utilities.RequestHeaders.AUTHORIZATION_HEADER))
23522340
customHeaders.Add(Utilities.RequestHeaders.AUTHORIZATION_HEADER, new List<string>() { string.Format("Bearer {0}", await RefreshClientTokenAsync().ConfigureAwait(false)) });
2353-
2354-
logDt.Restart(); // start clock.
2341+
logDt.Stop();
2342+
logDt = Stopwatch.StartNew();
23552343

23562344
logEntry.Log(string.Format(CultureInfo.InvariantCulture, "Execute Command - {0}{1}: {2}",
23572345
$"{method} {queryString}",
@@ -2534,7 +2522,7 @@ private bool ShouldRetryWebAPI(Exception ex, int retryCount, int maxRetryCount,
25342522
RequestId = requestTrackingId.Value;
25352523

25362524
HttpResponseMessage _httpResponse = null;
2537-
Stopwatch logDt = new Stopwatch();
2525+
Stopwatch logDt = Stopwatch.StartNew();
25382526
try
25392527
{
25402528
using (var _httpRequest = new HttpRequestMessage())
@@ -2596,7 +2584,8 @@ private bool ShouldRetryWebAPI(Exception ex, int retryCount, int maxRetryCount,
25962584

25972585
if (providedHttpClient != null)
25982586
{
2599-
logDt.Restart();
2587+
logDt.Stop();
2588+
logDt = Stopwatch.StartNew();
26002589
try
26012590
{
26022591
if (providedHttpClient.Timeout != MaxConnectionTimeout)
@@ -2613,7 +2602,8 @@ private bool ShouldRetryWebAPI(Exception ex, int retryCount, int maxRetryCount,
26132602
// Fall though logic to deal with an Http client not being passed in.
26142603
using (HttpClient httpCli = new HttpClient())
26152604
{
2616-
logDt.Restart();
2605+
logDt.Stop();
2606+
logDt = Stopwatch.StartNew();
26172607
try
26182608
{
26192609
if (httpCli.Timeout != MaxConnectionTimeout)
@@ -2805,7 +2795,7 @@ internal static async Task<OrganizationDetailCollection> DiscoverGlobalOrganizat
28052795
private static async Task<DiscoverOrganizationsResult> DiscoverOrganizations_InternalAsync(Uri discoveryServiceUri, ClientCredentials clientCredentials, X509Certificate2 loginCertificate, string clientId, Uri redirectUri, PromptBehavior promptBehavior, bool isOnPrem, string authority, bool useDefaultCreds = false, string tokenCacheStorePath = null, DataverseTraceLogger logSink = null, CancellationToken cancellationToken = default)
28062796
{
28072797
bool createdLogSource = false;
2808-
Stopwatch dtStartQuery = new Stopwatch();
2798+
Stopwatch dtStartQuery = Stopwatch.StartNew();
28092799
try
28102800
{
28112801
if (logSink == null)
@@ -2845,7 +2835,8 @@ private static async Task<DiscoverOrganizationsResult> DiscoverOrganizations_Int
28452835

28462836
try
28472837
{
2848-
dtStartQuery.Restart();
2838+
dtStartQuery.Stop();
2839+
dtStartQuery = Stopwatch.StartNew();
28492840
RetrieveOrganizationsResponse orgResponse = (RetrieveOrganizationsResponse)svcDiscoveryProxy.Execute(orgRequest);
28502841
dtStartQuery.Stop();
28512842

@@ -2973,8 +2964,7 @@ private static async Task<OrganizationDetailCollection> QueryGlobalDiscoveryAsyn
29732964
if (discoveryServiceUri == null)
29742965
throw new ArgumentNullException(nameof(discoveryServiceUri), "Discovery service uri cannot be null.");
29752966

2976-
Stopwatch dtStartQuery = new Stopwatch();
2977-
dtStartQuery.Start();
2967+
Stopwatch dtStartQuery = Stopwatch.StartNew();
29782968
// Initialize discovery service proxy.
29792969
logSink.Log("QueryGlobalDiscovery - Initializing Discovery Server Uri with " + discoveryServiceUri.ToString());
29802970

@@ -3143,10 +3133,9 @@ private async Task<IOrganizationService> ConnectAndInitServiceAsync(Organization
31433133

31443134
// Set the Org into system config
31453135
_organization = orgdata.UniqueName;
3146-
ConnectedOrganizationDetail = orgdata;
3136+
ConnectedOrganizationDetail = orgdata;
31473137

3148-
var logDt = new Stopwatch();
3149-
logDt.Start();
3138+
var logDt = Stopwatch.StartNew();
31503139
// Build User Credential
31513140
logEntry.Log("ConnectAndInitService - Initializing Organization Service Object", TraceEventType.Verbose);
31523141
// this to provide trouble shooting information when determining org connect failures.

src/GeneralTools/DataverseClient/Client/DataverseTelemetryBehaviors.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -96,9 +96,9 @@ public DataverseTelemetryBehaviors(ConnectionService cli)
9696
logg.Log($"Failed to parse MaxReceivedMessageSizeOverride property. Value found: {maxRecvSz}. MaxReceivedMessageSizeOverride must be a valid integer.", System.Diagnostics.TraceEventType.Warning);
9797
}
9898

99-
if (_maxBufferPoolSize == -1 && !string.IsNullOrEmpty(_configuration.Value.MaxBufferPoolSizeOveride))
99+
if (_maxBufferPoolSize == -1 && !string.IsNullOrEmpty(_configuration.Value.MaxBufferPoolSizeOverride))
100100
{
101-
var maxBufferPoolSz = _configuration.Value.MaxBufferPoolSizeOveride;
101+
var maxBufferPoolSz = _configuration.Value.MaxBufferPoolSizeOverride;
102102
if (maxBufferPoolSz is string && !string.IsNullOrWhiteSpace(maxBufferPoolSz))
103103
{
104104
int.TryParse(maxBufferPoolSz, out _maxBufferPoolSize);

0 commit comments

Comments
 (0)