Problem
Bugs and there handling are very important for each software developer. Often bugs are detected during internal test processes. But it’s also common that a bug appears the first time on a customer machine. In this case is important to log the exception / problem and to report this to the developer. Weiterhin ist das Schreiben von guten Logs nicht selbstverständlich, dies soll allerdings nicht Thema diesem Blogeintrag sein. It’s clear that good logs are important, but the technics to write good logs are not part of this blog entry.

An example of an log is the stack trace. A stack trace describes the last process steps if an unhandled exception is thrown.In this example we throw an exception in the method “test”. The log shows you the source code file and the line.

1
2
3
4
   bei System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
   bei System.Environment.get_StackTrace()
   bei ConsoleApp2.Program.test(Int32 wert) in C:\\Users\\lpl\\source\\repos\\ConsoleApp2\\ConsoleApp2\\Program.cs:Zeile 31.
   bei ConsoleApp2.Program.Main(String[] args) in C:\\Users\\lpl\\source\\repos\\ConsoleApp2\\ConsoleApp2\\Program.cs:Zeile 16.

As you see in the stack trace above, the trace gives you a good hint where the error could be. But it’s not clear which parameter are used to call the method “test”, that this error appears. Also this used local variables and there values are not listed. These kind of information are often very important and gives you a better hint of that error. Often developers spent a lot of time to extract this kind of data. On technic is to reproduce that error, so that the developer is able to see the values with his debugger.

Soluction

Based on this, I started to search for option to get this information’s and values automatically, bevor a developer start to this about this issue. In my mind formed a tool that runs as a service on a client machine. And observes a process if any unhandled exceptions are thrown, so that this process is able to catch all needed information. Surly this kind of tool need to be fast and small, that it’s not blocking or interfering the main process.
I found the library MdbEngine. This library is a mobile debugger, like the debugger on a developer machine. This debugger is able to catch the same information’s as a developer with there debugger.

This code below shows you how to you the MdbEngine debugger. First of all you need to attach the debugger to a process. For that you need the process id. Additionally you need a workaround right after the start.

1
2
3
4
5
6
7
8
9
10
11
12
13
_symbolPath = Uri.UnescapeDataString(symbolPath);
_engine=new MDbgEngine();
_engine.Options.SymbolPath = _symbolPath;
_process = _engine.Attach(processID);
_process.SymbolPath = _symbolPath;
_process.Go().WaitOne();

if (!(_process.StopReason is AttachCompleteStopReason))
throw new System.Exception("Unexpected");

_process.Go();

_process.PostDebugEvent += ProcessOnPostDebugEvent;

With the PostDebugEvent we get a notification on a debug event. This means also on each exception.

1
2
3
4
5
6
7
8
9
10
11
private void ProcessOnPostDebugEvent(object sender, CustomPostCallbackEventArgs e)
        {
            try
            {
                Process(sender, e);
            }
            catch (System.Exception)
            {

            }
        }

In der eigentlichen Verarbeitung gibt es zunächst einen Filter auf den Debugeventtyp. Zusätzlich wird geprüft ob der Exceptionname nicht null ist.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
if (e.CallbackType != ManagedCallbackType.OnException2)
            return;
CorException2EventArgs exception;
exception = (CorException2EventArgs)e.CallbackArgs;

