Beispiel #1
0
        /// <summary>
        /// 加载Excel文件
        /// </summary>
        /// <param name="options">导入设置</param>
        public void loadExcel(Program.Options options)
        {
            mOptions = options;
            string excelPath = options.ExcelPath;
            string excelName = Path.GetFileNameWithoutExtension(excelPath);
            int    header    = options.HeaderRows;

            // 加载Excel文件
            using (FileStream excelFile = File.Open(excelPath, FileMode.Open, FileAccess.Read))
            {
                // Reading from a OpenXml Excel file (2007 format; *.xlsx)
                IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(excelFile);

                // The result of each spreadsheet will be created in the result.Tables
                excelReader.IsFirstRowAsColumnNames = true;
                DataSet book = excelReader.AsDataSet();

                // 数据检测
                if (book.Tables.Count < 1)
                {
                    throw new Exception("Excel file is empty: " + excelPath);
                }

                // 取得数据
                DataTable sheet = book.Tables[0];
                if (sheet.Rows.Count <= 0)
                {
                    throw new Exception("Excel Sheet is empty: " + excelPath);
                }

                //-- 确定编码
                Encoding cd = new UTF8Encoding(false);
                if (options.Encoding != "utf8-nobom")
                {
                    foreach (EncodingInfo ei in Encoding.GetEncodings())
                    {
                        Encoding e = ei.GetEncoding();
                        if (e.HeaderName == options.Encoding)
                        {
                            cd = e;
                            break;
                        }
                    }
                }
                mEncoding = cd;

                //-- 导出JSON
                mJson = new JsonExporter(sheet, header, options.Lowcase, options.ExportArray, options.EsacapeNonAscii);

                //-- 导出SQL
                mSQL = new SQLExporter(excelName, sheet, header);

                //-- 生成C#定义代码
                mCSharp = new CSDefineGenerator(excelName, sheet);


                //-- 生成C#定义代码
                mTS = new TSDefineGenerator(excelName, sheet);
            }
        }
Beispiel #2
0
        /// <summary>
        /// 加载Excel文件
        /// </summary>
        /// <param name="options">导入设置</param>
        public void loadExcel(Program.Options options)
        {
            mOptions = options;

            //-- Excel File
            string excelPath = options.ExcelPath;
            string excelName = Path.GetFileNameWithoutExtension(excelPath);

            //-- Header
            int header = options.HeaderRows;

            //-- Encoding
            Encoding cd = new UTF8Encoding(false);

            if (options.Encoding != "utf8-nobom")
            {
                foreach (EncodingInfo ei in Encoding.GetEncodings())
                {
                    Encoding e = ei.GetEncoding();
                    if (e.HeaderName == options.Encoding)
                    {
                        cd = e;
                        break;
                    }
                }
            }
            mEncoding = cd;

            //-- Load Excel
            ExcelLoader excel = new ExcelLoader(excelPath, header);

            //-- 导出JSON
            mJson = new JsonExporter(excel, options.Lowcase, options.ExportArray, options.DateFormat);
        }
Beispiel #3
0
        public void CodePlex13272()
        {
            string file = @"C:\tmp\test.sdf";

            if (System.IO.File.Exists(file))
            {
                System.IO.File.Delete(file);
            }
            SqlCeEngineHelper testEngine = new SqlCeEngineHelper(string.Format("Data Source={0};", file));

            testEngine.Execute(SqlCeEngineHelper.EngineAction.Create);
            Assert.IsTrue(System.IO.File.Exists(file), "Create OK");

            SqlCeCommandHelper cmdHelper = new SqlCeCommandHelper(string.Format("Data Source={0};", file));

            Program.Options options = new Program.Options();
            options.QueryFile = @"C:\tmp\CodePlex\sqlcecmd\Test\goscript.sql";

            cmdHelper.RunCommands(options);

            SqlCeCommand cmd = new SqlCeCommand("SELECT COUNT(*) FROM [example]", new SqlCeConnection(string.Format("Data Source={0};", file)));

            cmd.Connection.Open();
            int count = (int)cmd.ExecuteScalar();

            Assert.AreEqual(count, 1);
        }
