Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 23 additions & 9 deletions src/GeneralTools/CDSClient/Client/CdsConnectionService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,12 +113,7 @@ internal sealed class CdsConnectionService : ICdsConnectionService, IDisposable
/// Defaulted to true.
/// </summary>
private bool _enableCookieRelay = Utils.AppSettingsHelper.GetAppSetting<bool>("PreferConnectionAffinity", true);

/// <summary>
/// switch for actions that should run only once.
/// </summary>
//private bool firstPass = true;


/// <summary>
/// last Authentication Response from oAuth.
/// </summary>
Expand Down Expand Up @@ -761,7 +756,21 @@ private IOrganizationService GetCachedCDSService(out CdsConnectionService Connec
{
// try to get the object from Memory .
if (!string.IsNullOrEmpty(_ServiceCACHEName))
ConnectionObject = (CdsConnectionService)System.Runtime.Caching.MemoryCache.Default[_ServiceCACHEName];
{
try
{
var objProspectiveCachedClient = System.Runtime.Caching.MemoryCache.Default[_ServiceCACHEName];
if (objProspectiveCachedClient != null && objProspectiveCachedClient is CdsConnectionService)
ConnectionObject = (CdsConnectionService)objProspectiveCachedClient;
else
ConnectionObject = null;
}
catch(Exception ex)
{
logEntry?.Log("Failed to get cached service object from memory", TraceEventType.Warning, ex);
ConnectionObject = null;
}
}
else
ConnectionObject = null;
if (ConnectionObject == null)
Expand All @@ -773,6 +782,8 @@ private IOrganizationService GetCachedCDSService(out CdsConnectionService Connec

if (!string.IsNullOrEmpty(_ServiceCACHEName))
{
if (System.Runtime.Caching.MemoryCache.Default.Contains(_ServiceCACHEName))
System.Runtime.Caching.MemoryCache.Default.Remove(_ServiceCACHEName);
// Cache the Service for 5 min.
System.Runtime.Caching.MemoryCache.Default.Add(_ServiceCACHEName, this, DateTime.Now.AddMinutes(5));
}
Expand Down Expand Up @@ -1386,6 +1397,8 @@ internal void SetClonedProperties(CdsServiceClient sourceClient)
/// <param name="requestTrackingId">ID of the request if set by an external caller</param>
/// <param name="contentType">content type to use when calling into the remote host</param>
/// <param name="sessionTrackingId">Session Tracking ID to assoicate with the request.</param>
/// <param name="providedHttpClient"></param>
/// <param name="suppressDebugMessage"></param>
/// <returns></returns>
internal static async Task<HttpResponseMessage> ExecuteHttpRequestAsync(string uri, HttpMethod method, string body = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken), CdsTraceLogger logSink = null, Guid? requestTrackingId = null, string contentType = default(string), Guid? sessionTrackingId = null , bool suppressDebugMessage = false , HttpClient providedHttpClient = null)
{
Expand Down Expand Up @@ -2517,7 +2530,9 @@ private async Task<IOrganizationService> ConnectAndInitCdsOrgService(Organizatio
OrganizationVersion = null;
try
{
OrganizationVersion = new Version(orgdata.OrganizationVersion);
Version tempVer = null;
if ( Version.TryParse(orgdata.OrganizationVersion, out tempVer))
OrganizationVersion = tempVer;
}
catch { };

Expand Down Expand Up @@ -2696,7 +2711,6 @@ private Uri BuildOrgConnectUri(OrganizationDetail orgdata)
/// Iterates through the list of CRM online Discovery Servers to find one that knows the user.
/// </summary>
/// <param name="onlineServerList"></param>
/// <param name="useO365Servers"></param>
private CdsOrgList FindCdsDiscoveryServer(CdsDiscoveryServers onlineServerList)
{
CdsOrgList orgsList = new CdsOrgList();
Expand Down
295 changes: 193 additions & 102 deletions src/GeneralTools/CDSClient/Client/CdsServiceClient.cs

Large diffs are not rendered by default.

141 changes: 58 additions & 83 deletions src/GeneralTools/CDSClient/Client/CdsTraceLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
using Microsoft.Xrm.Sdk;
using System.Collections.Generic;
using System.Collections.Concurrent;
using Microsoft.Rest;
using Newtonsoft.Json.Linq;

namespace Microsoft.PowerPlatform.Cds.Client
{
Expand Down Expand Up @@ -139,15 +141,25 @@ public override void Log(string message, TraceEventType eventType, Exception exc
lastMessage.AppendLine(message); // Added to fix missing last error line.
detailedDump.AppendLine(message); // Added to fix missing error line.

if (!(exception != null && _ActiveExceptionsList.Contains(exception))) // Skip this line if its allready been done.
if (!(exception != null && _ActiveExceptionsList.Contains(exception))) // Skip this line if its already been done.
GetExceptionDetail(exception, detailedDump, 0, lastMessage);

TraceEvent(eventType, (int)eventType, detailedDump.ToString());
if (eventType == TraceEventType.Error)
{
base.LastError.Append(lastMessage.ToString());
if (!(exception != null && _ActiveExceptionsList.Contains(exception))) // Skip this line if its allready been done.
LastException = exception;
if (!(exception != null && _ActiveExceptionsList.Contains(exception))) // Skip this line if its already been done.
{
// check and or alter the exception is its and HTTPOperationExecption.
if (exception is HttpOperationException httpOperationException)
{
JObject contentBody = JObject.Parse(httpOperationException.Response.Content);
Utils.CdsClientOperationException webApiExcept = new Utils.CdsClientOperationException(string.IsNullOrEmpty(contentBody["error"]["message"]?.ToString()) ? "Not Provided" : GetFirstLineFromString(contentBody["error"]["message"]?.ToString()).Trim(), httpOperationException);
LastException = webApiExcept;
}
else
LastException = exception;
}
}
_ActiveExceptionsList.Add(exception);

Expand Down Expand Up @@ -307,61 +319,34 @@ private void GetExceptionDetail(object objException, StringBuilder sw, int level
}
else
{
// if (objException is FaultException<DeploymentServiceFault>)
//{
// FaultException<DeploymentServiceFault> DeploymentFault = (FaultException<DeploymentServiceFault>)objException;
// FormatExceptionMessage(
// DeploymentFault.Source != null ? DeploymentFault.Source.ToString().Trim() : "Not Provided",
// DeploymentFault.TargetSite != null ? DeploymentFault.TargetSite.Name.ToString() : "Not Provided",
// DeploymentFault.Detail != null ? string.Format(CultureInfo.InvariantCulture, "Message: {0}\nErrorCode: {1}\n", DeploymentFault.Detail.Message, DeploymentFault.Detail.ErrorCode) :
// string.IsNullOrEmpty(DeploymentFault.Message) ? "Not Provided" : DeploymentFault.Message.ToString().Trim(),
// string.IsNullOrEmpty(DeploymentFault.StackTrace) ? "Not Provided" : DeploymentFault.StackTrace.ToString().Trim()
// , sw, level);

// lastErrorMsg.Append(DeploymentFault.Detail != null ? DeploymentFault.Detail.Message :
// string.IsNullOrEmpty(DeploymentFault.Message) ? string.Empty : DeploymentFault.Message.ToString().Trim());

// if (lastErrorMsg.Length > 0 && (DeploymentFault.InnerException != null || DeploymentFault.Detail != null && DeploymentFault.Detail.InnerFault != null))
// lastErrorMsg.Append(" => ");

// level++;
// if ((DeploymentFault.InnerException != null || DeploymentFault.Detail != null && DeploymentFault.Detail.InnerFault != null))
// GetExceptionDetail(DeploymentFault.Detail != null && DeploymentFault.Detail.InnerFault != null ? DeploymentFault.Detail.InnerFault : (object)DeploymentFault.InnerException,
// sw, level, lastErrorMsg);

// return;

//}
//else
// if (objException is DeploymentServiceFault)
//{
// DeploymentServiceFault oFault = (DeploymentServiceFault)objException;

// StringBuilder errorText = new StringBuilder();
// if (oFault.ErrorDetails != null && oFault.ErrorDetails.Count > 0)
// foreach (var er in oFault.ErrorDetails)
// {
// errorText.AppendLine(string.Format(CultureInfo.InvariantCulture, "\t{0} raising error : {1}", er.Key, er.Value));
// }

// FormatDeploymentFaultMessage(
// string.IsNullOrEmpty(oFault.Message) ? "Not Provided" : oFault.Message.ToString().Trim(),
// oFault.Timestamp.ToString(),
// oFault.ErrorCode.ToString(), errorText.ToString(), sw, level);

// level++;

// lastErrorMsg.Append(oFault.Message);
// if (lastErrorMsg.Length > 0 && oFault.InnerFault != null)
// lastErrorMsg.Append(" => ");

// if (oFault.InnerFault != null)
// GetExceptionDetail(oFault.InnerFault, sw, level, lastErrorMsg);

// return;

//}
//else
if (objException is HttpOperationException httpOperationException)
{
JObject contentBody = JObject.Parse(httpOperationException.Response.Content);

FormatExceptionMessage(
httpOperationException.Source != null ? httpOperationException.Source.ToString().Trim() : "Not Provided",
httpOperationException.TargetSite != null ? httpOperationException.TargetSite.Name?.ToString() : "Not Provided",
string.IsNullOrEmpty(contentBody["error"]["message"]?.ToString()) ? "Not Provided" : GetFirstLineFromString(contentBody["error"]["message"]?.ToString()).Trim(),
string.IsNullOrEmpty(contentBody["error"]["stacktrace"]?.ToString()) ? "Not Provided" : contentBody["error"]["stacktrace"]?.ToString().Trim()
, sw, level);

lastErrorMsg.Append(string.IsNullOrEmpty(httpOperationException.Message) ? "Not Provided" : httpOperationException.Message.ToString().Trim());

// WebEx currently only returns 1 leve of error.
var InnerError = contentBody["error"]["innererror"];
if (lastErrorMsg.Length > 0 && InnerError != null)
{
level++;
lastErrorMsg.Append(" => ");
FormatExceptionMessage(
httpOperationException.Source != null ? httpOperationException.Source.ToString().Trim() : "Not Provided",
httpOperationException.TargetSite != null ? httpOperationException.TargetSite.Name?.ToString() : "Not Provided",
string.IsNullOrEmpty(InnerError["message"]?.ToString()) ? "Not Provided" : GetFirstLineFromString(InnerError["message"]?.ToString()).Trim(),
string.IsNullOrEmpty(InnerError["stacktrace"]?.ToString()) ? "Not Provided" : InnerError["stacktrace"]?.ToString().Trim()
, sw, level);
}
}
else
if (objException is Exception)
{
Exception generalEx = (Exception)objException;
Expand All @@ -386,6 +371,21 @@ private void GetExceptionDetail(object objException, StringBuilder sw, int level
return;
}

/// <summary>
/// returns the first line from the text block.
/// </summary>
/// <param name="textBlock"></param>
/// <returns></returns>
internal static string GetFirstLineFromString(string textBlock)
{
if (!string.IsNullOrEmpty(textBlock))
{
if (textBlock.Contains(Environment.NewLine))
return textBlock.Substring(0, textBlock.IndexOf(Environment.NewLine));
}
return textBlock;
}

/// <summary>
/// Formats the detail collection from a service exception.
/// </summary>
Expand Down Expand Up @@ -451,31 +451,6 @@ private static void FormatOrgFaultMessage(string message, string timeOfEvent, st
sw.AppendLine("Trace\t: " + traceText);
sw.AppendLine("======================================================================================================================");
}

/// <summary>
/// Formats an Exception specific to an Deployment fault.
/// </summary>
/// <param name="message">Exception Message</param>
/// <param name="timeOfEvent">Time occurred</param>
/// <param name="errorCode">Error code of message</param>
/// <param name="traceTextList">Message Text</param>
/// <param name="sw">Writer to write too</param>
/// <param name="level">Depth</param>
private static void FormatDeploymentFaultMessage(string message, string timeOfEvent, string errorCode, string traceTextList, StringBuilder sw, int level)
{
if (level != 0)
sw.AppendLine(string.Format(CultureInfo.InvariantCulture, "Inner Exception Level {0}\t: ", level));
sw.AppendLine("==DeploymentServiceFault Info==========================================================================================");
sw.AppendLine("Error\t: " + message);
sw.AppendLine("Time\t: " + timeOfEvent);
sw.AppendLine("ErrorCode\t: " + errorCode);
sw.AppendLine("Date\t: " + DateTime.Now.ToShortDateString());
sw.AppendLine("Time\t: " + DateTime.Now.ToLongTimeString());
sw.AppendLine("Error Items:");
sw.AppendLine(traceTextList);
sw.AppendLine("======================================================================================================================");
}

}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@

<PropertyGroup>
<GeneratePackageOnBuild>false</GeneratePackageOnBuild>
<DocumentationFile>$(OutDir)\Microsoft.PowerPlatform.Cds.Client.xml</DocumentationFile>
</PropertyGroup>


<ItemGroup>
<Compile Remove="UnitTestBehaviors\**" />
<Compile Remove="UnitTests\**" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,6 @@ public CdsDiscoveryServer GetServerByOrgUrl ( Uri orgUri )
/// Finds a Server by Name in the List or return null.
/// </summary>
/// <param name="shortName">Short Name of the server you are looking for</param>
/// <param name="isO365">if set, uses the office 365 server list.</param>
/// <returns>CdsDiscoveryServer Data or Null</returns>
public CdsDiscoveryServer GetServerByShortName(string shortName)
{
Expand Down Expand Up @@ -130,7 +129,6 @@ public CdsDiscoveryServer GetServerByGeo(string geoCode)
/// Finds the server short name by server uri
/// </summary>
/// <param name="serverDisplayName">Name of the Server to find</param>
/// <param name="isO365">if set, uses the office 365 server list.</param>
/// <returns></returns>
public string GetServerShortNameByDisplayName(string serverDisplayName)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace Microsoft.PowerPlatform.Cds.Client.Utils
{
/// <summary>
/// Used to encompass a ServiceClient Connection Centric exceptions
/// </summary>
[Serializable]
public class CdsClientConnectionException : Exception
{
/// <summary>
/// Creates a CdsService Client Exception
/// </summary>
/// <param name="message">Error Message</param>
public CdsClientConnectionException(string message)
: base(message)
{
}

/// <summary>
/// Creates a CdsService Client Exception
/// </summary>
/// <param name="message">Error Message</param>
/// <param name="innerException">Supporting Exception</param>
public CdsClientConnectionException(string message, Exception innerException)
: base(message, innerException)
{
}

/// <summary>
/// Creates a CdsService Client Exception
/// </summary>
/// <param name="serializationInfo"></param>
/// <param name="streamingContext"></param>
protected CdsClientConnectionException(SerializationInfo serializationInfo, StreamingContext streamingContext)
: base(serializationInfo, streamingContext)
{
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace Microsoft.PowerPlatform.Cds.Client.Utils
{
/// <summary>
/// Used to encompass a ServiceClient Operation Exception
/// </summary>
[Serializable]
public class CdsClientOperationException : Exception
{
/// <summary>
/// Creates a CdsService Client Exception
/// </summary>
/// <param name="message">Error Message</param>
public CdsClientOperationException(string message)
: base(message)
{
}

/// <summary>
/// Creates a CdsService Client Exception
/// </summary>
/// <param name="message">Error Message</param>
/// <param name="innerException">Supporting Exception</param>
public CdsClientOperationException(string message, Exception innerException)
: base(message, innerException)
{
}

/// <summary>
/// Creates a CdsService Client Exception
/// </summary>
/// <param name="serializationInfo"></param>
/// <param name="streamingContext"></param>
protected CdsClientOperationException(SerializationInfo serializationInfo, StreamingContext streamingContext)
: base(serializationInfo, streamingContext)
{
}
}
}
Loading