예제 #1
0
        }//Main

        /// <summary>
        /// Load .json config
        /// </summary>
        /// <param name="configPath"></param>
        /// <returns></returns>
        private static GenConfig LoadConfig(string configPath)
        {
            string    jsonString = File.ReadAllText(configPath);
            GenConfig config     = JsonConvert.DeserializeObject <GenConfig>(jsonString);

            //TODO: exception handling

            //TODO: VALIDATE config
            //verify all paths
            //verify critical values are set
            config.words_base_path  = GetPath(config.words_base_path);
            config.test_hashes_path = GetPath(config.test_hashes_path);
            config.output_path      = GetPath(config.output_path);
            if (config.words_base_path == null)
            {
                config.words_base_path = Path.GetDirectoryName(configPath);
            }
            if (config.output_path == null)
            {
                config.output_path = config.words_base_path;
            }

            if (config.test_hashes_func != null)
            {
                config.test_hashes_func = config.test_hashes_func.ToLower();
            }

            return(config);
        }//LoadConfig
예제 #2
0
        /// <summary>
        /// 生成Class字符串
        /// </summary>
        /// <param name="genConfig">生成配置信息</param>
        /// <param name="genTable">表信息</param>
        /// <param name="classType">类型:Entity-实体,Service-服务实现类, Service.Interface-服务接口类, Repository-数据库仓储类</param>
        /// <param name="classNameSubfix">类后缀</param>
        /// <returns></returns>
        private static string GetHeader(GenConfig genConfig, GenTable genTable, string classType, string classNameSubfix = "")
        {
            StringBuilder ret = new StringBuilder();

            ret.AppendLine(@"/************************************************************************************
* Copyright (c) " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + @" 优网科技 All Rights Reserved.
* CLR版本: .Standard 2.x
* 公司名称:优网科技
* 命名空间:" + genConfig.Namespace + "." + genConfig.ModuleName + "." + classType + @"
* 文件名:  " + genConfig.Namespace + "." + genConfig.ModuleName + "." + classType + "." + genTable.CaseClassName + classNameSubfix + @".cs
* 版本号:  V1.0.0.0
* 唯一标识:" + Guid.NewGuid() + @"
* 创建人:  " + genConfig.Author + @"
* 电子邮箱:" + genConfig.Email + @"
* 创建时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + @" 
* 描述:" + genTable.Comments + @" 
* 
* 
* =====================================================================
* 修改标记 
* 修改时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + @" 
* 修改人: 谢韶光
* 版本号: V1.0.0.0
* 描述:
* 
* 
* 
* 
************************************************************************************/
");
            ret.AppendLine();
            ret.AppendLine();
            ret.AppendLine("namespace   " + genConfig.Namespace + "." + genConfig.ModuleName + "." + classType);
            return(ret.ToString());
        }
예제 #3
0
        private static string GetInterfaceUsing(GenConfig genConfig)
        {
            var sb = new StringBuilder();

            sb.AppendLine(GetEntityUsing());
            sb.AppendLine(GetTabs(1) + "using UWay.Skynet.Cloud.Request;");
            sb.AppendLine(GetTabs(1) + "using " + genConfig.Namespace + "." + genConfig.ModuleName + ".Entity;");
            sb.AppendLine(GetTabs(1) + "using System.Collections.Generic;");
            return(sb.ToString());
        }
예제 #4
0
        private static string GetRepositoryUsing(GenConfig genConfig)
        {
            var sb = new StringBuilder();

            sb.AppendLine(GetEntityUsing());
            sb.AppendLine(GetTabs(1) + "using  " + genConfig.Namespace + "." + genConfig.ModuleName + ".Entity;");
            sb.AppendLine(GetTabs(1) + "using System.Linq;");
            sb.AppendLine(GetTabs(1) + "using System.Collections.Generic;");
            return(sb.ToString());
        }
예제 #5
0
        private static string GetServiceUsing(GenConfig genConfig)
        {
            var sb = new StringBuilder();

            sb.AppendLine(GetInterfaceUsing(genConfig));
            sb.AppendLine(GetTabs(1) + "using System.Linq;");
            sb.AppendLine(GetTabs(1) + "using " + genConfig.Namespace + "." + genConfig.ModuleName + ".Service.Interface;");
            sb.AppendLine(GetTabs(1) + "using " + genConfig.Namespace + "." + genConfig.ModuleName + ".Repository;");
            sb.AppendLine(GetTabs(1) + "using UWay.Skynet.Cloud.Linq;");
            sb.AppendLine(GetTabs(1) + "using UWay.Skynet.Cloud;");
            return(sb.ToString());
        }
예제 #6
0
        }//GetWordsLists

        /// <summary>
        /// Generates various variations of strings for a given list.
        /// </summary>
        /// <param name="genConfig"></param>
        /// <param name="allWordsLists"></param>
        private static void GenerateWordVariations(GenConfig genConfig, ref List <string>[] allWordsLists)
        {
            if (genConfig.word_variations_all.Count > 0)
            {
                Console.WriteLine("Generating variations for words lists");
                for (int i = 0; i < allWordsLists.Length; i++)
                {
                    //foreach (var wordsList in allWordsLists)

                    var wordsList    = allWordsLists[i];
                    var expandedList = new HashSet <string>();

                    foreach (string word in wordsList)
                    {
                        if (!genConfig.word_variations_all.Contains("dont_add_original"))
                        {
                            expandedList.Add(word);
                        }
                        if (genConfig.word_variations_all.Contains("all_upper"))
                        {
                            expandedList.Add(word.ToUpper());
                        }
                        if (genConfig.word_variations_all.Contains("all_lower"))
                        {
                            expandedList.Add(word.ToLower());
                        }
                        if (genConfig.word_variations_all.Contains("capitalized"))
                        {
                            if (word.Length > 1)
                            {
                                expandedList.Add($"{word[0].ToString().ToUpper()}{word.Substring(1)}");
                            }
                            else
                            {
                                expandedList.Add(word.ToUpper());
                            }
                        }
                    }//foreach words

                    //tex after above since dont_add_original will clear non alphbetical strings since they have no case
                    if (genConfig.word_variations_all.Contains("blank_optional"))
                    {
                        expandedList.Add("");
                    }

                    allWordsLists[i] = expandedList.ToList <string>();
                    allWordsLists[i].Sort();
                }
            } //if word_variations_all
        }     //GenerateWordVariations
