-
Notifications
You must be signed in to change notification settings - Fork 2
/
DatasetGenerator.cs
1590 lines (1392 loc) · 53.8 KB
/
DatasetGenerator.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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#region license
/*
Copyright 2005 - 2021 Advantage Solutions, s. r. o.
This file is part of ORIGAM (http://www.origam.org).
ORIGAM is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ORIGAM is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with ORIGAM. If not, see <http://www.gnu.org/licenses/>.
*/
#endregion
using System;
using System.Data;
using System.Collections;
using System.Text;
using System.Globalization;
using Origam.Services;
using Origam.Workbench.Services;
using Origam.Schema;
using Origam.Schema.EntityModel;
using Origam.Schema.WorkflowModel;
namespace Origam.DA.Service
{
/// <summary>
/// Summary description for DatasetGenerator.
/// </summary>
public class DatasetGenerator
{
private IParameterService _parameterService = ServiceManager.Services.GetService(typeof(IParameterService)) as IParameterService;
// removed to Da.Common Const.
// const string DefaultHideUIAttribute = "DefaultHideUI";
// const string DefaultLookupIdAttribute = "DefaultLookupId";
public DatasetGenerator(bool userDefinedParameters)
{
this.UserDefinedParameters = userDefinedParameters;
}
private bool _userDefinedParameters = false;
public bool UserDefinedParameters
{
get
{
return _userDefinedParameters;
}
set
{
_userDefinedParameters = value;
}
}
private void AddExtendedProperties(PropertyCollection collection, Key primaryKey)
{
foreach(DictionaryEntry entry in primaryKey)
collection.Add(entry.Key, entry.Value);
}
/* @short Evaluates parameter value. Firstly look into custom parameters
* (e.g. parCurrentOrganizationId, etc.) and if not found there look at
* the incoming parameter. If found, returns a parameter value otherwise
* returns null.
* */
private static object EvaluateParameters(System.Data.DataColumn c,
object param,
UserProfile profile,
IDictionary parameters)
{
// try custom parameters first
ICustomParameter customParameter =
CustomParameterService.MatchParameter((string) param);
if (customParameter != null)
{
object val = customParameter.Evaluate(profile);
if (c.DataType == typeof(string) && val != null)
{
return val.ToString();
}
else
{
return val;
}
}
// try ordinary input parameters
if (parameters.Contains(param))
{
object val = parameters[param];
if(c.DataType == typeof(string) && val != null)
{
return val.ToString();
}
else
{
return val;
}
}
return null;
}
public static void ApplyDynamicDefaults(DataSet data, IDictionary parameters)
{
UserProfile profile = SecurityManager.CurrentUserProfile();
foreach(DataTable t in data.Tables)
{
foreach(DataColumn c in t.Columns)
{
if(c.ExtendedProperties.Contains("DynamicEntityDefaultParameter"))
{
// defaultValue parameter name defined on entity level
object entityParam = c.ExtendedProperties["DynamicEntityDefaultParameter"];
c.DefaultValue = EvaluateParameters(c, entityParam, profile, parameters);
}
if (c.ExtendedProperties.Contains("DynamicDefaultParameter"))
{
// defaultValue parameter name defined on datastructure default set level
// (overrides entity-level settings)
object param = c.ExtendedProperties["DynamicDefaultParameter"];
c.DefaultValue = EvaluateParameters(c, param, profile, parameters);
}
}
}
}
public DataSet CreateDataSet(IDataEntity entity)
{
return CreateDataSet(entity, null);
}
public DataSet CreateDataSet(IDataEntity entity, CultureInfo culture)
{
DataSet dataset = new DataSet(dataSetName);
if (culture == null)
{
culture = System.Globalization.CultureInfo.CurrentUICulture;
}
dataset.Locale = culture;
AddTableFromEntity(entity, entity.Name, dataset);
return dataset;
}
private void AddTableFromEntity(IDataEntity entity, string name, DataSet dataset)
{
ArrayList arrayTypeEntities = new ArrayList();
// Add the table
DataTable table = new OrigamDataTable(name);
table.Locale = dataset.Locale;
AddTableExtendedProperties(table, entity);
// Add columns
foreach (IDataEntityColumn column in entity.EntityColumns)
{
if (!column.ExcludeFromAllFields)
{
DataColumn tableColumn = new DataColumn(
column.Name,
ConvertDataType(column.DataType)
);
AddColumnExtendedProperties(tableColumn, column, entity,
column.DefaultLookup);
tableColumn.Caption = GetCaption(column);
tableColumn.AllowDBNull = column.AllowNulls;
if (column.DataType == OrigamDataType.Boolean)
{
tableColumn.DefaultValue = false;
}
switch (column.XmlMappingType)
{
case EntityColumnXmlMapping.Element:
tableColumn.ColumnMapping = MappingType.Element;
break;
case EntityColumnXmlMapping.Attribute:
tableColumn.ColumnMapping = MappingType.Attribute;
break;
default:
throw new ArgumentOutOfRangeException("XmlMappingType", column.XmlMappingType, ResourceUtils.GetString("UnknownXmlMapping"));
}
if (column.DefaultValue != null)
{
tableColumn.DefaultValue = RenderDefaultValue(column.DefaultValue);
}
if (column.DataType == OrigamDataType.String)
{
tableColumn.MaxLength = column.DataLength;
}
DetachedField detachedField = column as DetachedField;
if (detachedField != null && detachedField.DataType == OrigamDataType.Array)
{
string relationName = detachedField.ArrayRelation.Name;
tableColumn.ExtendedProperties.Add(Const.ArrayRelation, relationName);
tableColumn.ExtendedProperties.Add(Const.ArrayRelationField, detachedField.ArrayValueField.Name);
if (!arrayTypeEntities.Contains(relationName))
{
arrayTypeEntities.Add(relationName);
}
}
table.Columns.Add(tableColumn);
if (column.IsPrimaryKey)
{
AddPrimaryKey(table, column, tableColumn);
}
}
}
dataset.Tables.Add(table);
// add children tables for array-type relationships
foreach (IAssociation relation in entity.EntityRelations)
{
if (arrayTypeEntities.Contains(relation.Name))
{
AddTableFromEntity(relation.AssociatedEntity, relation.Name, dataset);
AddRelation(dataset, entity.Name, relation, entity.Name, relation.Name, relation.Name);
}
}
}
private static void AddPrimaryKey(DataTable table, IDataEntityColumn column, DataColumn tableColumn)
{
//PrimaryKey
int oldCount = table.PrimaryKey.Length;
DataColumn[] keys = new DataColumn[++oldCount];
table.PrimaryKey.CopyTo(keys, 0);
keys.SetValue(tableColumn, --oldCount);
table.Constraints.Add("PK_" + column.Name, keys, true);
//tableColumn.Unique = true;
}
public DataSet CreateDataSet(DataStructure ds)
{
return this.CreateDataSet(ds, true);
}
public DataSet CreateDataSet(DataStructure ds, CultureInfo culture)
{
return this.CreateDataSet(ds, true, null, culture);
}
public DataSet CreateDataSet(DataStructure ds, DataStructureDefaultSet defaultSet)
{
return this.CreateDataSet(ds, true, defaultSet);
}
public DataSet CreateDataSet(DataStructure ds, bool includeCalculatedColumns)
{
return this.CreateDataSet(ds, true, null);
}
private Hashtable GetCache()
{
Hashtable context = OrigamUserContext.Context;
if(! context.Contains("DataStructureCache"))
{
context.Add("DataStructureCache", new Hashtable());
}
return (Hashtable)OrigamUserContext.Context["DataStructureCache"];
}
public DataSet CreateDataSet(DataStructure ds, bool includeCalculatedColumns, DataStructureDefaultSet defaultSet)
{
return CreateDataSet(ds, includeCalculatedColumns, defaultSet, null);
}
public DataSet CreateDataSet(DataStructure ds, bool includeCalculatedColumns,
DataStructureDefaultSet defaultSet, CultureInfo culture)
{
return CreateDataSet(ds, includeCalculatedColumns, defaultSet, culture, false);
}
private DataSet CreateDataSet(DataStructure ds, bool includeCalculatedColumns,
DataStructureDefaultSet defaultSet, CultureInfo culture, bool forceBuildFromDatastructure)
{
if(ds == null) throw new ArgumentNullException("ds", ResourceUtils.GetString("ErrorDatastructureNull"));
Hashtable dsCache = GetCache();
string cacheKey = ds.Id.ToString() + (defaultSet == null ? Guid.Empty.ToString() : defaultSet.Id.ToString());
// get strongly typed dataset class
if (ds.DataSetClass != null && ds.DataSetClass.Trim() != "" && !forceBuildFromDatastructure)
{
// get DS from strongly typed dataset class
string[] splittedDataSetClass = ds.DataSetClass.Split(',');
if(splittedDataSetClass.Length < 2)
{
throw new ArgumentException(
ResourceUtils.GetString("ErrorDataSetClassInvalid"),
"DataSetClass");
}
DataSet outDS = Reflector.InvokeObject(splittedDataSetClass[0].Trim(), splittedDataSetClass[1].Trim()) as DataSet;
outDS.DataSetName = dataSetName;
// get DS generated from datastructure
// try to get from cache
if (dsCache.Contains(cacheKey) && includeCalculatedColumns)
{
DataSet cachedDS = dsCache[cacheKey] as DataSet;
return CopyPropertiesToTypedOneDataSet(cachedDS, outDS);
}
DataSet generatedDS = CreateDataSet(ds, includeCalculatedColumns, defaultSet, culture, true);
return CopyPropertiesToTypedOneDataSet(generatedDS, outDS);
}
if(dsCache.Contains(cacheKey) & includeCalculatedColumns)
{
DataSet clone = DatasetTools.CloneDataSet((dsCache[cacheKey] as DataSet));
return clone;
}
DataSet dataset = new DataSet(dataSetName);
StateMachineSchemaItemProvider states = (ServiceManager.Services.GetService(typeof(ISchemaService)) as ISchemaService).GetProvider(typeof(StateMachineSchemaItemProvider)) as StateMachineSchemaItemProvider;
//dataset.BeginInit();
if(culture == null)
{
culture = CultureInfo.CurrentUICulture;
}
dataset.Locale = culture;
AddExtendedProperties(dataset.ExtendedProperties, ds.PrimaryKey);
//dataset.EndInit();
ArrayList entities = ds.Entities;
ArrayList aggregatedColumns = new ArrayList();
// Add tables
foreach(DataStructureEntity entity in entities)
{
// Skip self joins - they will be added only as relations
if(!(entity.Entity is IAssociation && (entity.Entity as IAssociation).IsSelfJoin) && entity.Columns.Count > 0)
{
ArrayList nonPhysicalColumns = new ArrayList();
DataTable table = new OrigamDataTable(entity.Name);
//table.BeginInit();
table.Locale = dataset.Locale;
AddTableExtendedProperties(table, entity);
// Set caption
if(entity.Caption == null || entity.Caption == "")
{
if(entity.EntityDefinition.Caption == null || entity.EntityDefinition.Caption == "")
{
table.DisplayExpression = DatasetTools.TextExpression(entity.Name);
}
else
{
table.DisplayExpression = DatasetTools.TextExpression(entity.EntityDefinition.Caption);
}
}
else
table.DisplayExpression = DatasetTools.TextExpression(entity.Caption);
//table.EndInit();
// Add columns
foreach(DataStructureColumn column in entity.Columns)
{
bool isCalculated = false;
DataStructureColumn finalColumn = column.FinalColumn;
OrigamDataType finalDataType = column.DataType;
DataColumn tableColumn = new DataColumn(
column.Name,
ConvertDataType(finalDataType)
);
tableColumn.ExtendedProperties.Add(Const.OrigamDataType, finalDataType);
tableColumn.ExtendedProperties.Add(Const.FieldId, finalColumn.Id);
switch(column.Field)
{
// mark column as a database field if the entity column
// is of type FieldMappingItem and the datastructure column
// doesn't have 'UseLookupValue' set (read-only datastructure lookups
// aren't saveable so they aren't actually database fields)
case FieldMappingItem _:
tableColumn.ExtendedProperties.Add(
Const.IsDatabaseField, !column.UseLookupValue);
break;
case DetachedField detachedField
when detachedField.DataType == OrigamDataType.Array:
{
var relatedEntity = LookupRelation(
entity, detachedField.ArrayRelation);
if(relatedEntity == null)
{
throw new Exception(
"Data Structure does not contain entity " +
detachedField.ArrayRelation.Name +
" that is required for creating an Array field "
+ detachedField.Path);
}
tableColumn.ExtendedProperties.Add(
Const.ArrayRelation, relatedEntity.Name);
tableColumn.ExtendedProperties.Add(
Const.ArrayRelationField,
LookupColumnName(relatedEntity, detachedField.ArrayValueField));
aggregatedColumns.Add(column);
break;
}
}
// Set caption
if(column.Caption == null || column.Caption == "")
{
tableColumn.Caption = GetCaption(column.Field);
}
else
{
tableColumn.Caption = column.Caption;
}
if(finalDataType == OrigamDataType.Boolean)
{
tableColumn.DefaultValue = false;
}
if(column.IsWriteOnly)
{
tableColumn.ExtendedProperties.Add(Const.IsWriteOnlyAttribute, true);
}
// Skip allow nulls on looked-up columns. With these it is never clear, if we get a value or not
// The same e.g. with aliased primary key
if(column.UseLookupValue || column.UseCopiedValue
|| column.Entity != null || column.IsWriteOnly)
{
tableColumn.AllowDBNull = true;
}
else
{
tableColumn.AllowDBNull = finalColumn.Field.AllowNulls;
if(! finalColumn.Field.AllowNulls)
{
tableColumn.ExtendedProperties.Add("AllowNulls", false);
}
}
//tableColumn.ReadOnly = (entity.EntityDefinition.EntityIsReadOnly | column.UseLookupValue) ? true : column.Field.ReadOnly;
tableColumn.AutoIncrement = finalColumn.Field.AutoIncrement;
tableColumn.AutoIncrementSeed = finalColumn.Field.AutoIncrementSeed;
tableColumn.AutoIncrementStep = finalColumn.Field.AutoIncrementStep;
switch(column.XmlMappingType)
{
case DataStructureColumnXmlMappingType.Default:
switch(column.Field.XmlMappingType)
{
case EntityColumnXmlMapping.Element:
tableColumn.ColumnMapping = MappingType.Element;
break;
case EntityColumnXmlMapping.Attribute:
tableColumn.ColumnMapping = MappingType.Attribute;
break;
case EntityColumnXmlMapping.Hidden:
tableColumn.ColumnMapping = MappingType.Hidden;
break;
default:
throw new ArgumentOutOfRangeException("XmlMappingType", finalColumn.Field.XmlMappingType, "Unknown XmlMappingType");
}
break;
case DataStructureColumnXmlMappingType.Attribute:
tableColumn.ColumnMapping = MappingType.Attribute;
break;
case DataStructureColumnXmlMappingType.Element:
tableColumn.ColumnMapping = MappingType.Element;
break;
default:
throw new ArgumentOutOfRangeException("XmlMappingType", finalColumn.XmlMappingType, "Unknown XmlMappingType");
}
if (column.HideInOutput)
{
tableColumn.ColumnMapping = MappingType.Hidden;
}
tableColumn.ExtendedProperties.Add("OnCopyAction", finalColumn.Field.OnCopyAction);
// auditing exclusion
AbstractDataEntityColumn dataField = column.Field as AbstractDataEntityColumn;
EntityAuditingType auditing = entity.EntityDefinition.AuditingType;
if (dataField != null && dataField.ExcludeFromAuditing)
{
auditing = EntityAuditingType.None;
}
tableColumn.ExtendedProperties.Add(Const.EntityAuditingAttribute, auditing);
StateMachine sm = null;
if(states != null)
{
sm = states.GetMachine((Guid)entity.EntityDefinition.PrimaryKey["Id"], (Guid)finalColumn.Field.PrimaryKey["Id"]);
}
if(sm == null)
{
SetDefault(defaultSet, finalColumn, entity, tableColumn);
}
else
{
// we have a state machine, we use its initial state as default value
object[] initStates = sm.InitialStateValues(null);
// if(initStates.Length == 0)
// {
// throw new ArgumentNullException("InitialState", ResourceUtils.GetString("ErrorNoInitialState", entity.Name, tableColumn.ColumnName));
// }
if(initStates.Length == 1)
{
tableColumn.DefaultValue = initStates[0];
}
else
{
// more than 1 initial state - we have to use the default, otherwise no default value
SetDefault(defaultSet, finalColumn, entity, tableColumn);
}
tableColumn.ExtendedProperties.Add("IsState", true);
}
if(finalDataType == OrigamDataType.String)
{
tableColumn.MaxLength = finalColumn.Field.DataLength;
}
if(column.UseCopiedValue)
{
AddExtendedProperties(tableColumn.ExtendedProperties,
new ModelElementKey(Guid.Empty));
tableColumn.ExtendedProperties.Add(Const.OriginalFieldId, column.Field.PrimaryKey["Id"]);
tableColumn.ExtendedProperties.Add(Const.IsAddittionalFieldAttribute, true);
}
else if(column.UseLookupValue)
{
// Save the original field and lookup for the rule engine so it can refresh the data
// when the original field value changes.
tableColumn.ExtendedProperties.Add(Const.OriginalLookupIdAttribute, column.FinalLookup.PrimaryKey["Id"]);
LookupField lookupField = column.Field as LookupField;
if(lookupField != null)
{
AddExtendedProperties(tableColumn.ExtendedProperties, column.Field.PrimaryKey);
tableColumn.ExtendedProperties.Add(Const.OriginalFieldId, lookupField.FieldId);
}
else
{
AddExtendedProperties(tableColumn.ExtendedProperties, finalColumn.PrimaryKey);
tableColumn.ExtendedProperties.Add(Const.OriginalFieldId, column.Field.PrimaryKey["Id"]);
tableColumn.ExtendedProperties.Add(Const.IsAddittionalFieldAttribute, true);
}
}
else
{
AddExtendedProperties(tableColumn.ExtendedProperties, finalColumn.Field.PrimaryKey);
// Put default lookup to the extended properties, so it can be mapped
// automatically in the designer to the combo box.
if(column.FinalLookup != null)
{
tableColumn.ExtendedProperties.Add(Const.DefaultLookupIdAttribute, column.FinalLookup.PrimaryKey["Id"]);
}
FunctionCall functionCall = column.Field as FunctionCall;
if(column.Entity == null && functionCall != null && functionCall.Function.FunctionType == OrigamFunctionType.Standard
&& functionCall.ForceDatabaseCalculation == false && column.Aggregation == AggregationType.None)
{
isCalculated = true;
if(includeCalculatedColumns)
{
nonPhysicalColumns.Add(column);
}
}
if(column.Field is AggregatedColumn
||
column.IsFromParentEntity())
{
isCalculated = true;
if(includeCalculatedColumns)
{
aggregatedColumns.Add(column);
}
}
}
if(includeCalculatedColumns || (includeCalculatedColumns == false && isCalculated == false))
{
table.Columns.Add(tableColumn);
}
// mark a primary key only for the physical fields from the original entity
if(column.Field.IsPrimaryKey && column.UseLookupValue == false && column.UseCopiedValue == false
&& column.IsWriteOnly == false && column.Entity == null && column.Aggregation == AggregationType.None)
{
bool columnInPkAlready = DatasetTools.IsAliasedColumn(table.PrimaryKey, (Guid)column.Field.PrimaryKey["Id"]);
if(! columnInPkAlready)
{
//PrimaryKey
int oldCount = table.PrimaryKey.Length;
DataColumn[] keys = new DataColumn[++oldCount];
table.PrimaryKey.CopyTo(keys, 0);
keys.SetValue(tableColumn, --oldCount);
table.Constraints.Add("PK_" + column.Name, keys, true);
//tableColumn.Unique = true;
}
}
}
foreach(DataStructureColumn column in nonPhysicalColumns)
{
try {
table.Columns[column.Name].Expression = RenderExpression(column.Field, entity);
} catch (Exception e)
{
throw new OrigamException(string.Format("Error occured while rendering column `{0}', ({1}) - {2}",
(column as AbstractSchemaItem), (column as AbstractSchemaItem).Id, e.Message), e);
}
}
dataset.Tables.Add(table);
}
}
AddQueryRelations(dataset, ds);
foreach(DataStructureColumn column in aggregatedColumns)
{
DataStructureEntity entity = column.ParentItem as DataStructureEntity;
if(column.IsFromParentEntity())
{
dataset.Tables[entity.Name].Columns[column.Name].Expression = RenderParentField(column);
}
else
{
dataset.Tables[entity.Name].Columns[column.Name].Expression = RenderExpression(column.Field, entity);
}
if(!dataset.Tables[entity.Name].ExtendedProperties.ContainsKey(Const.HasAggregation))
{
dataset.Tables[entity.Name].ExtendedProperties.Add(Const.HasAggregation, true);
}
}
if(includeCalculatedColumns)
{
lock(dsCache)
{
DataSet clone = DatasetTools.CloneDataSet(dataset);
if (!dsCache.Contains(cacheKey))
{
dsCache.Add(cacheKey, dataset);
}
return clone;
}
}
return dataset;
}
private DataSet CopyPropertiesToTypedOneDataSet(DataSet origamDS, DataSet typedDS)
{
foreach (DataTable origamTable in origamDS.Tables)
{
// find table in typedDS
DataTable typedTable = typedDS.Tables[origamTable.TableName];
if (typedTable == null)
{
continue;
}
// process table extended properties
typedTable.ExtendedProperties.Clear();
foreach (DictionaryEntry item in origamTable.ExtendedProperties)
{
typedTable.ExtendedProperties.Add(item.Key, item.Value);
}
// process columns
foreach (DataColumn origamColumn in origamTable.Columns)
{
// find column in typed DS
DataColumn typedColumn = typedTable.Columns[origamColumn.ColumnName];
if (typedColumn == null)
{
continue;
}
// process column extended properties and default values
typedColumn.ExtendedProperties.Clear();
foreach (DictionaryEntry item in origamColumn.ExtendedProperties)
{
typedColumn.ExtendedProperties.Add(item.Key, item.Value);
typedColumn.DefaultValue = origamColumn.DefaultValue;
}
}
}
return typedDS;
}
private void SetDefault(DataStructureDefaultSet defaultSet, DataStructureColumn finalColumn, DataStructureEntity entity, DataColumn column)
{
// mark the dynamic default parameter form entity-level-defined 'DefaultValueParameter'
if (finalColumn.Field.DefaultValueParameter != null)
{
column.ExtendedProperties.Add("DynamicEntityDefaultParameter",
finalColumn.Field.DefaultValueParameter.Name);
}
// check if the default set has a default for this column
if(defaultSet != null)
{
foreach(DataStructureDefaultSetDefault d in defaultSet.ChildItemsByType(DataStructureDefaultSetDefault.CategoryConst))
{
if(d.Field.PrimaryKey.Equals(finalColumn.Field.PrimaryKey) & d.Entity.PrimaryKey.Equals(entity.PrimaryKey))
{
if(d.Default != null)
{
column.DefaultValue = RenderDefaultValue(d.Default);
}
// mark the dynamic default parameter
if(d.Parameter != null)
{
column.ExtendedProperties.Add("DynamicDefaultParameter", d.Parameter.Name);
}
return;
}
}
}
// no state machine and no default from the default set, we use the default value from the entity
if(finalColumn.Field.DefaultValue != null)
{
column.DefaultValue = RenderDefaultValue(finalColumn.Field.DefaultValue);
}
}
public DataSet CreateUpdateFieldDataSet(TableMappingItem table, FieldMappingItem field)
{
DataSet ds = new DataSet(dataSetName);
ds.Locale = System.Globalization.CultureInfo.CurrentUICulture;
DataTable dt = ds.Tables.Add(table.Name);
dt.Locale = ds.Locale;
AddTableExtendedProperties(dt, table);
foreach(IDataEntityColumn col in table.EntityPrimaryKey)
{
DataColumn dtc = dt.Columns.Add(col.Name, ConvertDataType(col.DataType));
AddColumnExtendedProperties(dtc, col, table, col.DefaultLookup);
AddPrimaryKey(dt, col, dtc);
}
DataColumn fieldDtc = dt.Columns.Add(field.Name, ConvertDataType(field.DataType));
AddColumnExtendedProperties(fieldDtc, field, table, field.DefaultLookup);
return ds;
}
private string GetCaption(IDataEntityColumn column)
{
string result;
// if there is just 1 dynamic label and it is actually static (never changes)
// we take it as the default label so it can be used also in empty form or grid column
// label
ArrayList dynamicLabels = column.ChildItemsByType(EntityFieldDynamicLabel.CategoryConst);
EntityFieldDynamicLabel dynamicLabel = null;
if(dynamicLabels.Count == 1)
{
EntityFieldDynamicLabel lbl = dynamicLabels[0] as EntityFieldDynamicLabel;
if(lbl.IsStatic)
{
dynamicLabel = lbl;
}
}
if(dynamicLabel != null)
{
result = (string)_parameterService.GetParameterValue(dynamicLabel.LabelConstantId, OrigamDataType.String);
}
else if(column.Caption == null || column.Caption == "")
{
result = column.Name;
}
else if(IsCaptionExpression(column.Caption))
{
// expression
result = EvaluateCaptionExpression(column.Caption);
}
else
{
result = column.Caption;
}
return result;
}
public static bool IsCaptionExpression(string caption)
{
return caption.StartsWith("{") && caption.EndsWith("}");
}
public static string EvaluateCaptionExpression(string caption)
{
string expression = caption.Substring(1, caption.Length - 2);
IRuleEngineService re = ServiceManager.Services.GetService(typeof(IRuleEngineService)) as IRuleEngineService;
return re.EvaluateExpression(expression);
}
private void AddTableExtendedProperties(DataTable table, DataStructureEntity entity)
{
AddExtendedProperties(table.ExtendedProperties, entity.PrimaryKey);
AddTableExtendedProperties(table, entity.EntityDefinition);
}
private void AddTableExtendedProperties(DataTable table, IDataEntity entity)
{
table.ExtendedProperties.Add("EntityId", entity.PrimaryKey["Id"]);
table.ExtendedProperties.Add(Const.EntityAuditingAttribute, entity.AuditingType);
table.ExtendedProperties.Add(
Const.AuditingSecondReferenceKeyColumnAttribute,
entity.AuditingSecondReferenceKeyColumn);
if(entity.DescribingField != null)
{
table.ExtendedProperties.Add(Const.DescribingField, entity.DescribingField.Name);
}
}
private void AddColumnExtendedProperties(DataColumn tableColumn,
IDataEntityColumn column, IDataEntity entity, IDataLookup dataLookup)
{
tableColumn.ExtendedProperties.Add(Const.OrigamDataType, column.DataType);
AddExtendedProperties(tableColumn.ExtendedProperties, column.PrimaryKey);
if(! column.AllowNulls)
{
tableColumn.ExtendedProperties.Add("AllowNulls", false);
}
tableColumn.ExtendedProperties.Add("OnCopyAction", column.OnCopyAction);
// Put default lookup to the extended properties, so it can be mapped
// automatically in the designer to the combo box.
if(dataLookup != null)
{
tableColumn.ExtendedProperties.Add(Const.DefaultLookupIdAttribute, dataLookup.PrimaryKey["Id"]);
}
// auditing exclusion
EntityAuditingType auditing = !(column is DetachedField)
? entity.AuditingType : EntityAuditingType.None;
if (column is FieldMappingItem databaseField)
{
tableColumn.ExtendedProperties.Add(Const.IsDatabaseField, true);
auditing = !databaseField.ExcludeFromAuditing ?
entity.AuditingType : EntityAuditingType.None;
}
tableColumn.ExtendedProperties.Add(Const.EntityAuditingAttribute, auditing);
}
private void AddQueryRelations(DataSet dataset, DataStructure ds)
{
dataset.Relations.Clear();
ArrayList entities = ds.Entities;
string debugPath = ds.Path;
foreach(DataStructureEntity entity in entities)
{
IAssociation assoc = entity.Entity as IAssociation;
if(assoc != null && entity.Columns.Count > 0)
{
if(assoc.IsOR) throw new InvalidOperationException("IsOR = true not supported for data structures, only for data filtering.");
string baseEntityName = entity.ParentItem.Name;
string relatedEntityName = entity.Name;
string relationName = entity.Name;
relatedEntityName = AddRelation(dataset, debugPath, assoc, baseEntityName, relatedEntityName, relationName);
}
}
}
private static string AddRelation(DataSet dataset, string debugPath, IAssociation assoc, string baseEntityName, string relatedEntityName, string relationName)
{
ArrayList entityItems = assoc.ChildItemsByType(EntityRelationColumnPairItem.CategoryConst);
DataColumn[] baseColumns = new DataColumn[entityItems.Count];
DataColumn[] relatedColumns = new DataColumn[entityItems.Count];
if (assoc.IsSelfJoin)
{
relatedEntityName = baseEntityName;
}
for (int i = 0; i < entityItems.Count; i++)
{
DataTable baseTable = dataset.Tables[baseEntityName];
DataTable relatedTable = dataset.Tables[relatedEntityName];
string baseFieldName = (entityItems[i] as EntityRelationColumnPairItem
).BaseEntityField.Name;
string relatedFieldName = (entityItems[i] as EntityRelationColumnPairItem
).RelatedEntityField.Name;
if (baseTable == null)
{
throw new ArgumentOutOfRangeException("baseEntityName",
string.Format("Cannot create relation {0} > {1}. {0} entity is not present because it contains no fields. DataStructure: {2}.",
baseEntityName, relatedEntityName, debugPath
));
}
if (relatedTable == null)
{
throw new ArgumentOutOfRangeException("relatedEntityName",
string.Format("Cannot create relation {0} > {1}. {1} entity is not present because it contains no fields. DataStructure: {2}.",
baseEntityName, relatedEntityName, debugPath
));
}
if (!baseTable.Columns.Contains(baseFieldName))
{
throw new ArgumentOutOfRangeException("baseFieldName",
string.Format("Cannot create relation {0} > {1}. {0} entity does not contain field {2}. DataStructure: {3}.",
baseEntityName, relatedEntityName, baseFieldName, debugPath
));
}
if (!relatedTable.Columns.Contains(relatedFieldName))
{
throw new ArgumentOutOfRangeException("relatedFieldName",
string.Format("Cannot create relation {0} > {1}. {1} entity does not contain field {2}. DataStructure: {3}.",
baseEntityName, relatedEntityName, relatedFieldName, debugPath
));
}
baseColumns[i] = baseTable.Columns[baseFieldName];
relatedColumns[i] = relatedTable.Columns[relatedFieldName];
}
DataRelation relation;
try
{
// This is a relation - not a base entity
relation = dataset.Relations.Add(
relationName,
baseColumns,
relatedColumns,
false
);
}
catch (Exception ex)
{
throw new Exception(ResourceUtils.GetString("ErrorCreateRelation", baseEntityName, relatedEntityName, debugPath), ex);
}
if (baseColumns[0].Unique) // Only make such a key on parent(PK)-child(FK)
{
try
{
ForeignKeyConstraint fkConstraint = new ForeignKeyConstraint(
"FK_" + baseEntityName,
baseColumns,
relatedColumns
);
fkConstraint.AcceptRejectRule = AcceptRejectRule.None;
fkConstraint.UpdateRule = System.Data.Rule.Cascade;
fkConstraint.DeleteRule = System.Data.Rule.Cascade;
dataset.Tables[relatedEntityName].Constraints.Add(fkConstraint);
}
catch
{
}
}
relation.Nested = assoc.IsParentChild;
return relatedEntityName;
}
public static Type ConvertDataType(OrigamDataType dataType)
{
Type returnType;
switch(dataType)
{
case OrigamDataType.Blob:
returnType = typeof(Byte[]);
break;
case OrigamDataType.Boolean:
returnType = typeof(System.Boolean);
break;
case OrigamDataType.Byte:
returnType = typeof(System.Byte);
break;
case OrigamDataType.Currency:
returnType = typeof(System.Decimal);
break;
case OrigamDataType.Date:
returnType = typeof(System.DateTime);
break;
case OrigamDataType.Array:
case OrigamDataType.Long:
returnType = typeof(System.Int64);
break;
case OrigamDataType.Float:
returnType = typeof(System.Decimal);