Esempio n. 1
0
        public void SwapTest()
        {
            int a = 2;
            int b = 3;

            CsharpHelper.Swap(ref a, ref b);
            Assert.AreEqual(a, 3);
            Assert.AreEqual(b, 2);
        }
        private void EntityStruct(EntityConfig table, StringBuilder code, StringBuilder code2, ref bool isFirst)
        {
            if (table == null)
            {
                return;
            }
            if (!string.IsNullOrEmpty(table.ModelBase))
            {
                EntityStruct(Project.Entities.FirstOrDefault(p => p.Name == table.ModelBase), code, code2, ref isFirst);
            }

            foreach (PropertyConfig property in table.PublishProperty)
            {
                if (isFirst)
                {
                    isFirst = false;
                }
                else
                {
                    code.Append(',');
                }

                code.AppendFormat(@"
                {{
                    Real_{0},
                    new PropertySturct
                    {{
                        Index = Index_{0},
                        Name = ""{0}"",
                        Title = ""{5}"",
                        ColumnName = ""{4}"",
                        PropertyType = typeof({1}),
                        CanNull = {2},
                        ValueType = PropertyValueType.{3},
                        CanImport = {6},
                        CanExport = {7}
                    }}
                }}", property.Name
                                  , property.CustomType ?? property.CsType
                                  , property.Nullable ? "true" : "false"
                                  , CsharpHelper.PropertyValueType(property)
                                  , property.ColumnName
                                  , property.Caption
                                  , property["CanImport"] == "1" ? "true" : "false"
                                  , property["CanExport"] == "1" ? "true" : "false");
            }
            code2.Clear();
            foreach (PropertyConfig property in table.PublishProperty)
            {
                code2.AppendFormat(@"
        public const byte Index_{0} = {1};", property.Name, property.Index);
            }
        }
        public List <PropertyConfig> DoCheckFieldes(string arg)
        {
            var columns = new List <PropertyConfig>();
            var lines   = Fields.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            var idx     = 0;

            foreach (var line in lines)
            {
                if (string.IsNullOrEmpty(line))
                {
                    continue;
                }
                var words = line.Trim().Split(new[] { ',', ',' }, StringSplitOptions.RemoveEmptyEntries);

                var name = words[0].TrimStart('_').ToUWord();

                /*
                 * 文本说明:
                 * 1 每行为一条数据
                 * 2 每个单词用逗号分开
                 * 3 第一个单词 代码名称; 第二个单词 数据类型;第三个单词 说明文本
                 */
                PropertyConfig column = new PropertyConfig
                {
                    IsPrimaryKey = name.Equals("ID", StringComparison.OrdinalIgnoreCase),
                    ColumnName   = name,
                    Name         = name,
                    CsType       = "string",
                    DbType       = "nvarchar"
                };
                column.Option.Index = idx++;
                if (words.Length > 1)
                {
                    CsharpHelper.CheckType(column, words[1]);
                }
                if (words.Length > 2)
                {
                    column.Caption = words[2];
                }
                if (words.Length > 3)
                {
                    column.Description = words.Length < 4 ? null : words.Skip(3).LinkToString(",");
                }
                var old = columns.FirstOrDefault(p => p != null && p.Name == name);
                if (old != null)
                {
                    columns.Remove(old);
                }
                columns.Add(column);
            }

            return(columns);
        }
        public async Task <ActionResult> ProcessMethodDetails(string projectId)
        {
            var projectMaster = _floKaptureService.ProjectMasterRepository.GetById(projectId);

            if (projectMaster == null)
            {
                return(BadRequest($@"Project with id {projectId} not found!"));
            }

            var methodDetailsService   = new GeneralService().BaseRepository <MethodDetails>();
            var fieldOrPropertyService = new GeneralService().BaseRepository <FieldAndPropertyDetails>();
            var allCsFiles             = _floKaptureService.FileMasterRepository.GetAllListItems(f => f.ProjectId == projectId && f.FileTypeReferenceId == "60507f66591cfa72c53a859e");

            foreach (var fileMaster in allCsFiles)
            {
                if (!System.IO.File.Exists(fileMaster.FilePath))
                {
                    continue;
                }
                if (Regex.IsMatch(fileMaster.FilePath, "reference.cs|Service References|AssemblyInfo.cs", RegexOptions.IgnoreCase))
                {
                    continue;
                }
                var allLines      = System.IO.File.ReadAllText(fileMaster.FilePath);
                var returnedTuple = CsharpHelper.ExtractMemberDetails(allLines);
                var methodDetails = returnedTuple.Item1;
                var patternList   = (from mr in methodDetails where mr.ClassName != mr.MethodName select $@"\b{mr.ClassName}.{mr.MethodName}\b").ToList();
                if (methodDetails.Any() && patternList.Any())
                {
                    string pattern = string.Concat("(?<FoundMatch>", string.Join("|", patternList), ")");
                    methodDetails.Last().MethodMatchRegex = pattern;
                }
                foreach (var methodDetail in methodDetails)
                {
                    methodDetail.ProjectId = fileMaster.ProjectId;
                    methodDetail.FileId    = fileMaster._id;
                    await methodDetailsService.AddDocument(methodDetail).ConfigureAwait(false);
                }
                var fieldOrPropertyDetails = returnedTuple.Item2;
                foreach (var fieldOrProperty in fieldOrPropertyDetails)
                {
                    fieldOrProperty.ProjectId = fileMaster.ProjectId;
                    fieldOrProperty.FileId    = fileMaster._id;
                    await fieldOrPropertyService.AddDocument(fieldOrProperty).ConfigureAwait(false);
                }
            }
            return(Ok(projectMaster));
        }
Esempio n. 5
0
        public void RandomReservedTest()
        {
            var listA = new List <int>();
            var listB = new List <int>();

            for (int i = 0; i < 100; i++)
            {
                listA.Add(i);
                listB.Add(i);
            }
            CsharpHelper.RandomReserve(ref listA);
            bool equal = true;

            for (int i = 0; i < listA.Count; i++)
            {
                if (listA[i] != listB[i])
                {
                    equal = false;
                    break;
                }
            }
            Assert.IsFalse(equal);
        }
Esempio n. 6
0
        private static void CheckPropertyType(Type type, EntityConfig entity, PropertyConfig prperty, MemberInfo field, Type fieldType, bool json, bool dataMember)
        {
            try
            {
                prperty.Nullable = fieldType.IsSubclassOf(typeof(Nullable <>));
                Type type1 = prperty.Nullable ? fieldType.GetGenericArguments()[0] : fieldType;
                if (type1.IsArray)
                {
                    prperty.ReferenceType = ReflectionHelper.GetTypeName(type1);
                    prperty.IsArray       = true;
                    type1 = type1.MakeArrayType();
                }
                else if (type1.IsSupperInterface(typeof(IDictionary <,>)))
                {
                    prperty.ReferenceType = ReflectionHelper.GetTypeName(type1);
                    var pars = type1.GetGenericArguments();
                    prperty.IsDictionary = true;
                    prperty.CsType       = ReflectionHelper.GetTypeName(type1);
                    type1 = pars[1];
                }
                else if (type1.IsGenericType && type1.IsSupperInterface(typeof(IEnumerable <>)))
                {
                    prperty.ReferenceType = ReflectionHelper.GetTypeName(type1);
                    prperty.IsArray       = true;
                    type1 = type1.GetGenericArguments()[0];
                }

                CsharpHelper.CheckType(prperty, type1.GetTypeName());
                if (type1.IsEnum)
                {
                    prperty.CustomType = ReflectionHelper.GetTypeName(type1);
                    prperty.CsType     = "int";
                    prperty.IsEnum     = true;
                }
                else if (!type1.IsBaseType())
                {
                    //prperty.CustomType = ReflectionHelper.GetTypeName(type1);
                    prperty.NoStorage   = true;
                    prperty.IsLinkField = true;
                    prperty.LinkTable   = prperty.CustomType;
                }
            }
            catch (Exception ex)
            {
                prperty.CsType = "object";
                Trace.WriteLine(ex, $"Error : {type.FullName}.{field.Name}");
            }
            if (json)
            {
                var ji = field.GetAttribute <JsonIgnoreAttribute>();
                if (ji != null)
                {
                    prperty.NoneJson = true;
                }
                else
                {
                    var jp = field.GetAttribute <JsonPropertyAttribute>();
                    if (jp == null)
                    {
                        return;
                    }
                    prperty.NoneJson = false;
                    if (!string.IsNullOrWhiteSpace(jp.PropertyName))
                    {
                        prperty.JsonName = jp.PropertyName;
                    }
                }
            }
            else if (dataMember)
            {
                var id = field.GetAttribute <IgnoreDataMemberAttribute>();
                if (id != null)
                {
                    prperty.NoneJson = true;
                }
                var dm = field.GetAttribute <DataMemberAttribute>();
                if (dm == null)
                {
                    return;
                }
                prperty.NoneJson = false;
                if (!string.IsNullOrWhiteSpace(dm.Name))
                {
                    prperty.JsonName = dm.Name;
                }
            }
        }
        public async Task <ActionResult> StartParsingCsFiles(string projectId)
        {
            var projectMaster = _floKaptureService.ProjectMasterRepository.GetById(projectId);

            if (projectMaster == null)
            {
                return(BadRequest($@"Project with id {projectId} not found!"));
            }
            // var filterDefinition = _floKaptureService.FileMasterRepository.Filter.Or(_floKaptureService.FileMasterRepository.Filter.Eq(d => d.FileTypeReferenceId, "60507f342a60e0e6cbefd106"), _floKaptureService.FileMasterRepository.Filter.Eq(d => d.FileTypeReferenceId, "60507f66591cfa72c53a859e"));
            // var fileCursor = await _floKaptureService.FileMasterRepository.Collection.FindAsync<FileMaster>(filter: filterDefinition).ConfigureAwait(false);
            var allCsFiles = await _floKaptureService.FileMasterRepository.Aggregate() /*.Limit(200)*/.ToListAsync().ConfigureAwait(false);

            foreach (var fileMaster in allCsFiles)
            {
                var programLines             = System.IO.File.ReadAllLines(fileMaster.FilePath).ToList();
                var csLineDetails            = CsharpHelper.PrepareCsLineDetails(programLines);
                var assignedTryCatchCommands = BaseCommandExtractor.AssignBaseCommandToTryCatch(csLineDetails);
                var assignedBaseCommands     = BaseCommandExtractor.AssignBaseCommandId(assignedTryCatchCommands);
                int methods     = assignedBaseCommands.Count(d => d.BaseCommandId == 8);
                int endMethods  = assignedBaseCommands.Count(d => d.BaseCommandId == 9);
                int ifs         = assignedBaseCommands.Count(d => d.BaseCommandId == 1);
                int elses       = assignedBaseCommands.Count(d => d.BaseCommandId == 10);
                int endIfs      = assignedBaseCommands.Count(d => d.BaseCommandId == 2);
                int loops       = assignedBaseCommands.Count(d => d.BaseCommandId == 3);
                int endLoops    = assignedBaseCommands.Count(d => d.BaseCommandId == 4);
                int tries       = assignedBaseCommands.Count(d => d.BaseCommandId == 101);
                int endTries    = assignedBaseCommands.Count(d => d.BaseCommandId == 102);
                int catches     = assignedBaseCommands.Count(d => d.BaseCommandId == 201);
                int endCatches  = assignedBaseCommands.Count(d => d.BaseCommandId == 202);
                int finalies    = assignedBaseCommands.Count(d => d.BaseCommandId == 301);
                int endFinalies = assignedBaseCommands.Count(d => d.BaseCommandId == 302);
                int switches    = assignedBaseCommands.Count(d => d.BaseCommandId == 58);
                int endSwitches = assignedBaseCommands.Count(d => d.BaseCommandId == 59);
                int classes     = assignedBaseCommands.Count(d => d.BaseCommandId == 19);
                int endClasses  = assignedBaseCommands.Count(d => d.BaseCommandId == 20);

                if (!classes.Equals(endClasses) || !methods.Equals(endMethods) || !ifs.Equals(endIfs) || !loops.Equals(endLoops))
                {
                    Console.BackgroundColor = ConsoleColor.Red;
                    Console.WriteLine($"{fileMaster.FileName} # {fileMaster.FilePath}");
                    Console.BackgroundColor = ConsoleColor.Black;
                }

                Console.WriteLine($"==========================File Statistics=========================");
                Console.WriteLine($"=========================={fileMaster.FileName}===================");
                Console.WriteLine($"\nMethods: {methods}\nEndMethods: {endMethods}\nIfs: {ifs}" +
                                  $"\nElses: {elses}\nEnd Ifs: {endIfs}\nLoops: {loops}\nEnd Loops: {endLoops}" +
                                  $"\nTries: {tries}\nEnd-Tries: {endTries}\nCatches: {catches}" +
                                  $"\nEnd-Catches: {endCatches}\nFinally: {finalies}\nEnd-Finally: {endFinalies}" +
                                  $"\nSwitch: {switches}\nEnd-Switches: {endSwitches}" +
                                  $"\nClass(es): {classes}\nEnd-Clssses: {endClasses}");
                Console.WriteLine("==========================File Statistics=========================");
                Console.WriteLine("\n=======================================================\n");

                string lineComment = string.Empty;
                foreach (var csLineDetail in assignedBaseCommands)
                {
                    if (Regex.IsMatch(csLineDetail.ResolvedStatement.Trim('\r', '\n', ' '), @"^([;()\[\]]+)$"))
                    {
                        continue;
                    }
                    if (string.IsNullOrEmpty(csLineDetail.ResolvedStatement))
                    {
                        continue;
                    }
                    if (Regex.IsMatch(csLineDetail.ResolvedStatement, "^using\\s"))
                    {
                        continue;
                    }
                    if (RegexCollections.LineComment.IsMatch(csLineDetail.ResolvedStatement))
                    {
                        lineComment += csLineDetail.ResolvedStatement;
                        continue;
                    }
                    string ceiName            = RegexCollections.TypeNameRegex.Match(csLineDetail.ResolvedStatement).Groups["TypeName"].Value.Trim();
                    string variableName       = RegexCollections.VariableDeclaration.Match(csLineDetail.ResolvedStatement).Groups["VariableName"].Value;
                    int    baseCommandId      = Regex.IsMatch(csLineDetail.ResolvedStatement.Trim(), @"^{$") ? 41 : csLineDetail.BaseCommandId;
                    var    statementReference = new StatementReferenceMaster
                    {
                        BaseCommandId     = baseCommandId,
                        LineIndex         = csLineDetail.LineIndex,
                        FileId            = fileMaster._id,
                        OriginalStatement = csLineDetail.OriginalStatement,
                        ResolvedStatement = csLineDetail.ResolvedStatement,
                        ProjectId         = fileMaster.ProjectId
                    };
                    if (!string.IsNullOrEmpty(variableName))
                    {
                        statementReference.VariableNameDeclared = variableName;
                    }
                    if (!string.IsNullOrEmpty(ceiName))
                    {
                        statementReference.ClassNameDeclared = ceiName;
                    }
                    if (!string.IsNullOrEmpty(lineComment))
                    {
                        statementReference.StatementComment = lineComment;
                    }
                    if (!string.IsNullOrEmpty(csLineDetail.MethodName))
                    {
                        statementReference.MethodName = csLineDetail.MethodName;
                    }

                    await _floKaptureService.StatementReferenceMasterRepository.AddDocument(statementReference).ConfigureAwait(false);

                    lineComment = string.Empty;
                }
            }
            return(Ok());
        }
Esempio n. 8
0
        /// <summary>
        ///     数据校验
        /// </summary>
        protected override bool Validate()
        {
            var result = true;

            if (string.IsNullOrWhiteSpace(Property.Name))
            {
                result        = false;
                Message.Track = "====>属性名称不能为空";
            }
            else if (Property.Name == "NewField" || (Property.Name[0] >= '0' && Property.Name[0] <= '9'))
            {
                result        = false;
                Message.Track = "====>属性名称不正确:" + Property.Name;
            }
            else
            {
                Property.Name = Property.Name.Trim();
            }
            if (IsReference)
            {
                return(result);
            }
            string cstype = Property.CsType;

            if (cstype.Length > 4 && cstype.Substring(cstype.Length - 4, 4) == "Data")
            {
                cstype = cstype.Substring(0, cstype.Length - 4);
            }
            if (!CsharpHelper.IsCsType(cstype))
            {
                result        = false;
                Message.Track = "====>字段类型不正确" + Property.CsType;
            }

            if (IsClass)
            {
                return(result);
            }
            if (Property.IsPrimaryKey && Property.Nullable)
            {
                result        = false;
                Message.Track = "====>主键被设置为可为空";
            }
            if (Property.NoStorage)
            {
                return(result);
            }
            if (string.IsNullOrWhiteSpace(Property.ColumnName))
            {
                result        = false;
                Message.Track = "====>字段存储名称不能为空";
            }
            else if (Property.ColumnName == "NewField" ||
                     (Property.ColumnName[0] >= '0' && Property.ColumnName[0] <= '9'))
            {
                result        = false;
                Message.Track = "====>字段存储名称不正确:" + Property.ColumnName;
            }
            //if (CreateIndex && IsPrimaryKey)
            //{
            //    result = false;
            //    trace.Track = "====>主键不需要建立索引";
            //}
            //if (IsUserId && CsType != "int")
            //{
            //    result = false;
            //    trace.Track = "====>字段为用户ID映射而字段类型不是Int型";
            //}
            if (!DataBaseHelper.IsDataBaseType(Property.DbType))
            {
                result        = false;
                Message.Track = "====>字段存储类型不正确" + Property.DbType;
            }

            if (Property.IsLinkKey)
            {
                Property.DbNullable = false;
            }
            if (Property.IsCompute)
            {
                Property.DbNullable = true;
            }
            if (Property.IsPrimaryKey)
            {
                Property.DbNullable = false;
            }
            //if (Property.CreateIndex && Property.Nullable)
            //{
            //    result = false;
            //    this.Message.Track = "====>字段需要建立索引而字段被设置为可为空";
            //}
            return(result);
        }