예제 #7
0
        private static StringBuilder GeneratorServiceInterface(GenConfig genConfig, GenTable table)
        {
            var sb = new StringBuilder();

            sb.Append(GetHeader(genConfig, table, "Service.Interface"));
            sb.AppendLine("{");
            sb.Append(GetInterfaceUsing(genConfig));
            sb.Append(GetClassDescription(table, "服务接口类"));
            sb.Append(GetName(table, "Service", true));
            sb.AppendLine(GetTabs(1) + "{");
            sb.Append(GetInterfaceBody(table));
            sb.AppendLine(GetTabs(1) + "}");
            sb.AppendLine("}");
            return(sb);
        }
예제 #8
0
        private static StringBuilder GeneratorRepository(GenConfig genConfig, GenTable table)
        {
            var sb = new StringBuilder();

            sb.Append(GetHeader(genConfig, table, "Repository"));
            sb.AppendLine("{");
            sb.AppendLine(GetRepositoryUsing(genConfig));
            sb.Append(GetClassDescription(table, "仓储类"));
            sb.Append(GetName(table, "Repository"));
            sb.AppendLine(GetTabs(1) + "{");
            sb.Append(GetRepositoryBody(table));
            sb.AppendLine(GetTabs(1) + "}");
            sb.AppendLine("}");
            return(sb);
        }
예제 #9
0
        public static StringBuilder GeneratorServiceInterfaceProject(GenConfig genConfig)
        {
            var           assemblyName = genConfig.Namespace.Substring(genConfig.Namespace.IndexOf(".") + 1);
            StringBuilder sb           = new StringBuilder();

            sb.AppendLine("<Project Sdk=\"Microsoft.NET.Sdk\">");
            sb.AppendLine(GetTabs(1) + "<PropertyGroup>");
            sb.AppendLine(GetTabs(2) + "<TargetFramework>netstandard2.0</TargetFramework>");
            sb.AppendLine(GetTabs(2) + "<RootNamespace>" + genConfig.Namespace + "." + genConfig.ModuleName + ".Service.Interface</RootNamespace>");
            sb.AppendLine(GetTabs(1) + "</PropertyGroup>");
            sb.AppendLine(GetTabs(1) + "<ItemGroup>");
            sb.AppendLine(GetTabs(2) + "<ProjectReference Include=\"..\\" + assemblyName + "." + genConfig.ModuleName + ".Entity\\" + assemblyName + "." + genConfig.ModuleName + ".Entity.csproj\" />");
            sb.AppendLine(GetTabs(1) + "</ItemGroup>");
            sb.AppendLine("</Project>");
            return(sb);
        }
