Skip to content

Commit 5fef1cb

Browse files
committed
Merge pull request #1 from rdavisau/new-inputs
Add text and url inputs
2 parents efc7790 + c4d9f19 commit 5fef1cb

31 files changed

+1177
-264
lines changed

JsonCSharpClassGeneratorLib/CodeWriters/CSharpCodeWriter.cs

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,16 @@ namespace Xamasoft.JsonClassGenerator.CodeWriters
99
{
1010
public class CSharpCodeWriter : ICodeWriter
1111
{
12+
private static HashSet<string> _csharpKeywords = new HashSet<string>
13+
{
14+
"abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default",
15+
"delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto",
16+
"if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out",
17+
"override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc",
18+
"static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using",
19+
"virtual", "void", "volatile", "while"
20+
};
21+
1222
public string FileExtension
1323
{
1424
get { return ".cs"; }
@@ -46,7 +56,7 @@ public string GetTypeName(JsonType type, IJsonClassGeneratorConfig config)
4656
case JsonTypeEnum.NullableSomething: return "object";
4757
case JsonTypeEnum.Object: return type.AssignedName;
4858
case JsonTypeEnum.String: return "string";
49-
default: throw new System.NotSupportedException("Unsupported json type");
59+
default: throw new NotSupportedException("Unsupported json type");
5060
}
5161
}
5262

@@ -193,15 +203,14 @@ private void WriteClassMembers(IJsonClassGeneratorConfig config, TextWriter sw,
193203
sw.WriteLine(prefix + "/// </summary>");
194204
}
195205

196-
if (config.UsePascalCase)
206+
if (true || config.UsePascalCase)
197207
{
198-
199208
sw.WriteLine(prefix + "[JsonProperty(\"{0}\")]", field.JsonMemberName);
200209
}
201210

202211
if (config.UseProperties)
203212
{
204-
sw.WriteLine(prefix + "public {0} {1} {{ get; set; }}", field.Type.GetTypeName(), field.MemberName);
213+
sw.WriteLine(prefix + "public {0} {1}{2} {{ get; set; }}", field.Type.GetTypeName(), (ShouldPrefix(field.MemberName) || field.MemberName == type.AssignedName) ? "_" : "", field.MemberName);
205214
}
206215
else
207216
{
@@ -212,7 +221,16 @@ private void WriteClassMembers(IJsonClassGeneratorConfig config, TextWriter sw,
212221
}
213222

214223

224+
private bool ShouldPrefix(string fieldName)
225+
{
226+
if (!Char.IsLetter(fieldName.ToCharArray()[0]))
227+
return true;
215228

229+
if (_csharpKeywords.Contains(fieldName))
230+
return true;
231+
232+
return false;
233+
}
216234

217235

218236

@@ -234,7 +252,7 @@ private void WriteClassWithPropertiesExplicitDeserialization(TextWriter sw, Json
234252
string variable = null;
235253
if (field.Type.MustCache)
236254
{
237-
variable = "_" + char.ToLower(field.MemberName[0]) + field.MemberName.Substring(1);
255+
variable = "_" + Char.ToLower(field.MemberName[0]) + field.MemberName.Substring(1);
238256
sw.WriteLine(prefix + "[System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]");
239257
sw.WriteLine(prefix + "private {0} {1};", field.Type.GetTypeName(), variable);
240258
}
@@ -295,6 +313,5 @@ private void WriteClassWithFieldsExplicitDeserialization(TextWriter sw, JsonType
295313
}
296314
}
297315
#endregion
298-
299316
}
300317
}

JsonCSharpClassGeneratorLib/JsonClassGenerator.cs

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -249,17 +249,6 @@ private void GenerateClass(JObject[] examples, JsonType type)
249249
}
250250
}
251251

252-
// detect and correct when a field's name matches its containing class.
253-
if (jsonFields.ContainsKey(type.AssignedName))
254-
{
255-
var newKey = type.AssignedName + "_";
256-
257-
jsonFields.Add(newKey, jsonFields[type.AssignedName]);
258-
fieldExamples.Add(newKey, fieldExamples[type.AssignedName]);
259-
260-
jsonFields.Remove(type.AssignedName);
261-
fieldExamples.Remove(type.AssignedName);
262-
}
263252

