public Type LoadTypeFromDescriptor(TypeDescriptor typeDescriptor) { if (typeDescriptor.TypeDescriptors.Count == 0) return LoadTypeFromName(typeDescriptor.Name); var typeParams = typeDescriptor .TypeDescriptors .Select(LoadTypeFromDescriptor) .ToArray(); return LoadTypeFromName(typeDescriptor.Name, typeParams); }
public ContextIValueImpl() { if (TypeManager.IsKnownType(this.GetType())) { _type = TypeManager.GetTypeByFrameworkType(this.GetType()); } else { throw new InvalidOperationException("Type is not defined"); } }
public MethodDescriptor FindMethodImplementation(MethodDescriptor methodDescriptor, TypeDescriptor typeDescriptor) { var roslynMethod = FindMethod(methodDescriptor); if (roslynMethod != null) { var roslynType = RoslynSymbolFactory.GetTypeByName(typeDescriptor.TypeName, this.Compilation); var implementedMethod = Utils.FindMethodImplementation(roslynMethod, roslynType); return new MethodDescriptor(implementedMethod); } // If we cannot resolve the method, we return the same method. return methodDescriptor; }
public IXILMapping TryAllocate(Component host, XILInstr instr, TypeDescriptor[] operandTypes, TypeDescriptor[] resultTypes, IProject proj) { List<IXILMapper> mappers = _mlookup.Get(instr.Name); foreach (IXILMapper mapper in mappers) { IXILMapping mapping = mapper.TryAllocate(host, instr, operandTypes, resultTypes, proj); if (mapping != null) { return mapping; } } return null; }
internal static string GetName(this MemberInfo @this, Assembly containingAssembly, bool isDeclaration) { var methodName = string.Empty; if(!isDeclaration) { methodName += new TypeDescriptor( @this.DeclaringType, containingAssembly, @this.DeclaringType.IsGenericType).Value + "::"; } return methodName + @this.Name; }
/// <summary> /// Initialize a new instance of <see cref="PropertyDescriptor"/>. /// </summary> /// <param name="propertyInfo">The <see cref="PropertyInfo"/> to wrap.</param> /// <param name="typeDescriptor">The <see cref="Reflection.TypeDescriptor"/> this <see cref="PropertyDescriptor"/> belongs to.</param> /// <param name="getMethodInfo">The get <see cref="MethodInfo"/> for the <see cref="PropertyInfo"/> being wrapped.</param> /// <exception cref="NullReferenceException"><paramref name="propertyInfo"/> is null.</exception> internal PropertyDescriptor(TypeDescriptor typeDescriptor, PropertyInfo propertyInfo, MethodInfo getMethodInfo) : base(getMethodInfo.ReturnType, propertyInfo.Name) { if (propertyInfo.PropertyType.IsGenericParameter) { throw new ArgumentException("propertyInfo cannot be a genetic type.", "propertyInfo"); } TypeDescriptor = typeDescriptor; IsStatic = getMethodInfo.IsStatic; IsVirtual = getMethodInfo.IsVirtual; #if(WindowsCE || SILVERLIGHT) this.getMethodInfo = getMethodInfo; #else invoker = MethodInvokerCreator.GetMethodInvoker(getMethodInfo); #endif AddRulesForPropertyInfo(propertyInfo); }
public StandartTypeManager() { foreach (var item in Enum.GetValues(typeof(DataType))) { DataType typeEnum = (DataType)item; string alias; switch (typeEnum) { case DataType.Undefined: alias = "Неопределено"; break; case DataType.Boolean: alias = "Булево"; break; case DataType.String: alias = "Строка"; break; case DataType.Date: alias = "Дата"; break; case DataType.Number: alias = "Число"; break; case DataType.Type: alias = "Тип"; break; case DataType.Object: alias = "Object"; break; default: continue; } var td = new TypeDescriptor() { Name = alias, ID = (int)typeEnum }; RegisterType(td, typeof(DataType)); } RegisterType("Null", typeof(NullValueImpl)); }
public void ToTypedKeyValue_WhenJsonWithDataTypes_DictionaryGetsTypedValues() { const string json = "{\"Name\":\"Daniel\",\"Age\":31,\"Item\":{\"Int1\":42,\"DateTime1\":\"\\/Date(-3600000+0000)\\/\"}}"; var typeDescriptor = new TypeDescriptor { {"Name", typeof (string)}, {"Age", typeof (int)}, {"Item", typeof (Item)}, }; var kv = _jsonSerializer.ToTypedKeyValueOrNull(typeDescriptor, json); var expectedKv = new Dictionary<string, object> { {"Name", "Daniel"},{"Age", 31}, {"Item", new Item{Int1 = 42, DateTime1 = new DateTime(1970,01,01)}} }; CustomAssert.KeyValueEquality(expectedKv, kv); }
public bool SentAll(IEnumerable<IDistributedEventAggregator> eventAggregators, byte[] messageContent, TypeDescriptor descriptor) { Logger = LogManager.GetLogger(NomadConstants.NOMAD_LOGGER_REPOSITORY, typeof (BasicTopicDeliverySubsystem)); foreach (IDistributedEventAggregator dea in eventAggregators) { try { dea.OnPublish(messageContent, descriptor); } catch (Exception e) { Logger.Warn(string.Format("Could not sent message '{0}' to DEA: {1}", descriptor, dea), e); } } // using the reliable mechanisms of WCF devlivery is always succesfull to all proper processes return true; }
/// <summary> /// Internalizes a type descriptor. /// </summary> /// <param name="td">a type descriptor</param> /// <returns>equivalent type descriptor which is contained inside the library</returns> public TypeDescriptor Canonicalize(TypeDescriptor td) { TypeDescriptor tdOut; if (_types.TryGetValue(td, out tdOut)) { return tdOut; } else { td = td.Clone(); _types[td] = td; if (!td.HasIntrinsicTypeOverride) { PackageDescriptor pd = GetPackage(td.CILType); td.Package = pd; pd.AddChild(td, td.Name); } return td; } }
/// <summary> /// Initialize a new instance of <see cref="FieldDescriptor"/>. /// </summary> /// <param name="fieldInfo">The <see cref="FieldInfo"/> to wrap.</param> /// <param name="typeDescriptor">The <see cref="Reflection.TypeDescriptor"/> this <see cref="FieldDescriptor"/> belongs to.</param> /// <exception cref="NullReferenceException"><paramref name="fieldInfo"/> is null.</exception> internal FieldDescriptor(TypeDescriptor typeDescriptor, FieldInfo fieldInfo) : base(fieldInfo.FieldType, fieldInfo.Name) { if (fieldInfo.FieldType.IsGenericParameter) { throw new ArgumentException("fieldInfo cannot be a genetic type.", "fieldInfo"); } //TODO: Use Dynamic method instead this.fieldInfo = fieldInfo; TypeDescriptor = typeDescriptor; IsStatic = fieldInfo.IsStatic; // invoker = MethodInvokerCreator.GetFieldGetInvoker(Type.GetTypeFromHandle(typeDescriptor.RuntimeTypeHandle), fieldInfo); var attributes = (IRuleAttribute[])fieldInfo.GetCustomAttributes(RuleAttributeType, true); for (var index = 0; index < attributes.Length; index++) { var fieldRuleAttribute = attributes[index]; //Make sure each attribute is "aware" of the fieldInfo it's validating var rule = fieldRuleAttribute.CreateRule(this); Rules.Add(rule); } }
internal static void UnPackData(TypeDescriptor typeDescriptor, byte[] byteStream, out object sendObject, out Type type) { type = Type.GetType(typeDescriptor.QualifiedName); if (type != null) { var nomadVersion = new Version(type.Assembly.GetName().Version); if (!nomadVersion.Equals(typeDescriptor.Version)) { throw new InvalidCastException("The version of the assembly does not match"); } } // try deserializing object sendObject = Deserialize(byteStream); // check if o is assignable if (type != null && !type.IsInstanceOfType(sendObject)) { throw new InvalidCastException("The sent object cannot be casted to sent type"); } }
public IDictionary<string, object> ToTypedKeyValueOrNull(TypeDescriptor typeDescriptor, string json) { if (string.IsNullOrWhiteSpace(json)) return null; var kvRepresentation = Serializer.Deserialize<IDictionary<string, dynamic>>(json); if (kvRepresentation == null || kvRepresentation.Count < 1) return null; foreach (var key in kvRepresentation.Keys.ToArray()) { var membername = key; var member = typeDescriptor.Get(membername); if (member == null) continue; kvRepresentation[membername] = JsonSerializer.DeserializeFromString(kvRepresentation[membername], member.Type); } return kvRepresentation; }
public String GetClassName() { return(TypeDescriptor.GetClassName(this, true)); }
public String GetComponentName() { return(TypeDescriptor.GetComponentName(this, true)); }
public EventDescriptorCollection GetEvents(Attribute[] attributes) { return(TypeDescriptor.GetEvents(this, attributes, true)); }
public FieldsToPropertiesTypeDescriptionProvider(Type t) { _baseProvider = TypeDescriptor.GetProvider(t); }
public PropertyDescriptor GetDefaultProperty() { return(TypeDescriptor.GetDefaultProperty(this, true)); }
public static void GetTypeBuilderDescription() { using (var assembly = AssemblyCreationTests.CreateDebuggingAssembly("TypeBuilderDescriptor")) { using (var type = AssemblyCreationTests.CreateDebuggingType( assembly, assembly.Builder.GetDynamicModule(assembly.Builder.GetName().Name), "Holder")) { var descriptor = new TypeDescriptor(type.Builder); Assert.Equal("class TypeBuilderDescriptor.Holder", descriptor.Value); } } }
public override void Exit(TypeDescriptor node) { level--; }
private string GetTypeString(TypeDescriptor td) { if (td.CILType.Equals(typeof(StdLogic))) return "std_logic"; else if (td.CILType.Equals(typeof(StdLogicVector))) return "std_logic_vector(" + td.Constraints[0].FirstBound + " downto " + td.Constraints[0].SecondBound + ")"; else throw new NotSupportedException("Only StdLogic/StdLogicVector supported for user ports"); }
public static void RegisterAliasFor(TypeDescriptor td, string alias) { _instance.RegisterAliasFor(td, alias); }
private static void WriteReport(Histogram[] histogram, string[] timeMarker) { TypeDescriptor[] typeIndexToTypeDescriptor = new TypeDescriptor[histogram[0].readNewLog.typeName.Length]; int[] totalSize = new int[histogram.Length]; int[] totalCount = new int[histogram.Length]; for (int h = 0; h < histogram.Length; h++) { int[] typeSizeStacktraceToCount = histogram[h].typeSizeStacktraceToCount; for (int i = 0; i < typeSizeStacktraceToCount.Length; i++) { int count = typeSizeStacktraceToCount[i]; if (count == 0) continue; int[] stacktrace = histogram[h].readNewLog.stacktraceTable.IndexToStacktrace(i); int typeIndex = stacktrace[0]; int size = stacktrace[1]; if (typeIndexToTypeDescriptor[typeIndex] == null) typeIndexToTypeDescriptor[typeIndex] = new TypeDescriptor(typeIndex, histogram.Length); typeIndexToTypeDescriptor[typeIndex].size[h] += size*count; typeIndexToTypeDescriptor[typeIndex].count[h] += count; totalSize[h] += size*count; totalCount[h] += count; } } ArrayList al = new ArrayList(); for (int i = 0; i < typeIndexToTypeDescriptor.Length; i++) { if (typeIndexToTypeDescriptor[i] == null) continue; al.Add(typeIndexToTypeDescriptor[i]); } al.Sort(); Console.Write("Typename"); for (int h = 0; h < histogram.Length; h++) Console.Write(",Size({0}),#Instances({1})", timeMarker[h], timeMarker[h]); Console.WriteLine(); Console.Write("Grand total"); for (int h = 0; h < histogram.Length; h++) Console.Write(",{0},{1}", totalSize[h], totalCount[h]); Console.WriteLine(); foreach (TypeDescriptor td in al) { Console.Write("{0}", histogram[0].readNewLog.typeName[td.typeIndex]); for (int h = 0; h < histogram.Length; h++) Console.Write(",{0},{1}", td.size[h], td.count[h]); Console.WriteLine(); } }
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { return(TypeDescriptor.GetEvents(this.Target, attributes)); }
public TypeDescriptor RegisterType(string name, Type implementingClass) { if (_knownTypesIndexes.ContainsKey(name)) { var td = GetTypeByName(name); if (GetImplementingClass(td.ID) != implementingClass) throw new InvalidOperationException("Name already registered"); return td; } else { var nextId = _knownTypes.Count; var typeDesc = new TypeDescriptor() { ID = nextId, Name = name }; RegisterType(typeDesc, implementingClass); return typeDesc; } }
EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return(TypeDescriptor.GetEvents(this.Target)); }
public virtual void Exit(TypeDescriptor node) { }
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return(TypeDescriptor.GetProperties(this.Target)); }
public IEnumerable<IXILMapping> TryMap(ITransactionSite taSite, XILInstr instr, TypeDescriptor[] operandTypes, TypeDescriptor[] resultTypes) { IFixedAbsTransactionSite fats = taSite as IFixedAbsTransactionSite; if (fats == null) yield break; if (instr.Name != InstructionCodes.Abs) yield break; var operandFormat = operandTypes[0].GetFixFormat(); if (operandFormat == null) yield break; var resultFormat = resultTypes[0].GetFixFormat(); if (resultFormat == null) yield break; if (operandFormat.FracWidth != resultFormat.FracWidth) yield break; if (operandFormat.TotalWidth != fats.Host.InputWidth) yield break; if (resultFormat.TotalWidth != fats.Host.OutputWidth) yield break; yield return new AbsMapping(fats.Host); }
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { // we'll walk the extenders properties looking for the ones marked as ExtenderControl properties. // for those, we'll make them visible, then add them to the list. // PropertyDescriptorCollection propCollection = TypeDescriptor.GetProperties(this.Target); if (_propsToHide != null && _propsToHide.Length > 0) { List <PropertyDescriptor> props = new List <PropertyDescriptor>(); for (int i = 0; i < propCollection.Count; i++) { PropertyDescriptor prop = propCollection[i]; ScriptControlPropertyAttribute extenderPropAttr = (ScriptControlPropertyAttribute)prop.Attributes[typeof(ScriptControlPropertyAttribute)]; if (extenderPropAttr == null) { continue; } ExtenderVisiblePropertyAttribute evpa = (ExtenderVisiblePropertyAttribute)prop.Attributes[typeof(ExtenderVisiblePropertyAttribute)]; if (evpa == null || !evpa.Value) { // if there isn't an ExtenderVisiblePropertyAttribute on here (the designer adds this), // then we shouldn't process it. Usually this means the developer marked it as Browsable.False. // continue; } // if the name is in the list, remove browsable from the name. // int index = Array.FindIndex <string>(_propsToHide, delegate(string s) { return(s == prop.Name); } ); if (index != -1) { continue; } // add the drop down if it is selectable. // IDReferencePropertyAttribute controlRefAttr = (IDReferencePropertyAttribute)prop.Attributes[typeof(IDReferencePropertyAttribute)]; Attribute tca = prop.Attributes[typeof(TypeConverterAttribute)]; if (controlRefAttr != null && !controlRefAttr.IsDefaultAttribute()) { Type t = typeof(TypedControlIDConverter <Control>).GetGenericTypeDefinition(); t = t.MakeGenericType(controlRefAttr.ReferencedControlType); tca = new TypeConverterAttribute(t); } prop = TypeDescriptor.CreateProperty(prop.ComponentType, prop, BrowsableAttribute.Yes, tca); // add it to the list. // props.Add(prop); } propCollection = new PropertyDescriptorCollection(props.ToArray()); } return(propCollection); }
public EventDescriptor GetDefaultEvent() { return(TypeDescriptor.GetDefaultEvent(this, true)); }
public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors) { return(TypeDescriptor.GetProperties(typeof(Entry))); }
public object GetEditor(Type editorBaseType) { return(TypeDescriptor.GetEditor(this, editorBaseType, true)); }
public override string ToString() { return(TypeDescriptor.GetProperties(this).Cast <PropertyDescriptor>() .Aggregate("Class[", (current, descriptor) => current + ("{" + descriptor.Name + ": " + descriptor.GetValue(this) + "}")) + "]"); }
public EventDescriptorCollection GetEvents() { return(TypeDescriptor.GetEvents(this, true)); }
internal void RegisterNewExpressionAssignment(VariableNode lhsNode, TypeDescriptor typeDescriptor) { this.StatementProcessor.RegisterNewExpressionAssignment(lhsNode, typeDescriptor); }
public string GetName(MemberInfo memberInfo, TypeDescriptor typeDescriptor) { return(this.GetName(memberInfo, this.Name, typeDescriptor)); }
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) { return(TypeDescriptor.GetProperties(typeof(GroupList))); }
public AttributeCollection GetAttributes() { return(TypeDescriptor.GetAttributes(this, true)); }
/// <summary> /// Provisions the specified target object's properties /// from host settings (ie AppSettings) /// with keys match the property's name, or any <see cref="AliasAttribute"/> /// the property has been decorated with. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="target">The target object .</param> /// <param name="prefix">The prefix.</param> /// <returns></returns> public virtual T Provision <T>(T target, string prefix = null) where T : class { var objectName = target.GetType().Name; // Iterate over the public properties of the target object // using the property's name, o foreach (var propertyInfo in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase)) { var hostKey = propertyInfo.Name; // Determine if we should look for this value here: var sourceAttribute = propertyInfo.GetCustomAttribute <ConfigurationSettingSource>(); if (sourceAttribute?.Source == ConfigurationSettingSource.SourceType.KeyVault) { continue; } // The setting is either not decorated with ConfigurationSettingsSourceAttribute // or it's fine, as it is either marked All, AppSetttings, or AppSettingsViaDeploymentPipeline // Use aliases first, as they can be richer, if there are any: var aliasAttribute = propertyInfo.GetCustomAttribute <AliasAttribute>(); if (aliasAttribute != null) { hostKey = aliasAttribute.DisplayName; } // Falling back to the property's name if (string.IsNullOrEmpty(hostKey)) { hostKey = propertyInfo.Name; } // If given a prefix as an argument // see if there is a property with the prefix: var set = false; string s = null; if (!string.IsNullOrEmpty(prefix)) { var tmp = prefix + hostKey; if (DoesKeyExist(tmp)) { s = GetAppSetting(tmp); set = true; } } // If not set/not found, work with just the key // without prefix: if (!set) { var tmp = hostKey; if (DoesKeyExist(tmp)) { s = GetAppSetting(tmp); } } // Set the typed value from th string // to the target property: if (s == null) { continue; } var typeConverter = TypeDescriptor.GetConverter(propertyInfo.PropertyType); var typedValue = typeConverter .ConvertFromString( s); propertyInfo.SetValue(target, typedValue); }//~ iterate to the next property return(target); }
public TypeConverter GetConverter() { return(TypeDescriptor.GetConverter(this, true)); }
public NameProperties(object paramNamed) { // list = Reflection.ReflectionUtils.GetProperties(paramNamed); list = TypeDescriptor.GetProperties(paramNamed); }
public static void GetGenericTypeBuilderDescription() { using (var assembly = AssemblyCreationTests.CreateDebuggingAssembly("GenericTypeBuilderDescriptor")) { using (var type = AssemblyCreationTests.CreateDebuggingType( assembly, assembly.Builder.GetDynamicModule(assembly.Builder.GetName().Name), "Holder")) { type.Builder.DefineGenericParameters("T", "U", "V"); var descriptor = new TypeDescriptor(type.Builder); Assert.Equal("class GenericTypeBuilderDescriptor.Holder`3<T, U, V>", descriptor.Value); } } }
public bool CanSupport(Type type) { var typeConverter = TypeDescriptor.GetConverter(type); return(typeConverter.CanConvertFrom(typeof(string))); }
/// <summary> /// Added by Sonal: /// Writes Difference between two heap dumps /// </summary> /// <param name="histogram"></param> /// <param name="timeMarker"></param> private static void WriteDiffReport(Histogram[] histogram, string[] timeMarker, ReadLogResult entireLogResult) { TypeDescriptor[] typeIndexToTypeDescriptor = new TypeDescriptor[histogram[0].readNewLog.typeName.Length]; int[] totalSize = new int[histogram.Length]; int[] totalCount = new int[histogram.Length]; for (int h = 0; h < histogram.Length; h++) { int[] typeSizeStacktraceToCount = histogram[h].typeSizeStacktraceToCount; for (int i = 0; i < typeSizeStacktraceToCount.Length; i++) { int count = typeSizeStacktraceToCount[i]; if (count == 0) continue; int[] stacktrace = histogram[h].readNewLog.stacktraceTable.IndexToStacktrace(i); int typeIndex = stacktrace[0]; int size = stacktrace[1]; if (typeIndexToTypeDescriptor[typeIndex] == null) typeIndexToTypeDescriptor[typeIndex] = new TypeDescriptor(typeIndex, histogram.Length); typeIndexToTypeDescriptor[typeIndex].size[h] += size * count; typeIndexToTypeDescriptor[typeIndex].count[h] += count; totalSize[h] += size * count; totalCount[h] += count; } } ArrayList al = new ArrayList(); for (int i = 0; i < typeIndexToTypeDescriptor.Length; i++) { if (typeIndexToTypeDescriptor[i] == null) continue; al.Add(typeIndexToTypeDescriptor[i]); } al.Sort(); Console.WriteLine("<?xml version=\"1.0\"?>"); Console.WriteLine("<DetailedLeakReport>"); Console.WriteLine("<LeakSummary>"); int counter = 0; foreach (TypeDescriptor td in al) { int diffCount = td.count[histogram.Length - 1] - td.count[0]; int diffSize = td.size[histogram.Length - 1] - td.size[0]; if (diffCount > 0) { counter++; Console.WriteLine("<Object>"); Console.WriteLine("<Counter>{0}</Counter>", counter); Console.WriteLine("<ObjectName><!--{0}--></ObjectName>", histogram[0].readNewLog.typeName[td.typeIndex]); for (int h = 0; h < histogram.Length; h++) { Console.WriteLine("<CheckPoint{0}>", h + 1); Console.WriteLine("<Instances>{0}</Instances>", td.count[h]); Console.WriteLine("<Size>{0}</Size>", td.size[h]); Console.WriteLine("</CheckPoint{0}>", h + 1); } Console.WriteLine("<Difference>"); Console.WriteLine("<Instances>{0}</Instances>", diffCount); Console.WriteLine("<Size>{0}</Size>", diffSize); Console.WriteLine("</Difference>"); Console.WriteLine("</Object>"); } } Console.WriteLine("</LeakSummary>"); Console.WriteLine("<LeakDetails>"); counter = 0; foreach (TypeDescriptor td in al) { int diffCount = td.count[histogram.Length - 1] - td.count[0]; int diffSize = td.size[histogram.Length - 1] - td.size[0]; if (diffCount > 0) { counter++; Console.WriteLine("<LeakedObject>"); Console.WriteLine("<Summary>"); Console.WriteLine("<Counter>{0}</Counter>", counter); Console.WriteLine("<ObjectName><!--{0}--></ObjectName>", histogram[0].readNewLog.typeName[td.typeIndex]); for (int h = 0; h < histogram.Length; h++) { Console.WriteLine("<CheckPoint{0}>", h + 1); Console.WriteLine("<Instances>{0}</Instances>", td.count[h]); Console.WriteLine("<Size>{0}</Size>", td.size[h]); Console.WriteLine("</CheckPoint{0}>", h + 1); } Console.WriteLine("<Difference>"); Console.WriteLine("<Instances>{0}</Instances>", diffCount); Console.WriteLine("<Size>{0}</Size>", diffSize); if (entireLogResult.requestedObjectGraph != null) entireLogResult.requestedObjectGraph.WriteVertexPaths(histogram[0].tickIndex, histogram[histogram.Length - 1].tickIndex, histogram[0].readNewLog.typeName[td.typeIndex]); else if (entireLogResult.objectGraph != null) entireLogResult.objectGraph.WriteVertexPaths(histogram[0].tickIndex, histogram[histogram.Length - 1].tickIndex, histogram[0].readNewLog.typeName[td.typeIndex]); Console.WriteLine("</LeakedObject>"); } } Console.WriteLine("</LeakDetails>"); Console.WriteLine("</DetailedLeakReport>"); }
internal static ElementValue Parse(Stream stream, ClassReaderState readerState) { var elementValue = new ElementValue { Tag = (ElementValueTag)stream.ReadByteFully() }; switch (elementValue.Tag) { case ElementValueTag.Byte: case ElementValueTag.Character: case ElementValueTag.Integer: case ElementValueTag.Short: case ElementValueTag.Boolean: elementValue.ConstValue = readerState.ConstantPool.GetEntry <IntegerEntry>(Binary.BigEndian.ReadUInt16(stream)).Value; break; case ElementValueTag.Double: elementValue.ConstValue = readerState.ConstantPool.GetEntry <DoubleEntry>(Binary.BigEndian.ReadUInt16(stream)).Value; break; case ElementValueTag.Float: elementValue.ConstValue = readerState.ConstantPool.GetEntry <FloatEntry>(Binary.BigEndian.ReadUInt16(stream)).Value; break; case ElementValueTag.Long: elementValue.ConstValue = readerState.ConstantPool.GetEntry <LongEntry>(Binary.BigEndian.ReadUInt16(stream)).Value; break; case ElementValueTag.String: elementValue.ConstValue = readerState.ConstantPool.GetEntry <Utf8Entry>(Binary.BigEndian.ReadUInt16(stream)).String; break; case ElementValueTag.Enum: elementValue.EnumConstValue = new EnumConstValueType { TypeName = TypeDescriptor.Parse(readerState.ConstantPool .GetEntry <Utf8Entry>(Binary.BigEndian.ReadUInt16(stream)).String), ConstName = readerState.ConstantPool.GetEntry <Utf8Entry>(Binary.BigEndian.ReadUInt16(stream)) .String }; break; case ElementValueTag.Class: elementValue.Class = TypeDescriptor.Parse(readerState.ConstantPool .GetEntry <Utf8Entry>(Binary.BigEndian.ReadUInt16(stream)).String, true); break; case ElementValueTag.Annotation: elementValue.AnnotationNode = AnnotationNode.Parse(stream, readerState); break; case ElementValueTag.Array: var arraySize = Binary.BigEndian.ReadUInt16(stream); elementValue.ArrayValue = new List <ElementValue>(arraySize); for (var i = 0; i < arraySize; i++) { elementValue.ArrayValue.Add(Parse(stream, readerState)); } break; default: throw new ArgumentOutOfRangeException(nameof(elementValue.Tag)); } return(elementValue); }
public SortDirectionEnum(TypeDescriptor typeRepresentation, TypeDescriptor valuesType) : base(typeRepresentation, valuesType) { }
private static bool CanConvertFromString(Type destinationType) { destinationType = Nullable.GetUnderlyingType(destinationType) ?? destinationType; return(IsSimpleType(destinationType) || TypeDescriptor.GetConverter(destinationType).CanConvertFrom(typeof(string))); }
public void RegisterAliasFor(TypeDescriptor td, string alias) { _knownTypesIndexes[alias] = td.ID; }
static T ToObject <T>(this IDataRecord r) where T : new() { var indexMembers = new Dictionary <string, Member>(); T obj = new T(); var accessor = TypeAccessor.Create(typeof(T)); var members = accessor.GetMembers(); if (!IndexMembers.ContainsKey(typeof(T).Name)) { foreach (var item in members) { indexMembers.Add(item.Name, item); } IndexMembers.Add(typeof(T).Name, indexMembers); } indexMembers = IndexMembers[typeof(T).Name]; for (int i = 0; i < r.FieldCount; i++) { var name = r.GetName(i); if (r.GetName(i).Equals("RSRC_ID")) { var k = 10; } if (indexMembers.ContainsKey(name)) { var PropertyType = indexMembers[name].Type; if (r[i].GetType().Name.Equals("DBNull")) { accessor[obj, name] = null; } else if (PropertyType == r[i].GetType()) { accessor[obj, name] = r[i]; } else { if (PropertyType.GenericTypeArguments.Contains(r[i].GetType())) { accessor[obj, name] = r[i]; } else { var c = TypeDescriptor.GetConverter(r[i]); if (PropertyType.IsGenericType) { PropertyType = PropertyType.GenericTypeArguments[0]; } if (c.CanConvertTo(PropertyType)) { accessor[obj, name] = c.ConvertTo(r[i], PropertyType); } else { try { if (r[i].GetType().Name.Equals("Int64")) { accessor[obj, name] = System.Int64.Parse(r[i].ToString()); } if ((indexMembers[name].Type.Name.Contains("Decimal")) || (indexMembers[name].Type.GenericTypeArguments.First().Name.Contains("Decimal"))) { accessor[obj, name] = r[i].ToDecimal(); } else { accessor[obj, name] = System.Convert.ChangeType(r[i], indexMembers[name].Type); } } catch (System.Exception ex) { throw new System.Exception(string.Format("Could not conver field {0} of type {1} to {2}", name, r[i].GetType().Name, indexMembers[name].Type.Name), ex); } } } } } } return(obj); }
private void RegisterType(TypeDescriptor td, Type implementingClass) { _knownTypesIndexes.Add(td.Name, td.ID); _knownTypes.Add(new KnownType() { Descriptor = td, SystemType = implementingClass }); }
public T Get <T>(string property, T defaultValue) { lock (properties) { object o; if (!properties.TryGetValue(property, out o)) { properties.Add(property, defaultValue); return(defaultValue); } if (o is string && typeof(T) != typeof(string)) { TypeConverter c = TypeDescriptor.GetConverter(typeof(T)); try { o = c.ConvertFromInvariantString(o.ToString()); } catch (Exception ex) { LoggingService.Warn("Error loading property '" + property + "': " + ex.Message); o = defaultValue; } properties[property] = o; // store for future look up } else if (o is ArrayList && typeof(T).IsArray) { ArrayList list = (ArrayList)o; Type elementType = typeof(T).GetElementType(); Array arr = System.Array.CreateInstance(elementType, list.Count); TypeConverter c = TypeDescriptor.GetConverter(elementType); try { for (int i = 0; i < arr.Length; ++i) { if (list[i] != null) { arr.SetValue(c.ConvertFromInvariantString(list[i].ToString()), i); } } o = arr; } catch (Exception ex) { LoggingService.Warn("Error loading property '" + property + "': " + ex.Message); o = defaultValue; } properties[property] = o; // store for future look up } else if (!(o is string) && typeof(T) == typeof(string)) { TypeConverter c = TypeDescriptor.GetConverter(typeof(T)); if (c.CanConvertTo(typeof(string))) { o = c.ConvertToInvariantString(o); } else { o = o.ToString(); } } else if (o is SerializedValue) { try { o = ((SerializedValue)o).Deserialize <T>(); } catch (Exception ex) { LoggingService.Warn("Error loading property '" + property + "': " + ex.Message); o = defaultValue; } properties[property] = o; // store for future look up } try { return((T)o); } catch (NullReferenceException) { // can happen when configuration is invalid -> o is null and a value type is expected return(defaultValue); } } }
public virtual bool Enter(TypeDescriptor node) { return true; }
public ClubCloud_BaanSpeciaal_View GetBanenSpeciaalByQuery(string bondsnummer, Guid verenigingId, System.Web.UI.DataSourceSelectArguments selectArgs = null, List <System.Web.UI.WebControls.Parameter> parameters = null, ClubCloud_Setting settings = null) { if (settings != null) { ValidateSettings(ref settings); } ClubCloud_BaanSpeciaal_View view = new ClubCloud_BaanSpeciaal_View(); using (new SPMonitoredScope("BanenSpeciaal GetBanenSpeciaalByQuery")) { StringBuilder querybuilder = new StringBuilder("SELECT * FROM dbo.ClubCloud_BaanSpeciaal"); List <SqlParameter> sqlparams = new List <SqlParameter>(); List <SqlParameter> sqlparamscount = new List <SqlParameter>(); string and = " AND "; if (parameters != null && parameters.Count > 0) { querybuilder.Append(" WHERE "); foreach (System.Web.UI.WebControls.Parameter parameter in parameters) { object value = null; Type type = TypeConvertor.ToNetType(parameter.DbType); if (type == typeof(DateTime)) { IFormatProvider culture = new System.Globalization.CultureInfo("nl-NL", true); value = DateTime.Parse(parameter.DefaultValue, culture, System.Globalization.DateTimeStyles.AssumeLocal); querybuilder.Append(parameter.Name + " >= @" + parameter.Name + and); } else { value = TypeDescriptor.GetConverter(type).ConvertFrom(parameter.DefaultValue); querybuilder.Append(parameter.Name + " = @" + parameter.Name + and); } if (value != null) { sqlparams.Add(new SqlParameter { Value = value, ParameterName = "@" + parameter.Name, DbType = parameter.DbType, Direction = parameter.Direction }); sqlparamscount.Add(new SqlParameter { Value = value, ParameterName = "@" + parameter.Name, DbType = parameter.DbType, Direction = parameter.Direction }); } } if (querybuilder.Length > and.Length) { querybuilder.Remove(querybuilder.Length - and.Length, and.Length); } } if (!string.IsNullOrWhiteSpace(selectArgs.SortExpression)) { querybuilder.Append(" ORDER BY " + selectArgs.SortExpression); } view.ClubCloud_BaanSpeciaal = beheerModel.Database.SqlQuery <ClubCloud_BaanSpeciaal>(querybuilder.ToString(), sqlparams.ToArray()).Skip(selectArgs.StartRowIndex).Take(selectArgs.MaximumRows).ToList <ClubCloud_BaanSpeciaal>(); if (selectArgs.RetrieveTotalRowCount) { view.TotalRowCount = beheerModel.Database.SqlQuery <ClubCloud_BaanSpeciaal>(querybuilder.ToString(), sqlparamscount.ToArray()).Count(); } } return(view); }
public override bool Enter(TypeDescriptor node) { Print("TypeDescriptor: {0}", node.Name); level++; return true; }
public static bool TryChangeType(object value, Type targetType, out object result, IFormatProvider provider = null) { result = value; Type typeofValue = value?.GetType(); if (ReferenceEquals(value, null) || targetType.IsAssignableFrom(typeofValue)) { return(true); } targetType = Nullable.GetUnderlyingType(targetType) ?? targetType; var typeConverter = TypeDescriptor.GetConverter(targetType); if (typeConverter != null && typeConverter.CanConvertFrom(typeofValue)) { try { result = typeConverter.ConvertFrom(value); } catch (FormatException) { return(false); } return(true); } if (targetType.IsEnum) { try { result = Enum.ToObject(targetType, value); } catch (ArgumentException) { return(false); } } if (!(value is IConvertible)) { if (targetType == typeof(string)) { result = value.ToString(); return(true); } return(false); } if (value is char && _charInderectlySupportedConvertions.Contains(targetType)) { value = (int)(char)value; } var convertible = value as IConvertible; if (convertible != null && _convertibleInterfaceTypes.Contains(targetType)) { try { result = convertible.ToType(targetType, provider ?? CultureInfo.CurrentCulture); return(true); } catch (InvalidCastException) { return(false); } } return(false); }
/// <summary> /// Returns an object to describe this type reference. /// </summary> /// <returns>An object to describe this type reference.</returns> public TypeDescriptor Describe() { return this._descriptor ?? ( this._descriptor = TypeDescriptor.ParserAssemblyQualified(this.GetName().AsStream()) .TryGetValue(out this._descriptor) .Let(_ => this._descriptor) ); }
public async Task <(List <DynamicRow> result, IEnumerable <TreeDimensionResult> trees)> ToListAsync(CancellationToken cancellation) { var queryArgs = await _factory(cancellation); var conn = queryArgs.Connection; var sources = queryArgs.Sources; var userId = queryArgs.UserId; var userToday = queryArgs.UserToday; var localizer = queryArgs.Localizer; var logger = queryArgs.Logger; // ------------------------ Validation Step // SELECT Validation if (_select == null) { string message = $"The select argument is required"; throw new InvalidOperationException(message); } // Make sure that measures are well formed: every column access is wrapped inside an aggregation function foreach (var exp in _select) { if (exp.ContainsAggregations) // This is a measure { // Every column access must descend from an aggregation function var exposedColumnAccess = exp.UnaggregatedColumnAccesses().FirstOrDefault(); if (exposedColumnAccess != null) { throw new QueryException($"Select parameter contains a measure with a column access {exposedColumnAccess} that is not included within an aggregation."); } } } // ORDER BY Validation if (_orderby != null) { foreach (var exp in _orderby) { // Order by cannot be a constant if (!exp.ContainsAggregations && !exp.ContainsColumnAccesses) { throw new QueryException("OrderBy parameter cannot be a constant, every orderby expression must contain either an aggregation or a column access."); } } } // FILTER Validation if (_filter != null) { var conditionWithAggregation = _filter.Expression.Aggregations().FirstOrDefault(); if (conditionWithAggregation != null) { throw new QueryException($"Filter contains a condition with an aggregation function: {conditionWithAggregation}"); } } // HAVING Validation if (_having != null) { // Every column access must descend from an aggregation function var exposedColumnAccess = _having.Expression.UnaggregatedColumnAccesses().FirstOrDefault(); if (exposedColumnAccess != null) { throw new QueryException($"Having parameter contains a column access {exposedColumnAccess} that is not included within an aggregation."); } } // ------------------------ Preparation Step // If all is good Prepare some universal variables and parameters var vars = new SqlStatementVariables(); var ps = new SqlStatementParameters(); var today = userToday ?? DateTime.Today; var now = DateTimeOffset.Now; // ------------------------ Tree Analysis Step // By convention if A.B.Id AND A.B.ParentId are both in the select expression, // then this is a tree dimension and we return all the ancestors of A.B, // What do we select for the ancestors? All non-aggregated expressions in // the original select that contain column accesses exclusively starting with A.B var additionalNodeSelects = new List <QueryexColumnAccess>(); var ancestorsStatements = new List <DimensionAncestorsStatement>(); { // Find all column access atoms that terminate with ParentId, those are the potential tree dimensions var parentIdSelects = _select .Where(e => e is QueryexColumnAccess ca && ca.Property == "ParentId") .Cast <QueryexColumnAccess>(); foreach (var parentIdSelect in parentIdSelects) { var pathToTreeEntity = parentIdSelect.Path; // A.B // Confirm it's a tree dimension var idSelect = _select.FirstOrDefault(e => e is QueryexColumnAccess ca && ca.Property == "Id" && ca.PathEquals(pathToTreeEntity)); if (idSelect != null) { // Prepare the Join Trie var treeType = TypeDescriptor.Get <T>(); foreach (var step in pathToTreeEntity) { treeType = treeType.NavigationProperty(step)?.TypeDescriptor ?? throw new QueryException($"Property {step} does not exist on type {treeType.Name}."); } // Create or Get the name of the Node column string nodeColumnName = NodeColumnName(additionalNodeSelects.Count); additionalNodeSelects.Add(new QueryexColumnAccess(pathToTreeEntity, "Node")); // Tell the principal query to include this node // Get all atoms that contain column accesses exclusively starting with A.B var principalSelectsWithMatchingPrefix = _select .Where(exp => exp.ColumnAccesses().All(ca => ca.PathStartsWith(pathToTreeEntity))); // Calculate the target indices var targetIndices = principalSelectsWithMatchingPrefix .Select(exp => SelectIndexDictionary[exp]); // Remove the prefix from all column accesses var ancestorSelects = principalSelectsWithMatchingPrefix .Select(exp => exp.Clone(prefixToRemove: pathToTreeEntity)); var allPaths = ancestorSelects.SelectMany(e => e.ColumnAccesses()).Select(e => e.Path); var joinTrie = JoinTrie.Make(treeType, allPaths); var joinSql = joinTrie.GetSql(sources, fromSql: null); // Prepare the Context var ctx = new QxCompilationContext(joinTrie, sources, vars, ps, today, now, userId); // Prepare the SQL components var selectSql = PrepareAncestorSelectSql(ctx, ancestorSelects); var principalQuerySql = PreparePrincipalQuerySql(nodeColumnName); // Combine the SQL components string sql = QueryTools.CombineSql( selectSql: selectSql, joinSql: joinSql, principalQuerySql: principalQuerySql, whereSql: null, orderbySql: null, offsetFetchSql: null, groupbySql: null, havingSql: null, selectFromTempSql: null); // Get the index of the id select int idIndex = SelectIndexDictionary[idSelect]; // Create and add the statement object var statement = new DimensionAncestorsStatement(idIndex, sql, targetIndices); ancestorsStatements.Add(statement); } } } // ------------------------ The SQL Generation Step // (1) Prepare the JOIN's clause var principalJoinTrie = PreparePrincipalJoin(); var principalJoinSql = principalJoinTrie.GetSql(sources, fromSql: null); // Compilation context var principalCtx = new QxCompilationContext(principalJoinTrie, sources, vars, ps, today, now, userId); // (2) Prepare all the SQL clauses var(principalSelectSql, principalGroupbySql, principalColumnCount) = PreparePrincipalSelectAndGroupBySql(principalCtx, additionalNodeSelects); string principalWhereSql = PreparePrincipalWhereSql(principalCtx); string principalHavingSql = PreparePrincipalHavingSql(principalCtx); string principalOrderbySql = PreparePrincipalOrderBySql(); string principalSelectFromTempSql = PrepareSelectFromTempSql(); // (3) Put together the final SQL statement and return it string principalSql = QueryTools.CombineSql( selectSql: principalSelectSql, joinSql: principalJoinSql, principalQuerySql: null, whereSql: principalWhereSql, orderbySql: principalOrderbySql, offsetFetchSql: null, groupbySql: principalGroupbySql, havingSql: principalHavingSql, selectFromTempSql: principalSelectFromTempSql ); // ------------------------ Execute SQL and return Result var principalStatement = new SqlDynamicStatement(principalSql, principalColumnCount); var(result, trees, _) = await EntityLoader.LoadDynamicStatement( principalStatement : principalStatement, dimAncestorsStatements : ancestorsStatements, includeCount : false, vars : vars, ps : ps, conn : conn, logger : logger, cancellation : cancellation); return(result, trees); }
public IXILMapping TryAllocate(Component host, XILInstr instr, TypeDescriptor[] operandTypes, TypeDescriptor[] resultTypes, IProject targetProject) { if (instr.Name != InstructionCodes.Abs) return null; var operandFormat = operandTypes[0].GetFixFormat(); if (operandFormat == null) return null; var resultFormat = resultTypes[0].GetFixFormat(); if (resultFormat == null) return null; if (operandFormat.FracWidth != resultFormat.FracWidth) return null; var fu = new FixedAbs( operandFormat.TotalWidth, resultFormat.TotalWidth, ComputeLatency(operandFormat.TotalWidth, resultFormat.TotalWidth)); return new AbsMapping(fu); }
private static T ConvertValue <T>(string value) { var converter = TypeDescriptor.GetConverter(typeof(T)); return((T)converter.ConvertFromInvariantString(value)); }