-
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathLcmMetaDataCache.cs
More file actions
1458 lines (1275 loc) · 49 KB
/
LcmMetaDataCache.cs
File metadata and controls
1458 lines (1275 loc) · 49 KB
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
// Copyright (c) 2007-2017 SIL International
// This software is licensed under the LGPL, version 2.1 or later
// (http://www.gnu.org/licenses/lgpl-2.1.html)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using SIL.LCModel.Core.Cellar;
using SIL.LCModel.Core.KernelInterfaces;
using SIL.LCModel.Utils;
// Needed for Marshal
// To load meta data cache file data.
//using SIL.Utils;
/* From Field$ table
*
* Id - Standard Flid: MDC:int/DB:int *All
* Type, Field Type: int *All
* Class, Id of class with field: MDC:int/DB:int *All
* Name, String/DB:nvarcher(100) *All
*
* DstCls, Signature of object in the field. *Null/0 for non-model object).
*
* Custom, byte/DB:tinyint *Custom
* CustomId, Guid *Custom
* Min, long/DB:bigint *Custom
* Max, long/DB:bigint *Custom
* Big, bool/DB:bit *Custom
* UserLabel, String/DB:nvarcher(100) *Custom
* HelpString, String/DB:nvarcher(100) *Custom
* ListRootId, int *Custom
* WsSelector, int *Custom
* XmlUI, string/DB:ntext *Custom
*/
namespace SIL.LCModel.Infrastructure.Impl
{
/// <summary>
/// Implementation of the IFwMetaDataCache interface for LcmCache.
/// </summary>
/// ----------------------------------------------------------------------------------------
/// <remarks>
/// We add 'extra' for virtual, virtual generated (back references),
/// and user created custom fields. This addon fluff should keep us well within
/// the Int32 Max size of 2,147,483,647, even without having to use
/// 0 or the negative values.
/// 1,000,000,000 addon for virtual generated properties
/// 1,100,000,000 addon for virtual hand made properties.
/// 2,000,000,000 addon for custom properties.
/// </remarks>
/// ----------------------------------------------------------------------------------------
[ComVisible(true)]
internal sealed class LcmMetaDataCache : IFwMetaDataCacheManaged, IFwMetaDataCacheManagedInternal
{
#region Data Members for IFwMetaDataCache Support
private readonly bool m_initialized = true;
private readonly Dictionary<int, MetaClassRec> m_metaClassRecords = new Dictionary<int, MetaClassRec>();
private readonly Dictionary<string, int> m_nameToClid = new Dictionary<string, int>();
private readonly Dictionary<int, MetaFieldRec> m_metaFieldRecords = new Dictionary<int, MetaFieldRec>();
private readonly Dictionary<string, int> m_nameToFlid = new Dictionary<string, int>();
private readonly Dictionary<int, int> m_clidToNextCustomFlid = new Dictionary<int, int>();
private readonly HashSet<MetaFieldRec> m_customFields = new HashSet<MetaFieldRec>();
private readonly HashSet<int> m_analysisClids = new HashSet<int>();
#endregion Data Members for IFwMetaDataCache Support
#region Construction
private static readonly object s_constructorLock = new object();
/// <summary>
/// Constructor.
/// </summary>
internal LcmMetaDataCache()
{
lock (s_constructorLock)
{
m_initialized = false;
// Reset static counters for attrs.
VirtualPropertyAttribute.ResetFlidCounter();
FieldDescription.ClearDataAbout();
var cmObjectTypesBaseFirst = CmObjectTypesBaseFirst();
CmObjectSurrogate.InitializeConstructors(cmObjectTypesBaseFirst);
InitializeMetaDataCache(cmObjectTypesBaseFirst);
m_initialized = true;
}
}
/// <summary/>
/// <returns>The CmObject types in the executing assembly with the base types ordered first</returns>
private static List<Type> CmObjectTypesBaseFirst()
{
var cmObjectTypes = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.Namespace == "SIL.LCModel.DomainImpl"
&& t.IsClass && t.GetInterface("ICmObject") != null).ToList();
// Take the list of all the ICmObject types in the assembly and make sure that the base types appear first
var cmObjectTypesBaseFirst = new List<Type>();
var type = cmObjectTypes[0];
while (cmObjectTypes.Count > 0)
{
// If the basetype is also a CmObject type and not yet added then go add it first
if (cmObjectTypes.Contains(type.BaseType))
{
type = type.BaseType;
}
else // the basetype is either not a CmObject or already added to the sorted list
{
cmObjectTypesBaseFirst.Add(type); // Add to the end, remove from the list and move on
cmObjectTypes.Remove(type);
if (cmObjectTypes.Count > 0)
{
type = cmObjectTypes[0];
}
}
}
return cmObjectTypesBaseFirst;
}
private void InitializeMetaDataCache(IEnumerable<Type> cmObjectTypes)
{
//AddClassesAndProps(cmObjectTypes);
foreach (var lcmType in cmObjectTypes)
{
// Cache classes.
var classAttrs = lcmType.GetCustomAttributes(typeof(ModelClassAttribute), false);
if (classAttrs == null || classAttrs.Length <= 0)
continue; // ScrFootnote does not have the 'ModelClassAttribute'.
//throw new InvalidOperationException("CmObjects must use 'ModelClassAttribute'.");
// Add its class information.
AddClass(lcmType.Name,
((ModelClassAttribute)classAttrs[0]).Clsid,
lcmType.Name == "CmObject" ? "CmObject" : lcmType.BaseType.Name,
lcmType.IsAbstract);
if (lcmType.GetInterface("IAnalysis") != null)
m_analysisClids.Add(((ModelClassAttribute)classAttrs[0]).Clsid);
// Cache properties.
// Regular foreach loop is faster.
//PropertyInfo[] pis = lcmType.GetProperties();
//for (int i = 0; i < pis.Length; ++i)
//{
// PropertyInfo pi = pis[i];
foreach (var pi in lcmType.GetProperties())
{
var decType = pi.DeclaringType;
// TODO-Linux: System.Boolean System.Type::op_Inequality(System.Type,System.Type)
// is marked with [MonoTODO] and might not work as expected in 4.0.
if (decType != lcmType) continue;
var customAttributes = pi.GetCustomAttributes(false);
if (customAttributes.Length <= 0) continue;
var customAttribute = customAttributes[0];
int attrFlid;
string fieldSignature;
CellarPropertyType flidType;
FieldSource source;
switch (customAttribute.GetType().Name)
{
default:
continue;
case "ModelPropertyAttribute":
// Add hand made virtual property to MDC.
var modelAttr = (ModelPropertyAttribute)customAttribute;
attrFlid = modelAttr.Flid;
fieldSignature = modelAttr.Signature;
flidType = modelAttr.FlidType;
source = FieldSource.kModel;
break;
case "VirtualPropertyAttribute":
// Add hand made virtual property to MDC.
var vAttr = (VirtualPropertyAttribute)customAttribute;
attrFlid = vAttr.Flid;
fieldSignature = vAttr.Signature;
flidType = vAttr.FlidType;
source = FieldSource.kVirtual;
break;
}
AddField(lcmType.Name,
attrFlid,
PlainFieldName(pi.Name),
null, null, null,
fieldSignature,
flidType,
source,
Guid.Empty, 0);
}
}
// mfr objects have not set their m_dstClsid member.
// Connect them now.
foreach (var mfr in m_metaFieldRecords.Values)
ConnectMetaFieldRec(mfr);
}
private void ConnectMetaFieldRec(MetaFieldRec mfr)
{
if (mfr.m_sig == null)
return;
int clid;
if (m_nameToClid.TryGetValue(mfr.m_sig, out clid))
{
SetDestClass(mfr, clid);
mfr.m_sig = null;
}
else if (mfr.m_sig == "IAnalyses")
{
foreach (int analysisClid in m_analysisClids)
m_metaClassRecords[analysisClid].m_incomingFields.Add(mfr);
mfr.m_sig = null;
}
}
private void SetDestClass(MetaFieldRec mfr, int clid)
{
mfr.m_dstClsid = clid;
if (!mfr.Virtual)
m_metaClassRecords[clid].m_incomingFields.Add(mfr);
}
// Remove extra fieldname information that is not part of model.
private static string PlainFieldName(string fieldname)
{
if (fieldname.EndsWith("OA") || fieldname.EndsWith("OS") || fieldname.EndsWith("OC")
|| fieldname.EndsWith("RA") || fieldname.EndsWith("RS") || fieldname.EndsWith("RC"))
{
return fieldname.Substring(0, fieldname.Length - 2);
}
return fieldname;
}
#endregion Construction
#region IFwMetaDataCache implementation
#region Initialization methods
/// <summary>
///
/// </summary>
/// <param name="bstrPathname"></param>
/// <param name="fClearPrevCache"></param>
public void InitXml(string bstrPathname, bool fClearPrevCache)
{
throw new NotSupportedException("'InitXml' not supported, because this class loads the model itself.");
}
#endregion Initialization methods
#region Field access methods
/// <summary> Get the source of the field. </summary>
public FieldSource get_FieldSource(int flid)
{
CheckFlid(flid);
return m_metaFieldRecords[flid].m_fieldSource;
}
/// <summary>
///
/// </summary>
public string GetFieldNameOrNull(int flid)
{
if (!m_metaFieldRecords.ContainsKey(flid))
return null;
return GetFieldName(flid);
}
/// <summary>Gets the number of "fields" defined for this conceptual model.</summary>
/// <returns>Count of fields in the entire model.</returns>
public int FieldCount
{
get { return m_metaFieldRecords.Count; }
}
/// <summary>Gets the list of field identification numbers (in no particular order).</summary>
/// <param name='countOfOutputArray'>The size of the output array.</param>
/// <param name='flids'>An integer array for returning the field identification numbers.</param>
/// <remarks>
/// If the array provided is too small, only an arbitrary subset of cclid values is returned.
/// If the array provided is too large, the excess entries are set to zero.
/// To ensure a complete set of field ids is returned, first use the get_FieldCount() method to get the full count.
/// </remarks>
public void GetFieldIds(int countOfOutputArray,
[MarshalAs(UnmanagedType.CustomMarshaler,
MarshalTypeRef = typeof(ArrayPtrMarshaler),
SizeParamIndex = 0)] ArrayPtr/*ULONG[]*/ flids)
{
var iflid = 0;
var uIds = new int[countOfOutputArray];
foreach (var flid in GetFieldIds())
{
if (iflid == countOfOutputArray)
break;
uIds[iflid++] = flid;
}
MarshalEx.ArrayToNative(flids, countOfOutputArray, uIds);
}
/// <summary>Gets the name of the class that contains this field.</summary>
/// <param name='flid'>Field identification number.</param>
public string GetOwnClsName(int flid)
{
CheckFlid(flid);
return m_metaClassRecords[m_metaFieldRecords[flid].m_ownClsid].m_className;
}
/// <summary>
/// Gets the name of the destination class that corresponds to this field.
/// This is the name of the class that is either owned or referred to by another class.
/// </summary>
/// <param name='flid'>Field identification number.</param>
public string GetDstClsName(int flid)
{
CheckFlid(flid);
return m_metaClassRecords[m_metaFieldRecords[flid].m_dstClsid].m_className;
}
/// <summary>Gets the "Id" value of the class that contains this field.</summary>
/// <param name='flid'>Field identification number.</param>
public int GetOwnClsId(int flid)
{
CheckFlid(flid);
return m_metaFieldRecords[flid].m_ownClsid;
}
/// <summary>Gets the "Id" of the destination class that corresponds to this field.</summary>
/// <param name='flid'>Field identification number.</param>
public int GetDstClsId(int flid)
{
CheckFlid(flid);
return m_metaFieldRecords[flid].m_dstClsid;
}
/// <summary>Gets the name of a field.</summary>
/// <param name='flid'>Field identification number.</param>
public string GetFieldName(int flid)
{
CheckFlid(flid);
return m_metaFieldRecords[flid].m_fieldName;
}
/// <summary>Gets the user label of a field.</summary>
/// <param name='flid'>Field identification number.</param>
public string GetFieldLabel(int flid)
{
CheckFlid(flid);
return m_metaFieldRecords[flid].m_fieldLabel;
}
/// <summary>Gets the help string of a field.p</summary>
/// <param name='flid'>Field identification number.</param>
public string GetFieldHelp(int flid)
{
CheckFlid(flid);
return m_metaFieldRecords[flid].m_fieldHelp;
}
/// <summary>Gets the Xml UI of a field.</summary>
/// <param name='flid'>Field identification number.</param>
public string GetFieldXml(int flid)
{
CheckFlid(flid);
return m_metaFieldRecords[flid].m_fieldXml;
}
/// <summary>
/// Gets the GUID of the CmPossibilityList associated with this field. This is only used by
/// custom fields.
/// </summary>
/// <param name="flid">The flid.</param>
/// <returns></returns>
public Guid GetFieldListRoot(int flid)
{
CheckFlid(flid);
return m_metaFieldRecords[flid].m_fieldListRoot;
}
/// <summary>Gets the Ws of the field.</summary>
/// <param name='flid'>Field identification number.</param>
public int GetFieldWs(int flid)
{
CheckFlid(flid);
return m_metaFieldRecords[flid].m_fieldWs;
}
/// <summary>
/// Gets the type of the field. If the field is unknown, return zero.
/// </summary>
/// <param name='flid'>Field identification number.</param>
/// <remarks>
/// This type value indicates if the field is a primitive data type
/// or a MultiStr/MultiTxt value or describes the relationship
/// between two classes (i.e. owning/reference and atomic/collection/sequence).
/// These numeric values are defined in the 'FWROOT\Src\Cellar\lib\CmTypes.h' file.
/// </remarks>
public int GetFieldType(int flid)
{
CheckFlid(flid);
return (int)m_metaFieldRecords[flid].m_fieldType;
}
/// <summary>
/// Given a field id and a class id,
/// this returns true if it is legal to store this class of object
/// (or any of its superclasses) in the field.
/// </summary>
/// <param name='flid'>Field identification number.</param>
/// <param name='clid'>Class identification number.</param>
/// <returns>A System.Boolean</returns>
public bool get_IsValidClass(int flid, int clid)
{
CheckClid(clid);
CheckFlid(flid);
var mfr = m_metaFieldRecords[flid];
if (mfr.m_dstClsid == clid)
return IsObjectFieldType(mfr.m_fieldType);
// Check superclasses.
do
{
var mcr = m_metaClassRecords[clid];
clid = mcr.m_baseClsid;
if (mfr.m_dstClsid == clid)
return IsObjectFieldType(mfr.m_fieldType);
} while (clid != 0);
return false;
}
#endregion Field access methods
#region Class access methods
/// <summary>Gets the number of "classes" defined for this conceptual model.</summary>
/// <returns>Count of classes.</returns>
public int ClassCount
{
get { return m_metaClassRecords.Count; }
}
/// <summary>
/// Gets the list of class identification numbers (in no particular order).
/// </summary>
/// <param name='arraySize'>The size of the output array.</param>
/// <param name='clids'>An integer array for returning the class identification numbers.</param>
/// <remarks>
/// If the array provided is too small, only an arbitrary subset of clid values is returned.
/// If the array provided is too large, the excess entries are set to zero.
/// </remarks>
public void GetClassIds(int arraySize,
[MarshalAs(UnmanagedType.CustomMarshaler,
MarshalTypeRef = typeof(ArrayPtrMarshaler),
SizeParamIndex = 0)] ArrayPtr/*ULONG[]*/ clids)
{
var iclid = 0;
var uIds = new int[arraySize];
foreach (var clid in GetClassIds())
{
if (iclid == arraySize)
break;
uIds[iclid++] = clid;
}
MarshalEx.ArrayToNative(clids, arraySize, uIds);
}
/// <summary>Gets the name of the class.</summary>
/// <param name='clid'>Class identification number.</param>
public string GetClassName(int clid)
{
CheckClid(clid);
return m_metaClassRecords[clid].m_className;
}
/// <summary>Indicates whether a class is abstract or concrete.</summary>
/// <param name='clid'>Class identification number.</param>
public bool GetAbstract(int clid)
{
CheckClid(clid);
return m_metaClassRecords[clid].m_abstract;
}
/// <summary>Gets the base class id for a given class.</summary>
/// <param name='clid'>Class identification number.</param>
public int GetBaseClsId(int clid)
{
if (clid == 0)
throw new ArgumentException("CmObject has no base class.");
CheckClid(clid);
return m_metaClassRecords[clid].m_baseClsid;
}
/// <summary>Gets the name of the base class for a given class.</summary>
/// <param name='clid'>Class identification number.</param>
public string GetBaseClsName(int clid)
{
if (clid == 0)
throw new ArgumentException("CmObject has no base class.");
CheckClid(clid);
return m_metaClassRecords[m_metaClassRecords[clid].m_baseClsid].m_className;
}
/// <summary>
/// Gets a list of the fields for the specified class.
/// Fields of superclasses are also returned, if the relevant flag is true.
/// </summary>
/// <param name='clid'>Class identification number.</param>
/// <param name='includeSuperclasses'>'True' to also get superclass fields.</param>
/// <param name='fieldTypes'>
/// Gets all fields whose types match the specified argument,
/// which should be a combination of the fcpt values defined in CmTypes.h, e.g.,
/// to get all owning properties pass kfcptOwningCollection | kfcptOwningAtom | kfcptOwningSequence.
/// </param>
/// <param name='countFlidMax'>
/// Size of the 'flids' array.
/// (Use 0 to get the size to use in a second call to actually get them.)</param>
/// <param name='flids'>Array of flids.</param>
/// <returns>
/// Count of flids that are returned,
/// or that could be returned, if 'countFlidMax' is 0.</returns>
/// <exception cref="ArgumentException">
/// Thrown if the output array is too small.
/// </exception>
public int GetFields(int clid, bool includeSuperclasses, int fieldTypes, int countFlidMax,
[MarshalAs(UnmanagedType.CustomMarshaler,
MarshalTypeRef = typeof(ArrayPtrMarshaler),
SizeParamIndex = 3)] ArrayPtr/*ULONG[]*/ flids)
{
CheckClid(clid);
var countFlids = 0;
var iflid = 0;
var uIds = new int[countFlidMax];
foreach (var flid in GetFields(clid, includeSuperclasses, fieldTypes))
{
var mfr = m_metaFieldRecords[flid];
if (fieldTypes != (int)CellarPropertyTypeFilter.All)
{
// Look up field type and see if it matches
var flidType = mfr.m_fieldType;
var fcpt = 1 << (int)flidType;
if ((fieldTypes & fcpt) == 0)
continue; // don't return this one
}
countFlids++;
if (countFlidMax <= 0) continue;
if (countFlids > countFlidMax)
throw new ArgumentException("Output array is too small.", "countFlidMax");
uIds[iflid++] = flid;
}
if (iflid > 0)
MarshalEx.ArrayToNative(flids, countFlidMax, uIds);
return countFlids;
}
#endregion Class access methods
#region Reverse access methods
/// <summary>Get the ID of the class having the specified name.</summary>
/// <param name='className'>Name of the class to look for.</param>
/// <returns>Class identification number, or 0 if not found.</returns>
public int GetClassId(string className)
{
CheckClid(className);
return m_nameToClid[className];
}
/// <summary>
/// Return true if the specified class exists.
/// </summary>
public bool ClassExists(string className)
{
return m_nameToClid.ContainsKey(className);
}
/// <summary>
/// Return true if the specified field (and class) exist.
/// </summary>
public bool FieldExists(string className, string fieldName, bool includeBaseClasses)
{
if (!ClassExists(className))
return false;
return FieldExists(GetClassId(className), fieldName, includeBaseClasses);
}
/// <summary>
/// Return true if the specified field (and class) exist.
/// </summary>
public bool FieldExists(int clid, string fieldName, bool includeBaseClasses)
{
if (!m_metaClassRecords.ContainsKey(clid))
return false;
return GetFlid(clid, fieldName, includeBaseClasses) != 0;
}
/// <summary>
/// Return true if the specified field exists.
/// </summary>
public bool FieldExists(int flid)
{
return m_metaFieldRecords.ContainsKey(flid);
}
/// <summary>Gets the field ID given the class and field names (throws if invalid).</summary>
/// <param name='className'>Name of the class that should contain the fieldname.</param>
/// <param name='fieldName'>FieldName to look for.</param>
/// <param name='includeBaseClasses'>'True' to look in superclasses,
/// otherwise 'false' to just look in the given class.</param>
/// <returns>Field identification number (throws if invalid)</returns>
public int GetFieldId(string className, string fieldName, bool includeBaseClasses)
{
return GetFieldId2(GetClassId(className), fieldName, includeBaseClasses);
}
/// <summary>Gets the field ID given the class ID and field name (throws if invalid).</summary>
/// <param name='clid'>ID of the class that should contain the fieldname.</param>
/// <param name='fieldName'>FieldName to look for.</param>
/// <param name='includeBaseClasses'>'True' to look in superclasses,
/// otherwise 'false' to just look in the given class.</param>
/// <returns>Field identification number (throws if invalid).</returns>
public int GetFieldId2(int clid, string fieldName, bool includeBaseClasses)
{
CheckClid(clid);
int flid = GetFlid(clid, fieldName, includeBaseClasses);
if (flid == 0)
throw new LcmInvalidFieldException("Fieldname '" + fieldName + "' does not exist. Consider using a decorator or review the fieldname for typos.");
return flid;
}
private int GetFlid(int clid, string fieldName, bool includeBaseClasses)
{
int flid; // Start on the pessimistic side.
var flidKey = MakeFlidKey(clid, fieldName);
if (!m_nameToFlid.TryGetValue(flidKey, out flid))
{
if (includeBaseClasses && clid > 0)
flid = GetFlid(GetBaseClsId(clid), fieldName, true);
}
return flid;
}
/// <summary>Gets the direct subclasses of the given class (not including itself).</summary>
/// <param name='clid'>Class indentifier to work with.</param>
/// <param name='countMaximumToReturn'>Count of the maximum number of subclass IDs to return (Size of the array.)
/// When set to zero, countDirectSubclasses will contain the full count, so a second call can use the right sized array.</param>
/// <param name='countDirectSubclasses'>Count of how many subclass IDs are the output array.</param>
/// <param name='subclasses'>Array of subclass IDs.</param>
public void GetDirectSubclasses(int clid,
int countMaximumToReturn, out int countDirectSubclasses,
[MarshalAs(UnmanagedType.CustomMarshaler,
MarshalTypeRef = typeof(ArrayPtrMarshaler),
SizeParamIndex = 1)] ArrayPtr/*int[]*/ subclasses)
{
CheckClid(clid);
var mcr = m_metaClassRecords[clid];
countDirectSubclasses = mcr.m_directSubclasses.Count;
if (countMaximumToReturn == 0)
return; // Client only wanted the count.
if (countMaximumToReturn < countDirectSubclasses)
throw new ArgumentException("Output array is too small.", "countMaximumToReturn");
MarshalEx.ArrayToNative(subclasses,
countMaximumToReturn,
GetDirectSubclasses(clid));
}
/// <summary>
/// Gets all subclasses of the given class,
/// including itself (which is always the first result in the list,
/// so it can easily be skipped if desired).
/// </summary>
/// <param name='clid'>Class indentifier to work with.</param>
/// <param name='countMaximumToReturn'>Count of the maximum number of subclass IDs to return (Size of the array.)
/// When set to zero, countDirectSubclasses will contain the full count, so a second call can use the right sized array.</param>
/// <param name='countAllSubclasses'>Count of how many subclass IDs are the output array.</param>
/// <param name='subclasses'>Array of subclass IDs.</param>
/// <remarks>
/// The list is therefore a complete list of the classes which are valid to store in a property whose
/// signature is the class identified by 'clid'.
/// </remarks>
public void GetAllSubclasses(int clid,
int countMaximumToReturn, out int countAllSubclasses,
[MarshalAs(UnmanagedType.CustomMarshaler,
MarshalTypeRef = typeof(ArrayPtrMarshaler),
SizeParamIndex = 1)] ArrayPtr/*int[]*/ subclasses)
{
CheckClid(clid);
countAllSubclasses = 0; // Start with 0 for output parameter.
var allSubclassClids = GetAllSubclasses(clid);
var uIds = new int[countMaximumToReturn];
var iSubclassClid = 0;
var countAllSubclassesActual = allSubclassClids.Length;
while (iSubclassClid < countMaximumToReturn && iSubclassClid < countAllSubclassesActual)
{
uIds[iSubclassClid] = allSubclassClids[iSubclassClid];
++iSubclassClid;
countAllSubclasses++;
}
MarshalEx.ArrayToNative(subclasses, countMaximumToReturn, uIds);
}
#endregion Reverse access methods
#region Virtual access methods
/// <summary>Add a virtual property (field) to a class.</summary>
/// <param name='className'>Name of the class that gets the new virtual property</param>
/// <param name='fieldName'>Name of the new virtual Field.</param>
/// <param name='virtualFlid'>Field identifier for the enw virtual field</param>
/// <param name='fieldType'>
/// This type value indicates if the field is a primitive data type
/// or a MultiStr/MultiBigStr/MultiTxt/MultiBigTxt value or describes the relationship
/// between two classes (i.e. owning/reference and atomic/collection/sequence).
/// These numeric values are defined in the 'FWROOT\src\cellar\lib\CmTypes.h' file.
/// It must NOT have the virtual bit OR'd in.
/// </param>
public void AddVirtualProp(string className, string fieldName, int virtualFlid, int fieldType)
{
throw new NotSupportedException("'AddVirtualProp' not supported, because this class loads the model itself.");
}
/// <summary>Check if the given flid is virtual or regular.</summary>
/// <param name='flid'>Field identifier to check.</param>
/// <returns>'True' if 'flid' is a virtual field, otherwise 'false'. </returns>
public bool get_IsVirtual(int flid)
{
CheckFlid(flid);
return m_metaFieldRecords[flid].Virtual;
}
#endregion Virtual access methods
#endregion IFwMetaDataCache implementation
#region Managed extentions to IFwMetaDataCache interface
/// <summary>
/// Gets the list of field identification numbers (in no particular order).
/// </summary>
/// <remarks>
/// This is a non-COM version of GetFieldIds. Managed clients should cast 'this'
/// into LcmMetaDataCache, and use this method.
/// </remarks>
[ComVisible(false)]
public int[] GetFieldIds()
{
var uIds = new int[m_nameToFlid.Values.Count];
m_nameToFlid.Values.CopyTo(uIds, 0);
return uIds;
}
/// <summary>
/// Gets the list of class identification numbers (in no particular order).
/// </summary>
[ComVisible(false)]
public int[] GetClassIds()
{
var clids = new HashSet<int>();
foreach (var clid in m_nameToClid.Values)
clids.Add(clid);
return clids.ToArray();
}
/// <summary>
/// Get the field Ids for the specified class, and optionally its superclasses.
/// </summary>
/// <param name="clid">Class identification number.</param>
/// <param name="includeSuperclasses">'True' to also get superclass fields.</param>
/// <param name='fieldTypes'>
/// Gets all fields whose types match the specified argument,
/// which should be a combination of the fcpt values defined in CmTypes.h, e.g.,
/// to get all owning properties pass kfcptOwningCollection | kfcptOwningAtom | kfcptOwningSequence.
/// </param>
/// <returns>The field Ids.</returns>
[ComVisible(false)]
public int[] GetFields(int clid, bool includeSuperclasses, int fieldTypes)
{
CheckClid(clid);
var currentClid = clid;
var uFlids = new HashSet<int>();
// This loop executes once if fIncludeSuperclasses is false, otherwise over clid
// and all superclasses.
for (; ; )
{
var mcr = m_metaClassRecords[currentClid];
var cnt = mcr.m_uFields.Count;
for (var i = 0; i < cnt; ++i)
{
var mfr = mcr.m_uFields[i];
if (!IsMatchingFieldType(fieldTypes, mfr))
continue;
uFlids.Add(mfr.m_flid);
}
if (!includeSuperclasses)
break;
if (currentClid == 0) // just processed CmObject
break;
currentClid = mcr.m_baseClsid;
}
return uFlids.ToArray();
}
private static bool IsMatchingFieldType(int fieldTypes, MetaFieldRec mfr)
{
if (fieldTypes != (int)CellarPropertyTypeFilter.All)
{
// Look up field type and see if it matches
var flidType = mfr.m_fieldType;
var fcpt = 1 << (int)flidType;
if ((fieldTypes & fcpt) == 0)
return false;
}
return true;
}
/// <summary>
/// Get the class Ids of the direct subclasses of the specified class Id.
/// </summary>
/// <param name="clid">Class Id to get the subclass Ids of.</param>
/// <returns>An array of direct subclass class Ids.</returns>
[ComVisible(false)]
public int[] GetDirectSubclasses(int clid)
{
CheckClid(clid);
var mcr = m_metaClassRecords[clid];
var cnt = mcr.m_directSubclasses.Count;
var clids = new HashSet<int>();
for (var i = 0; i < cnt; ++i)
clids.Add(mcr.m_directSubclasses[i].m_clid);
return clids.ToArray();
}
/// <summary>
/// Get all of the subclass Ids, including the given class Id.
/// </summary>
/// <param name="clid">Class Id to get subclass Ids of.</param>
/// <returns></returns>
[ComVisible(false)]
public int[] GetAllSubclasses(int clid)
{
CheckClid(clid);
var allSubclassClids = new HashSet<int> { clid };
GetAllSubclassesForClid(clid, allSubclassClids);
return allSubclassClids.ToArray();
}
/// <summary>
/// Add a user-defined custom field.
/// </summary>
/// <param name="className">Class that gets the new custom field.</param>
/// <param name="fieldName">Field name for the custom field.</param>
/// <param name="fieldType">Data type for the custom field.</param>
/// <param name="destinationClass">Class Id for object type custom properties</param>
/// <returns>The Id for tne new custom field.</returns>
/// <exception cref="KeyNotFoundException">
/// Thrown if 'fieldType' is an object type (owning/reference and atomic/collection/sequence) property,
/// but 'destinationClass' does not match a class in the model.
/// </exception>
/// <exception cref="ArgumentNullException">
/// Thrown if 'className' or 'fieldName' are null or empty.
/// </exception>
/// <exception cref="KeyNotFoundException">
/// Thrown if class is not defined.
/// </exception>
/// <remarks>
/// If 'fieldType' is a basic property type, then 'destinationClass' is ignored.
///
/// If 'fieldType' is an object type (owning/reference and atomic/collection/sequence) property,
/// then 'destinationClass' must match a class in the model.
/// </remarks>
[ComVisible(false)]
public int AddCustomField(string className, string fieldName, CellarPropertyType fieldType, int destinationClass)
{
CheckClid(className);
var clid = m_nameToClid[className];
if (string.IsNullOrEmpty(fieldName)) throw new ArgumentNullException("fieldName");
int flid;
// Don't allow custom field with same name as non-custom field
if (m_nameToFlid.TryGetValue(MakeFlidKey(clid, fieldName), out flid) && !IsCustom(flid))
throw new LcmInvalidFieldException("Field already exists: " + fieldName, fieldName);
// FWR-2804 - in case a custom field already exists that originally had this name,
// make sure we use a unique name this time.
var uniqueName = AssureUniqueFieldName(clid, fieldName);
// Get custom flid for clid.
if (m_clidToNextCustomFlid.TryGetValue(clid, out flid))
{
// Bump it up by 1.
flid += 1;
m_clidToNextCustomFlid[clid] = flid;
}
else
{
// Start with 500.
flid = (clid*1000) + 500;
m_clidToNextCustomFlid.Add(clid, flid);
}
string fieldSig = null;
MetaClassRec mcrSig;
if (m_metaClassRecords.TryGetValue(destinationClass, out mcrSig))
fieldSig = mcrSig.m_className;
AddField(className,
flid, uniqueName,
null, null, null,
fieldSig,
fieldType, FieldSource.kCustom, Guid.Empty, 0);
var mfr = m_metaFieldRecords[flid];
mfr.m_fieldLabel = fieldName; // user label is original proposed name.
m_customFields.Add(mfr);
ConnectMetaFieldRec(mfr);
return flid;
}
private string AssureUniqueFieldName(int clid, string proposedName)
{
// Handles case where user changed another field's userlabel and now wants to reuse
// the old name for a new field.
var result = proposedName;
var defaultLabel = result;
var extraId = 0;
while (!IsFieldNameUnique(clid, result))
{
extraId++;
result = defaultLabel + extraId;
// LT-21212 This is an attempt to get a stack trace in the rare cases where fields get incorrectly duplicated.
// This code should never get hit during normal operations in Flex.
throw new Exception($"Attempting to create duplicate custom field with the name {result}. PLEASE REPORT THIS TO FlexErrors.");
}
return result;
}
private bool IsFieldNameUnique(int clid, string proposedName)
{
int dummyFlid;
return !m_nameToFlid.TryGetValue(MakeFlidKey(clid, proposedName), out dummyFlid);
}
/// <summary>Check if the given flid is Custom, or not.</summary>
/// <param name='flid'>Field identifier to check.</param>
/// <returns>'True' if 'flid' is a custom field, otherwise 'false'. </returns>
[ComVisible(false)]
public bool IsCustom(int flid)
{
CheckFlid(flid);
return m_metaFieldRecords[flid].m_fieldSource == FieldSource.kCustom;
}