-
-
Notifications
You must be signed in to change notification settings - Fork 230
Expand file tree
/
Copy pathCocoaExtensions.cs
More file actions
398 lines (352 loc) · 14.7 KB
/
CocoaExtensions.cs
File metadata and controls
398 lines (352 loc) · 14.7 KB
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
using Sentry.Extensibility;
namespace Sentry.Cocoa.Extensions;
internal static class CocoaExtensions
{
public static DateTimeOffset ToDateTimeOffset(this NSDate timestamp) => new((DateTime)timestamp);
public static NSDate ToNSDate(this DateTimeOffset timestamp) => (NSDate)timestamp.UtcDateTime;
public static NSString ToNSString(this string str) => new NSString(str);
public static string? ToJsonString(this NSObject? obj, IDiagnosticLogger? logger = null)
{
using var data = obj.ToJsonData(logger);
return data?.ToString();
}
public static Stream? ToJsonStream(this NSObject? obj, IDiagnosticLogger? logger = null) =>
obj.ToJsonData(logger)?.AsStream();
private static NSData? ToJsonData(this NSObject? obj, IDiagnosticLogger? logger = null)
{
if (obj == null)
{
return null;
}
if (obj is CocoaSdk.ISentrySerializable serializable)
{
// For types that implement Sentry Cocoa's SentrySerializable protocol (interface),
// We should call that first, and then serialize the result to JSON later.
obj = serializable.Serialize();
}
// Now we will use Apple's JSON Serialization functions.
// See https://developer.apple.com/documentation/foundation/nsjsonserialization
if (!NSJsonSerialization.IsValidJSONObject(obj))
{
logger?.LogWarning("Cannot serialize a {0} directly to JSON", obj.GetType().Name);
return null;
}
try
{
return NSJsonSerialization.Serialize(obj, 0, out _);
}
catch (Exception ex)
{
logger?.LogError(ex, "Error serializing {0} to JSON", obj.GetType().Name);
return null;
}
}
public static Dictionary<string, string> ToStringDictionary<TValue>(
this NSDictionary<NSString, TValue>? dict,
IDiagnosticLogger? logger = null)
where TValue : NSObject
{
if (dict == null)
{
return new Dictionary<string, string>();
}
var result = new Dictionary<string, string>(capacity: (int)dict.Count);
foreach (var key in dict.Keys)
{
var value = dict[key];
if (value is NSString s)
{
result.Add(key, s);
}
else if (value.ToJsonString(logger) is { } json)
{
result.Add(key, json);
}
// Skip null values, including anything that couldn't be serialized
}
return result;
}
public static Dictionary<string, string>? ToNullableStringDictionary<TValue>(
this NSDictionary<NSString, TValue>? dict,
IDiagnosticLogger? logger = null)
where TValue : NSObject
{
if (dict is null || dict.Count == 0)
{
return null;
}
return dict.ToStringDictionary(logger);
}
public static Dictionary<string, object?> ToObjectDictionary<TValue>(
this NSDictionary<NSString, TValue>? dict,
IDiagnosticLogger? logger = null)
where TValue : NSObject
{
if (dict == null)
{
return new Dictionary<string, object?>();
}
var result = new Dictionary<string, object?>(capacity: (int)dict.Count);
foreach (var key in dict.Keys)
{
var value = dict[key];
switch (value)
{
case null or NSNull:
result.Add(key, null);
break;
case NSString s:
result.Add(key, s);
break;
case NSNumber n:
result.Add(key, n.ToObject());
break;
default:
if (value.ToJsonString(logger) is { } json)
{
result.Add(key, json);
}
else
{
logger?.LogWarning("Could not add value of type {0} to dictionary.", value.GetType());
}
break;
}
}
return result;
}
public static Dictionary<string, object?>? ToNullableObjectDictionary<TValue>(
this NSDictionary<NSString, TValue>? dict,
IDiagnosticLogger? logger = null)
where TValue : NSObject
{
if (dict is null || dict.Count == 0)
{
return null;
}
return dict.ToObjectDictionary(logger);
}
public static NSDictionary<NSString, NSObject> ToNSDictionary<TValue>(
this IEnumerable<KeyValuePair<string, TValue>> dict)
{
var d = new Dictionary<NSString, NSObject>();
foreach (var item in dict)
{
// skip null values, but add others as NSObject
if (item.Value is { } value)
{
d.Add((NSString)item.Key, NSObject.FromObject(value));
}
}
return NSDictionary<NSString, NSObject>
.FromObjectsAndKeys(
d.Values.ToArray(),
d.Keys.ToArray());
}
public static NSDictionary<NSString, NSString> ToNSDictionaryStrings(
this IEnumerable<KeyValuePair<string, string>> dict)
{
var d = new Dictionary<NSString, NSString>();
foreach (var item in dict)
{
if (item.Value != null)
{
d.Add((NSString)item.Key, new NSString(item.Value));
}
}
return NSDictionary<NSString, NSString>
.FromObjectsAndKeys(
d.Values.ToArray(),
d.Keys.ToArray());
}
public static NSDictionary<NSString, NSObject>? ToNullableNSDictionary<TValue>(
this ICollection<KeyValuePair<string, TValue>> dict) =>
dict.Count == 0 ? null : dict.ToNSDictionary();
public static NSDictionary<NSString, NSObject>? ToNullableNSDictionary<TValue>(
this IReadOnlyCollection<KeyValuePair<string, TValue>> dict) =>
dict.Count == 0 ? null : dict.ToNSDictionary();
public static NSDictionary<NSString, NSObject>? ToCocoaBreadcrumbData(
this IReadOnlyDictionary<string, string> source)
{
// Avoid an allocation if we can
if (source.Count == 0)
{
return null;
}
var dict = new NSDictionary<NSString, NSObject>();
foreach (var (key, value) in source)
{
// Cocoa Session Replay expects `request_start` to be a Date (`NSDate`).
// See https://github.com/getsentry/sentry-cocoa/blob/2b4e787e55558e1475eda8f98b02c19a0d511741/Sources/Swift/Integrations/SessionReplay/SentrySRDefaultBreadcrumbConverter.swift#L73
if (key == SentryHttpMessageHandler.RequestStartKey && TryParseUnixMs(value, out var unixMs))
{
var dto = DateTimeOffset.FromUnixTimeMilliseconds(unixMs);
dict[key] = dto.ToNSDate();
continue;
}
dict[key] = NSObject.FromObject(value);
}
return dict.Count == 0 ? null : dict;
static bool TryParseUnixMs(string value, out long unixMs) =>
long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out unixMs);
}
/// <summary>
/// Converts an <see cref="NSNumber"/> to a .NET primitive data type and returns the result box in an <see cref="object"/>.
/// </summary>
/// <param name="n">The <see cref="NSNumber"/> to convert.</param>
/// <returns>An <see cref="object"/> that contains the number in its primitive type.</returns>
/// <exception cref="ArgumentOutOfRangeException">Thrown when the number's <c>ObjCType</c> was unrecognized.</exception>
/// <remarks>
/// This method always returns a result that is compatible with its value, but does not always give the expected result.
/// Specifically:
/// <list type="bullet">
/// <item><c>byte</c> returns <c>short</c></item>
/// <item><c>ushort</c> return <c>int</c></item>
/// <item><c>uint</c> returns <c>long</c></item>
/// <item><c>ulong</c> returns <c>long</c> unless it's > <c>long.MaxValue</c></item>
/// <item>n/nu types return more primitive types (ex. <c>nfloat</c> => <c>double</c>)</item>
/// </list>
/// Type encodings are listed here:
/// https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html
/// </remarks>
public static object ToObject(this NSNumber n)
{
if (n is NSDecimalNumber d)
{
// handle NSDecimalNumber type directly
return (decimal)d.NSDecimalValue;
}
return n.ObjCType switch
{
"c" when n.Class.Name == "__NSCFBoolean" => n.BoolValue, // ObjC bool
"c" => n.SByteValue, // signed char
"i" => n.Int32Value, // signed int
"s" => n.Int16Value, // signed short
"l" => n.Int32Value, // signed long (32 bit)
"q" => n.Int64Value, // signed long long (64 bit)
"C" => n.ByteValue, // unsigned char
"I" => n.UInt32Value, // unsigned int
"S" => n.UInt16Value, // unsigned short
"L" => n.UInt32Value, // unsigned long (32 bit)
"Q" => n.UInt64Value, // unsigned long long (64 bit)
"f" => n.FloatValue, // float
"d" => n.DoubleValue, // double
"B" => n.BoolValue, // C++ bool or C99 _Bool
_ => throw new ArgumentOutOfRangeException(nameof(n), n,
$"NSNumber \"{n.StringValue}\" has an unknown ObjCType \"{n.ObjCType}\" (Class: \"{n.Class.Name}\")")
};
}
public static void CopyToCocoaSentryEvent(this SentryEvent managed, CocoaSdk.SentryEvent native)
{
// we only support a subset of mutated data to be passed back to the native SDK at this time
native.ServerName = managed.ServerName;
native.Dist = managed.Distribution;
native.Logger = managed.Logger;
native.ReleaseName = managed.Release;
native.Environment = managed.Environment;
native.Transaction = managed.TransactionName!;
native.Message = managed.Message?.ToCocoaSentryMessage();
native.Tags = managed.Tags?.ToNSDictionaryStrings();
native.Extra = managed.Extra?.ToNSDictionary();
native.Breadcrumbs = managed.Breadcrumbs?.Select(x => x.ToCocoaBreadcrumb()).ToArray();
native.User = managed.User?.ToCocoaUser();
if (managed.Level != null)
{
native.Level = managed.Level.Value.ToCocoaSentryLevel();
}
if (managed.Exception != null)
{
native.Error = new NSError(new NSString(managed.Exception.ToString()), IntPtr.Zero);
}
}
public static SentryEvent? ToSentryEvent(this CocoaSdk.SentryEvent sentryEvent)
{
using var stream = sentryEvent.ToJsonStream();
if (stream == null)
return null;
using var json = JsonDocument.Parse(stream);
var exception = sentryEvent.Error == null ? null : new NSErrorException(sentryEvent.Error);
var ev = SentryEvent.FromJson(json.RootElement, exception);
return ev;
}
public static CocoaSdk.SentryMessage ToCocoaSentryMessage(this SentryMessage msg)
{
var native = new CocoaSdk.SentryMessage(msg.Formatted ?? string.Empty);
native.Params = msg.Params?.Select(x => x.ToString()!).ToArray() ?? new string[0];
return native;
}
// not tested or needed yet - leaving for future just in case
// public static CocoaSdk.SentryThread ToCocoaSentryThread(this SentryThread thread)
// {
// var id = NSNumber.FromInt32(thread.Id ?? 0);
// var native = new CocoaSdk.SentryThread(id);
// native.Crashed = thread.Crashed;
// native.Current = thread.Current;
// native.Name = thread.Name;
// native.Stacktrace = thread.Stacktrace?.ToCocoaSentryStackTrace();
// // native.IsMain = not in dotnet
// return native;
// }
//
// public static CocoaSdk.SentryRequest ToCocoaSentryRequest(this SentryRequest request)
// {
// var native = new CocoaSdk.SentryRequest();
// native.Cookies = request.Cookies;
// native.Headers = request.Headers?.ToNSDictionaryStrings();
// native.Method = request.Method;
// native.QueryString = request.QueryString;
// native.Url = request.Url;
//
// // native.BodySize does not exist in dotnet
// return native;
// }
//
// public static CocoaSdk.SentryException ToCocoaSentryException(this SentryException ex)
// {
// var native = new CocoaSdk.SentryException(ex.Value ?? string.Empty, ex.Type ?? string.Empty);
// native.Module = ex.Module;
// native.Mechanism = ex.Mechanism?.ToCocoaSentryMechanism();
// native.Stacktrace = ex.Stacktrace?.ToCocoaSentryStackTrace();
// // not part of native - ex.ThreadId;
// return native;
// }
//
// public static CocoaSdk.SentryStacktrace ToCocoaSentryStackTrace(this SentryStackTrace stackTrace)
// {
// var frames = stackTrace.Frames?.Select(x => x.ToCocoaSentryFrame()).ToArray() ?? new CocoaSdk.SentryFrame[0];
// var native = new CocoaSdk.SentryStacktrace(frames, new NSDictionary<NSString, NSString>());
// // native.Register & native.Snapshot missing in dotnet
// return native;
// }
//
// public static CocoaSdk.SentryFrame ToCocoaSentryFrame(this SentryStackFrame frame)
// {
// var native = new CocoaSdk.SentryFrame();
// native.Module = frame.Module;
// native.Package = frame.Package;
// native.InstructionAddress = frame.InstructionAddress?.ToString();
// native.Function = frame.Function;
// native.Platform = frame.Platform;
// native.ColumnNumber = frame.ColumnNumber;
// native.FileName = frame.FileName;
// native.InApp = frame.InApp;
// native.ImageAddress = frame.ImageAddress?.ToString();
// native.LineNumber = frame.LineNumber;
// native.SymbolAddress = frame.SymbolAddress?.ToString();
//
// // native.StackStart = doesn't exist in dotnet
// return native;
// }
//
// public static CocoaSdk.SentryMechanism ToCocoaSentryMechanism(this Mechanism mechanism)
// {
// var native = new CocoaSdk.SentryMechanism(mechanism.Type);
// native.Synthetic = mechanism.Synthetic;
// native.Handled = mechanism.Handled;
// native.Desc = mechanism.Description;
// native.HelpLink = mechanism.HelpLink;
// native.Data = mechanism.Data?.ToNSDictionary();
// // TODO: Meta does not currently translate in dotnet - native.Meta = null;
// return native;
// }
}