/// <summary> /// Return the map for type, if not found will return a map with Type.Name in camelcase for index name and indexType and use the ElasticsearchTypeAttribute /// </summary> /// <param name="type"></param> /// <returns>The Map for type<see cref="ElasticIndexMap"/></returns> public static ElasticIndexMap GetMap(Type type) { ElasticIndexMap map = null; if (TypeMaps.TryGetValue(type, out map)) { return(map); } else { var typeNames = new List <string>(); typeNames.Add(type.Name.ToLower()); var attrs = type.GetCustomAttributes() .Where(w => w is ElasticsearchTypeAttribute) .Select(s => s as ElasticsearchTypeAttribute); if (attrs.Any()) { typeNames.AddRange(attrs.Select(s => s.Name.ToLower())); } return(new ElasticIndexMap(type.Name.ToLower(), typeNames.Distinct().ToArray())); }; }
/// <summary>获取类型</summary> /// <param name="name">名称</param> /// <returns></returns> public Type GetType(String name) { if (String.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } // 第一次使用时编译 if (Assembly == null) { Compile(); } if (Assembly == null) { throw new Exception("未编译!"); } var asmx = AssemblyX.Create(Assembly); if (TypeMaps.TryGetValue(name, out var typeName)) { return(asmx.GetType(typeName)); } else { return(asmx.GetType(name)); } }
private bool IsTypeComplete(Type type) { TypeMap typeMap; if (TypeMaps.FindTypeMap(type, out typeMap) && !typeMap.IsIgnored) { return(true); } var desugared = type.Desugar(); var finalType = (desugared.GetFinalPointee() ?? desugared).Desugar(); var templateSpecializationType = finalType as TemplateSpecializationType; if (templateSpecializationType != null) { finalType = templateSpecializationType.Desugared.Type; } Declaration decl; if (!finalType.TryGetDeclaration(out decl)) { return(true); } return(!decl.IsIncomplete); }
private string TranslateEnumExpression(Function function, Type desugared, string @params) { TypeMap typeMap; if ((function.Parameters.Count == 0 || HasSingleZeroArgExpression(function)) && TypeMaps.FindTypeMap(desugared, out typeMap)) { var typePrinterContext = new TypePrinterContext { MarshalKind = MarshalKind.DefaultExpression, Type = desugared }; var typeInSignature = typeMap.CSharpSignatureType(typePrinterContext) .SkipPointerRefs().Desugar(); Enumeration @enum; if (typeInSignature.TryGetEnum(out @enum)) { return("0"); } } if (@params.Contains("::")) { return(regexDoubleColon.Replace(@params, desugared + ".")); } return(regexName.Replace(@params, desugared + ".$1")); }
private bool IsTypeComplete(Type type) { TypeMap typeMap; if (TypeMaps.FindTypeMap(type, out typeMap) && !typeMap.IsIgnored) { return(true); } var desugared = type.Desugar(); var finalType = (desugared.GetFinalPointee() ?? desugared).Desugar(); var templateSpecializationType = finalType as TemplateSpecializationType; if (templateSpecializationType != null) { finalType = templateSpecializationType.Desugared.Type; } Declaration decl; if (!finalType.TryGetDeclaration(out decl)) { return(true); } var @class = (decl as Class); if (@class != null && @class.IsOpaque && [email protected] && !(@class is ClassTemplateSpecialization)) { return(true); } return(!decl.IsIncomplete || decl.CompleteDeclaration != null); }
/// <summary> /// 获取字段类型名称 /// </summary> /// <param name="type"></param> /// <param name="length">字段固定长度</param> /// <param name="varLength">字段不定长度(仅对字符型字段有效)</param> /// <param name="unicode">是否为unicode字符(仅对字符型字段有效)</param> /// <returns></returns> private static string GetTypeName(Type type, int?length, int?varLength, bool unicode) { var kvp = TypeMaps.FirstOrDefault(t => t.Value.Contains(type)); if (kvp.Key.IsValid()) { return(kvp.Key); } if (typeof(Enum) == type.BaseType) { return("INTEGER"); } if (typeof(DateTime) == type) { return("VARCHAR(50)"); } var len = varLength ?? 0; if (len > 0) { return(unicode ? $"NVARCHAR({len})" : $"VARCHAR({len})"); } len = length ?? 0; if (len <= 0) { return("TEXT"); } return(unicode ? $"NCHAR({len})" : $"CHARACTER({len})"); }
private bool IsDeclIgnored(Declaration decl) { var parameter = decl as Parameter; if (parameter != null) { if (parameter.Type.Desugar().IsPrimitiveType(PrimitiveType.Null)) { return(true); } TypeMap typeMap; if (TypeMaps.FindTypeMap(parameter.Type, out typeMap)) { return(typeMap.IsIgnored); } } if (decl.Ignore) { return(true); } decl.Visit(this); return(decl.Ignore); }
public static void Map(Type type, string index, params string[] indexTypes) { if (TypeMaps.ContainsKey(type)) { throw new InvalidOperationException($"The type {type.FullName} already has a map."); } TypeMaps.Add(type, new ElasticIndexMap(index, indexTypes)); }
public void shoud_map_to_a_constant() { IDataReader reader = GetDataReader(); var mapper = new DataReaderMapperBuilder <IgnoreType>("shoud_map_to_a_constant") .Map("name", TypeMaps.String("myname")) .Build(); Assert.That(mapper.Map(reader).Name, Is.EqualTo("myname")); }
static public IOpenApiAny GetExample(Type parameter, TypeMaps maps, OpenApiComponents components) { if (components.Schemas.ContainsKey(parameter.Name)) { return(components.Schemas[parameter.Name].Example); } if (maps.ContainsMap(parameter)) { return(maps.GetMap(parameter).OpenApiExample); } else if (parameter == typeof(string)) { int randomNum = new Random().Next() % 3; var words = new string[] { "foo", "bar", "baz" }; return(new OpenApiString(words[randomNum])); } else if (IsNumericType(parameter)) { int randomNum = new Random().Next() % 400; return(new OpenApiInteger(randomNum)); } else if (parameter == typeof(bool)) { int randomNum = new Random().Next() % 1; return(new OpenApiBoolean(randomNum == 0)); } else if (parameter.GetInterfaces().Contains(typeof(IEnumerable))) { var exampleArr = new OpenApiArray(); int randomNum = new Random().Next() % 3; for (int _ = 0; _ < randomNum + 1; _++) { var innerType = parameter.GetElementType() ?? parameter.GenericTypeArguments[0]; exampleArr.Add(GetExample(innerType, maps, components)); } return(exampleArr); } else { if (parameter.GetProperties().Length == 0) { return(new OpenApiNull()); } var example = new OpenApiObject(); foreach (var prop in parameter.GetProperties()) { example.Add(prop.Name, GetExample(prop.PropertyType, maps, components)); } return(example); } }
private bool IsDeclIgnored(Declaration decl) { var parameter = decl as Parameter; if (parameter != null && parameter.Type.Desugar().IsPrimitiveType(PrimitiveType.Null)) { return(true); } TypeMap typeMap; return(TypeMaps.FindTypeMap(decl, out typeMap) ? typeMap.IsIgnored : decl.Ignore); }
public void Dispose() { r_Ships.Dispose(); TypeMaps.Clear(); Types = null; if (r_UpdateSubscription != null) { r_UpdateSubscription.Dispose(); r_UpdateSubscription = null; } if (r_HomeportSubscription != null) { r_HomeportSubscription.Dispose(); r_HomeportSubscription = null; } }
public void should_be_thread_safe() { IDataReader reader = GetDataReader(); var sync = new CountdownEvent(2); Action method = () => { var mapper = new DataReaderMapperBuilder <IgnoreType>("shoud_map_to_a_constant") .Map("name", TypeMaps.String("myname")) .Build(); sync.Signal(); Assert.That(mapper.Map(reader).Name, Is.EqualTo("myname")); }; Action parallel = () => { ThreadPool.QueueUserWorkItem(state => method()); ThreadPool.QueueUserWorkItem(state => method()); }; Assert.That(() => parallel(), Throws.Nothing); sync.Wait(); }
/// <summary>获取类型</summary> /// <param name="name"></param> /// <returns></returns> public Type GetType(String name) { if (String.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } if (Assembly == null) { throw new Exception("未编译!"); } var asmx = AssemblyX.Create(Assembly); String typeName = null; if (TypeMaps.TryGetValue(name, out typeName)) { return(asmx.GetType(typeName)); } else { return(asmx.GetType(name)); } }
public static OpenApiResponses GetOpenApiResponses(MethodInfo methodInfo, IEnumerable <ReturnsAttribute> returnsAttributes, OpenApiComponents components, string InterfaceType, TypeMaps maps) { //var methodInfo = handlerInfo.Method; var returnMediaType = new OpenApiMediaType { Schema = new OpenApiSchema { Type = methodInfo.ReturnType.FullName.Contains("Task") ? methodInfo.ReturnType.GenericTypeArguments[0].Name : methodInfo.ReturnType.FullName, } }; var responses = returnsAttributes .ToOpenApiResponses(components, maps) .GetDefaultResponses(methodInfo, InterfaceType); return(responses); }
public static OpenApiRequestBody GetOpenApiRequestBody(MethodInfo methodInfo, OpenApiComponents components, TypeMaps maps, bool withKey = false) { var conentMediaType = new OpenApiMediaType { Schema = new OpenApiSchema { Type = methodInfo.ReturnType.FullName.Contains("Task") ? methodInfo.ReturnType.GenericTypeArguments[0].Name : methodInfo.ReturnType.FullName } }; List <ParameterInfo> relevantParameters = withKey ? methodInfo.GetParameters().Skip(1).ToList() : methodInfo.GetParameters().ToList(); var paramterDict = new Dictionary <string, OpenApiSchema>(); foreach (var param in relevantParameters) { paramterDict[param.Name] = TypeUtils.ExplodeParameter(param.ParameterType, components, maps); } string bodyName = relevantParameters[0].ParameterType.Name; var requestBody = new OpenApiRequestBody { Description = "Command Body", Required = relevantParameters.Any(p => !p.IsOptional), Content = { ["application/json"] = new OpenApiMediaType { Schema = new OpenApiSchema { Reference = new OpenApiReference { Type = ReferenceType.Schema, Id = bodyName } } } }, }; return(requestBody); }
private bool?CheckForDefaultConstruct(Type desugared, Expression expression, ref string result) { var type = desugared.GetFinalPointee() ?? desugared; Class decl; if (!type.TryGetClass(out decl)) { return(false); } var ctor = expression as CXXConstructExpr; var typePrinter = new CSharpTypePrinter(Context); typePrinter.PushMarshalKind(MarshalKind.DefaultExpression); var typePrinterResult = type.Visit(typePrinter).Type; TypeMap typeMap; if (TypeMaps.FindTypeMap(decl, type, out typeMap)) { var typePrinterContext = new TypePrinterContext() { Kind = typePrinter.Kind, MarshalKind = typePrinter.MarshalKind, Type = type }; var typeInSignature = typeMap.CSharpSignatureType(typePrinterContext) .SkipPointerRefs().Desugar(); Enumeration @enum; if (typeInSignature.TryGetEnum(out @enum)) { if (ctor != null && (ctor.Arguments.Count == 0 || HasSingleZeroArgExpression((Function)ctor.Declaration))) { result = "0"; return(true); } return(false); } if (ctor != null && typePrinterResult == "string" && ctor.Arguments.Count == 0) { result = "\"\""; return(true); } } if (ctor == null) { CheckForSimpleExpressions(expression, ref result, desugared); return(decl.IsValueType ? (bool?)false : null); } var method = (Method)expression.Declaration; var expressionSupported = decl.IsValueType && method.Parameters.Count == 0; if (expression.String.Contains('(')) { var argsBuilder = new StringBuilder("new "); argsBuilder.Append(typePrinterResult); argsBuilder.Append('('); for (var i = 0; i < ctor.Arguments.Count; i++) { var argument = ctor.Arguments[i]; var argResult = argument.String; expressionSupported &= PrintExpression(method, method.Parameters[i].Type.Desugar(), argument, ref argResult) ?? false; argsBuilder.Append(argResult); if (i < ctor.Arguments.Count - 1) { argsBuilder.Append(", "); } } argsBuilder.Append(')'); result = argsBuilder.ToString(); } return(expressionSupported ? true : (bool?)null); }
private bool FindTypeMap(string name, out TypeMap typeMap) { return(TypeMaps.TryGetValue(name, out typeMap) && typeMap.IsEnabled); }
public static OpenApiResponses ToOpenApiResponses(this IEnumerable <ReturnsAttribute> attributes, OpenApiComponents components, TypeMaps maps) { var responses = new OpenApiResponses(); foreach (var attribute in attributes) { OpenApiSchema schema = TypeUtils.ExplodeParameter(attribute.Type, components, maps); var mediaType = new OpenApiMediaType { Schema = schema }; responses.Add(attribute.StatusCode.ToString(), new OpenApiResponse { Description = attribute.Description, Content = { ["application/json"] = mediaType } }); } return(responses); }
internal ShipOverviewViewModel() { TypeMaps = KanColleGame.Current.MasterInfo.ShipTypes.Values.Where(r => r.ID != 12 && r.ID != 15).ToDictionary(IdentityFunction <ShipTypeInfo> .Instance, r => new FilterTypeViewModel <ShipTypeInfo>(r)); Types = TypeMaps.Values.ToArray(); r_Ships = new ShipCollectionView(this); Ships = r_Ships; var rSelectedTypes = Preference.Instance.Game.SelectedShipTypes.Value; if (rSelectedTypes != null) { foreach (var rID in rSelectedTypes) { ShipTypeInfo rShipType; FilterTypeViewModel <ShipTypeInfo> rTypeVM; if (KanColleGame.Current.MasterInfo.ShipTypes.TryGetValue(rID, out rShipType) && TypeMaps.TryGetValue(rShipType, out rTypeVM)) { rTypeVM.IsSelected = true; } } } r_UpdateSubscription = r_UpdateObservable .Do(_ => IsLoading = true) .Throttle(TimeSpan.FromSeconds(.5)) .Do(_ => r_Ships.Refresh()) .Do(_ => IsLoading = false) .Subscribe(); UpdateSelectionCore(); r_HomeportSubscription = ApiService.Subscribe("api_port/port", _ => Refresh()); }
public static void Clean() { TypeMaps.Clear(); }
public static OpenApiSchema ExplodeParameter(Type parameter, OpenApiComponents components, TypeMaps maps) { OpenApiSchema schema = new OpenApiSchema(); var jsonifed = parameter.GetJsonType(); string name = parameter.Name; if (parameter.GenericTypeArguments.Length > 0) { foreach (var genArg in parameter.GenericTypeArguments) { ExplodeParameter(genArg, components, maps); } schema.Type = "object"; name = parameter.GetGenericName(); } if (maps.ContainsMap(parameter)) { var map = maps.GetMap(parameter); schema = ExplodeParameter(map.Type, components, maps); schema.Example = map.OpenApiExample; components.Schemas[name] = schema; } else if (components.Schemas.ContainsKey(name)) { schema = components.Schemas[name]; } else if (!String.IsNullOrEmpty(parameter.GetDefaultSchema().Title)) { schema = parameter.GetDefaultSchema(); } else if (Nullable.GetUnderlyingType(parameter) != null) { schema = ExplodeParameter(Nullable.GetUnderlyingType(parameter), components, maps); schema.Nullable = true; } else if (parameter.IsEnum) { List <IOpenApiAny> enumVals = new List <IOpenApiAny>(); foreach (var enumSingle in parameter.GetEnumNames()) { var enumStr = enumSingle.ToString(); enumVals.Add(new OpenApiString(enumStr)); } schema.Type = "string"; schema.Enum = enumVals; } else if (parameter.IsPrimitive || IsNumericType(parameter) || parameter == typeof(string)) { schema.Type = jsonifed.Type.ToJsonType(); schema.Example = GetExample(parameter, maps, components); } else if (jsonifed.Items != null) { schema.Type = jsonifed.Type.ToJsonType(); schema.Items = jsonifed.Items[0].GetOpenApiSchema(); schema.Example = GetExample(parameter, maps, components); } else if (parameter.GetProperties().Length != 0 && !IsNumericType(parameter)) { Dictionary <string, OpenApiSchema> props = new Dictionary <string, OpenApiSchema>(); foreach (var prop in parameter.GetProperties()) { if (prop.GetCustomAttribute <IgnoreMemberAttribute>() != null || prop.PropertyType == parameter) { continue; } props[prop.Name] = ExplodeParameter(prop.PropertyType, components, maps); } schema.Properties = props; } else { schema.Type = "Object"; } components.Schemas[name] = schema; return(schema); }
public CqApiOptions() { Maps = new TypeMaps(); AuthOptions = new CqApiAuthOptions(); ResourceDescriptions = new ResourceDescriptions(); }
public static IList <OpenApiParameter> GetOpenApiParameters(IEnumerable <ParameterInfo> parameters, OpenApiComponents components, TypeMaps maps, bool withKey = false) { var openApiParams = new List <OpenApiParameter>(); foreach (var parameter in parameters) { if (parameter.GetCustomAttribute <IgnoreMemberAttribute>() != null) { continue; } var schemaParam = TypeUtils.ExplodeParameter(parameter.ParameterType, components, maps); if (schemaParam.Properties.Count > 0) { foreach (var prop in schemaParam.Properties) { openApiParams.Add(new OpenApiParameter { Name = prop.Key, Required = !prop.Value.Nullable, AllowEmptyValue = !prop.Value.Nullable, In = withKey ? ParameterLocation.Path : ParameterLocation.Query, Schema = prop.Value }); } } else { openApiParams.Add(new OpenApiParameter { Name = parameter.Name, //Required = !parameter.IsOptional, AllowEmptyValue = parameter.IsOptional, In = withKey ? ParameterLocation.Path : ParameterLocation.Query, Schema = TypeUtils.ExplodeParameter(parameter.ParameterType, components, maps) }); } } return(openApiParams); }