Beispiel #4
0
        public void ExerciseFileInput()
        {
            string file = @"C:\data\test.sdf";

            if (System.IO.File.Exists(file))
            {
                System.IO.File.Delete(file);
            }
            SqlCeEngineHelper testEngine = new SqlCeEngineHelper(string.Format("Data Source={0};", file));

            testEngine.Execute(SqlCeEngineHelper.EngineAction.Create);
            Assert.IsTrue(System.IO.File.Exists(file), "Create OK");

            SqlCeCommandHelper cmdHelper = new SqlCeCommandHelper(string.Format("Data Source={0};", file));

            Program.Options options = new Program.Options();
            options.QueryFile = @"C:\Data\SQLCE\Test\ExportSqlCETest\northwind.sql";

            cmdHelper.RunCommands(options);

            SqlCeCommand cmd = new SqlCeCommand("SELECT COUNT(*) FROM [Order Details]", new SqlCeConnection(string.Format("Data Source={0};", file)));

            cmd.Connection.Open();
            int count = (int)cmd.ExecuteScalar();

            Assert.AreEqual(count, 2820);
        }
Beispiel #5
0
        internal static bool Parse(string[] args)
        {
            var options = new Program.Options();
            var parser  = new Parser(with =>
            {
                with.EnableDashDash         = true;
                with.CaseSensitive          = false;
                with.AutoVersion            = false;
                with.IgnoreUnknownArguments = true;
                with.AutoHelp   = false;
                with.HelpWriter = null;
            });
            var parserResults = parser
                                .ParseArguments <Program.Options>(args)
                                .WithParsed(o => options = o);

            Program.OptionFlags = options;

            // start handling flags that result in program exit
            if (options.Help)
            {
                Help(parserResults);
                return(false);
            }
            if (options.Version)
            {
                Version();
                return(false);
            }

            if (options.Information)
            {
                Console.WriteLine(JsonConvert.SerializeObject(new ResultMachine(), Formatting.Indented));
                return(false);
            }
            // end handling flags that result in program exit

#if DEBUG
            Program.IsDebug = true;
#endif

            if (options.Debug || Program.IsDebug)
            {
                Program.IsDebug = true;
                Debug();
            }
            else
            {
                Console.WriteLine($"GHOSTS ({ApplicationDetails.Name}:{ApplicationDetails.Version}) running in production mode. Installed path: {ApplicationDetails.InstalledPath}");
            }

            if (options.Randomize)
            {
                throw new NotImplementedException("Randomize not released yet...");
                //Console.WriteLine("randomize!");
                //return;
            }

            return(true);
        }
Beispiel #6
0
        /// <summary>
        /// 使用BackgroundWorker加载Excel文件,使用UI中的Options设置
        /// </summary>
        /// <param name="path">Excel文件路径</param>
        private void loadExcelAsync(string path)
        {
            mCurrentXlsx = path;
            FileName     = System.IO.Path.GetFileNameWithoutExtension(path);

            //-- update ui
            this.btnReimport.Enabled = true;
            this.labelExcelFile.Text = path;
            enableExportButtons(false);

            this.statusLabel.IsLink = false;
            this.statusLabel.Text   = "加载 Excel ...";

            //-- load options from ui
            Program.Options options = new Program.Options();
            options.ExcelPath   = path;
            options.ExportArray = this.comboBoxType.SelectedIndex == 0;
            options.Encoding    = this.comboBoxEncoding.SelectedText;
            options.Lowcase     = this.comboBoxLowcase.SelectedIndex == 1;
            options.HeaderRows  = int.Parse(this.comboBoxHeader.Text);
            options.DateFormat  = this.comboBoxDateFormat.Text;

            //-- start import
            this.backgroundWorker.RunWorkerAsync(options);
        }
