public ClassDiagramRelationship(string name, ClassDescriptor party1, ClassDescriptor party2, ClassDiagramRelationshipTypes relationshipType) { Name = name; Party1 = party1; Party2 = party2; RelationshipType = relationshipType; }
public static Gtk.Bin CreateInstance (ClassDescriptor klass) { if (klass.Name == "Gtk.Bin") return new CustomWidget (); else return null; }
public virtual string FormatType(ClassDescriptor descriptor) { if (_namespaces.Contains(descriptor.Namespace)) { return descriptor.Name; } return descriptor.FullName; }
private TreeNode CreateNode(ISettings settings) { var descriptor = new ClassDescriptor(settings.GetType()); var node = new TreeNode(); node.Text = descriptor.Title; node.Tag = settings; if (descriptor.Icon != null) { int index = this.AddImage(descriptor.Icon.Small); node.ImageIndex = index; node.SelectedImageIndex = index; } // Create CreateChildNodes(settings.GetType(), node.Nodes); return node; }
/// <summary> /// /// </summary> /// <param name="obj"></param> /// <param name="textWriter"></param> /// <param name="translationContext"></param> /// <param name="rootObjectClassDescrpitor"></param> private void SerializedAttributes(object obj, TextWriter textWriter, TranslationContext translationContext, ClassDescriptor rootObjectClassDescrpitor) { List<FieldDescriptor> attributeFieldDescriptors = rootObjectClassDescrpitor .AttributeFieldDescriptors; foreach (FieldDescriptor childFd in attributeFieldDescriptors) { try { WriteValueAsAtrribute(obj, childFd, textWriter, translationContext); } catch (Exception ex) { throw new Exception("serialize for attribute " + obj, ex); } } if (SimplTypesScope.graphSwitch == SimplTypesScope.GRAPH_SWITCH.ON) { if (translationContext.NeedsHashCode(obj)) { WriteSimplIdAttribute(obj, textWriter, translationContext); } if (_isRoot && translationContext.IsGraph) { WriteSimplNameSpace(textWriter); _isRoot = false; } } }
internal string GetClassColor(ClassDescriptor @class) { return(null); }
protected void CreateClassModels( IModelGeneratorContext context, FieldNode fieldSelection, IFragmentNode returnType, IInterfaceDescriptor interfaceDescriptor, IReadOnlyCollection <SelectionInfo> selections, List <ResultParserTypeDescriptor> resultParserTypes, Path path) { foreach (SelectionInfo selection in selections) { IFragmentNode modelType = ResolveReturnType( context, selection.Type, fieldSelection, selection); var interfaces = new List <IInterfaceDescriptor>(); foreach (IFragmentNode fragment in ShedNonMatchingFragments(selection.Type, modelType)) { interfaces.Add(CreateInterfaceModel(context, fragment, path)); } interfaces.Insert(0, interfaceDescriptor); NameString typeName = HoistName(selection.Type, modelType); if (typeName.IsEmpty) { typeName = selection.Type.Name; } bool update = false; var fieldNames = new HashSet <string>( selection.Fields.Select(t => GetPropertyName(t.ResponseName))); string className = context.GetOrCreateName( modelType.Fragment.SelectionSet, GetClassName(typeName), fieldNames); if (context.TryGetDescriptor(className, out ClassDescriptor? modelClass)) { var interfaceNames = new HashSet <string>(interfaces.Select(t => t.Name)); foreach (IInterfaceDescriptor item in modelClass !.Implements.Reverse()) { if (!interfaceNames.Contains(item.Name)) { interfaces.Insert(0, item); } } update = true; } modelClass = new ClassDescriptor( className, context.Namespace, selection.Type, interfaces); context.Register(modelClass, update); resultParserTypes.Add(new ResultParserTypeDescriptor(modelClass)); } }
/// <summary> /// /// </summary> /// <param name="obj"></param> /// <param name="textWriter"></param> /// <param name="translationContext"></param> /// <param name="rootObjectClassDescrpitor"></param> private void SerializedAttributes(object obj, TextWriter textWriter, TranslationContext translationContext, ClassDescriptor rootObjectClassDescrpitor) { List <FieldDescriptor> attributeFieldDescriptors = rootObjectClassDescrpitor .AttributeFieldDescriptors; foreach (FieldDescriptor childFd in attributeFieldDescriptors) { try { WriteValueAsAtrribute(obj, childFd, textWriter, translationContext); } catch (Exception ex) { throw new Exception("serialize for attribute " + obj, ex); } } if (SimplTypesScope.graphSwitch == SimplTypesScope.GRAPH_SWITCH.ON) { if (translationContext.NeedsHashCode(obj)) { WriteSimplIdAttribute(obj, textWriter, translationContext); } if (_isRoot && translationContext.IsGraph) { WriteSimplNameSpace(textWriter); _isRoot = false; } } }
public bool ContainsValue(ClassDescriptor value) { return innerHash.ContainsValue(value); }
/// <summary> /// /// </summary> /// <param name="root"></param> /// <param name="rootClassDescriptor"></param> /// <param name="length"></param> /// <returns></returns> private Object CreateObjectModel(Object root, ClassDescriptor rootClassDescriptor, int length) { int bytesRead = 0; while (!_isEos && bytesRead < length) { bytesRead += NextHeader(); if (_blockType == TranslationContext.SimplId.GetTlvId()) { int simplId = _binaryReader.ReadInt32(); translationContext.MarkAsUnmarshalled(simplId.ToString(), root); bytesRead += 4; continue; } if (_blockType == TranslationContext.SimplRef.GetTlvId()) { int simplRef = _binaryReader.ReadInt32(); return translationContext.GetFromMap(simplRef.ToString()); } FieldDescriptor currentFieldDescriptor = rootClassDescriptor.GetFieldDescriptorByTlvId(_blockType); int fieldType = currentFieldDescriptor.FdType; switch (fieldType) { case FieldTypes.Scalar: bytesRead += DeserializeScalar(root, currentFieldDescriptor); break; case FieldTypes.CollectionScalar: bytesRead += DeserializeScalarCollectionElement(root, currentFieldDescriptor); break; case FieldTypes.CompositeElement: bytesRead += DeserializeComposite(root, currentFieldDescriptor); break; case FieldTypes.CollectionElement: bytesRead += DeserializeCompositeCollectionElement(root, currentFieldDescriptor); break; case FieldTypes.MapElement: bytesRead += DeserializeCompositeMapElement(root, currentFieldDescriptor); break; case FieldTypes.Wrapper: currentFieldDescriptor = currentFieldDescriptor.WrappedFd; switch (currentFieldDescriptor.FdType) { case FieldTypes.CollectionScalar: bytesRead += DeserializeScalarCollection(root, currentFieldDescriptor); break; case FieldTypes.CollectionElement: bytesRead += DeserializeCompositeCollection(root, currentFieldDescriptor); break; case FieldTypes.MapElement: bytesRead += DeserializeCompositeMap(root, currentFieldDescriptor); break; case FieldTypes.CompositeElement: //TODO: wrapped composites in tlv? break; } break; } } DeserializationPostHook(root, translationContext); if (deserializationHookStrategy != null) deserializationHookStrategy.DeserializationPostHook(root, null); return root; }
/// <summary> /// /// </summary> /// <param name="obj"></param> /// <param name="textWriter"></param> /// <param name="translationContext"></param> /// <param name="allFieldDescriptors"></param> private void SerializeFields(object obj, TextWriter textWriter, TranslationContext translationContext, ClassDescriptor cd) { List<FieldDescriptor> allFieldDescriptors = cd.AllFieldDescriptors.ToList(); if(SimplTypesScope.graphSwitch == SimplTypesScope.GRAPH_SWITCH.ON) { if(translationContext.NeedsHashCode(obj)) { WriteSimplIdAttribute(obj, textWriter, allFieldDescriptors.Count <= 0, translationContext); } } List<FieldDescriptor> attributeFieldDescriptors = cd.AttributeFieldDescriptors as List<FieldDescriptor>; int numOfFields = SerializeFieldsHelper(textWriter, obj, translationContext, attributeFieldDescriptors, 0); List<FieldDescriptor> elementFieldDescriptors = cd.ElementFieldDescriptors; SerializeFieldsHelper(textWriter, obj, translationContext, elementFieldDescriptors,numOfFields); }
protected virtual void OnRootClassVisited(ClassDescriptor rootClass) { }
public bool IsMatch(ClassDescriptor classDescriptor) { return(_matcher.Any(matcher => matcher(classDescriptor))); }
public MetaMetadataFieldDescriptor(ClassDescriptor baseClassDescriptor, FieldDescriptor wrappedFD, String wrapperTag) : base(baseClassDescriptor, wrappedFD, wrapperTag) { IsInheritable = true; }
/// <summary> /// /// </summary> /// <param name="obj"></param> /// <returns></returns> protected ClassDescriptor GetClassDescriptor(Object obj) { return(ClassDescriptor.GetClassDescriptor(obj.GetType())); }
public MetaMetadataClassDescriptor(string tagName, string comment, string describedClassPackageName, string describedClassSimpleName, ClassDescriptor superClass, List <string> interfaces) : base(tagName, comment, describedClassPackageName, describedClassSimpleName, superClass, interfaces) { }
public void CanTranslateSql() { IFeatureClass fc; ITable table; IRelationshipClass rc; CreateTestWorkspace( "CanTranslateSql_master", "fc", "table", "rc", out fc, out table, out rc); IFeatureClass fc_child; ITable table_child; IRelationshipClass rc_child; IFeatureWorkspace childWorkspace = CreateTestWorkspace( "CanTranslateSql_child", "fc_child", "table_child", "rc_child", out fc_child, out table_child, out rc_child); IRow t = table_child.CreateRow(); t.Value[table_child.FindField("TEXT")] = "table"; // same as table name int pk = t.OID; t.Store(); IFeature f = fc_child.CreateFeature(); f.Value[fc_child.FindField("FKEY")] = pk; f.Shape = GeometryFactory.CreatePoint(100, 200); f.Store(); var model = new SimpleModel("model", fc); ModelVectorDataset vectorDataset = model.AddDataset( new ModelVectorDataset(DatasetUtils.GetName(fc))); ModelTableDataset tableDataset = model.AddDataset( new ModelTableDataset(DatasetUtils.GetName(table))); AttributeHarvestingUtils.HarvestAttributes( vectorDataset, ModelElementUtils.GetMasterDatabaseWorkspaceContext(vectorDataset)); AttributeHarvestingUtils.HarvestAttributes( tableDataset, ModelElementUtils.GetMasterDatabaseWorkspaceContext(tableDataset)); ObjectAttribute fkAttribute = vectorDataset.GetAttribute("FKEY"); ObjectAttribute pkAttribute = tableDataset.GetAttribute(table.OIDFieldName); Assert.NotNull(fkAttribute); Assert.NotNull(pkAttribute); Association association = model.AddAssociation(new ForeignKeyAssociation(DatasetUtils.GetName(rc), AssociationCardinality.OneToMany, fkAttribute, pkAttribute)); var childWorkspaceContext = new SimpleWorkspaceContext( model, childWorkspace, new[] { new WorkspaceDataset("fc_child", null, vectorDataset), new WorkspaceDataset("table_child", null, tableDataset), }, new[] { new WorkspaceAssociation("rc_child", null, association) }); var clsDesc = new ClassDescriptor(typeof(QaRelConstraint)); var tstDesc = new TestDescriptor("RelConstraint", clsDesc); QualityCondition condition = new QualityCondition("fc_table_constraints", tstDesc); QualityConditionParameterUtils.AddParameterValue(condition, "relationTables", vectorDataset); QualityConditionParameterUtils.AddParameterValue(condition, "relationTables", tableDataset); QualityConditionParameterUtils.AddParameterValue(condition, "relation", "rc"); QualityConditionParameterUtils.AddParameterValue(condition, "join", JoinType.InnerJoin); QualityConditionParameterUtils.AddParameterValue(condition, "constraint", "(fc.OBJECTID = 1 AND table.OBJECTID = 1) AND (table.TEXT = 'table')"); var factory = new QaRelConstraint { Condition = condition }; ITest test = factory.CreateTests(new SimpleDatasetOpener(childWorkspaceContext))[0]; var runner = new QaContainerTestRunner(1000, test); runner.Execute(GeometryFactory.CreateEnvelope(0, 0, 1000, 1000)); AssertUtils.NoError(runner); }
/// <summary> /// Compile the given <paramref name="model"/> with the current <see cref="LanguageSpecification"/>. /// </summary> /// <param name="model">The <see cref="ClassDescriptor"/> to convert to the given <see cref="Language"/>.</param> /// <param name="referenceDataModels">Check type reference for found <see cref="ClassDescriptor"/>(s).</param> public ClassDescriptor Compile(ClassDescriptor model, List <ClassDescriptor> referenceDataModels) { var modelBuilder = new StringBuilder(); var doc = _kernel.Documentation?.GetDocumentationForType(model.Type); var template = Language.Template .Replace(TYPE_NAME_KEY, model.Name) .Replace(TYPE_NAMESPACE_KEY, model.Type.Namespace) .Replace(ARGUMENT_NAME, _kernel.ArgumentName) ; var enumerator = new StringEnumerator(template); while (enumerator.MoveNext()) { var row = enumerator.Current; if (row == null) { continue; } // Recognition if (row.Contains(CTOR_PROPERTIES_KEY)) { // Set the values for each property in the ctor var indent = row.Before(CTOR_PROPERTIES_KEY); var propertyValueBuilder = new StringBuilder(); foreach (var property in model.Properties) { foreach (var line in Language.FormatProperty(_kernel, property)) { propertyValueBuilder.AppendLine(indent + line); } } modelBuilder.Append(propertyValueBuilder); } // Define else if (row.Contains(CLASS_PROPERTIES_KEY)) { var indent = row.Before(CLASS_PROPERTIES_KEY); var propertyDefinitionBuilder = new StringBuilder(); foreach (var property in model.Properties) { foreach (var line in Language.FormatPropertyDefinition(_kernel, property)) { propertyDefinitionBuilder.AppendLine(indent + line); } } modelBuilder.Append(propertyDefinitionBuilder); } // Check else if (row.Contains(VALIDATION_KEY)) { var indent = row.Before(VALIDATION_KEY); var statementBuilder = new StringBuilder(); var statements = Language.FormatStatements(_kernel, model.Properties.ToList()).GroupBy(x => x.Type); foreach (var group in statements) { if (group.All(x => x.IsEmpty || x.IsComment || x.IsEmptyLine)) { continue; // No actual statement, continue. } foreach (var statement in group.Where(x => !x.IsEmpty)) { foreach (var line in statement.Lines) { statementBuilder.AppendLine(indent + line); } } } modelBuilder.Append(statementBuilder); } // Defined check else if (row.Contains(IS_DEFINED_CHECK)) { var statement = Language.StatementPipeline.ArgumentDefinedStatement(_kernel); var rowWithStatement = row.Replace(IS_DEFINED_CHECK, statement.ToString()); modelBuilder.Append(rowWithStatement); } // Undefined check else if (row.Contains(IS_UNDEFINED_CHECK)) { var statement = Language.StatementPipeline.ArgumentUndefinedStatement(_kernel); var rowWithStatement = row.Replace(IS_UNDEFINED_CHECK, statement.ToString()); modelBuilder.Append(rowWithStatement); } // JsDoc else if (row.Contains(SUMMARY_KEY)) { var summary = doc?.Summary ?? string.Empty; if (!summary.IsEmpty()) { modelBuilder.Append(enumerator.Current.Replace(SUMMARY_KEY, summary)); } } // Comments & Empty lines else if (row.StartsWith("// ReSharper")) // Remove resharper comments. { continue; } else { modelBuilder.Append(enumerator.Current); } } // Set the model name in the template. var result = modelBuilder.ToString(); model.Script = result; return(model); }
private ICodeDescriptor GenerateUnionSelectionSet( OperationDefinitionNode operation, UnionType unionType, IType fieldType, FieldNode fieldSelection, IReadOnlyCollection <FieldCollectionResult> typeCases, Path path) { IFragmentNode returnType = null; FieldCollectionResult result = typeCases.First(); IReadOnlyList <IFragmentNode> fragments = result.Fragments; while (fragments.Count == 1) { if (fragments[0].Fragment.TypeCondition == unionType) { returnType = fragments[0]; fragments = fragments[0].Children; } else { break; } } InterfaceDescriptor unionInterface; if (returnType is null) { string name = CreateName( fieldSelection, unionType, Utilities.NameUtils.GetInterfaceName); unionInterface = new InterfaceDescriptor( name, _namespace, unionType); } else { unionInterface = CreateInterface(returnType, path); unionInterface = unionInterface.RemoveAllImplements(); } var resultParserTypes = new List <ResultParserTypeDescriptor>(); foreach (var typeCase in typeCases) { string className; string interfaceName; IFragmentNode fragment = typeCase.Fragments.FirstOrDefault( t => t.Fragment.TypeCondition == typeCase.Type); if (fragment is null) { className = CreateName(typeCase.Type.Name); interfaceName = CreateName(GetInterfaceName(className)); } else { className = CreateName(fragment.Fragment.Name); interfaceName = CreateName(GetInterfaceName(fragment.Fragment.Name)); } var modelInterfaces = new List <IInterfaceDescriptor>(); modelInterfaces.Add( new InterfaceDescriptor( interfaceName, _namespace, typeCase.Type, typeCase.Fields.Select(t => { string responseName = (t.Selection.Alias ?? t.Selection.Name).Value; return(new FieldDescriptor( t.Field, t.Selection, t.Field.Type, t.Path.Append(responseName))); }).ToList(), new[] { unionInterface })); modelInterfaces.AddRange(CreateInterfaces(typeCase.Fragments, path)); var modelClass = new ClassDescriptor( className, _namespace, typeCase.Type, modelInterfaces); RegisterDescriptors(modelInterfaces); RegisterDescriptor(modelClass); resultParserTypes.Add(new ResultParserTypeDescriptor(modelClass)); } RegisterDescriptor(unionInterface); RegisterDescriptor( new ResultParserMethodDescriptor( GetPathName(path), operation, fieldType, fieldSelection, path, unionInterface, resultParserTypes)); return(unionInterface); }
private static Instance Reflect_BIN(ClassDescriptor classDesc, Type objType) { if (!typeof(Instance).IsAssignableFrom(objType)) { throw new Exception("'T' must be an Instance."); } Instance obj = (Instance)Activator.CreateInstance(objType); foreach (PropertyDescriptor prop in classDesc.Properties) { string propertyName = prop.Name.Replace(" ", "_"); FieldInfo field = objType.GetField(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy); if (field != null) { BinaryPropertyFormat format = prop.Format; object value = null; switch (format) { // In most use cases, we can just set the value directly. case BinaryPropertyFormat.Float: case BinaryPropertyFormat.Double: case BinaryPropertyFormat.Bool: case BinaryPropertyFormat.Int: case BinaryPropertyFormat.Int64: value = prop.Value; break; // In some cases however, we need to handle it directly. case BinaryPropertyFormat.Vector3: float[] xyz = prop.Value as float[]; value = new Vector3(xyz); break; case BinaryPropertyFormat.CFrame: float[] components = prop.Value as float[]; value = CFrame.FromComponents(components); break; case BinaryPropertyFormat.Enum: Type fieldType = field.FieldType; if (fieldType.IsEnum) { uint enumIndex = (uint)prop.Value; int index = (int)enumIndex; value = Enum.ToObject(fieldType, index); } break; case BinaryPropertyFormat.String: value = prop.Value.ToString(); break; default: break; } if (value != null) { field.SetValue(obj, value); } } } foreach (ClassDescriptor child in classDesc.Children) { Type classType = GetClassType(child.ClassName); if (classType != null) { Instance childObj = Reflect_BIN(child, classType); childObj.Parent = obj; } } return(obj); }
/// <inheritdoc /> public override string RemoveComments(ClassDescriptor model) => model.Script;
public void TestRelatedFactory() { IFeatureWorkspace initTestWs = _testWs; try { _testWs = RelTestWs; IFeatureClass fc1 = CreateFeatureClass("TestRelatedFactory", esriGeometryType.esriGeometryPolyline); var ds1 = (IDataset)fc1; IFieldsEdit fields = new FieldsClass(); fields.AddField(FieldUtils.CreateOIDField()); fields.AddField(FieldUtils.CreateIntegerField(_fkFieldName)); fields.AddField(FieldUtils.CreateTextField(_textFieldName, 200)); string tableName = ds1.Name + "_table"; ITable table = TestWorkspaceUtils.CreateSimpleTable(_testWs, tableName, fields); var tableDataset = (IDataset)table; string relClassName = "relClass" + Math.Abs(Environment.TickCount); IRelationshipClass rel = TestWorkspaceUtils.CreateSimpleMNRelationship( _testWs, relClassName, table, (ITable)fc1, "fkGrp", "fkFc"); ((IWorkspaceEdit)_testWs).StartEditing(false); IFeature f = AddFeature(fc1, CurveConstruction.StartLine(0, 0) .LineTo(4, 0) .Curve); IRow r = AddRow(table, textFieldValue: "A"); rel.CreateRelationship((IObject)r, f); r = AddRow(table, textFieldValue: "B"); rel.CreateRelationship((IObject)r, f); f = AddFeature(fc1, CurveConstruction.StartLine(4, 0) .LineTo(4, 8) .Curve); r = AddRow(table, textFieldValue: "A"); rel.CreateRelationship((IObject)r, f); ((IWorkspaceEdit)_testWs).StopEditing(true); var model = new SimpleModel("model", fc1); Dataset mds1 = model.AddDataset(new ModelVectorDataset(ds1.Name)); Dataset mdsRel = model.AddDataset(new ModelTableDataset(tableDataset.Name)); var clsDesc = new ClassDescriptor(typeof(QaRelRegularExpression)); var tstDesc = new TestDescriptor("GroupEnds", clsDesc); var condition = new QualityCondition("cndGroupEnds", tstDesc); QualityConditionParameterUtils.AddParameterValue(condition, "relationTables", mds1); QualityConditionParameterUtils.AddParameterValue(condition, "relationTables", mdsRel); QualityConditionParameterUtils.AddParameterValue(condition, "relation", relClassName); QualityConditionParameterUtils.AddParameterValue(condition, "join", JoinType.InnerJoin); QualityConditionParameterUtils.AddParameterValue(condition, "pattern", "A"); QualityConditionParameterUtils.AddParameterValue(condition, "fieldNames", $"{tableName}.{_textFieldName}"); QualityConditionParameterUtils.AddParameterValue(condition, "MatchIsError", false); //condition.AddParameterValue("PatternDescription", "Hallo"); var factory = new QaRelRegularExpression { Condition = condition }; IList <ITest> tests = factory.CreateTests(new SimpleDatasetOpener(model.MasterDatabaseWorkspaceContext)); Assert.AreEqual(1, tests.Count); IList <QaError> errors = Run(tests[0], 1000); AssertErrors(1, errors); IList <InvolvedRow> involvedRows = errors[0].InvolvedRows; Assert.AreEqual(2, involvedRows.Count); Assert.AreEqual($"{tableName}.{_textFieldName}", errors[0].AffectedComponent); Assert.AreEqual("RegularExpression.FieldValueDoesNotMatchRegularExpression", errors[0].IssueCode?.ID); // TOP-4945: expected involved dataset name: base table name, not joined table name Assert.IsTrue(tableName == involvedRows[0].TableName || tableName == involvedRows[1].TableName); } finally { _testWs = initTestWs; } }
public void AddTranslation(ClassDescriptor entry) { if (!EntriesByTag.ContainsKey(entry.TagName)) EntriesByTag.Add(entry.TagName, entry); if (!EntriesByClassSimpleName.ContainsKey(entry.DescribedClassSimpleName)) EntriesByClassSimpleName.Add(entry.DescribedClassSimpleName, entry); if (!EntriesByClassName.ContainsKey(entry.DescribedClassSimpleName)) EntriesByClassName.Add(entry.DescribedClassSimpleName, entry); String[] otherTags = XmlTools.OtherTags(entry.DescribedClass); if(otherTags != null) foreach (string otherTag in otherTags.Where(otherTag => !string.IsNullOrEmpty(otherTag))) { EntriesByTag.Add(otherTag, entry); } }
/// <inheritdoc /> public virtual string RemoveComments(ClassDescriptor model) => SpecificationDefaults.RemoveCommentsFromModel(model);
// String nameSpacePrefix /** * Should this field be inherited in meta-metadata */ public MetaMetadataFieldDescriptor(ClassDescriptor declaringClassDescriptor, FieldInfo field, int annotationType) : base(declaringClassDescriptor, field, annotationType) { if (field != null) { IsInheritable = !field.IsDefined(typeof(MmDontInherit), false); //isAnnotationPresent(mm_dont_inherit.class); } else { IsInheritable = true; } }
public void TestRelatedFactoryMinParameters() { IFeatureWorkspace testWs = RelTestWs; const string fkTable = "fkTable"; IFeatureClass fc1 = CreateLineClass( testWs, "Fc1_" + Environment.TickCount, new List <IField> { FieldUtils.CreateIntegerField(fkTable) }); IFeatureClass fc2 = CreateLineClass(testWs, "Fc2_" + Environment.TickCount); var ds1 = (IDataset)fc1; var ds2 = (IDataset)fc2; IFieldsEdit fields = new FieldsClass(); fields.AddField(FieldUtils.CreateOIDField()); const string IdField = "IdRel"; fields.AddField(FieldUtils.CreateIntegerField(IdField)); string relTableName = "Rel_" + ds1.Name; ITable relTable = TestWorkspaceUtils.CreateSimpleTable(testWs, relTableName, fields); var dsRel = (IDataset)relTable; string relName = "relName" + Environment.TickCount; IRelationshipClass rel = TestWorkspaceUtils.CreateSimple1NRelationship( testWs, relName, relTable, (ITable)fc1, relTable.OIDFieldName, fkTable); ((IWorkspaceEdit)testWs).StartEditing(false); IRow r1 = AddRow(relTable, new object[] { 12 }); IRow r2 = AddRow(relTable, new object[] { 14 }); IFeature f11 = AddFeature( fc1, CurveConstruction.StartLine(0, 0).LineTo(4, 0).Curve, new object[] { r1.OID }); IFeature f12 = AddFeature( fc1, CurveConstruction.StartLine(0, 0).LineTo(4, 0).Curve, new object[] { r2.OID }); IFeature f2 = AddFeature(fc2, CurveConstruction.StartLine(10, 1).LineTo(14, 1).Curve); ((IWorkspaceEdit)testWs).StopEditing(true); var model = new SimpleModel("model", fc1); Dataset mds1 = model.AddDataset(new ModelVectorDataset(ds1.Name)); Dataset mdsRel = model.AddDataset(new ModelTableDataset(dsRel.Name)); Dataset mds2 = model.AddDataset(new ModelVectorDataset(ds2.Name)); var clsDesc = new ClassDescriptor(typeof(QaRelMustBeNearOther)); var tstDesc = new TestDescriptor("testNear", clsDesc); var condition = new QualityCondition("cndNear", tstDesc); QualityConditionParameterUtils.AddParameterValue(condition, "relationTables", mds1); QualityConditionParameterUtils.AddParameterValue(condition, "relationTables", mdsRel, $"{relTableName}.{IdField} = 12"); // --> only f11 get's checked QualityConditionParameterUtils.AddParameterValue(condition, "relation", relName); QualityConditionParameterUtils.AddParameterValue(condition, "join", JoinType.InnerJoin); QualityConditionParameterUtils.AddParameterValue(condition, "nearClasses", mds2); QualityConditionParameterUtils.AddParameterValue(condition, "maximumDistance", 5); QualityConditionParameterUtils.AddParameterValue(condition, "relevantRelationCondition", string.Empty); var fact = new QaRelMustBeNearOther(); fact.Condition = condition; IList <ITest> tests = fact.CreateTests(new SimpleDatasetOpener(model.MasterDatabaseWorkspaceContext)); Assert.AreEqual(1, tests.Count); var runner = new QaContainerTestRunner(1000, tests[0]); runner.Execute(); Assert.AreEqual(1, runner.Errors.Count); }
public void SetElementClassDescriptor(ClassDescriptor elementClassDescriptor) { ElementClassDescriptor = elementClassDescriptor; Type newElementClass = elementClassDescriptor.DescribedClass; if (newElementClass != null) { ElementClass = newElementClass; } }
/// <summary> /// Flush the generated <see cref="ClassDescriptor.Script"/> in the given <paramref name="model"/> /// to the <paramref name="fileName"/>. /// </summary> public void FlushToFile(ClassDescriptor model, string fileName = "") => FlushToFile(new List <ClassDescriptor> { model }, fileName);
public DocumentGenerator Proxy(ContractDefinition definition = null, ClassDescriptor descriptor = null, bool forceAsync = false) { return AddContractGenerator(new ProxyGenerator(Output, Formatter, IntendProvider) { ContractDefinition = definition ?? ContractDefinition, ContractDescriptor = descriptor, ForceAsync = forceAsync }); }
/// <summary> /// Flush the generated <see cref="ClassDescriptor.Script"/> in the given <paramref name="model"/> /// to the <paramref name="fileName"/> asynchronously. /// </summary> public async Task FlushToFileAsync(ClassDescriptor model, string fileName = "") => await FlushToFileAsync(new List <ClassDescriptor> { model }, fileName);
/// <summary> /// /// </summary> /// <param name="theObject"></param> /// <param name="objectClassDescriptor"></param> private void DeserializeObjectFields(object theObject, ClassDescriptor objectClassDescriptor) { FieldDescriptor currentFieldDescriptor = null; bool insideWrapped = false; while (_jsonReader.TokenType != JsonToken.EndObject) { var currentJsonProperty = _jsonReader.Value; if (currentJsonProperty == null || _jsonReader.TokenType != JsonToken.PropertyName) { Debug.WriteLine("should have found PropertyName, but instead found " +_jsonReader.TokenType); _jsonReader.Skip(); } var currentTag = _jsonReader.Value.ToString(); if (!HandleSimplId(currentTag, theObject)) { currentFieldDescriptor = currentFieldDescriptor != null && currentFieldDescriptor.FdType== FieldTypes.Wrapper ? currentFieldDescriptor.WrappedFd : objectClassDescriptor.GetFieldDescriptorByTag(currentTag); if (currentFieldDescriptor == null) { currentFieldDescriptor = FieldDescriptor.MakeIgnoredFieldDescriptor(currentTag); Debug.WriteLine("ignoring " + currentTag); _jsonReader.Skip(); } switch (currentFieldDescriptor.FdType) { case FieldTypes.Scalar: DeserializeScalar(theObject, currentFieldDescriptor); break; case FieldTypes.CompositeElement: DeserializeComposite(theObject, currentFieldDescriptor); if (insideWrapped) { insideWrapped = false; _jsonReader.Read(); } break; case FieldTypes.CollectionScalar: DeserializeScalarCollection(theObject, currentFieldDescriptor); break; case FieldTypes.CollectionElement: DeserializeCompositeCollection(theObject, currentFieldDescriptor); break; case FieldTypes.MapElement: DeserializeCompositeMap(theObject, currentFieldDescriptor); break; case FieldTypes.Wrapper: // don't do this for collections or maps because they are always wrapped (even when nowrap is specified) // and this is handled in respective method calls. if (currentFieldDescriptor.WrappedFd.IsComposite) { _jsonReader.Read(); _jsonReader.Read(); if (_jsonReader.TokenType != JsonToken.PropertyName) { // expecting property name, but found something else. not a properly wrapped composite. while(_jsonReader.TokenType != JsonToken.EndObject) _jsonReader.Skip(); _jsonReader.Read(); continue; } insideWrapped = true; } // currentFieldDescriptor = currentFieldDescriptor.WrappedFd; // if (currentFieldDescriptor.FdType == FieldTypes.CompositeElement) // goto case FieldTypes.CompositeElement; // if (currentFieldDescriptor.FdType == FieldTypes.CollectionScalar) // goto case FieldTypes.CollectionScalar; // if (currentFieldDescriptor.FdType == FieldTypes.CollectionElement) // goto case FieldTypes.CollectionElement; // if (currentFieldDescriptor.FdType == FieldTypes.MapElement) // goto case FieldTypes.MapElement; break; } } // if simpl.id or non-wrapper field descriptor, advance to next token. if (currentFieldDescriptor == null || currentFieldDescriptor.FdType != FieldTypes.Wrapper) _jsonReader.Read(); } DeserializationPostHook(theObject, translationContext); if (deserializationHookStrategy != null) deserializationHookStrategy.DeserializationPostHook(theObject, null); }
public static string GetResourceImagePath(ClassDescriptor descriptor ) { string name = descriptor.Icon.Small; if (String.IsNullOrEmpty(name)) return string.Empty; var assembly = descriptor.ClassType.Assembly; var length = name.LastIndexOf('.'); if(length < 1) return string.Empty; var path = name.Substring(0, length); // "SPM2.SharePoint.Properties.Resources"; name = name.Substring(length+1); if (String.IsNullOrEmpty(name)) return string.Empty; var result = String.Format("{0};{1};{2}", assembly.FullName, path, name); //Trace.WriteLine("Resource: " + result); return result; }
/// <summary> /// /// </summary> /// <param name="root"></param> /// <param name="rootClassDescriptor"></param> /// <param name="rootTag"></param> private void CreateObjectModel(object root, ClassDescriptor rootClassDescriptor, string rootTag) { FieldDescriptor currentFieldDescriptor = new FieldDescriptor(); while (NextEvent() && (_xmlReader.NodeType != XmlNodeType.EndElement || !CurrentTag.Equals(rootTag))) { if (_xmlReader.NodeType != XmlNodeType.Element) { continue; } if (currentFieldDescriptor.FdType != FieldTypes.Wrapper) { currentFieldDescriptor = rootClassDescriptor.GetFieldDescriptorByTag(CurrentTag); } if (currentFieldDescriptor == null) { //Debug.WriteLine("ignoring tag " + CurrentTag); currentFieldDescriptor = FieldDescriptor.MakeIgnoredFieldDescriptor(CurrentTag); if (!_xmlReader.IsEmptyElement) { SkipTag(CurrentTag); } continue; } switch (currentFieldDescriptor.FdType) { case FieldTypes.Scalar: DeserializeScalar(root, currentFieldDescriptor); break; case FieldTypes.CompositeElement: DeserializeComposite(root, currentFieldDescriptor); break; case FieldTypes.CollectionScalar: DeserializeScalarCollectionElement(root, currentFieldDescriptor); break; case FieldTypes.CollectionElement: DeserializeCompositeCollectionElement(root, currentFieldDescriptor); break; case FieldTypes.MapElement: DeserializeCompositeMapElement(root, currentFieldDescriptor); break; case FieldTypes.Wrapper: currentFieldDescriptor = currentFieldDescriptor.WrappedFd; switch (currentFieldDescriptor.FdType) { case FieldTypes.CollectionScalar: DeserializeScalarCollection(root, currentFieldDescriptor); break; case FieldTypes.CollectionElement: DeserializeCompositeCollection(root, currentFieldDescriptor); break; case FieldTypes.MapElement: DeserializeCompositeMap(root, currentFieldDescriptor); break; case FieldTypes.CompositeElement: DeserializeWrappedComposite(root, currentFieldDescriptor); break; } break; case FieldTypes.IgnoredElement: SkipTag(CurrentTag); break; default: NextEvent(); break; } } DeserializationPostHook(root, translationContext); if (deserializationHookStrategy != null) { deserializationHookStrategy.DeserializationPostHook(root, null); } }
/// <summary> /// /// </summary> /// <param name="root"></param> /// <param name="rootClassDescriptor"></param> /// <param name="rootTag"></param> private void CreateObjectModel(object root, ClassDescriptor rootClassDescriptor, string rootTag) { FieldDescriptor currentFieldDescriptor = new FieldDescriptor(); while (NextEvent() && (_xmlReader.NodeType != XmlNodeType.EndElement || !CurrentTag.Equals(rootTag))) { if (_xmlReader.NodeType != XmlNodeType.Element) continue; if(currentFieldDescriptor.FdType != FieldTypes.Wrapper) currentFieldDescriptor = rootClassDescriptor.GetFieldDescriptorByTag(CurrentTag); if (currentFieldDescriptor == null) { //Debug.WriteLine("ignoring tag " + CurrentTag); currentFieldDescriptor = FieldDescriptor.MakeIgnoredFieldDescriptor(CurrentTag); if (!_xmlReader.IsEmptyElement) SkipTag(CurrentTag); continue; } switch (currentFieldDescriptor.FdType) { case FieldTypes.Scalar: DeserializeScalar(root, currentFieldDescriptor); break; case FieldTypes.CompositeElement: DeserializeComposite(root, currentFieldDescriptor); break; case FieldTypes.CollectionScalar: DeserializeScalarCollectionElement(root, currentFieldDescriptor); break; case FieldTypes.CollectionElement: DeserializeCompositeCollectionElement(root, currentFieldDescriptor); break; case FieldTypes.MapElement: DeserializeCompositeMapElement(root, currentFieldDescriptor); break; case FieldTypes.Wrapper: currentFieldDescriptor = currentFieldDescriptor.WrappedFd; switch (currentFieldDescriptor.FdType) { case FieldTypes.CollectionScalar: DeserializeScalarCollection(root, currentFieldDescriptor); break; case FieldTypes.CollectionElement: DeserializeCompositeCollection(root, currentFieldDescriptor); break; case FieldTypes.MapElement: DeserializeCompositeMap(root, currentFieldDescriptor); break; case FieldTypes.CompositeElement: DeserializeWrappedComposite(root, currentFieldDescriptor); break; } break; case FieldTypes.IgnoredElement: SkipTag(CurrentTag); break; default: NextEvent(); break; } } DeserializationPostHook(root, translationContext); if (deserializationHookStrategy != null) deserializationHookStrategy.DeserializationPostHook(root, null); }
/// <summary> /// Recursively compares two objects to ensure that they are the same. /// Compares only values in the objects that will be simpl de/serialized /// </summary> /// <param name="originalObject">Original object</param> /// <param name="deserializedObject">Deserialized representation, the result of round-tripping</param> /// <param name="originalCompared">List of compared composite objects, prevents graph infinite loops</param> /// <param name="derserializedCompared">List of compared composite objects, prevents graph infinite loops</param> /// <param name="issues">List of issues found in the comparison</param> /// <returns>True if both are equal, false otherwise</returns> private static bool CompareObjectsRecursive(object originalObject, object deserializedObject, List <object> originalCompared, List <object> derserializedCompared, List <SimplIssue> issues) { if (originalObject == null && deserializedObject == null) { // both null is questionably acceptable. :| System.Diagnostics.Debug.WriteLine("Both null for deserialization... seems questionable.", category: "Comparison warning."); return(true); } else { // They are not equal here, obviously if (OneIsNullAndOtherIsNot(originalObject, deserializedObject)) { issues.Add(new SimplIssue("One object null, the other wasn't.", originalObject, deserializedObject)); return(false); } } // Add our objects to the compared object lists originalCompared.Add(originalObject); derserializedCompared.Add(deserializedObject); // Compare object types... Make sure they are the same. if (originalObject.GetType().Equals(deserializedObject.GetType())) { // Get a class descriptor for both. var classDescriptor = ClassDescriptor.GetClassDescriptor(originalObject.GetType()); foreach (var fieldDescriptor in classDescriptor.AllFieldDescriptors) { var originalDescribedObject = fieldDescriptor.GetValue(originalObject); var deserializedDescribedObject = fieldDescriptor.GetValue(deserializedObject); if (originalCompared.Contains(originalDescribedObject) || derserializedCompared.Contains(deserializedDescribedObject)) { // skip if we've already compared these. continue; } if (fieldDescriptor.IsComposite) { // Catches a self-reference if (Object.ReferenceEquals(originalDescribedObject, originalObject) || Object.ReferenceEquals(deserializedDescribedObject, deserializedObject)) { // Circular refernces are fine, skip them / move on. continue; } //Recurse and compare the inner objects bool result = CompareObjectsRecursive(originalDescribedObject, deserializedDescribedObject, originalCompared, derserializedCompared, issues); if (!result) { issues.Add(new SimplIssue("The composite objects are not equal.", originalDescribedObject, deserializedDescribedObject)); return(false); } } else { if (fieldDescriptor.IsCollection) { // We have three options here; either the field is an IDictionary, in which case we need to sort and compare keys // or we have an IList, in which case we should sort and compare values. // or we have another collection that we don't support for some reason. Throw exception. var collectionType = originalDescribedObject.GetType(); var comparator = new SimplObjectEqualityComparer(); var result = comparator.Equals(originalDescribedObject, deserializedDescribedObject); if (!result) { issues.Add(new SimplIssue("Collections between two types differ in values", originalDescribedObject, deserializedDescribedObject)); } return(result); } else { if (fieldDescriptor.IsScalar) { if (!fieldDescriptor.ContextSimplEquals(originalObject, deserializedObject)) { issues.Add(new SimplIssue("RHS and LHS scalars are different", originalDescribedObject.ToString(), deserializedDescribedObject.ToString())); return(false); } } else { throw new ArgumentException("Given field descriptor cannot be compared in the test method yet. Type: {0}", fieldDescriptor.CSharpTypeName); } } } } } else { issues.Add(new SimplIssue("Types of original object and deserialized object differ.", originalObject.GetType(), deserializedObject.GetType())); return(false); } //If we didn't return false by now, the types are equal. return(true); }
/// <summary> /// /// </summary> /// <param name="root"></param> /// <param name="rootClassDescriptor"></param> /// <returns></returns> private void DeserializeAttributes(object root, ClassDescriptor rootClassDescriptor) { while (_xmlReader.MoveToNextAttribute()) { String tag = _xmlReader.Name; String value = _xmlReader.Value; //silently ignore simpl namespace. if (tag.Equals(TranslationContext.SimplNamespace)) continue; if(tag.Equals(TranslationContext.SimplId)) { translationContext.MarkAsUnmarshalled(value, root); } else { FieldDescriptor attributeFieldDescriptor = rootClassDescriptor.GetFieldDescriptorByTag(tag); if (attributeFieldDescriptor != null) { attributeFieldDescriptor.SetFieldToScalar(root, value, translationContext); } else { Debug.WriteLine("ignoring attribute: " + tag); } } } _xmlReader.MoveToElement(); }
private string WriteClassDefinition(ClassDescriptor @class) { IDescriptorWriter writer = @class.GetWriter(_diagram); return(writer.Write(_context)); }
public QualityCondition Convert([NotNull] Matrix matrix, [NotNull] IList <Dataset> datasets) { Assert.ArgumentNotNull(matrix, nameof(matrix)); Assert.ArgumentNotNull(datasets, nameof(datasets)); var classDescriptor = new ClassDescriptor(typeof(QaTopoNotNearPolyFactory)); var testDescriptor = new TestDescriptor( _importedTestDescriptor, classDescriptor); var qualityCondition = new QualityCondition( _importedQualityCondition, testDescriptor); Dictionary <string, TestParameter> parDict = QaTopoNotNearPolyFactory .CreateParameterList() .ToDictionary(x => x.Name); VectorDataset featureClassDs = GetDataset(matrix.FeatureClassName, datasets); qualityCondition.AddParameterValue(new DatasetTestParameterValue( parDict[ QaTopoNotNearPolyFactory .FeatureClassParamName], featureClassDs) { FilterExpression = matrix.FeatureClassFilter }); VectorDataset referenceDs = GetDataset(matrix.ReferenceName, datasets); qualityCondition.AddParameterValue(new DatasetTestParameterValue( parDict[ QaTopoNotNearPolyFactory.ReferenceParamName], referenceDs) { FilterExpression = matrix.ReferenceFilter }); { GetSubtypes(featureClassDs, out string field, out IList <Subtype> subtypes); Assert.NotNull(field); Assert.NotNull(subtypes); foreach (FeatureTypeProps featureTypeProps in matrix.FeatureClassTypes) { string subtypeName = featureTypeProps.SubType.SubtypeName.Trim(); Subtype subtype = subtypes.First(x => x.Name.Equals(subtypeName)); StringBuilder rulesBuilder = new StringBuilder(); rulesBuilder.Append($"{subtype.Code};"); rulesBuilder.Append($"{featureTypeProps.DefaultDistance};"); rulesBuilder.Append($"{featureTypeProps.RightSideDistance};"); foreach (int canOverlap in featureTypeProps.CanOverlap) { rulesBuilder.Append($"{canOverlap};"); } qualityCondition.AddParameterValue(new ScalarTestParameterValue( parDict[ QaTopoNotNearPolyFactory .FeaturesubtypeRulesParamName], rulesBuilder.ToString())); } } { GetSubtypes(referenceDs, out string field, out IList <Subtype> subtypes); Assert.NotNull(field); Assert.NotNull(subtypes); foreach (ConnectionType refType in matrix.ReferenceTypes) { string subtypeName = refType.SubtypeName.Trim(); Subtype subtype = subtypes.First(x => x.Name.Equals(subtypeName)); qualityCondition.AddParameterValue(new ScalarTestParameterValue( parDict[ QaTopoNotNearPolyFactory .ReferenceSubtypesParamName], subtype.Code)); } } return(qualityCondition); }
public CompositeType(Type theType) : base(theType.Name, theType, "java", "objc", "db") { this.Type = ClassDescriptor.GetClassDescriptor(theType); this.cSharpTypeName = theType.Name; }
public static IEnumerable <T> LineToObject <T>(this IEnumerable <Line> lines) where T : class, new() { if (lines == null) { yield break; } var classDescriptor = ClassDescriptor.GetClassDescriptor(typeof(T)); using (var e = lines.GetEnumerator()) { Line header = null; string[] allFields = null; HashSet <string> allValidFields = null; if (e.MoveNext()) { header = e.Current; allFields = header.Fields.Select(f => f.Trim()).ToArray(); var allMembers = classDescriptor .Members .Where(m => m.MemberInfo.GetCustomAttributes(typeof(IgnoreMemberAttribute), true).Length == 0) .ToArray() ; var allWriteableMembers = allMembers .Where(m => m.HasSetter) .Select(memberDefinition => memberDefinition.Name) .ToArray(); var allStringMembers = allMembers .Where(m => m.MemberType == typeof(string)) .Select(memberDefinition => memberDefinition.Name) .ToArray(); var allNonWriteableMembers = allMembers .Where(m => !m.HasSetter) .Select(memberDefinition => memberDefinition.Name) .ToArray(); var allNonStringMembers = allMembers .Where(m => m.MemberType != typeof(string)) .Select(memberDefinition => memberDefinition.Name) .ToArray(); var emptyFieldCount = allFields.Count(s => s.IsNullOrWhiteSpace()); if (emptyFieldCount > 0) { ParserWarning("Empty field names in header line: {0}", emptyFieldCount); } var missingFields = allWriteableMembers.Except(allFields).ToArray(); if (missingFields.Length > 0) { ParserWarning("Missing field names in header line: {0}", missingFields.Concatenate()); } var additionalFields = allFields.Except(allWriteableMembers).ToArray(); if (additionalFields.Length > 0) { ParserWarning("Additionals field names in header line (ignored): {0}", additionalFields.Concatenate()); } var allNonWriteableFields = allFields.Intersect(allNonWriteableMembers).ToArray(); if (allNonWriteableFields.Length > 0) { ParserWarning("Non writeable fields referenced: {0}", allNonWriteableFields.Concatenate()); } var allNonStringFields = allFields.Intersect(allNonStringMembers).ToArray(); if (allNonWriteableFields.Length > 0) { ParserWarning("Non string fields referenced: {0}", allNonStringFields.Concatenate()); } allValidFields = new HashSet <string>(allFields .Intersect(allWriteableMembers) .Intersect(allStringMembers) ); } if (header == null) { yield break; } while (e.MoveNext()) { var line = e.Current; if (line.IsEmpty) { continue; } var lineFields = line.Fields; if (allFields.Length < lineFields.Length) { ParserWarning( "Line @{0} - {1} additinal fields detected", line.LineNo, lineFields.Length - allFields.Length ); } if (lineFields.Length < allFields.Length) { ParserWarning( "Line @{0} - {1} missing fields detected", line.LineNo, allFields.Length - lineFields.Length ); } var instance = new T(); var lineSource = instance as IOriginatedFromLine; if (lineSource != null) { lineSource.SetLine(line); } var max = Math.Min(lineFields.Length, allFields.Length); for (var iter = 0; iter < max; ++iter) { var fieldName = allFields[iter]; var fieldValue = lineFields[iter] ?? ""; if (allValidFields.Contains(fieldName)) { var memberDescriptor = classDescriptor.FindMember(fieldName); if (memberDescriptor != null) { memberDescriptor.Setter(instance, fieldValue.Trim()); } else { ParserWarning( "Line @{0} - Failed to set field {1}: {2}", line.LineNo, fieldName ); } } } yield return(instance); } } }
/// <summary> /// /// </summary> /// <param name="newMap"></param> /// <param name="key"></param> /// <param name="translationEntry"></param> /// <param name="warn"></param> private void UpdateMapWithEntry(Scope<ClassDescriptor> newMap, string key, ClassDescriptor translationEntry, string warn) { ClassDescriptor existingEntry = null; Boolean entryExists = newMap.TryGetValue(key, out existingEntry); Boolean newEntry = !entryExists ? true : existingEntry.DescribedClass != translationEntry.DescribedClass; if (newEntry) { if (entryExists) Debug.WriteLine("Overriding " + warn + " " + key + " with " + translationEntry); newMap.Add(key, translationEntry); } }
protected virtual void GenerateChildPropertySet (GeneratorContext ctx, CodeVariableReferenceExpression var, ClassDescriptor containerChildClass, PropertyDescriptor prop, object child) { if (containerChildClass.InitializationProperties != null && Array.IndexOf (containerChildClass.InitializationProperties, prop) != -1) return; // Design time if (prop.Name == "AutoSize") return; object oval = prop.GetValue (child); if (oval == null || (prop.HasDefault && prop.IsDefaultValue (oval))) return; CodePropertyReferenceExpression cprop = new CodePropertyReferenceExpression (var, prop.Name); CodeExpression val = ctx.GenerateValue (oval, prop.RuntimePropertyType, prop.Translatable); ctx.Statements.Add (new CodeAssignStatement (cprop, val)); }
public override void LoadChildren() { Children.Clear(); foreach (ISettings item in SettingsObject.Children.AsSafeEnumable()) { var modelItem = new SettingsModel {SettingsObject = item}; //modelItem.Parent = this; var descriptor = new ClassDescriptor(item.GetType()); modelItem.Text = descriptor.Title; modelItem.ToolTipText = descriptor.Description; Children.Add(modelItem); } }
public FieldDescriptor(ClassDescriptor baseClassDescriptor) : base(baseClassDescriptor.TagName, null) { declaringClassDescriptor = baseClassDescriptor; field = null; type = FieldTypes.Pseudo; ScalarType = null; bibtexTag = baseClassDescriptor.BibtexType; }
public MetaMetadataClassDescriptor(string tagName, string comment, string describedClassPackageName, string describedClassSimpleName, ClassDescriptor superClass, List<string> interfaces) : base(tagName, comment, describedClassPackageName, describedClassSimpleName, superClass, interfaces) { }
public FieldDescriptor(ClassDescriptor declaringClassDescriptor, FieldInfo field, int annotationType) : base(XmlTools.GetXmlTagName(field), field.Name) { this.declaringClassDescriptor = declaringClassDescriptor; this.field = field; fieldType = field.FieldType.Name; //generics if (field.FieldType.IsGenericParameter || field.FieldType.GetTypeInfo().IsGenericType) { Type realFieldType = field.FieldType; while (realFieldType.IsGenericParameter) { Type[] realFieldTypeConstraints = realFieldType.GetTypeInfo().GetGenericParameterConstraints(); if (realFieldTypeConstraints == null || realFieldTypeConstraints.Length == 0) { realFieldType = typeof(Object); break; } else realFieldType = realFieldTypeConstraints[0]; } fieldType = realFieldType.Name; if (realFieldType.GetTypeInfo().IsGenericType)//can also be a generic parameter that extends a generic type { int pos = fieldType.IndexOf('`'); fieldType = fieldType.Substring(0, pos); } } if (XmlTools.IsAnnotationPresent<SimplMapKeyField>(field)) { mapKeyFieldName = XmlTools.GetAnnotation<SimplMapKeyField>(field).FieldName; } DerivePolymorphicDescriptors(field); type = FieldTypes.UnsetType; if (annotationType == FieldTypes.Scalar) { type = DeriveScalarSerialization(field); } else { type = DeriveNestedSerialization(field, annotationType); } String fieldName = field.Name; StringBuilder capFieldName = new StringBuilder(fieldName); //generics Type genericType = field.DeclaringType; isGeneric = genericType.GetTypeInfo().IsGenericType || genericType.IsGenericParameter; }
/// <summary> /// resolving the graph based on the value of the graph switch /// </summary> /// <param name="obj"></param> public void ResolveGraph(object obj) { if (SimplTypesScope.graphSwitch == SimplTypesScope.GRAPH_SWITCH.ON) { _visitedElements.Add(obj.GetHashCode(), obj); List <FieldDescriptor> elementFieldDescriptors = ClassDescriptor.GetClassDescriptor(obj).ElementFieldDescriptors; foreach (FieldDescriptor elementFieldDescriptor in elementFieldDescriptors) { Object thatReferenceObject = null; FieldInfo childField = elementFieldDescriptor.Field; try { thatReferenceObject = childField.GetValue(obj); } catch (MemberAccessException e) { Debug.WriteLine("WARNING re-trying access! " + e.StackTrace); try { thatReferenceObject = childField.GetValue(obj); } catch (MemberAccessException e1) { Debug.WriteLine("Can't access " + childField.Name); Debug.WriteLine(e1.StackTrace); } } catch (Exception e) { Debug.WriteLine("error" + e); } if (thatReferenceObject == null) { continue; } int childFdType = elementFieldDescriptor.FdType; ICollection thatCollection; switch (childFdType) { case FieldTypes.CollectionElement: case FieldTypes.CollectionScalar: case FieldTypes.MapElement: thatCollection = XmlTools.GetCollection(thatReferenceObject); break; default: thatCollection = null; break; } if (thatCollection != null && (thatCollection.Count > 0)) { foreach (Object next in thatCollection) { var compositeElement = next; if (AlreadyVisited(compositeElement)) { _needsAttributeHashCode.Add(compositeElement.GetHashCode(), compositeElement); } else { ResolveGraph(compositeElement); } } } else { var compositeElement = thatReferenceObject; if (AlreadyVisited(compositeElement)) { _needsAttributeHashCode.Add(compositeElement.GetHashCode(), compositeElement); } else { ResolveGraph(compositeElement); } } } } }
private void RegisterPolymorphicDescriptor(ClassDescriptor classDescriptor) { if (polymorphClassDescriptors == null) InitPolymorphicClassDescriptorsList(1); String classTag = classDescriptor.TagName; polymorphClassDescriptors.Put(classTag, classDescriptor); tlvClassDescriptors.Put(classTag.GetHashCode(), classDescriptor); if (otherTags != null) foreach (String otherTag in classDescriptor.OtherTags) { if (!String.IsNullOrEmpty(otherTag)) { polymorphClassDescriptors.Put(otherTag, classDescriptor); tlvClassDescriptors.Put(otherTag.GetHashCode(), classDescriptor); } } }
/// <summary> /// /// </summary> /// <param name="root"></param> /// <param name="rootClassDescriptor"></param> /// <param name="length"></param> /// <returns></returns> private Object CreateObjectModel(Object root, ClassDescriptor rootClassDescriptor, int length) { int bytesRead = 0; while (!_isEos && bytesRead < length) { bytesRead += NextHeader(); if (_blockType == TranslationContext.SimplId.GetTlvId()) { int simplId = _binaryReader.ReadInt32(); translationContext.MarkAsUnmarshalled(simplId.ToString(), root); bytesRead += 4; continue; } if (_blockType == TranslationContext.SimplRef.GetTlvId()) { int simplRef = _binaryReader.ReadInt32(); return(translationContext.GetFromMap(simplRef.ToString())); } FieldDescriptor currentFieldDescriptor = rootClassDescriptor.GetFieldDescriptorByTlvId(_blockType); int fieldType = currentFieldDescriptor.FdType; switch (fieldType) { case FieldTypes.Scalar: bytesRead += DeserializeScalar(root, currentFieldDescriptor); break; case FieldTypes.CollectionScalar: bytesRead += DeserializeScalarCollectionElement(root, currentFieldDescriptor); break; case FieldTypes.CompositeElement: bytesRead += DeserializeComposite(root, currentFieldDescriptor); break; case FieldTypes.CollectionElement: bytesRead += DeserializeCompositeCollectionElement(root, currentFieldDescriptor); break; case FieldTypes.MapElement: bytesRead += DeserializeCompositeMapElement(root, currentFieldDescriptor); break; case FieldTypes.Wrapper: currentFieldDescriptor = currentFieldDescriptor.WrappedFd; switch (currentFieldDescriptor.FdType) { case FieldTypes.CollectionScalar: bytesRead += DeserializeScalarCollection(root, currentFieldDescriptor); break; case FieldTypes.CollectionElement: bytesRead += DeserializeCompositeCollection(root, currentFieldDescriptor); break; case FieldTypes.MapElement: bytesRead += DeserializeCompositeMap(root, currentFieldDescriptor); break; case FieldTypes.CompositeElement: //TODO: wrapped composites in tlv? break; } break; } } DeserializationPostHook(root, translationContext); if (deserializationHookStrategy != null) { deserializationHookStrategy.DeserializationPostHook(root, null); } return(root); }
public FieldDescriptor(ClassDescriptor baseClassDescriptor, FieldDescriptor wrappedFD, String wrapperTag) : base(wrapperTag, null) { declaringClassDescriptor = baseClassDescriptor; this.wrappedFD = wrappedFD; wrappedFD.Wrapper = this; type = FieldTypes.Wrapper; }
public static void Render <TProperties>(this ClassDescriptor <TProperties> classDescriptor, string targetId) where TProperties : new() { var instance = createElement(classDescriptor.Class, classDescriptor.Properties); render(instance, document.getElementById(targetId)); }
FieldDescriptor(String tag) : base(tag, null) { this._tagName = tag; this.type = FieldTypes.IgnoredElement; this.field = null; this.declaringClassDescriptor = null; }
public static void Render <TProperties>(this ClassDescriptor <TProperties> classDescriptor, HTMLElement target) where TProperties : new() { var instance = createElement(classDescriptor.Class, classDescriptor.Properties); render(instance, target); }
private int DeriveNestedSerialization(FieldInfo thatField, int annotationType) { int result = annotationType; Type thatFieldType = thatField.FieldType; switch (annotationType) { case FieldTypes.CompositeElement: String compositeTag = XmlTools.GetAnnotation<SimplComposite>(thatField).TagName; Boolean isWrap = XmlTools.IsAnnotationPresent<SimplWrap>(thatField); Boolean compositeTagIsNullOrEmpty = String.IsNullOrEmpty(compositeTag); if (!IsPolymorphic) { if (isWrap && compositeTagIsNullOrEmpty) { String msg = "In " + declaringClassDescriptor.DescribedClass + "\n\tCan't translate [SimplComposite] " + thatField.Name + " because its tag argument is missing."; Debug.WriteLine(msg); return FieldTypes.IgnoredAttribute; } _elementClassDescriptor = ClassDescriptor.GetClassDescriptor(thatFieldType); _elementClass = _elementClassDescriptor.DescribedClass; compositeTag = XmlTools.GetXmlTagName(thatField); } else { if (!compositeTagIsNullOrEmpty) { String msg = "In " + declaringClassDescriptor.DescribedClass + "\n\tCan't translate [SimplComposite] " + thatField.Name + " because its tag argument is missing."; Debug.WriteLine(msg); } } compositeTagName = compositeTag; break; case FieldTypes.CollectionElement: if (!(typeof(IList).GetTypeInfo().IsAssignableFrom(thatField.FieldType.GetTypeInfo()))) { String msg = "In " + declaringClassDescriptor.DescribedClass + "\n\tCan't translate " + "[SimplCollection] " + field.Name + " because the annotated field is not an instance of " + typeof (IList).Name + "."; Debug.WriteLine(msg); return FieldTypes.IgnoredAttribute; } String collectionTag = XmlTools.GetAnnotation<SimplCollection>(thatField).TagName; if (!IsPolymorphic) { Type collectionElementType = GetTypeArgs(thatField, 0); if (String.IsNullOrEmpty(collectionTag)) { String msg = "In " + declaringClassDescriptor.DescribedClass + "\n\tCan't translate [SimplCollection]" + field.Name + " because its tag argument is missing."; Debug.WriteLine(msg); return FieldTypes.IgnoredElement; } if (collectionElementType == null) { String msg = "In " + declaringClassDescriptor.DescribedClass + "\n\tCan't translate [SimplCollection] " + field.Name + " because the parameterized type argument for the Collection is missing."; Debug.WriteLine(msg); return FieldTypes.IgnoredElement; } if (!TypeRegistry.ScalarTypes.Contains(collectionElementType)) { _elementClassDescriptor = ClassDescriptor.GetClassDescriptor(collectionElementType); _elementClass = _elementClassDescriptor.DescribedClass; } else { result = FieldTypes.CollectionScalar; DeriveScalarSerialization(collectionElementType, field); if (ScalarType == null) { result = FieldTypes.IgnoredElement; String msg = "Can't identify ScalarType for serialization of " + collectionElementType; Debug.WriteLine(msg); } } } else { if (!String.IsNullOrEmpty(collectionTag)) { String msg = "In " + declaringClassDescriptor.DescribedClass + "\n\tIgnoring argument to [SimplCollection] " + field.Name + " because it is declared polymorphic with [SimplClasses]."; } } _collectionOrMapTagName = collectionTag; collectionType = TypeRegistry.GetCollectionType(thatField); break; case FieldTypes.MapElement: if (!(typeof(IDictionary).GetTypeInfo().IsAssignableFrom(thatField.FieldType.GetTypeInfo()))) { String msg = "In " + declaringClassDescriptor.DescribedClass + "\n\tCan't translate " + "[SimplMap] " + field.Name + " because the annotated field is not an instance of " + typeof (IDictionary).Name + "."; Debug.WriteLine(msg); return FieldTypes.IgnoredAttribute; } String mapTag = XmlTools.GetAnnotation<SimplMap>(thatField).TagName; if (!IsPolymorphic) { Type mapElementType = GetTypeArgs(thatField, 1); if (String.IsNullOrEmpty(mapTag)) { String msg = "In " + declaringClassDescriptor.DescribedClass + "\n\tCan't translate [SimplMap]" + field.Name + " because its tag argument is missing."; Debug.WriteLine(msg); return FieldTypes.IgnoredElement; } if (mapElementType == null) { String msg = "In " + declaringClassDescriptor.DescribedClass + "\n\tCan't translate [SimplMap] " + field.Name + " because the parameterized type argument for the map is missing."; Debug.WriteLine(msg); return FieldTypes.IgnoredElement; } if (!TypeRegistry.ScalarTypes.Contains(mapElementType)) { _elementClassDescriptor = ClassDescriptor.GetClassDescriptor(mapElementType); _elementClass = _elementClassDescriptor.DescribedClass; } } else { if (!String.IsNullOrEmpty(mapTag)) { String msg = "In " + declaringClassDescriptor.DescribedClass + "\n\tIgnoring argument to [SimplMap] " + field.Name + " because it is declared polymorphic with [SimplClasses]."; } } _collectionOrMapTagName = mapTag; collectionType = TypeRegistry.GetCollectionType(thatField); break; } switch (annotationType) { case FieldTypes.CollectionElement: case FieldTypes.MapElement: if (!XmlTools.IsAnnotationPresent<SimplNoWrap>(thatField)) { _wrapped = true; } collectionType = TypeRegistry.GetCollectionType(thatField); break; case FieldTypes.CompositeElement: if (XmlTools.IsAnnotationPresent<SimplWrap>(thatField)) { _wrapped = true; } break; } return result; }
public void Add(UInt64 key, ClassDescriptor value) { innerHash.Add(key, value); }