if (exception.EventType == CorDebugExceptionCallbackType.DEBUG_EXCEPTION_FIRST_CHANCE ||
    exception.EventType == CorDebugExceptionCallbackType.DEBUG_EXCEPTION_USER_FIRST_CHANCE)
{
    MDbgThread thread; thread = _process.Threads.Lookup(exception.Thread);
   
    Exception exceptionResult = new Exception();
    if (thread.CurrentException.Name != null)
    {
        exceptionResult.Name = thread.CurrentException.Name;
        exceptionResult.Value = thread.CurrentException.Value;
    }
    exceptionResult.TypeName = thread.CurrentException.TypeName;

In a loop we read out all local variables and all parameters. We cut the stack trace after the first 10 frames. Normally the first 10 are enough, if you need more feel free to increase it. Just make sure that you do not ran into a performance issue, because your process is stopped at this point. Your process can only continue if you leave this method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
var maxCount = 10;
var count = 0;
foreach (var frame in thread.Frames)
{
    if (frame.Function == null)
        continue;

    if (count >= maxCount)
        break;
    count++;

    var frameResult = new Frame();
    if (frame.SourcePosition != null)
    {
        frameResult.Path = frame.SourcePosition.Path;
        frameResult.Line = frame.SourcePosition.Line;

    }

    frameResult.FunctionName = frame.Function.FullName;
    if (frame.IsManaged && !frame.IsInfoOnly)
    {
        try
        {
            foreach (var argument in frame.Function.GetArguments(frame))
            {
                var value = GetValue(argument);
                if (value != null)
                    frameResult.Parameter.Add(value);
            }
        }
        catch (System.Exception)
        {

        }


        try
        {
            foreach (var variable in frame.Function.GetActiveLocalVars(frame))
            {
                var value = GetValue(variable);
                if (value != null)
                    frameResult.LocalVariables.Add(value);
            }
        }
        catch (System.Exception)
        {

        }

    }

    exceptionResult.Frames.Add(frameResult);
}
CreateTraceFile(thread.CurrentException.CorValue.Raw.GetHashCode() + "_" + thread.CurrentException.CorValue.Address, exceptionResult);

We save all these values into a Json file. Additionally we need to define how we handle with complex types. We cannot use the object internal toString() method, because it’s not clear if the method is correctly implemented. What we get from the MdbEngine, is to print all members of an object. So that we roll out an object into their peace’s. we just need to define how deep we would like to go. Also make sure that you exclude some namespaces. Normally we do not need to roll out a foreign GUI object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
private Value GetValue(MDbgValue aValue)
{
   
    try
    {
        Value value = new Value();
        value.Name = aValue.Name;
        if (aValue.IsNull)
        {
            value.TypeName = aValue.TypeName;
            value.ValueO = "null";
        }
        else
        {
            value.TypeName = aValue.TypeName;
            value.ValueO = expandValue(aValue);
           
        }

        return value;
    }
    catch (System.Exception)
    {
        return null;
    }
}

private string expandValue(MDbgValue value)
{
    if(value.TypeName.Contains("WebControls") ||
       value.TypeName.Contains("ascx") ||
       value.TypeName.Contains("ASP") ||
       value.TypeName.Contains("System.Web"))
        return value.GetStringValue(0);

    int level = 0;
    string result = "";
    while (level <= 3)
    {
        try
        {
            result = value.GetStringValue(level);
            level++;
        }
        catch (System.Exception)
        {
            return result;
        }
    }

    return result;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Options
{

[Value(0, Required = true, MetaName = "ProcessID",
HelpText = "ID off Process")]
public int ProcessID { get; set; }

[Value(1, Required = true , MetaName = "FilePath",
HelpText = @"Path to folder where debug files are saved.
HttpRuntime.AppDomainAppPath + \"
\\\\App_Data\\\\TraceFiles\\\\\" ")]
public string FilePath { get; set; }

[Value(2, Required = true, MetaName = "SymbolPath",
HelpText = @"Path to folder where dlls and symbols are stored.
HttpRuntime.AppDomainAppPath + \"
\\\\bin\" ")]
public string SymbolPath { get; set; }
}

static void Main(string[] args)
{
CommandLine.Parser.Default.ParseArguments
<options>(args)
.WithParsed
<options>(Start);</options></options>

AppDomain appDomain = AppDomain.CurrentDomain;
appDomain.ProcessExit += new EventHandler(OnClose);
while (true)
{
Thread.Sleep(1000);
}
}

private static void Start(Options obj)
{
stackTrace = new StackTraceDataCollectorService(obj.ProcessID, obj.FilePath, obj.SymbolPath);
}
}

Das Ergebnis sieht nun wie folgt aus.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
{
    "Name": null,
    "Value": null,
    "TypeName": "System.Exception",
    "Frames": [
        {
            "Path": "source\\\\repos\\\\ConsoleApp2\\\\ConsoleApp2\\\\Program.cs",
            "Line": 35,
            "FunctionName": "ConsoleApp2.Program.test",
            "Parameter": [
                {
                    "Name": "wert",
                    "TypeName": "N/A",
                    "ValueO": "null"
                },
                {
                    "Name": "wert2",
                    "TypeName": "System.Int32",
                    "ValueO": "2"
                },
                {
                    "Name": "StringValue",
                    "TypeName": "System.String",
                    "ValueO": "\"myvalue\""
                }
            ],
            "LocalVariables": [
                {
                    "Name": "b",
                    "TypeName": "System.Int32",
                    "ValueO": "1"
                }
            ]
        },
        {
            "Path": "source\\\\repos\\\\ConsoleApp2\\\\ConsoleApp2\\\\Program.cs",
            "Line": 17,
            "FunctionName": "ConsoleApp2.Program.Main",
            "Parameter": [
                {
                    "Name": "args",
                    "TypeName": "N/A",
                    "ValueO": "null"
                }
            ],
            "LocalVariables": []
        }
    ],
    "DateTime": "2019-10-29T09:41:18.8572539+01:00"
}

Weiter unten finden Sie die Sourcen.

Program.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using Microsoft.Samples.Debugging.CorDebug;
using Microsoft.Samples.Debugging.CorDebug.NativeApi;
using Microsoft.Samples.Debugging.MdbgEngine;
using CommandLine;

namespace StackTraceApp
{
class Program
{
private static StackTrace stackTrace
class Options
{

[Value(0, Required = true, MetaName = "ProcessID",
HelpText = "ID off Process")]
public int ProcessID { get; set; }

[Value(1, Required = true , MetaName = "FilePath",
HelpText = @"Path to folder where debug files are saved.
HttpRuntime.AppDomainAppPath + \"
\\\\App_Data\\\\TraceFiles\\\\\" ")]
public string FilePath { get; set; }

[Value(2, Required = true, MetaName = "SymbolPath",
HelpText = @"Path to folder where dlls and symbols are stored.
HttpRuntime.AppDomainAppPath + \"
\\\\bin\" ")]
public string SymbolPath { get; set; }
}

static void Main(string[] args)
{
CommandLine.Parser.Default.ParseArguments
<options>(args)
.WithParsed
<options>(Start);</options></options>

AppDomain appDomain = AppDomain.CurrentDomain;
appDomain.ProcessExit += new EventHandler(OnClose);
while (true)
{
Thread.Sleep(1000);
}
}

private static void OnClose(object sender, EventArgs e)
{
stackTrace.Close();
}

private static void Start(Options obj)
{
stackTrace = new StackTraceDataCollectorService(obj.ProcessID, obj.FilePath, obj.SymbolPath);
}
}

}

StackTraceService.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Web;
using Microsoft.Samples.Debugging.CorDebug;
using Microsoft.Samples.Debugging.CorDebug.NativeApi;
using Microsoft.Samples.Debugging.MdbgEngine;
using Newtonsoft.Json;

namespace StackTraceApp {
 public class StackTraceService {
  private MDbgEngine _engine;
  private MDbgProcess _process;
  private string _filePath;
  private string _symbolPath;

  public StackTraceService(int processID, string filePath, string symbolPath) {

   _filePath = Uri.UnescapeDataString(filePath);
   _symbolPath = Uri.UnescapeDataString(symbolPath);
   _engine = new MDbgEngine();
   _engine.Options.SymbolPath = _symbolPath;
   _process = _engine.Attach(processID);
   _process.SymbolPath = _symbolPath;
   _process.Go().WaitOne();

   if (!(_process.StopReason is AttachCompleteStopReason))
    throw new System.Exception("Unexpected");

   _process.Go();

   _process.PostDebugEvent += ProcessOnPostDebugEvent;

   System.Timers.Timer aTimer = new System.Timers.Timer();
   aTimer.Elapsed += new ElapsedEventHandler(CleanUp);
   aTimer.Interval = 60000;
   aTimer.Enabled = true;
   aTimer.AutoReset = true;

   AllCleanUp();
  }

  public void Close() {
   _process.Detach();
  }

  private void AllCleanUp() {
   if (!Directory.Exists(_filePath)) {
    Directory.CreateDirectory(_filePath);
   }

   System.IO.DirectoryInfo di = new DirectoryInfo(_filePath);

   foreach(FileInfo file in di.GetFiles()) {
    file.Delete();
   }
  }

  private void CleanUp(object sender, ElapsedEventArgs e) {
   if (!Directory.Exists(_filePath)) {
    Directory.CreateDirectory(_filePath);
   }

   System.IO.DirectoryInfo di = new DirectoryInfo(_filePath);

   foreach(FileInfo file in di.GetFiles()) {
    if (file.CreationTime.AddMinutes(30) & lt; = DateTime.Now) {
     file.Delete();
    }
   }
  }
  private void ProcessOnPostDebugEvent(object sender, CustomPostCallbackEventArgs e) {
   try {
    Process(sender, e);
   } catch (System.Exception) {}
  }
  private void Process(object sender, CustomPostCallbackEventArgs e) {
   if (e.CallbackType != ManagedCallbackType.OnException2) return;
   CorException2EventArgs exception;
   exception = (CorException2EventArgs) e.CallbackArgs;
   if (exception.EventType == CorDebugExceptionCallbackType.DEBUG_EXCEPTION_FIRST_CHANCE || exception.EventType == CorDebugExceptionCallbackType.DEBUG_EXCEPTION_USER_FIRST_CHANCE) {
    MDbgThread thread;
    thread = _process.Threads.Lookup(exception.Thread);
    Exception exceptionResult = new Exception();
    if (thread.CurrentException.Name != null) {
     exceptionResult.Name = thread.CurrentException.Name;
     exceptionResult.Value = thread.CurrentException.Value;
    }
    exceptionResult.TypeName = thread.CurrentException.TypeName;
    var maxCount = 10;
    var count = 0;
    bool wasSPData = false;
    foreach(var frame in thread.Frames) {
     if (frame.Function == null) continue;
     if (!wasSPData & amp; & amp; frame.Function.FullName.Contains("SPData")) {
      wasSPData = true;
      maxCount = count + 3;
     }
     if (count & gt; = maxCount)
      break;
     count++;

     var frameResult = new Frame();
     if (frame.SourcePosition != null) {
      frameResult.Path = frame.SourcePosition.Path;
      frameResult.Line = frame.SourcePosition.Line;

     }

     frameResult.FunctionName = frame.Function.FullName;
     if (frame.IsManaged & amp; & amp; !frame.IsInfoOnly) {
      try {
       foreach(var argument in frame.Function.GetArguments(frame)) {
        var value = GetValue(argument);
        if (value != null)
         frameResult.Parameter.Add(value);
       }
      } catch (System.Exception) {

      }

      try {
       foreach(var variable in frame.Function.GetActiveLocalVars(frame)) {
        var value = GetValue(variable);
        if (value != null)
         frameResult.LocalVariables.Add(value);
       }
      } catch (System.Exception) {

      }

     }

     exceptionResult.Frames.Add(frameResult);
    }

    CreateTraceFile(thread.CurrentException.CorValue.Raw.GetHashCode() +
     "_" + thread.CurrentException.CorValue.Address, exceptionResult);

   }
  }

  private struct ToPrint {
   public MDbgThread Thread;
   public Exception ExceptionResult;
  }

  private Value GetValue(MDbgValue aValue) {

   try {
    Value value = new Value();
    value.Name = aValue.Name;
    if (aValue.IsNull) {
     value.TypeName = aValue.TypeName;
     value.ValueO = "null";
    } else {
     value.TypeName = aValue.TypeName;
     value.ValueO = expandValue(aValue);

    }

    return value;
   } catch (System.Exception) {
    return null;
   }
  }

  private string expandValue(MDbgValue value) {
   if (value.TypeName.Contains("WebControls") ||
    value.TypeName.Contains("ascx") ||
    value.TypeName.Contains("ASP") ||
    value.TypeName.Contains("System.Web"))
    return value.GetStringValue(0);

   int level = 0;
   string result = "";
   while (level & lt; = 3) {
    try {
     result = value.GetStringValue(level);
     level++;
    } catch (System.Exception) {
     return result;
    }
   }

   return result;
  }

  private void CreateTraceFile(string ID, Exception exceptionResult) {
   if (!Directory.Exists(_filePath)) {
    Directory.CreateDirectory(_filePath);
   }

   string path = Path.Combine(_filePath, ID.ToString());

   if (File.Exists(path)) {
    File.Delete(path);
   }

   byte[] bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(exceptionResult));
   FileStream fs = File.Create(path);
   fs.Write(bytes, 0, bytes.Length);

   fs.Close();
  }

  private class Exception {
   public string Name {
    get;
    set;
   }

   public Object Value {
    get;
    set;
   }

   public string TypeName {
    get;
    set;
   }

   public List Frames {
    get;
    set;
   } = new List();

   public DateTime DateTime {
    get;
    set;
   } = DateTime.Now;
  }

  private class Frame {
   public string Path {
    get;
    set;
   }
   public int Line {
    get;
    set;
   }
   public string FunctionName {
    get;
    set;
   }

   public List < value > Parameter {
    get;
    set;
   } = new List < value > (); < /value></value >

   public List < value > LocalVariables {
    get;
    set;
   } = new List < value > ();
  } < /value></value >

  private class Value {
   public string Name {
    get;
    set;
   }

   public string TypeName {
    get;
    set;
   }

   public Object ValueO {
    get;
    set;
   }
  }
 }
}
Categories: Allgemein

Leave a Reply

Your email address will not be published. Required fields are marked *