-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathJsonFormGenerator.cs
254 lines (251 loc) · 10 KB
/
JsonFormGenerator.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
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Dynamic;
using System.Linq;
using System.Reflection;
using SurveyJSAsFormLibrary.Attributes;
using SurveyJSAsFormLibrary.DomainModels;
namespace SurveyJSAsFormLibrary.Code
{
public class JSONGeneratorByModelClass
{
Type type;
public JSONGeneratorByModelClass(Type type)
{
this.type = type;
}
// Generates a form JSON schema based upon a domain model type.
public dynamic Generate()
{
// Get domain model properties and their metadata
List<PropertyInfo> properties = new List<PropertyInfo>();
this.fillProperties(properties, this.type);
if (properties.Count == 0) return new { };
// Arrays of form pages and elements (questions and panels)
var pages = new List<dynamic>();
var elements = new List<dynamic>();
CustomAttributeData curPageAttr = getFormPageAttribute(properties[0]);
for(int i = 0; i < properties.Count; i ++)
{
var prop = properties[i];
if (i > 0)
{
CustomAttributeData pageAttr = getFormPageAttribute(prop);
// If `pageAttr` has a value, it means that the previous page has run out of form elements,
// and we should add it to the `pages` array
if (pageAttr != null)
{
pages.Add(new { title = this.getAttributeValueByProp(curPageAttr, "Title"), elements = elements });
elements = new List<dynamic>();
curPageAttr = pageAttr;
}
}
// Create a form element for the current domain model property
var element = this.createElementByProp(prop);
if(element != null)
{
elements.Add(element);
}
}
// If the `elements` array is not empty, create a form page for its elements. This page will be the last.
if (elements.Count > 0)
{
pages.Add(new { title = this.getAttributeValueByProp(curPageAttr, "Title"), elements = elements });
}
var json = new ExpandoObject();
json.TryAdd("pages", pages);
return json;
}
private void fillProperties(List<PropertyInfo> properties, Type type)
{
Type parentType = type.BaseType;
if(parentType != null && typeof(DomainModel).IsAssignableFrom(parentType))
{
fillProperties(properties, parentType);
}
properties.AddRange(type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly));
}
// Creates a form element based upon the metadata of a domain model property.
// You can expand this method to process more attributes.
private dynamic createElementByProp(PropertyInfo prop)
{
var el = new ExpandoObject();
el.TryAdd("name", prop.Name);
this.setElementAttrByPropType(el, prop);
foreach (var attr in prop.CustomAttributes)
{
if (attr.AttributeType == typeof(RequiredAttribute))
{
el.TryAdd("isRequired", true);
}
if (attr.AttributeType == typeof(DisplayAttribute))
{
var autoGenerated = getAttributeValueByProp(attr, "AutoGenerateField");
if (autoGenerated != null && (bool)autoGenerated == true) return null;
var title = getAttributeValueByProp(attr, "Name");
if (title != null)
{
el.TryAdd("title", title);
}
}
if(attr.AttributeType == typeof(FormFieldAttribute))
{
this.setElementAttrByFormFieldAttr(el, attr);
}
}
if (!this.hasProperty(el, "title"))
{
el.TryAdd("title", getTitleByName(prop.Name));
}
return el;
}
// Sets a form element type based upon the type of the passed domain model property.
private void setElementAttrByPropType(ExpandoObject el, PropertyInfo prop)
{
if (this.isGenericListType(prop.PropertyType))
{
Type argType = prop.PropertyType.GetGenericArguments()[0];
if (argType == typeof(string) || IsNumericType(argType)) {
el.TryAdd("type", "checkbox");
} else
{
this.setListElementAttrByPropType(el, prop);
}
return;
}
string type = prop.PropertyType == typeof(bool) ? "boolean" : "text";
el.TryAdd("type", type);
if(prop.PropertyType == typeof(DateTime))
{
el.TryAdd("inputType", "date");
}
if(IsNumericType(prop.PropertyType))
{
el.TryAdd("inputType", "number");
}
}
// Sets the type of cells in a Matrix Dynamic question based upon the type of the passed domain model property.
private void setListElementAttrByPropType(ExpandoObject el, PropertyInfo prop)
{
el.TryAdd("type", "matrixdynamic");
el.TryAdd("rowCount", 0);
Type rowType = prop.PropertyType.GenericTypeArguments[0];
PropertyInfo[] properties = rowType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
var columns = new List<dynamic>();
foreach(PropertyInfo colProp in properties)
{
dynamic column = this.createElementByProp(colProp);
if(column != null)
{
var dic = column as IDictionary<string, Object>;
dic["cellType"] = dic["type"];
dic.Remove("type");
columns.Add(column);
}
}
el.TryAdd("columns", columns);
}
private bool isGenericListType(Type type)
{
return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>);
}
// Sets form element properties based upon `FormFieldAttribute` properties.
private void setElementAttrByFormFieldAttr(ExpandoObject el, CustomAttributeData attr)
{
var choicesByUrl = getAttributeValueByProp(attr, "ChoicesByUrl");
var choices = getAttributeValueByProp(attr, "Choices");
var fieldType = getAttributeValueByProp(attr, "FieldType");
var inputType = getAttributeValueByProp(attr, "InputType");
var dic = el as IDictionary<string, Object>;
if (fieldType == null && (choicesByUrl != null || choices != null))
{
fieldType = "dropdown";
}
if (fieldType != null)
{
dic["type"] = fieldType;
}
if(choicesByUrl != null)
{
el.TryAdd("choicesByUrl", new { url = choicesByUrl });
}
if(choices != null)
{
el.TryAdd("choices", convertToStringArray((ReadOnlyCollection<CustomAttributeTypedArgument>)choices));
}
if (inputType != null)
{
dic["inputType"] = inputType;
}
}
private dynamic createNewPage(IList<dynamic> elements, CustomAttributeData pageAttr)
{
var res = new ExpandoObject();
res.TryAdd("elements", elements);
var title = this.getAttributeValueByProp(pageAttr, "Title");
if(title != null)
{
res.TryAdd("title", title);
}
return res;
}
private CustomAttributeData getFormPageAttribute(PropertyInfo prop)
{
return prop.CustomAttributes.FirstOrDefault<CustomAttributeData>(item => item.AttributeType == typeof(FormPageAttribute));
}
private object getAttributeValueByProp(CustomAttributeData attr, string name)
{
if (attr == null) return null;
var arg = attr.NamedArguments.FirstOrDefault<CustomAttributeNamedArgument>(item => item.MemberName == name);
return arg != null ? arg.TypedValue.Value : null;
}
private bool hasProperty(ExpandoObject obj, string propName)
{
return ((IDictionary<String, object>)obj).ContainsKey(propName);
}
private string getTitleByName(string name)
{
string res = "";
for (int i = 0; i < name.Length; i++)
{
if (i > 0 && char.IsUpper(name[i]))
{
res += ' ';
}
res += name[i];
}
return res;
}
private string[] convertToStringArray(ReadOnlyCollection<CustomAttributeTypedArgument> val)
{
var res = new List<string>();
foreach(var obj in val)
{
res.Add(obj.Value.ToString());
}
return res.ToArray();
}
private static bool IsNumericType(Type type)
{
switch (Type.GetTypeCode(type))
{
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Single:
return true;
default:
return false;
}
}
}
}