Beispiel #7
0
        public Program.Result Process(string expression, Program.Options options)
        {
            var result = new Program.Result();

            try
            {
                Check(expression, options);
                Apply(options);
                double answer = Calculate(expression);
                result.Output     = numberFormatter.Format(answer);
                result.ReturnCode = Program.ErrorCode.OK;
            }
            catch (BadCommandLineArguments e)
            {
                result.Output     = $"Bad arguments: {e.Message}";
                result.ReturnCode = Program.ErrorCode.BadCommandLineArguments;
            }
            catch (InvalidMathExpression e)
            {
                result.Output     = $"Error: {e.Message}";
                result.ReturnCode = Program.ErrorCode.InvalidExpression;
            }
            catch (Exception e)
            {
                result.Output     = $"Unexpected error:\n{e}";
                result.ReturnCode = Program.ErrorCode.UnexpectedError;
            }

            return(result);
        }
Beispiel #8
0
 private void Check(string expression, Program.Options options)
 {
     if (expression == null && options.ReadStdin == false)
     {
         throw new BadCommandLineArguments(
                   "Need to provide an expression or use \"-i\" option");
     }
 }
Beispiel #9
0
 private void Apply(Program.Options options)
 {
     numberFormatter = new NumberFormatter(
         precision:   options.Precision,
         scientific:  options.ScientificOutput,
         _decimal:    options.DecimalOutput,
         percent:     options.PercentOutput
         );
 }
Beispiel #10
0
 public ManagedNode(Program.Options o)
 {
     this.o        = o;
     this.services = new ServiceCollection();
     this.logger   = LoggerFactory.Create(logging =>
     {
         logging.AddConsole();
         logging.SetMinimumLevel(LogLevel.None);
     });
 }
Beispiel #11
0
        public void ExerciseCommandWithLoadImage()
        {
            SqlCeCommandHelper cmdHelper = new SqlCeCommandHelper(@"Data Source=C:\Data\SQLCE\Test\Northwind.sdf;");

            Program.Options options = new Program.Options();
            options.OutputFile = @"C:\out.txt";
            options.Headers    = 4;
            options.MakeXML    = true;
            options.QueryText  = "INSERT INTO [Categories] ([Category ID],[Category Name],[Description],[Picture]) VALUES (1,N'Beverages',N'Soft drinks, coffees, teas, beer, and ale',SqlCeCmd_LoadImage(1fc193b9270e4bda856b9c9a2aecf943.blob));";
            cmdHelper.RunCommand(options);
        }
Beispiel #12
0
        public void ExerciseCommandXml()
        {
            SqlCeCommandHelper cmdHelper = new SqlCeCommandHelper(@"Data Source=C:\Users\Erik\SkyDrive\Dokumenter\Code\SQLCE\Test\nw40.sdf;");

            Program.Options options = new Program.Options();
            options.OutputFile   = @"C:\data\out.txt";
            options.Headers      = 0;
            options.HideOutput   = true;
            options.RemoveSpaces = true;
            options.MakeXML      = true;
            options.QueryText    = @"SELECT * FROM [Orders] o
                INNER JOIN [Order Details] od ON od.[Order Id] = o.[Order Id]";
            cmdHelper.RunCommand(options);
        }
        public void Init()
        {
            string path   = Directory.GetCurrentDirectory();
            var    option = new Program.Options()
            {
                File = path + "/TestClasses/Contract_InvokeCsNef.cs"
            };

            Program.Compile(option);

            testengine = new TestEngine();
            testengine.AddEntryScript(path + "/TestClasses/Contract_InvokeCsNef.nef");

            //Compile changes the path, reseting so that other UT won't break
            Directory.SetCurrentDirectory(path);
        }
        public AudioGenerator(Program.Options opts)
        {
            this.opts = opts;

            if (opts.Gender.Trim().ToLower() == "male")
            {
                this.SpeakerGender = VoiceGender.Male;
            }
            else if (opts.Gender.Trim().ToLower() == "neutral")
            {
                this.SpeakerGender = VoiceGender.Neutral;
            }
            else
            {
                this.SpeakerGender = VoiceGender.Female;
            }
        }
