Get CrmServiceClient Error Log using Tracing

When working on  new integrations, updating connection strings, onetime jobs we would often rely on creating a connection string and making sure that it works with CrmServiceClient to instantiate a connection to the target org.

However, we sometimes face connection issues be it either due to typos, TLS 1.2 or other, we do not get a detailed error message from the CrmServiceClient which makes this process of successfully authenticating to Dynamics a little bit tedious.

In order to quickly identify the root cause of the issue we could leverage tracing to get more information.

For this example let's consider when the connection string has a typo(agreed, not a common use case in real world) on the URL. Now when we retrieve the CrmServiceClient we notice the below error which isn't much helpful.

We could use the below  quick and dirty code which uses the TextWriterTraceListener to enable tracing and get the detailed error information

Stream stream = new MemoryStream();
StreamWriter streamWriter = new StreamWriter(stream, Encoding.UTF8);
TextWriterTraceListener twtl = new TextWriterTraceListener(streamWriter);
TraceControlSettings.TraceLevel = SourceLevels.All;
CrmServiceClient crmService = new CrmServiceClient(dynamicsConnectionString);
string traceText = GetTextFromStream(stream);

public static string GetTextFromStream(Stream stream)
byte[] bytes = new byte[stream.Length];
stream.Position = 0;
stream.Read(bytes, 0, (int)stream.Length);
string data = Encoding.UTF8.GetString(bytes);
return data;

In the above example if we take a look at the trace we would now find the detailed error information which indicates that something is wrong with our URL.

Of course if you do not want to use any of this code and want a better way to quickly get the information you could just use the Plugin Registration, Configuration Migration tool etc. from the SDK tools. On the login screen we can use the same information from our failing connection string and get the trace information by looking at the error logs.

Hope this helps!