/// <summary> /// 安装完成处理 /// </summary> protected unsafe override void onCreated() { foreach (ClientCode code in clientCodes.Values) { Server server; if (servers.TryGetValue(code.Attribute.ServerName, out server)) { if (server.Attribute.GetIsSegmentation) { server.ClientCodes.Add(code.SegmentationCode); } else { Coder.Add(code.Code); } } } if (clientCodes.Count != 0) { clientCodes = DictionaryCreator.CreateOnly <Type, ClientCode>(); } StringArray clientCallCode = new StringArray(); LeftArray <TcpMethod> methods = new LeftArray <TcpMethod>(); TcpMethod[] methodIndexs; ParameterBuilder parameterBuilder = new ParameterBuilder(); int staticMethodIndex = 0; foreach (Server server in servers.Values) { if (server.IsMethod || server.RemoteLinkTypes.Length != 0 || server.ClientCodes.Length != 0) { Attribute = server.Attribute; TcpServerAttributeType = server.AttributeType == null || server.AttributeType.Type == null ? null : server.AttributeType.FullName; Part = PartType.RemoteLink; foreach (RemoteLinkType remoteLinkType in server.RemoteLinkTypes) { if (remoteLinkType.IsRemoteLink) { Type = remoteLinkType.Type; CurrentRemoteLinkType = remoteLinkType; remoteLinkType.IsRemoteMember = remoteLinkType.RemoteMethods.Length != 0 && RemoteMemberTypes.Add(Type); CSharpTypeDefinition definition = new CSharpTypeDefinition(Type, true, false); _code_.Length = 0; create(false); Coder.Add(definition.Start + _partCodes_["SERVERREMOTE"] + definition.End); if (ServiceAttribute.GetIsSegmentation) { clientCallCode.Add(definition.Start + _partCodes_["CLIENTREMOTE"] + definition.End); } else { Coder.Add(definition.Start + _partCodes_["CLIENTREMOTE"] + definition.End); } } } string clientCode = null; if (server.IsMethod) { Part = PartType.CallType; foreach (ServerType serverType in server.Types) { methods.Add(serverType.Methods); } methodIndexs = methods.ToArray(); methods.Length = 0; methodIndexs = TcpMethod.CheckIdentity(methodIndexs, null, getRememberIdentityName(), method => method.Method.MethodKeyFullName); if (methodIndexs == null) { return; } int index = CallQueueCount = 0; IsVerifyMethod = false; IsCallQueueLink = ServiceAttribute.GetRemoteExpressionServerTask == Net.TcpServer.ServerTaskType.QueueLink; if (ServiceAttribute.GetRemoteExpressionServerTask == Net.TcpServer.ServerTaskType.Queue || ServiceAttribute.GetRemoteExpressionServerTask == Net.TcpServer.ServerTaskType.QueueLink) { CallQueueCount = (int)ServiceAttribute.GetRemoteExpressionCallQueueIndex + 1; } parameterBuilder.Clear(ServiceAttribute.IsSimpleSerialize); QueueTypeBuilder queueTypeBuilder = new QueueTypeBuilder(); foreach (TcpMethod method in methodIndexs) { method.MethodIndex = index++; method.StaticMethodIndex = ++staticMethodIndex; if (!method.IsNullMethod) { if (IsVerifyMethod) { method.Attribute.IsVerifyMethod = false; } else if (method.IsVerifyMethod) { IsVerifyMethod = true; IsSynchronousVerifyMethod = method.Attribute.ServerTaskType == AutoCSer.Net.TcpServer.ServerTaskType.Synchronous && !method.IsAsynchronousCallback; if (method.MethodType == server.AttributeType && server.IsTimeVerify) { TimeVerifyMethod = method; } //method.Attribute.ServerTaskType = Net.TcpServer.ServerTaskType.Synchronous; } parameterBuilder.Add(method); queueTypeBuilder.Add(method); IsCallQueueLink |= method.Attribute.ServerTaskType == Net.TcpServer.ServerTaskType.QueueLink; if (method.Attribute.ServerTaskType == Net.TcpServer.ServerTaskType.Queue || method.Attribute.ServerTaskType == Net.TcpServer.ServerTaskType.QueueLink) { CallQueueCount = Math.Max((int)method.Attribute.GetServerQueueIndex + 1, CallQueueCount); } MaxTimeoutSeconds = Math.Max(MaxTimeoutSeconds, method.Attribute.GetClientTimeoutSeconds); //if (method.IsAsynchronousCallback && method.Attribute.ServerTaskType != Net.TcpServer.ServerTaskType.Synchronous) //{ // Messages.Message("异步函数警告" + method.MemberFullName); //} } } ParameterTypes = parameterBuilder.Get(); ServerCallQueueTypes = queueTypeBuilder.Get(); foreach (ServerType serverType in server.Types) { if (serverType.Methods.Length != 0) { Type = serverType.Type; //TimeVerifyType = Type == server.AttributeType && server.IsTimeVerify ? Type : ExtensionType.Null; Attribute = serverType.Attribute ?? server.Attribute; MethodIndexs = serverType.Methods.ToArray(); CSharpTypeDefinition definition = new CSharpTypeDefinition(Type, true, false); _code_.Length = 0; create(false); Coder.Add(definition.Start + _partCodes_["SERVERCALL"] + definition.End); if (ServiceAttribute.GetIsSegmentation) { clientCallCode.Add(definition.Start + _partCodes_["CLIENTCALL"] + definition.End); } else { Coder.Add(definition.Start + _partCodes_["CLIENTCALL"] + definition.End); } } } Part = PartType.ServerType; Type = server.AttributeType; Attribute = server.Attribute; MethodIndexs = methodIndexs; methods.Length = 0; _code_.Length = 0; create(false); Coder.Add(@" namespace " + AutoParameter.DefaultNamespace + "." + serverPart + @" { " + _partCodes_["SERVER"] + @" }"); clientCode = @" namespace " + AutoParameter.DefaultNamespace + "." + ClientPart + @" { " + _partCodes_["CLIENT"] + @" }"; } if (ServiceAttribute.GetIsSegmentation) { if (clientCode != null) { clientCallCode.Add(clientCode); } clientCallCode.Append(ref server.ClientCodes); string fileName = AutoParameter.ProjectPath + "{" + AutoParameter.DefaultNamespace + "}.TcpStaticServer." + ServiceAttribute.ServerName + ".Client.cs"; clientCode = Coder.WarningCode + clientCallCode.ToString() + Coder.FileEndCode; if (Coder.WriteFile(fileName, clientCode)) { if (ServiceAttribute.ClientSegmentationCopyPath != null) { string copyFileName = ServiceAttribute.ClientSegmentationCopyPath + "{" + AutoParameter.DefaultNamespace + "}.TcpStaticServer." + ServiceAttribute.ServerName + ".Client.cs"; if (Coder.WriteFile(copyFileName, clientCode)) { Messages.Message(copyFileName + " 被修改"); } } Messages.Message(fileName + " 被修改"); } clientCallCode.Length = 0; } else if (clientCode != null) { Coder.Add(clientCode); } } } }
/// <summary> /// 获取分组数据成员位图 /// </summary> /// <param name="group">分组</param> /// <returns>分组数据成员位图</returns> private static MemberMap <modelType> getGroupMemberMap(int group) { if (groupMemberMaps == null) { LeftArray <KeyValue <MemberMap <modelType>, int> > memberMaps = new LeftArray <KeyValue <MemberMap <modelType>, int> >(); memberMaps.Add(new KeyValue <MemberMap <modelType>, int>(MemberMap, 0)); Monitor.Enter(groupMemberMapLock); if (groupMemberMaps == null) { try { foreach (Field field in Fields) { if (field.DataMember.Group != 0) { int index = memberMaps.Length; foreach (KeyValue <MemberMap <modelType>, int> memberMap in memberMaps.Array) { if (memberMap.Value == field.DataMember.Group || --index == 0) { break; } } if (index == 0) { MemberMap <modelType> memberMap = new MemberMap <modelType>(); memberMaps.Add(new KeyValue <MemberMap <modelType>, int>(memberMap, field.DataMember.Group)); memberMap.SetMember(field.MemberMapIndex); } else { memberMaps.Array[memberMaps.Length - index].Key.SetMember(field.MemberMapIndex); } } } if (memberMaps.Length != 1) { MemberMap <modelType> memberMap = memberMaps.Array[0].Key = new MemberMap <modelType>(); foreach (Field field in Fields) { if (field.DataMember.Group == 0) { memberMap.SetMember(field.MemberMapIndex); } } } groupMemberMaps = memberMaps.ToArray(); } finally { Monitor.Exit(groupMemberMapLock); } } else { Monitor.Exit(groupMemberMapLock); } } foreach (KeyValue <MemberMap <modelType>, int> memberMap in groupMemberMaps) { if (memberMap.Value == group) { return(memberMap.Key); } } AutoCSer.Log.Pub.Log.Add(AutoCSer.Log.LogType.Error, typeof(modelType).fullName() + " 缺少缓存分组 " + group.toString()); return(null); }
/// <summary> /// 服务端映射标识检测 /// </summary> /// <param name="node"></param> /// <param name="types"></param> /// <returns>是否映射成功</returns> internal unsafe AutoCSer.Net.TcpServer.ReturnType Check(Node node, ref LeftArray <Type> types) { node.CheckServerNodeId(this, ref types); if (types.Length == 0) { return(AutoCSer.Net.TcpServer.ReturnType.Success); } int count = types.Length; LeftArray <RemoteType> remoteTypes = new LeftArray <RemoteType>(types.Length); types.Length = 0; AutoCSer.Net.TcpServer.ReturnType returnType = AutoCSer.Net.TcpServer.ReturnType.Success; Monitor.Enter(serverNodeIdLock); try { foreach (Type type in types.Array) { if (!ServerNodeIds.ContainsKey(type)) { types.UnsafeAdd(type); remoteTypes.Add(type); } if (--count == 0) { break; } } if ((count = types.Length) != 0) { AutoCSer.Net.TcpServer.ReturnValue <int[]> ids = Get(remoteTypes.ToArray()); if (ids.Type == TcpServer.ReturnType.Success) { fixed(int *idFixed = ids.Value) { int *idStart = idFixed; foreach (Type type in types.Array) { if (*idStart == 0) { returnType = TcpServer.ReturnType.RemoteExpressionServerNodeError; } else { ServerNodeIds[type] = *idStart; } if (--count == 0) { break; } ++idStart; } } } else { returnType = ids.Type; } } } finally { Monitor.Exit(serverNodeIdLock); } return(returnType); }
/// <summary> /// 获取搜索数据标识集合(匹配所有分词结果) /// </summary> /// <param name="text">搜索关键字</param> /// <param name="maxSize">关键字最大字符长度</param> /// <param name="isKey">数据标识过滤</param> /// <returns>数据标识集合</returns> public LeftArray <keyType> SearchAll(string text, int maxSize, Func <keyType, bool> isKey = null) { resultArray.Length = 0; Simplified.Set(text, maxSize); Search(true); switch (queryResult.Count) { case 0: break; case 1: foreach (KeyValuePair <keyType, ResultIndexArray> result in queryResult[0].Value.Dictionary) { if (isKey(result.Key)) { resultArray.Add(result.Key); } } break; default: Dictionary <keyType, ResultIndexArray> resultDictionary = null; foreach (KeyValue <HashString, QueryResult> result in queryResult) { if (resultDictionary == null || result.Value.Dictionary.Count < resultDictionary.Count) { resultDictionary = result.Value.Dictionary; } } resultCountDictionary.Empty(); foreach (keyType key in resultDictionary.Keys) { if (isKey(key)) { resultCountDictionary.Set(key, 0); } } if (resultCountDictionary.Count != 0) { int count = 0, keyCount = resultCountDictionary.Count; foreach (KeyValue <HashString, QueryResult> result in queryResult) { if (!object.ReferenceEquals(result.Value.Dictionary, resultDictionary)) { int nextCount = count + 1, resultCount; keyCount = 0; foreach (keyType key in result.Value.Dictionary.Keys) { if (resultCountDictionary.TryGetValue(key, out resultCount) && resultCount == count) { resultCountDictionary.Set(key, nextCount); ++keyCount; } } if (keyCount == 0) { resultCountDictionary.Empty(); break; } count = nextCount; } } if (keyCount > 0) { resultArray.PrepLength(keyCount); foreach (KeyValue <keyType, int> result in resultCountDictionary.KeyValues) { if (result.Value == count) { resultArray.UnsafeAdd(result.Key); } } } } break; } return(resultArray); }
internal static void GetColumnNames <valueType>(ref LeftArray <string> names, string name) { names.Add(Column <valueType> .Verifyer.GetColumnNames(name)); }
/// <summary> /// 根据表格名称获取表格信息 /// </summary> /// <param name="connection">SQL连接</param> /// <param name="tableName">表格名称</param> /// <returns>表格信息</returns> internal override TableColumnCollection GetTable(DbConnection connection, string tableName) { if (isTable(connection, tableName)) { using (DbCommand command = getCommand(connection, @"describe `" + tableName + @"`; show index from `" + tableName + @"`;")) using (DbDataReader reader = command.ExecuteReader(CommandBehavior.Default)) { Column identity = null; Dictionary <HashString, Column> columns = DictionaryCreator.CreateHashString <Column>(); LeftArray <Column> primaryKeys = default(LeftArray <Column>); Dictionary <HashString, ListArray <IndexColumn> > indexs = null; while (reader.Read()) { string key = (string)reader["Key"]; object defaultValue = reader["Default"]; Column column = new Column { Name = (string)reader["Field"], DefaultValue = defaultValue == DBNull.Value ? null : (string)defaultValue, IsNull = (string)reader["Null"] == "YES", }; column.DbType = DbType.FormatDbType((string)reader["Type"], out column.Size); columns.Add(column.Name, column); if (key == "PRI") { primaryKeys.Add(column); } } if (reader.NextResult()) { indexs = DictionaryCreator.CreateHashString <ListArray <IndexColumn> >(); ListArray <IndexColumn> indexColumns; while (reader.Read()) { string name = (string)reader["Key_name"]; IndexColumn indexColumn = new IndexColumn { Column = columns[(string)reader["Column_name"]], Index = (int)(long)reader["Seq_in_index"], IsNull = (string)reader["Null"] == "YES" }; HashString nameKey = name; if (!indexs.TryGetValue(nameKey, out indexColumns)) { indexs.Add(nameKey, indexColumns = new ListArray <IndexColumn>()); indexColumns.Add(indexColumn); indexColumn.Type = (long)reader["Non_unique"] == 0 ? ColumnCollectionType.UniqueIndex : ColumnCollectionType.Index; } else { indexColumns.Add(indexColumn); } } } return(new TableColumnCollection { Columns = new ColumnCollection { Name = tableName, Columns = columns.Values.getArray(), Type = ColumnCollectionType.None }, Identity = identity, PrimaryKey = primaryKeys.Length == 0 ? null : new ColumnCollection { Type = ColumnCollectionType.PrimaryKey, Columns = primaryKeys.ToArray() }, Indexs = indexs.getArray(index => new ColumnCollection { Name = index.Key.ToString(), Type = index.Value[0].Type, Columns = index.Value.ToLeftArray().GetSort(value => value.Index).getArray(column => column.Column) }) }); } } return(null); }
/// <summary> /// 安装完成处理 /// </summary> protected unsafe override void onCreated() { StringArray clientCallCode = new StringArray(); LeftArray <TcpMethod> methods = new LeftArray <TcpMethod>(); TcpMethod[] methodIndexs; ParameterBuilder parameterBuilder = new ParameterBuilder(); int staticMethodIndex = 0; foreach (Server server in servers.Values) { if (server.IsMethod) { IsAllType = false; TcpServerAttributeType = server.AttributeType == null || server.AttributeType.Type == null ? null : server.AttributeType.FullName; ServiceAttribute = server.Attribute; foreach (ServerType serverType in server.Types) { methods.Add(serverType.Methods); } methodIndexs = methods.ToArray(); methods.Length = 0; methodIndexs = TcpMethod.CheckIdentity(methodIndexs, getRememberIdentityName(), method => method.Method.MethodKeyFullName); if (methodIndexs == null) { return; } int index = 0; IsVerifyMethod = IsCallQueue = false; parameterBuilder.Clear(ServiceAttribute.IsSimpleSerialize); foreach (TcpMethod method in methodIndexs) { method.MethodIndex = index++; method.StaticMethodIndex = ++staticMethodIndex; if (!method.IsNullMethod) { if (IsVerifyMethod) { method.Attribute.IsVerifyMethod = false; } else if (method.IsVerifyMethod) { IsVerifyMethod = true; if (method.MethodType == server.AttributeType && server.IsTimeVerify) { TimeVerifyMethod = method; } method.Attribute.ServerTaskType = Net.TcpServer.ServerTaskType.Synchronous; } parameterBuilder.Add(method); IsCallQueue |= method.Attribute.ServerTaskType == Net.TcpServer.ServerTaskType.Queue; } } ParameterTypes = parameterBuilder.Get(); foreach (ServerType serverType in server.Types) { if (serverType.Methods.Length != 0) { Type = serverType.Type; //TimeVerifyType = Type == server.AttributeType && server.IsTimeVerify ? Type : ExtensionType.Null; Attribute = serverType.Attribute ?? server.Attribute; MethodIndexs = serverType.Methods.ToArray(); CSharpTypeDefinition definition = new CSharpTypeDefinition(Type, true, false); _code_.Length = 0; create(false); Coder.Add(definition.Start + _partCodes_["SERVERCALL"] + definition.End); if (ServiceAttribute.IsSegmentation) { clientCallCode.Add(definition.Start + _partCodes_["CLIENTCALL"] + definition.End); } else { Coder.Add(definition.Start + _partCodes_["CLIENTCALL"] + definition.End); } } } Type = server.AttributeType; Attribute = server.Attribute; IsAllType = true; MethodIndexs = methodIndexs; methods.Length = 0; _code_.Length = 0; create(false); Coder.Add(@" namespace " + AutoParameter.DefaultNamespace + "." + serverPart + @" { " + _partCodes_["SERVER"] + @" }"); string clientCode = @" namespace " + AutoParameter.DefaultNamespace + "." + StreamClientPart + @" { " + _partCodes_["CLIENT"] + @" }"; if (ServiceAttribute.IsSegmentation) { clientCallCode.Add(clientCode); string fileName = AutoParameter.ProjectPath + "{" + AutoParameter.DefaultNamespace + "}.TcpStaticStreamServer." + ServiceAttribute.ServerName + ".Client.cs"; clientCode = Coder.WarningCode + clientCallCode.ToString() + Coder.FileEndCode; if (Coder.WriteFile(fileName, clientCode)) { if (ServiceAttribute.ClientSegmentationCopyPath != null) { string copyFileName = ServiceAttribute.ClientSegmentationCopyPath + "{" + AutoParameter.DefaultNamespace + "}.TcpStaticStreamServer." + ServiceAttribute.ServerName + ".Client.cs"; if (Coder.WriteFile(copyFileName, clientCode)) { Messages.Message(copyFileName + " 被修改"); } } Messages.Message(fileName + " 被修改"); } clientCallCode.Length = 0; } else { Coder.Add(clientCode); } } } }
internal void Append(ReflectionObjectScanner objectScanner) { Objects.Add(objectScanner); }
internal void Append(ReflectionArrayScanner arrayScanner) { Arrays.Add(arrayScanner); }
/// <summary> /// 创建关键字整表缓存 /// </summary> /// <typeparam name="primaryKey"></typeparam> /// <param name="getValue">根据关键字获取数据</param> /// <param name="member">缓存字段表达式</param> /// <param name="group">数据分组</param> /// <param name="isSave">是否保存缓存对象防止被垃圾回收</param> /// <returns></returns> public Event.MemberKey <valueType, modelType, primaryKey> CreateMemberPrimaryKey <primaryKey>(Func <primaryKey, valueType> getValue, Expression <Func <valueType, valueType> > member, int group = 1, bool isSave = true) where primaryKey : struct, IEquatable <primaryKey> { Event.MemberKey <valueType, modelType, primaryKey> cache = new Event.MemberKey <valueType, modelType, primaryKey>(this, ((Sql.Table <valueType, modelType, primaryKey>)SqlTable).GetPrimaryKey, getValue, member, group); if (isSave) { memberCaches.Add(cache); } return(cache); }
/// <summary> /// 创建JS脚本文件类库目录信息 /// </summary> /// <param name="directoryInfo"></param> /// <param name="lastWriteTime"></param> /// <returns></returns> private static Directory loadJs(DirectoryInfo directoryInfo, DateTime lastWriteTime) { DirectoryInfo jsDirectory = new DirectoryInfo(directoryInfo.fullName() + "js"); Directory directory = new Directory(); if (jsDirectory.Exists) { DirectoryInfo[] directoryInfos = jsDirectory.GetDirectories(); if (directoryInfos.Length != 0) { LeftArray <Directory> directorys = new LeftArray <Directory>(directoryInfos.Length); foreach (DirectoryInfo nextDirectoryInfo in directoryInfos) { Directory nextDirectory; switch (nextDirectoryInfo.Name) { case "ace": nextDirectory = js(nextDirectoryInfo, lastWriteTime, new string[] { "ace.js" }); break; case "mathJax": nextDirectory = js(nextDirectoryInfo, lastWriteTime, new string[] { "MathJax.js" }); break; case "highcharts": nextDirectory = js(nextDirectoryInfo, false, lastWriteTime); break; default: AutoCSer.Log.Pub.Log.Add(AutoCSer.Log.LogType.Error, "未知的js文件夹 " + nextDirectoryInfo.fullName()); nextDirectory = new Directory(); break; } if (nextDirectory.Name != null) { directorys.Add(nextDirectory); } } if (directorys.Length != 0) { directory.Directorys = directorys.ToArray(); } } FileInfo[] files = jsDirectory.GetFiles("*.js"); if (files.Length != 0) { LeftArray <FileTime> fileTimes = new LeftArray <FileTime>(files.Length); FileTime loadFileTime = new FileTime(), loadPageFileTime = new FileTime(); foreach (FileInfo file in files) { if (file.LastWriteTimeUtc > lastWriteTime) { if (file.Name == "load.js") { loadFileTime = new FileTime(file); } else if (file.Name == "loadPage.js") { loadPageFileTime = new FileTime(file); } else { fileTimes.Add(new FileTime(file)); } } } if (loadFileTime.FileName != null) { fileTimes.Add(loadFileTime); } if (loadPageFileTime.FileName != null) { fileTimes.Add(loadPageFileTime); } if (fileTimes.Length != 0) { directory.Files = fileTimes.ToArray(); } } if (directory.Files != null || directory.Directorys != null) { directory.Name = jsDirectory.Name; directory = new Directory { Name = directoryInfo.Name, Directorys = new Directory[] { directory } }; } } return(directory); }
/// <summary> /// 生成代码 /// </summary> /// <param name="fileName">模板文件名</param> /// <returns>代码</returns> private static LeftArray <string> getCode(string fileName) { string code = File.ReadAllText(fileName, System.Text.Encoding.UTF8); int startIndex = code.IndexOf("/*", StringComparison.Ordinal), endIndex = code.IndexOf(@"*/ ", startIndex + 2, StringComparison.Ordinal); if (endIndex > 0 && startIndex > 0) { LeftArray <string[][]> headerArray = new LeftArray <string[][]>(0); foreach (SubString line in new SubString(startIndex += 2, endIndex - startIndex, code).Trim().Split('\n')) { SubString headerLine = line.Trim(); if (headerLine.Length != 0) { headerArray.Add(headerLine.Split(';').GetArray(p => p.Split(',').GetArray(v => (string)v))); } } if (headerArray.Length != 0) { CombinationTemplateLink header = new CombinationTemplateLink(code = code.Substring(endIndex + 4)); int row = 0; foreach (string[][] line in headerArray) { int col = 0; foreach (string value in line[0]) { bool isSplit = false; CombinationTemplateLink link = header; do { link = link.Split(value, row, col, ref isSplit); }while (link != null); if (!isSplit) { Messages.Error("自定义简单组合模板文件内容没有找到匹配替换标记 " + value + " : " + fileName); return(new LeftArray <string>(0)); } ++col; } ++row; } LeftArray <CombinationTemplateLink> linkArray = new LeftArray <CombinationTemplateLink>(0); LeftArray <string> codeArray = new LeftArray <string>(0); do { if (header.Row >= 0) { linkArray.Add(header); header.Index = codeArray.Length; codeArray.Add(string.Empty); } else { codeArray.Add(header.Code); } }while ((header = header.Next) != null); CombinationTemplateHeaderEnumerable headerEnumerable = new CombinationTemplateHeaderEnumerable(ref headerArray, codeArray.ToArray(), linkArray.ToArray()); codeArray.Length = 0; foreach (string enumerableCode in headerEnumerable.GetCode()) { codeArray.Add(enumerableCode); } return(codeArray); } else { Messages.Error("自定义简单组合模板文件缺少头部信息解析失败 : " + fileName); } } else { Messages.Error("自定义简单组合模板文件缺少头部注释信息 : " + fileName); } return(new LeftArray <string>(0)); }
/// <summary> /// 添加 TCP 服务注册信息 /// </summary> /// <param name="server"></param> /// <param name="isMainChanged">主服务是否被修改</param> /// <returns>日志是否需要推送到客户端</returns> internal bool Add(ServerLog server, out bool isMainChanged) { if (Server == null) { Server = server; return(isMainChanged = true); } server.Name = Server.Name; if (server.IsSingle ^ Server.IsSingle) { AutoCSer.Log.Pub.Log.Add(Log.LogType.Warn, "TCP 服务 " + server.Name + " 单实例定义冲突 " + server.IsSingle.ToString()); } if (server.HostPortEquals(Server)) { if (server.Random == Server.Random) { return(isMainChanged = false); } if (server.IsSingle) { Servers.Length = 0; } Server = server; isMainChanged = false; return(true); } if (server.IsSingle || Server.IsSingle) { Servers.Length = 0; Server = server; return(isMainChanged = true); } int index = indexOf(server); if (!Server.IsMain || server.IsMain) { Server.IsMain = false; if (index < 0) { Servers.Add(Server); } else { Servers.Array[index] = Server; } Server = server; return(isMainChanged = true); } isMainChanged = false; if (index < 0) { Servers.Add(server); return(true); } if (server.Random == Servers.Array[index].Random) { return(false); } Servers.Array[index] = server; return(true); }
/// <summary> /// 动态成员分组 /// </summary> /// <param name="type">目标类型</param> /// <param name="isStatic">是否静态成员</param> public group(Type type, bool isStatic) { Dictionary <HashString, typeDepth> members = AutoCSer.DictionaryCreator.CreateHashString <typeDepth>(); BindingFlags staticFlags = isStatic ? (BindingFlags.Static | BindingFlags.FlattenHierarchy) : BindingFlags.Instance; typeDepth oldMember; foreach (FieldInfo field in type.GetFields(BindingFlags.Public | staticFlags)) { typeDepth member = new typeDepth(type, field, true); HashString nameKey = field.Name; if (!members.TryGetValue(nameKey, out oldMember) || member.Depth < oldMember.Depth) { members[nameKey] = member; } } int anonymousCount = 0; bool isAnonymous = !isStatic && type.Name[0] == '<', isAnonymousCount = !isStatic && !isAnonymous; foreach (FieldInfo field in type.GetFields(BindingFlags.NonPublic | staticFlags)) { if (field.Name[0] == '<') { if (isAnonymous) { int index = field.Name.IndexOf('>'); if (index != -1) { typeDepth member = new typeDepth(type, field, false); HashString nameKey = new SubString { String = field.Name, Start = 1, Length = index - 1 }; if (!members.TryGetValue(nameKey, out oldMember)) { members[nameKey] = member; } } } else if (isAnonymousCount) { ++anonymousCount; } } else { typeDepth member = new typeDepth(type, field, false); HashString nameKey = field.Name; if (!members.TryGetValue(nameKey, out oldMember) || member.Depth < oldMember.Depth) { members[nameKey] = member; } } } foreach (PropertyInfo property in type.GetProperties(BindingFlags.Public | staticFlags)) { if (!members.ContainsKey(property.Name)) { typeDepth member = new typeDepth(type, property, true); string name = property.Name + "."; ParameterInfo[] parameters = property.GetIndexParameters(); if (parameters.Length != 0) { name += parameters.joinString(',', value => value.ParameterType.fullName()); } HashString nameKey = name; if (!members.TryGetValue(nameKey, out oldMember) || member.Depth < oldMember.Depth) { members[nameKey] = member; } } } foreach (PropertyInfo property in type.GetProperties(BindingFlags.NonPublic | staticFlags)) { if (!members.ContainsKey(property.Name)) { typeDepth member = new typeDepth(type, property, false); string name = property.Name + "."; ParameterInfo[] parameters = property.GetIndexParameters(); if (parameters.Length != 0) { name += parameters.joinString(',', value => value.ParameterType.fullName()); } HashString nameKey = name; if (!members.TryGetValue(nameKey, out oldMember) || member.Depth < oldMember.Depth) { members[nameKey] = member; } } } PublicFields = members.Values.getFindArray(value => value.PublicField, value => value != null); NonPublicFields = members.Values.getFindArray(value => value.NonPublicField, value => value != null); PublicProperties = members.Values.getFindArray(value => value.PublicProperty, value => value != null); NonPublicProperties = members.Values.getFindArray(value => value.NonPublicProperty, value => value != null); if (anonymousCount != 0) { LeftArray <FieldInfo> anonymousFields = new LeftArray <FieldInfo>(); foreach (FieldInfo field in type.GetFields(BindingFlags.NonPublic | staticFlags)) { if (field.Name[0] == '<') { HashString nameKey = field.Name; if (!members.ContainsKey(nameKey)) { members[nameKey] = new typeDepth(); anonymousFields.Add(field); } } } AnonymousFields = anonymousFields.ToArray(); } else { AnonymousFields = NullValue <FieldInfo> .Array; } }
/// <summary> /// 泛型处理 /// </summary> /// <param name="type">类型</param> internal void GenericFullName(Type type) { Type reflectedType = type.ReflectedType; if (reflectedType == null) { if (type.GetGenericTypeDefinition() == typeof(Nullable <>)) { if (IsXml) { NameStream.Write("System.Nullable{"); getFullName(type.GetGenericArguments()[0]); NameStream.Write('}'); } else { getFullName(type.GetGenericArguments()[0]); NameStream.Write('?'); } return; } string name = type.Name; NameStream.Write(type.Namespace); NameStream.Write('.'); NameStream.Write(name, 0, name.IndexOf(GenericSplit)); genericParameter(type); return; } LeftArray <Type> reflectedTypeList = new LeftArray <Type>(sizeof(int)); do { reflectedTypeList.Add(reflectedType); reflectedType = reflectedType.ReflectedType; }while (reflectedType != null); Type[] reflectedTypeArray = reflectedTypeList.Array; int reflectedTypeIndex = reflectedTypeList.Length - 1; reflectedType = reflectedTypeArray[reflectedTypeIndex]; NameStream.Write(reflectedType.Namespace); Type[] parameterTypes = type.GetGenericArguments(); int parameterIndex = 0; bool isType = true; do { NameStream.Write('.'); if (reflectedType.IsGenericType) { string name = reflectedType.Name; int splitIndex = name.IndexOf(GenericSplit); if (splitIndex != -1) { NameStream.Write(name, 0, splitIndex); int parameterCount = reflectedType.GetGenericArguments().Length; genericParameter(parameterTypes, parameterIndex, parameterCount); parameterIndex = parameterCount; } else { NameStream.SimpleWrite(name); } } else { NameStream.SimpleWrite(reflectedType.Name); } if (reflectedTypeIndex == 0) { if (isType) { reflectedType = type; isType = false; } else { return; } } else { reflectedType = reflectedTypeArray[--reflectedTypeIndex]; } }while (true); }
private static void getColumnNames <valueType>(ref LeftArray <string> names, string name) { names.Add(Column <valueType> .Updater.GetColumnNames(name)); }
/// <summary> /// 安装下一个类型 /// </summary> protected unsafe override void nextCreate() { if (Type.Type.IsClass && !Type.Type.IsAbstract) { LeftArray <TcpMethod> methodArray = new LeftArray <TcpMethod>(Metadata.MethodIndex.GetMethods <AutoCSer.Net.TcpSimpleServer.MethodAttribute>(Type, Attribute.MemberFilters, false, Attribute.IsAttribute, Attribute.IsBaseTypeAttribute) .getFind(value => !value.Method.IsGenericMethod) .getArray(value => new TcpMethod { Method = value, MethodType = Type, ServiceAttribute = Attribute })); foreach (MemberIndexInfo member in MemberIndexGroup.Get <AutoCSer.Net.TcpSimpleServer.MethodAttribute>(Type, Attribute.MemberFilters, false, Attribute.IsAttribute, Attribute.IsBaseTypeAttribute)) { if (member.IsField) { FieldInfo field = (FieldInfo)member.Member; TcpMethod getMethod = new TcpMethod { Method = new Metadata.MethodIndex(field, true), MemberIndex = member, MethodType = Type, ServiceAttribute = Attribute }; if (!getMethod.Attribute.IsOnlyGetMember) { getMethod.SetMethod = new TcpMethod { Method = new MethodIndex(field, false), MemberIndex = member, MethodType = Type, ServiceAttribute = Attribute }; } methodArray.Add(getMethod); if (getMethod.SetMethod != null) { methodArray.Add(getMethod.SetMethod); } } else if (member.CanGet) { PropertyInfo property = (PropertyInfo)member.Member; TcpMethod getMethod = new TcpMethod { Method = new MethodIndex(property, true), MemberIndex = member, MethodType = Type, ServiceAttribute = Attribute }; if (member.CanSet && !getMethod.Attribute.IsOnlyGetMember) { getMethod.SetMethod = new TcpMethod { Method = new MethodIndex(property, false), MemberIndex = member, MethodType = Type, ServiceAttribute = Attribute }; } methodArray.Add(getMethod); if (getMethod.SetMethod != null) { methodArray.Add(getMethod.SetMethod); } } } MethodIndexs = methodArray.ToArray(); MethodIndexs = TcpMethod.CheckIdentity(MethodIndexs, Attribute.CommandIdentityEnmuType, getRememberIdentityName(Attribute.CommandIdentityEnmuType == null ? Attribute.GenericType ?? Type : null), method => method.Method.MethodKeyFullName); if (MethodIndexs == null) { return; } int methodIndex = 0; IsVerifyMethod = IsCallQueue = false; ParameterBuilder parameterBuilder = new ParameterBuilder { IsSimpleSerialize = Attribute.IsSimpleSerialize }; foreach (TcpMethod method in MethodIndexs) { method.MethodIndex = methodIndex++; if (!method.IsNullMethod) { if (IsVerifyMethod) { method.Attribute.IsVerifyMethod = false; } else if (method.IsVerifyMethod) { IsVerifyMethod = true; } parameterBuilder.Add(method); IsCallQueue |= method.Attribute.ServerTaskType == Net.TcpServer.ServerTaskType.Queue; } } ParameterTypes = parameterBuilder.Get(); //TcpMethod[] methodIndexs = MethodIndexs.getFindArray(value => !value.IsNullMethod); if (ServiceAttribute.IsSegmentation) { IsClientCode = false; create(IsServerCode = true); CSharpTypeDefinition definition = new CSharpTypeDefinition(Type, IsClientCode = true, false, Type.Type.Namespace + ".TcpSimpleClient"); _code_.Length = 0; _code_.Add(definition.Start); create(IsServerCode = false); _code_.Add(definition.End); string fileName = AutoParameter.ProjectPath + "{" + AutoParameter.DefaultNamespace + "}.TcpInternalSimpleServer." + ServerName + ".Client.cs"; string clientCode = Coder.WarningCode + _code_.ToString() + Coder.FileEndCode; if (Coder.WriteFile(fileName, clientCode)) { if (ServiceAttribute.ClientSegmentationCopyPath != null) { string copyFileName = ServiceAttribute.ClientSegmentationCopyPath + "{" + AutoParameter.DefaultNamespace + "}.TcpInternalSimpleServer." + ServerName + ".Client.cs"; if (Coder.WriteFile(copyFileName, clientCode)) { Messages.Message(copyFileName + " 被修改"); } } Messages.Message(fileName + " 被修改"); } } else { create(IsServerCode = IsClientCode = true); } } }
/// <summary> /// 添加数据 /// </summary> /// <param name="value">数据对象</param> /// <param name="typeIndex">数据类型</param> internal void Append(object value, byte typeIndex) { switch (typeIndex) { case 0: stream.Write((int)value); break; case 1: stream.Write((int)(int?)value); break; case 2: strings.Add((string)value); break; case 3: stream.Write(((DateTime)value).toKindTicks()); break; case 4: stream.Write(((DateTime)(DateTime?)value).toKindTicks()); break; case 5: stream.Write((double)value); break; case 6: stream.Write((double)(double?)value); break; case 7: stream.Write((float)value); break; case 8: stream.Write((float)(float?)value); break; case 9: stream.Write((decimal)value); break; case 10: stream.Write((decimal)(decimal?)value); break; case 11: stream.Write((Guid)value); break; case 12: stream.Write((Guid)(Guid?)value); break; case 13: stream.Write((bool)value ? (byte)1 : (byte)0); break; case 14: stream.Write((bool)(bool?)value ? (byte)1 : (byte)0); break; case 15: stream.Write((byte)value); break; case 16: stream.Write((byte)(byte?)value); break; case 17: bytes.Add((byte[])value); break; case 18: stream.Write((sbyte)value); break; case 19: stream.Write((sbyte)(sbyte?)value); break; case 20: stream.Write((short)value); break; case 21: stream.Write((short)(short?)value); break; case 22: stream.Write((ushort)value); break; case 23: stream.Write((ushort)(ushort?)value); break; case 24: stream.Write((uint)value); break; case 25: stream.Write((uint)(uint?)value); break; case 26: stream.Write((long)value); break; case 27: stream.Write((long)(long?)value); break; case 28: stream.Write((ulong)value); break; case 29: stream.Write((ulong)(ulong?)value); break; } }
/// <summary> /// 成员扩展缓存初始化依赖类型加载 /// </summary> /// <param name="wait">依赖当前缓存初始化的类型</param> private MemberCacheLinkWait(MemberCacheLinkWait wait) { this.wait.Set(0); waits.Add(wait); }
static TypeDeSerializer() { Type type = typeof(valueType), attributeType; MethodInfo methodInfo = DeSerializer.GetDeSerializeMethod(type); attribute = type.customAttribute <SerializeAttribute>(out attributeType) ?? Serializer.DefaultAttribute; if (methodInfo != null) { DefaultDeSerializer = (deSerialize)Delegate.CreateDelegate(typeof(deSerialize), methodInfo); IsReferenceMember = false; isValueType = true; return; } if (type.IsArray) { isValueType = true; if (type.GetArrayRank() == 1) { Type elementType = type.GetElementType(); if (!elementType.IsPointer && !typeof(Delegate).IsAssignableFrom(elementType)) { if (elementType.IsValueType) { if (elementType.IsEnum) { Type enumType = System.Enum.GetUnderlyingType(elementType); if (enumType == typeof(uint)) { methodInfo = GenericType.Get(elementType).BinaryDeSerializeEnumUIntArrayMethod; // DeSerializeMethodCache.EnumUIntArrayMethod.MakeGenericMethod(elementType); } else if (enumType == typeof(byte)) { methodInfo = GenericType.Get(elementType).BinaryDeSerializeEnumByteArrayMethod; // DeSerializeMethodCache.EnumByteArrayMethod.MakeGenericMethod(elementType); } else if (enumType == typeof(ulong)) { methodInfo = GenericType.Get(elementType).BinaryDeSerializeEnumULongArrayMethod; // DeSerializeMethodCache.EnumULongArrayMethod.MakeGenericMethod(elementType); } else if (enumType == typeof(ushort)) { methodInfo = GenericType.Get(elementType).BinaryDeSerializeEnumUShortArrayMethod; // DeSerializeMethodCache.EnumUShortArrayMethod.MakeGenericMethod(elementType); } else if (enumType == typeof(long)) { methodInfo = GenericType.Get(elementType).BinaryDeSerializeEnumLongArrayMethod; // DeSerializeMethodCache.EnumLongArrayMethod.MakeGenericMethod(elementType); } else if (enumType == typeof(short)) { methodInfo = GenericType.Get(elementType).BinaryDeSerializeEnumShortArrayMethod; // DeSerializeMethodCache.EnumShortArrayMethod.MakeGenericMethod(elementType); } else if (enumType == typeof(sbyte)) { methodInfo = GenericType.Get(elementType).BinaryDeSerializeEnumSByteArrayMethod; // DeSerializeMethodCache.EnumSByteArrayMethod.MakeGenericMethod(elementType); } else { methodInfo = GenericType.Get(elementType).BinaryDeSerializeEnumIntArrayMethod; // DeSerializeMethodCache.EnumIntArrayMethod.MakeGenericMethod(elementType); } IsReferenceMember = false; } else if (elementType.IsGenericType && elementType.GetGenericTypeDefinition() == typeof(Nullable <>)) { //methodInfo = DeSerializeMethodCache.NullableArrayMethod.MakeGenericMethod(elementType = elementType.GetGenericArguments()[0]); methodInfo = StructGenericType.Get(elementType = elementType.GetGenericArguments()[0]).BinaryDeSerializeNullableArrayMethod; IsReferenceMember = SerializeMethodCache.IsReferenceMember(elementType); } else { //methodInfo = DeSerializeMethodCache.StructArrayMethod.MakeGenericMethod(elementType); methodInfo = GenericType.Get(elementType).BinaryDeSerializeStructArrayMethod; IsReferenceMember = SerializeMethodCache.IsReferenceMember(elementType); } } else { //methodInfo = DeSerializeMethodCache.ArrayMethod.MakeGenericMethod(elementType); methodInfo = ClassGenericType.Get(elementType).BinaryDeSerializeArrayMethod; IsReferenceMember = SerializeMethodCache.IsReferenceMember(elementType); } DefaultDeSerializer = (deSerialize)Delegate.CreateDelegate(typeof(deSerialize), methodInfo); return; } } DefaultDeSerializer = fromNull; IsReferenceMember = false; return; } if (type.IsEnum) { Type enumType = System.Enum.GetUnderlyingType(type); if (enumType == typeof(uint)) { DefaultDeSerializer = enumUInt; } else if (enumType == typeof(byte)) { DefaultDeSerializer = enumByte; } else if (enumType == typeof(ulong)) { DefaultDeSerializer = enumULong; } else if (enumType == typeof(ushort)) { DefaultDeSerializer = enumUShort; } else if (enumType == typeof(long)) { DefaultDeSerializer = enumLong; } else if (enumType == typeof(short)) { DefaultDeSerializer = enumShort; } else if (enumType == typeof(sbyte)) { DefaultDeSerializer = enumSByte; } else { DefaultDeSerializer = enumInt; } IsReferenceMember = false; isValueType = true; return; } if (type.IsPointer || typeof(Delegate).IsAssignableFrom(type)) { DefaultDeSerializer = fromNull; IsReferenceMember = false; isValueType = true; return; } if (type.IsGenericType) { Type genericType = type.GetGenericTypeDefinition(); Type[] parameterTypes = type.GetGenericArguments(); if (genericType == typeof(LeftArray <>)) { //DefaultDeSerializer = (deSerialize)Delegate.CreateDelegate(typeof(deSerialize), DeSerializeMethodCache.LeftArrayDeSerializeMethod.MakeGenericMethod(type.GetGenericArguments())); DefaultDeSerializer = (deSerialize)Delegate.CreateDelegate(typeof(deSerialize), GenericType.Get(type.GetGenericArguments()[0]).BinaryDeSerializeLeftArrayMethod); IsReferenceMember = SerializeMethodCache.IsReferenceMember(parameterTypes[0]); isValueType = true; return; } #if !Serialize if (genericType == typeof(SubArray <>)) { //DefaultDeSerializer = (deSerialize)Delegate.CreateDelegate(typeof(deSerialize), DeSerializeMethodCache.SubArrayDeSerializeMethod.MakeGenericMethod(type.GetGenericArguments())); DefaultDeSerializer = (deSerialize)Delegate.CreateDelegate(typeof(deSerialize), GenericType.Get(type.GetGenericArguments()[0]).BinaryDeSerializeSubArrayMethod); IsReferenceMember = SerializeMethodCache.IsReferenceMember(parameterTypes[0]); isValueType = true; return; } #endif if (genericType == typeof(Dictionary <,>)) { //DefaultDeSerializer = (deSerialize)Delegate.CreateDelegate(typeof(deSerialize), DeSerializeMethodCache.DictionaryDeSerializeMethod.MakeGenericMethod(type.GetGenericArguments())); DefaultDeSerializer = (deSerialize)Delegate.CreateDelegate(typeof(deSerialize), GenericType2.Get(type.GetGenericArguments()).BinaryDeSerializeDictionaryMethod); IsReferenceMember = SerializeMethodCache.IsReferenceMember(parameterTypes[0]) || SerializeMethodCache.IsReferenceMember(parameterTypes[1]); isValueType = true; return; } if (genericType == typeof(Nullable <>)) { //DefaultDeSerializer = (deSerialize)Delegate.CreateDelegate(typeof(deSerialize), DeSerializeMethodCache.NullableDeSerializeMethod.MakeGenericMethod(type.GetGenericArguments())); DefaultDeSerializer = (deSerialize)Delegate.CreateDelegate(typeof(deSerialize), StructGenericType.Get(type.GetGenericArguments()[0]).BinaryDeSerializeNullableMethod); IsReferenceMember = SerializeMethodCache.IsReferenceMember(parameterTypes[0]); isValueType = true; return; } if (genericType == typeof(KeyValuePair <,>)) { //DefaultDeSerializer = (deSerialize)Delegate.CreateDelegate(typeof(deSerialize), DeSerializeMethodCache.KeyValuePairDeSerializeMethod.MakeGenericMethod(type.GetGenericArguments())); DefaultDeSerializer = (deSerialize)Delegate.CreateDelegate(typeof(deSerialize), GenericType2.Get(type.GetGenericArguments()).BinaryDeSerializeKeyValuePairMethod); IsReferenceMember = SerializeMethodCache.IsReferenceMember(parameterTypes[0]) || SerializeMethodCache.IsReferenceMember(parameterTypes[1]); isValueType = true; return; } if (genericType == typeof(SortedDictionary <,>)) { //DefaultDeSerializer = (deSerialize)Delegate.CreateDelegate(typeof(deSerialize), DeSerializeMethodCache.SortedDictionaryDeSerializeMethod.MakeGenericMethod(type.GetGenericArguments())); DefaultDeSerializer = (deSerialize)Delegate.CreateDelegate(typeof(deSerialize), GenericType2.Get(type.GetGenericArguments()).BinaryDeSerializeSortedDictionaryMethod); IsReferenceMember = SerializeMethodCache.IsReferenceMember(parameterTypes[0]) || SerializeMethodCache.IsReferenceMember(parameterTypes[1]); isValueType = true; return; } if (genericType == typeof(SortedList <,>)) { //DefaultDeSerializer = (deSerialize)Delegate.CreateDelegate(typeof(deSerialize), DeSerializeMethodCache.SortedListDeSerializeMethod.MakeGenericMethod(type.GetGenericArguments())); DefaultDeSerializer = (deSerialize)Delegate.CreateDelegate(typeof(deSerialize), GenericType2.Get(type.GetGenericArguments()).BinaryDeSerializeSortedListMethod); IsReferenceMember = SerializeMethodCache.IsReferenceMember(parameterTypes[0]) || SerializeMethodCache.IsReferenceMember(parameterTypes[1]); isValueType = true; return; } } if ((methodInfo = SerializeMethodCache.GetCustom(type, false)) != null) { if (type.IsValueType) { #if NOJIT DefaultDeSerializer = new CustomDeSerializer(methodInfo).DeSerialize; #else DynamicMethod dynamicMethod = new DynamicMethod("CustomDeSerializer", null, new Type[] { typeof(DeSerializer), type.MakeByRefType() }, type, true); ILGenerator generator = dynamicMethod.GetILGenerator(); generator.Emit(OpCodes.Ldarg_1); generator.Emit(OpCodes.Ldarg_0); generator.call(methodInfo); generator.Emit(OpCodes.Ret); DefaultDeSerializer = (deSerialize)dynamicMethod.CreateDelegate(typeof(deSerialize)); #endif } else { DefaultDeSerializer = (deSerialize)Delegate.CreateDelegate(typeof(deSerialize), methodInfo); } IsReferenceMember = attribute.IsReferenceMember; isValueType = true; return; } if (type.IsAbstract || type.IsInterface || Emit.Constructor <valueType> .New == null) { DefaultDeSerializer = noConstructor; isValueType = IsReferenceMember = true; return; } IsReferenceMember = attribute.IsReferenceMember; foreach (Type interfaceType in type.GetInterfaces()) { if (interfaceType.IsGenericType) { Type genericType = interfaceType.GetGenericTypeDefinition(); if (genericType == typeof(ICollection <>)) { Type[] parameters = interfaceType.GetGenericArguments(); Type argumentType = parameters[0]; parameters[0] = argumentType.MakeArrayType(); ConstructorInfo constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, parameters, null); if (constructorInfo != null) { //methodInfo = (type.IsValueType ? DeSerializeMethodCache.StructCollectionMethod : DeSerializeMethodCache.ClassCollectionMethod).MakeGenericMethod(type, argumentType); if (type.IsValueType) { methodInfo = CollectionGenericType2.Get(type, argumentType).BinaryDeSerializeStructCollectionMethod; } else { methodInfo = CollectionGenericType2.Get(type, argumentType).BinaryDeSerializeClassCollectionMethod; } break; } parameters[0] = typeof(IList <>).MakeGenericType(argumentType); constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, parameters, null); if (constructorInfo != null) { //methodInfo = (type.IsValueType ? DeSerializeMethodCache.StructCollectionMethod : DeSerializeMethodCache.ClassCollectionMethod).MakeGenericMethod(type, argumentType); if (type.IsValueType) { methodInfo = CollectionGenericType2.Get(type, argumentType).BinaryDeSerializeStructCollectionMethod; } else { methodInfo = CollectionGenericType2.Get(type, argumentType).BinaryDeSerializeClassCollectionMethod; } break; } parameters[0] = typeof(ICollection <>).MakeGenericType(argumentType); constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, parameters, null); if (constructorInfo != null) { //methodInfo = (type.IsValueType ? DeSerializeMethodCache.StructCollectionMethod : DeSerializeMethodCache.ClassCollectionMethod).MakeGenericMethod(type, argumentType); if (type.IsValueType) { methodInfo = CollectionGenericType2.Get(type, argumentType).BinaryDeSerializeStructCollectionMethod; } else { methodInfo = CollectionGenericType2.Get(type, argumentType).BinaryDeSerializeClassCollectionMethod; } break; } parameters[0] = typeof(IEnumerable <>).MakeGenericType(argumentType); constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, parameters, null); if (constructorInfo != null) { //methodInfo = (type.IsValueType ? DeSerializeMethodCache.StructCollectionMethod : DeSerializeMethodCache.ClassCollectionMethod).MakeGenericMethod(type, argumentType); if (type.IsValueType) { methodInfo = CollectionGenericType2.Get(type, argumentType).BinaryDeSerializeStructCollectionMethod; } else { methodInfo = CollectionGenericType2.Get(type, argumentType).BinaryDeSerializeClassCollectionMethod; } break; } } else if (genericType == typeof(IDictionary <,>)) { ConstructorInfo constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { interfaceType }, null); if (constructorInfo != null) { Type[] parameters = interfaceType.GetGenericArguments(); //methodInfo = (type.IsValueType ? DeSerializeMethodCache.StructDictionaryDeSerializeMethod : DeSerializeMethodCache.ClassDictionaryDeSerializeMethod).MakeGenericMethod(type, parameters[0], parameters[1]); if (type.IsValueType) { methodInfo = DictionaryGenericType3.Get(type, parameters[0], parameters[1]).BinaryDeSerializeStructDictionaryMethod; } else { methodInfo = DictionaryGenericType3.Get(type, parameters[0], parameters[1]).BinaryDeSerializeClassDictionaryMethod; } break; } } } } if (methodInfo != null) { DefaultDeSerializer = (deSerialize)Delegate.CreateDelegate(typeof(deSerialize), methodInfo); return; } if (type.IsValueType) { isValueType = true; } else if (attribute != Serializer.DefaultAttribute && attributeType != type) { for (Type baseType = type.BaseType; baseType != typeof(object); baseType = baseType.BaseType) { SerializeAttribute baseAttribute = baseType.customAttribute <SerializeAttribute>(); if (baseAttribute != null) { if (baseAttribute.IsBaseType) { methodInfo = DeSerializeMethodCache.BaseSerializeMethod.MakeGenericMethod(baseType, type); DefaultDeSerializer = (deSerialize)Delegate.CreateDelegate(typeof(deSerialize), methodInfo); return; } break; } } } LeftArray <DeSerializeVersionField> attributeFields = new LeftArray <DeSerializeVersionField>(); if ((attribute.MemberFilters & MemberFilters.PublicInstanceField) != 0) { appendField(ref attributeFields, MemberIndexGroup <valueType> .Group.PublicFields); } else { foreach (FieldIndex field in MemberIndexGroup <valueType> .Group.PublicFields) { attributeFields.Add(new DeSerializeVersionField { Field = field }); } } if ((attribute.MemberFilters & MemberFilters.NonPublicInstanceField) != 0) { appendField(ref attributeFields, MemberIndexGroup <valueType> .Group.NonPublicFields); } if (attribute.IsAnonymousFields) { appendField(ref attributeFields, MemberIndexGroup <valueType> .Group.AnonymousFields); } foreach (FieldIndex field in new MemberIndexGroup(type, true).NonPublicFields) { Type fieldType = field.Member.FieldType; if (!fieldType.IsPointer && (!fieldType.IsArray || fieldType.GetArrayRank() == 1) && !field.IsIgnore && !typeof(Delegate).IsAssignableFrom(fieldType)) { SerializeMemberAttribute memberAttribute = field.GetAttribute <SerializeMemberAttribute>(true); if (memberAttribute != null && memberAttribute.IsSetup && memberAttribute.RemoveGlobalVersion != memberAttribute.GlobalVersion) { attributeFields.Add(new DeSerializeVersionField { Field = field, Attribute = memberAttribute }); if (memberAttribute.IsRemove) { attributeFields.Add(new DeSerializeVersionField { Field = field, Attribute = memberAttribute, IsRemove = true }); } } } } isMemberMap = attribute.GetIsMemberMap; isJson = attribute.GetIsJson; uint globalVersion = 0, removeMemberCount = 0; int noSerializeMemberCount = 0; LeftArray <DeSerializeVersionFields <valueType> > deSerializeVersionFields = default(LeftArray <DeSerializeVersionFields <valueType> >); LeftArray <DeSerializeVersionField> attributeVersionFields = new LeftArray <DeSerializeVersionField>(attributeFields.Length); foreach (DeSerializeVersionField field in attributeFields.Sort(DeSerializeVersionField.GlobalVersionSort)) { if (field.GlobalVersion != globalVersion) { deSerializeVersionFields.Add(new DeSerializeVersionFields <valueType>(globalVersion, attributeVersionFields.GetArray(), removeMemberCount, noSerializeMemberCount)); globalVersion = field.GlobalVersion; } if (field.IsRemove) { attributeVersionFields.RemoveToEnd(value => object.ReferenceEquals(value.Field, field.Field)); if (field.Attribute.IsRemove) { --removeMemberCount; } } else { attributeVersionFields.Add(field); if (field.Attribute != null) { if (field.Attribute.IsRemove) { ++removeMemberCount; } } else { ++noSerializeMemberCount; } } } fieldDeSerializer = new DeSerializeVersionFields <valueType>(globalVersion, attributeVersionFields.GetArray(), removeMemberCount, noSerializeMemberCount).CreateOnly(attribute); if (deSerializeVersionFields.Length != 0) { int count = deSerializeVersionFields.Length; DeSerializeVersionFields <valueType>[] deSerializeVersionFieldsArray = new DeSerializeVersionFields <valueType> [count]; foreach (DeSerializeVersionFields <valueType> value in deSerializeVersionFields) { deSerializeVersionFieldsArray[--count] = value; deSerializeVersionFieldsArray[count].CreateLock = new object(); } fieldDeSerializers = deSerializeVersionFieldsArray; } }
/// <summary> /// 安装下一个类型 /// </summary> protected override void nextCreate() { MemberIndex identity = Identity = null; int isIdentityCase = SqlStreamTypeCount = 0; LeftArray <MemberIndex> members = default(LeftArray <MemberIndex>), primaryKeys = default(LeftArray <MemberIndex>), indexMembers = default(LeftArray <MemberIndex>); LeftArray <CountMember> counterMembers = default(LeftArray <CountMember>); LeftArray <MemberIndex> nowTimeMembers = default(LeftArray <MemberIndex>); LeftArray <LogMember> logMembers = new LeftArray <LogMember>(); LeftArray <string> strings = default(LeftArray <string>); foreach (MemberIndex member in MemberIndex.GetMembers(Type, Attribute.MemberFilters)) { if (!member.IsIgnore) { AutoCSer.Sql.MemberAttribute attribute = member.GetAttribute <AutoCSer.Sql.MemberAttribute>(false); bool isMember = attribute == null || attribute.IsSetup; if (Attribute.LogServerName != null) { AutoCSer.Sql.LogAttribute logAttribute = member.GetAttribute <AutoCSer.Sql.LogAttribute>(false); if (logAttribute != null) { logMembers.Add(new LogMember { Member = member, Attribute = logAttribute, MemberAttribute = attribute }); if (!logAttribute.IsMember) { isMember = false; } } } if (isMember) { members.Add(member); if (attribute != null) { if (attribute.IsMemberIndex) { indexMembers.Add(member); } if (attribute.IsNowTime && (member.MemberSystemType == typeof(DateTime) || member.MemberSystemType == typeof(DateTime?))) { nowTimeMembers.Add(member); } if (attribute.PrimaryKeyIndex != 0) { primaryKeys.Add(member); } if (attribute.IsIdentity) { Identity = member; } } if (Identity == null) { if (isIdentityCase == 0 && member.MemberName == AutoCSer.Sql.Field.IdentityName) { identity = member; isIdentityCase = 1; } else if (identity == null && member.MemberName.Length == AutoCSer.Sql.Field.IdentityName.Length && member.MemberName.ToLower() == AutoCSer.Sql.Field.IdentityName) { identity = member; } } AutoCSer.Sql.CountAttribute countAttribute = member.GetAttribute <AutoCSer.Sql.CountAttribute>(false); if (countAttribute != null) { counterMembers.Add(new CountMember { Member = member, Attribute = countAttribute }); } if (member.MemberSystemType == typeof(string) && (attribute == null || (attribute.MaxStringLength == 0 && !attribute.IsIgnoreMaxStringLength))) { strings.Add(member.MemberName); } } } } if (Identity == null) { Identity = identity; } if (Attribute.LogServerName == null) { LogMembers = NullValue <LogMember> .Array; } else { LogMembers = logMembers.ToArray(); if (!Attribute.IsDefaultSerialize && Attribute.IsLogMemberMap) { AutoCSer.BinarySerialize.SerializeAttribute dataSerialize = Type.Type.customAttribute <AutoCSer.BinarySerialize.SerializeAttribute>(); if (dataSerialize != null && !dataSerialize.IsMemberMap) { Messages.Message("数据库日志流处理类型 " + Type.FullName + " 序列化不支持成员位图"); } } foreach (LogMember member in LogMembers) { if (member.Attribute.CountType != null) { ++SqlStreamTypeCount; } } } CounterMembers = counterMembers.ToArray(); IndexMembers = indexMembers.ToArray(); NowTimeMembers = nowTimeMembers.ToArray(); if (strings.Length != 0) { Messages.Message(Type.FullName + " 字符串字段缺少最大长度限制 " + string.Join(",", strings.ToArray())); } WebPaths.Length = 0; ListArray <WebPathType> types; if (webPathTypes == null) { webPathTypes = new Dictionary <Type, ListArray <WebPathType> >(); foreach (Type nextType in AutoParameter.Types) { AutoCSer.WebView.PathAttribute webPath = nextType.customAttribute <AutoCSer.WebView.PathAttribute>(); if (webPath != null && webPath.Type != null && webPath.MemberName != null) { FieldInfo[] fields = nextType.GetFields(BindingFlags.Instance | BindingFlags.Public); if (fields.Length != 0) { if (!webPathTypes.TryGetValue(webPath.Type, out types)) { webPathTypes.Add(webPath.Type, types = new ListArray <WebPathType>()); } int memberIndex = fields.Length; types.Add(new WebPathType { MemberType = nextType, Attribute = webPath, Members = fields.getArray(value => new MemberIndex(value, --memberIndex)) }); } } } } if (webPathTypes.TryGetValue(Type, out types)) { foreach (WebPathType webPath in types) { MemberIndex[] fields = webPath.CheckMembers(ref members); if (fields != null) { WebPaths.Add(new WebPathType { MemberType = webPath.MemberType, Attribute = webPath.Attribute, Members = fields }); } } } dataPrimaryKey.Run(Type, PrimaryKeys = primaryKeys.ToArray()); create(true); }
/// <summary> /// 安装下一个类型 /// </summary> protected override void nextCreate() { if ((Attribute.IsAbstract || Type.Type.IsSealed || !Type.Type.IsAbstract) && !Type.Type.IsInterface) { defaultServerName = Attribute.ServerName; defaultServer = null; defaultType = null; if (defaultServerName != null) { HashString nameKey = defaultServerName; if (!servers.TryGetValue(nameKey, out defaultServer)) { servers.Add(nameKey, defaultServer = new Server()); } defaultServer.Attribute.Name = defaultServerName; defaultServer.Types.Add(defaultType = new ServerType { Type = Type, Attribute = Attribute }); if (Attribute.IsServer) { defaultServer.AttributeType = Type; defaultServer.Attribute.CopyFrom(Attribute); } } RemoteLinkType remoteLinkType = null; if (Attribute.ServerName != null) { if (Attribute.IsRemoteLinkType) { remoteLinkType = new RemoteLinkType { Type = Type, ParameterType = Type } } ; else if (Attribute.IsRemoteLink) { remoteLinkType = GetRemoteLinkType(Type); } } LeftArray <RemoteMethod> remoteMethods = new LeftArray <RemoteMethod>(); foreach (MethodIndex method in MethodIndex.GetMethods <AutoCSer.Net.TcpStaticServer.MethodAttribute>(Type, Attribute.MemberFilters, false, Attribute.IsAttribute, Attribute.IsBaseTypeAttribute)) { next(new TcpMethod { Method = method, MethodType = Type }); if (remoteLinkType != null && !method.Method.IsGenericMethodDefinition) { AutoCSer.Net.TcpStaticServer.RemoteMemberAttribute remoteAttribute = method.GetSetupAttribute <AutoCSer.Net.TcpStaticServer.RemoteMemberAttribute>(false); if (remoteAttribute != null && remoteAttribute.IsClientRemoteMember) { MethodParameter[] parameters = method.Parameters; if (parameters.Length >= 1 && parameters[0].ParameterType.Type == remoteLinkType.ParameterType) { remoteMethods.Add(new RemoteMethod { Type = Type, Method = method, MethodParameters = parameters, Attribute = remoteAttribute }); } } } } if (remoteLinkType != null) { remoteLinkType.RemoteMethods = remoteMethods.ToArray(); LeftArray <RemoteMember> remoteMembers = new LeftArray <RemoteMember>(); foreach (MemberIndex member in MemberIndex.GetMembers <AutoCSer.Net.TcpStaticServer.RemoteMemberAttribute>(Type, AutoCSer.Metadata.MemberFilters.NonPublicInstanceProperty, true, false)) { if (member.CanGet) { AutoCSer.Net.TcpStaticServer.RemoteMemberAttribute remoteAttribute = member.GetSetupAttribute <AutoCSer.Net.TcpStaticServer.RemoteMemberAttribute>(false); if (remoteAttribute != null) { if (member.IsField || ((PropertyInfo)member.Member).GetIndexParameters().Length == 0) { remoteMembers.Add(new RemoteMember { Member = member, Attribute = remoteAttribute }); } } } } foreach (MethodIndex member in MethodIndex.GetMethods <AutoCSer.Net.TcpStaticServer.RemoteMemberAttribute>(Type, AutoCSer.Metadata.MemberFilters.NonPublicInstance, false, true, false)) { if (!member.Method.IsGenericMethodDefinition) { AutoCSer.Net.TcpStaticServer.RemoteMemberAttribute remoteAttribute = member.GetSetupAttribute <AutoCSer.Net.TcpStaticServer.RemoteMemberAttribute>(false); if (remoteAttribute != null) { remoteMembers.Add(new RemoteMember { Method = member, Attribute = remoteAttribute }); } } } remoteLinkType.RemoteMembers = remoteMembers.ToArray(); RemoteLinkBuilder cacheBuilder = new RemoteLinkBuilder(); foreach (MemberIndex member in MemberIndex.GetMembers <AutoCSer.Net.TcpStaticServer.RemoteLinkAttribute>(Type, AutoCSer.Metadata.MemberFilters.NonPublicInstance, true, false)) { cacheBuilder.Push(member); } remoteLinkType.RemoteLinks = cacheBuilder.Caches.ToArray(); if (remoteLinkType.IsRemoteLink) { defaultServer.RemoteLinkTypes.Add(remoteLinkType); } } if (!Type.Type.IsGenericType) { foreach (MemberIndexInfo member in StaticMemberIndexGroup.Get <AutoCSer.Net.TcpStaticServer.MethodAttribute>(Type, Attribute.MemberFilters, false, Attribute.IsAttribute, Attribute.IsBaseTypeAttribute)) { if (member.IsField) { FieldInfo field = (FieldInfo)member.Member; TcpMethod getMethod = new TcpMethod { Method = new Metadata.MethodIndex(field, true), MemberIndex = member, MethodType = Type }; if (!getMethod.Attribute.IsOnlyGetMember) { getMethod.SetMethod = new TcpMethod { Method = new Metadata.MethodIndex(field, false), MemberIndex = member, MethodType = Type }; } next(getMethod); if (getMethod.SetMethod != null) { next(getMethod.SetMethod); } } else if (member.CanGet) { PropertyInfo property = (PropertyInfo)member.Member; TcpMethod getMethod = new TcpMethod { Method = new Metadata.MethodIndex(property, true), MemberIndex = member, MethodType = Type }; if (member.CanSet && !getMethod.Attribute.IsOnlyGetMember) { getMethod.SetMethod = new TcpMethod { Method = new Metadata.MethodIndex(property, false), MemberIndex = member, MethodType = Type }; } next(getMethod); if (getMethod.SetMethod != null) { next(getMethod.SetMethod); } } } } serverTypes.Empty(); } }
internal void Insert(valueType value) { Array.Add(value); isSorted = false; }
/// <summary> /// 转换表达式 /// </summary> /// <param name="expression">表达式</param> /// <param name="isIn"></param> private void convertCall(MethodCallExpression expression, bool isIn) { System.Collections.ObjectModel.ReadOnlyCollection <Expression> arguments = expression.Arguments; System.Collections.IEnumerable values = (System.Collections.IEnumerable)arguments[1].GetConstant(); if (values != null) { LeftArray <object> array = new LeftArray <object>(); foreach (object value in values) { array.Add(value); } switch (array.Length) { case 0: break; case 1: Expression leftExpression = arguments[0]; if (array[0] == null) { convertIsSimple(leftExpression); SqlStream.SimpleWriteNotNull(isIn ? " is null" : " is not null"); } else { convertIsSimple(leftExpression); if (isIn) { SqlStream.Write('='); } else { SqlStream.Write('<'); SqlStream.Write('>'); } convertConstant(array[0]); } return; default: Convert(arguments[0]); SqlStream.SimpleWriteNotNull(isIn ? " In(" : " Not In("); Action <CharStream, object> toString = ConstantConverter[array[0].GetType()]; int index = 0; if (toString == null) { foreach (object value in array) { if (index == 0) { index = 1; } else { SqlStream.Write(','); } ConstantConverter.Convert(SqlStream, value.ToString()); } } else { foreach (object value in array) { if (index == 0) { index = 1; } else { SqlStream.Write(','); } toString(SqlStream, value); } } SqlStream.Write(')'); return; } } SqlStream.SimpleWriteNotNull(isIn ? "(1=0)" : "(1=1)"); }
/// <summary> /// 获取文本分词结果 /// </summary> /// <param name="textFixed"></param> /// <returns></returns> private bool get(char *textFixed) { char *start = textFixed, end = textFixed + formatLength; try { matchs.Length = 0; byte type, nextType; bool isMatchMap = false; if (charTypeData != StringTrieGraph.DefaultCharTypeData.Byte) { StaticStringTrieGraph trieGraph = searcher.trieGraph; int count, index, startIndex; char trieGraphHeadChar = trieGraph.AnyHeadChar; do { if (((type = charTypeData[*start]) & StringTrieGraph.TrieGraphHeadFlag) == 0) { *end = trieGraphHeadChar; do { if ((type & ((byte)WordType.Chinese | (byte)WordType.TrieGraph)) == ((byte)WordType.Chinese | (byte)WordType.TrieGraph)) { if (!checkAddWordLess((int)(start - textFixed), 1)) { return(false); } } if (((nextType = charTypeData[*++start]) & StringTrieGraph.TrieGraphHeadFlag) != 0) { if (start == end) { goto TRIEGRAPHEND; } if ((nextType & (byte)WordType.Chinese) != 0 || (type & nextType & ((byte)WordType.OtherLetter | (byte)WordType.Letter | (byte)WordType.Number | (byte)WordType.Keep)) == 0) { goto TRIEGRAPH; } } type = nextType; }while (true); } TRIEGRAPH: *end = ' '; char *segment = start, segmentEnd = (type & StringTrieGraph.TrieGraphEndFlag) == 0 ? start++ : ++start; while (((type = charTypeData[*start]) & (byte)WordType.TrieGraph) != 0) { ++start; if ((type & StringTrieGraph.TrieGraphEndFlag) != 0) { segmentEnd = start; } } if ((int)(start - segment) == 1) { if ((charTypeData[*segment] & (byte)WordType.Chinese) != 0) { if (!checkAddWordLess((int)(segment - textFixed), 1)) { return(false); } } } else { if (segment != segmentEnd) { matchs.Length = 0; trieGraph.LeftRightMatchs(segment, segmentEnd, ref matchs); if ((count = matchs.Length) == 0) { segmentEnd = segment; goto CHINESE; } if (!isMatchMap) { checkMatchMap(); isMatchMap = true; } startIndex = (int)(segment - textFixed); foreach (KeyValue <int, int> value in matchs.Array) { if (checkAddWord(index = value.Key + startIndex, value.Value)) { matchMap.Set(index, value.Value); } else { lessWords.Add(new SubString(index, value.Value, formatText)); } if (--count == 0) { break; } } index = (int)(segmentEnd - textFixed); do { if (matchMap.Get(startIndex) == 0 && (charTypeData[textFixed[startIndex]] & (byte)WordType.Chinese) != 0) { if (!checkAddWordLess(startIndex, 1)) { return(false); } } }while (++startIndex != index); } CHINESE: while (segmentEnd != start) { if ((charTypeData[*segmentEnd] & (byte)WordType.Chinese) != 0) { if (!checkAddWordLess((int)(segmentEnd - textFixed), 1)) { return(false); } } ++segmentEnd; } } }while (start != end); TRIEGRAPHEND: start = textFixed; } do { type = charTypeData[*start]; if ((type &= ((byte)WordType.Chinese | (byte)WordType.OtherLetter | (byte)WordType.Letter | (byte)WordType.Number | (byte)WordType.Keep)) == 0) { *end = '0'; do { type = charTypeData[*++start]; if ((type &= ((byte)WordType.Chinese | (byte)WordType.OtherLetter | (byte)WordType.Letter | (byte)WordType.Number | (byte)WordType.Keep)) != 0) { if (start == end) { return(true); } goto OTHER; } }while (true); } OTHER: *end = ' '; if ((type & (byte)WordType.Chinese) != 0) { type = charTypeData[*start]; do { if (matchType != MatchType.All && (type & (byte)WordType.TrieGraph) == 0) { checkAddWordLess((int)(start - textFixed), 1); } }while (((type = charTypeData[*++start]) & (byte)WordType.Chinese) != 0); } else { char *segment = start; if ((type & (byte)WordType.OtherLetter) == 0) { char *word = start; bool isWord = false; for (nextType = charTypeData[*++start]; (nextType &= ((byte)WordType.Letter | (byte)WordType.Number | (byte)WordType.Keep)) != 0; nextType = charTypeData[*++start]) { if (type != nextType) { if (type != (byte)WordType.Keep) { if (!checkAddWord((int)(word - textFixed), (int)(start - word))) { return(false); } isWord = true; } type = nextType; word = start; } } if (word != segment && type != (byte)WordType.Keep) { if (!checkAddWord((int)(word - textFixed), (int)(start - word))) { return(false); } isWord = true; } if (!isWord) { if (!checkAddWord((int)(segment - textFixed), (int)(start - segment))) { return(false); } } } else { while ((charTypeData[*++start] & (byte)WordType.OtherLetter) != 0) { ; } if (!checkAddWord((int)(segment - textFixed), (int)(start - segment))) { return(false); } } } }while (start != end); if (lessWords.Length != 0) { if (isMatchMap) { SubString[] wordArray = lessWords.Array; for (int index = lessWords.Length; index != 0;) { int mapIndex = wordArray[--index].Start, endIndex = wordArray[index].EndIndex; do { if (matchMap.Get(mapIndex) == 0) { break; } }while (++mapIndex != endIndex); if (mapIndex == endIndex && index != --lessWords.Length) { wordArray[index] = wordArray[lessWords.Length]; } } } if (matchType == MatchType.All && lessWords.Length != 0) { return(false); } } } finally { *end = ' '; } return(true); }
/// <summary> /// 获取查询信息 /// </summary> /// <typeparam name="valueType">对象类型</typeparam> /// <typeparam name="modelType">模型类型</typeparam> /// <param name="sqlTool">SQL操作工具</param> /// <param name="connection"></param> /// <param name="query">查询信息</param> /// <returns>对象集合</returns> internal virtual LeftArray <valueType> Select <valueType, modelType>(Sql.Table <valueType, modelType> sqlTool, ref DbConnection connection, ref SelectQuery <modelType> query) where valueType : class, modelType where modelType : class { try { if (query.Sql != null) { if (connection == null) { connection = GetConnection(); } if (connection != null) { if (query.IndexFieldName != null) { sqlTool.CreateIndex(connection, query.IndexFieldName, false); query.IndexFieldName = null; } using (DbCommand command = getCommand(connection, query.Sql)) { DbDataReader reader = null; try { reader = command.ExecuteReader(CommandBehavior.SingleResult); } catch (Exception error) { sqlTool.Log.Add(AutoCSer.Log.LogType.Error, error, query.Sql); } if (reader != null) { using (reader) { int skipCount = query.SkipCount; while (skipCount != 0 && reader.Read()) { --skipCount; } if (skipCount == 0) { LeftArray <valueType> array = new LeftArray <valueType>(); while (reader.Read()) { valueType value = AutoCSer.Emit.Constructor <valueType> .New(); DataModel.Model <modelType> .Setter.Set(reader, value, query.MemberMap); array.Add(value); } return(array); } } } } } } } finally { query.Free(); } return(default(LeftArray <valueType>)); }
/// <summary> /// 生成代码 /// </summary> /// <param name="fileName">模板文件名</param> /// <returns>代码</returns> private static LeftArray <string> code(string fileName) { string code = File.ReadAllText(fileName); int index = code.IndexOf(@"*/ ", StringComparison.Ordinal); if (index != -1) { int startIndex = index += 4, count = 0; Dictionary <SubString, Replace> keys = DictionaryCreator.CreateSubString <Replace>(); Replace replace; foreach (string keyValue in code.Substring(0, index).Split(new string[] { "/*" }, StringSplitOptions.None)) { if (count == 0) { count = 1; continue; } if ((index = keyValue.IndexOf(':')) != -1 && keyValue.EndsWith(@"*/ ", StringComparison.Ordinal)) { keys[new SubString { String = keyValue, StartIndex = 0, Length = index }] = replace = new Replace { values = new SubString { String = keyValue, StartIndex = ++index, Length = keyValue.Length - index - 4 }.Split(';').GetArray(value => value.Split(',')) }; replace.indexs = new LeftArray <int> [replace.values[0].Length]; } else { Messages.Add("自定义数据错误 : " + keyValue); } } LeftArray <string> codeList = new LeftArray <string>(); for (code = code.Substring(startIndex), startIndex = 0, index = code.IndexOf("/*", StringComparison.Ordinal); index != -1; index = code.IndexOf("/*", startIndex)) { codeList.Add(code.Substring(startIndex, index - startIndex)); if ((startIndex = code.IndexOf("*/", index, StringComparison.Ordinal) + 2) != 1 && startIndex != index + 4) { string name = code.Substring(index, startIndex - index); if ((index = code.IndexOf(name, startIndex, StringComparison.Ordinal)) != -1) { startIndex = index + name.Length; name = name.Substring(2, name.Length - 4); if (name[name.Length - 1] == ']') { int arrayIndex = name.LastIndexOf('[') + 1; if (arrayIndex == 0 || !int.TryParse(name.Substring(arrayIndex, name.Length - arrayIndex - 1), out index)) { Messages.Add("自定义名称索引错误 : " + name); index = 0; } else { name = name.Substring(0, arrayIndex - 1); } } else { index = 0; } if (keys.TryGetValue(name, out replace)) { replace.indexs[index].Add(codeList.Length); codeList.Add(string.Empty); } else { Messages.Add("自定义名称不匹配 : " + name); } } else { Messages.Add("自定义名称不匹配 : " + name); } } else { Messages.Add("自定义名称错误 : " + code.Substring(index)); startIndex = code.Length; } } codeList.Add(code.Substring(startIndex)); string[] codes = codeList.ToArray(); LeftArray <string> values = default(LeftArray <string>); Replace[] replaces = keys.Values.getArray(); do { index = replaces.Length; while (--index >= 0 && ++replaces[index].index == replaces[index].values.Length) { ; } if (index == -1) { break; } while (++index != replaces.Length) { replaces[index].index = 0; } for (index = replaces.Length; --index >= 0;) { replace = replaces[index]; LeftArray <SubString> replaceCode = replace.values[replace.index]; for (startIndex = replace.indexs.Length; --startIndex >= 0;) { foreach (int codeIndex in replace.indexs[startIndex]) { codes[codeIndex] = replaceCode[startIndex]; } } } values.Add(string.Concat(codes)); }while (true); return(values); } else { Messages.Add("自定义文件错误 : " + fileName); } return(default(LeftArray <string>)); }
/// <summary> /// 计算状态数量 /// </summary> /// <param name="start">起始名称位置</param> /// <param name="end">结束名称位置</param> /// <param name="current"></param> private void count(int start, int end, int current) { ++tableCount; int index = start, prefixSize = 0; char value = (char)0; while (names[start].Key.Length != current) { value = names[start].Key[current]; while (++index != end && names[index].Key[current] == value) { ; } if (index != end) { break; } ++prefixSize; index = start; ++current; } if (prefixSize != 0) { this.prefixSize += prefixSize + 1; } do { int count = index - start; if (count == 0) { index = ++start; } else { if (value == 0) { throw new IndexOutOfRangeException(); } chars.Add(value); if (count == 1) { ++stateCount; prefixSize = names[start].Key.Length - current - 1; if (prefixSize != 0) { this.prefixSize += prefixSize + 1; } } else { this.count(start, index, current + 1); } } if (index == end) { break; } value = names[start = index].Key[current]; while (++index != end && names[index].Key[current] == value) { ; } }while (true); }
/// <summary> /// 客户端创建目录信息 /// </summary> /// <param name="directoryInfo"></param> /// <param name="lastWriteTime"></param> /// <param name="searchPatterns"></param> /// <returns></returns> private static Directory create(DirectoryInfo directoryInfo, DateTime lastWriteTime, string[] searchPatterns) { Directory directory = new Directory(); DirectoryInfo[] directoryInfos = directoryInfo.GetDirectories(); if (directoryInfos.Length != 0) { LeftArray <Directory> directorys = new LeftArray <Directory>(directoryInfos.Length); foreach (DirectoryInfo nextDirectoryInfo in directoryInfos) { Directory nextDirectory = create(nextDirectoryInfo, lastWriteTime, searchPatterns); if (nextDirectory.Name != null) { directorys.Add(nextDirectory); } } if (directorys.Length != 0) { directory.Directorys = directorys.ToArray(); } } if (searchPatterns == null) { FileInfo[] files = directoryInfo.GetFiles(); if (files.Length != 0) { LeftArray <FileTime> fileTimes = new LeftArray <FileTime>(files.Length); foreach (FileInfo file in files) { if (file.LastWriteTimeUtc > lastWriteTime) { fileTimes.Add(new FileTime(file)); } } if (fileTimes.Length != 0) { directory.Files = fileTimes.ToArray(); } } } else { LeftArray <FileTime> fileTimes = new LeftArray <FileTime>(0); foreach (string searchPattern in searchPatterns) { foreach (FileInfo file in directoryInfo.GetFiles(searchPattern)) { if (file.LastWriteTimeUtc > lastWriteTime) { fileTimes.Add(new FileTime(file)); } } } if (fileTimes.Length != 0) { directory.Files = fileTimes.ToArray(); } } if (directory.Files != null || directory.Directorys != null) { directory.Name = directoryInfo.Name; } return(directory); }
/// <summary> /// 安装下一个类型 /// </summary> protected override void nextCreate() { Type modelType; AutoCSer.Sql.ModelAttribute modelAttribute = Type.Type.customAttribute <AutoCSer.Sql.ModelAttribute>(out modelType); if (modelAttribute != null) { AutoCSer.Net.TcpStaticServer.ServerAttribute serverAttribute = AutoCSer.Metadata.TypeAttribute.GetAttribute <AutoCSer.Net.TcpStaticServer.ServerAttribute>(Type, false); if (serverAttribute != null && serverAttribute.ServerName != null && !serverAttribute.IsRemoteLinkType && serverAttribute.IsRemoteLink && (RemoteLinkType = TcpStaticServer.Generator.GetRemoteLinkType(Type)) != null) { LeftArray <TcpStaticServer.Generator.RemoteMethod> remoteMethods = new LeftArray <TcpStaticServer.Generator.RemoteMethod>(); foreach (MethodIndex method in MethodIndex.GetMethods <AutoCSer.Net.TcpStaticServer.MethodAttribute>(Type, serverAttribute.MemberFilters, false, serverAttribute.IsAttribute, serverAttribute.IsBaseTypeAttribute)) { if (!method.Method.IsGenericMethodDefinition) { AutoCSer.Net.TcpStaticServer.RemoteMemberAttribute remoteAttribute = method.GetSetupAttribute <AutoCSer.Net.TcpStaticServer.RemoteMemberAttribute>(false); if (remoteAttribute != null && !remoteAttribute.IsClientRemoteMember) { MethodParameter[] parameters = method.Parameters; if (parameters.Length >= 1 && parameters[0].ParameterType == RemoteLinkType.ParameterType) { remoteMethods.Add(new TcpStaticServer.Generator.RemoteMethod { Type = Type, Method = method, MethodParameters = parameters, Attribute = remoteAttribute }); } } } } LeftArray <SqlModel.Generator.LogMember> logMembers = new LeftArray <SqlModel.Generator.LogMember>(); foreach (MemberIndex member in MemberIndex.GetMembers(modelType, modelAttribute.MemberFilters)) { if (!member.IsIgnore) { AutoCSer.Sql.MemberAttribute attribute = member.GetAttribute <AutoCSer.Sql.MemberAttribute>(false); if (modelAttribute.LogServerName != null) { AutoCSer.Sql.LogAttribute logAttribute = member.GetAttribute <AutoCSer.Sql.LogAttribute>(false); if (logAttribute != null) { SqlModel.Generator.LogMember logMember = new SqlModel.Generator.LogMember { Member = member, Attribute = logAttribute, MemberAttribute = attribute }; if (modelAttribute.LogServerName != null && logMember.IsProxy) { logMembers.Add(logMember); foreach (TcpStaticServer.Generator.RemoteMethod remoteMethod in remoteMethods) { if (remoteMethod.Attribute.MemberName == member.MemberName) { remoteMethod.Member = member; break; } } } } } } } RemoteMethods = remoteMethods.GetFindArray(value => value.Member != null); LogMembers = logMembers.Length != 0 && (modelAttribute.CacheType != AutoCSer.Sql.Cache.Whole.Event.Type.Unknown && modelAttribute.CacheType != AutoCSer.Sql.Cache.Whole.Event.Type.CreateMemberKey) ? logMembers.ToArray() : NullValue <SqlModel.Generator.LogMember> .Array; if ((LogMembers.Length | RemoteMethods.Length) != 0) { //create(true); IsRemoteMember = RemoteMethods.Length != 0 && TcpStaticServer.Generator.RemoteMemberTypes.Add(Type); CSharpTypeDefinition definition = new CSharpTypeDefinition(Type, true, false); _code_.Length = 0; create(false); Coder.Add(definition.Start + _partCodes_["SERVER"] + definition.End); TcpStaticServer.Generator.AddClientCode(new TcpStaticServer.Generator.ClientCode { Type = Type, Attribute = serverAttribute, Code = definition.Start + _partCodes_["CLIENT"] + definition.End, SegmentationCode = definition.Start + _partCodes_["CLIENTCALL"] + definition.End }); } } } }