Skip to content

Commit

Permalink
Merge pull request #272 from microsoft/release/update/220425093423
Browse files Browse the repository at this point in the history
Sync up from Mainline branch 4/25/2022
  • Loading branch information
MattB-msft authored Apr 25, 2022
2 parents 254952f + 03ad5d5 commit 6e462a7
Show file tree
Hide file tree
Showing 17 changed files with 407 additions and 363 deletions.
10 changes: 5 additions & 5 deletions src/GeneralTools/DataverseClient/Client/Auth/AuthProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ internal async static Task<ExecuteAuthenticationResults> ExecuteAuthenticateServ
{
ClientId = clientId,
EnablePiiLogging = true,
RedirectUri = redirectUri.ToString(),
RedirectUri = redirectUri?.ToString(),
LogLevel = LogLevel.Verbose,
})
.WithAuthority(Authority)
Expand All @@ -196,7 +196,7 @@ internal async static Task<ExecuteAuthenticationResults> ExecuteAuthenticateServ
if (tokenCacheStorePath != null)
{
var f = new FileBackedTokenCache(new FileBackedTokenCacheHints(tokenCacheStorePath));
await f.Initialize(pApp.UserTokenCache);
await f.Initialize(pApp.UserTokenCache).ConfigureAwait(false);
}
}

Expand Down Expand Up @@ -241,7 +241,7 @@ internal async static Task<ExecuteAuthenticationResults> ExecuteAuthenticateServ
}
catch (MsalException ex)
{
var errorHandledResult = await ProcessMsalExecptionAsync(serviceUrl, clientCredentials, userCert, clientId, redirectUri, promptBehavior, isOnPrem, authority, msalAuthClient, logSink, useDefaultCreds, msalEx: ex, memoryBackedTokenCache: memoryBackedTokenCache, tokenCacheStorePath: tokenCacheStorePath);
var errorHandledResult = await ProcessMsalExecptionAsync(serviceUrl, clientCredentials, userCert, clientId, redirectUri, promptBehavior, isOnPrem, authority, msalAuthClient, logSink, useDefaultCreds, msalEx: ex, memoryBackedTokenCache: memoryBackedTokenCache, tokenCacheStorePath: tokenCacheStorePath).ConfigureAwait(false);
if (errorHandledResult != null)
processResult = errorHandledResult;
}
Expand Down Expand Up @@ -431,7 +431,7 @@ internal static UriBuilder GetUriBuilderWithVersion(Uri discoveryServiceUri)
}

UriBuilder versionTaggedUriBuilder = new UriBuilder(webUrlBuilder.Uri);
string version = FileVersionInfo.GetVersionInfo(typeof(Xrm.Sdk.Organization.OrganizationDetail).Assembly.Location).FileVersion;
string version = Environs.XrmSdkFileVersion;
string versionQueryStringParameter = string.Format("SDKClientVersion={0}", version);

