Skip to content

Commit f0e2687

Browse files
authored
Merge pull request #169 from microsoft/release/update/211004081602
Interface Update - Bug fix for External Auth.
2 parents ba545dc + a0ffe18 commit f0e2687

File tree

5 files changed

+303
-84
lines changed

5 files changed

+303
-84
lines changed

src/GeneralTools/DataverseClient/Client/ConnectionService.cs

Lines changed: 98 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -616,8 +616,9 @@ internal ConnectionService(IOrganizationService testIOrganziationSvc , string ba
616616
/// Sets up an initialized the Dataverse Service interface.
617617
/// </summary>
618618
/// <param name="externalOrgWebProxyClient">This is an initialized organization web Service proxy</param>
619+
/// <param name="authType">Authentication Type to use</param>
619620
/// <param name="logSink">incoming Log Sink</param>
620-
internal ConnectionService(OrganizationWebProxyClientAsync externalOrgWebProxyClient, DataverseTraceLogger logSink = null)
621+
internal ConnectionService(OrganizationWebProxyClientAsync externalOrgWebProxyClient, AuthenticationType authType, DataverseTraceLogger logSink = null)
621622
{
622623
if (logSink == null)
623624
{
@@ -643,7 +644,7 @@ internal ConnectionService(OrganizationWebProxyClientAsync externalOrgWebProxyCl
643644
}
644645
UseExternalConnection = true;
645646
GenerateCacheKeys(true);
646-
_eAuthType = AuthenticationType.OAuth;
647+
_eAuthType = authType;
647648
}
648649

649650
/// <summary>
@@ -1337,82 +1338,103 @@ private async Task RefreshInstanceDetails(IOrganizationService dvService, Uri ur
13371338
// Load the organization instance details
13381339
if (dvService != null)
13391340
{
1340-
//TODO:// Add Logic here to improve perf by connecting to global disco.
1341-
Guid guRequestId = Guid.NewGuid();
1342-
logEntry.Log(string.Format("Querying Organization Instance Details. Request ID: {0}", guRequestId));
1343-
Stopwatch dtQueryTimer = new Stopwatch();
1344-
dtQueryTimer.Restart();
1345-
1346-
var request = new RetrieveCurrentOrganizationRequest() { AccessType = 0, RequestId = guRequestId };
1347-
RetrieveCurrentOrganizationResponse resp;
1348-
1349-
if (_configuration.Value.UseWebApiLoginFlow)
1341+
try
13501342
{
1351-
OrganizationResponse orgResp = await Command_WebAPIProcess_ExecuteAsync(
1352-
request, null, false, null, Guid.Empty, false, _configuration.Value.MaxRetryCount, _configuration.Value.RetryPauseTime, new CancellationToken(), uriOfInstance).ConfigureAwait(false);
1353-
try
1343+
//TODO:// Add Logic here to improve perf by connecting to global disco.
1344+
Guid trackingID = Guid.NewGuid();
1345+
logEntry.Log(string.Format("Querying Organization Instance Details. Request ID: {0}", trackingID));
1346+
Stopwatch dtQueryTimer = new Stopwatch();
1347+
dtQueryTimer.Restart();
1348+
1349+
var request = new RetrieveCurrentOrganizationRequest() { AccessType = 0, RequestId = trackingID };
1350+
RetrieveCurrentOrganizationResponse resp;
1351+
logEntry.Log(string.Format(CultureInfo.InvariantCulture, "Execute Command - RetrieveCurrentOrganizationRequest : RequestId={0}", dtQueryTimer.Elapsed.ToString()));
1352+
if (_configuration.Value.UseWebApiLoginFlow)
13541353
{
1355-
resp = (RetrieveCurrentOrganizationResponse)orgResp;
1354+
OrganizationResponse orgResp = await Command_WebAPIProcess_ExecuteAsync(
1355+
request, null, false, null, Guid.Empty, false, _configuration.Value.MaxRetryCount, _configuration.Value.RetryPauseTime, new CancellationToken(), uriOfInstance).ConfigureAwait(false);
1356+
try
1357+
{
1358+
resp = (RetrieveCurrentOrganizationResponse)orgResp;
1359+
}
1360+
catch (Exception ex)
1361+
{
1362+
dtQueryTimer.Stop();
1363+
logEntry.Log(string.Format(CultureInfo.InvariantCulture, "Failed to Executed Command - RetrieveCurrentOrganizationRequest : RequestId={1} : total duration: {0}", dtQueryTimer.Elapsed.ToString(), trackingID.ToString()), TraceEventType.Error);
1364+
logEntry.Log("************ Exception - Failed to lookup current organization information", TraceEventType.Error, ex);
1365+
throw new DataverseOperationException($"Failure to convert OrganziationResponse to requested type - request was {request.RequestName}", ex);
1366+
}
13561367
}
1357-
catch ( Exception ex )
1368+
else
13581369
{
1359-
throw new DataverseOperationException($"Failure to convert OrganziationResponse to requested type - request was {request.RequestName}", ex);
1370+
try
1371+
{
1372+
resp = (RetrieveCurrentOrganizationResponse)dvService.Execute(request);
1373+
}
1374+
catch(Exception ex)
1375+
{
1376+
dtQueryTimer.Stop();
1377+
logEntry.Log(string.Format(CultureInfo.InvariantCulture, "Failed to Executed Command - RetrieveCurrentOrganizationRequest : RequestId={1} : total duration: {0}", dtQueryTimer.Elapsed.ToString(), trackingID.ToString()), TraceEventType.Error);
1378+
logEntry.Log("************ Exception - Failed to lookup current organization information", TraceEventType.Error, ex);
1379+
throw new DataverseOperationException("Exception - Failed to lookup current organization data", ex);
1380+
}
13601381
}
1361-
}
1362-
else
1363-
{
1364-
resp = (RetrieveCurrentOrganizationResponse)dvService.Execute(request);
1365-
}
1382+
dtQueryTimer.Stop();
1383+
// Left in information mode intentionally
1384+
logEntry.Log(string.Format(CultureInfo.InvariantCulture, "Executed Command - RetrieveCurrentOrganizationRequest : RequestId={1} : total duration: {0}", dtQueryTimer.Elapsed.ToString(), trackingID.ToString()));
13661385

1367-
dtQueryTimer.Stop();
1368-
logEntry.Log(string.Format(CultureInfo.InvariantCulture, "Completed Querying Organization Instance Details, total duration: {0}", dtQueryTimer.Elapsed.ToString()));
1369-
if (resp.Detail != null)
1370-
{
1371-
_OrgDetail = new OrganizationDetail();
1372-
//Add Endpoints.
1373-
foreach (var ep in resp.Detail.Endpoints)
1386+
if (resp.Detail != null)
13741387
{
1375-
string endPointName = ep.Key.ToString();
1376-
EndpointType epd = EndpointType.OrganizationDataService;
1377-
Enum.TryParse<EndpointType>(endPointName, out epd);
1388+
_OrgDetail = new OrganizationDetail();
1389+
//Add Endpoints.
1390+
foreach (var ep in resp.Detail.Endpoints)
1391+
{
1392+
string endPointName = ep.Key.ToString();
1393+
EndpointType epd = EndpointType.OrganizationDataService;
1394+
Enum.TryParse<EndpointType>(endPointName, out epd);
13781395

1379-
if (!_OrgDetail.Endpoints.ContainsKey(epd))
1380-
_OrgDetail.Endpoints.Add(epd, ep.Value);
1381-
else
1382-
_OrgDetail.Endpoints[epd] = ep.Value;
1396+
if (!_OrgDetail.Endpoints.ContainsKey(epd))
1397+
_OrgDetail.Endpoints.Add(epd, ep.Value);
1398+
else
1399+
_OrgDetail.Endpoints[epd] = ep.Value;
1400+
}
1401+
_OrgDetail.FriendlyName = resp.Detail.FriendlyName;
1402+
_OrgDetail.OrganizationId = resp.Detail.OrganizationId;
1403+
_OrgDetail.OrganizationVersion = resp.Detail.OrganizationVersion;
1404+
_OrgDetail.EnvironmentId = resp.Detail.EnvironmentId;
1405+
_OrgDetail.TenantId = resp.Detail.TenantId;
1406+
_OrgDetail.Geo = resp.Detail.Geo;
1407+
_OrgDetail.UrlName = resp.Detail.UrlName;
1408+
1409+
OrganizationState ostate = OrganizationState.Disabled;
1410+
Enum.TryParse<OrganizationState>(_OrgDetail.State.ToString(), out ostate);
1411+
1412+
_OrgDetail.State = ostate;
1413+
_OrgDetail.UniqueName = resp.Detail.UniqueName;
1414+
_OrgDetail.UrlName = resp.Detail.UrlName;
13831415
}
1384-
_OrgDetail.FriendlyName = resp.Detail.FriendlyName;
1385-
_OrgDetail.OrganizationId = resp.Detail.OrganizationId;
1386-
_OrgDetail.OrganizationVersion = resp.Detail.OrganizationVersion;
1387-
_OrgDetail.EnvironmentId = resp.Detail.EnvironmentId;
1388-
_OrgDetail.TenantId = resp.Detail.TenantId;
1389-
_OrgDetail.Geo = resp.Detail.Geo;
1390-
_OrgDetail.UrlName = resp.Detail.UrlName;
1391-
1392-
OrganizationState ostate = OrganizationState.Disabled;
1393-
Enum.TryParse<OrganizationState>(_OrgDetail.State.ToString(), out ostate);
13941416

1395-
_OrgDetail.State = ostate;
1396-
_OrgDetail.UniqueName = resp.Detail.UniqueName;
1397-
_OrgDetail.UrlName = resp.Detail.UrlName;
1398-
}
1399-
1400-
_organization = _OrgDetail.UniqueName;
1401-
ConnectedOrgFriendlyName = _OrgDetail.FriendlyName;
1402-
ConnectedOrgPublishedEndpoints = _OrgDetail.Endpoints;
1417+
_organization = _OrgDetail.UniqueName;
1418+
ConnectedOrgFriendlyName = _OrgDetail.FriendlyName;
1419+
ConnectedOrgPublishedEndpoints = _OrgDetail.Endpoints;
14031420

1404-
// try to create a version number from the org.
1405-
OrganizationVersion = new Version("0.0.0.0");
1406-
try
1407-
{
1408-
Version outVer = null;
1409-
if (Version.TryParse(_OrgDetail.OrganizationVersion, out outVer))
1421+
// try to create a version number from the org.
1422+
OrganizationVersion = new Version("0.0.0.0");
1423+
try
14101424
{
1411-
OrganizationVersion = outVer;
1425+
if (Version.TryParse(_OrgDetail.OrganizationVersion, out Version outVer))
1426+
{
1427+
OrganizationVersion = outVer;
1428+
}
14121429
}
1430+
catch { };
1431+
logEntry.Log("Completed Parsing Organization Instance Details", TraceEventType.Verbose);
1432+
}
1433+
catch (Exception ex)
1434+
{
1435+
logEntry.Log("************ Exception - Fault While initializing client - RefreshInstanceDetails", TraceEventType.Error, ex);
1436+
throw new DataverseConnectionException("Exception - Fault While initializing client - RefreshInstanceDetails", ex);
14131437
}
1414-
catch { };
1415-
logEntry.Log("Completed Parsing Organization Instance Details", TraceEventType.Verbose);
14161438
}
14171439
}
14181440

@@ -1421,7 +1443,7 @@ private async Task RefreshInstanceDetails(IOrganizationService dvService, Uri ur
14211443
/// </summary>
14221444
/// <param name="trackingID"></param>
14231445
/// <param name="dvService"></param>
1424-
internal async Task<WhoAmIResponse> GetWhoAmIDetails(IOrganizationService dvService, Guid trackingID = default(Guid))
1446+
internal async Task<WhoAmIResponse> GetWhoAmIDetails(IOrganizationService dvService, Guid trackingID = default)
14251447
{
14261448
if (dvService != null)
14271449
{
@@ -1436,6 +1458,7 @@ private async Task RefreshInstanceDetails(IOrganizationService dvService, Uri ur
14361458
if (trackingID != Guid.Empty) // Add Tracking number of present.
14371459
req.RequestId = trackingID;
14381460

1461+
logEntry.Log(string.Format(CultureInfo.InvariantCulture, "Execute Command - WhoAmIRequest : RequestId={0}", trackingID.ToString()));
14391462
WhoAmIResponse resp;
14401463
if (_configuration.Value.UseWebApiLoginFlow)
14411464
{
@@ -1447,15 +1470,15 @@ private async Task RefreshInstanceDetails(IOrganizationService dvService, Uri ur
14471470
resp = (WhoAmIResponse)dvService.Execute(req);
14481471
}
14491472

1450-
// Left in information mode intentionaly.
1473+
// Left in information mode intentionally.
14511474
logEntry.Log(string.Format(CultureInfo.InvariantCulture, "Executed Command - WhoAmIRequest : RequestId={1} : total duration: {0}", dtQueryTimer.Elapsed.ToString(), trackingID.ToString()));
14521475
return resp;
14531476
}
14541477
catch (Exception ex)
14551478
{
14561479
logEntry.Log(string.Format(CultureInfo.InvariantCulture, "Failed to Executed Command - WhoAmIRequest : RequestId={1} : total duration: {0}", dtQueryTimer.Elapsed.ToString(), trackingID.ToString()), TraceEventType.Error);
14571480
logEntry.Log("************ Exception - Failed to lookup current user", TraceEventType.Error, ex);
1458-
throw ex;
1481+
throw new DataverseOperationException("Exception - Failed to lookup current user", ex);
14591482
}
14601483
finally
14611484
{
@@ -1537,6 +1560,8 @@ internal void SetClonedProperties(ServiceClient sourceClient)
15371560
internal async Task<OrganizationResponse> Command_WebAPIProcess_ExecuteAsync(OrganizationRequest req, string logMessageTag, bool bypassPluginExecution,
15381561
MetadataUtility metadataUtlity, Guid callerId, bool disableConnectionLocking, int maxRetryCount, TimeSpan retryPauseTime, CancellationToken cancellationToken, Uri uriOfInstance = null)
15391562
{
1563+
cancellationToken.ThrowIfCancellationRequested();
1564+
15401565
if (!Utilities.IsRequestValidForTranslationToWebAPI(req)) // THIS WILL GET REMOVED AT SOME POINT, TEMP FOR TRANSTION //TODO:REMOVE ON COMPELTE
15411566
{
15421567
logEntry.Log("Execute Organization Request failed, WebAPI is only supported for limited type of messages at this time.", TraceEventType.Error);
@@ -1558,6 +1583,7 @@ internal async Task<OrganizationResponse> Command_WebAPIProcess_ExecuteAsync(Org
15581583
if (cReq != null)
15591584
{
15601585
// if CRUD type. get Entity
1586+
cancellationToken.ThrowIfCancellationRequested();
15611587
entityMetadata = metadataUtlity.GetEntityMetadata(EntityFilters.Relationships, cReq.LogicalName);
15621588
if (entityMetadata == null)
15631589
{
@@ -1574,6 +1600,7 @@ internal async Task<OrganizationResponse> Command_WebAPIProcess_ExecuteAsync(Org
15741600

15751601
if (cReq != null)
15761602
{
1603+
cancellationToken.ThrowIfCancellationRequested();
15771604
requestBodyObject = Utilities.ToExpandoObject(cReq, metadataUtlity, methodToExecute , logEntry);
15781605
if (cReq.RelatedEntities != null && cReq.RelatedEntities.Count > 0)
15791606
requestBodyObject = Utilities.ReleatedEntitiesToExpandoObject(requestBodyObject, cReq.LogicalName, cReq.RelatedEntities, metadataUtlity, methodToExecute, logEntry);
@@ -1721,7 +1748,7 @@ internal async Task<OrganizationResponse> Command_WebAPIProcess_ExecuteAsync(Org
17211748
}
17221749

17231750
// Execute request
1724-
var sResp = await Command_WebExecuteAsync(postUri, bodyOfRequest, methodToExecute, headers, "application/json", logMessageTag, callerId, disableConnectionLocking, maxRetryCount, retryPauseTime, uriOfInstance).ConfigureAwait(false);
1751+
var sResp = await Command_WebExecuteAsync(postUri, bodyOfRequest, methodToExecute, headers, "application/json", logMessageTag, callerId, disableConnectionLocking, maxRetryCount, retryPauseTime, uriOfInstance, cancellationToken: cancellationToken).ConfigureAwait(false);
17251752
if (sResp != null && sResp.IsSuccessStatusCode)
17261753
{
17271754
if (req is CreateRequest)
@@ -1800,9 +1827,10 @@ internal async Task<OrganizationResponse> Command_WebAPIProcess_ExecuteAsync(Org
18001827
/// <param name="retryPauseTime">retry pause time</param>
18011828
/// <param name="uriOfInstance">uri of instance</param>
18021829
/// <param name="requestTrackingId"></param>
1830+
/// <param name="cancellationToken"></param>
18031831
/// <returns></returns>
18041832
internal async Task<HttpResponseMessage> Command_WebExecuteAsync(string queryString, string body, HttpMethod method, Dictionary<string, List<string>> customHeaders,
1805-
string contentType, string errorStringCheck, Guid callerId, bool disableConnectionLocking, int maxRetryCount, TimeSpan retryPauseTime, Uri uriOfInstance = null, Guid requestTrackingId = default(Guid))
1833+
string contentType, string errorStringCheck, Guid callerId, bool disableConnectionLocking, int maxRetryCount, TimeSpan retryPauseTime, Uri uriOfInstance = null, Guid requestTrackingId = default, CancellationToken cancellationToken = default)
18061834
{
18071835
Stopwatch logDt = new Stopwatch();
18081836
int retryCount = 0;
@@ -1974,6 +2002,7 @@ internal async Task<HttpResponseMessage> Command_WebExecuteAsync(string queryStr
19742002
resp = await ConnectionService.ExecuteHttpRequestAsync(
19752003
TargetUri.ToString(),
19762004
method,
2005+
cancellationToken: cancellationToken,
19772006
body: body,
19782007
customHeaders: customHeaders,
19792008
logSink: logEntry,

0 commit comments

Comments
 (0)