예제 #10
0
        private static StringBuilder GeneratorEntity(GenConfig genConfig, GenTable table, IEnumerable <GenColumn> columns)
        {
            var sb = new StringBuilder();

            sb.Append(GetHeader(genConfig, table, "Entity"));
            sb.AppendLine("{");

            sb.AppendLine(GetEntityUsing());
            sb.Append(GetClassDescription(table));
            sb.Append(GetName(table));
            sb.AppendLine(GetTabs(1) + "{");
            sb.Append(GetEntityBody(genConfig.IsGeneratorMapping, table.PrimaryKey == null ? string.Empty: table.PrimaryKey.ColumnName, columns));
            sb.AppendLine(GetTabs(1) + "}");
            sb.AppendLine("}");
            return(sb);
        }
예제 #11
0
        public void Test1()
        {
            var appsettings = @"
{
    'spring': {
        'application': {
            'name': 'myName'
        },
    },
    'skynet': {
        'cloud': {
            'filepath': 'c:/doc',
        }
    }
}";

            var    path      = TestHelpers.CreateTempFile(appsettings);
            string directory = Path.GetDirectoryName(path);
            string fileName  = Path.GetFileName(path);
            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

            configurationBuilder.SetBasePath(directory);

            configurationBuilder.AddJsonFile(fileName);
            var config = configurationBuilder.Build();

            DbConfiguration.Configure(dbContextOption);
            IFileHandler    fileHandler    = new FileHandler(config, GetLoggerFactory().CreateLogger <FileHandler>());
            ICodeGenService codeGenService = new CodeGenService(fileHandler, GetLoggerFactory().CreateLogger <CodeGenService>());
            GenConfig       genConfig      = new GenConfig()
            {
                Author      = "magic.s.g.xie",
                Comments    = "Á÷³ÌÒµÎñ",
                Email       = "*****@*****.**",
                Namespace   = "UWay.Skynet.Cloud",
                ModuleName  = "Uflow",
                TablePrefix = "UF_"
            };

            codeGenService.GeneratorCode(genConfig);
        }
예제 #12
0
        private static void SimpleTests(List <string>[] allWordsLists)
        {
            Console.WriteLine("!!!!SimpleTests");

            //tex filling out all variables to get concanical serialization.
            GenConfig config = new GenConfig();

            config.batch_size      = 1;
            config.words_base_path = @"D:\GitHub\BruteGen\Examples\3x3 - test hashes";
            config.words_paths.Add("wordA");
            config.words_paths.Add("wordB");
            config.words_paths.Add("wordC");
            config.output_path = @"D:\GitHub\BruteGen\Examples\Examples Output";
            config.word_variations_all.Add("dont_add_original");
            config.word_variations_all.Add("all_upper");
            config.word_variations_all.Add("all_lower");
            config.word_variations_all.Add("capitalized");
            config.word_variations_all.Add("blank_optional");
            config.test_hashes_path = @"D:\GitHub\BruteGen\Examples\3x3 - test hashes\StrCode32Hashes";
            config.test_hashes_func = "StrCode32";

            JsonSerializerSettings serializeSettings = new JsonSerializerSettings();

            serializeSettings.Formatting = Formatting.Indented;
            string jsonStringOut = JsonConvert.SerializeObject(config, serializeSettings);
            string jsonOutPath   = @"D:\GitHub\BruteGen\full-config.json";

            File.WriteAllText(jsonOutPath, jsonStringOut);


            RecurseStep startStateS = new RecurseStep();

            startStateS.currentDepth         = 0;
            startStateS.currentWordListIndex = 0;
            startStateS.currentString        = "";
            GenerateStringSimple2_r(allWordsLists, startStateS);

            GenerateStringSimple_Stack(allWordsLists);
        } //SimpleTests
예제 #13
0
 public Application(Config config)
 {
     this.config = config;
     genConfig   = GenConfig.Load(Frame.MapPath(config.APP + "compile.xml"));
 }
