public ILExpressed(ILGenerator il, TypeCache typeCache) { _il = il; _typeCache = typeCache; _snippets = new ILCodeSnippets(this); _var = new ILCodeVariableGenerator(this); }
public void NamesTest() { Assembly assembly = null; // TODO: 初始化为适当的值 TypeCache target = new TypeCache( assembly ); // TODO: 初始化为适当的值 TypeTable actual; actual = target.Names; Assert.Inconclusive( "验证此测试方法的正确性。" ); }
internal override object FetchValue(Element element, object target, TypeCache typeCache, Cache cache) { Node.Attribute attribute; if (!GetNodeFromQuery(Query, null, element, out attribute)) { attribute = element.Attribute(Name); } return attribute == null ? null : GetObjectFromString(attribute.Value, Default, target, typeCache.Type, _typeConverter); }
internal override object FetchValue(Element element, object target, TypeCache typeCache, Cache cache) { Text child; if (!GetNodeFromQuery(Query, null, element, out child)) { child = element.Children.OfType<Text>().FirstOrDefault(); } return child == null ? null : GetObjectFromString(child.Value, Default, target, typeCache.Type, _typeConverter); }
public void ShouldReturnResultOfValueFactoryWhenTypeIsNotInCache() { // Given var cache = new TypeCache<object>(); // When var value = cache.Get<string>(() => "value"); // Then value.Should().Be("value"); }
public void ShouldReturnResultValueFromDictionaryWhenTypeIsInCache() { // Given var cache = new TypeCache<Exception>(); var initialValue = cache.Get<ArgumentNullException>(() => new ArgumentNullException()); // When var value = cache.Get<ArgumentNullException>(() => new ArgumentNullException()); // Then value.Should().BeSameAs(initialValue); }
/// <summary> /// /// </summary> /// <param name="byteHashCode"></param> internal void AddScriptAssembly( Assembly scriptAssembly ) { // 创建新的Assembly数组,添加数据,交换数组数据,不需要锁定,没有引用时自动会回收数据 Assembly[] tempAssemblyArray = new Assembly[m_ScriptAssembly.Length + 1]; for ( int iIndex = 0; iIndex < m_ScriptAssembly.Length; ++iIndex ) tempAssemblyArray[iIndex] = m_ScriptAssembly[iIndex]; tempAssemblyArray[m_ScriptAssembly.Length] = scriptAssembly; m_TypeCache[scriptAssembly] = new TypeCache( scriptAssembly ); m_ScriptAssembly = tempAssemblyArray; }
/// <summary> /// Queries the <see cref="IServiceLocator"/> instance for any instances of <see cref="ModelBinderRegistry"/> to process. /// </summary> /// <param name="serviceLocator">Current <see cref="IServiceLocator"/> instance for the application.</param> public virtual void SetupBinderRegistries(IServiceLocator serviceLocator) { var binderRegistries = GetBinderRegistries(serviceLocator); if (binderRegistries == null) return; var aggregateCache = new TypeCache(); foreach (var modelBinderRegistry in binderRegistries) { var binderCache = modelBinderRegistry.GetBinderRegistrations(); if (binderCache == null) continue; // We will register auto-register the binders for you using (serviceLocator.Batch()) { foreach (var binderType in binderCache.Values) { serviceLocator.Register(binderType, binderType); } } aggregateCache.Merge(binderCache); } ModelBinderProviders.BinderProviders.Add(new ModelBinderRegistryProvider(serviceLocator, aggregateCache)); }
/// <summary> /// 格式化为更新值查询 /// </summary> /// <param name="setValue"></param> /// <param name="joinType"></param> /// <returns></returns> string ForamtSetValue <T>(ParameCollection setValue, Type joinType = null) where T : IModel { //string tableName = TypeCache.GetTableName(typeof(T), dbContext); string setString = ""; var fields = TypeCache.GetProperties(typeof(T), true); foreach (var pair in setValue) { string name = pair.Key; object value = pair.Value; value = ObjectConvert.CheckNullValue(value); if (name.StartsWith("$"))//直接按值拼接 c2["$SoldCount"] = "SoldCount+" + num; { name = name.Substring(1, name.Length - 1); if (!fields.ContainsKey(name)) { throw new CRLException("找不到对应的字段,在" + typeof(T) + ",名称" + name); } var field = fields[name]; string value1 = value.ToString(); //未处理空格 value1 = System.Text.RegularExpressions.Regex.Replace(value1, name + @"([\+\-])", _DBAdapter.KeyWordFormat(field.MapingName) + "$1", System.Text.RegularExpressions.RegexOptions.IgnoreCase); name = field.MapingName; value = value1; setString += string.Format(" {0}={1},", _DBAdapter.KeyWordFormat(name), value); } else { if (joinType != null && value.ToString().Contains("$"))//当是关联更新 { if (!fields.ContainsKey(name)) { throw new CRLException("找不到对应的字段,在" + typeof(T) + ",名称" + name); } var field = fields[name]; name = field.MapingName;//转换映射名 var fields2 = TypeCache.GetProperties(joinType, true); var value1 = System.Text.RegularExpressions.Regex.Match(value.ToString(), @"\$(\w+)", System.Text.RegularExpressions.RegexOptions.IgnoreCase).Groups[1].Value; if (!fields2.ContainsKey(value1)) { throw new CRLException("找不到对应的字段,在" + joinType + ",名称" + value1); } var field2 = fields2[value1]; value = value.ToString().Replace("$" + value1, "t2." + field2.MapingName);//右边字段需加前辍 name = string.Format("t1.{0}", name); } else { if (!fields.ContainsKey(name)) { throw new CRLException("找不到对应的字段,在" + typeof(T) + ",名称" + name); } var field = fields[name]; name = field.MapingName;//转换映射名 var parame = _DBAdapter.GetParamName(name, dbContext.parIndex); AddParam(parame, value); dbContext.parIndex += 1; value = parame; if (joinType != null)//mysql 修正 { name = string.Format("t1.{0}", name); } } setString += string.Format(" {0}={1},", name, value); } } setString = setString.Substring(0, setString.Length - 1); return(setString); }
private void SerializeValue(IDataAdapter data, object target) { objectsCache.Add(target, maxObjId++); TypeWrapper wrapper = TypeCache.GetWrapper(target.GetType()); if (wrapper.TrySerialize(target, data, this)) { return; } for (int i = 0; i < wrapper.Properties.Count; i++) { PropertyWrapper property = wrapper.Properties[i]; if (property.IsPrivate) { if (!settings.SerializePrivateProperties) { continue; } havePrivateProperties = true; } bool isReadOnly; if (property.ConstructorArg != -1 || // will be used in constructor settings.SerializeReadOnly) { isReadOnly = false; // always serialize } else { isReadOnly = !property.CanWrite; } object value = property.GetValue(target); if (value != null) { SerializeValue(property.MemberType, value, data, new Info(property), isReadOnly); } else if (settings.SerializeNull) { data.AddNullValue(property.Name, property.Location != NanoLocation.SubNode); } } for (int i = 0; i < wrapper.Fields.Count; i++) { FieldWrapper field = wrapper.Fields[i]; if (!settings.IgnoreNotSerialized && field.Info.IsNotSerialized) { continue; } object value = field.GetValue(target); if (value != null) { SerializeValue(field.MemberType, value, data, new Info(field), false); } else if (settings.SerializeNull) { data.AddNullValue(field.Name, field.Location != NanoLocation.SubNode); } } }
public static TypeCache Create(Type type) { var typeCache = new TypeCache(type); typeCache.Constructors.AddRange(type.GetConstructors()); while (type != null) { // Instances foreach (var propertyInfo in type.GetProperties(InstanceDefaultBindingFlags)) { if (propertyInfo.GetIndexParameters().Any()) { typeCache.InstanceIndexers.Add(propertyInfo); } else { if (!typeCache.InstanceProperties.ContainsKey(propertyInfo.Name)) { typeCache.InstanceProperties.Add(propertyInfo.Name, propertyInfo); } } } foreach (var fieldInfo in type.GetFields(InstanceDefaultBindingFlags)) { if (!typeCache.InstanceFields.ContainsKey(fieldInfo.Name)) { typeCache.InstanceFields.Add(fieldInfo.Name, fieldInfo); } } // Static foreach (var propertyInfo in type.GetProperties(StaticDefaultBindingFlags)) { if (propertyInfo.GetIndexParameters().Any()) { typeCache.StaticIndexers.Add(propertyInfo); } else { if (!typeCache.StaticProperties.ContainsKey(propertyInfo.Name)) { typeCache.StaticProperties.Add(propertyInfo.Name, propertyInfo); } } } foreach (var fieldInfo in type.GetFields(StaticDefaultBindingFlags)) { if (!typeCache.StaticFields.ContainsKey(fieldInfo.Name)) { typeCache.StaticFields.Add(fieldInfo.Name, fieldInfo); } } type = type.BaseType; } return(typeCache); }
internal override void Inititalize(Type memberType, string memberName, Cache cache) { base.Inititalize(memberType, memberName, cache); // Get element names Name = GetName(Name, memberName, Query, CreateQuery); ItemName = GetName(ItemName, "Item", ItemQuery); KeyAttributeName = GetName(KeyAttributeName, null, KeyElementName, KeyQuery); if (String.IsNullOrEmpty(KeyAttributeName)) { KeyElementName = GetName(KeyElementName, "Key", KeyQuery); } ValueAttributeName = GetName(ValueAttributeName, null, ValueElementName, ValueQuery); if (String.IsNullOrEmpty(ValueAttributeName)) { ValueElementName = GetName(ValueElementName, "Value", ValueQuery); } // Get attribute names if(KeysArePersistentObjects && !String.IsNullOrEmpty(KeyAttributeName)) throw new Exception("KeyAttributeName must not be specified if KeysArePersistentObjects is true."); if (ValuesArePersistentObjects && !String.IsNullOrEmpty(ValueAttributeName)) throw new Exception("ValueAttributeName must not be specified if ValuesArePersistentObjects is true."); // Get the TypeConverters if (KeyTypeConverter != null) { if (KeysArePersistentObjects) throw new Exception("A TypeConverter can not be specified for persistent member objects."); _keyTypeConverter = InitializeTypeConverter(KeyTypeConverter); } if (ValueTypeConverter != null) { if (ValuesArePersistentObjects) throw new Exception("A TypeConverter can not be specified for persistent member objects."); _valueTypeConverter = InitializeTypeConverter(ValueTypeConverter); } // Resolve the type of collection and the key/value type // Key = ICollection<>, Value = KeyValuePair<,> List<KeyValuePair<Type, Type>> kvpInterfaces = new List<KeyValuePair<Type, Type>>(memberType.GetInterfaces() .Where(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(ICollection<>)) .Select(t => new KeyValuePair<Type, Type>(t, t.GetGenericArguments()[0])) .Where(k => k.Value.IsGenericType && k.Value.GetGenericTypeDefinition() == typeof(KeyValuePair<,>))); if(kvpInterfaces.Count > 0) { // The member implements ICollection<KeyValuePair<TKey,TValue>> // Verify KeyType and ValueType are compatable (if specified) KeyValuePair<Type, Type>? kvpType = null; foreach (KeyValuePair<Type, Type> kvp in kvpInterfaces) { Type keyType = kvp.Value.GetGenericArguments()[0]; Type valueType = kvp.Value.GetGenericArguments()[1]; if((KeyType == null || keyType.IsAssignableFrom(KeyType)) && (ValueType == null || valueType.IsAssignableFrom(ValueType))) { kvpType = kvp; if(KeyType == null) KeyType = keyType; if(ValueType == null) ValueType = valueType; break; } } // Make sure we got a kvp type if (!kvpType.HasValue) throw new Exception("No appropriate key or value type could be found."); // Get the constructor and other functions ConstructorInfo constructor = memberType.GetConstructor(Type.EmptyTypes); if (constructor == null) throw new Exception("Persistent collection member must implement an empty constructor."); MethodInfo clearMethod = kvpType.Value.Key.GetMethod("Clear"); _getCollection = c => { if (c == null) return constructor.Invoke(null); clearMethod.Invoke(c, null); return c; }; ConstructorInfo kvpConstructor = kvpType.Value.Value.GetConstructor(new[] { KeyType, ValueType }); if (kvpConstructor == null) throw new Exception("Could not get KeyValuePair constructor."); MethodInfo addMethod = kvpType.Value.Key.GetMethod("Add"); _setCollectionItem = (c, k, v) => addMethod.Invoke(c, new[] { kvpConstructor.Invoke(new []{k, v}) }); PropertyInfo keyProperty = kvpType.Value.Value.GetProperty("Key"); if(keyProperty == null) throw new Exception("Could not get Key property."); _getKey = i => keyProperty.GetValue(i, null); PropertyInfo valueProperty = kvpType.Value.Value.GetProperty("Value"); if (valueProperty == null) throw new Exception("Could not get Value property."); _getValue = i => valueProperty.GetValue(i, null); } else if(typeof(IDictionary).IsAssignableFrom(memberType)) { // The member implements IDictionary if (KeyType == null) throw new Exception("A persistent collection that implements IDictionary must provide a KeyType."); if (ValueType == null) throw new Exception("A persistent collection that implements IDictionary must provide a ValueType."); ConstructorInfo constructor = memberType.GetConstructor(Type.EmptyTypes); if (constructor == null) throw new Exception("Persistent collection member must implement an empty constructor."); _getCollection = c => { if (c == null) return constructor.Invoke(null); ((IDictionary)c).Clear(); return c; }; _setCollectionItem = (c, k, v) => ((IDictionary)c).Add(k, v); _getKey = i => ((DictionaryEntry)i).Key; _getValue = i => ((DictionaryEntry)i).Value; } else { throw new Exception("Persistent kvp collection member must implement ICollection<KeyValuePair<TKey,TValue>> or implement IDictionary."); } _keyTypeCache = cache.GetTypeCache(KeyType); _valueTypeCache = cache.GetTypeCache(ValueType); }
/// <summary> /// 给出类型申明,是否忽略大小写 /// </summary> public Type FindTypeByName( string strName, bool bIgnoreCase ) { Type type = null; for ( int iIndex = 0; type == null && iIndex < m_ScriptAssembly.Length; ++iIndex ) { TypeCache typeCache = GetTypeCache( m_ScriptAssembly[iIndex] ); if ( typeCache == null ) continue; type = typeCache.GetTypeByName( strName, bIgnoreCase ); if ( type != null ) break; } if ( type == null ) { if ( s_AssemblyTypeCache == null ) s_AssemblyTypeCache = new TypeCache( OneServer.Assembly ); type = s_AssemblyTypeCache.GetTypeByName( strName, bIgnoreCase ); } return type; }
/// <summary> /// Default constructor. /// </summary> /// <param name="serviceLocator"></param> /// <param name="cache"></param> public ModelBinderRegistryProvider(IServiceLocator serviceLocator, TypeCache cache) { ServiceLocator = serviceLocator; BinderCache = cache; }
public void GetTypeByNameTest() { Assembly assembly = null; // TODO: 初始化为适当的值 TypeCache target = new TypeCache( assembly ); // TODO: 初始化为适当的值 string strName = string.Empty; // TODO: 初始化为适当的值 bool ignoreCase = false; // TODO: 初始化为适当的值 Type expected = null; // TODO: 初始化为适当的值 Type actual; actual = target.GetTypeByName( strName, ignoreCase ); Assert.AreEqual( expected, actual ); Assert.Inconclusive( "验证此测试方法的正确性。" ); }
internal static IEnumerable <MethodInfo> GetAllMethodsWithAttribute <T>() where T : System.Attribute { return(TypeCache.GetMethodsWithAttribute <T>()); }
CRLExpression.CRLExpression MethodCallExpressionHandler(Expression exp, ExpressionType?nodeType = null, bool firstLevel = false) { #region methodCall MethodCallExpression mcExp = (MethodCallExpression)exp; var arguments = new List <object>(); var allArguments = mcExp.Arguments; int argsIndex = 0; Expression firstArgs; if (mcExp.Method.IsStatic) //区分静态方法还是实例方法 { firstArgs = allArguments[0]; //like b.Name.IsNull("22") argsIndex = 1; } else { firstArgs = mcExp.Object;//like b.Id.ToString() } MethodCallExpressionCacheItem methodCache; #region 缓存处理 string key = __PrefixsAllKey + mcExp + nodeType; var exists = MethodCallExpressionCache.TryGetValue(key, out methodCache); if (exists) { if (!methodCache.isConstantMethod) { var methodCall = methodCache.CRLExpression.Data as CRLExpression.MethodCallObj; if (methodCall.Args.Count > 0) { for (int i = 0; i < allArguments.Count; i++) { bool isConstant1; var obj = GetParameExpressionValue(allArguments[i], out isConstant1); arguments.Add(obj); } methodCall.Args = arguments; } } methodCache.CRLExpression.SqlOut = ""; return(methodCache.CRLExpression); } #endregion #region MethodCallExpression bool isConstantMethod = false; MemberExpression memberExpression; string methodField = ""; string memberName = ""; string methodName = mcExp.Method.Name; if (firstArgs is ParameterExpression) { var exp2 = mcExp.Arguments[1] as UnaryExpression; var type = exp2.Operand.GetType(); var p = type.GetProperty("Body"); var exp3 = p.GetValue(exp2.Operand, null) as Expression; methodField = RouteExpressionHandler(exp3).SqlOut; memberName = ""; } else if (firstArgs is UnaryExpression)//like a.Code.Count() { memberExpression = (firstArgs as UnaryExpression).Operand as MemberExpression; memberName = memberExpression.Member.Name; methodField = FormatFieldPrefix(memberExpression.Expression.Type, memberExpression.Member.Name); } else if (firstArgs is MemberExpression) { //like a.Code memberExpression = firstArgs as MemberExpression; memberName = memberExpression.Member.Name; var type = memberExpression.Expression.Type; if (type.IsSubclassOf(typeof(IModel))) { memberName = TypeCache.GetProperties(type, true)[memberExpression.Member.Name].MapingName; } if (memberExpression.Expression.NodeType == ExpressionType.Parameter) { methodField = FormatFieldPrefix(memberExpression.Expression.Type, memberName); var allConstant = true; for (int i = argsIndex; i < allArguments.Count; i++) { bool isConstant2; var obj = GetParameExpressionValue(allArguments[i], out isConstant2); if (!isConstant2) { allConstant = true; } arguments.Add(obj); } if (allConstant) { isConstantMethod = true; } } else { //like Convert.ToDateTime(times) var obj = ConstantValueVisitor.GetParameExpressionValue(firstArgs); arguments.Add(obj); isConstantMethod = true; } } else if (firstArgs is ConstantExpression)//按常量 { //like DateTime.Parse("2016-02-11 12:56"), isConstantMethod = true; var obj = ConstantValueVisitor.GetParameExpressionValue(firstArgs); arguments.Add(obj); } //else //{ // throw new CRLException("不支持此语法解析:" + args); //} if (nodeType == null) { nodeType = ExpressionType.Equal; } if (string.IsNullOrEmpty(methodField)) { //当是常量转换方法 //like DateTime.Parse("2016-02-11") var method = mcExp.Method; object obj; if (mcExp.Method.IsStatic) { obj = method.Invoke(null, arguments.ToArray()); } else { var args1 = arguments.First(); arguments.RemoveAt(0); obj = method.Invoke(args1, arguments.ToArray()); } var exp2 = new CRLExpression.CRLExpression() { Type = CRLExpression.CRLExpressionType.Value, Data = obj }; var cache = new MethodCallExpressionCacheItem() { CRLExpression = exp2, argsIndex = argsIndex, isConstantMethod = isConstantMethod, isStatic = mcExp.Method.IsStatic }; MethodCallExpressionCache[key] = cache; return(exp2); } var methodInfo = new CRLExpression.MethodCallObj() { Args = arguments, ExpressionType = nodeType.Value, MemberName = memberName, MethodName = methodName, MemberQueryName = methodField }; methodInfo.ReturnType = mcExp.Type; #endregion var exp4 = new CRLExpression.CRLExpression() { Type = CRLExpression.CRLExpressionType.MethodCall, Data = methodInfo }; var cache2 = new MethodCallExpressionCacheItem() { CRLExpression = exp4, argsIndex = argsIndex, isConstantMethod = isConstantMethod }; MethodCallExpressionCache[key] = cache2; return(exp4); #endregion }
CRLExpression.CRLExpression MemberExpressionHandler(Expression exp, ExpressionType?nodeType = null, bool firstLevel = false) { #region MemberExpression //区分 属性表达带替换符{0} 变量值不带 MemberExpression mExp = (MemberExpression)exp; if (mExp.Expression != null && mExp.Expression.NodeType == ExpressionType.Parameter) //like b.Name==b.Name1 或b.Name { #region MemberParameter var fieldName = mExp.Member.Name; var type = mExp.Expression.Type; if (mExp.Member.ReflectedType.Name.StartsWith("<>f__AnonymousType"))//按匿名类 { //var queryField = FormatFieldPrefix(type, fieldName); var exp2 = new CRLExpression.CRLExpression() { Type = CRLExpression.CRLExpressionType.Name, Data = fieldName, MemberType = type }; //MemberExpressionCache[key] = exp2; return(exp2); } CRL.Attribute.FieldAttribute field; var a = TypeCache.GetProperties(type, true).TryGetValue(fieldName, out field); if (!a) { throw new CRLException("类型 " + type.Name + "." + fieldName + " 不是数据库字段,请检查查询条件"); } //if (!string.IsNullOrEmpty(field.VirtualField))//按虚拟字段 //{ // //return filed.VirtualField; // var queryField = field.VirtualField.Replace("{" + type.FullName + "}", Prefixs[type]);//替换前辍 // var exp2 = new CRLExpression.CRLExpression() { Type = CRLExpression.CRLExpressionType.Name, Data = queryField, MemberType = type }; // //MemberExpressionCache[key] = exp2; // return exp2; //} //var fieldStr = FormatFieldPrefix(type, field.MapingName);//格式化为别名 var fieldStr = field.MapingName; //return field; if (firstLevel) { var exp2 = exp.Equal(Expression.Constant(true)); return(RouteExpressionHandler(exp2)); } var exp3 = new CRLExpression.CRLExpression() { Type = CRLExpression.CRLExpressionType.Name, Data = fieldStr, MemberType = type }; //MemberExpressionCache[key] = exp3; return(exp3); #endregion } else { string key = exp.ToString() + firstLevel; CRLExpression.CRLExpression val; var a1 = MemberExpressionCache.TryGetValue(key, out val); if (a1) { return(val); } #region 值 bool isConstant; var obj = GetParameExpressionValue(mExp, out isConstant); if (obj is Enum) { obj = (int)obj; } else if (obj is Boolean)//sql2000需要转换 { obj = Convert.ToInt32(obj); } var exp4 = new CRLExpression.CRLExpression() { Type = CRLExpression.CRLExpressionType.Value, Data = obj, IsConstantValue = isConstant }; if (isConstant) { MemberExpressionCache[key] = exp4; } return(exp4); #endregion } #endregion }
/// <summary> /// 获取完整查询 /// </summary> /// <returns></returns> internal override string GetQuery() { string fields = GetQueryFieldString(); if (!string.IsNullOrEmpty(__FieldFunctionFormat)) { fields = string.Format(__FieldFunctionFormat, fields); } if (distinctCount) { fields = System.Text.RegularExpressions.Regex.Replace(fields, @" as \w+", "");//替换别名 fields = string.Format(" count({0}) as Total", fields); if (_CurrentSelectFieldCache.fields.Count > 1) { throw new CRLException("distinct 时,不能count多个字段 " + fields); } } var part = " from " + GetQueryConditions(); var orderBy = GetOrderBy(); StringBuilder sql = new StringBuilder(); //当设置了分表联合查询 if (__DbContext.UseSharding && __ShanrdingUnionType != UnionType.None) { #region 当设置了分表联合查询 string tableName = TypeCache.GetTable(typeof(T)).TableName; var tables = Sharding.DBService.GetAllTable(__DbContext.DBLocation.ShardingDataBase, tableName); string unionType = __ShanrdingUnionType == UnionType.Union ? "union" : "union all"; //var dbExtend = new DBExtend(dbContext); //todo 检查分表是否被创建 for (int i = 0; i < tables.Count; i++) { var table = tables[i]; var part1 = part.Replace("from " + __DBAdapter.KeyWordFormat(tableName), "from " + __DBAdapter.KeyWordFormat(table.PartName)); sql.Append(__DBAdapter.GetSelectTop(fields, part1, "", TakeNum)); if (i < tables.Count - 1) { sql.Append("\r\n " + unionType + " \r\n"); } } orderBy = System.Text.RegularExpressions.Regex.Replace(orderBy, @"t\d+\.", ""); sql.Append("\r\n " + orderBy); #endregion } else { if (__Unions.Count == 0) { var sql2 = __DBAdapter.GetSelectTop(fields, part, orderBy, TakeNum); sql.Append(sql2); } else { #region 联合查询 var sql2 = __DBAdapter.GetSelectTop(fields, part, "", TakeNum); sql.Append(sql2); foreach (var unionQuery in __Unions) { var query = unionQuery.query; query.__QueryOrderBy = ""; string unionType = unionQuery.unionType == UnionType.Union ? "union" : "union all"; var sqlUnoin = query.GetQuery(); sql.Append("\r\n " + unionType + " \r\n"); sql.Append(sqlUnoin); } if (!string.IsNullOrEmpty(orderBy)) { orderBy = System.Text.RegularExpressions.Regex.Replace(orderBy, @"t\d+\.", " "); sql.Append("\r\n " + orderBy); } #endregion } } var ts = DateTime.Now - startTime; AnalyticalTime = ts.TotalMilliseconds; return(sql.ToString()); }
public static List <T> Selectors <T>() { var allSelectorsTypes = TypeCache.GetTypesDerivedFrom <T>(); var unusedSelectors = new HashSet <T>(allSelectorsTypes.Select(t => (T)Activator.CreateInstance(t))); Dictionary <Type, T> selectorsMapping = unusedSelectors.ToDictionary(s => s.GetType()); HashSet <T> leftSelectors = new HashSet <T>(unusedSelectors); List <T> selectors = new List <T>(); Dictionary <T, HashSet <T> > pairs = new Dictionary <T, HashSet <T> >(); // Find pairs foreach (var selector in unusedSelectors) { // Process after var processAfter = selector.GetType().GetCustomAttribute <ProcessAfter>(); if (processAfter?.ReferenceType != null) { selectorsMapping.TryGetValue(processAfter.ReferenceType, out var leftSelector); if (leftSelector != null) { if (!pairs.TryGetValue(leftSelector, out var dependencies)) { dependencies = new HashSet <T>(); pairs[leftSelector] = dependencies; } dependencies.Add(selector); } } // Process before var processBefore = selector.GetType().GetCustomAttribute <ProcessBefore>(); if (processBefore?.ReferenceType != null) { selectorsMapping.TryGetValue(processBefore.ReferenceType, out var dependent); if (dependent != null) { if (!pairs.TryGetValue(selector, out var dependencies)) { dependencies = new HashSet <T>(); pairs[selector] = dependencies; } dependencies.Add(dependent); } } } Queue <T> selectorsQueue = new Queue <T>(unusedSelectors.Except(pairs.SelectMany(p => p.Value))); // Find chain while (selectorsQueue.Count > 0) { var selector = selectorsQueue.Dequeue(); if (unusedSelectors.Contains(selector)) { selectors.Add(selector); unusedSelectors.Remove(selector); if (pairs.TryGetValue(selector, out var dependencies)) { foreach (var dependent in dependencies) { if (unusedSelectors.Contains(dependent)) { selectorsQueue.Enqueue(dependent); } } } } } if (unusedSelectors.Count > 1) { throw new Exception($"For type {typeof( T )} there is impossible dependencies chain"); } // Check constrains for (int i = 0; i < selectors.Count; i++) { var selector = selectors[i]; if (pairs.TryGetValue(selector, out var dependencies)) { if (dependencies.Except(selectors.Skip(i)).Count() > 0) { throw new Exception($"For type {typeof( T )} there is impossible dependencies chain"); } } } return(selectors); }
private object GetPropertyValue(IEdmTypeReference propertyType, object value, ODataResource root) { if (value == null) { return(value); } switch (propertyType.TypeKind()) { case EdmTypeKind.Complex: if (Converter.HasObjectConverter(value.GetType())) { return(Converter.Convert(value, value.GetType())); } return(CreateODataEntry(propertyType.FullName(), value.ToDictionary(TypeCache), root)); case EdmTypeKind.Collection: var collection = propertyType.AsCollection(); return(new ODataCollectionValue { TypeName = propertyType.FullName(), Items = ((IEnumerable)value).Cast <object>().Select(x => GetPropertyValue(collection.ElementType(), x, root)), }); case EdmTypeKind.Primitive: var mappedTypes = _typeMap.Where(x => x.Value == ((IEdmPrimitiveType)propertyType.Definition).PrimitiveKind); if (mappedTypes.Any()) { foreach (var mappedType in mappedTypes) { if (TryConvert(value, mappedType.Key, out var result)) { return(result); } else if (TypeCache.TryConvert(value, mappedType.Key, out result)) { return(result); } } throw new NotSupportedException($"Conversion is not supported from type {value.GetType()} to OData type {propertyType}"); } return(value); case EdmTypeKind.Enum: return(new ODataEnumValue(value.ToString())); case EdmTypeKind.Untyped: return(new ODataUntypedValue { RawValue = value.ToString() }); case EdmTypeKind.None: if (Converter.HasObjectConverter(value.GetType())) { return(Converter.Convert(value, value.GetType())); } throw new NotSupportedException($"Conversion is not supported from type {value.GetType()} to OData type {propertyType}"); default: return(value); } }
public void TypeCacheConstructorTest() { Assembly assembly = null; // TODO: 初始化为适当的值 TypeCache target = new TypeCache( assembly ); Assert.Inconclusive( "TODO: 实现用来验证目标的代码" ); }
// C# compiler does not emit the full qualified type name when it fails to resolve a 'theoretically', fully qualified type reference // for instance, if 'NSBar', a namespace gets renamed to 'NSBar2', a reference to 'NSFoo.NSBar.TypeBaz' will emit an error // with only NSBar and NSFoo in the message. In this case we use NRefactory to dive in to the code, looking for type references // in the reported error line/column static Type FindTypeMatchingMovedTypeBasedOnNamespaceFromError(IEnumerable <string> lines) { var value = GetValueFromNormalizedMessage(lines, "Line="); var line = (value != null) ? Int32.Parse(value) : -1; value = GetValueFromNormalizedMessage(lines, "Column="); var column = (value != null) ? Int32.Parse(value) : -1; var script = GetValueFromNormalizedMessage(lines, "Script="); if (line == -1 || column == -1 || script == null) { return(null); } var entityName = GetValueFromNormalizedMessage(lines, "EntityName="); try { using (var scriptStream = File.Open(script, System.IO.FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) { var parser = ParserFactory.CreateParser(ICSharpCode.NRefactory.SupportedLanguage.CSharp, new StreamReader(scriptStream)); parser.Lexer.EvaluateConditionalCompilation = false; parser.Parse(); var self = new InvalidTypeOrNamespaceErrorTypeMapper(line, column, entityName); parser.CompilationUnit.AcceptVisitor(self, null); if (self.identifiers.Count == 0) { return(null); } var availableTypes = TypeCache.GetTypesWithAttribute(typeof(MovedFromAttribute)); foreach (var ns in self.NamespacesInScope) { foreach (var i in self.identifiers) { foreach (var t in availableTypes) { var @namespace = ns; foreach (var part in i.parts) { //If the usage + any of the candidate namespaces matches a real type, this usage is valid and does not need to be updated //this is required to avoid false positives when a type that exists on *editor* (and is marked as moved) is used in a platform that //does not support it. If we don't check the namespaces in scope we'll flag this as an error due to the type being moved (and //whence, trigger the updater, whereas the real problem is that the type is not supported in the platform (see issue #96123) //whence this is indeed a programing error that the user needs to fix. if (t.Name == part && t.Namespace == @namespace) { return(null); } if (t.Name == part && NamespaceHasChanged(t, @namespace)) { return(t); } if (string.IsNullOrEmpty(@namespace)) { @namespace = part; } else { @namespace = @namespace + "." + part; } } } } } return(null); } } catch (FileNotFoundException) { return(null); } }
internal override object FetchValue(Element element, object target, TypeCache typeCache, Cache cache) { object result = element.EvalSingle(Query); if (result == null) return null; Node.Node node = result as Node.Node; return GetObjectFromString( node != null ? node.Value : result.ToString(), Default, target, typeCache.Type, _typeConverter); }
/// <summary> /// Gets the known types inside the specific type. /// </summary> /// <param name="type">The type.</param> /// <param name="serializerTypeInfo">The serializer type info.</param> /// <param name="resolveAbstractClassesAndInterfaces">if set to <c>true</c> [resolve abstract classes and interfaces].</param> /// <returns>Array of <see cref="Type" /> that are found in the object type.</returns> protected virtual void GetKnownTypes(Type type, XmlSerializerTypeInfo serializerTypeInfo, bool resolveAbstractClassesAndInterfaces = true) { if (ShouldTypeBeIgnored(type, serializerTypeInfo)) { return; } #if ENABLE_DETAILED_LOGGING Log.Debug("Getting known types for '{0}'", type.GetSafeFullName(false)); #endif GetKnownTypesForItems(type, serializerTypeInfo); // If this is an interface or abstract, we need to retieve all items that might possible implement or derive var isInterface = type.IsInterfaceEx(); var isAbstract = type.IsAbstractEx(); if (isInterface || isAbstract) { if (!serializerTypeInfo.IsTypeAlreadyHandled(type) && resolveAbstractClassesAndInterfaces) { // Interfaces / abstract classes are not a type, and in fact a LOT of types can be added (in fact every object implementing // the interface). For serialization, this is not a problem (we know the exact type), but for deserialization this IS an // issue because we should expect EVERY type that implements the type in the whole AppDomain. // This is huge performance hit, but it's the cost for dynamic easy on-the-fly serialization in WPF and Silverlight. Luckily // we already implemented caching. // Don't check this type again in children checks serializerTypeInfo.AddTypeAsHandled(type); #if ENABLE_DETAILED_LOGGING Log.Debug("Type is an interface / abstract class, checking all types implementing / deriving"); #endif if (isInterface) { var typesImplementingInterface = TypeCache.GetTypesImplementingInterface(type); foreach (var typeImplementingInterface in typesImplementingInterface) { if (typeImplementingInterface != type) { GetKnownTypes(typeImplementingInterface, serializerTypeInfo); } } } if (isAbstract) { var typesDerivingFromClass = TypeCache.GetTypes(type.IsAssignableFromEx, false); foreach (var typeDerivingFromClass in typesDerivingFromClass) { if (typeDerivingFromClass != type) { GetKnownTypes(typeDerivingFromClass, serializerTypeInfo); } } } #if ENABLE_DETAILED_LOGGING Log.Debug("Finished checking all types implementing / deriving"); #endif } // The interface itself is ignored return; } if (serializerTypeInfo.IsSpecialCollectionType(type) && !type.IsInterfaceEx()) { #if ENABLE_DETAILED_LOGGING Log.Debug("Type is a special collection type, adding it to the array of known types"); #endif AddTypeToKnownTypesIfSerializable(type, serializerTypeInfo); } // Fix generics if (type.GetSafeFullName(false).StartsWith("System.")) { var genericArguments = type.GetGenericArgumentsEx(); foreach (var genericArgument in genericArguments) { #if ENABLE_DETAILED_LOGGING Log.Debug("Retrieving known types for generic argument '{0}' of '{1}'", genericArgument.GetSafeFullName(false), type.GetSafeFullName(false)); #endif GetKnownTypes(genericArgument, serializerTypeInfo); } return; } if (!AddTypeToKnownTypesIfSerializable(type, serializerTypeInfo)) { serializerTypeInfo.AddTypeAsHandled(type); } AddTypeMembers(type, serializerTypeInfo); // If this isn't the base type, check that as well var baseType = type.GetBaseTypeEx(); if (baseType != null) { #if ENABLE_DETAILED_LOGGING Log.Debug("Checking base type of '{0}' for known types", type.GetSafeFullName(false)); #endif if (baseType.FullName != null) { GetKnownTypes(baseType, serializerTypeInfo); } else { serializerTypeInfo.AddTypeAsHandled(baseType); } } // Last but not least, check if the type is decorated with KnownTypeAttributes var knowTypesByAttributes = GetKnownTypesViaAttributes(type); if (knowTypesByAttributes.Length > 0) { #if ENABLE_DETAILED_LOGGING Log.Debug("Found {0} additional known types for type '{1}'", knowTypesByAttributes.Length, type.GetSafeFullName(false)); #endif foreach (var knownTypeByAttribute in knowTypesByAttributes) { var attributeType = knownTypeByAttribute; var attributeTypeFullName = attributeType.GetSafeFullName(false); if (attributeTypeFullName != null) { GetKnownTypes(knownTypeByAttribute, serializerTypeInfo); } else { serializerTypeInfo.AddTypeAsHandled(attributeType); } } } }
internal override object SerializeValue(object source, TypeCache typeCache, Cache cache) { if (!String.IsNullOrEmpty(ItemQuery) || !String.IsNullOrEmpty(KeyQuery) || !String.IsNullOrEmpty(ValueQuery)) throw new Exception("Can not store persistent collection that uses queries."); // Key/key = key source object, key/value = serialized key data // Value/key = value source object, value/value = serialized value data List<KeyValuePair<KeyValuePair<object, object>, KeyValuePair<object, object>>> values = new List<KeyValuePair<KeyValuePair<object, object>, KeyValuePair<object, object>>>(); // Iterate over the source object if (source != null) { IEnumerable items = (IEnumerable)source; foreach (object item in items) { object key = _getKey(item); object keyValue = KeysArePersistentObjects ? _keyTypeCache.Persister.Serialize(key, _keyTypeCache, cache) : GetStringFromObject(key, KeyType, _keyTypeConverter); object value = _getValue(item); object valueValue = ValuesArePersistentObjects ? _valueTypeCache.Persister.Serialize(value, _valueTypeCache, cache) : GetStringFromObject(value, ValueType, _valueTypeConverter); values.Add(new KeyValuePair<KeyValuePair<object, object>, KeyValuePair<object, object>>( new KeyValuePair<object, object>(key, keyValue), new KeyValuePair<object, object>(value, valueValue))); } } return values; }
internal static string Process(AssemblyOptions options, string templateFileName, string currentNamespace) { StringBuilder sb = new StringBuilder(); var entities = options.Resolver.SignumEntities; Cache = new TypeCache(entities); var namespacesReferences = new Dictionary <string, Dictionary <string, NamespaceTSReference> >(); namespacesReferences.GetNamespaceReference(options, Cache.ModifiableEntity); var exportedTypes = options.ModuleDefinition.Types.Where(a => a.Namespace == currentNamespace).ToList(); if (exportedTypes.Count == 0) { throw new InvalidOperationException($"Assembly '{options.CurrentAssembly}' has not types in namespace '{currentNamespace}'"); } var imported = options.ModuleDefinition.Assembly.CustomAttributes.Where(at => at.AttributeType.FullName == Cache.ImportInTypeScriptAttribute.FullName) .Where(at => (string)at.ConstructorArguments[1].Value == currentNamespace) .Select(at => ((TypeReference)at.ConstructorArguments[0].Value).Resolve()) .ToList(); var importedMessage = imported.Where(a => a.Name.EndsWith("Message")).ToList(); var importedEnums = imported.Except(importedMessage).ToList(); var entityResults = (from type in exportedTypes where !type.IsValueType && (type.InTypeScript() ?? IsModifiableEntity(type)) select new { ns = type.Namespace, type, text = EntityInTypeScript(type, options, namespacesReferences), }).ToList(); var interfacesResults = (from type in exportedTypes where type.IsInterface && (type.InTypeScript() ?? type.AnyInterfaces(IEntityCache, i => i.FullName == Cache.IEntity.FullName)) select new { ns = type.Namespace, type, text = EntityInTypeScript(type, options, namespacesReferences), }).ToList(); var usedEnums = (from type in entityResults.Select(a => a.type) from p in GetAllProperties(type) let pt = (p.PropertyType.ElementType() ?? p.PropertyType).UnNullify() let def = pt.Resolve() where def != null && def.IsEnum select def).Distinct().ToList(); var symbolResults = (from type in exportedTypes where !type.IsValueType && type.IsStaticClass() && type.ContainsAttribute("AutoInitAttribute") && (type.InTypeScript() ?? true) select new { ns = type.Namespace, type, text = SymbolInTypeScript(type, options, namespacesReferences), }).ToList(); var enumResult = (from type in exportedTypes where type.IsEnum && (type.InTypeScript() ?? usedEnums.Contains(type)) select new { ns = type.Namespace, type, text = EnumInTypeScript(type, options), }).ToList(); var externalEnums = (from type in usedEnums.Where(options.IsExternal).Concat(importedEnums) select new { ns = currentNamespace + ".External", type, text = EnumInTypeScript(type, options), }).ToList(); var externalMessages = (from type in importedMessage select new { ns = currentNamespace + ".External", type, text = MessageInTypeScript(type, options), }).ToList(); var messageResults = (from type in exportedTypes where type.IsEnum && type.Name.EndsWith("Message") select new { ns = type.Namespace, type, text = MessageInTypeScript(type, options), }).ToList(); var queryResult = (from type in exportedTypes where type.IsEnum && type.Name.EndsWith("Query") select new { ns = type.Namespace, type, text = QueryInTypeScript(type, options), }).ToList(); var namespaces = entityResults .Concat(interfacesResults) .Concat(enumResult) .Concat(messageResults) .Concat(queryResult) .Concat(symbolResults) .Concat(externalEnums) .Concat(externalMessages) .GroupBy(a => a.ns) .OrderBy(a => a.Key); foreach (var ns in namespaces) { var key = RemoveNamespace(ns.Key.ToString(), currentNamespace); if (key.Length == 0) { foreach (var item in ns.OrderBy(a => a.type.Name)) { sb.AppendLine(item.text); } } else { sb.AppendLine("export namespace " + key + " {"); sb.AppendLine(); foreach (var item in ns.OrderBy(a => a.type.Name)) { foreach (var line in item.text.Split(new[] { "\r\n" }, StringSplitOptions.None)) { sb.AppendLine(" " + line); } } sb.AppendLine("}"); sb.AppendLine(); } } var code = sb.ToString(); return(WriteFillFile(options, code, templateFileName, namespacesReferences)); }
internal static void InitializeBuildCallbacks(BuildCallbacks findFlags) { if (findFlags == previousFlags) { return; } CleanupBuildCallbacks(); previousFlags = findFlags; bool findBuildProcessors = (findFlags & BuildCallbacks.BuildProcessors) == BuildCallbacks.BuildProcessors; bool findSceneProcessors = (findFlags & BuildCallbacks.SceneProcessors) == BuildCallbacks.SceneProcessors; bool findTargetProcessors = (findFlags & BuildCallbacks.BuildTargetProcessors) == BuildCallbacks.BuildTargetProcessors; bool findFilterProcessors = (findFlags & BuildCallbacks.FilterAssembliesProcessors) == BuildCallbacks.FilterAssembliesProcessors; bool findShaderProcessors = (findFlags & BuildCallbacks.ShaderProcessors) == BuildCallbacks.ShaderProcessors; bool findComputeShaderProcessors = (findFlags & BuildCallbacks.ComputeShaderProcessors) == BuildCallbacks.ComputeShaderProcessors; bool findBuildPlayerScriptDLLsProcessors = (findFlags & BuildCallbacks.BuildPlayerScriptDLLProcessors) == BuildCallbacks.BuildPlayerScriptDLLProcessors; bool findUnityLinkerProcessors = (findFlags & BuildCallbacks.UnityLinkerProcessors) == BuildCallbacks.UnityLinkerProcessors; var postProcessBuildAttributeParams = new Type[] { typeof(BuildTarget), typeof(string) }; foreach (var t in TypeCache.GetTypesDerivedFrom <IOrderedCallback>()) { if (t.IsAbstract || t.IsInterface) { continue; } // Defer creating the instance until we actually add it to one of the lists object instance = null; if (findBuildProcessors) { AddToListIfTypeImplementsInterface(t, ref instance, ref processors.buildPlayerProcessors); AddToListIfTypeImplementsInterface(t, ref instance, ref processors.buildPreprocessors); AddToListIfTypeImplementsInterface(t, ref instance, ref processors.buildPreprocessorsWithReport); AddToListIfTypeImplementsInterface(t, ref instance, ref processors.buildPostprocessors); AddToListIfTypeImplementsInterface(t, ref instance, ref processors.buildPostprocessorsWithReport); } if (findSceneProcessors) { AddToListIfTypeImplementsInterface(t, ref instance, ref processors.sceneProcessors); AddToListIfTypeImplementsInterface(t, ref instance, ref processors.sceneProcessorsWithReport); } if (findTargetProcessors) { AddToListIfTypeImplementsInterface(t, ref instance, ref processors.buildTargetProcessors); } if (findFilterProcessors) { AddToListIfTypeImplementsInterface(t, ref instance, ref processors.filterBuildAssembliesProcessor); } if (findUnityLinkerProcessors) { AddToListIfTypeImplementsInterface(t, ref instance, ref processors.unityLinkerProcessors); } if (findShaderProcessors) { AddToListIfTypeImplementsInterface(t, ref instance, ref processors.shaderProcessors); } if (findComputeShaderProcessors) { AddToListIfTypeImplementsInterface(t, ref instance, ref processors.computeShaderProcessors); } if (findBuildPlayerScriptDLLsProcessors) { AddToListIfTypeImplementsInterface(t, ref instance, ref processors.buildPlayerScriptDLLProcessors); } } if (findBuildProcessors) { foreach (var m in EditorAssemblies.GetAllMethodsWithAttribute <Callbacks.PostProcessBuildAttribute>()) { if (ValidateMethod <Callbacks.PostProcessBuildAttribute>(m, postProcessBuildAttributeParams)) { AddToList(new AttributeCallbackWrapper(m), ref processors.buildPostprocessorsWithReport); } } } if (findSceneProcessors) { foreach (var m in EditorAssemblies.GetAllMethodsWithAttribute <Callbacks.PostProcessSceneAttribute>()) { if (ValidateMethod <Callbacks.PostProcessSceneAttribute>(m, Type.EmptyTypes)) { AddToList(new AttributeCallbackWrapper(m), ref processors.sceneProcessorsWithReport); } } } processors.buildPlayerProcessors?.Sort(CompareICallbackOrder); if (processors.buildPreprocessors != null) { processors.buildPreprocessors.Sort(CompareICallbackOrder); } if (processors.buildPreprocessorsWithReport != null) { processors.buildPreprocessorsWithReport.Sort(CompareICallbackOrder); } if (processors.buildPostprocessors != null) { processors.buildPostprocessors.Sort(CompareICallbackOrder); } if (processors.buildPostprocessorsWithReport != null) { processors.buildPostprocessorsWithReport.Sort(CompareICallbackOrder); } if (processors.buildTargetProcessors != null) { processors.buildTargetProcessors.Sort(CompareICallbackOrder); } if (processors.sceneProcessors != null) { processors.sceneProcessors.Sort(CompareICallbackOrder); } if (processors.sceneProcessorsWithReport != null) { processors.sceneProcessorsWithReport.Sort(CompareICallbackOrder); } if (processors.filterBuildAssembliesProcessor != null) { processors.filterBuildAssembliesProcessor.Sort(CompareICallbackOrder); } if (processors.unityLinkerProcessors != null) { processors.unityLinkerProcessors.Sort(CompareICallbackOrder); } if (processors.shaderProcessors != null) { processors.shaderProcessors.Sort(CompareICallbackOrder); } if (processors.computeShaderProcessors != null) { processors.computeShaderProcessors.Sort(CompareICallbackOrder); } if (processors.buildPlayerScriptDLLProcessors != null) { processors.buildPlayerScriptDLLProcessors.Sort(CompareICallbackOrder); } }
public SaveServiceTests() { _serviceId = Guid.NewGuid(); _serviceVersionedId = Guid.NewGuid(); _channelId = Guid.NewGuid(); _channelVersionedId = Guid.NewGuid(); SetupTypesCacheMock <ServiceType>(); SetupTypesCacheMock <ServiceChargeType>(); var serviceVersioned = new ServiceVersioned { Id = _serviceVersionedId, UnificRootId = _serviceId, UnificRoot = new Model.Models.Service() { Id = _serviceId, ServiceServiceChannels = new List <ServiceServiceChannel>() }, Organization = new Model.Models.Organization() }; var channelVersioned = EntityGenerator.CreateEntity <ServiceChannelVersioned, ServiceChannel, ServiceChannelLanguageAvailability>(PublishedId, _channelId, _channelVersionedId); channelVersioned.UnificRoot = new ServiceChannel { Id = _channelId, Versions = new List <ServiceChannelVersioned> { channelVersioned } }; var connectionList = new List <ServiceServiceChannel> { new ServiceServiceChannel { Service = serviceVersioned.UnificRoot, ServiceId = serviceVersioned.UnificRootId, ServiceChannel = channelVersioned.UnificRoot, ServiceChannelId = channelVersioned.UnificRootId } }; // for PUT/SAVE translationManagerVModelMockSetup.Setup(t => t.Translate <IVmOpenApiServiceInVersionBase, ServiceVersioned>(It.IsAny <IVmOpenApiServiceInVersionBase>(), It.IsAny <IUnitOfWorkWritable>())) .Returns((IVmOpenApiServiceInVersionBase x, IUnitOfWorkWritable y) => { if (!string.IsNullOrEmpty(x.StatutoryServiceGeneralDescriptionId)) { serviceVersioned.StatutoryServiceGeneralDescriptionId = x.StatutoryServiceGeneralDescriptionId.ParseToGuid(); } if (!string.IsNullOrEmpty(x.PublishingStatus)) { serviceVersioned.PublishingStatusId = PublishingStatusCache.Get(x.PublishingStatus); } if (x.ServiceNames?.Count > 0) { serviceVersioned.ServiceNames = new List <ServiceName>(); x.ServiceNames.ForEach(n => serviceVersioned.ServiceNames.Add(new ServiceName { Name = n.Value })); } if (!string.IsNullOrEmpty(x.Type)) { serviceVersioned.TypeId = TypeCache.Get <ServiceType>(x.Type); } if (!string.IsNullOrEmpty(x.ServiceChargeType)) { serviceVersioned.ChargeTypeId = TypeCache.Get <ServiceChargeType>(x.ServiceChargeType); } return(serviceVersioned); }); translationManagerVModelMockSetup.Setup(t => t.Translate <V7VmOpenApiServiceAndChannelRelationAstiInBase, Model.Models.Service>(It.IsAny <V7VmOpenApiServiceAndChannelRelationAstiInBase>(), It.IsAny <IUnitOfWorkWritable>())) .Returns((V7VmOpenApiServiceAndChannelRelationAstiInBase x, IUnitOfWorkWritable y) => { var service = new Model.Models.Service(); if (x.ChannelRelations?.Count > 0) { service.ServiceServiceChannels = new List <ServiceServiceChannel>(); x.ChannelRelations.ForEach(c => { var cv = EntityGenerator.CreateEntity <ServiceChannelVersioned, ServiceChannel, ServiceChannelLanguageAvailability>(PublishedId, c.ChannelGuid, _channelVersionedId); cv.UnificRoot = new ServiceChannel { Id = c.ChannelGuid, Versions = new List <ServiceChannelVersioned> { cv } }; var connection = new ServiceServiceChannel { ServiceChannelId = c.ChannelGuid, ServiceChannel = cv.UnificRoot }; if (c.Description?.Count > 0) { connection.ServiceServiceChannelDescriptions = new List <ServiceServiceChannelDescription>(); c.Description.ForEach(d => { var description = new ServiceServiceChannelDescription { Description = d.Value }; connection.ServiceServiceChannelDescriptions.Add(description); }); service.ServiceServiceChannels.Add(connection); } }); } return(service); }); ServiceRepoMock.Setup(g => g.All()).Returns((new List <ServiceVersioned> { serviceVersioned }).AsQueryable()); ConnectionRepoMock.Setup(g => g.All()).Returns(connectionList.AsQueryable()); unitOfWorkMockSetup.Setup(uw => uw.ApplyIncludes( It.IsAny <IQueryable <ServiceVersioned> >(), It.IsAny <Func <IQueryable <ServiceVersioned>, IQueryable <ServiceVersioned> > >(), It.IsAny <bool>() )).Returns(new List <ServiceVersioned> { serviceVersioned }.AsQueryable()); unitOfWorkMockSetup.Setup(uw => uw.ApplyIncludes( It.IsAny <IQueryable <ServiceServiceChannel> >(), It.IsAny <Func <IQueryable <ServiceServiceChannel>, IQueryable <ServiceServiceChannel> > >(), It.IsAny <bool>() )).Returns(connectionList.AsQueryable()); // for GET translationManagerMockSetup.Setup(t => t.Translate <ServiceVersioned, VmOpenApiServiceVersionBase>(It.IsAny <ServiceVersioned>())) .Returns((ServiceVersioned sv) => { if (sv == null) { return(null); } var vm = new VmOpenApiServiceVersionBase() { Id = sv.UnificRootId, StatutoryServiceGeneralDescriptionId = sv.StatutoryServiceGeneralDescriptionId, }; if (sv.PublishingStatusId.IsAssigned()) { vm.PublishingStatus = PublishingStatusCache.GetByValue(sv.PublishingStatusId); } if (sv.ServiceNames?.Count > 0) { vm.ServiceNames = new List <VmOpenApiLocalizedListItem>(); sv.ServiceNames.ForEach(n => vm.ServiceNames.Add(new VmOpenApiLocalizedListItem { Value = n.Name })); } if (sv.UnificRoot?.ServiceServiceChannels?.Count > 0) { vm.ServiceChannels = new List <V7VmOpenApiServiceServiceChannel>(); sv.UnificRoot.ServiceServiceChannels.ForEach(c => { var channel = new V7VmOpenApiServiceServiceChannel { ServiceChannel = new VmOpenApiItem { Id = c.ServiceChannelId } }; vm.ServiceChannels.Add(channel); }); } return(vm); }); }
/// <summary> /// 更新缓存中的一项 /// </summary> /// <param name="typeKey"></param> /// <param name="obj"></param> /// <param name="c"></param> /// <param name="checkInsert"></param> internal static void UpdateCacheItem <TItem>(string typeKey, TItem obj, ParameCollection c = null, bool checkInsert = false) where TItem : IModel { if (obj == null) { //throw new CRLException("obj is null"); return; } if (!cacheDatas.ContainsKey(typeKey)) { return; } var data = cacheDatas[typeKey].Data as Dictionary <string, TItem>; if (data == null) { return; } var keyValue = obj.GetpPrimaryKeyValue().ToString(); if (!data.ContainsKey(keyValue)) { if (checkInsert) { data.Add(keyValue, obj); } return; } TItem originObj = data[keyValue]; if (c != null)//按更改的值 { var fields = TypeCache.GetProperties(obj.GetType(), true); var Reflection = ReflectionHelper.GetInfo <TItem>(); foreach (var f in c) { //var field = fields.Find(b => b.Name.ToUpper() == f.Key.ToUpper()); var field = fields[f.Key]; if (field == null)//名称带$时不更新 { continue; } //field.TupleSetValue<TItem>(originObj, f.Value); Reflection.GetAccessor(field.MemberName).Set((TItem)originObj, f.Value); } } else//整体更新 { lock (lockObj) { if (originObj != null)//删除原来的 { data.Remove(keyValue); } data.Add(keyValue, obj); } } //CacheUpdated(data.Type.Name); string log = string.Format("更新缓存中的一项 [{0}]", obj.GetModelKey()); CoreHelper.EventLog.Log(log, "DataCache", false); }
public void CanQueryIfTypeHasAttribute() { Assert.That(TypeCache.HasAttribute <int, SerializableAttribute>(), Is.True); Assert.That(TypeCache.HasAttribute <NoAttributes, SerializableAttribute>(), Is.False); Assert.That(TypeCache.HasAttribute <SomeAttributes, SerializableAttribute>(), Is.True); }
/* * Lets say we need access all property getters with array[name] notation */ protected static void InitReflectionChache(Type who) { TypeCache.GetTypeCacheData(who); }
public static void UpdateRpcList() { List <string> additionalRpcs = new List <string>(); List <string> allRpcs = new List <string>(); #if UNITY_2019_2_OR_NEWER // we can make use of the new TypeCache to find methods with PunRPC attribute var extractedMethods = TypeCache.GetMethodsWithAttribute <PunRPC>(); foreach (var methodInfo in extractedMethods) { allRpcs.Add(methodInfo.Name); if (!PhotonNetwork.PhotonServerSettings.RpcList.Contains(methodInfo.Name) && !additionalRpcs.Contains(methodInfo.Name)) { additionalRpcs.Add(methodInfo.Name); } } #else System.Reflection.Assembly[] assemblies = System.AppDomain.CurrentDomain.GetAssemblies().Where(a => !(a.ManifestModule is System.Reflection.Emit.ModuleBuilder)).ToArray(); foreach (var assembly in assemblies) { if (!assembly.Location.Contains("ScriptAssemblies") || assembly.FullName.StartsWith("Assembly-CSharp-Editor")) { continue; } var types = assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(MonoBehaviour))); var methodInfos = types.SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)); var methodNames = methodInfos.Where(m => m.IsDefined(typeof(PunRPC), false)).Select(mi => mi.Name).ToArray(); var additional = methodNames.Where(n => !PhotonNetwork.PhotonServerSettings.RpcList.Contains(n) && !additionalRpcs.Contains(n)); allRpcs.AddRange(methodNames); additionalRpcs.AddRange(additional); } #endif if (additionalRpcs.Count <= 0) { //Debug.Log("UpdateRPCs did not found new."); return; } if (additionalRpcs.Count + PhotonNetwork.PhotonServerSettings.RpcList.Count >= byte.MaxValue) { if (allRpcs.Count <= byte.MaxValue) { bool clearList = EditorUtility.DisplayDialog(CurrentLang.IncorrectRPCListTitle, CurrentLang.IncorrectRPCListLabel, CurrentLang.RemoveOutdatedRPCsLabel, CurrentLang.CancelButton); if (clearList) { PhotonNetwork.PhotonServerSettings.RpcList.Clear(); additionalRpcs = allRpcs.Distinct().ToList(); // we add all unique names } else { return; } } else { EditorUtility.DisplayDialog(CurrentLang.FullRPCListTitle, CurrentLang.FullRPCListLabel, CurrentLang.SkipRPCListUpdateLabel); return; } } additionalRpcs.Sort(); Undo.RecordObject(PhotonNetwork.PhotonServerSettings, "RPC-list update of PUN."); PhotonNetwork.PhotonServerSettings.RpcList.AddRange(additionalRpcs.Distinct().ToList()); PhotonEditor.SaveSettings(); }
private void SerializeContainer(object value, IDataAdapter data, TypeCategory category, Type[] genericArgs) { Type type = value.GetType(); // arrays if (category == TypeCategory.Array) { Array array = (Array)value; Type elementType = type.GetElementType(); int[] coords = new int[array.Rank]; if (array.Rank > 1) { data.AddIntValue(array.Rank, ATTRIBUTE_ARRAY_RANK, true); } SerializeArrayRank(array, elementType, coords, 0, data); haveContainers = true; return; } // dictionaries if (category == TypeCategory.IDictionary) { Type keyType = genericArgs[0]; Type valueType = genericArgs[1]; Func <object, object> getKeyFunc = null; Func <object, object> getValueFunc = null; IDataArray array = data.AddArray(); foreach (object o in (IEnumerable)value) { if (getKeyFunc == null) { Type objectType = o.GetType(); if (!TypeCache.TryGetNamedAccessor(objectType, "Key", ref getKeyFunc)) { getKeyFunc = InvocationHelper.CreateGetDelegate(o.GetType(), keyType, objectType.GetProperty("Key").GetMethod); TypeCache.AddTypeNamedAccessor(objectType, "Key", getKeyFunc); } if (!TypeCache.TryGetNamedAccessor(objectType, "Value", ref getValueFunc)) { getValueFunc = InvocationHelper.CreateGetDelegate(o.GetType(), valueType, objectType.GetProperty("Value").GetMethod); TypeCache.AddTypeNamedAccessor(objectType, "Value", getValueFunc); } } IDataAdapter itemEl = array.AddArrayValue(); SerializeSubValue(keyType, getKeyFunc(o), itemEl.AddChild(settings.DictionaryKeyName), null); SerializeSubValue(valueType, getValueFunc(o), itemEl.AddChild(settings.DictionaryValueName), null); } haveContainers = true; return; } // generics if (category == TypeCategory.GenericIList || category == TypeCategory.ISet || category == TypeCategory.GenericQueue || category == TypeCategory.GenericStack || category == TypeCategory.LinkedList) { SerializeContainer((IEnumerable)value, genericArgs[0], data); return; } // non-generic versions if (category == TypeCategory.IList || category == TypeCategory.Queue || category == TypeCategory.Stack) { SerializeContainer((IEnumerable)value, typeof(object), data); return; } }
/// Purpose. /// This is generic selection menu. /// Filtering. /// You can add substring filter here to filter by search string. /// As well ass type or interface restrictions. /// As well as any custom restriction that is based on input type. /// And it will be performed on each Appropriate type found by TypeCache. public static void ShowContextMenuForManagedReference(this SerializedProperty property, IEnumerable <Func <Type, bool> > filters = null) { var context = new GenericMenu(); FillContextMenu(); context.ShowAsContext(); void FillContextMenu() { context.AddItem(new GUIContent("Null"), false, MakeNull); Type realPropertyType = SerializeReferenceTypeNameUtility.GetRealTypeFromTypename(property.managedReferenceFieldTypename); if (realPropertyType == null) { Debug.LogError("Can not get type from"); return; } TypeCache.TypeCollection types = TypeCache.GetTypesDerivedFrom(realPropertyType); foreach (Type type in types) { // Skips unity engine Objects (because they are not serialized by SerializeReference) if (type.IsSubclassOf(typeof(UnityEngine.Object))) { continue; } // Skip abstract classes because they should not be instantiated if (type.IsAbstract) { continue; } if (FilterTypeByFilters(filters, type) == false) { continue; } AddContextMenu(type, context); } void MakeNull() { property.serializedObject.Update(); property.managedReferenceValue = null; property.serializedObject.ApplyModifiedPropertiesWithoutUndo(); // undo is bugged for now } void AddContextMenu(Type type, GenericMenu genericMenuContext) { string assemblyName = type.Assembly.ToString().Split('(', ',')[0]; string entryName = type + " ( " + assemblyName + " )"; genericMenuContext.AddItem(new GUIContent(entryName), false, AssignNewInstanceOfType, type); } void AssignNewInstanceOfType(object typeAsObject) { var type = (Type)typeAsObject; object instance = Activator.CreateInstance(type); property.serializedObject.Update(); property.managedReferenceValue = instance; property.serializedObject.ApplyModifiedPropertiesWithoutUndo(); // undo is bugged for now } bool FilterTypeByFilters(IEnumerable <Func <Type, bool> > filters_, Type type) => filters_.All(f => f.Invoke(type)); } }
//^ requires peFileReader.IsAssembly ==> moduleIdentity.ContainingAssembly != null; //^ requires peFileReader.IsAssembly ==> containingAssembly == null; //^ requires !(moduleIdentity.Location != null && moduleIdentity.Location.Length != 0); /*^ #pragma warning disable 2666, 2669, 2677, 2674 ^*/ internal PEFileToObjectModel( PeReader peReader, PEFileReader peFileReader, ModuleIdentity moduleIdentity, Assembly/*?*/ containingAssembly, byte pointerSize ) { this.pointerSize = pointerSize; this.ModuleReader = peReader; this.PEFileReader = peFileReader; this.NameTable = peReader.metadataReaderHost.NameTable; this.StringIndexToNameTable = new Hashtable<IName>(); this.StringIndexToUnmangledNameTable = new Hashtable<IName>(); this.typeCache = new TypeCache(this); uint moduleNameOffset = peFileReader.ModuleTable.GetName(1); IName moduleName = this.GetNameFromOffset(moduleNameOffset); AssemblyIdentity/*?*/ assemblyIdentity = moduleIdentity as AssemblyIdentity; if (peFileReader.IsAssembly) { //^ assert assemblyIdentity != null; AssemblyRow assemblyRow = peFileReader.AssemblyTable[1]; IName assemblyName = this.GetNameFromOffset(assemblyRow.Name); byte[] publicKeyArray = TypeCache.EmptyByteArray; if (assemblyRow.PublicKey != 0) { publicKeyArray = peFileReader.BlobStream[assemblyRow.PublicKey]; } uint internedModuleId = (uint)peReader.metadataReaderHost.InternFactory.GetAssemblyInternedKey(assemblyIdentity); Assembly assem = new Assembly(this, moduleName, peFileReader.COR20Header.COR20Flags, internedModuleId, assemblyIdentity, assemblyName, assemblyRow.Flags, publicKeyArray); this.ContainingAssembly = assem; this.Module = assem; } else { uint internedModuleId = (uint)peReader.metadataReaderHost.InternFactory.GetModuleInternedKey(moduleIdentity); this.ContainingAssembly = containingAssembly; this.Module = new Module(this, moduleName, peFileReader.COR20Header.COR20Flags, internedModuleId, moduleIdentity); } this.LoadAssemblyReferences(); this.LoadModuleReferences(); this.RootModuleNamespace = new RootNamespace(this); this.NamespaceINameHashtable = new Hashtable<Namespace>(); this.LoadNamespaces(); this.NamespaceReferenceINameHashtable = new DoubleHashtable<NamespaceReference>(); this.NamespaceTypeTokenTable = new DoubleHashtable(peFileReader.TypeDefTable.NumberOfRows + peFileReader.ExportedTypeTable.NumberOfRows); this.NestedTypeTokenTable = new DoubleHashtable(peFileReader.NestedClassTable.NumberOfRows + peFileReader.ExportedTypeTable.NumberOfRows); this.PreLoadTypeDefTableLookup(); this.ModuleTypeDefArray = new TypeBase/*?*/[peFileReader.TypeDefTable.NumberOfRows + 1]; this.ModuleTypeDefLoadState = new LoadState[peFileReader.TypeDefTable.NumberOfRows + 1]; this.ModuleTypeDefLoadState[0] = LoadState.Loaded; this.ExportedTypeArray = new ExportedTypeAliasBase/*?*/[peFileReader.ExportedTypeTable.NumberOfRows + 1]; this.ExportedTypeLoadState = new LoadState[peFileReader.ExportedTypeTable.NumberOfRows + 1]; this.ExportedTypeLoadState[0] = LoadState.Loaded; this.ModuleGenericParamArray = new GenericParameter[peFileReader.GenericParamTable.NumberOfRows + 1]; if (peFileReader.MethodSpecTable.NumberOfRows > 0) { this.ModuleMethodSpecHashtable = new DoubleHashtable<GenericMethodInstanceReference>(peFileReader.MethodSpecTable.NumberOfRows + 1); } this.ModuleTypeRefReferenceArray = new TypeRefReference[peFileReader.TypeRefTable.NumberOfRows + 1]; this.ModuleTypeRefReferenceLoadState = new LoadState[peFileReader.TypeRefTable.NumberOfRows + 1]; this.ModuleTypeRefReferenceLoadState[0] = LoadState.Loaded; if (peFileReader.TypeSpecTable.NumberOfRows > 0) { this.ModuleTypeSpecHashtable = new DoubleHashtable<TypeSpecReference>(peFileReader.TypeSpecTable.NumberOfRows + 1); } this.ModuleFieldArray = new FieldDefinition[peFileReader.FieldTable.NumberOfRows + 1]; this.ModuleMethodArray = new MethodDefinition[peFileReader.MethodTable.NumberOfRows + 1]; this.ModuleEventArray = new EventDefinition[peFileReader.EventTable.NumberOfRows + 1]; this.ModulePropertyArray = new PropertyDefinition[peFileReader.PropertyTable.NumberOfRows + 1]; this.ModuleMemberReferenceArray = new MemberReference/*?*/[peFileReader.MemberRefTable.NumberOfRows + 1]; this.CustomAttributeArray = new ICustomAttribute/*?*/[peFileReader.CustomAttributeTable.NumberOfRows + 1]; this.DeclSecurityArray = new ISecurityAttribute/*?*/[peFileReader.DeclSecurityTable.NumberOfRows + 1]; uint moduleClassTypeDefToken = this.NamespaceTypeTokenTable.Find((uint)this.NameTable.EmptyName.UniqueKey, (uint)peReader._Module_.UniqueKey); _Module_Type/*?*/ _module_ = null; if (moduleClassTypeDefToken != 0 && ((TokenTypeIds.TokenTypeMask & moduleClassTypeDefToken) == TokenTypeIds.TypeDef)) { _module_ = this.Create_Module_Type(moduleClassTypeDefToken & TokenTypeIds.RIDMask); } if (_module_ == null) { // Error throw new MetadataReaderException("<Module> Type not present"); } this._Module_ = _module_; //^ NonNullType.AssertInitialized(this.ModuleGenericParamArray); //^ NonNullType.AssertInitialized(this.ModuleTypeRefReferenceArray); //^ NonNullType.AssertInitialized(this.ModuleFieldArray); //^ NonNullType.AssertInitialized(this.ModuleMethodArray); //^ NonNullType.AssertInitialized(this.ModuleEventArray); //^ NonNullType.AssertInitialized(this.ModulePropertyArray); }
private static void InitializeWorker(CompilationStartAnalysisContext compilationStartAnalysisContext, TypeCache typeCache) { compilationStartAnalysisContext.RegisterSymbolAction(symbolAnalysisContext => { var method = (IMethodSymbol)symbolAnalysisContext.Symbol; var declaringType = method.ContainingType; if (!IsPageModel(declaringType, typeCache.PageModelAttribute) || !IsPageHandlerMethod(method)) { return; } ReportFilterDiagnostic(ref symbolAnalysisContext, method, typeCache.IFilterMetadata); ReportFilterDiagnostic(ref symbolAnalysisContext, method, typeCache.AuthorizeAttribute); ReportFilterDiagnostic(ref symbolAnalysisContext, method, typeCache.AllowAnonymousAttribute); ReportRouteDiagnostic(ref symbolAnalysisContext, method, typeCache.IRouteTemplateProvider); }, SymbolKind.Method); compilationStartAnalysisContext.RegisterSymbolAction(symbolAnalysisContext => { var type = (INamedTypeSymbol)symbolAnalysisContext.Symbol; if (!IsPageModel(type, typeCache.PageModelAttribute)) { return; } ReportRouteDiagnosticOnModel(ref symbolAnalysisContext, type, typeCache.IRouteTemplateProvider); }, SymbolKind.NamedType); }
public BondDynamicDriver() { _typeCache = new TypeCache(); }
protected AdvancedDropdownItem RebuildTree() { m_SearchableElements = new List <AdvancedDropdownItem>(); AdvancedDropdownItem root = new PresetTypeDropdownItem(L10n.Tr("Add Default Type")); var type = UnityType.FindTypeByName("AssetImporter"); var presetTypes = UnityType.GetTypes() .Where(t => t.IsDerivedFrom(type) && !t.isAbstract) .Select(t => new PresetType(t.persistentTypeID)) .Union( TypeCache.GetTypesDerivedFrom <ScriptedImporter>() .Where(t => !t.IsAbstract) .Select(t => new PresetType(t)) ) .Distinct() .Where(pt => pt.IsValidDefault()); // Add Importers var importersRoot = new PresetTypeDropdownItem(L10n.Tr("Importer")); root.AddChild(importersRoot); foreach (var presetType in presetTypes) { var menuPath = presetType.GetManagedTypeName(); var paths = menuPath.Split('.').Last(); var parent = importersRoot; var element = new PresetTypeDropdownItem(paths, presetType); parent.AddChild(element); m_SearchableElements.Add(element); } // Add Components var menuDictionary = GetMenuDictionary(); menuDictionary.Sort(CompareItems); for (var i = 0; i < menuDictionary.Count; i++) { var menu = menuDictionary[i]; if (menu.Value == "ADD") { continue; } var menuPath = menu.Key; var paths = menuPath.Split('/'); var parent = root; for (var j = 0; j < paths.Length; j++) { var path = paths[j]; if (j == paths.Length - 1) { var element = new PresetTypeDropdownItem(path, menu.Value); parent.AddChild(element); m_SearchableElements.Add(element); continue; } var group = (PresetTypeDropdownItem)parent.children.SingleOrDefault(c => c.name == path); if (group == null) { group = new PresetTypeDropdownItem(path); parent.AddChild(group); } parent = group; } } return(root); }
private object FetchValue(Element item, string attributeName, string elementName, string query, bool arePersistentObjects, bool attach, TypeCache typeCache, TypeConverter typeConverter, Cache cache) { object value = null; if (!String.IsNullOrEmpty(attributeName)) { Node.Attribute attribute = item.Attribute(attributeName); value = attribute == null ? null : GetObjectFromString(attribute.Value, null, null, typeCache.Type, typeConverter); } else { object result = !String.IsNullOrEmpty(query) ? item.EvalSingle(query) : item.Children.OfType<Element>().FirstOrDefault(e => e.Name.Equals(elementName)); if (arePersistentObjects) { // Get, attach, and fetch the persistent object instance Element element = result as Element; if (element == null) throw new Exception("Persistent value node must be an element."); value = cache.GetObject(typeCache, element, attach); } else { Node.Node itemNode = result as Node.Node; value = GetObjectFromString(itemNode != null ? itemNode.Value : result == null ? null : result.ToString(), null, null, typeCache.Type, typeConverter); } } return value; }
/// <summary> /// 检查表是否被创建 /// </summary> internal override void CheckTableCreated(Type type) { if (!SettingConfig.CheckModelTableMaping) { return; } //if (!type.IsSubclassOf(typeof(IModel))) //{ // return; //} bool a1; var typeKey = type + "|" + DatabaseName; var a = tableCheckedCache.TryGetValue(typeKey, out a1); if (a && a1) { return; } tableCheckedCache.TryAdd(typeKey, false); //TypeCache.SetDBAdapterCache(type, _DBAdapter); var dbName = DatabaseName; var cacheInstance = CRL.ExistsTableCache.ExistsTableCache.Instance; var table = TypeCache.GetTable(type); AbsDBExtend db; if (!cacheInstance.DataBase.ContainsKey(dbName)) { db = GetBackgroundDBExtend(); #region 初始表 lock (lockObj) { //BackupParams(); string sql = _DBAdapter.GetAllTablesSql(); var dic = db.ExecDictionary <string, int>(sql); //RecoveryParams(); cacheInstance.InitTable(dbName, dic.Keys.ToList()); } #endregion } var tableName = TypeCache.GetTableName(table.TableName, dbContext); var tb = cacheInstance.GetTable(dbName, tableName); if (tb == null)//没有创建表 { db = GetBackgroundDBExtend(); #region 创建表 //BackupParams(); var obj = System.Activator.CreateInstance(type) as IModel; var initDatas = obj.GetInitData(); if (initDatas != null) { foreach (IModel item in initDatas) { CheckData(item); } } string msg; ModelCheck.CreateTable(type, db, out msg); cacheInstance.SaveTable(dbName, table, tableName); if (initDatas != null) { _DBAdapter.BatchInsert(initDatas, false); } tableCheckedCache[typeKey] = true; return; #endregion } if (tb.ColumnChecked) { tableCheckedCache[typeKey] = true; return; } //从本地缓存判断字段是否一致 var needCreates = CRL.ExistsTableCache.ExistsTableCache.Instance.CheckFieldExists(dbName, table, tableName); if (needCreates.Count > 0) { db = GetBackgroundDBExtend(); #region 创建列 //BackupParams(); foreach (var item in needCreates) { ModelCheck.SetColumnDbType(_DBAdapter, item); try { string str = ModelCheck.CreateColumn(db, item); } catch { } } //RecoveryParams(); #endregion } //二次检查从数据库,对照表结构 if (!tb.ColumnChecked2) { var db2 = copyDBExtend(); ExistsTableCache.ColumnBackgroundCheck.Add(db2, type); tb.ColumnChecked2 = true; } tableCheckedCache[typeKey] = true; }
internal override void StoreValue(Element element, object serialized, object source, TypeCache typeCache, Cache cache) { Node.Node node = element.EvalSingle(Query) as Node.Node; string value = (string) serialized; if (node == null && value != null && !String.IsNullOrEmpty(CreateQuery)) { element.Eval(CreateQuery); node = element.EvalSingle(Query) as Node.Node; } else if (node != null && value == null) { node.Remove(); return; } if (node != null) { node.Value = value; } }
internal override object FetchValue(Element element, object target, TypeCache typeCache, Cache cache) { // Get the primary element Element child; if (!GetNodeFromQuery(Query, null, element, out child)) { child = element.Children.OfType<Element>().Where(e => e.Name.Equals(Name)).FirstOrDefault(); } if (child == null) { return null; } // Get all the item nodes IList<object> items = new List<object>(!String.IsNullOrEmpty(ItemQuery) ? child.Eval(ItemQuery) : child.Children.OfType<Element>().Where(e => e.Name.Equals(ItemName)).Cast<object>()); // Create the collection (or reuse it if appropriate) object collection = _getCollection(target, items.Count); // Populate with values int c = 0; foreach(object item in items) { if(ItemsArePersistentObjects) { // Get, attach, and fetch the persistent object instance Element itemElement = item as Element; if (itemElement == null) throw new Exception("Persistent value node must be an element."); object itemObject = cache.GetObject(_itemTypeCache, itemElement, AttachItems); if(itemObject != null) _setCollectionItem(collection, c++, itemObject); } else { Node.Node itemNode = item as Node.Node; object itemObject = GetObjectFromString( itemNode != null ? itemNode.Value : item.ToString(), null, null, _itemTypeCache.Type, _itemTypeConverter); if (itemObject != null) _setCollectionItem(collection, c++, itemObject); } } return collection; }
public MediumTrustTypeFinder(TypeCache assemblyCache, EngineSection engineConfiguration) : base(assemblyCache, engineConfiguration) { this.engineConfiguration = engineConfiguration; }
internal override object SerializeValue(object source, TypeCache typeCache, Cache cache) { if (!String.IsNullOrEmpty(ItemQuery)) throw new Exception("Can not store persistent collection that uses queries."); // Key = source object, Value = serialized data List<KeyValuePair<object, object>> values = new List<KeyValuePair<object, object>>(); // Iterate over the source object if (source != null) { IEnumerable items = (IEnumerable) source; foreach (object item in items) { object value = ItemsArePersistentObjects ? _itemTypeCache.Persister.Serialize(item, _itemTypeCache, cache) : GetStringFromObject(item, _itemTypeCache.Type, _itemTypeConverter); values.Add(new KeyValuePair<object, object>(item, value)); } } return values; }
/*^ #pragma warning disable 2666, 2669, 2677, 2674 ^*/ internal PEFileToObjectModel( PeReader peReader, PEFileReader peFileReader, ModuleIdentity moduleIdentity, Assembly/*?*/ containingAssembly, byte pointerSize ) //^ requires peFileReader.IsAssembly ==> moduleIdentity.ContainingAssembly != null; //^ requires peFileReader.IsAssembly ==> containingAssembly == null; //^ requires !(moduleIdentity.Location != null && moduleIdentity.Location.Length != 0); { this.pointerSize = pointerSize; this.document = new MetadataObjectDocument(this); this.ModuleReader = peReader; this.PEFileReader = peFileReader; this.NameTable = peReader.metadataReaderHost.NameTable; this.InternFactory = peReader.metadataReaderHost.InternFactory; this.StringIndexToNameTable = new Hashtable<IName>(); this.StringIndexToUnmangledNameTable = new Hashtable<IName>(); this.typeCache = new TypeCache(this); uint moduleNameOffset = peFileReader.ModuleTable.GetName(1); IName moduleName = this.GetNameFromOffset(moduleNameOffset); AssemblyIdentity/*?*/ assemblyIdentity = moduleIdentity as AssemblyIdentity; if (peFileReader.IsAssembly) { //^ assert assemblyIdentity != null; AssemblyRow assemblyRow = peFileReader.AssemblyTable[1]; IName assemblyName = this.GetNameFromOffset(assemblyRow.Name); byte[] publicKeyArray = TypeCache.EmptyByteArray; if (assemblyRow.PublicKey != 0) { publicKeyArray = peFileReader.BlobStream[assemblyRow.PublicKey]; } uint internedModuleId = (uint)peReader.metadataReaderHost.InternFactory.GetAssemblyInternedKey(assemblyIdentity); Assembly assem = new Assembly(this, moduleName, peFileReader.COR20Header.COR20Flags, internedModuleId, assemblyIdentity, assemblyName, assemblyRow.Flags, publicKeyArray); this.ContainingAssembly = assem; this.Module = assem; } else { uint internedModuleId = (uint)peReader.metadataReaderHost.InternFactory.GetModuleInternedKey(moduleIdentity); this.ContainingAssembly = containingAssembly; this.Module = new Module(this, moduleName, peFileReader.COR20Header.COR20Flags, internedModuleId, moduleIdentity); } this.LoadAssemblyReferences(); this.LoadModuleReferences(); this.RootModuleNamespace = new RootNamespace(this); this.NamespaceINameHashtable = new Hashtable<Namespace>(); this.LoadNamespaces(); this.NamespaceReferenceINameHashtable = new DoubleHashtable<NamespaceReference>(); this.NamespaceTypeTokenTable = new DoubleHashtable(peFileReader.TypeDefTable.NumberOfRows + peFileReader.ExportedTypeTable.NumberOfRows); this.NestedTypeTokenTable = new DoubleHashtable(peFileReader.NestedClassTable.NumberOfRows + peFileReader.ExportedTypeTable.NumberOfRows); this.PreLoadTypeDefTableLookup(); this.ModuleTypeDefArray = new TypeBase/*?*/[peFileReader.TypeDefTable.NumberOfRows + 1]; this.ModuleTypeDefLoadState = new LoadState[peFileReader.TypeDefTable.NumberOfRows + 1]; this.RedirectedTypeDefArray = new INamedTypeReference/*?*/[peFileReader.TypeDefTable.NumberOfRows + 1]; this.ModuleTypeDefLoadState[0] = LoadState.Loaded; this.ExportedTypeArray = new ExportedTypeAliasBase/*?*/[peFileReader.ExportedTypeTable.NumberOfRows + 1]; this.ExportedTypeLoadState = new LoadState[peFileReader.ExportedTypeTable.NumberOfRows + 1]; this.ExportedTypeLoadState[0] = LoadState.Loaded; this.ModuleGenericParamArray = new GenericParameter[peFileReader.GenericParamTable.NumberOfRows + 1]; if (peFileReader.MethodSpecTable.NumberOfRows > 0) { this.ModuleMethodSpecHashtable = new DoubleHashtable<IGenericMethodInstanceReference>(peFileReader.MethodSpecTable.NumberOfRows + 1); } this.ModuleTypeRefReferenceArray = new INamedTypeReference[peFileReader.TypeRefTable.NumberOfRows + 1]; this.ModuleTypeRefReferenceLoadState = new LoadState[peFileReader.TypeRefTable.NumberOfRows + 1]; this.ModuleTypeRefReferenceLoadState[0] = LoadState.Loaded; if (peFileReader.TypeSpecTable.NumberOfRows > 0) { this.ModuleTypeSpecHashtable = new DoubleHashtable<TypeSpecReference>(peFileReader.TypeSpecTable.NumberOfRows + 1); } this.ModuleFieldArray = new FieldDefinition[peFileReader.FieldTable.NumberOfRows + 1]; this.ModuleMethodArray = new IMethodDefinition[peFileReader.MethodTable.NumberOfRows + 1]; this.ModuleEventArray = new EventDefinition[peFileReader.EventTable.NumberOfRows + 1]; this.ModulePropertyArray = new PropertyDefinition[peFileReader.PropertyTable.NumberOfRows + 1]; this.ModuleMemberReferenceArray = new MemberReference/*?*/[peFileReader.MemberRefTable.NumberOfRows + 1]; this.UnspecializedMemberReferenceArray = new MemberReference/*?*/[peFileReader.MemberRefTable.NumberOfRows + 1]; this.SpecializedFieldHashtable = new DoubleHashtable<ISpecializedFieldReference>(); this.SpecializedMethodHashtable = new DoubleHashtable<ISpecializedMethodReference>(); this.CustomAttributeArray = new ICustomAttribute/*?*/[peFileReader.CustomAttributeTable.NumberOfRows + 1]; this.DeclSecurityArray = new ISecurityAttribute/*?*/[peFileReader.DeclSecurityTable.NumberOfRows + 1]; this._Module_ = this.Create_Module_Type(); }
internal override void StoreValue(Element element, object serialized, object source, TypeCache typeCache, Cache cache) { Text child; if (!GetNodeFromQuery(Query, CreateQuery, element, out child)) { child = element.Children.OfType<Text>().FirstOrDefault(); } else if (child == null) { return; } string value = (string) serialized; if (child == null && value != null) { element.Append(new Text(value)); } else if (child != null && value == null) { child.Remove(); } else if (child != null) { child.Value = value; } }
private void FlattenProperies <T>(Dictionary <string, object> dic, string prefix, T @object, FlattenMemberType memberType, Type type) { if (_knownTypes.Contains(type) || (_doNotFlattenTypes != null && _doNotFlattenTypes.Contains(type))) { // Property directly dic.Add(prefix, @object); return; } prefix = string.IsNullOrWhiteSpace(prefix) ? "" : prefix + "."; var properties = TypeCache.GetProperties(type, BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public); foreach (var property in properties) { var pt = property.PropertyType; var key = prefix + property.Name; var ptil = TypeCache.GetInterfaces(pt); if (_knownTypes.Contains(pt) || _knownTypes.ContainsRange(ptil) || // Quick lookup for known types (_doNotFlattenTypes != null && (_doNotFlattenTypes.Contains(pt) && _doNotFlattenTypes.ContainsRange(ptil))) || TypeCache.GetDoNotFlattenAttribute(property) // Or with DoNotFlattenAttribute //|| property.PropertyType.GetGenericTypeDefinition() ) { // Property directly var dval = property.GetValue(@object); dic.Add(key, dval); continue; } if (pt.IsArray) { var list = (object[])property.GetValue(@object); for (var c = 0; c < list.Length; c++) { ToFlatDictionaryInt(dic, $"{key}[{c}]", list[c], memberType); } continue; } if (ptil.Contains(typeof(IList))) { var list = (IList)property.GetValue(@object); for (var c = 0; c < list.Count; c++) { ToFlatDictionaryInt(dic, $"{key}[{c}]", list[c], memberType); } continue; } if (ptil.Contains(typeof(IEnumerable))) { var c = 0; foreach (var e in (IEnumerable)property.GetValue(@object)) { ToFlatDictionaryInt(dic, $"{key}[{c}]", e, memberType); c++; } continue; } var val = property.GetValue(@object); // Go into property ToFlatDictionaryInt(dic, key, val, memberType); } }
public static Type ParseType(XAttribute attribute) { return(attribute != null?TypeCache.GetType(attribute.Value) : null); }
internal override void Inititalize(Type memberType, string memberName, Cache cache) { base.Inititalize(memberType, memberName, cache); Name = GetName(Name, memberName, Query, CreateQuery); ItemName = GetName(ItemName, "Item", ItemQuery); // Get the TypeConverter if(ItemTypeConverter != null) { if (ItemsArePersistentObjects) throw new Exception("A TypeConverter can not be specified for persistent member objects."); _itemTypeConverter = InitializeTypeConverter(ItemTypeConverter); } // Resolve the type of collection and the item type if (memberType.IsArray) { // It's an array, get the array item type Type itemType = memberType.GetElementType(); if (itemType == null) { throw new Exception("Could not determine array item type."); } if (ItemType == null) { ItemType = itemType; } else if (!itemType.IsAssignableFrom(ItemType)) { throw new Exception("The specified ItemType must be assignable to the array type."); } _getCollection = (c, s) => { if (c == null || ((Array)c).Length != s) return Array.CreateInstance(ItemType, s); return c; }; _setCollectionItem = (c, i, v) => ((Array)c).SetValue(v, (Int64)i); } else { // Not an array, check interfaces List<Type> collectionInterfaces = new List<Type>(memberType.GetInterfaces() .Where(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(ICollection<>))); if (collectionInterfaces.Count > 0) { // The member implements ICollection<T>, verify the ItemType (if specified) is compatable Type collectionType = null; foreach (Type collectionInterface in collectionInterfaces) { Type itemType = collectionInterface.GetGenericArguments()[0]; if (ItemType == null || itemType.IsAssignableFrom(ItemType)) { if(ItemType == null) ItemType = itemType; collectionType = collectionInterface; break; } } // Make sure we got an item type if (collectionType == null) throw new Exception("No appropriate item type could be found."); // Get the constructor and add functions ConstructorInfo constructor = memberType.GetConstructor(Type.EmptyTypes); if (constructor == null) throw new Exception("Persistent collection member must implement an empty constructor."); MethodInfo clearMethod = collectionType.GetMethod("Clear"); _getCollection = (c, s) => { if (c == null) return constructor.Invoke(null); clearMethod.Invoke(c, null); return c; }; MethodInfo addMethod = collectionType.GetMethod("Add"); _setCollectionItem = (c, i, v) => addMethod.Invoke(c, new[] {v}); } else if (typeof(IList).IsAssignableFrom(memberType)) { // The member implements IList if (ItemType == null) throw new Exception("A persistent collection that implements IList must provide an ItemType."); ConstructorInfo constructor = memberType.GetConstructor(Type.EmptyTypes); if (constructor == null) throw new Exception("Persistent collection member must implement an empty constructor."); _getCollection = (c, s) => { if( c == null) return constructor.Invoke(null); ((IList) c).Clear(); return c; }; _setCollectionItem = (c, i, v) => ((IList) c).Add(v); } else { throw new Exception("Persistent collection member must be an array, implement ICollection<T>, or implement IList."); } } _itemTypeCache = cache.GetTypeCache(ItemType); }
public static void GenerateAll() { s_TypeName = new Dictionary <string, ShaderTypeGenerator>(); // Iterate over assemblyList, discover all applicable types with fully qualified names var assemblyList = AppDomain.CurrentDomain.GetAssemblies() // We need to exclude dynamic assemblies (their type can't be queried, throwing an exception below) .Where(ass => !(ass.ManifestModule is System.Reflection.Emit.ModuleBuilder)) .ToList(); foreach (var type in TypeCache.GetTypesWithAttribute <GenerateHLSL>()) { var attr = type.GetCustomAttributes(typeof(GenerateHLSL), false).First() as GenerateHLSL; ShaderTypeGenerator gen; if (s_TypeName.TryGetValue(type.FullName, out gen)) { Debug.LogError("Duplicate typename with the GenerateHLSL attribute detected: " + type.FullName + " declared in both " + gen.type.Assembly.FullName + " and " + type.Assembly.FullName + ". Skipping the second instance."); } s_TypeName[type.FullName] = new ShaderTypeGenerator(type, attr); } // Now that we have extracted all the typenames that we care about, parse all .cs files in all asset // paths and figure out in which files those types are actually declared. s_SourceGenerators = new Dictionary <string, List <ShaderTypeGenerator> >(); var assetPaths = AssetDatabase.GetAllAssetPaths().Where(s => s.EndsWith(".cs")).ToList(); foreach (var assetPath in assetPaths) { LoadTypes(assetPath); } // Finally, write out the generated code foreach (var it in s_SourceGenerators) { string fileName = it.Key + ".hlsl"; bool skipFile = false; foreach (var gen in it.Value) { if (!gen.Generate()) { // Error reporting will be done by the generator. Skip this file. gen.PrintErrors(); skipFile = true; break; } } if (!skipFile && File.Exists(fileName)) { FileInfo info = null; try { info = new FileInfo(fileName); } catch (UnauthorizedAccessException) { Debug.Log("Access to " + fileName + " is denied. Skipping it."); skipFile = true; } catch (System.Security.SecurityException) { Debug.Log("You do not have permission to access " + fileName + ". Skipping it."); skipFile = true; } if (info?.IsReadOnly ?? false) { Debug.Log(fileName + " is ReadOnly. Skipping it."); skipFile = true; } } if (skipFile) { continue; } using (var writer = File.CreateText(fileName)) { writer.NewLine = Environment.NewLine; var guard = Path.GetFileName(fileName).Replace(".", "_").ToUpper(); if (!char.IsLetter(guard[0])) { guard = "_" + guard; } writer.WriteLine("//"); writer.WriteLine("// This file was automatically generated. Please don't edit by hand."); writer.WriteLine("//"); writer.WriteLine(); writer.WriteLine("#ifndef " + guard); writer.WriteLine("#define " + guard); foreach (var gen in it.Value) { if (gen.hasStatics) { writer.WriteLine(gen.EmitDefines().Replace("\n", writer.NewLine)); } } foreach (var gen in it.Value) { if (gen.hasFields) { writer.WriteLine(gen.EmitTypeDecl().Replace("\n", writer.NewLine)); } } foreach (var gen in it.Value) { if (gen.hasFields && gen.needAccessors && !gen.hasPackedInfo) { writer.Write(gen.EmitAccessors().Replace("\n", writer.NewLine)); writer.Write(gen.EmitSetters().Replace("\n", writer.NewLine)); const bool emitInitters = true; writer.Write(gen.EmitSetters(emitInitters).Replace("\n", writer.NewLine)); } } foreach (var gen in it.Value) { if (gen.hasStatics && gen.hasFields && gen.needParamDebug && !gen.hasPackedInfo) { writer.WriteLine(gen.EmitFunctions().Replace("\n", writer.NewLine)); } } foreach (var gen in it.Value) { if (gen.hasPackedInfo) { writer.WriteLine(gen.EmitPackedInfo().Replace("\n", writer.NewLine)); } } writer.WriteLine(); writer.WriteLine("#endif"); var customFile = it.Key + ".custom.hlsl"; if (File.Exists(customFile)) { writer.Write("#include \"{0}\"", Path.GetFileName(customFile)); } } } }
internal override void StoreValue(Element element, object serialized, object source, TypeCache typeCache, Cache cache) { if (!String.IsNullOrEmpty(ItemQuery)) throw new Exception("Can not store persistent collection that uses queries."); // Get the child element Element child; if (!GetNodeFromQuery(Query, CreateQuery, element, out child)) { child = element.Children.OfType<Element>().Where(e => e.Name.Equals(Name)).FirstOrDefault(); } else if (child == null) { return; } // Create or remove the child if needed if (child == null && serialized != null) { element.Append(new Element(Name)); child = (Element)element.Children.Last(); } else if (child != null && serialized == null) { child.Remove(); return; } else if (child == null) { return; } // Remove all elements with the item name List<Element> removeElements = child.Children.OfType<Element>() .Where(e => e.Name == ItemName).ToList(); foreach (Element removeElement in removeElements) { removeElement.Remove(); } // Store all items foreach (KeyValuePair<object, object> kvp in (IEnumerable<KeyValuePair<object, object>>) serialized) { child.Append(new Element(ItemName)); Element itemElement = (Element) child.Children.Last(); if (ItemsArePersistentObjects) { _itemTypeCache.Persister.Store(itemElement, kvp.Value, kvp.Key, _itemTypeCache, cache); } else { itemElement.Value = (string) kvp.Value; } } }
internal static Type[] GetAllDerivedTypes(this AppDomain aAppDomain, Type aType) { return(TypeCache.GetTypesDerivedFrom(aType).ToArray()); }
internal static IEnumerable <MethodInfo> GetAllMethodsWithAttribute <T>(BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) where T : System.Attribute { return(TypeCache.GetMethodsWithAttribute <T>()); }
internal static IEnumerable <MethodInfo> GetAllMethodsWithAttribute(Type attributeType) { return(TypeCache.GetMethodsWithAttribute(attributeType)); }
internal override void StoreValue(Element element, object serialized, object source, TypeCache typeCache, Cache cache) { Node.Attribute attribute; if (!GetNodeFromQuery(Query, CreateQuery, element, out attribute)) { attribute = element.Attribute(Name); } else if (attribute == null) { return; } string value = (string) serialized; if (attribute == null && value != null) { element.InsertAttribute(Name, value); } else if (attribute != null && value == null) { attribute.Remove(); } else if (attribute != null) { attribute.Value = value; } }
public static Type GetTypeFromName(string typeName) { return(TypeCache.GetTypesDerivedFrom <UnityEngine.Object>().FirstOrDefault(t => t.Name == typeName) ?? typeof(UnityEngine.Object)); }
internal override object SerializeValue(object source, TypeCache typeCache, Cache cache) { return GetStringFromObject(source, typeCache.Type, _typeConverter); }
internal override object FetchValue(Element element, object target, TypeCache typeCache, Cache cache) { // Get the primary element Element child; if (!GetNodeFromQuery(Query, null, element, out child)) { child = element.Children.OfType<Element>().Where(e => e.Name.Equals(Name)).FirstOrDefault(); } if (child == null) { return null; } // Get all the item nodes (this will throw an exception on Cast<>() if an ItemQuery returns other than Element nodes) IList<Element> items = new List<Element>(!String.IsNullOrEmpty(ItemQuery) ? child.Eval(ItemQuery).Cast<Element>() : child.Children.OfType<Element>().Where(e => e.Name.Equals(ItemName))); // Create the collection object collection = _getCollection(target); // Populate with values foreach(Element item in items) { object keyValue = FetchValue(item, KeyAttributeName, KeyElementName, KeyQuery, KeysArePersistentObjects, AttachKeys, _keyTypeCache, _keyTypeConverter, cache); object valueValue = FetchValue(item, ValueAttributeName, ValueElementName, ValueQuery, ValuesArePersistentObjects, AttachValues, _valueTypeCache, _valueTypeConverter, cache); if(keyValue != null && valueValue != null) _setCollectionItem(collection, keyValue, valueValue); } return collection; }