Beispiel #15
0
        /// <summary>
        /// 使用BackgroundWorker加载Excel文件,使用UI中的Options设置
        /// </summary>
        /// <param name="path">Excel文件路径</param>
        private void loadExcelAsync(string path)
        {
            //-- update ui
            this.labelExcelFile.Text = path;
            enableExportButtons(false);

            //-- load options from ui
            Program.Options options = new Program.Options();
            options.ExcelPath   = path;
            options.ExportArray = this.comboBoxType.SelectedIndex == 0;
            options.Encoding    = this.comboBoxEncoding.SelectedText;
            options.Lowcase     = this.comboBoxLowcase.SelectedIndex == 0;
            options.HeaderRows  = int.Parse(this.comboBoxHeader.Text);

            //-- start import
            this.backgroundWorker.RunWorkerAsync(options);
        }
Beispiel #16
0
        public void ExerciseCommand()
        {
            SqlCeCommandHelper cmdHelper = new SqlCeCommandHelper(@"Data Source=C:\Data\SQLCE\ExportSqlCETest\Northwind.sdf;");

            Program.Options options = new Program.Options();
            options.OutputFile = @"C:\out.txt";
            options.Headers    = 4;
            options.MakeXML    = true;
            options.QueryText  = "Insert Into [Tree] ([Id],[RowId],[TagId],[ParentTreeId],[Latitude],[Longitude],[Active],[Weight]) Values (1538,22,N'13-1225',null,null,null,1,null);";
            cmdHelper.RunCommand(options);
            //options.QueryText = "SELECT * FROM [Orders]";
            //cmdHelper.RunCommand(options);
            //options.QueryText = "SELECT * FROM [Order Details]";
            //cmdHelper.RunCommand(options);
            //options.QueryText = "SELECT * FROM [Employees]";
            //cmdHelper.RunCommand(options);
        }
        public void TestAttribute()
        {
            string path   = Directory.GetCurrentDirectory();
            var    option = new Program.Options()
            {
                File = path + "/TestClasses/Contract_SupportedStandards.cs"
            };

            Program.Compile(option);

            //Compile changes the path, reseting so that other UT won't break
            Directory.SetCurrentDirectory(path);

            var jobj = JObject.Parse(File.ReadAllText(path + "/TestClasses/Contract_SupportedStandards.manifest.json"));

            Assert.AreEqual(jobj["supportedstandards"].ToString(), @"[""NEP10"",""NEP5""]");
        }
Beispiel #18
0
        public void ExerciseCommand2()
        {
            SqlCeCommandHelper cmdHelper = new SqlCeCommandHelper(@"Data Source=C:\data\sqlce\test\northwind.sdf;");

            Program.Options options = new Program.Options();
            options.OutputFile   = @"C:\data\sqlce\out.txt";
            options.Headers      = 0;
            options.HideOutput   = true;
            options.RemoveSpaces = true;
            //options.QueryText = "SELECT * FROM Shippers;";
            //cmdHelper.RunCommand(options);
            options.QueryText = "SELECT * FROM [Orders]";
            cmdHelper.RunCommand(options);
            //options.QueryText = "SELECT * FROM [Order Details]";
            //cmdHelper.RunCommand(options);
            //options.QueryText = "SELECT * FROM [Employees]";
            //cmdHelper.RunCommand(options);
        }