264253
type.Fields = jsonFields.Select(x => new FieldInfo(this, x.Key, x.Value, UsePascalCase, fieldExamples[x.Key])).ToArray();
265254

@@ -302,7 +291,7 @@ internal static string ToTitleCase(string str)
302291
for (int i = 0; i < str.Length; i++)
303292
{
304293
var c = str[i];
305-
if (char.IsLetterOrDigit(c))
294+
if (char.IsLetterOrDigit(c) || c == '_')
306295
{
307296
sb.Append(flag ? char.ToUpper(c) : c);
308297
flag = false;

JsonCSharpClassGeneratorLib/JsonType.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,9 @@ internal JsonType MaybeMakeNullable(IJsonClassGeneratorConfig generator)
7676

7777
public void AssignName(string name)
7878
{
79+
if (!char.IsLetter(name.ToCharArray()[0]))
80+
name = "_" + name;
81+
7982
AssignedName = name;
8083
}
8184

Lines changed: 66 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,73 @@
11
using System;
2+
using System.Collections;
23
using System.Collections.Generic;
34
using System.IO;
5+
using System.Linq;
6+
using System.Net;
7+
using System.Runtime.CompilerServices;
8+
using System.Security.Policy;
49
using Newtonsoft.Json;
510

11+
612
namespace JsonDataContext
713
{
814
public class JsonDataContextBase
915
{
10-
protected static IEnumerable<T> DeserializeSequenceFromJsonFile<T>(string filePath)
16+
public Dictionary<string, string> _jsonTextInputs = new Dictionary<string, string>();
17+
18+
protected IEnumerable<T> GetFileJsonInput<T>(string filePath)
19+
{
20+
var stream = File.OpenRead(filePath);
21+
22+
return ReadFromJsonStream<T>(stream);
23+
}
24+
25+
protected IEnumerable<T> GetTextJsonInput<T>(string key)
26+
{
27+
var json = "";
28+
29+
if (!_jsonTextInputs.TryGetValue(key, out json))
30+
throw new Exception(String.Format("Could not find json data for key '{0}'", key));
31+
32+
if (!json.Trim().StartsWith("["))
33+
json = String.Format("[{0}]", json.Trim());
34+
35+
var stream = ToStream(json);
36+
37+
return ReadFromJsonStream<T>(stream);
38+
}
39+
40+
protected IEnumerable<T> GetUrlParameterlessInput<T>(string url)
1141
{
12-
using (var sr = new StreamReader(filePath))
13-
{
42+
var req = (HttpWebRequest) HttpWebRequest.Create(url);
43+
req.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
44+
req.UserAgent = @"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36";
45+
46+
var stream = req.GetResponse().GetResponseStream();
47+
48+
return ReadFromJsonStream<T>(stream);
49+
}
50+
51+
private static IEnumerable<T> ReadFromJsonStream<T>(Stream stream)
52+
{
53+
using (var sr = new StreamReader(stream))
54+
{
1455
using (var reader = new JsonTextReader(sr))
1556
{
1657
var serializer = new JsonSerializer();
17-
if (!reader.Read() || reader.TokenType != JsonToken.StartArray)
18-
throw new Exception("The source input did not appear to be an array of objects.");
1958

59+
if (!reader.Read())
60+
throw new InvalidDataException("Could not interpret input as JSON");
61+
62+
// not an array
63+
if (reader.TokenType != JsonToken.StartArray)
64+
{
65+
var item = serializer.Deserialize<T>(reader);
66+
yield return item;
67+
yield break;
68+
}
69+
70+
// yes an array
2071
while (reader.Read())
2172
{
2273
if (reader.TokenType == JsonToken.EndArray) break;
@@ -26,5 +77,15 @@ protected static IEnumerable<T> DeserializeSequenceFromJsonFile<T>(string filePa
2677
}
2778
}
2879
}
80+
81+
protected static Stream ToStream(string str)
82+
{
83+
var stream = new MemoryStream();
84+
var writer = new StreamWriter(stream);
85+
writer.Write(str);
86+
writer.Flush();
87+
stream.Position = 0;
88+
return stream;
89+
}
2990
}
3091
}

JsonDataContextDriver/DevDeploy.bat

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,5 @@
22
taskkill /f /im:LINQPad.exe
33
xcopy /i/y *.* "%programdata%\LINQPad\Drivers\DataContext\4.0\JsonDataContextDriver (ed22602f98bb09d6)\"
44
powershell start-process "C:\Users\rdavis\Dropbox\code\LINQPad4\LINQPad.exe"
5+
rem powershell start-process "C:\Users\rdavis\Desktop\LINQPad4\LINQPad.exe"
56
exit 0

JsonDataContextDriver/Extensions/Extensions.cs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.Collections.Generic;
3+
using System.Linq;
34
using System.Threading.Tasks;
45

56
namespace JsonDataContextDriver
@@ -8,6 +9,9 @@ public static class Extensions
89
{
910
public static string ReplaceAll(this string s, IEnumerable<Tuple<string, string>> replacements)
1011
{
12+
if (String.IsNullOrEmpty(s))
13+
return s;
14+
1115
foreach (var repl in replacements)
1216
s = s.Replace(repl.Item1, repl.Item2);
1317

@@ -22,5 +26,19 @@ public static IEnumerable<T> DoEach<T>(this IEnumerable<T> items, Action<T> acti
2226
yield return item;
2327
}
2428
}
29+
30+
public static string SanitiseClassName(this string originalName)
31+
{
32+
var replacers = new[] { "\n", "'", " ", "*", "/", "-", "(", ")", ".", "!", "?", "#", ":", "+", "{", "}", "&", "," };
33+
var tuples = replacers.Select(r => Tuple.Create(r, "_")).ToList();
34+
35+
var newName = originalName.ReplaceAll(tuples);
36+
if (char.IsNumber(newName[0]))
37+
newName = "_" + newName;
38+
39+
return newName;
40+
}
2541
}
42+
43+
2644
}

JsonDataContextDriver/GeneratedClass.cs

Lines changed: 0 additions & 14 deletions
This file was deleted.
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
using System;
2+
3+
namespace JsonDataContextDriver
4+
{
5+
public interface IGeneratedClass
6+
{
7+
string Namespace { get; set; }
8+
string ClassName { get; set; }
9+
string ClassDefinition { get; set; }
10+
bool Success { get; set; }
11+
Exception Error { get; set; }
12+
13+
IJsonInput OriginalInput { get; set; }
14+
}
15+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
using System.Collections.Generic;
2+
using LINQPad.Extensibility.DataContext;
3+
4+
namespace JsonDataContextDriver
5+
{
6+
public interface IJsonInput
7+
{
8+
void GenerateClasses(string nameSpace);
9+
10+
List<IGeneratedClass> GeneratedClasses { get; }
11+
List<ExplorerItem> ExplorerItems { get; }
12+
List<string> NamespacesToAdd { get; }
13+
List<string> ContextProperties { get; }
14+
List<string> Errors { get; }
15+
}
16+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
using System;
2+
3+
namespace JsonDataContextDriver
4+
{
5+
public class JsonFileGeneratedClass : IGeneratedClass
6+
{
7+
public JsonFileGeneratedClass(JsonFileInput input)
8+
{
9+
OriginalInput = input;
10+
}
11+
12+
public string Namespace { get; set; }
13+
public string ClassName { get; set; }
14+
public string DataFilePath { get; set; }
15+
public string ClassDefinition { get; set; }
16+
public bool Success { get; set; }
17+
public Exception Error { get; set; }
18+
19+
public JsonFileInput OriginalInput { get; set; }
20+
IJsonInput IGeneratedClass.OriginalInput
21+
{
22+
get { return OriginalInput; }
23+
set { OriginalInput = (JsonFileInput) value; }
24+
}
25+
}
26+
}

0 commit comments

Comments
 (0)