Skip to content

Commit

Permalink
Merge pull request #1 from rdavisau/new-inputs
Browse files Browse the repository at this point in the history
Add text and url inputs
  • Loading branch information
rdavisau committed Jun 17, 2015
2 parents efc7790 + c4d9f19 commit 5fef1cb
Show file tree
Hide file tree
Showing 31 changed files with 1,177 additions and 264 deletions.
29 changes: 23 additions & 6 deletions JsonCSharpClassGeneratorLib/CodeWriters/CSharpCodeWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@ namespace Xamasoft.JsonClassGenerator.CodeWriters
{
public class CSharpCodeWriter : ICodeWriter
{
private static HashSet<string> _csharpKeywords = new HashSet<string>
{
"abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default",
"delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto",
"if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out",
"override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc",
"static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using",
"virtual", "void", "volatile", "while"
};

public string FileExtension
{
get { return ".cs"; }
Expand Down Expand Up @@ -46,7 +56,7 @@ public string GetTypeName(JsonType type, IJsonClassGeneratorConfig config)
case JsonTypeEnum.NullableSomething: return "object";
case JsonTypeEnum.Object: return type.AssignedName;
case JsonTypeEnum.String: return "string";
default: throw new System.NotSupportedException("Unsupported json type");
default: throw new NotSupportedException("Unsupported json type");
}
}

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

if (config.UsePascalCase)
if (true || config.UsePascalCase)
{

sw.WriteLine(prefix + "[JsonProperty(\"{0}\")]", field.JsonMemberName);
}

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


private bool ShouldPrefix(string fieldName)
{
if (!Char.IsLetter(fieldName.ToCharArray()[0]))
return true;

if (_csharpKeywords.Contains(fieldName))
return true;

return false;
}



Expand All @@ -234,7 +252,7 @@ private void WriteClassWithPropertiesExplicitDeserialization(TextWriter sw, Json
string variable = null;
if (field.Type.MustCache)
{
variable = "_" + char.ToLower(field.MemberName[0]) + field.MemberName.Substring(1);
variable = "_" + Char.ToLower(field.MemberName[0]) + field.MemberName.Substring(1);
sw.WriteLine(prefix + "[System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]");
sw.WriteLine(prefix + "private {0} {1};", field.Type.GetTypeName(), variable);
}
Expand Down Expand Up @@ -295,6 +313,5 @@ private void WriteClassWithFieldsExplicitDeserialization(TextWriter sw, JsonType
}
}
#endregion

}
}
13 changes: 1 addition & 12 deletions JsonCSharpClassGeneratorLib/JsonClassGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -249,17 +249,6 @@ private void GenerateClass(JObject[] examples, JsonType type)
}
}

// detect and correct when a field's name matches its containing class.
if (jsonFields.ContainsKey(type.AssignedName))
{
var newKey = type.AssignedName + "_";

jsonFields.Add(newKey, jsonFields[type.AssignedName]);
fieldExamples.Add(newKey, fieldExamples[type.AssignedName]);

jsonFields.Remove(type.AssignedName);
fieldExamples.Remove(type.AssignedName);
}

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