예제 #14
0
        /// <summary>
        /// Main, entry point
        /// </summary>
        /// <param name="args">args[0] == .json config path</param>
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("Usage: BruteGen.exe <config .json path>");

                GenConfig defaultConfig = new GenConfig();
                JsonSerializerSettings serializeSettings = new JsonSerializerSettings();
                serializeSettings.Formatting = Formatting.Indented;
                string jsonStringOut = JsonConvert.SerializeObject(defaultConfig, serializeSettings);
                string jsonOutPath   = Directory.GetCurrentDirectory() + @"\default-config.json";
                jsonOutPath = Regex.Replace(jsonOutPath, @"\\", "/");
                File.WriteAllText(jsonOutPath, jsonStringOut);

                Console.WriteLine($"Writing default config to {jsonOutPath}");
                return;
            }

            string configPath = GetPath(args[0]);

            if (configPath == null)
            {
                Console.WriteLine("ERROR: Could not find .json file for path " + args[0]);
                return;
            }
            if (!configPath.Contains(".json"))
            {
                Console.WriteLine("ERROR: path does not contain '.json' :" + configPath);
                return;
            }

            GenConfig config = LoadConfig(configPath);

            if (!Directory.Exists(config.output_path))
            {
                Console.WriteLine("ERROR: could not find config.outputPath: " + config.output_path);
                return;
            }

            if (!Directory.Exists(config.words_base_path))
            {
                Console.WriteLine("ERROR: could not find config.words_path: " + config.words_base_path);
                return;
            }

            Directory.SetCurrentDirectory(config.words_base_path);


            string outputName = Path.GetFileNameWithoutExtension(configPath);//tex filename for resume state and matches file.

            string resumeStatePath = Path.Combine(config.output_path, $"{outputName}-resume_state.json");

            // hash test info
            var hashInfo = new HashInfo();

            if (config.test_hashes_path != null)
            {
                Console.WriteLine("Reading input hashes:");
                int maxLength;
                hashInfo.inputHashes = GetStrings(config.test_hashes_path, out maxLength);
                if (hashInfo.inputHashes == null)
                {
                    Console.WriteLine("ERROR: no hashes found in " + config.test_hashes_path);
                    return;
                }

                if (config.test_hashes_func == null)
                {
                    Console.WriteLine("ERROR: Could not find test_'hashes_func' in config");
                    return;
                }

                hashInfo.HashFunc = HashFuncs.GetHashFuncByName(config.test_hashes_func);
                if (hashInfo.HashFunc == null)
                {
                    Console.WriteLine("ERROR: Could not find hash function " + config.test_hashes_func);
                    return;
                }

                if (hashInfo.inputHashes != null)
                {
                    Console.WriteLine("Will test strings with " + config.test_hashes_func);
                }
            }//if test_hashes_path

            Console.WriteLine("Reading words lists");
            int[] maxWordLengths;
            var   allWordsLists   = GetWordsLists(config.words_paths, out maxWordLengths);
            int   maxStringLength = maxWordLengths.Sum();

            GenerateWordVariations(config, ref allWordsLists);

            Console.WriteLine("Word counts:");
            string listNames = " ";

            for (int i = 0; i < allWordsLists.Length; i++)
            {
                listNames += Path.GetFileName(config.words_paths[i]) + "\t";
            }
            Console.WriteLine(listNames);

            string wordCounts = " ";

            for (int i = 0; i < allWordsLists.Length; i++)
            {
                wordCounts += allWordsLists[i].Count + "\t";
            }
            Console.WriteLine(wordCounts);

            Console.WriteLine("Batch size:" + config.batch_size);

            string stringsOutPath = Path.Combine(config.output_path, outputName + ".txt");

            //LEGACY CULL
            //Stack<RecurseStep> resumeStackState = ReadResumeStackState(resumeStatePath);
            //GenerateStringsStack(resumeStackState, allWordsLists, hashInfo, config.batch_size, config.test_on_batch, resumeStatePath, stringsOutPath);

            int[] lockstepIds   = new int[allWordsLists.Length];
            int[] lockstepHeads = new int[allWordsLists.Length];//tex maximum number of ids is actually wordsLists.Length / 2 + 1 (id 0 for 'not a lockstep list').
            if (config.lockstep_same_word_lists)
            {
                BuildLockstepInfo(config.words_paths, ref lockstepIds, ref lockstepHeads);
            }//config.lockstep_same_word_lists


            GenerateStrings(allWordsLists, lockstepIds, lockstepHeads, hashInfo, maxStringLength, config.batch_size, config.test_on_batch, resumeStatePath, stringsOutPath);//tex the main generate/test loop

            if (File.Exists(resumeStatePath))
            {
                File.Delete(resumeStatePath);
            }

            //SimpleTests(allWordsLists);

            Console.WriteLine("done");
        }//Main