Beispiel #19
0
        public void ExerciseParser()
        {
            string file = @"C:\test.sdf";

            if (System.IO.File.Exists(file))
            {
                System.IO.File.Delete(file);
            }
            SqlCeEngineHelper testEngine = new SqlCeEngineHelper(string.Format("Data Source={0};", file));

            testEngine.Execute(SqlCeEngineHelper.EngineAction.Create);
            Assert.IsTrue(System.IO.File.Exists(file), "Create OK");

            SqlCeCommandHelper cmdHelper = new SqlCeCommandHelper(string.Format("Data Source={0};", file));

            Program.Options options = new Program.Options();

            options.QueryFile = @"C:\Data\SQLCE\SqlCeCmdTest\northwind.sql";
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            cmdHelper.RunCommands(options);
            System.Diagnostics.Debug.Write("Time to run: " + sw.ElapsedMilliseconds.ToString());
            sw.Stop();
            cmdHelper.Dispose();

            //if (System.IO.File.Exists(file))
            //{
            //    System.IO.File.Delete(file);
            //}
            //SqlCeEngineHelper testEngine2 = new SqlCeEngineHelper(string.Format("Data Source={0};", file));
            //testEngine.Execute(SqlCeEngineHelper.EngineAction.Create);
            //Assert.IsTrue(System.IO.File.Exists(file), "Create OK");

            //SqlCeCommandHelper cmdHelper2 = new SqlCeCommandHelper(string.Format("Data Source={0};", file));
            //Program.Options options2 = new Program.Options();

            //options.UseBatch = false;
            //options.QueryFile = @"C:\Data\SQLCE\SqlCeCmdTest\nworders.sql";
            //sw.Start();
            //cmdHelper2.RunCommands(options, true);
            //System.Diagnostics.Debug.Write("QA: " + sw.ElapsedMilliseconds.ToString());
            //sw.Stop();
            //cmdHelper2.Dispose();
        }
Beispiel #20
0
 // callback is intended to be Program.RealMain,
 // but it can be swapped for testing
 public CommandLineParser(Callback callback)
 {
     rootCommand         = DescribeRootCommand();
     rootCommand.Handler = CommandHandler.Create(
         (string argument, bool readStdin, int?precision,
          bool scientificOutput, bool decimalOutput, bool percentOutput) =>
     {
         var parsedOptions = new Program.Options
         {
             ReadStdin        = readStdin,
             Precision        = precision,
             ScientificOutput = scientificOutput,
             DecimalOutput    = decimalOutput,
             PercentOutput    = percentOutput
         };
         return(callback(argument, parsedOptions));
     }
         );
 }
Beispiel #21
0
        /// <summary>
        /// 使用BackgroundWorker加载Excel文件,使用UI中的Options设置
        /// </summary>
        /// <param name="path">Excel文件路径</param>
        private void loadExcelAsync(string path)
        {
            mCurrentXlsx = path;
            FileName     = System.IO.Path.GetFileNameWithoutExtension(path);

            //-- update ui
            this.toolReimport.Enabled = true;
            this.labelExcelFile.Text  = path;
            enableExportButtons(false);

            this.statusLabel.IsLink = false;
            this.statusLabel.Text   = "Loading Excel ...";

            //-- load options from ui
            Program.Options options = new Program.Options();
            options.excelPath = path;

            //-- start import
            this.backgroundWorker.RunWorkerAsync(options);
        }
Beispiel #22
0
        /// <summary>
        /// 加载Excel文件
        /// </summary>
        /// <param name="options">导入设置</param>
        public void loadExcel(Program.Options options)
        {
            _options = options;

            //-- Excel File
            string excelPath = options.excelPath;
            string excelName = Path.GetFileNameWithoutExtension(excelPath);

            HashSet <string> exportTags = new HashSet <string>();

            exportTags.Add("");
            if (options.exportTags != null)
            {
                var tags = options.exportTags.Split(',');
                foreach (var tag in tags)
                {
                    exportTags.Add(tag);
                }
            }

            //-- Encoding
            _encoding = new UTF8Encoding(false);

            //-- Load Excel
            ExcelLoader excel = new ExcelLoader(excelPath);

            //-- Parse Excel
            List <ExcelParser.TableInfo> tableInfos = ExcelParser.ReadSheetData(excel.Sheets[0]);

            //-- 导出 json
            _json = new JsonExporter(tableInfos, excelName, exportTags);

            //-- 导出 xml
            _xml = new XmlExporter(tableInfos, excelName, exportTags);

            //-- C# 结构体定义
            _csharp = new CSharpExporter(tableInfos, excelName, exportTags);
        }