Expand Down Expand Up @@ -302,7 +291,7 @@ internal static string ToTitleCase(string str)
for (int i = 0; i < str.Length; i++)
{
var c = str[i];
if (char.IsLetterOrDigit(c))
if (char.IsLetterOrDigit(c) || c == '_')
{
sb.Append(flag ? char.ToUpper(c) : c);
flag = false;
Expand Down
3 changes: 3 additions & 0 deletions JsonCSharpClassGeneratorLib/JsonType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ internal JsonType MaybeMakeNullable(IJsonClassGeneratorConfig generator)

public void AssignName(string name)
{
if (!char.IsLetter(name.ToCharArray()[0]))
name = "_" + name;

AssignedName = name;
}

Expand Down
71 changes: 66 additions & 5 deletions JsonDataContextBase/JsonDataContextBase.cs
Original file line number Diff line number Diff line change
@@ -1,22 +1,73 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Security.Policy;
using Newtonsoft.Json;


namespace JsonDataContext
{
public class JsonDataContextBase
{
protected static IEnumerable<T> DeserializeSequenceFromJsonFile<T>(string filePath)
public Dictionary<string, string> _jsonTextInputs = new Dictionary<string, string>();

protected IEnumerable<T> GetFileJsonInput<T>(string filePath)
{
var stream = File.OpenRead(filePath);

return ReadFromJsonStream<T>(stream);
}

protected IEnumerable<T> GetTextJsonInput<T>(string key)
{
var json = "";

if (!_jsonTextInputs.TryGetValue(key, out json))
throw new Exception(String.Format("Could not find json data for key '{0}'", key));

if (!json.Trim().StartsWith("["))
json = String.Format("[{0}]", json.Trim());

var stream = ToStream(json);

return ReadFromJsonStream<T>(stream);
}

protected IEnumerable<T> GetUrlParameterlessInput<T>(string url)
{
using (var sr = new StreamReader(filePath))
{
var req = (HttpWebRequest) HttpWebRequest.Create(url);
req.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
req.UserAgent = @"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36";

var stream = req.GetResponse().GetResponseStream();

return ReadFromJsonStream<T>(stream);
}

private static IEnumerable<T> ReadFromJsonStream<T>(Stream stream)
{
using (var sr = new StreamReader(stream))
{
using (var reader = new JsonTextReader(sr))
{
var serializer = new JsonSerializer();
if (!reader.Read() || reader.TokenType != JsonToken.StartArray)
throw new Exception("The source input did not appear to be an array of objects.");

if (!reader.Read())
throw new InvalidDataException("Could not interpret input as JSON");

// not an array
if (reader.TokenType != JsonToken.StartArray)
{
var item = serializer.Deserialize<T>(reader);
yield return item;
yield break;
}

// yes an array
while (reader.Read())
{
if (reader.TokenType == JsonToken.EndArray) break;
Expand All @@ -26,5 +77,15 @@ protected static IEnumerable<T> DeserializeSequenceFromJsonFile<T>(string filePa
}
}
}

protected static Stream ToStream(string str)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(str);
writer.Flush();
stream.Position = 0;
return stream;
}
}
}
1 change: 1 addition & 0 deletions JsonDataContextDriver/DevDeploy.bat
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@
taskkill /f /im:LINQPad.exe
xcopy /i/y *.* "%programdata%\LINQPad\Drivers\DataContext\4.0\JsonDataContextDriver (ed22602f98bb09d6)\"
powershell start-process "C:\Users\rdavis\Dropbox\code\LINQPad4\LINQPad.exe"
rem powershell start-process "C:\Users\rdavis\Desktop\LINQPad4\LINQPad.exe"
exit 0
18 changes: 18 additions & 0 deletions JsonDataContextDriver/Extensions/Extensions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace JsonDataContextDriver
Expand All @@ -8,6 +9,9 @@ public static class Extensions
{
public static string ReplaceAll(this string s, IEnumerable<Tuple<string, string>> replacements)
{
if (String.IsNullOrEmpty(s))
return s;

foreach (var repl in replacements)
s = s.Replace(repl.Item1, repl.Item2);

Expand All @@ -22,5 +26,19 @@ public static IEnumerable<T> DoEach<T>(this IEnumerable<T> items, Action<T> acti
yield return item;
}
}

public static string SanitiseClassName(this string originalName)
{
var replacers = new[] { "\n", "'", " ", "*", "/", "-", "(", ")", ".", "!", "?", "#", ":", "+", "{", "}", "&", "," };
var tuples = replacers.Select(r => Tuple.Create(r, "_")).ToList();

var newName = originalName.ReplaceAll(tuples);
if (char.IsNumber(newName[0]))
newName = "_" + newName;

return newName;
}
}


}
14 changes: 0 additions & 14 deletions JsonDataContextDriver/GeneratedClass.cs

This file was deleted.

15 changes: 15 additions & 0 deletions JsonDataContextDriver/Inputs/IGeneratedClass.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System;

namespace JsonDataContextDriver
{
public interface IGeneratedClass
{
string Namespace { get; set; }
string ClassName { get; set; }
string ClassDefinition { get; set; }
bool Success { get; set; }
Exception Error { get; set; }

IJsonInput OriginalInput { get; set; }
}
}
16 changes: 16 additions & 0 deletions JsonDataContextDriver/Inputs/IJsonInput.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System.Collections.Generic;
using LINQPad.Extensibility.DataContext;

namespace JsonDataContextDriver
{
public interface IJsonInput
{
void GenerateClasses(string nameSpace);

List<IGeneratedClass> GeneratedClasses { get; }
List<ExplorerItem> ExplorerItems { get; }
List<string> NamespacesToAdd { get; }
List<string> ContextProperties { get; }
List<string> Errors { get; }
}
}
26 changes: 26 additions & 0 deletions JsonDataContextDriver/Inputs/JsonFileGeneratedClass.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System;

namespace JsonDataContextDriver
{
public class JsonFileGeneratedClass : IGeneratedClass
{
public JsonFileGeneratedClass(JsonFileInput input)
{
OriginalInput = input;
}

public string Namespace { get; set; }
public string ClassName { get; set; }
public string DataFilePath { get; set; }
public string ClassDefinition { get; set; }
public bool Success { get; set; }
public Exception Error { get; set; }

public JsonFileInput OriginalInput { get; set; }
IJsonInput IGeneratedClass.OriginalInput
{
get { return OriginalInput; }
set { OriginalInput = (JsonFileInput) value; }
}
}
}
Loading

0 comments on commit 5fef1cb

Please sign in to comment.