forked from jwaliszko/ExpressiveAnnotations
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Helper.cs
90 lines (80 loc) · 3.06 KB
/
Helper.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
/* https://github.com/jwaliszko/ExpressiveAnnotations
* Copyright (c) 2014 Jarosław Waliszko
* Licensed MIT: http://opensource.org/licenses/MIT */
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
namespace ExpressiveAnnotations.MvcUnobtrusive
{
internal static class Helper
{
public static string GetCoarseType(Type type)
{
Debug.Assert(type != null);
if (type.IsTimeSpan())
return "timespan";
if (type.IsDateTime())
return "datetime";
if (type.IsNumeric())
return "numeric";
if (type.IsString())
return "string";
if (type.IsBool())
return "bool";
if (type.IsGuid())
return "guid";
type = type.IsNullable() ? Nullable.GetUnderlyingType(type) : type;
return type.Name.ToLowerInvariant();
}
[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")] // code that deals with disposables should be consistent (and classes should be resilient to multiple Dispose() calls)
public static string ToJson(this object data)
{
Debug.Assert(data != null);
var stringBuilder = new StringBuilder();
var jsonSerializer = new JsonSerializer();
using (var stringWriter = new StringWriter(stringBuilder))
using (var jsonTextWriter = new JsonTextWriter(stringWriter))
{
jsonSerializer.Serialize(jsonTextWriter, data);
return stringBuilder.ToString();
}
}
public static bool SegmentsCollide(IEnumerable<string> listA, IEnumerable<string>listB, out string name, out int level)
{
Debug.Assert(listA != null);
Debug.Assert(listB != null);
name = null;
level = -1;
var segmentsA = listA.Select(x => x.Split('.')).ToList();
var segmentsB = listB.Select(x => x.Split('.')).ToList();
foreach (var segA in segmentsA)
{
foreach (var segB in segmentsB)
{
var equal = true;
var boundary = new[] {segA.Length, segB.Length}.Min() - 1;
for (var i = 0; i <= boundary; i++)
{
if (segA[i] != segB[i])
{
equal = false;
break;
}
}
if (equal)
{
name = segA[boundary];
level = boundary;
return true;
}
}
}
return false;
}
}
}