Beispiel #23
0
        /// <summary>
        /// Parses the program from source and creates the VHDL output for the program
        /// </summary>
        /// <param name="source">The source file</param>
        /// <param name="timeout">The timeout to apply to the make process</param>
        public static void GenerateVHDLAndVerify(string source, TimeSpan timeout)
        {
            var outname   = Path.GetFileNameWithoutExtension(source);
            var targetdir = Path.Combine("output", outname);
            var opts      = new Program.Options()
            {
                EntryFile         = source,
                Arguments         = new string[0],
                OutputFolder      = targetdir,
                ClearTargetFolder = true
            };

            Program.RunCompiler(opts);

            var vhdldir = Path.Combine(targetdir, opts.VHDLOutputFolder);

            // Run Make test and check exit code
            var p = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo()
            {
                FileName = "make",

                // Since we do not have a trace file, we only test that the source can be build with GHDL
                Arguments        = "build",
                WorkingDirectory = vhdldir
            });

            p.WaitForExit((int)TimeSpan.FromSeconds(30).TotalMilliseconds);
            if (!p.HasExited)
            {
                p.Kill();
                throw new Exception($"Timeout from \"make\" in folder {Path.GetFullPath(vhdldir)} (ran for {timeout})");
            }

            if (p.ExitCode != 0)
            {
                throw new Exception($"Bad exit code from \"make\" in folder {Path.GetFullPath(vhdldir)}");
            }
        }
        internal static bool Parse(string[] args)
        {
            var options = new Program.Options();
            var parser  = new Parser(with =>
            {
                with.EnableDashDash         = true;
                with.CaseSensitive          = false;
                with.AutoVersion            = false;
                with.IgnoreUnknownArguments = true;
                with.AutoHelp   = false;
                with.HelpWriter = null;
            });
            var parserResults = parser
                                .ParseArguments <Program.Options>(args)
                                .WithParsed(o => options = o);

            Program.OptionFlags = options;

            // start handling flags that result in program exit
            if (options.Help)
            {
                Help(parserResults);
                return(false);
            }

            if (options.Version)
            {
                Version();
                return(false);
            }
            // end handling flags that result in program exit

#if DEBUG
            Program.IsDebug = true;
#endif

            var header = @"             ('-. .-.               .-')    .-') _     .-')    
            ( OO )  /              ( OO ). (  OO) )   ( OO ).  
  ,----.    ,--. ,--. .-'),-----. (_)---\_)/     '._ (_)---\_) 
 '  .-./-') |  | |  |( OO'  .-.  '/    _ | |'--...__)/    _ |  
 |  |_( O- )|   .|  |/   |  | |  |\  :` `. '--.  .--'\  :` `.  
 |  | .--, \|       |\_) |  |\|  | '..`''.)   |  |    '..`''.) 
(|  | '. (_/|  .-.  |  \ |  | |  |.-._)   \   |  |   .-._)   \ 
 |  '--'  | |  | |  |   `'  '-'  '\       /   |  |   \       / 
  `------'  `--' `--'     `-----'  `-----'    `--'    `-----'  ";
            Console.Write(header + Environment.NewLine);

            if (options.Debug || Program.IsDebug)
            {
                Program.IsDebug = true;
                Debug();
            }
            else
            {
                Console.WriteLine(
                    $"GHOSTS ({ApplicationDetails.Name}:{ApplicationDetails.Version}) running in production mode. Installed path: {ApplicationDetails.InstalledPath}");
            }

            if (options.Randomize)
            {
                throw new NotImplementedException("Randomize not released yet...");
                //Console.WriteLine("randomize!");
                //return;
            }

            return(true);
        }
Beispiel #25
0
        public void ExecutableExamples(IKjuExample example)
        {
            var options = new Program.Options
            {
                GenExe = true
            };
            var exeName = $"{TestsDirectory}/{example.SimpleName}";
            var query   = new CompilationQuery(example.Program, exeName);
            var diag    = new Mock <IDiagnostics>();

            Program.GenerateArtifacts(options, Compiler, query, diag.Object);
            var process = new System.Diagnostics.Process
            {
                StartInfo =
                {
                    FileName               = exeName,
                    Arguments              = string.Empty,
                    UseShellExecute        = false,
                    RedirectStandardInput  = true,
                    RedirectStandardOutput = true,
                    WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden,
                    CreateNoWindow         = true
                }
            };

            process.Start();
            using (var writer = process.StandardInput)
            {
                writer.Write(example.Input);
            }

            if (!process.WaitForExit(example.Timeout))
            {
                process.Kill();
                if (example.Ends)
                {
                    Assert.Fail($"Process has not ended before timeout ({example.Timeout}).");
                }
            }
            else
            {
                var exitCode = process.ExitCode;
                if (!example.Ends)
                {
                    Assert.Fail($"Should not end but ended with exit code {exitCode}.");
                }

                Assert.AreEqual(
                    example.ExpectedExitCode,
                    exitCode,
                    $"Process returned with wrong exit code.");
            }

            var processOutput = process.StandardOutput.ReadToEnd();

            var outputCheckResult = example.OutputChecker.CheckOutput(processOutput);

            outputCheckResult.Notes.ForEach(Console.WriteLine);
            if (outputCheckResult is OutputCheckResult.Wrong)
            {
                Assert.Fail("Output is wrong.");
            }

            MockDiagnostics.Verify(diag, example.ExpectedMagicStrings.ToArray());
        }
Beispiel #26
0
        static void Main(string[] args)
        {
            Program program = new Program();

            program.InitializeHash();



            int choice;

            do
            {
                Console.WriteLine("");
                Console.WriteLine("Hashtable operations");

                Console.WriteLine();
                Console.WriteLine("Enter Opertion choice : ");
                Console.WriteLine("1 for Addition of data ");
                Console.WriteLine("2 for Removal of data ");
                Console.WriteLine("3 for Updation of data ");
                Console.WriteLine("4 for Accessing data ");
                Console.WriteLine("5 for counting data");
                Console.WriteLine("6 for clearing data");
                Console.WriteLine("7 for cloaning data");
                Console.WriteLine("8 for getting miscellaneous information about hashtable");
                Console.WriteLine("9 for checking existance of key");
                Console.WriteLine("10 for checking existance of value");

                Console.WriteLine("0 to exit");

                Console.WriteLine();
                string choiceText = Console.ReadLine();
                if (int.TryParse(choiceText, out choice))
                {
                    Program.Options options = (Program.Options)choice;
                    Console.WriteLine();
                    Console.WriteLine("You have Selected " + options.ToString());
                }
                else
                {
                    Console.WriteLine("Invalid Input");
                    choice = 9;
                }

                switch (choice)
                {
                case 1:

                    Console.WriteLine("Enter Key : ");
                    var key = Console.ReadLine();
                    Console.WriteLine("Enter Value : ");
                    var value = Console.ReadLine();
                    program.AdditionToHashtable(key, value);
                    Console.WriteLine("Element added to the table");
                    break;

                case 2:
                    program.RemoveByKey();
                    break;

                case 3:
                    program.UpdateToHashTable();
                    break;

                case 4:
                    program.AccessData();
                    break;

                case 5:
                    program.CountData();
                    break;

                case 6:
                    program.ClearData();
                    break;

                case 7:
                    program.CloneData();
                    break;

                case 8:
                    program.MiscellaneousData();
                    break;

                case 9:
                    program.ContainsKey();
                    break;

                case 10:
                    program.ContainsValue();
                    break;
                }
            } while (choice != 0);
        }
Beispiel #27
0
        /// <summary>
        /// Creates the VHDL output files
        /// </summary>
        /// <param name="state">The validated network to create the files for</param>
        /// <param name="outputfolder">The folder to use as the base for the VHDL output</param>
        /// <param name="options">The options for creating the code</param>
        public static void CreateFiles(Validation.ValidationState state, string outputfolder, Program.Options options)
        {
            if (options.GHDLStandard != "93" && options.GHDLStandard != "93c")
            {
                throw new ParserException("Only 93 and 93c are currently supported", null);
            }

            var vhdlout = Path.GetFullPath(Path.Combine(outputfolder, options.VHDLOutputFolder));

            if (options.ClearTargetFolder && Directory.Exists(vhdlout))
            {
                if (string.IsNullOrWhiteSpace(options.VHDLOutputFolder) || options.VHDLOutputFolder.Trim().StartsWith("/"))
                {
                    throw new ArgumentException($"Refusing to delete folder, please supply a relative path: {options.VHDLOutputFolder}");
                }
                Directory.Delete(vhdlout, true);
            }

            if (!Directory.Exists(vhdlout))
            {
                Directory.CreateDirectory(vhdlout);
            }

            var config = new RenderConfig();

            if (options.CreateAocFiles)
            {
                Console.WriteLine("Note: aoc file generation activated, forcing options to be compatible with aoc output");
                config.REMOVE_ENABLE_FLAGS = true;
                config.RESET_SIGNAL_NAME   = "resetn";
                config.CLOCK_SIGNAL_NAME   = "clock";
                config.RESET_ACTIVE_LOW    = true;
                options.VHDLFileExtensions = "vhd";
            }

            var generator = new Codegen.VHDL.VHDLGenerator(state, config)
            {
                CSVTracename = options.TraceFile,
                Ticks        = File.Exists(options.TraceFile) ? File.ReadAllLines(options.TraceFile).Count() + 2 : 100,
                CustomFiles  = options.ExtraVHDLFiles
            };

            var rs = new Codegen.VHDL.VHDLGenerator.RenderState();

            var export = generator.GenerateExportModule(rs);

            File.WriteAllText(Path.Combine(vhdlout, Path.ChangeExtension("export.vhdl", options.VHDLFileExtensions)), export);

            var custtypes = generator.GenerateCustomTypes(rs);

            File.WriteAllText(Path.Combine(vhdlout, Path.ChangeExtension("customtypes.vhdl", options.VHDLFileExtensions)), custtypes);

            var tdoc = generator.GenerateMainModule(rs);

            File.WriteAllText(Path.Combine(vhdlout, Path.ChangeExtension("toplevel.vhdl", options.VHDLFileExtensions)), tdoc);

            var tbdoc = generator.GenerateTestbench(rs);

            File.WriteAllText(Path.Combine(vhdlout, Path.ChangeExtension("testbench.vhdl", options.VHDLFileExtensions)), tbdoc);

            var filenames = new Dictionary <Instance.Process, string>();

            foreach (var p in generator.AllRenderedProcesses)
            {
                var doc = generator.GenerateProcess(rs, p);
                var fn  = filenames[p] = generator.ProcessNames[p];
                File.WriteAllText(Path.Combine(vhdlout, Path.ChangeExtension(fn + ".vhdl", options.VHDLFileExtensions)), doc);
            }

            if (options.CreateXpf)
            {
                var txpf = generator.GenerateXpf(rs, filenames, options.VHDLFileExtensions);
                File.WriteAllText(Path.Combine(vhdlout, $"project.xpf"), txpf);
            }

            if (options.CreateAocFiles)
            {
                var aoclproj = generator.GenerateAocl(rs, filenames, options.VHDLFileExtensions);
                File.WriteAllText(Path.Combine(vhdlout, $"opencl_lib.xml"), aoclproj);
            }

            var makefile = generator.GenerateMakefile(rs, filenames, options.GHDLStandard, options.VHDLFileExtensions);

            File.WriteAllText(Path.Combine(vhdlout, $"Makefile"), makefile);

            generator.CopySupportFiles(vhdlout);
        }