public bool equals(FieldDescriptor fd) { return fieldName.Equals(fd.fieldName) && className.Equals(fd.className) && valueDesc == fd.valueDesc && type == fd.type; }
private static bool IsSerializable(FieldDescriptor fd, object obj) { switch (fd.FdType) { case FieldTypes.Scalar: if (fd.IsDefaultValueFromContext(obj)) return false; break; case FieldTypes.CompositeElement: case FieldTypes.CollectionElement: case FieldTypes.MapElement: Object tempObj = fd.GetObject(obj); if (tempObj == null) return false; break; case FieldTypes.CollectionScalar: case FieldTypes.MapScalar: Object scalarCollectionObject = fd.GetObject(obj); if (scalarCollectionObject == null) return false; ICollection scalarCollection = XmlTools.GetCollection(scalarCollectionObject); if (scalarCollection == null || scalarCollection.Count <= 0) return false; break; } return true; }
internal ExtensionGenerator(FieldDescriptor descriptor) : base(descriptor, 0) { if (Descriptor.ExtensionScope != null) { scope = GetClassName(Descriptor.ExtensionScope); } else { scope = DescriptorUtil.GetFullUmbrellaClassName(Descriptor.File); } switch (Descriptor.MappedType) { case MappedType.Message: type = GetClassName(Descriptor.MessageType); break; case MappedType.Enum: type = GetClassName(Descriptor.EnumType); break; default: type = DescriptorUtil.GetMappedTypeName(Descriptor.MappedType); break; } extends = GetClassName(Descriptor.ContainingType); name = Descriptor.CSharpOptions.PropertyName; }
public override void Get(FieldDescriptor ds_, IDataReader dr_) { switch( ds_.Pos ) { case 0: Name = dr_.AsString(); break; case 1: dr_.AsMessage(_data??(Data = new Struct()), ds_); break; } }
public override void LoadFields(FieldDescriptor[] fields) { base.LoadFields(fields); // removes RequiredMessageHeader if (Fields.Length != 2 || Fields[0].Type.Name != "DT_INT" || Fields[0].HasMinMax != false && Fields[0].EncodedBits != 32 || Fields[1].Type != null) throw new Exception("Unexpected fields in GenericBlobMessage"); }
public override void LoadFields(FieldDescriptor[] fields) { base.LoadFields(fields); // removes RequiredMessageHeader if (Fields.Length != 3 || Fields[0].Type.Name != "DT_INT" || Fields[1].Type.Name != "DT_FIXEDARRAY" || Fields[1].SubType.Name != "NetAttributeKeyValue" || Fields[2].Type != null) throw new Exception("Unexpected fields in AttributesSetValuesMessage."); }
public override void LoadFields(FieldDescriptor[] fields) { base.LoadFields(fields); // removes RequiredMessageHeader if (this.Fields.Length != 4 || this.Fields[0].Type._Name != "RequiredMessageHeader" || this.Fields[1].Type._Name != "DT_INT" || this.Fields[2].Type._Name != "NetAttributeKeyValue" || this.Fields[3].Type != null) throw new Exception("Unexpected fields in AttributeSetValueMessage"); }
/// <summary> /// /// </summary> /// <param name="obj"></param> /// <param name="textWriter"></param> /// <param name="translationContext"></param> /// <param name="fd"></param> private void SerializeComposite(object obj, TextWriter textWriter, TranslationContext translationContext, FieldDescriptor fd) { Object compositeObject = fd.GetObject(obj); FieldDescriptor compositeAsScalarFd = GetClassDescriptor(compositeObject).ScalarValueFieldDescripotor; if (compositeAsScalarFd != null) { WriteBibtexAttribute(compositeObject, fd, textWriter, translationContext); } }
/// <summary> /// Munges a single value and checks that the length ends up the same as it was before. /// </summary> private static object CheckedMungeValue(FieldDescriptor fieldDescriptor, object value) { int currentSize = CodedOutputStream.ComputeFieldSize(fieldDescriptor.FieldType, fieldDescriptor.FieldNumber, value); object mungedValue = MungeValue(fieldDescriptor, value); int mungedSize = CodedOutputStream.ComputeFieldSize(fieldDescriptor.FieldType, fieldDescriptor.FieldNumber, mungedValue); // Exceptions log more easily than assertions if (currentSize != mungedSize) { throw new Exception("Munged value had wrong size. Field type: " + fieldDescriptor.FieldType + "; old value: " + value + "; new value: " + mungedValue); } return mungedValue; }
protected virtual FieldDescriptor GetAdditionalParameters(Item standardValues, Dictionary<string, string> additionalParameters) { Assert.ArgumentNotNull(standardValues, "standardValues"); Assert.ArgumentNotNull(additionalParameters, "additionalParameters"); var value = new UrlString(); foreach (var key in additionalParameters.Keys) { value[key] = HttpUtility.UrlDecode(additionalParameters[key]); } var descriptor = new FieldDescriptor(standardValues, "Additional Parameters") { Value = value.ToString() }; return descriptor; }
/// <summary> /// /// </summary> /// <param name="obj"></param> /// <param name="rootObjectFieldDescriptor"></param> /// <param name="textWriter"></param> /// <param name="translationContext"></param> private void Serialize(object obj, FieldDescriptor rootObjectFieldDescriptor, TextWriter textWriter, TranslationContext translationContext) { SerializationPreHook(obj, translationContext); WriteObjectStart(rootObjectFieldDescriptor, textWriter); IEnumerable<FieldDescriptor> allFieldDescriptors = GetClassDescriptor(obj).AllFieldDescriptors; SerializeFields(obj, textWriter, translationContext, allFieldDescriptors.ToList()); WriteClose(textWriter); SerializationPostHook(obj, translationContext); }
internal SingleFieldAccessor(PropertyInfo property, FieldDescriptor descriptor) : base(property, descriptor) { if (!property.CanWrite) { throw new ArgumentException("Not all required properties/methods available"); } setValueDelegate = ReflectionUtil.CreateActionIMessageObject(property.GetSetMethod()); var clrType = property.PropertyType; // TODO: Validate that this is a reasonable single field? (Should be a value type, a message type, or string/ByteString.) object defaultValue = descriptor.FieldType == FieldType.Message ? null : clrType == typeof(string) ? "" : clrType == typeof(ByteString) ? ByteString.Empty : Activator.CreateInstance(clrType); clearDelegate = message => SetValue(message, defaultValue); }
private void AddToMapOrMarkUnresolved(object root, FieldDescriptor currentFieldDescriptor, object subRoot, string simplId) { IDictionary collection = (IDictionary) currentFieldDescriptor.AutomaticLazyGetCollectionOrMap(root); if (subRoot != null) { var mappable = subRoot as IMappable<object>; if (mappable != null) { var key = mappable.Key(); collection.Add(key, mappable); } } else translationContext.RefObjectNeedsIdResolve(collection, null, simplId); }
private static void SerializeScalar(object obj, FieldDescriptor fd, TextWriter textWriter, TranslationContext translationContext) { // check wether we need quotation marks to surround the value. bool needQuotationMarks = true; ScalarType st = fd.ScalarType; if (st != null) { needQuotationMarks = st.NeedsJsonQuotationWrap(); } textWriter.Write('"'); textWriter.Write(fd.TagName); textWriter.Write('"'); textWriter.Write(':'); if (needQuotationMarks) textWriter.Write('"'); fd.AppendValue(textWriter, obj, translationContext, Format.Json); if (needQuotationMarks) textWriter.Write('"'); }
/// <summary> /// /// </summary> /// <param name="obj"></param> /// <param name="rootObjectFieldDescriptor"></param> /// <param name="binaryWriter"></param> /// <param name="translationContext"></param> private void Serialize(object obj, FieldDescriptor rootObjectFieldDescriptor, BinaryWriter binaryWriter, TranslationContext translationContext) { if (AlreadySerialized(obj, translationContext)) { WriteSimplRef(obj, rootObjectFieldDescriptor, binaryWriter); return; } translationContext.MapObject(obj); SerializationPreHook(obj, translationContext); ClassDescriptor rootObjectClassDescriptor = GetClassDescriptor(obj); MemoryStream bufferMemoryStream = new MemoryStream(); BinaryWriter outputBuffer = new BinaryWriter(bufferMemoryStream); IEnumerable<FieldDescriptor> allFieldDescriptors = GetClassDescriptor(obj).AllFieldDescriptors; SerializeFields(obj, outputBuffer, translationContext, allFieldDescriptors.ToList()); WriteHeader(binaryWriter, bufferMemoryStream, rootObjectFieldDescriptor.TlvId); SerializationPostHook(obj, translationContext); }
internal static void PrintField(FieldDescriptor field, object value, TextGenerator generator) { if (field.IsRepeated) { // Repeated field. Print each element. foreach (object element in (IEnumerable) value) { PrintSingleField(field, element, generator); } } else { PrintSingleField(field, value, generator); } }
private static void PrintFieldValue(FieldDescriptor field, object value, TextGenerator generator) { switch (field.FieldType) { // The Float and Double types must specify the "r" format to preserve their precision, otherwise, // the double to/from string will trim the precision to 6 places. As with other numeric formats // below, always use the invariant culture so it's predictable. case FieldType.Float: generator.Print(((float)value).ToString("r", FrameworkPortability.InvariantCulture)); break; case FieldType.Double: generator.Print(((double)value).ToString("r", FrameworkPortability.InvariantCulture)); break; case FieldType.Int32: case FieldType.Int64: case FieldType.SInt32: case FieldType.SInt64: case FieldType.SFixed32: case FieldType.SFixed64: case FieldType.UInt32: case FieldType.UInt64: case FieldType.Fixed32: case FieldType.Fixed64: // The simple Object.ToString converts using the current culture. // We want to always use the invariant culture so it's predictable. generator.Print(((IConvertible)value).ToString(FrameworkPortability.InvariantCulture)); break; case FieldType.Bool: // Explicitly use the Java true/false generator.Print((bool) value ? "true" : "false"); break; case FieldType.String: generator.Print("\""); generator.Print(EscapeText((string) value)); generator.Print("\""); break; case FieldType.Bytes: { generator.Print("\""); generator.Print(EscapeBytes((ByteString) value)); generator.Print("\""); break; } case FieldType.Enum: { if (value is IEnumLite && !(value is EnumValueDescriptor)) { throw new NotSupportedException("Lite enumerations are not supported."); } generator.Print(((EnumValueDescriptor) value).Name); break; } case FieldType.Message: case FieldType.Group: if (value is IMessageLite && !(value is IMessage)) { throw new NotSupportedException("Lite messages are not supported."); } Print((IMessage) value, generator); break; } }
IBuilder IBuilder.WeakAddRepeatedField(FieldDescriptor field, object value) { return(AddRepeatedField(field, value)); }
public static uint MakeTag(FieldDescriptor field) { return MakeTag(field.FieldNumber, GetWireType(field)); }
static Iso8583TermApp() { binaryTemplate = new Template { { Bit._002_PAN, FieldDescriptor.AsciiVar(2, 19, FieldValidators.N) }, { Bit._003_PROC_CODE, FieldDescriptor.AsciiFixed(6, FieldValidators.N) }, { Bit._004_TRAN_AMOUNT, FieldDescriptor.AsciiFixed(12, FieldValidators.N) }, { Bit._005_SETTLE_AMOUNT, FieldDescriptor.AsciiFixed(12, FieldValidators.N) }, { Bit._007_TRAN_DATE_TIME, FieldDescriptor.AsciiFixed(10, FieldValidators.N) }, { Bit._009_CONVERSION_RATE_SETTLEMENT, FieldDescriptor.AsciiFixed(8, FieldValidators.N) }, { Bit._011_SYS_TRACE_AUDIT_NUM, FieldDescriptor.AsciiFixed(6, FieldValidators.N) }, { Bit._012_LOCAL_TRAN_DATETIME, FieldDescriptor.AsciiFixed(12, FieldValidators.N) }, { Bit._014_EXPIRY_DATE, FieldDescriptor.AsciiFixed(4, FieldValidators.N) }, { Bit._016_CONVERSION_DATE, FieldDescriptor.AsciiFixed(4, FieldValidators.N) }, { Bit._022_POS_DATA_CODE, FieldDescriptor.AsciiFixed(15, FieldValidators.Ans) }, { Bit._023_CARD_SEQ_NR, FieldDescriptor.AsciiFixed(3, FieldValidators.N) }, { Bit._024_FUNC_CODE, FieldDescriptor.AsciiFixed(3, FieldValidators.N) }, { Bit._027_APPROVAL_CODE_LEN, FieldDescriptor.AsciiFixed(1, FieldValidators.N) }, { Bit._028_RECON_DATE, FieldDescriptor.AsciiFixed(6, FieldValidators.N) }, { Bit._029_RECON_INDICATOR, FieldDescriptor.AsciiFixed(3, FieldValidators.N) }, { Bit._030_AMOUNTS_ORIGINAL, FieldDescriptor.AsciiFixed(24, FieldValidators.N) }, { Bit._032_ACQ_INST_ID_CODE, FieldDescriptor.AsciiVar(2, 11, FieldValidators.N) }, { Bit._035_TRACK_2_DATA, FieldDescriptor.AsciiVar(2, 37, FieldValidators.Track2) }, { Bit._037_RET_REF_NR, FieldDescriptor.AsciiFixed(12, FieldValidators.Anp) }, { Bit._038_APPROVAL_CODE, FieldDescriptor.AsciiFixed(6, FieldValidators.Anp) }, { Bit._039_ACTION_CODE, FieldDescriptor.AsciiFixed(3, FieldValidators.N) }, { Bit._040_SERVICE_CODE, FieldDescriptor.AsciiFixed(3, FieldValidators.N) }, { Bit._041_TERMINAL_ID, FieldDescriptor.AsciiFixed(8, FieldValidators.Ans) }, { Bit._042_CARD_ACCEPTOR_ID, FieldDescriptor.AsciiFixed(15, FieldValidators.Ans) }, { Bit._044_ADDITIONAL_RESPONSE_DATA, FieldDescriptor.AsciiVar(2, 99, FieldValidators.Ans) }, { Bit._045_TRACK_1_DATA, FieldDescriptor.AsciiVar(2, 76, FieldValidators.Ans) }, { Bit._046_FEES_AMOUNTS, FieldDescriptor.AsciiVar(3, 204, FieldValidators.Ans) }, { Bit._048_PRIVATE_ADDITIONAL_DATA, FieldDescriptor.AsciiVar(4, 9999, FieldValidators.None) }, { Bit._049_TRAN_CURRENCY_CODE, FieldDescriptor.AsciiFixed(3, FieldValidators.N) }, { Bit._050_SETTLEMENT_CURRENCY_CODE, FieldDescriptor.AsciiFixed(3, FieldValidators.N) }, { Bit._052_PIN_DATA, FieldDescriptor.BinaryFixed(8) }, { Bit._053_SECURITY_INFO, new FieldDescriptor(new VariableLengthFormatter(2, 96), FieldValidators.Hex, Formatters.Binary, null) }, { Bit._054_ADDITIONAL_AMOUNTS, FieldDescriptor.AsciiVar(3, 96, FieldValidators.Hex) }, { Bit._055_ICC_DATA, FieldDescriptor.BinaryVar(3, 999, FieldValidators.None) }, { Bit._056_ORIG_DATA_ELEMENTS, FieldDescriptor.AsciiVar(2, 35, FieldValidators.N) }, { Bit._057_AUTH_LIFE_CYCLE_CODE, FieldDescriptor.AsciiFixed(3, FieldValidators.N) }, { Bit._058_AUTH_AGENT_INST_ID_CODE, FieldDescriptor.AsciiVar(2, 11, FieldValidators.N) }, { Bit._059_ECHO_DATA, FieldDescriptor.AsciiVar(3, 200, FieldValidators.Ans) }, { Bit._062_HOTCARD_CAPACITY, FieldDescriptor.AsciiVar(3, 5, FieldValidators.N) }, { Bit._063_TERMAPP_PRIVATE_DATA, FieldDescriptor.AsciiVar(3, 999, FieldValidators.Hex) }, { Bit._064_MAC, FieldDescriptor.AsciiFixed(16, FieldValidators.Hex) }, { Bit._066_ORIGINAL_FEES_AMOUNTS, FieldDescriptor.AsciiVar(3, 204, FieldValidators.Ans) }, { Bit._067_EXT_PAYMENT_DATA, FieldDescriptor.AsciiFixed(2, FieldValidators.N) }, { Bit._071_MSG_NR, FieldDescriptor.AsciiFixed(8, FieldValidators.N) }, { Bit._072_DATA_RECORD, FieldDescriptor.AsciiVar(3, 999, FieldValidators.Ans) }, { Bit._074_NR_CREDITS, FieldDescriptor.AsciiFixed(10, FieldValidators.N) }, { Bit._075_NR_CREDITS_REVERSAL, FieldDescriptor.AsciiFixed(10, FieldValidators.N) }, { Bit._076_NR_DEBITS, FieldDescriptor.AsciiFixed(10, FieldValidators.N) }, { Bit._077_NR_DEBITS_REVERSAL, FieldDescriptor.AsciiFixed(10, FieldValidators.N) }, { Bit._081_NR_AUTHS, FieldDescriptor.AsciiFixed(10, FieldValidators.N) }, { Bit._086_AMOUNT_CREDITS, FieldDescriptor.AsciiFixed(16, FieldValidators.N) }, { Bit._087_AMOUNT_CREDITS_REVERSAL, FieldDescriptor.AsciiFixed(16, FieldValidators.N) }, { Bit._088_AMOUNT_DEBITS, FieldDescriptor.AsciiFixed(16, FieldValidators.N) }, { Bit._089_AMOUNT_DEBITS_REVERSAL, FieldDescriptor.AsciiFixed(16, FieldValidators.N) }, { Bit._090_NR_AUTHS_REVERSAL, FieldDescriptor.AsciiFixed(10, FieldValidators.N) }, { Bit._096_KEY_MANAGEMENT_DATA, FieldDescriptor.AsciiVar(3, 999, FieldValidators.Ans) }, { Bit._097_AMOUNT_NET_RECON, FieldDescriptor.AsciiFixed(17, FieldValidators.An) }, { Bit._098_PAYEE, FieldDescriptor.AsciiFixed(25, FieldValidators.Ans) }, { Bit._100_RECEIVING_INST_ID_CODE, FieldDescriptor.AsciiVar(2, 11, FieldValidators.N) }, { Bit._101_FILE_NAME, FieldDescriptor.AsciiVar(2, 99, FieldValidators.Ans) }, { Bit._102_ACCOUNT_ID_1, FieldDescriptor.AsciiVar(2, 28, FieldValidators.Ans) }, { Bit._103_ACCOUNT_ID_2, FieldDescriptor.AsciiVar(2, 28, FieldValidators.Ans) }, { Bit._104_TRAN_DESCRIPTION, FieldDescriptor.AsciiVar(4, 9999, FieldValidators.Ans) }, { Bit._109_FEE_AMOUNTS_CREDITS, FieldDescriptor.AsciiVar(2, 84, FieldValidators.Ans) }, { Bit._110_FEE_AMOUNTS_DEBITS, FieldDescriptor.AsciiVar(2, 84, FieldValidators.Ans) }, { Bit._123_RECEIPT_DATA, FieldDescriptor.AsciiVar(3, 999, FieldValidators.Ans) }, { Bit._124_DISPLAY_DATA, FieldDescriptor.AsciiVar(3, 999, FieldValidators.Ans) }, { Bit._128_MAC, FieldDescriptor.AsciiFixed(16, FieldValidators.Hex) }, }; binaryTemplate.BitmapFormatter = Formatters.Binary; asciiTemplate = new Template { { Bit._002_PAN, FieldDescriptor.AsciiVar(2, 19, FieldValidators.N) }, { Bit._003_PROC_CODE, FieldDescriptor.AsciiFixed(6, FieldValidators.N) }, { Bit._004_TRAN_AMOUNT, FieldDescriptor.AsciiFixed(12, FieldValidators.N) }, { Bit._005_SETTLE_AMOUNT, FieldDescriptor.AsciiFixed(12, FieldValidators.N) }, { Bit._007_TRAN_DATE_TIME, FieldDescriptor.AsciiFixed(10, FieldValidators.N) }, { Bit._009_CONVERSION_RATE_SETTLEMENT, FieldDescriptor.AsciiFixed(8, FieldValidators.N) }, { Bit._011_SYS_TRACE_AUDIT_NUM, FieldDescriptor.AsciiFixed(6, FieldValidators.N) }, { Bit._012_LOCAL_TRAN_DATETIME, FieldDescriptor.AsciiFixed(12, FieldValidators.N) }, { Bit._014_EXPIRY_DATE, FieldDescriptor.AsciiFixed(4, FieldValidators.N) }, { Bit._016_CONVERSION_DATE, FieldDescriptor.AsciiFixed(4, FieldValidators.N) }, { Bit._022_POS_DATA_CODE, FieldDescriptor.AsciiFixed(15, FieldValidators.Ans) }, { Bit._023_CARD_SEQ_NR, FieldDescriptor.AsciiFixed(3, FieldValidators.N) }, { Bit._024_FUNC_CODE, FieldDescriptor.AsciiFixed(3, FieldValidators.N) }, { Bit._027_APPROVAL_CODE_LEN, FieldDescriptor.AsciiFixed(1, FieldValidators.N) }, { Bit._028_RECON_DATE, FieldDescriptor.AsciiFixed(6, FieldValidators.N) }, { Bit._029_RECON_INDICATOR, FieldDescriptor.AsciiFixed(3, FieldValidators.N) }, { Bit._030_AMOUNTS_ORIGINAL, FieldDescriptor.AsciiFixed(24, FieldValidators.N) }, { Bit._032_ACQ_INST_ID_CODE, FieldDescriptor.AsciiVar(2, 11, FieldValidators.N) }, { Bit._035_TRACK_2_DATA, FieldDescriptor.AsciiVar(2, 37, FieldValidators.Track2) }, { Bit._037_RET_REF_NR, FieldDescriptor.AsciiFixed(12, FieldValidators.Anp) }, { Bit._038_APPROVAL_CODE, FieldDescriptor.AsciiFixed(6, FieldValidators.Anp) }, { Bit._039_ACTION_CODE, FieldDescriptor.AsciiFixed(3, FieldValidators.N) }, { Bit._040_SERVICE_CODE, FieldDescriptor.AsciiFixed(3, FieldValidators.N) }, { Bit._041_TERMINAL_ID, FieldDescriptor.AsciiFixed(8, FieldValidators.Ans) }, { Bit._042_CARD_ACCEPTOR_ID, FieldDescriptor.AsciiFixed(15, FieldValidators.Ans) }, { Bit._044_ADDITIONAL_RESPONSE_DATA, FieldDescriptor.AsciiVar(2, 99, FieldValidators.Ans) }, { Bit._045_TRACK_1_DATA, FieldDescriptor.AsciiVar(2, 76, FieldValidators.Ans) }, { Bit._046_FEES_AMOUNTS, FieldDescriptor.AsciiVar(3, 204, FieldValidators.Ans) }, { Bit._048_PRIVATE_ADDITIONAL_DATA, FieldDescriptor.AsciiVar(4, 9999, FieldValidators.None) }, { Bit._049_TRAN_CURRENCY_CODE, FieldDescriptor.AsciiFixed(3, FieldValidators.N) }, { Bit._050_SETTLEMENT_CURRENCY_CODE, FieldDescriptor.AsciiFixed(3, FieldValidators.N) }, { Bit._052_PIN_DATA, FieldDescriptor.AsciiFixed(16, FieldValidators.Hex) }, { Bit._053_SECURITY_INFO, new FieldDescriptor(new VariableLengthFormatter(2, 96), FieldValidators.Hex, Formatters.Binary, null) }, { Bit._054_ADDITIONAL_AMOUNTS, FieldDescriptor.AsciiVar(3, 96, FieldValidators.Hex) }, { Bit._055_ICC_DATA, FieldDescriptor.BinaryVar(3, 999, FieldValidators.None) }, { Bit._056_ORIG_DATA_ELEMENTS, FieldDescriptor.AsciiVar(2, 35, FieldValidators.N) }, { Bit._057_AUTH_LIFE_CYCLE_CODE, FieldDescriptor.AsciiFixed(3, FieldValidators.N) }, { Bit._058_AUTH_AGENT_INST_ID_CODE, FieldDescriptor.AsciiVar(2, 11, FieldValidators.N) }, { Bit._059_ECHO_DATA, FieldDescriptor.AsciiVar(3, 200, FieldValidators.Ans) }, { Bit._062_HOTCARD_CAPACITY, FieldDescriptor.AsciiVar(3, 5, FieldValidators.N) }, { Bit._063_TERMAPP_PRIVATE_DATA, FieldDescriptor.AsciiVar(3, 999, FieldValidators.Hex) }, { Bit._064_MAC, FieldDescriptor.AsciiFixed(16, FieldValidators.Hex) }, { Bit._066_ORIGINAL_FEES_AMOUNTS, FieldDescriptor.AsciiVar(3, 204, FieldValidators.Ans) }, { Bit._067_EXT_PAYMENT_DATA, FieldDescriptor.AsciiFixed(2, FieldValidators.N) }, { Bit._071_MSG_NR, FieldDescriptor.AsciiFixed(8, FieldValidators.N) }, { Bit._072_DATA_RECORD, FieldDescriptor.AsciiVar(3, 999, FieldValidators.Ans) }, { Bit._074_NR_CREDITS, FieldDescriptor.AsciiFixed(10, FieldValidators.N) }, { Bit._075_NR_CREDITS_REVERSAL, FieldDescriptor.AsciiFixed(10, FieldValidators.N) }, { Bit._076_NR_DEBITS, FieldDescriptor.AsciiFixed(10, FieldValidators.N) }, { Bit._077_NR_DEBITS_REVERSAL, FieldDescriptor.AsciiFixed(10, FieldValidators.N) }, { Bit._081_NR_AUTHS, FieldDescriptor.AsciiFixed(10, FieldValidators.N) }, { Bit._086_AMOUNT_CREDITS, FieldDescriptor.AsciiFixed(16, FieldValidators.N) }, { Bit._087_AMOUNT_CREDITS_REVERSAL, FieldDescriptor.AsciiFixed(16, FieldValidators.N) }, { Bit._088_AMOUNT_DEBITS, FieldDescriptor.AsciiFixed(16, FieldValidators.N) }, { Bit._089_AMOUNT_DEBITS_REVERSAL, FieldDescriptor.AsciiFixed(16, FieldValidators.N) }, { Bit._090_NR_AUTHS_REVERSAL, FieldDescriptor.AsciiFixed(10, FieldValidators.N) }, { Bit._096_KEY_MANAGEMENT_DATA, FieldDescriptor.AsciiVar(3, 999, FieldValidators.Ans) }, { Bit._097_AMOUNT_NET_RECON, FieldDescriptor.AsciiFixed(17, FieldValidators.An) }, { Bit._098_PAYEE, FieldDescriptor.AsciiFixed(25, FieldValidators.Ans) }, { Bit._100_RECEIVING_INST_ID_CODE, FieldDescriptor.AsciiVar(2, 11, FieldValidators.N) }, { Bit._101_FILE_NAME, FieldDescriptor.AsciiVar(2, 99, FieldValidators.Ans) }, { Bit._102_ACCOUNT_ID_1, FieldDescriptor.AsciiVar(2, 28, FieldValidators.Ans) }, { Bit._103_ACCOUNT_ID_2, FieldDescriptor.AsciiVar(2, 28, FieldValidators.Ans) }, { Bit._104_TRAN_DESCRIPTION, FieldDescriptor.AsciiVar(4, 9999, FieldValidators.Ans) }, { Bit._109_FEE_AMOUNTS_CREDITS, FieldDescriptor.AsciiVar(2, 84, FieldValidators.Ans) }, { Bit._110_FEE_AMOUNTS_DEBITS, FieldDescriptor.AsciiVar(2, 84, FieldValidators.Ans) }, { Bit._123_RECEIPT_DATA, FieldDescriptor.AsciiVar(3, 999, FieldValidators.Ans) }, { Bit._124_DISPLAY_DATA, FieldDescriptor.AsciiVar(3, 999, FieldValidators.Ans) }, { Bit._128_MAC, FieldDescriptor.AsciiFixed(16, FieldValidators.Hex) }, }; asciiTemplate.BitmapFormatter = Formatters.Ascii; }
private bool IsTrait(FieldDescriptor f, out string traitID, out string catID, out string tableName) { return(IsOneToMany("trait", f, out traitID, out catID, out tableName)); }
private void GenerateSerializeOneField(TextGenerator writer, FieldDescriptor fieldDescriptor) { SourceGenerators.CreateFieldGenerator(fieldDescriptor).GenerateSerializationCode(writer); }
public abstract int GetRepeatedFieldCount(FieldDescriptor field);
public abstract TBuilder ClearField(FieldDescriptor field);
public abstract TBuilder AddRepeatedField(FieldDescriptor field, object value);
public abstract IBuilder CreateBuilderForField(FieldDescriptor field);
public abstract bool HasField(FieldDescriptor field);
public abstract object this[FieldDescriptor field, int index] { get; set; }
private bool IsNote(FieldDescriptor f, out string noteID, out string catID, out string tableName) { return(IsOneToMany("note", f, out noteID, out catID, out tableName)); }
IBuilder IBuilder.WeakClearField(FieldDescriptor field) { return(ClearField(field)); }
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) { if (properties == null) { List <PropertyDescriptor> props = new List <PropertyDescriptor>(); Type type = value.GetType(); FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); for (int i = 0; i < fields.Length; i++) { List <Attribute> attrs = new List <Attribute>(); attrs.AddRange(fields[i].FieldType.GetCustomAttributes(true) as Attribute[] ?? new Attribute[0]); foreach (Attribute item in fields[i].GetCustomAttributes(true)) { int index = attrs.IndexOf(item); if (index >= 0) { attrs.RemoveAt(index); } attrs.Add(item); } var fd = new FieldDescriptor(fields[i], attrs.ToArray()); if (fd.IsBrowsable) { props.Add(fd); } } foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(value, attributes)) { if (prop.IsBrowsable) { PropertyDescriptor pd = prop; for (int i = 0; i < prop.Attributes.Count; i++) { if (prop.Attributes[i] is IPDProvider) { pd = ((IPDProvider)prop.Attributes[i]).CreateProperty(value, pd, attributes); } } //if (prop.Attributes.Contains(DeferredAttribute.Yes)) // pd = new DeferredPropertyDescriptors(pd, LockFunction); //if (prop.Attributes.Contains(LockOnSetAttribute.Yes)) // pd = new LockeablePropertyDescriptors(pd, LockFunction); //if (prop.Attributes.Contains(UIEditableAttribute.Yes)) // pd = new EditablePropertyDescriptor(pd, ReadOnlyAttribute.No); //if (prop.Attributes.Contains(DynamicEditableAttribute.Yes)) //{ // object instance = prop.GetValue(value); // if (instance != null) // { // EditorAttribute attr = instance.GetType().GetCustomAttribute<EditorAttribute>(true); // if (attr != null) // { // pd = TypeDescriptor.CreateProperty(type, pd, attr); // } // } // else // { // pd = TypeDescriptor.CreateProperty(type, pd, new EditorAttribute(typeof(UICreatorEditor),typeof(UITypeEditor))); // } //} //if (prop.Attributes.OfType<PropertyDescriptorAttribute>().Count() > 0) //{ // var attr = prop.Attributes.OfType<PropertyDescriptorAttribute>().First(); // pd = (PropertyDescriptor)Activator.CreateInstance(attr.DescriptorType, pd); //} props.Add(pd); } } properties = new PropertyDescriptorCollection(props.ToArray()); } return(properties); }
public abstract object this[FieldDescriptor field] { get; set; }
/// <summary> /// Verifies that the given object is of the correct type to be a valid /// value for the given field. /// </summary> /// <remarks> /// For repeated fields, this checks if the object is of the right /// element type, not whether it's a list. /// </remarks> /// <exception cref="ArgumentException">The value is not of the right type.</exception> /// <exception cref="ArgumentNullException">The value is null.</exception> private static void VerifyType(IFieldDescriptorLite field, object value) { ThrowHelper.ThrowIfNull(value, "value"); bool isValid = false; switch (field.MappedType) { case MappedType.Int32: isValid = value is int; break; case MappedType.Int64: isValid = value is long; break; case MappedType.UInt32: isValid = value is uint; break; case MappedType.UInt64: isValid = value is ulong; break; case MappedType.Single: isValid = value is float; break; case MappedType.Double: isValid = value is double; break; case MappedType.Boolean: isValid = value is bool; break; case MappedType.String: isValid = value is string; break; case MappedType.ByteString: isValid = value is ByteString; break; case MappedType.Enum: IEnumLite enumValue = value as IEnumLite; isValid = enumValue != null && field.EnumType.IsValidValue(enumValue); break; case MappedType.Message: IMessageLite messageValue = value as IMessageLite; isValid = messageValue != null; #if !LITE if (isValid && messageValue is IMessage && field is FieldDescriptor) { isValid = ((IMessage)messageValue).DescriptorForType == ((FieldDescriptor)field).MessageType; } #endif break; } if (!isValid) { // When chaining calls to SetField(), it can be hard to tell from // the stack trace which exact call failed, since the whole chain is // considered one line of code. So, let's make sure to include the // field name and other useful info in the exception. string message = "Wrong object type used with protocol message reflection."; #if !LITE FieldDescriptor fieldinfo = field as FieldDescriptor; if (fieldinfo != null) { message += "Message type \"" + fieldinfo.ContainingType.FullName; message += "\", field \"" + (fieldinfo.IsExtension ? fieldinfo.FullName : fieldinfo.Name); message += "\", value was type \"" + value.GetType().Name + "\"."; } #endif throw new ArgumentException(message); } }
public void TestBasicGenerics()//ported from simplTranslators/test ecologylab.translators.java.generics.JavaTranslatorGenericTest.java { SimplTypesScope.EnableGraphSerialization(); //My SimplTypesScope s = SimplTypesScope.Get("test_basic_generics", typeof(My <>)); FieldInfo f = typeof(My <>).GetField("v"); Type t1 = f.FieldType; Console.Out.WriteLine(t1); f = typeof(My <>).GetField("n"); Type t2 = f.FieldType; Console.Out.WriteLine(t2); ClassDescriptor cd; s.EntriesByClassSimpleName.TryGetValue("My", out cd); FieldDescriptor fd = cd.GetFieldDescriptorByFieldName("v"); //Search SimplTypesScope scope = SimplTypesScope.Get("test-basic-generics", typeof(SearchResult), typeof(Search <>), typeof(SocialSearchResult), typeof(SocialSearch)); ClassDescriptor cdSearch; scope.EntriesByClassSimpleName.TryGetValue("Search", out cdSearch); List <GenericTypeVar> classGenericTypeVars = cdSearch.GetGenericTypeVars(); foreach (GenericTypeVar genericTypeVar in classGenericTypeVars) { Console.Out.WriteLine(genericTypeVar.ToString()); } FieldDescriptor fdSearchResults = cdSearch.GetFieldDescriptorByFieldName("searchResults"); List <GenericTypeVar> fieldGenericTypeVars = fdSearchResults.GetGenericTypeVars(); foreach (GenericTypeVar genericTypeVar in fieldGenericTypeVars) { Console.Out.WriteLine(genericTypeVar.ToString()); } scope.EntriesByClassSimpleName.TryGetValue("SocialSearch", out cdSearch); classGenericTypeVars = cdSearch.GetGenericTypeVars(); foreach (GenericTypeVar genericTypeVar in classGenericTypeVars) { Console.Out.WriteLine(genericTypeVar.ToString()); } fdSearchResults = cdSearch.GetFieldDescriptorByFieldName("searchResults"); fieldGenericTypeVars = fdSearchResults.GetGenericTypeVars(); foreach (GenericTypeVar genericTypeVar in fieldGenericTypeVars) { Console.Out.WriteLine(genericTypeVar.ToString()); } SimplTypesScope.DisableGraphSerialization(); }
public virtual IBuilder SetField(FieldDescriptor field, object value) { this[field] = value; return(ThisBuilder); }
public FieldReference(string name, ClassReference declaringClass, FieldDescriptor descriptor) { _name = new LazyValue <string>(name); _declaringClass = new LazyValue <ClassReference>(declaringClass); _descriptor = new LazyValue <FieldDescriptor>(descriptor); }
internal RepeatedEnumFieldGenerator(FieldDescriptor descriptor, int fieldOrdinal) : base(descriptor, fieldOrdinal) { }
private static String SubMessagePrefix(String prefix, FieldDescriptor field, int index) { StringBuilder result = new StringBuilder(prefix); if (field.IsExtension) { result.Append('(') .Append(field.FullName) .Append(')'); } else { result.Append(field.Name); } if (index != -1) { result.Append('[') .Append(index) .Append(']'); } result.Append('.'); return result.ToString(); }
private static Dictionary<string, FieldDescriptor> GetFieldsForDataTable( DataTable dataTable ) { DataColumnCollection columns = dataTable.Columns; int fieldCount = columns.Count; Dictionary<string, FieldDescriptor> fieldDescriptors = new Dictionary<string, FieldDescriptor>( fieldCount ); Dictionary<string, ForeignKeyConstraint> foreignKeyConstraints = ItemsSourceHelper.GetForeignKeyConstraints( dataTable.Constraints ); for( int i = 0; i < fieldCount; i++ ) { DataColumn column = columns[ i ]; string name = column.Caption; ForeignKeyConstraint foreignKeyConstraint = null; foreignKeyConstraints.TryGetValue( name, out foreignKeyConstraint ); DataTableForeignKeyDescription foreignKeyDescription = ItemsSourceHelper.GetDataGridForeignKeyDescriptionForForeignKeyConstraint( foreignKeyConstraint ); fieldDescriptors[ name ] = new FieldDescriptor( name, name, column.DataType, null, null, "[" + name + "]", column.ReadOnly, false, column.AllowDBNull, true, false, false, foreignKeyDescription ); } return fieldDescriptors; }
public virtual IBuilder SetRepeatedField(FieldDescriptor field, int index, object value) { this[field, index] = value; return(ThisBuilder); }
private static Dictionary<string, FieldDescriptor> GetFieldsForEntityFramework( Type itemType ) { PropertyDescriptorCollection propertyDescriptors = TypeDescriptor.GetProperties( itemType ); Dictionary<string, FieldDescriptor> fieldDescriptors = new Dictionary<string, FieldDescriptor>( propertyDescriptors.Count ); foreach( PropertyDescriptor propertyDescriptor in propertyDescriptors ) { bool isEntityKey = false; bool allowNull = false; EdmScalarPropertyAttribute attribute = propertyDescriptor.Attributes[ typeof( EdmScalarPropertyAttribute ) ] as EdmScalarPropertyAttribute; if( attribute != null ) { isEntityKey = attribute.EntityKeyProperty; allowNull = attribute.IsNullable; } string name = propertyDescriptor.Name; fieldDescriptors[ name ] = new FieldDescriptor( name, propertyDescriptor.DisplayName, propertyDescriptor.PropertyType, propertyDescriptor, null, name, ( propertyDescriptor.IsReadOnly || isEntityKey ), // A column must be read-only if it's an EntityKey (except for the InsertionRow) ( !propertyDescriptor.IsReadOnly && isEntityKey ), allowNull, propertyDescriptor.IsBrowsable, ItemsSourceHelper.IsASubRelationship( propertyDescriptor.PropertyType ), false, null ); } return fieldDescriptors; }
public static Column CreateColumnFromItemsSourceField( DataGridControl dataGridControl, IDictionary<Type, CellEditor> defaultCellEditors, FieldDescriptor field, bool autoCreateForeignKeyConfigurations ) { if( ( field.IsASubRelationship ) || ( !field.Browsable ) ) return null; string fieldName = field.Name; Type dataType = field.DataType; Column dataColumn = new Column(); dataColumn.IsAutoCreated = true; dataColumn.FieldName = fieldName; bool readOnly = field.ReadOnly; bool overrideReadOnlyForInsertion = field.OverrideReadOnlyForInsertion; // We only set ReadOnly when the value is true in order for the inheritence chain to work. // Otherwise, the column value is always used instead of the row or grid value. if( readOnly ) dataColumn.ReadOnly = readOnly; dataColumn.OverrideReadOnlyForInsertion = overrideReadOnlyForInsertion; dataColumn.Title = field.DisplayName; // Disable warning for DisplayMemberBinding when internaly used #pragma warning disable 618 dataColumn.DisplayMemberBinding = ItemsSourceHelper.CreateDefaultBinding( false, field.Name, field, false, ( readOnly && !overrideReadOnlyForInsertion ), dataType ); #pragma warning restore 618 //mark the Column's Binding as AutoCreated. dataColumn.IsBindingAutoCreated = true; dataColumn.IsBoundToDataGridUnboundItemProperty = field.IsDataGridUnboundItemProperty; CellEditor cellEditor = null; if( defaultCellEditors != null ) { defaultCellEditors.TryGetValue( dataType, out cellEditor ); } if( ( field.ForeignKeyDescription != null ) && ( field.ForeignKeyDescription.ItemsSource != null ) && ( autoCreateForeignKeyConfigurations ) ) { // We will only use the default foreign key CellEditor // if: // - a ForeignKey ItemsSource was detected // - the grid allows the auto-creation of the ForeignKeyConfigurations // else, use the default CellEditor if( cellEditor == null ) { cellEditor = DefaultCellEditorSelector.ForeignKeyCellEditor; } // Update the ForeignKeyConfiguration from the ForeignKeyDescription // found on the FieldDescriptor ForeignKeyConfiguration.SynchronizeForeignKeyConfigurationFromForeignKeyDescription( dataColumn, field.ForeignKeyDescription, autoCreateForeignKeyConfigurations ); } if( cellEditor == null ) { cellEditor = DefaultCellEditorSelector.SelectCellEditor( dataType ); } dataColumn.CellEditor = cellEditor; return dataColumn; }
public ManualTotalSummary(Group g, FieldDescriptor field) { this.Field = field; this.Group = g; }
public static IEnumerable <Field> LoadResourceReference(MessageDescriptor msgDesc, FieldDescriptor fieldDesc, IReadOnlyDictionary <string, Definition> resourcesByUrt, IReadOnlyDictionary <string, IReadOnlyList <Definition> > resourcesByParentComparison, bool required) { // Is this field the name-field of a resource descriptor? var resourceDesc = msgDesc.GetExtension(ResourceExtensions.Resource); if (resourceDesc is object) { var def = resourcesByUrt[resourceDesc.Type]; if (fieldDesc.Name == def.NameField) { if (def.HasNotWildcard) { yield return(new Field(fieldDesc, def)); } if (def.HasWildcard) { yield return(new Field(fieldDesc, Definition.WildcardResource, def.HasNotWildcard ? new[] { def } : null)); } yield break; } } // Is this field a resource reference? var resourceRef = fieldDesc.GetExtension(ResourceExtensions.ResourceReference); if (resourceRef is object) { // Resource references must be string fields, or StringValue (well-known type) fields. // It's a relatively common error to put the annotation on a message field instead, which // will otherwise generate invalid code - better to fail generation. if (fieldDesc.FieldType != FieldType.String && !(fieldDesc.FieldType == FieldType.Message && fieldDesc.MessageType.FullName == StringValue.Descriptor.FullName)) { throw new InvalidOperationException($"Field {msgDesc.Name}.{fieldDesc.Name} has a resource reference annotation, but is not a string or StringValue field."); } if (!string.IsNullOrEmpty(resourceRef.Type)) { if (resourceRef.Type == "*" || resourceRef.Type == "**") { yield return(new Field(fieldDesc, Definition.WildcardResource)); yield break; } if (!resourcesByUrt.TryGetValue(resourceRef.Type, out var def)) { if (required) { throw new InvalidOperationException($"No resource type with name: '{resourceRef.Type}' for field {msgDesc.Name}.{fieldDesc.Name}"); } else { yield break; } } if (def.HasNotWildcard) { yield return(new Field(fieldDesc, def)); } if (def.HasWildcard) { yield return(new Field(fieldDesc, Definition.WildcardResource, def.HasNotWildcard ? new[] { def } : null)); } } else if (!string.IsNullOrEmpty(resourceRef.ChildType)) { if (resourceRef.ChildType == "*" || resourceRef.ChildType == "**") { yield return(new Field(fieldDesc, Definition.WildcardResource)); yield break; } if (!resourcesByUrt.TryGetValue(resourceRef.ChildType, out var childDef)) { if (required) { throw new InvalidOperationException($"No resource type with child name: '{resourceRef.ChildType}' for field {msgDesc.Name}.{fieldDesc.Name}"); } else { yield break; } } // Find all resources in which the patterns are a subset of the child patterns; a wildcard matches a child wildcard. // Verify that these resources together match all parent patterns of the child resource. // Order by most-specific-parent first, then by order in child-type patterns (then alphabetically as a last resort, to keep it deterministic). var parentPatterns = childDef.Patterns.Select(x => x.IsWildcard ? "*" : x.Template.Parent().ParentComparisonString).ToImmutableList(); var parentPatternsSet = parentPatterns.ToImmutableHashSet(); var parentDefs = parentPatterns .SelectMany(x => resourcesByParentComparison.TryGetValue(x, out var defs) ? defs : Enumerable.Empty <Definition>()) .Where(def => def.Patterns.All(x => parentPatternsSet.Contains(x.Template.ParentComparisonString))) .Distinct(Definition.TypeComparer.Instance) .OrderBy(def => def.Patterns.Count) .ThenBy(def => def.Patterns.Select(x => parentPatterns.IndexOf(x.Template.ParentComparisonString)).Where(x => x >= 0).Min()) .ThenBy(def => def.UnifiedResourceTypeName) .ToImmutableList(); // "*" pattern is not required to be matched; all others are required. if (parentPatternsSet.Except(parentDefs.SelectMany(x => x.Patterns).Select(x => x.Template.ParentComparisonString).Append("*")).Any()) { throw new InvalidOperationException($"Not all patterns can be matched to a parent resource for field {msgDesc.Name}.{fieldDesc.Name}"); } foreach (var parentDef in parentDefs) { yield return(new Field(fieldDesc, parentDef)); } if (parentDefs.Any(x => x.HasWildcard) || childDef.IsWildcardOnly || parentDefs.Count > 1) { yield return(new Field(fieldDesc, Definition.WildcardResource, parentDefs.Count > 1 ? parentDefs : null, parentPatternsSet.Contains("*"))); } } else { throw new InvalidOperationException("type or child_type must be set."); } } }
private static Dictionary<string, FieldDescriptor> GetFieldsForDataView( DataView dataView ) { PropertyDescriptorCollection itemProperties = ( ( ITypedList )dataView ).GetItemProperties( null ); int fieldCount = itemProperties.Count; Dictionary<string, FieldDescriptor> fieldDescriptors = new Dictionary<string, FieldDescriptor>( fieldCount ); Dictionary<string, ForeignKeyConstraint> foreignKeyConstraints = ItemsSourceHelper.GetForeignKeyConstraints( dataView.Table.Constraints ); DataColumnCollection columns = dataView.Table.Columns; for( int i = 0; i < fieldCount; i++ ) { PropertyDescriptor propertyDescriptor = itemProperties[ i ]; string name = propertyDescriptor.Name; DataColumn column = columns[ name ]; string displayName = ( column == null ) ? propertyDescriptor.DisplayName : column.Caption; bool allowBDNull = ( column == null ) ? false : column.AllowDBNull; ForeignKeyConstraint foreignKeyConstraint = null; foreignKeyConstraints.TryGetValue( name, out foreignKeyConstraint ); DataTableForeignKeyDescription foreignKeyDescription = ItemsSourceHelper.GetDataGridForeignKeyDescriptionForForeignKeyConstraint( foreignKeyConstraint ); fieldDescriptors[ name ] = new FieldDescriptor( name, displayName, propertyDescriptor.PropertyType, propertyDescriptor, null, name, propertyDescriptor.IsReadOnly, false, allowBDNull, propertyDescriptor.IsBrowsable, ( column == null ) && ItemsSourceHelper.IsASubRelationship( propertyDescriptor.PropertyType ), false, foreignKeyDescription ); Debug.Assert( ( column != null ) || ( ItemsSourceHelper.IsASubRelationship( propertyDescriptor.PropertyType ) ), "If we don't have a column that corresponds to the property of a DataRowView, it is safe to assume that we have a sub relation." ); } return fieldDescriptors; }
public void BaseTypeTest(BaseTypeValue primitive, string rawDescriptor) { Assert.Equal(new FieldDescriptor(new BaseType(primitive)), FieldDescriptor.FromString(rawDescriptor), Comparer); }
private static Dictionary<string, FieldDescriptor> GetFieldsForJaggedArray( Type itemType, IEnumerable jaggedArray ) { int fieldCount = 0; IEnumerator enumerator = jaggedArray.GetEnumerator(); enumerator.MoveNext(); try { Array arrayItem = enumerator.Current as Array; fieldCount = arrayItem.GetLength( 0 ); } catch { } Dictionary<string, FieldDescriptor> fieldDescriptors = new Dictionary<string, FieldDescriptor>( fieldCount ); Type fieldType = itemType.GetElementType(); for( int i = 0; i < fieldCount; i++ ) { string name = ".[" + i.ToString( CultureInfo.InvariantCulture ) + "]"; DataGridForeignKeyDescription foreignKeyDescription = null; // Try to retreive the ForeignKeyDescription if the field is an Enum if( ( fieldType != null ) && ( fieldType.IsEnum ) ) { foreignKeyDescription = ItemsSourceHelper.GetDataGridForeignKeyDescriptionForEnum( fieldType ); } fieldDescriptors[ name ] = new FieldDescriptor( name, name, fieldType, new JaggedArrayPropertyDescriptor( i, fieldType ), null, null, false, false, false, true, ItemsSourceHelper.IsASubRelationship( fieldType ), false, foreignKeyDescription ); } return fieldDescriptors; }
public void SimpleArrayTest() { Assert.Equal(new FieldDescriptor(new ArrayType(new BaseType(BaseTypeValue.Int))), FieldDescriptor.FromString("[I"), Comparer); }
public static void ExtractFieldDescriptors( string namePrefix, PropertyDescriptorCollection properties, bool supportDBNull, Dictionary<string, FieldDescriptor> fieldDescriptors ) { int propertyCount = properties.Count; for( int i = 0; i < propertyCount; i++ ) { PropertyDescriptor propertyDescriptor = properties[ i ]; string name = propertyDescriptor.Name; if( ( fieldDescriptors.ContainsKey( name ) ) && ( !string.IsNullOrEmpty( namePrefix ) ) ) name = namePrefix + "." + name; Type type = propertyDescriptor.PropertyType; DataGridForeignKeyDescription foreignKeyDescription = null; // Try to retreive the ForeignKeyDescription if the field is an Enum if( ( type != null ) && ( type.IsEnum ) ) { foreignKeyDescription = ItemsSourceHelper.GetDataGridForeignKeyDescriptionForEnum( type ); } fieldDescriptors[ name ] = new FieldDescriptor( name, propertyDescriptor.DisplayName, type, propertyDescriptor, null, null, propertyDescriptor.IsReadOnly, false, supportDBNull, propertyDescriptor.IsBrowsable, ItemsSourceHelper.IsASubRelationship( propertyDescriptor.PropertyType ), false, foreignKeyDescription ); } }
public void ObjectArrayTest() { Assert.Equal(new FieldDescriptor(new ArrayType(new ObjectType("java/lang/Object"))), FieldDescriptor.FromString("[Ljava/lang/Object;"), Comparer); }
public static System.Windows.Data.Binding CreateDefaultBinding( bool dataItemIsDataRow, string fieldName, FieldDescriptor sourceField, bool supportDBNull, bool readOnly, Type dataType ) { DataGridBindingInfo bindingInfo = new DataGridBindingInfo(); PropertyDescriptor propertyDescriptor = null; string bindingPath = null; string bindingXPath = null; if( sourceField != null ) { dataType = sourceField.DataType; supportDBNull = sourceField.SupportDBNull; readOnly |= ( sourceField.ReadOnly && !sourceField.OverrideReadOnlyForInsertion ); propertyDescriptor = sourceField.PropertyDescriptor; bindingXPath = sourceField.BindingXPath; bindingPath = sourceField.BindingPath; } if( dataItemIsDataRow ) { bindingInfo.Path = new PropertyPath( "Cells[" + fieldName + "].Content" ); } else { // We always use Path and XPath to be able to write back to a binding on self ("."). // Because the "propertyDescriptor" received is readonly, we must use the normal binding path to pass over that. if( !string.IsNullOrEmpty( bindingXPath ) ) { bindingInfo.XPath = bindingXPath; if( !string.IsNullOrEmpty( bindingPath ) ) bindingInfo.Path = new PropertyPath( bindingPath, ItemsSourceHelper.EmptyObjectArray ); } else { bindingInfo.Path = ItemsSourceHelper.CreatePropertyPath( fieldName, bindingPath, propertyDescriptor ); } } bindingInfo.ReadOnly = readOnly; bindingInfo.Converter = new SourceDataConverter( supportDBNull ); bindingInfo.ValidationRules.Add( new SourceDataConverterValidationRule( supportDBNull, dataType ) ); return bindingInfo.GetBinding(); }
public void MethodDescriptorCharacters() { Assert.Throws <FormatException>(() => FieldDescriptor.FromString("()V")); }
/// <summary> /// Returns the wire type for the given field descriptor. This differs /// from GetWireType(FieldType) for packed repeated fields. /// </summary> internal static WireType GetWireType(FieldDescriptor descriptor) { return descriptor.IsPacked ? WireType.LengthDelimited : GetWireType(descriptor.FieldType); }
private static bool TryCoerceType(string text, FieldDescriptor field, out object value, IList <string> tmpReasons) { value = null; switch (field.FieldType) { case FieldType.Int32: case FieldType.SInt32: case FieldType.SFixed32: value = Int32.Parse(text); break; case FieldType.Int64: case FieldType.SInt64: case FieldType.SFixed64: value = Int64.Parse(text); break; case FieldType.UInt32: case FieldType.Fixed32: value = UInt32.Parse(text); break; case FieldType.UInt64: case FieldType.Fixed64: value = UInt64.Parse(text); break; case FieldType.Float: value = float.Parse(text); break; case FieldType.Double: value = Double.Parse(text); break; case FieldType.Bool: value = Boolean.Parse(text); break; case FieldType.String: value = text; break; case FieldType.Enum: { EnumDescriptor enumType = field.EnumType; int number; if (int.TryParse(text, out number)) { value = enumType.FindValueByNumber(number); if (value == null) { tmpReasons.Add( "Enum type \"" + enumType.FullName + "\" has no value with number " + number + "."); return(false); } } else { value = enumType.FindValueByName(text); if (value == null) { tmpReasons.Add( "Enum type \"" + enumType.FullName + "\" has no value named \"" + text + "\"."); return(false); } } break; } case FieldType.Bytes: case FieldType.Message: case FieldType.Group: tmpReasons.Add("Unhandled field type " + field.FieldType.ToString() + "."); return(false); } return(true); }
/// <summary> /// Returns a SysDOM field descriptor for a particular instance /// </summary> /// <param name="inst">instance of class containing the field</param> /// <returns>SysDOM field descriptor</returns> public FieldDescriptor GetDescriptor(object inst) { if (inst == null) { if (_nullInstDesc == null) { _nullInstDesc = new CILFieldDescriptor(Field, null) { IsConstant = !IsWritten && !IsSubMutated }; } return _nullInstDesc; } else { FieldDescriptor result; if (!_descMap.TryGetValue(inst, out result)) { result = new CILFieldDescriptor(Field, inst) { IsConstant = !IsWritten && !IsSubMutated }; _descMap[inst] = result; } return result; } }
private void WriteSingleValue(StringBuilder builder, FieldDescriptor descriptor, object value) { switch (descriptor.FieldType) { case FieldType.Bool: builder.Append((bool)value ? "true" : "false"); break; case FieldType.Bytes: // Nothing in Base64 needs escaping builder.Append('"'); builder.Append(((ByteString)value).ToBase64()); builder.Append('"'); break; case FieldType.String: WriteString(builder, (string)value); break; case FieldType.Fixed32: case FieldType.UInt32: case FieldType.SInt32: case FieldType.Int32: case FieldType.SFixed32: { IFormattable formattable = (IFormattable)value; builder.Append(formattable.ToString("d", CultureInfo.InvariantCulture)); break; } case FieldType.Enum: EnumValueDescriptor enumValue = descriptor.EnumType.FindValueByNumber((int)value); // We will already have validated that this is a known value. WriteString(builder, enumValue.Name); break; case FieldType.Fixed64: case FieldType.UInt64: case FieldType.SFixed64: case FieldType.Int64: case FieldType.SInt64: { builder.Append('"'); IFormattable formattable = (IFormattable)value; builder.Append(formattable.ToString("d", CultureInfo.InvariantCulture)); builder.Append('"'); break; } case FieldType.Double: case FieldType.Float: string text = ((IFormattable)value).ToString("r", CultureInfo.InvariantCulture); if (text == "NaN" || text == "Infinity" || text == "-Infinity") { builder.Append('"'); builder.Append(text); builder.Append('"'); } else { builder.Append(text); } break; case FieldType.Message: case FieldType.Group: // Never expect to get this, but... if (descriptor.MessageType.IsWellKnownType) { WriteWellKnownTypeValue(builder, descriptor.MessageType, value, true); } else { WriteMessage(builder, (IMessage)value); } break; default: throw new ArgumentException("Invalid field type: " + descriptor.FieldType); } }
private static void PrintSingleField(FieldDescriptor field, Object value, TextGenerator generator) { if (field.IsExtension) { generator.Print("["); // We special-case MessageSet elements for compatibility with proto1. if (field.ContainingType.Options.MessageSetWireFormat && field.FieldType == FieldType.Message && field.IsOptional // object equality (TODO(jonskeet): Work out what this comment means!) && field.ExtensionScope == field.MessageType) { generator.Print(field.MessageType.FullName); } else { generator.Print(field.FullName); } generator.Print("]"); } else { if (field.FieldType == FieldType.Group) { // Groups must be serialized with their original capitalization. generator.Print(field.MessageType.Name); } else { generator.Print(field.Name); } } if (field.MappedType == MappedType.Message) { generator.Print(" {\n"); generator.Indent(); } else { generator.Print(": "); } PrintFieldValue(field, value, generator); if (field.MappedType == MappedType.Message) { generator.Outdent(); generator.Print("}"); } generator.Print("\n"); }
private static object?ConvertValue(object?value, FieldDescriptor descriptor) { switch (descriptor.FieldType) { case FieldType.Double: return(Convert.ToDouble(value, CultureInfo.InvariantCulture)); case FieldType.Float: return(Convert.ToSingle(value, CultureInfo.InvariantCulture)); case FieldType.Int64: case FieldType.SInt64: case FieldType.SFixed64: return(Convert.ToInt64(value, CultureInfo.InvariantCulture)); case FieldType.UInt64: case FieldType.Fixed64: return(Convert.ToUInt64(value, CultureInfo.InvariantCulture)); case FieldType.Int32: case FieldType.SInt32: case FieldType.SFixed32: return(Convert.ToInt32(value, CultureInfo.InvariantCulture)); case FieldType.Bool: return(Convert.ToBoolean(value, CultureInfo.InvariantCulture)); case FieldType.String: return(value); case FieldType.Bytes: { if (value is string s) { return(ByteString.FromBase64(s)); } throw new InvalidOperationException("Base64 encoded string required to convert to bytes."); } case FieldType.UInt32: case FieldType.Fixed32: return(Convert.ToUInt32(value, CultureInfo.InvariantCulture)); case FieldType.Enum: { if (value is string s) { var enumValueDescriptor = int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var i) ? descriptor.EnumType.FindValueByNumber(i) : descriptor.EnumType.FindValueByName(s); if (enumValueDescriptor == null) { throw new InvalidOperationException($"Invalid value '{s}' for enum type {descriptor.EnumType.Name}."); } return(enumValueDescriptor.Number); } throw new InvalidOperationException("String required to convert to enum."); } case FieldType.Message: if (IsWrapperType(descriptor.MessageType)) { if (value == null) { return(null); } return(ConvertValue(value, descriptor.MessageType.FindFieldByName("value"))); } break; } throw new InvalidOperationException("Unsupported type: " + descriptor.FieldType); }
private static bool TryCoerceType(string text, FieldDescriptor field, out object value, IList<string> tmpReasons) { value = null; switch (field.FieldType) { case FieldType.Int32: case FieldType.SInt32: case FieldType.SFixed32: value = Int32.Parse(text); break; case FieldType.Int64: case FieldType.SInt64: case FieldType.SFixed64: value = Int64.Parse(text); break; case FieldType.UInt32: case FieldType.Fixed32: value = UInt32.Parse(text); break; case FieldType.UInt64: case FieldType.Fixed64: value = UInt64.Parse(text); break; case FieldType.Float: value = float.Parse(text); break; case FieldType.Double: value = Double.Parse(text); break; case FieldType.Bool: value = Boolean.Parse(text); break; case FieldType.String: value = text; break; case FieldType.Enum: { EnumDescriptor enumType = field.EnumType; int number; if (int.TryParse(text, out number)) { value = enumType.FindValueByNumber(number); if (value == null) { tmpReasons.Add( "Enum type \"" + enumType.FullName + "\" has no value with number " + number + "."); return false; } } else { value = enumType.FindValueByName(text); if (value == null) { tmpReasons.Add( "Enum type \"" + enumType.FullName + "\" has no value named \"" + text + "\"."); return false; } } break; } case FieldType.Bytes: case FieldType.Message: case FieldType.Group: tmpReasons.Add("Unhandled field type " + field.FieldType.ToString() + "."); return false; } return true; }
public FieldCondition(FieldDescriptor field, bool condition) { this.field = field; this.condition = condition; }