forked from adlnet-archive/LR-Publisher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CsvToLrWindow.cs
359 lines (304 loc) · 11.5 KB
/
CsvToLrWindow.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
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
using System;
using System.Data;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using System.IO;
using System.Text;
using Gtk;
using LearningRegistry;
using LearningRegistry.RDDD;
using LumenWorks.Framework.IO.Csv;
public partial class CsvToLrWindow : Gtk.Window
{
private List<Label> _missingFields;
private List<string> _rawRowDataList = new List<string>();
private Dictionary<string, List<string>> _rowData;
private string[] _columns;
private DataTable _table;
List<Type> nestedTypes = new List<Type>()
{
typeof(lr_identity),
typeof(lr_TOS),
typeof(lr_digital_signature)
};
public CsvToLrWindow () :
base(Gtk.WindowType.Toplevel)
{
this.Build ();
}
public void PopulateFromCsv(string path)
{
loadFromCsv(path);
FieldInfo[] infos = typeof(lr_document).GetFields();
foreach(var info in infos)
{
var attrs = info.GetCustomAttributes(typeof(RequiredField), false);
if(attrs.Length > 0)
{
if(((RequiredField)attrs[0]).Immutable)
continue;
}
if(nestedTypes.Contains(info.FieldType))
{
//this is done internally
if(info.FieldType.Equals(typeof(lr_digital_signature)))
continue;
//Nesting only goes one level, which makes this work
foreach(var subInfo in info.FieldType.GetFields())
{
string name = String.Join(".", info.Name, subInfo.Name);
if(subInfo.GetCustomAttributes(typeof(LearningRegistry.RequiredField), true).Length > 0)
name = name.Insert(0, "*");
MapRowsContainer.Add(new CsvToLrMapRow(_columns, name));
}
}
else
{
string name = info.Name;
if(info.GetCustomAttributes(typeof(LearningRegistry.RequiredField), true).Length > 0)
name = name.Insert(0, "*");
CsvToLrMapRow row = new CsvToLrMapRow(_columns, name);
MapRowsContainer.Add(row);
}
}
}
private bool ValidateRequiredFields()
{
bool valid = true;
Gdk.Color black = new Gdk.Color();
Gdk.Color.Parse("black", ref black);
List<Label> missingFields = new List<Label>();
//Validate the rows
foreach(CsvToLrMapRow row in MapRowsContainer)
{
if (row.Key.Contains("*") && (
(row.DropDownValue == null && !row.IsConstant) ||
(row.IsConstant && String.IsNullOrEmpty(row.ConstantValue))
))
{
HBox container = (HBox)row.Children[0];
missingFields.Add((Label)container.Children[0]);
}
}
missingFields.AddRange(this.SignatureInformationWidget.GetMissingFields());
missingFields.AddRange(this.ServerInfoWidget.GetMissingFields());
if(this._missingFields != null)
{
foreach(var lbl in _missingFields)
{
if(missingFields.Where( x => x.LabelProp == lbl.LabelProp ).Count() == 0)
lbl.ModifyFg(StateType.Normal, black);
}
}
_missingFields = missingFields;
return _missingFields.Count == 0;
}
protected void ShowMissingFields()
{
Gdk.Color red = new Gdk.Color();
Gdk.Color.Parse("red", ref red);
foreach(var field in _missingFields)
field.ModifyFg(StateType.Normal, red);
PublishGUI.Helper.CreateNotficationWindow(PublishGUI.Helper.MSG_MISSING_FIELDS);
}
protected void PublishDocuments(object sender, EventArgs e)
{
bool validated = ValidateRequiredFields();
if(validated)
{
lr_Envelope envelope = buildEnvelopeFromMapping();
LRClient client = new LRClient(this.ServerInfoWidget.NodeUrl);
if (!String.IsNullOrEmpty(this.ServerInfoWidget.HttpUsername))
{
client.Username = ServerInfoWidget.HttpUsername;
client.Password = ServerInfoWidget.HttpPassword;
}
PublishResponse res = client.Publish(envelope);
buildAndShowNotification(res);
}
else
ShowMissingFields();
}
private void buildAndShowNotification(PublishResponse response)
{
StringBuilder sb = new StringBuilder();
bool success = response.OK;
if(!response.OK)
sb.AppendLine("General response error: " + response.error);
foreach(DocPublishResult docResult in response.document_results)
{
if(!docResult.OK)
{
success = false;
sb.AppendLine("Doc error: " + docResult.error);
}
}
if(success)
{
PublishGUI.Helper.SavePublishHistory(this.ServerInfoWidget.NodeUrl, response);
sb.AppendLine("Documents were successfully published!");
sb.AppendLine("To view the docs online, or for further information from the responses,"
+"you may go to History -> Show All in the main menu.");
}
else
sb.AppendLine("One or more errors occurred while publishing your documents. See above for detailed error report.");
PublishGUI.Helper.CreateNotficationWindow(sb.ToString());
}
private lr_Envelope buildEnvelopeFromMapping()
{
var sigInfo = this.SignatureInformationWidget;
PgpSigner signer = null;
bool needToSign = false;
if(sigInfo.SignatureType == PublishGUI.SignatureType.LR_PGP)
{
signer = new PgpSigner(sigInfo.PgpPublicKeyLocations,
sigInfo.PgpKeyringLocation,
sigInfo.PgpSecretKeyPassphrase);
needToSign = true;
}
Dictionary<string, string> map = new Dictionary<string, string>();
FieldInfo[] infos = typeof(lr_document).GetFields();
int j = 0;
for (int i = 0; i < MapRowsContainer.Children.Length; i++)
{
var info = infos[j];
var mapRow = (CsvToLrMapRow)MapRowsContainer.Children[i];
var customAttributes = info.GetCustomAttributes(typeof(RequiredField), false);
if (customAttributes.Length > 0)
{
RequiredField attr = (RequiredField)customAttributes[0];
if (attr.Immutable)
{
i--; //It was never added to the RowContainer, so we need to examine mapRow again with the next property
j++; //We examined the property, increment this index
continue;
}
}
if (nestedTypes.Contains(info.FieldType))
{
//Never added to RowContainer, decrement i and increment j
if (info.FieldType == typeof(lr_digital_signature))
{
i--;
j++;
continue;
}
foreach (var subInfo in info.FieldType.GetFields())
{
mapRow = (CsvToLrMapRow)MapRowsContainer.Children[i++];
string key = String.Join(".", info.Name, subInfo.Name);
map[key] = mapRow.DropDownValue;
}
if(info.FieldType.GetFields().Length > 0)
i--; //avoid double incrementing from loop iterator statment
j++;
}
else
map[infos[j++].Name] = mapRow.DropDownValue;
}
//Create the docs from the map and the dataDict
lr_Envelope envelope = new lr_Envelope();
for (int i = 0; i < _rawRowDataList.Count; i++)
{
lr_document doc = new lr_document();
int rowIndex = 0;
foreach (var info in infos)
{
CsvToLrMapRow currentRow = (CsvToLrMapRow)MapRowsContainer.Children[rowIndex++];
var customAttributes = info.GetCustomAttributes(typeof(RequiredField), false);
if(customAttributes.Length > 0 )
{
RequiredField attr = (RequiredField)customAttributes[0];
if (attr.Immutable)
{
rowIndex--;
continue;
}
}
if (!nestedTypes.Contains(info.FieldType))
{
string val;
if (currentRow.IsConstant)
val = currentRow.ConstantValue;
else if (currentRow.IsSerializeToRow)
val = _rawRowDataList[i];
else if (currentRow.DropDownValue == null)
continue; //Nothing to map to or assign if they did not choose a value from the dropdown
else
val = _rowData[map[info.Name]][i];
if (info.FieldType == typeof(List<string>))
{
List<string> vals = val.Split(',').ToList<string>();
info.SetValue(doc, vals);
}
else
info.SetValue(doc, Convert.ChangeType(val, info.FieldType));
}
else //This is a nested object property
{
var subFields = info.FieldType.GetFields();
object currentObj = info.GetValue(doc);
if (currentObj == null)
currentObj = new object();
rowIndex--;
if (typeof(lr_digital_signature).Equals(info.FieldType))
continue;
foreach (var subField in subFields)
{
var rowToAdd = MapRowsContainer.Children.Cast<CsvToLrMapRow>()
.Where(x =>
x.Key.Replace("*", "").Split('.')[0] == info.Name &&
x.Key.Replace("*", "").Split('.')[1] == subField.Name)
.ToList()[0];
rowIndex++; //Used another row from subInfo, need to update the index
string val;
if (rowToAdd.IsConstant)
val = rowToAdd.ConstantValue;
else if (rowToAdd.IsSerializeToRow)
val = _rawRowDataList[i];
else if (rowToAdd.DropDownValue == null)
continue;
else
val = _rowData[map[String.Join(".", info.Name, subField.Name)]][i];
if (subField.FieldType == typeof(List<string>))
{
List<string> vals = val.Split(',').ToList<string>();
subField.SetValue(currentObj, vals);
}
else
subField.SetValue(currentObj, val);
}
}
}
if(needToSign)
doc = signer.Sign(doc);
envelope.documents.Add(doc);
}
return envelope;
}
private void loadFromCsv(string path)
{
using (CsvReader csv = new CsvReader(new StreamReader(path), true))
{
_columns = csv.GetFieldHeaders();
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
Dictionary<string, List<string>> data = new Dictionary<string, List<string>>();
List<string> rawRowDataList = new List<string>();
while (csv.ReadNextRecord())
{
var rowDict = new Dictionary<string, string>();
for (int i = 0; i < csv.FieldCount; i++)
{
if (!data.ContainsKey(_columns[i]))
data[_columns[i]] = new List<string>();
data[_columns[i]].Add(csv[i]);
rowDict[_columns[i]] = csv[i];
}
rawRowDataList.Add(serializer.Serialize(rowDict));
}
_rawRowDataList = rawRowDataList;
_rowData = data;
}
}
}