예제 #15
0
        public byte[] GeneratorCode(GenConfig genConfig)
        {
            var assmeblyName = genConfig.Namespace.Substring(genConfig.Namespace.IndexOf(".") + 1);

            var path = assmeblyName + "." + genConfig.ModuleName;

            using (var context = UnitOfWork.Get(Unity.ContainerName))
            {
                var r = new CodeGenRepository(context);
                //查询表信息
                DataTable table = r.QueryTable(genConfig.TablePrefix);

                var entityProject = GenUtils.GeneratorEntityProject(genConfig);


                _handler.AddFile(path + ".Entity.csproj", path + "/" + path + ".Entity", entityProject.ToString());
                var repositoryProject = GenUtils.GeneratorRepositoryProject(genConfig);
                _handler.AddFile(path + ".Repository.csproj", path + "/" + path + ".Repository", repositoryProject.ToString());

                var serviceProject = GenUtils.GeneratorServiceProject(genConfig);
                _handler.AddFile(path + ".Service.csproj", path + "/" + path + ".Service", serviceProject.ToString());

                var interfaceProject = GenUtils.GeneratorServiceInterfaceProject(genConfig);
                _handler.AddFile(path + ".Service.Interface.csproj", path + "/" + path + ".Service.Interface", interfaceProject.ToString());
                var sb = new StringBuilder();
                sb.Append(GenUtils.GeneratorXmlHeader(assmeblyName + ".Entity", genConfig.Namespace + "." + genConfig.ModuleName + ".Entity"));
                foreach (DataRow dr in table.Rows)
                {
                    DataTable columns = r.QueryColumns(dr["tableName"].ToString());
                    var       dic     = GenUtils.GeneratorCode(genConfig, dr, columns, provider: context.DbConfiguration.DbProviderName);
                    foreach (var item in dic)
                    {
                        if (item.Key.StartsWith("xml"))
                        {
                            sb.Append(item.Value);
                        }
                        else
                        {
                            var keys = item.Key.Split('_');
                            _handler.AddFile(keys[1] + ".cs", path + "/" + path + "." + keys[0], item.Value.ToString());
                        }
                    }
                }
                sb.Append(GenUtils.GeneratorXmlFooter());
                if (genConfig.IsGeneratorMapping)
                {
                    _handler.AddFile(string.Format("uway.{0}.mapping.xml", genConfig.ModuleName), path + "/" + path + ".Entity", sb.ToString());
                }
                _handler.AddFile("Unity.cs", path + "/" + path + ".Service", GenUtils.GeneratorUnity(genConfig.Namespace, genConfig.ModuleName));
            }

            _handler.Zip(path + ".zip", path);

            using (var stream = _handler.OpenFile(path + ".zip", FileMode.Open))
            {
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                // 设置当前流的位置为流的开始
                stream.Seek(0, SeekOrigin.Begin);
                return(bytes);
            }
        }