if (string.IsNullOrEmpty(versionTaggedUriBuilder.Query))
Expand All @@ -458,7 +458,7 @@ private static async Task<AuthenticationDetails> GetAuthorityFromTargetServiceAs
{
var client = clientFactory.CreateClient("DataverseHttpClientFactory");
var resolver = new AuthorityResolver(client, (t, msg) => logger.Log(msg, t));
return await resolver.ProbeForExpectedAuthentication(targetServiceUrl, isOnPrem);
return await resolver.ProbeForExpectedAuthentication(targetServiceUrl, isOnPrem).ConfigureAwait(false);
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage
HttpResponseMessage response = null;
for (int i = 0; i < MaxRetryCount; i++)
{
response = await base.SendAsync(request, cancellationToken);
response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
return response;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Identity.Client.Extensions.Msal;
Expand Down Expand Up @@ -38,7 +38,7 @@ public FileBackedTokenCacheHints(string tokenPathAndFileName)
{
hostName = Path.GetFileNameWithoutExtension(AppDomain.CurrentDomain.FriendlyName);
}
string hostVersion = typeof(OrganizationDetail).Assembly.GetCustomAttribute<AssemblyFileVersionAttribute>().Version ?? FileVersionInfo.GetVersionInfo(typeof(OrganizationDetail).Assembly.Location).FileVersion;
string hostVersion = Environs.XrmSdkFileVersion;
string companyName = typeof(OrganizationDetail).Assembly.GetCustomAttribute<AssemblyCompanyAttribute>().Company;


Expand Down
21 changes: 11 additions & 10 deletions src/GeneralTools/DataverseClient/Client/ConnectionService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1822,10 +1822,9 @@ internal async Task<OrganizationResponse> Command_WebAPIProcess_ExecuteAsync(Org
bool? suppressDuplicateDetection = null;
if (req.Parameters.ContainsKey(Utilities.RequestHeaders.SUPPRESSDUPLICATEDETECTION))
{
if (req.Parameters[Utilities.RequestHeaders.SUPPRESSDUPLICATEDETECTION].GetType() == typeof(bool) &&
(bool)req.Parameters[Utilities.RequestHeaders.SUPPRESSDUPLICATEDETECTION])
if (req.Parameters[Utilities.RequestHeaders.SUPPRESSDUPLICATEDETECTION].GetType() == typeof(bool))
{
suppressDuplicateDetection = true;
suppressDuplicateDetection = (bool)req.Parameters[Utilities.RequestHeaders.SUPPRESSDUPLICATEDETECTION];
}
}

Expand Down Expand Up @@ -1911,7 +1910,7 @@ internal async Task<OrganizationResponse> Command_WebAPIProcess_ExecuteAsync(Org

if (suppressDuplicateDetection.HasValue)
{
headers.Add($"{Utilities.RequestHeaders.DATAVERSEHEADERPROPERTYPREFIX}{Utilities.RequestHeaders.SUPPRESSDUPLICATEDETECTION}", new List<string>() { "true" });
headers.Add($"{Utilities.RequestHeaders.DATAVERSEHEADERPROPERTYPREFIX}{Utilities.RequestHeaders.SUPPRESSDUPLICATEDETECTION}", new List<string>() { suppressDuplicateDetection.ToString() });
}

string addedQueryParams = "";
Expand Down Expand Up @@ -1963,7 +1962,7 @@ internal async Task<OrganizationResponse> Command_WebAPIProcess_ExecuteAsync(Org
}
else
{
var json = await sResp.Content.ReadAsStringAsync();
var json = await sResp.Content.ReadAsStringAsync().ConfigureAwait(false);

if (_knownTypesFactory.TryCreate($"{req.RequestName}Response", out var response, json))
{
Expand Down Expand Up @@ -2166,6 +2165,9 @@ internal async Task<HttpResponseMessage> Command_WebExecuteAsync(string queryStr
}

HttpResponseMessage resp = null;

//RequestId Logging line for telemetry
string requestIdLogSegement = logEntry.GetFormatedRequestSessionIdString(requestTrackingId, SessionTrackingId);
do
{
// Add authorization header. - Here to catch the situation where a token expires during retry.
Expand All @@ -2174,11 +2176,10 @@ internal async Task<HttpResponseMessage> Command_WebExecuteAsync(string queryStr

logDt.Restart(); // start clock.

logEntry.Log(string.Format(CultureInfo.InvariantCulture, "Execute Command - {0}{1}: RequestID={2} {3}",
logEntry.Log(string.Format(CultureInfo.InvariantCulture, "Execute Command - {0}{1}: {2}",
$"{method} {queryString}",
string.IsNullOrEmpty(errorStringCheck) ? "" : $" : {errorStringCheck} ",
requestTrackingId.ToString(),
SessionTrackingId.HasValue && SessionTrackingId.Value != Guid.Empty ? $"SessionID={SessionTrackingId.Value.ToString()} : " : ""
requestIdLogSegement
), TraceEventType.Verbose);
try
{
Expand Down Expand Up @@ -2225,7 +2226,7 @@ internal async Task<HttpResponseMessage> Command_WebExecuteAsync(string queryStr
else
{
retry = false;
logEntry.Log(string.Format(CultureInfo.InvariantCulture, "Failed to Execute Command - {3} {0} : {2}RequestID={1}", queryString, requestTrackingId.ToString(), SessionTrackingId.HasValue && SessionTrackingId.Value != Guid.Empty ? $"SessionID={SessionTrackingId.Value.ToString()} : " : "", method), TraceEventType.Verbose);
logEntry.Log(string.Format(CultureInfo.InvariantCulture, "Failed to Execute Command - {2} {0} : {1}", queryString, requestIdLogSegement, method), TraceEventType.Verbose);
logEntry.Log(string.Format(CultureInfo.InvariantCulture, "************ Exception - {2} : {0} |=> {1}", errorStringCheck, ex.Message, queryString), TraceEventType.Error, ex);
return null;
}
Expand Down Expand Up @@ -2379,7 +2380,7 @@ private bool ShouldRetryWebAPI(Exception ex, int retryCount, int maxRetryCount,
{
Agent = AppDomain.CurrentDomain.FriendlyName;
}
Agent = $"{Agent} (DataverseSvcClient:{Environs.FileVersion})";
Agent = $"{Agent} (DataverseSvcClient:{Environs.DvSvcClientFileVersion})";


if (!_httpRequest.Headers.Contains(Utilities.RequestHeaders.USER_AGENT_HTTP_HEADER))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,22 +113,7 @@ internal static string GetXrmSdkAssemblyFileVersion()
{
if (string.IsNullOrEmpty(_xrmSdkAssemblyFileVersion))
{
string[] assembliesToCheck = new string[] { "Microsoft.Xrm.Sdk.dll" };
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

foreach (var assemblyToCheck in assembliesToCheck)
{
foreach (Assembly assembly in assemblies)
{
if (assembly.ManifestModule.Name.Equals(assemblyToCheck, StringComparison.OrdinalIgnoreCase) &&
!string.IsNullOrEmpty(assembly.Location) &&
System.IO.File.Exists(assembly.Location))
{
_xrmSdkAssemblyFileVersion = FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion;
break;
}
}
}
_xrmSdkAssemblyFileVersion = Environs.XrmSdkFileVersion;
}

// If the assembly is embedded as resource and loaded from memory, there is no physical file on disk to check for file version
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,22 +169,7 @@ internal string GetXrmSdkAssemblyFileVersion()
{
if (string.IsNullOrEmpty(_xrmSdkAssemblyFileVersion))
{
string[] assembliesToCheck = { "Microsoft.Xrm.Sdk.dll" };
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

foreach (string assemblyToCheck in assembliesToCheck)
{
foreach (Assembly assembly in assemblies)
{
if (assembly.ManifestModule.Name.Equals(assemblyToCheck, StringComparison.OrdinalIgnoreCase) &&
!string.IsNullOrEmpty(assembly.Location) &&
System.IO.File.Exists(assembly.Location))
{
_xrmSdkAssemblyFileVersion = FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion;
break;
}
}
}
_xrmSdkAssemblyFileVersion = Environs.XrmSdkFileVersion;
}

// If the assembly is embedded as resource and loaded from memory, there is no physical file on disk to check for file version
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public DataverseTelemetryBehaviors(ConnectionService cli)
_userAgent = AppDomain.CurrentDomain.FriendlyName;
}

_userAgent = $"{_userAgent} (DataverseSvcClient:{Environs.FileVersion})";
_userAgent = $"{_userAgent} (DataverseSvcClient:{Environs.DvSvcClientFileVersion})";

if (_maxFaultSize == -1 && !string.IsNullOrEmpty(_configuration.Value.MaxFaultSizeOverride))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,13 @@ public void LogFailure(OrganizationRequest req, Guid requestTrackingId, Guid? se
}
}

internal string GetFormatedRequestSessionIdString( Guid requestId, Guid? sessionId )
{
return string.Format("RequestID={0} {1}",
requestId.ToString(),
sessionId.HasValue && sessionId.Value != Guid.Empty ? $": SessionID={sessionId.Value.ToString()} : " : "");
}

/// <summary>
/// Logs data to memory.
/// </summary>
Expand Down
44 changes: 30 additions & 14 deletions src/GeneralTools/DataverseClient/Client/Environs.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Diagnostics;
using Microsoft.Xrm.Sdk.Organization;
using System.Diagnostics;
using System.Reflection;

namespace Microsoft.PowerPlatform.Dataverse.Client
Expand All @@ -7,28 +8,43 @@ internal static class Environs
{
private static object _initLock = new object();

public static string FileVersion { get; private set; }
/// <summary>
/// Version number of the XrmSDK
/// </summary>
public static string XrmSdkFileVersion { get; private set; }

public static string DvSvcClientFileVersion { get; private set; }

static Environs()
{
if (string.IsNullOrEmpty(FileVersion))

if (string.IsNullOrEmpty(XrmSdkFileVersion))
{
lock(_initLock)
{
if ( string.IsNullOrEmpty(XrmSdkFileVersion))
{
XrmSdkFileVersion = "Unknown";
try
{
XrmSdkFileVersion = typeof(OrganizationDetail).Assembly.GetCustomAttribute<AssemblyFileVersionAttribute>().Version ?? FileVersionInfo.GetVersionInfo(typeof(OrganizationDetail).Assembly.Location).FileVersion;
}
catch { }
}
}
}


if (string.IsNullOrEmpty(DvSvcClientFileVersion))
{
lock (_initLock)
{
if (string.IsNullOrEmpty(FileVersion))
if (string.IsNullOrEmpty(DvSvcClientFileVersion))
{
FileVersion = "Unknown";
DvSvcClientFileVersion = "Unknown";
try
{
string location = Assembly.GetExecutingAssembly().Location;
if (!string.IsNullOrEmpty(location))
{
string version = FileVersionInfo.GetVersionInfo(location).FileVersion;
if (!string.IsNullOrEmpty(version))
{
FileVersion = version;
}
}
DvSvcClientFileVersion = typeof(ServiceClient).Assembly.GetCustomAttribute<AssemblyFileVersionAttribute>().Version ?? FileVersionInfo.GetVersionInfo(typeof(ServiceClient).Assembly.Location).FileVersion;
}
catch
{
Expand Down
Loading

0 comments on commit 6e462a7

Please sign in to comment.