예제 #16
0
        // Generate data
        public void GenerateData(string[] args)
        {
            Queue callBackQ = new Queue();

            // Parse parameters
            // Number of cdr records, probability of fraud, and number of hours
            GenConfig config = new GenConfig(Int32.Parse(args[0]), float.Parse(args[1]), Int32.Parse(args[2]));

            // print statistics
            Console.Error.WriteLine(config);

            // Start the generation

            // Generate the call nos
            CallStore mobileNos = new CallStore(100000);

            int numCallbackPerFile = (int)(config.nCallBackPercent * config.nCDRPerFile);

            // Data generation always start with the current time


            double timeAdvancementPerSet = (0.0 + config.nDurationHours) / config.nSets;

            Console.Error.WriteLine("Time Increment Per Set: " + timeAdvancementPerSet);

            // Start generating per set
            DateTime simulationTime = DateTime.Now;
            Random   r = new Random();

            bool invalidRec  = false;
            bool genCallback = false;


            // TOOD: Update this to number of hours
            DateTimeOffset ptTime  = DateTimeOffset.Now;
            DateTimeOffset endTime = ptTime.AddHours(config.nDurationHours);

            while (endTime.Subtract(ptTime) >= TimeSpan.Zero && FlowController.CanRun)
            {
                DateTimeOffset currentTime = ptTime;
                uiwriter.Write(String.Format("{0:yyyyMMdd HHmmss}", simulationTime));



                for (int cdr = 0; cdr < config.nCDRPerFile && FlowController.CanRun; cdr++)
                {
                    currentTime = ptTime;

                    // Determine whether to generate an invalid CDR record
                    double pvalue = r.NextDouble();
                    if (pvalue < 0.1)
                    {
                        invalidRec = true;
                    }
                    else
                    {
                        invalidRec = false;
                    }

                    // Determine whether there will be a callback
                    pvalue = r.NextDouble();
                    if (pvalue >= config.nCallBackPercent)
                    {
                        genCallback = true;
                    }
                    else
                    {
                        genCallback = false;
                    }


                    // Determine called and calling num
                    int calledIdx  = r.Next(0, mobileNos.CallNos.Length);
                    int callingIdx = r.Next(0, mobileNos.CallNos.Length);


                    CDRrecord rec = new CDRrecord();
                    rec.setData("FileNum", "" + cdr);

                    int switchIdx    = r.Next(0, mobileNos.switchCountries.Length);
                    int switchAltIdx = r.Next(0, mobileNos.switchCountries.Length);

                    // Find an alternate switch
                    while (switchAltIdx == switchIdx)
                    {
                        switchAltIdx = r.Next(0, mobileNos.switchCountries.Length);
                    }

                    rec.setData("SwitchNum", mobileNos.switchCountries[switchIdx]);

                    if (!FlowController.CanRun)
                    {
                        return;
                    }
                    if (invalidRec)
                    {
                        rec.setData("Date", "F");
                        rec.setData("Time", "F");
                        rec.setData("DateTime", "F F");
                    }
                    else
                    {
                        String callDate = String.Format("{0:yyyyMMdd}", currentTime);
                        String callTime = String.Format("{0:HHmmss}", currentTime);

                        rec.setData("Date", callDate);
                        rec.setData("Time", callTime);
                        rec.setData("DateTime", callDate + " " + callTime);

                        String calledNum  = mobileNos.CallNos[calledIdx];
                        String callingNum = mobileNos.CallNos[callingIdx];

                        rec.setData("CalledNum", calledNum);
                        rec.setData("CallingNum", callingNum);


                        // Sim card fraud record
                        if (genCallback)
                        {
                            // For call back the A->B end has duration 0
                            rec.setData("CallPeriod", "0");

                            // need to generate another set of no
                            calledIdx  = callingIdx;
                            callingIdx = r.Next(0, mobileNos.CallNos.Length);

                            CDRrecord callbackRec = new CDRrecord();
                            callbackRec.setData("FileNum", "" + cdr);
                            callbackRec.setData("SwitchNum", mobileNos.switchCountries[switchAltIdx]);

                            //callbackRec.setData("SwitchNum", "" + (f + 1));

                            // Pertub second
                            int pertubs = r.Next(0, 30);

                            callDate = String.Format("{0:yyyyMMdd}", currentTime);
                            callTime = String.Format("{0:HHmmss}", currentTime.AddMinutes(pertubs));

                            callbackRec.setData("Date", callDate);
                            callbackRec.setData("Time", callTime);
                            callbackRec.setData("DateTime", callDate + " " + callTime);

                            // Set it as the same calling IMSI
                            callbackRec.setData("CallingIMSI", rec.CallingIMSI);

                            calledNum  = mobileNos.CallNos[calledIdx];
                            callingNum = mobileNos.CallNos[callingIdx];

                            callbackRec.setData("CalledNum", calledNum);
                            callbackRec.setData("CallingNum", callingNum);


                            // Determine duration of call
                            int callPeriod = r.Next(1, 1000);
                            callbackRec.setData("CallPeriod", "" + callPeriod);

                            // Enqueue the call back rec
                            callBackQ.Enqueue(callbackRec);
                            cdr++;
                        }
                        else
                        {
                            int callPeriod = r.Next(1, 800);
                            rec.setData("CallPeriod", "" + callPeriod);
                        }
                    }

                    // send cdr rec to output
                    //if (genCallback)  Console.Write("callback A->B ");
                    uiwriter.Write(outputCDRRecs(rec));

                    if (callBackQ.Count > 0 && (cdr % 7 == 0))
                    {
                        CDRrecord drec;
                        drec = (CDRrecord)callBackQ.Dequeue();
                        uiwriter.Write(outputCDRRecs(drec));

                        //Console.Write("callback C->A!");
                        //outputCDRRecs(s, f, drec);
                    }

                    // Sleep for 1000ms
                    System.Threading.Thread.Sleep(100);

                    // get the current time after generation
                    ptTime = DateTimeOffset.Now;
                }                 // cdr


                // Clear the remaining entries in the call back queue
                if (callBackQ.Count > 0)
                {
                    // need to empty queue
                    while (callBackQ.Count > 0)
                    {
                        CDRrecord dr = (CDRrecord)callBackQ.Dequeue();
                        uiwriter.Write(outputCDRRecs(dr));
                        //outputCDRRecs(s, f, dr);
                    }
                }

                // close the file
                if (writer != null)
                {
                    writer.Flush();
                    writer.Close();
                    writer = null;
                }


                // Advance Time
                if (timeAdvancementPerSet < 1.0)
                {
                    simulationTime = simulationTime.AddMinutes(timeAdvancementPerSet * 60);
                }
                else
                {
                    simulationTime = simulationTime.AddHours(timeAdvancementPerSet);
                }



                // Sleep for 1000ms
                System.Threading.Thread.Sleep(1000);
            }             // while - within duration
        }
예제 #17
0
        public static IDictionary <string, StringBuilder> GeneratorCode(GenConfig genConfig, DataRow table, DataTable genColumns, string tablePrefix = "mod_", string provider = DbProviderNames.Oracle_Managed_ODP)
        {
            IDictionary <string, StringBuilder> classDetails = new Dictionary <string, StringBuilder>();
            var comments = table["tableComment"].ToString();

            GenTable genTable = new GenTable();

            if (comments.IsNullOrEmpty())
            {
                genTable.Comments = genConfig.Comments;
            }
            else
            {
                genTable.Comments = comments;
            }


            if (genConfig.TablePrefix.IsNullOrEmpty())
            {
                genConfig.TablePrefix = tablePrefix;
            }
            else
            {
                if (!genConfig.TablePrefix.EndsWith("_"))
                {
                    genConfig.TablePrefix = genConfig.TablePrefix + "_";
                }
            }

            genTable.TableName = table["tableName"].ToString();
            string className = genTable.TableName.Replace(genConfig.TablePrefix, "").ToCamelCase();

            genTable.CaseClassName  = className;
            genTable.LowerClassName = className.Replace(className.Substring(0, 1), className.Substring(0, 1).ToLower());

            IList <GenColumn> columns = new List <GenColumn>();

            foreach (DataRow item in genColumns.Rows)
            {
                var column     = new GenColumn();
                var columnName = item["columnName"].ToString();
                column.CaseAttrName  = columnName.ToCamelCase();
                column.LowerAttrName = column.CaseAttrName.Substring(0, 1).ToLower() + column.CaseAttrName.Substring(1);

                //是否主键
                if ("PRI".IsCaseInsensitiveEqual(item["columnKey"].ToString()) && genTable.PrimaryKey == null)
                {
                    genTable.PrimaryKey = column;
                }
                column.ColumnName = columnName;
                column.Comments   = item["columnComment"].ToString();
                column.DataType   = item["dataType"].ToString();
                column.AttrType   = ConvertType(column.DataType, item["nullable"].ToString());
                column.DataType   = ConvertDbType(column.DataType, provider);
                column.Extra      = item["extra"].ToString();
                columns.Add(column);
            }
            classDetails.Add("Entity_" + genTable.CaseClassName, GeneratorEntity(genConfig, genTable, columns));
            classDetails.Add("Service.Interface_I" + genTable.CaseClassName + "Service", GeneratorServiceInterface(genConfig, genTable));
            classDetails.Add("Service_" + genTable.CaseClassName + "Service", GeneratorService(genConfig, genTable));
            classDetails.Add("Repository_" + genTable.CaseClassName + "Repository", GeneratorRepository(genConfig, genTable));
            if (genConfig.IsGeneratorMapping)
            {
                classDetails.Add("xml_mapping", GeneratorMapping(genTable, columns));
            }
            return(classDetails);
        }