コード例 #1
0
ファイル: Program.cs プロジェクト: ppittle/LBi.LostDoc
        /// <summary>
        /// Mains the specified args.
        /// </summary>
        /// <param name="args">
        /// The args. 
        /// </param>
        public static void Main(string[] args)
        {
            WriteSignature();

            using (AggregateCatalog aggregateCatalog = new AggregateCatalog())
            {
                aggregateCatalog.Catalogs.Add(new ApplicationCatalog());

                string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                string pluginPath = Path.Combine(appPath, "plugins");
                if (Directory.Exists(pluginPath))
                    aggregateCatalog.Catalogs.Add(new DirectoryCatalog(pluginPath));

                using (CompositionContainer container = new CompositionContainer(aggregateCatalog))
                {
                    ICommandProvider[] providers = container.GetExports<ICommandProvider>().Select(l => l.Value).ToArray();
                    var commands = providers.SelectMany(p => p.GetCommands()).ToArray();

                    ArgumentParser<ICommand> argumentParser = new ArgumentParser<ICommand>(commands);
                    ICommand command;
                    if (argumentParser.TryParse(args, out command))
                    {
                        command.Invoke(container);
                    }
                }
            }
        }
コード例 #2
0
ファイル: SLProxy.cs プロジェクト: RavenB/gridsearch
        // ProxyConfig: construct a default proxy configuration, parsing command line arguments (try --proxy-help)
        public ProxyConfig(string userAgent, string author, string[] args)
            : this(userAgent, author)
        {
            Dictionary<string, ArgumentParser> argumentParsers = new Dictionary<string, ArgumentParser>();
            argumentParsers["proxy-help"] = new ArgumentParser(ParseHelp);
            argumentParsers["proxy-login-port"] = new ArgumentParser(ParseLoginPort);
            argumentParsers["proxy-client-facing-address"] = new ArgumentParser(ParseClientFacingAddress);
            argumentParsers["proxy-remote-facing-address"] = new ArgumentParser(ParseRemoteFacingAddress);
            argumentParsers["proxy-remote-login-uri"] = new ArgumentParser(ParseRemoteLoginUri);
            argumentParsers["proxy-verbose"] = new ArgumentParser(ParseVerbose);
            argumentParsers["proxy-quiet"] = new ArgumentParser(ParseQuiet);

            foreach (string arg in args)
                foreach (string argument in argumentParsers.Keys)
                {
                    Match match = (new Regex("^--" + argument + "(?:=(.*))?$")).Match(arg);
                    if (match.Success)
                    {
                        string value;
                        if (match.Groups[1].Captures.Count == 1)
                            value = match.Groups[1].Captures[0].ToString();
                        else
                            value = null;
                        try
                        {
                            ((ArgumentParser)argumentParsers[argument])(value);
                        }
                        catch
                        {
                            Console.WriteLine("invalid value for --" + argument);
                            ParseHelp(null);
                        }
                    }
                }
        }
コード例 #3
0
ファイル: GenerateCommand.cs プロジェクト: GeertVL/dbgen
 public void execute(ArgumentParser arguments)
 {
     if (arguments.DetailCommand == "file" || string.IsNullOrEmpty(arguments.DetailCommand))
     {
         this.CreateFile("general", null);
     }
     else if (arguments.DetailCommand == "create")
     {
         CreateAction(arguments.Parameters["type"], arguments.Parameters["name"], null);
     }
     else if (arguments.DetailCommand == "change")
     {
         ChangeAction(arguments.Parameters["type"], arguments.Parameters["tbl"], arguments.Parameters["name"], arguments.Parameters["args"]);
     }
     else if (arguments.DetailCommand == "drop")
     {
         DropAction(arguments.Parameters["tbl"]);
     }
     else if (arguments.DetailCommand == "data")
     {
         string connectionStringName = "db_develop";
         if (arguments.Parameters.ContainsKey("con"))
         {
             connectionStringName = arguments.Parameters["con"];
         }
         DataAction(arguments.Parameters["tbl"], connectionStringName);
     }
     else
     {
         Console.WriteLine("Unknown action for command Generate");
     }
 }
コード例 #4
0
ファイル: Cmd_BZip2.cs プロジェクト: icsharpcode/SharpZipLib
    public static int Main(string[] args)
    {
        if (args.Length == 0) {
            ShowHelp();
            return 1;
        }

        var parser = new ArgumentParser(args);

        switch (parser.Command) {
            case Command.Help:
                ShowHelp();
                break;

            case Command.Compress:
                Console.WriteLine("Compressing {0} to {1} at level {2}", parser.Source, parser.Target, parser.Level);
                BZip2.Compress(File.OpenRead(parser.Source), File.Create(parser.Target), true, parser.Level);
                break;

            case Command.Decompress:
                Console.WriteLine("Decompressing {0} to {1}", parser.Source, parser.Target);
                BZip2.Decompress(File.OpenRead(parser.Source), File.Create(parser.Target), true);
                break;
        }

        return 0;
    }
コード例 #5
0
        private static void Main(string[] args)
        {
            ArgumentParser argp = new ArgumentParser();
            var a = argp.Parse(args);
            string username = a.GetValue("u", "user", "username");
            string password = a.GetValue("p", "pwd", "pass", "password");
            string school = a.GetValue("s", "school");
            string year = a.GetValue("y", "year");

            if (string.IsNullOrWhiteSpace(username))
                username = Program.Prompt("username");
            if (string.IsNullOrWhiteSpace(username))
                return;

            if (string.IsNullOrWhiteSpace(password))
                password = Program.Prompt("password");
            if (string.IsNullOrWhiteSpace(password))
                return;

            int schoolNumber = 0;
            if (string.IsNullOrWhiteSpace(school))
                school = Program.Prompt("school");
            if (string.IsNullOrWhiteSpace(school) || !int.TryParse(school, out schoolNumber))
                return;

            int yearNumber = 0;
            if (string.IsNullOrWhiteSpace(year))
                year = Program.Prompt("year");
            if (string.IsNullOrWhiteSpace(year) || !int.TryParse(year, out yearNumber))
                return;

            try
            {
                Console.Clear();
                Console.WriteLine("Downloading...");
                YearbookClient yb = new YearbookClient(username, password);
                yb.DownloadRoot = Environment.CurrentDirectory;
                int downloadCount = 0;
                yb.ImageDownloaded += (sender, e) =>
                {
                    downloadCount = e.ImageNumber;
                    Console.Clear();
                    Console.WriteLine($"Downloaded {downloadCount} images...");
                };
                string dir = yb.DownloadYearbook(schoolNumber, yearNumber).Result;
                Console.Clear();
                Console.WriteLine($"Complete. Downloaded {downloadCount} images to '{dir}'.");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            if (Debugger.IsAttached)
            {
                Console.WriteLine();
                Console.WriteLine("Press [Enter] to exit.");
                Console.ReadLine();
            }
        }
コード例 #6
0
ファイル: ParserTest.cs プロジェクト: Platzer/ShellFx
        public void ParserTestHelp()
        {
            string[] args = new string[] { "c:\\test ordner2", "-Pfad", "c:\\test ordner", "/switch1", "/switch2-", "c:\\test ordner2", "--double=3.2" };
            var parsed = new ArgumentParser<MyArgs>();
            parsed.Parse(args);

            parsed.PrintPropertyHelp();
        }
コード例 #7
0
ファイル: ScriptFileHelperTest.cs プロジェクト: GeertVL/dbgen
 public void GetScriptPath_CurrentDir()
 {
     ArgumentParser arguments = new ArgumentParser(null);
     string expected = Environment.CurrentDirectory;
     string actual;
     actual = ScriptFileHelper.GetScriptPath(arguments);
     Assert.AreEqual(expected, actual);
 }
コード例 #8
0
 public void UrlDefined_ShouldGetServerUrl()
 {
     ArgumentParser parser = new ArgumentParser();
     var expected = "http://bhiabztfs01:8080";
     string[] arguments = { "/url:" + expected };
     parser.Parse(arguments);
     var actual = parser.Url;
     Assert.AreEqual(expected, actual);
 }
コード例 #9
0
 public void InvocationAsExpectedShouldGetFile()
 {
     ArgumentParser parser = new ArgumentParser();
     var expected = "john.cs";
     string[] arguments = {"/noprompt", expected};
     parser.Parse(arguments);
     var actual = parser.File;
     Assert.AreEqual(expected,actual);
 }
コード例 #10
0
 public void InvocationWithJustFilenameShouldGetFile()
 {
     ArgumentParser parser = new ArgumentParser();
     var expected = "john.cs";
     string[] arguments = { expected };
     parser.Parse(arguments);
     var actual = parser.File;
     Assert.AreEqual(expected, actual);
 }
コード例 #11
0
 public void UrlIncomplete_ShouldGetEmptyUrl()
 {
     ArgumentParser parser = new ArgumentParser();
     String expected = null;
     string[] arguments = { "/url:" + expected };
     parser.Parse(arguments);
     var actual = parser.Url;
     Assert.AreEqual(null, actual);
 }
コード例 #12
0
    public static void Main(string[] args)
    {
        using (ArgumentParser parser = new ArgumentParser("test_argument_parser.cs"))
        {
            parser.addOptionalIntArgument("runs", "how many runs to perform", 1);
            parser.addOptionalFlag("verbose", "print lots of debugging information");
            parser.addOptionalFloatArgument("q", "what is the q parameter", 0.01);
            parser.addOptionalStringArgument("mission", "the mission filename", "");

            string[] args1 = new string[] { "filename", "--runs", "3", "--q", "0.2", "--mission", "test.xml", "--verbose" };
            using (StringVector sargs1 = new StringVector(args1))
            {
                try
                {
                    parser.parse(sargs1);
                }
                catch
                {
                    Environment.Exit(1);
                }
            }

            if (!parser.receivedArgument("runs") || parser.getIntArgument("runs") != 3)
                Environment.Exit(1);

            if (!parser.receivedArgument("q") || Math.Abs(0.2 - parser.getFloatArgument("q")) > 1E-06)
                Environment.Exit(1);

            if (!parser.receivedArgument("mission") || parser.getStringArgument("mission") != "test.xml")
                Environment.Exit(1);

            if (!parser.receivedArgument("verbose"))
                Environment.Exit(1);

            if (parser.receivedArgument("test.xml"))
                Environment.Exit(1);

            // we expect this to give an error
            string[] args2 = new string[]{ "filename", "--runs" };
            using (StringVector sargs2 = new StringVector(args2))
            {
                try
                {
                    parser.parse(sargs2);
                }
                catch
                {
                    // this is what we expect to happen
                    Environment.Exit(0);
                }
            }

            Environment.Exit(1);
        }
    }
コード例 #13
0
ファイル: Program.cs プロジェクト: GeertVL/dbgen
        static void Main(string[] args)
        {
            var arguments = new ArgumentParser(args);
            string connectionStringName = "db_develop";
            if (arguments.Parameters.ContainsKey("con"))
            {
                connectionStringName = arguments.Parameters["con"];
            }

            if (arguments.Command == "generate")
            {
                // expected args[1] - gentype (file/create/change/remove/data)
                // create sqlscript with proper timestamp
                new GenerateCommand().execute(arguments);
            }
            else if (arguments.Command == "deploy")
            {
                var command = new DeployCommand(connectionStringName);
                if (arguments.Parameters.ContainsKey("data"))
                {
                    command.DeployData = true;
                }
                // expected args[1] - dbconname ; args[2] - van welke file of date
                // deploy de beschikbare scripts naar de db
                if (arguments.DetailCommand == "reset")
                {
                    // dbgen deploy reset (-con:connectionStringName)
                    command.Execute();
                }
                else if (arguments.Parameters.ContainsKey("file"))
                {
                    // dbgen deploy -file:deployfile.sql (-con:connectionStringName)
                    command.Execute(arguments.Parameters["file"]);
                }
                else
                {
                    // dbgen deploy (-con:connectionStringName)
                    DateTime version = VersionHelper.GetDbConfigVersionDate(connectionStringName);
                    if (version == DateTime.MinValue)
                    {
                        command.Execute();
                    }
                    else
                    {
                        command.Execute(version);
                    }
                }
            }
            else if (arguments.Command == "version")
            {
                // dbgen version (-con:connectionStringName)
                new VersionCommand().Execute(connectionStringName);
            }
        }
コード例 #14
0
ファイル: ParserTest.cs プロジェクト: Platzer/ShellFx
        public void ParserTestMultipleValues()
        {
            string[] args = new string[] { "c:\\test ordner2", "-Pfad", "c:\\test ordner", "/switch1", "c:\\test ordner2", "--double=3.2" };
            var parsed = new ArgumentParser<MyArgs>().Parse(args);

            Assert.IsTrue(parsed.Pfad == "c:\\test ordner");
            Assert.IsTrue(parsed.OutPutPfad == "c:\\test ordner2");
            Assert.IsTrue(parsed.Switch1);
            Assert.IsFalse(parsed.Switch2);
            Assert.IsTrue(3.2 == parsed.Double);
        }
コード例 #15
0
ファイル: Program.cs プロジェクト: LBiNetherlands/LBi.LostDoc
        /// <summary>
        /// Mains the specified args.
        /// </summary>
        /// <param name="args">
        /// The args. 
        /// </param>
        public static void Main(string[] args)
        {
            WriteSignature();

            using (AggregateCatalog aggregateCatalog = new AggregateCatalog())
            {
                RegistrationBuilder registrationBuilder = new RegistrationBuilder();

                registrationBuilder.ForTypesDerivedFrom<ICommand>()
                                   .Export(conf => conf.AsContractName(AttributedModelServices.GetContractName(typeof(ICommand))))
                                   .SetCreationPolicy(CreationPolicy.NonShared);
                
                aggregateCatalog.Catalogs.Add(new ApplicationCatalog(registrationBuilder));

                string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                string pluginPath = Path.Combine(appPath, "plugins");
                if (Directory.Exists(pluginPath))
                    aggregateCatalog.Catalogs.Add(new DirectoryCatalog(pluginPath, registrationBuilder));

                using (CompositionContainer container = new CompositionContainer(aggregateCatalog))
                {
                    ICommandProvider[] providers = container.GetExports<ICommandProvider>().Select(l => l.Value).ToArray();
                    Type[] commands = providers.SelectMany(p => p.GetCommands()).ToArray();

                    Func<Type, object> mefActivator =
                        t =>
                        {
                            if (!typeof(ICommand).IsAssignableFrom(t))
                                return DefaultActivator.Instance.CreateInstance(t);

                            ImportDefinition importDefinition = new ImportDefinition(ed => (string)ed.Metadata[CompositionConstants.ExportTypeIdentityMetadataName] == AttributedModelServices.GetTypeIdentity(t),
                                                                                     AttributedModelServices.GetContractName(typeof(ICommand)),
                                                                                     ImportCardinality.ExactlyOne,
                                                                                     false,
                                                                                     true);

                            return container.GetExports(importDefinition).First().Value;
                        };

                    ArgumentParserSettings parserSettings = new ArgumentParserSettings
                                                            {
                                                                TypeActivator = new DelegateActivator(mefActivator)
                                                            };

                    ArgumentParser<ICommand> argumentParser = new ArgumentParser<ICommand>(parserSettings, commands);
                    ICommand command;
                    if (argumentParser.TryParse(args, out command))
                    {
                        command.Invoke(container);
                    }
                }
            }
        }
コード例 #16
0
    public static int Main(string[] args)
    {
        if (args.Length == 0) {
            ShowHelp();
            return 1;
        }

        var parser = new ArgumentParser(args);

        if (!File.Exists(file_)) {
            Console.Error.WriteLine("Cannot find file {0}", file_);
            ShowHelp();
            return 1;
        }

        using (FileStream checksumStream = File.OpenRead(file_)) {

            byte[] buffer = new byte[4096];
            int bytesRead;

            switch (parser.Command) {
                case Command.Help:
                    ShowHelp();
                    break;

                case Command.Crc32:
                    var currentCrc = new Crc32();
                    while ((bytesRead = checksumStream.Read(buffer, 0, buffer.Length)) > 0) {
                        currentCrc.Update(buffer, 0, bytesRead);
                    }
                    Console.WriteLine("CRC32 for {0} is 0x{1:X8}", args[0], currentCrc.Value);
                    break;

                case Command.BZip2:
                    var currentBZip2Crc = new BZip2Crc();
                    while ((bytesRead = checksumStream.Read(buffer, 0, buffer.Length)) > 0) {
                        currentBZip2Crc.Update(buffer, 0, bytesRead);
                    }
                    Console.WriteLine("BZip2CRC32 for {0} is 0x{1:X8}", args[0], currentBZip2Crc.Value);
                    break;

                case Command.Adler:
                    var currentAdler = new Adler32();
                    while ((bytesRead = checksumStream.Read(buffer, 0, buffer.Length)) > 0) {
                        currentAdler.Update(buffer, 0, bytesRead);
                    }
                    Console.WriteLine("Adler32 for {0} is 0x{1:X8}", args[0], currentAdler.Value);
                    break;
            }
        }
        return 0;
    }
コード例 #17
0
        public static Args ParseArgs(string[] args)
        {
            if (args == null) args = new string[0];
            if (args.Length == 0)
                _isDefault = true;

            var result = new Args();
            IArgumentMapFactory _argumentMapFactory = new ArgumentMapFactory();
            IArgumentParser _argumentParser = new ArgumentParser();
            IEnumerable<IArgument> arguments = _argumentParser.Parse(args);
            IArgumentMap mapper = _argumentMapFactory.CreateMap(result);
            IEnumerable<IArgument> remaining = mapper.ApplyTo(result, arguments);

            return result;
        }
コード例 #18
0
        /// <summary>
        /// Note that in order to register a converter you can use:
        /// TypeDescriptor.AddAttributes(typeof(AType), new TypeConverterAttribute(typeof(ATypeConverter)));
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>
        public ParsedMethod Parse(IEnumerable<string> arg)
        {
            var lexed = RewriteLexedTokensToSupportHelpAndIndex.Rewrite(ArgumentLexer.Lex(arg).ToList());

            var methodInfo = FindMethodInfo(lexed);

            var argumentRecognizers = methodInfo.GetArguments()
                .ToList();
            argumentRecognizers.InsertRange(0, new[] {
                new ArgumentWithOptions(ArgumentParameter.Parse("#0" + _controller.Name, Culture), required: true, type: typeof(string)),
                new ArgumentWithOptions(ArgumentParameter.Parse("#1" + methodInfo.Name, Culture), required: false, type: typeof(string))
            });

            var parser = new ArgumentParser(argumentRecognizers, _allowInferParameter, Culture);
            var parsedArguments = parser.Parse(lexed, arg);

            return Parse(methodInfo, parsedArguments);
        }
コード例 #19
0
ファイル: Main.cs プロジェクト: firestrand/SharpZipLib
    public static void Main(string[] args)
    {
        ArgumentParser parser = new ArgumentParser(args);

        switch ( parser.Command ) {
            case Command.Help:
                ShowHelp();
                break;

            case Command.Compress:
                Console.WriteLine("Compressing {0} to {1}", parser.Source, parser.Target);
                BZip2.Compress(File.OpenRead(parser.Source), File.Create(parser.Target),true, 4096);
                break;

            case Command.Decompress:
                Console.WriteLine("Decompressing {0} to {1}", parser.Source, parser.Target);
                BZip2.Decompress(File.OpenRead(parser.Source), File.Create(parser.Target),true);
                break;
        }
    }
コード例 #20
0
    public static int Main(string[] args)
    {
        if (args.Length == 0) {
            ShowHelp();
            return 1;
        }

        if (!File.Exists(args[0])) {
            Console.Error.WriteLine("Cannot find file {0}", args[0]);
            ShowHelp();
            return 1;
        }

        var parser = new ArgumentParser(args);

        using (ZipFile zFile = new ZipFile(args[0])) {
            Console.WriteLine("Listing of : " + zFile.Name);
            Console.WriteLine("");
            if (false) {
                Console.WriteLine("Raw Size    Size       Date       Time     Name");
                Console.WriteLine("--------  --------  -----------  ------  ---------");
                foreach (ZipEntry e in zFile) {
                    DateTime d = e.DateTime;
                    Console.WriteLine("{0, -10}{1, -10}{2}  {3}   {4}", e.Size, e.CompressedSize,
                                                                        d.ToString("dd MMM yyyy"), d.ToString("HH:mm"),
                                                                        e.Name);
                }
            } else {
                Console.WriteLine("Raw Size,Size,Date,Time,Name");
                foreach (ZipEntry e in zFile) {
                    DateTime d = e.DateTime;
                    Console.WriteLine("{0, -10}{1, -10}{2}  {3}   {4}", e.Size, e.CompressedSize,
                                                                        d.ToString("dd MMM yyyy"), d.ToString("HH:mm"),
                                                                        e.Name);
                }

            }
        }

        return 0;
    }
コード例 #21
0
        public void CorrectArguments_CorrectionPerformed(string[] inputArgs, string[] expectedArgs)
        {
            var correctedArgs = ArgumentParser.CorrectArguments(inputArgs);

            Assert.Equal(expectedArgs, correctedArgs);
        }
コード例 #22
0
        public void Create_mulitple_assembly_info_protected(string command)
        {
            var exception = Assert.Throws <WarningException>(() => ArgumentParser.ParseArguments(command));

            exception.Message.ShouldBe("Can't specify multiple assembly info files when using /ensureassemblyinfo switch, either use a single assembly info file or do not specify /ensureassemblyinfo and create assembly info files manually");
        }
コード例 #23
0
ファイル: TestInputCommand.cs プロジェクト: kurumushi/SMAPI
 /// <summary>Handle the command.</summary>
 /// <param name="monitor">Writes messages to the console and log file.</param>
 /// <param name="command">The command name.</param>
 /// <param name="args">The command arguments.</param>
 public override void Handle(IMonitor monitor, string command, ArgumentParser args)
 {
     this.ExpiryTicks = DateTime.UtcNow.Add(TimeSpan.FromSeconds(this.LogSeconds)).Ticks;
     monitor.Log($"OK, logging all player input for {this.LogSeconds} seconds.", LogLevel.Info);
 }
コード例 #24
0
ファイル: ScriptFileHelperTest.cs プロジェクト: GeertVL/dbgen
 public void GetScriptPath_PathEmpty()
 {
     ArgumentParser arguments = new ArgumentParser(null);
     arguments.Parameters.Add("path", @"");
     string expected = Environment.CurrentDirectory;
     string actual;
     actual = ScriptFileHelper.GetScriptPath(arguments);
     Assert.AreEqual(expected, actual);
 }
コード例 #25
0
ファイル: Main.cs プロジェクト: vikasraz/indexsearchutils
	public static void Main(string[] args)
	{
		byte[] dataBuffer = new byte[4096];
		
		ArgumentParser parser = new ArgumentParser(args);
		
		switch ( parser.Command ) {
			case Command.Compress:
				Console.WriteLine("Compressing {0} to {1}", parser.Source, parser.Target);
				using (Stream s = new GZipOutputStream(File.Create(args[0] + ".gz")))
				using (FileStream fs = File.OpenRead(args[0])) {
					StreamUtils.Copy(fs, s, dataBuffer);
				}
				break;
				
			case Command.Decompress:
				Console.WriteLine("Decompressing {0} to {1}", parser.Source, parser.Target);
				using (Stream s = new GZipInputStream(File.OpenRead(args[1])))
				using (FileStream fs = File.Create(Path.GetFileNameWithoutExtension(args[1]))) {
					StreamUtils.Copy(s, fs, dataBuffer);
				}
				break;
				
			case Command.Help:
				ShowHelp();
				break;
		}
	}
コード例 #26
0
        static void Main(string[] args)
        {
            O2GSession            session          = null;
            SessionStatusListener statusListener   = null;
            ResponseListener      responseListener = null;
            string sInstrument = "EUR/USD";
            string sBuySell    = Constants.Buy;

            try
            {
                Console.WriteLine("RemoveOrder sample\n");

                ArgumentParser argParser = new ArgumentParser(args, "RemoveOrder");

                argParser.AddArguments(ParserArgument.Login,
                                       ParserArgument.Password,
                                       ParserArgument.Url,
                                       ParserArgument.Connection,
                                       ParserArgument.SessionID,
                                       ParserArgument.Pin,
                                       ParserArgument.AccountID);

                argParser.ParseArguments();

                if (!argParser.AreArgumentsValid)
                {
                    argParser.PrintUsage();
                    return;
                }

                argParser.PrintArguments();

                LoginParams  loginParams  = argParser.LoginParams;
                SampleParams sampleParams = argParser.SampleParams;

                session = O2GTransport.createSession();
                session.useTableManager(O2GTableManagerMode.Yes, null);
                statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin);
                session.subscribeSessionStatus(statusListener);
                statusListener.Reset();
                session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection);
                if (statusListener.WaitEvents() && statusListener.Connected)
                {
                    responseListener = new ResponseListener();
                    TableListener tableListener = new TableListener(responseListener);
                    session.subscribeResponse(responseListener);

                    O2GTableManager       tableManager  = session.getTableManager();
                    O2GTableManagerStatus managerStatus = tableManager.getStatus();
                    while (managerStatus == O2GTableManagerStatus.TablesLoading)
                    {
                        Thread.Sleep(50);
                        managerStatus = tableManager.getStatus();
                    }

                    if (managerStatus == O2GTableManagerStatus.TablesLoadFailed)
                    {
                        throw new Exception("Cannot refresh all tables of table manager");
                    }
                    O2GAccountRow account = GetAccount(tableManager, sampleParams.AccountID);
                    if (account == null)
                    {
                        if (string.IsNullOrEmpty(sampleParams.AccountID))
                        {
                            throw new Exception("No valid accounts");
                        }
                        else
                        {
                            throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID));
                        }
                    }
                    sampleParams.AccountID = account.AccountID;

                    O2GOfferRow offer = GetOffer(tableManager, sInstrument);
                    if (offer == null)
                    {
                        throw new Exception(string.Format("The instrument '{0}' is not valid", sInstrument));
                    }

                    O2GLoginRules loginRules = session.getLoginRules();
                    if (loginRules == null)
                    {
                        throw new Exception("Cannot get login rules");
                    }

                    O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider();
                    int    iBaseUnitSize = tradingSettingsProvider.getBaseUnitSize(sInstrument, account);
                    int    iAmount       = iBaseUnitSize * 1;
                    double dRate         = offer.Ask - (offer.PointSize * 10);
                    tableListener.SubscribeEvents(tableManager);
                    O2GRequest request = CreateEntryOrderRequest(session, offer.OfferID, account.AccountID, iAmount, dRate, sBuySell, Constants.Orders.LimitEntry);
                    if (request == null)
                    {
                        throw new Exception("Cannot create request");
                    }
                    responseListener.SetRequestID(request.RequestID);
                    tableListener.SetRequestID(request.RequestID);
                    session.sendRequest(request);
                    if (!responseListener.WaitEvents())
                    {
                        throw new Exception("Response waiting timeout expired");
                    }
                    string sOrderID = tableListener.GetOrderID();

                    if (!string.IsNullOrEmpty(sOrderID))
                    {
                        request = RemoveOrderRequest(session, account.AccountID, sOrderID);
                        if (request == null)
                        {
                            throw new Exception("Cannot create request");
                        }
                        responseListener.SetRequestID(request.RequestID);
                        tableListener.SetRequestID(request.RequestID);
                        session.sendRequest(request);
                        if (responseListener.WaitEvents())
                        {
                            Console.WriteLine("Done!");
                        }
                        else
                        {
                            throw new Exception("Response waiting timeout expired");
                        }
                    }

                    tableListener.UnsubscribeEvents(tableManager);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e.ToString());
            }
            finally
            {
                if (session != null)
                {
                    if (statusListener.Connected)
                    {
                        statusListener.Reset();
                        session.logout();
                        statusListener.WaitEvents();
                        if (responseListener != null)
                        {
                            session.unsubscribeResponse(responseListener);
                        }
                        session.unsubscribeSessionStatus(statusListener);
                    }
                    session.Dispose();
                }
            }
        }
コード例 #27
0
        public override PresentParserState Parse(IArgumentEnumerator argumentEnumerator, OptionMap map, object options)
        {
            var parts  = argumentEnumerator.Current.Substring(2).Split(new[] { '=' }, 2);
            var option = map[parts[0]];

            if (option == null)
            {
                return(_ignoreUnkwnownArguments ? PresentParserState.MoveOnNextElement : PresentParserState.Failure);
            }

            option.IsDefined = true;

            ArgumentParser.EnsureOptionArrayAttributeIsNotBoundToScalar(option);

            bool valueSetting;

            if (!option.IsBoolean)
            {
                if (parts.Length == 1 && (argumentEnumerator.IsLast || !ArgumentParser.IsInputValue(argumentEnumerator.Next)))
                {
                    return(PresentParserState.Failure);
                }

                if (parts.Length == 2)
                {
                    if (!option.IsArray)
                    {
                        valueSetting = option.SetValue(parts[1], options);
                        if (!valueSetting)
                        {
                            DefineOptionThatViolatesFormat(option);
                        }

                        return(ArgumentParser.BooleanToParserState(valueSetting));
                    }

                    ArgumentParser.EnsureOptionAttributeIsArrayCompatible(option);

                    var items = ArgumentParser.GetNextInputValues(argumentEnumerator);
                    items.Insert(0, parts[1]);

                    valueSetting = option.SetValue(items, options);
                    if (!valueSetting)
                    {
                        DefineOptionThatViolatesFormat(option);
                    }

                    return(ArgumentParser.BooleanToParserState(valueSetting));
                }
                else
                {
                    if (!option.IsArray)
                    {
                        valueSetting = option.SetValue(argumentEnumerator.Next, options);
                        if (!valueSetting)
                        {
                            DefineOptionThatViolatesFormat(option);
                        }

                        return(ArgumentParser.BooleanToParserState(valueSetting, true));
                    }

                    ArgumentParser.EnsureOptionAttributeIsArrayCompatible(option);

                    var items = ArgumentParser.GetNextInputValues(argumentEnumerator);

                    valueSetting = option.SetValue(items, options);
                    if (!valueSetting)
                    {
                        DefineOptionThatViolatesFormat(option);
                    }

                    return(ArgumentParser.BooleanToParserState(valueSetting));
                }
            }

            if (parts.Length == 2)
            {
                return(PresentParserState.Failure);
            }

            valueSetting = option.SetValue(true, options);
            if (!valueSetting)
            {
                DefineOptionThatViolatesFormat(option);
            }

            return(ArgumentParser.BooleanToParserState(valueSetting));
        }
コード例 #28
0
        public void Ensure_assembly_info_true()
        {
            var arguments = ArgumentParser.ParseArguments("-ensureAssemblyInfo true");

            arguments.EnsureAssemblyInfo.ShouldBe(true);
        }
コード例 #29
0
        /// <summary>
        ///     Parses raw bytes to RemoteConPacket
        /// </summary>
        /// <param name="rawPacket"></param>
        internal void ParsePacket(byte[] rawPacket)
        {
            try
            {
                var packet = new RemoteConPacket(rawPacket, _remoteConServer.UseUTF8);

                if (!_isUnitTest)
                {
                    _remoteConServer.LogDebug(((IPEndPoint)_tcp.Client.RemoteEndPoint).Address + " sent packet " +
                                              packet.Type + "!");
                }

                // Do not allow any other packets than auth to be sent when client is not authenticated
                if (!Authenticated)
                {
                    if (packet.Type != RemoteConPacket.PacketType.Auth)
                    {
                        if (_isUnitTest)
                        {
                            throw new NotAuthenticatedException();
                        }
                        CloseConnection();
                    }

                    _authTries++;

                    if (packet.Payload == _remoteConServer.Password)
                    {
                        if (!_isUnitTest)
                        {
                            _remoteConServer.LogDebug(((IPEndPoint)_tcp.Client.RemoteEndPoint).Address +
                                                      " successfully authenticated!");
                        }
                        Authenticated = true;

                        if (!_remoteConServer.SendAuthImmediately)
                        {
                            SendPacket(new RemoteConPacket(packet.Id, RemoteConPacket.PacketType.ResponseValue, "", _remoteConServer.UseUTF8));
                        }

                        SendPacket(new RemoteConPacket(packet.Id, RemoteConPacket.PacketType.ExecCommand, "", _remoteConServer.UseUTF8));
                        return;
                    }

                    if (_authTries >= _remoteConServer.MaxPasswordTries)
                    {
                        if (_remoteConServer.BanMinutes > 0)
                        {
                            _remoteConServer.IpBanList.Add(((IPEndPoint)_tcp.Client.RemoteEndPoint).Address.ToString(),
                                                           DateTime.Now.AddMinutes(_remoteConServer.BanMinutes).ToUnixTimestamp());
                        }

                        CloseConnection();
                        return;
                    }

                    if (!_isUnitTest)
                    {
                        _remoteConServer.LogDebug(((IPEndPoint)_tcp.Client.RemoteEndPoint).Address +
                                                  " entered wrong password!");
                    }

                    if (!_remoteConServer.SendAuthImmediately)
                    {
                        SendPacket(new RemoteConPacket(packet.Id, RemoteConPacket.PacketType.ResponseValue, "", _remoteConServer.UseUTF8));
                    }

                    SendPacket(new RemoteConPacket(-1, RemoteConPacket.PacketType.ExecCommand, "", _remoteConServer.UseUTF8));

                    return;
                }

                // Invalid packet type.
                if (packet.Type != RemoteConPacket.PacketType.ExecCommand)
                {
                    if (_isUnitTest)
                    {
                        throw new InvalidPacketTypeException();
                    }

                    _remoteConServer.LogDebug(((IPEndPoint)_tcp.Client.RemoteEndPoint).Address +
                                              " sent a packet with invalid type!");

                    if (_remoteConServer.InvalidPacketKick)
                    {
                        CloseConnection();
                    }
                    return;
                }

                if (packet.Payload == "")
                {
                    if (_isUnitTest)
                    {
                        throw new EmptyPacketPayloadException();
                    }
                    _remoteConServer.LogDebug(((IPEndPoint)_tcp.Client.RemoteEndPoint).Address +
                                              " sent a packet with empty payload!");

                    if (_remoteConServer.EmptyPayloadKick)
                    {
                        CloseConnection();
                    }
                    return;
                }

                var args = ArgumentParser.ParseLine(packet.Payload);
                var cmd  = args[0];
                args.RemoveAt(0);

                if (_remoteConServer.UseCustomCommandHandler)
                {
                    var result = _remoteConServer.ExecuteCustomCommandHandler(cmd, args);
                    SendPacket(new RemoteConPacket(packet.Id, RemoteConPacket.PacketType.ResponseValue,
                                                   result, _remoteConServer.UseUTF8));
                    return;
                }

                var command = _remoteConServer.CommandManager.GetCommand(cmd);
                if (command == null)
                {
                    SendPacket(new RemoteConPacket(packet.Id, RemoteConPacket.PacketType.ResponseValue,
                                                   "Invalid command \"" + packet.Payload + "\"", _remoteConServer.UseUTF8));
                }
                else
                {
                    var commandResult = command.Handler(cmd, args);
                    // TODO: Split packets?
                    SendPacket(new RemoteConPacket(packet.Id, RemoteConPacket.PacketType.ResponseValue,
                                                   commandResult, _remoteConServer.UseUTF8));
                }
            }
            catch (RconServerException)
            {
                throw;
            }
            catch (Exception e)
            {
                if (_isUnitTest)
                {
                    throw;
                }

                if (!_isUnitTest)
                {
                    _remoteConServer.LogDebug(string.Format("Client {0} caused an exception: {1} and was killed.",
                                                            ((IPEndPoint)_tcp.Client.RemoteEndPoint).Address, e.Message));
                }

                CloseConnection();
            }
        }
コード例 #30
0
        public void ParseCorruptedArguments_ParsesArguments(string arg, List <Match> argumentStarts, List <string> expectedResult)
        {
            var parsedArgs = ArgumentParser.ParseCorruptedArguments(arg, argumentStarts);

            Assert.Equal(expectedResult, parsedArgs);
        }
コード例 #31
0
        public override bool Execute(List <string> args)
        {
            //Arguments needed: filepath, <new>|<tagIndex>
            if (args.Count < 2)
            {
                return(false);
            }

            TagInstance tag = null;
            bool        b_duplicate;

            // optional argument: forces overwriting of tags that are not type: coll
            var b_force = (args.Count >= 3 && args[2].ToLower().Equals("force"));

            if (args[1].ToLower().Equals("new"))
            {
                b_duplicate = true;
            }
            else
            {
                tag = ArgumentParser.ParseTagIndex(Info.Cache, args[1]);
                if (tag == null)
                {
                    return(false);
                }
                b_duplicate = false;
            }

            if (!b_force && !b_duplicate && !tag.IsInGroup("coll"))
            {
                Console.WriteLine("Tag to override was not of class- 'coll'. Use third argument- 'force' to inject into this tag.");
                return(false);
            }

            string filepath = args[0];

            string[]       fpaths       = null;
            CollisionModel coll         = null;
            bool           b_singleFile = Path.GetExtension(filepath).Equals(".model_collision_geometry") &&
                                          !Directory.Exists(filepath);

            var modelbuilder = new CollisionGeometryBuilder();
            int n_objects    = 1;

            if (!b_singleFile)
            {
                fpaths = Directory.GetFiles(filepath, "*.model_collision_geometry");

                if (fpaths.Length == 0)
                {
                    Console.WriteLine("No Halo 1 coll tags in directory: \"{0}\"", filepath);
                    return(false);
                }

                filepath  = fpaths[0];
                n_objects = fpaths.Length;
            }

            Console.WriteLine(
                (n_objects == 1 ? "Loading coll tag..." : "Loading coll tags..."), n_objects);

            if (!modelbuilder.ParseFromFile(filepath))
            {
                return(false);
            }

            coll = modelbuilder.Build();

            if (coll == null)
            {
                Console.WriteLine("Builder produced null result.");
                return(false);
            }

            if (!b_singleFile)
            {
                for (int i = 1; i < fpaths.Length; ++i)
                {
                    if (!modelbuilder.ParseFromFile(fpaths[i]))
                    {
                        return(false);
                    }

                    var coll2 = modelbuilder.Build();

                    if (coll2 == null)
                    {
                        Console.WriteLine("Builder produced null result.");
                        return(false);
                    }

                    coll.Regions.Add(coll2.Regions[0]);
                }
            }

            using (var stream = Info.OpenCacheReadWrite())
            {
                if (b_duplicate)
                {
                    //duplicate an existing tag, trashcan phmo
                    tag = Info.Cache.DuplicateTag(stream, Info.Cache.Tags[0x4436]);
                    if (tag == null)
                    {
                        Console.WriteLine("Failed tag duplication.");
                        return(false);
                    }
                }

                var context = new TagSerializationContext(stream, Info.Cache, Info.StringIds, tag);
                Info.Serializer.Serialize(context, coll);
            }
            Console.WriteLine(
                (n_objects == 1 ? "Added 1 collision." : "Added {0} collisions in one tag."), n_objects);
            Console.Write("Successfully imported coll to: ");
            TagPrinter.PrintTagShort(tag);

            return(true);
        }
コード例 #32
0
        /// <summary>Handle the command.</summary>
        /// <param name="monitor">Writes messages to the console and log file.</param>
        /// <param name="command">The command name.</param>
        /// <param name="args">The command arguments.</param>
        public override void Handle(IMonitor monitor, string command, ArgumentParser args)
        {
            // check context
            if (!Context.IsWorldReady)
            {
                monitor.Log("You need to load a save to use this command.", LogLevel.Error);
                return;
            }

            // parse arguments
            if (!args.TryGet(0, "location", out string locationName, required: true))
            {
                return;
            }
            if (!args.TryGet(1, "object type", out string type, required: true, oneOf: this.ValidTypes))
            {
                return;
            }

            // get target location
            GameLocation location = Game1.locations.FirstOrDefault(p => p.Name != null && p.Name.Equals(locationName, StringComparison.InvariantCultureIgnoreCase));

            if (location == null && locationName == "current")
            {
                location = Game1.currentLocation;
            }
            if (location == null)
            {
                string[] locationNames = (from loc in Game1.locations where !string.IsNullOrWhiteSpace(loc.Name) orderby loc.Name select loc.Name).ToArray();
                monitor.Log($"Could not find a location with that name. Must be one of [{string.Join(", ", locationNames)}].", LogLevel.Error);
                return;
            }

            // apply
            switch (type)
            {
            case "debris":
            {
                int removed = 0;
                foreach (var pair in location.terrainFeatures.Pairs.ToArray())
                {
                    TerrainFeature feature = pair.Value;
                    if (feature is HoeDirt dirt && dirt.crop?.dead == true)
                    {
                        dirt.crop = null;
                        removed++;
                    }
                }

                removed +=
                    this.RemoveObjects(location, obj => obj.Name.ToLower().Contains("weed") || obj.Name == "Twig" || obj.Name == "Stone")
                    + this.RemoveResourceClumps(location, clump => this.DebrisClumps.Contains(clump.parentSheetIndex.Value));

                monitor.Log($"Done! Removed {removed} entities from {location.Name}.", LogLevel.Info);
                break;
            }

            case "fruit-trees":
            {
                int removed = this.RemoveTerrainFeatures(location, feature => feature is FruitTree);
                monitor.Log($"Done! Removed {removed} entities from {location.Name}.", LogLevel.Info);
                break;
            }

            case "grass":
            {
                int removed = this.RemoveTerrainFeatures(location, feature => feature is Grass);
                monitor.Log($"Done! Removed {removed} entities from {location.Name}.", LogLevel.Info);
                break;
            }

            case "trees":
            {
                int removed = this.RemoveTerrainFeatures(location, feature => feature is Tree);
                monitor.Log($"Done! Removed {removed} entities from {location.Name}.", LogLevel.Info);
                break;
            }

            case "everything":
            {
                int removed =
                    this.RemoveFurniture(location, p => true)
                    + this.RemoveObjects(location, p => true)
                    + this.RemoveTerrainFeatures(location, p => true)
                    + this.RemoveLargeTerrainFeatures(location, p => true)
                    + this.RemoveResourceClumps(location, p => true);
                monitor.Log($"Done! Removed {removed} entities from {location.Name}.", LogLevel.Info);
                break;
            }

            default:
                monitor.Log($"Unknown type '{type}'. Must be one [{string.Join(", ", this.ValidTypes)}].", LogLevel.Error);
                break;
            }
        }
コード例 #33
0
        static void Main(string[] args)
        {
            O2GSession            session          = null;
            SessionStatusListener statusListener   = null;
            ResponseListener      responseListener = null;

            try
            {
                Console.WriteLine("CreateOrderBySymbol sample\n");

                ArgumentParser argParser = new ArgumentParser(args, "CreateOrderBySymbol");

                argParser.AddArguments(ParserArgument.Login,
                                       ParserArgument.Password,
                                       ParserArgument.Url,
                                       ParserArgument.Connection,
                                       ParserArgument.SessionID,
                                       ParserArgument.Pin,
                                       ParserArgument.Instrument,
                                       ParserArgument.BuySell,
                                       ParserArgument.Rate,
                                       ParserArgument.Lots,
                                       ParserArgument.AccountID);

                argParser.ParseArguments();

                if (!argParser.AreArgumentsValid)
                {
                    argParser.PrintUsage();
                    return;
                }

                argParser.PrintArguments();

                LoginParams  loginParams  = argParser.LoginParams;
                SampleParams sampleParams = argParser.SampleParams;

                session        = O2GTransport.createSession();
                statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin);
                session.subscribeSessionStatus(statusListener);
                statusListener.Reset();
                session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection);
                if (statusListener.WaitEvents() && statusListener.Connected)
                {
                    responseListener = new ResponseListener(session);
                    session.subscribeResponse(responseListener);

                    O2GAccountRow account = GetAccount(session, sampleParams.AccountID);
                    if (account == null)
                    {
                        if (string.IsNullOrEmpty(sampleParams.AccountID))
                        {
                            throw new Exception("No valid accounts");
                        }
                        else
                        {
                            throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID));
                        }
                    }
                    sampleParams.AccountID = account.AccountID;

                    O2GOfferRow offer = GetOffer(session, sampleParams.Instrument);
                    if (offer == null)
                    {
                        throw new Exception(string.Format("The instrument '{0}' is not valid", sampleParams.Instrument));
                    }

                    O2GLoginRules loginRules = session.getLoginRules();
                    if (loginRules == null)
                    {
                        throw new Exception("Cannot get login rules");
                    }
                    O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider();
                    int iBaseUnitSize       = tradingSettingsProvider.getBaseUnitSize(sampleParams.Instrument, account);
                    int iAmount             = iBaseUnitSize * sampleParams.Lots;
                    int iCondDistEntryLimit = tradingSettingsProvider.getCondDistEntryLimit(sampleParams.Instrument);
                    int iCondDistEntryStop  = tradingSettingsProvider.getCondDistEntryStop(sampleParams.Instrument);

                    string sOrderType = GetEntryOrderType(offer.Bid, offer.Ask, sampleParams.Rate, sampleParams.BuySell, offer.PointSize, iCondDistEntryLimit, iCondDistEntryStop);

                    O2GRequest request = CreateEntryOrderRequest(session, offer.Instrument, sampleParams.AccountID, iAmount, sampleParams.Rate, sampleParams.BuySell, sOrderType);
                    if (request == null)
                    {
                        throw new Exception("Cannot create request");
                    }
                    responseListener.SetRequestID(request.RequestID);
                    session.sendRequest(request);
                    if (responseListener.WaitEvents())
                    {
                        Console.WriteLine("Done!");
                    }
                    else
                    {
                        throw new Exception("Response waiting timeout expired");
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e.ToString());
            }
            finally
            {
                if (session != null)
                {
                    if (statusListener.Connected)
                    {
                        statusListener.Reset();
                        session.logout();
                        statusListener.WaitEvents();
                        if (responseListener != null)
                        {
                            session.unsubscribeResponse(responseListener);
                        }
                    }
                    session.unsubscribeSessionStatus(statusListener);
                    session.Dispose();
                }
            }
        }
コード例 #34
0
        public void Overrideconfig_with_several_options(string options)
        {
            var exception = Assert.Throws <WarningException>(() => ArgumentParser.ParseArguments($"/overrideconfig {options}"));

            exception.Message.ShouldContain("Can't specify multiple /overrideconfig options");
        }
コード例 #35
0
ファイル: ArgumentParserTests.cs プロジェクト: eugene-g/Paket
 private static BootstrapperOptions ParseMagic(IEnumerable <string> arguments, NameValueCollection appSettings, IDictionary envVariables, IEnumerable <string> argumentsInDependenciesFile = null)
 {
     return(ArgumentParser.ParseArgumentsAndConfigurations(arguments, appSettings, envVariables, MagicModeFileSystemSystem, argumentsInDependenciesFile ?? Enumerable.Empty <string>()));
 }
コード例 #36
0
        public void Overrideconfig_with_invalid_option(string options)
        {
            var exception = Assert.Throws <WarningException>(() => ArgumentParser.ParseArguments($"/overrideconfig {options}"));

            exception.Message.ShouldContain("Could not parse /overrideconfig option");
        }
コード例 #37
0
ファイル: ScriptFileHelperTest.cs プロジェクト: GeertVL/dbgen
 public void GetScriptPath_PathSpecified()
 {
     ArgumentParser arguments = new ArgumentParser(null);
     arguments.Parameters.Add("path", @"c:\temp");
     string expected = @"c:\temp";
     string actual;
     actual = ScriptFileHelper.GetScriptPath(arguments);
     Assert.AreEqual(expected, actual);
 }
コード例 #38
0
        public void Ensure_assembly_info_false()
        {
            var arguments = ArgumentParser.ParseArguments("-ensureAssemblyInfo false");

            arguments.EnsureAssemblyInfo.ShouldBe(false);
        }
コード例 #39
0
        public override bool Execute(List <string> args)
        {
            if (args.Count < 1 || args.Count > 2)
            {
                return(false);
            }

            TagInstance destination = Info.Cache.Tags[0x3317];

            if (args.Count == 2)
            {
                destination = ArgumentParser.ParseTagIndex(Info, args[0]);

                if (!destination.IsInGroup("mode"))
                {
                    Console.WriteLine("Specified tag is not a render_model: " + args[0]);
                    return(false);
                }

                args = args.Skip(1).ToList();
            }

            var builder = new RenderModelBuilder(Info.Version);

            // Add a root node
            var node = builder.AddNode(new RenderModel.Node
            {
                Name            = Info.StringIDs.GetStringID("street_cone"),
                ParentNode      = -1,
                FirstChildNode  = -1,
                NextSiblingNode = -1,
                DefaultRotation = new Vector4(0, 0, 0, -1),
                DefaultScale    = 1,
                InverseForward  = new Vector3(1, 0, 0),
                InverseLeft     = new Vector3(0, 1, 0),
                InverseUp       = new Vector3(0, 0, 1),
            });

            // Begin building the default region and permutation
            builder.BeginRegion(Info.StringIDs.GetStringID("default"));
            builder.BeginPermutation(Info.StringIDs.GetStringID("default"));

            using (var importer = new AssimpContext())
            {
                Scene model;
                using (var logStream = new LogStream((msg, userData) => Console.WriteLine(msg)))
                {
                    logStream.Attach();
                    model = importer.ImportFile(args[0],
                                                PostProcessSteps.CalculateTangentSpace |
                                                PostProcessSteps.GenerateNormals |
                                                PostProcessSteps.JoinIdenticalVertices |
                                                PostProcessSteps.SortByPrimitiveType |
                                                PostProcessSteps.PreTransformVertices |
                                                PostProcessSteps.Triangulate);
                    logStream.Detach();
                }

                Console.WriteLine("Assembling vertices...");

                // Build a multipart mesh from the model data,
                // with each model mesh mapping to a part of one large mesh and having its own material
                builder.BeginMesh();
                ushort partStartVertex = 0;
                ushort partStartIndex  = 0;
                var    vertices        = new List <RigidVertex>();
                var    indices         = new List <ushort>();
                foreach (var mesh in model.Meshes)
                {
                    for (var i = 0; i < mesh.VertexCount; i++)
                    {
                        var position  = mesh.Vertices[i];
                        var normal    = mesh.Normals[i];
                        var uv        = mesh.TextureCoordinateChannels[0][i];
                        var tangent   = mesh.Tangents[i];
                        var bitangent = mesh.BiTangents[i];
                        vertices.Add(new RigidVertex
                        {
                            Position = new Vector4(position.X, position.Y, position.Z, 1),
                            Normal   = new Vector3(normal.X, normal.Y, normal.Z),
                            Texcoord = new Vector2(uv.X, uv.Y),
                            Tangent  = new Vector4(tangent.X, tangent.Y, tangent.Z, 1),
                            Binormal = new Vector3(bitangent.X, bitangent.Y, bitangent.Z),
                        });
                    }

                    // Build the index buffer
                    var meshIndices = mesh.GetIndices();
                    indices.AddRange(meshIndices.Select(i => (ushort)(i + partStartVertex)));

                    // Define a material and part for this mesh
                    var material = builder.AddMaterial(new RenderMaterial
                    {
                        RenderMethod = Info.Cache.Tags[0x101F],
                    });


                    builder.BeginPart(material, partStartIndex, (ushort)meshIndices.Length, (ushort)mesh.VertexCount);
                    builder.DefineSubPart(partStartIndex, (ushort)meshIndices.Length, (ushort)mesh.VertexCount);
                    builder.EndPart();

                    // Move to the next part
                    partStartVertex += (ushort)mesh.VertexCount;
                    partStartIndex  += (ushort)meshIndices.Length;
                }

                // Bind the vertex and index buffers
                builder.BindRigidVertexBuffer(vertices, node);
                builder.BindIndexBuffer(indices, PrimitiveType.TriangleList);
                builder.EndMesh();
            }

            builder.EndPermutation();
            builder.EndRegion();

            Console.WriteLine("Building Blam mesh data...");

            var resourceStream = new MemoryStream();
            var renderModel    = builder.Build(Info.Serializer, resourceStream);

            Console.WriteLine("Writing resource data...");

            // Add a new resource for the model data
            var resources = new ResourceDataManager();

            resources.LoadCachesFromDirectory(Info.CacheFile.DirectoryName);
            resourceStream.Position = 0;
            resources.Add(renderModel.Geometry.Resource, ResourceLocation.Resources, resourceStream);

            Console.WriteLine("Writing tag data...");

            using (var cacheStream = Info.OpenCacheReadWrite())
            {
                var tag     = destination;
                var context = new TagSerializationContext(cacheStream, Info.Cache, Info.StringIDs, tag);
                Info.Serializer.Serialize(context, renderModel);
            }

            Console.WriteLine("Model imported successfully!");

            return(true);
        }
コード例 #40
0
 private void SetWorldVelocity(ArgumentParser parser)
 {
     physicsBinding.SetWorldVelocity(parser);
 }
コード例 #41
0
        public void TestThrowsOnExtraKeys()
        {
            var args = new[] { "ls", "-r" };

            Assert.Throws <BadArgumentException>(() => ArgumentParser.ParseLs(args));
        }
コード例 #42
0
        public void TestThrowsOnMutuallyExclusiveKeys()
        {
            var args = new[] { "ls", "-l", "-a" };

            Assert.Throws <BadArgumentException>(() => ArgumentParser.ParseLs(args));
        }
コード例 #43
0
        static void Main(string[] args)
        {
            /*
             *  simple usage
             */

            // set up argument parser
            ArgumentParser<ExecuteCommandBase> argParser = new ArgumentParser<ExecuteCommandBase>(typeof(ExecuteCommandUsingName), typeof(ExecuteCommandUsingPath));
            ExecuteCommandBase paramSet;
            if (argParser.TryParse(args, out paramSet))
            {
                paramSet.Execute();
            }

            Console.ReadLine();

            /*
            *  advanced usage
            */

            // create parameter set collection from types
            ParameterSetCollection sets = ParameterSetCollection.FromTypes(typeof(ExecuteCommandUsingName), typeof(ExecuteCommandUsingPath));

            // parse the command line arguments
            Parser parser = new Parser();
            NodeSequence nodes = parser.Parse(string.Join(" ", args));

            // resolve parameter set against the parsed node set
            ResolveResult result = sets.Resolve(new ParameterSetBinder(),
                                                DefaultActivator.Instance,
                                                new IntransigentTypeConverter(),
                                                CultureInfo.InvariantCulture,
                                                nodes);
            if (result.IsMatch)
            {
                paramSet = (ExecuteCommandBase)result.BestMatch.Object;
                paramSet.Execute();
            }
            else
            {
                ErrorWriter errorWriter = new ErrorWriter();
                errorWriter.Write(new ConsoleWriter(Console.Error), result);

                HelpWriter helpWriter = new HelpWriter();
                helpWriter.Write(new ConsoleWriter(Console.Out), sets, HelpLevel.Parameters);
            }
        }
コード例 #44
0
        public void Output_buildserver_can_be_parsed()
        {
            var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -output buildserver");

            arguments.Output.ShouldBe(OutputType.BuildServer);
        }
コード例 #45
0
        public void ParseArgumentPair_ParsesPair(string arg, List <Match> argumentStarts, int i, List <string> expectedResult)
        {
            var parsedArgs = ArgumentParser.ParseArgumentPair(arg, argumentStarts, i);

            Assert.Equal(expectedResult, parsedArgs);
        }
コード例 #46
0
        //private static bool checkFile(string path)
        //{
        //    return File.Exists(path);
        //}

        public static void Main(string[] args)
        {
            if (IsSingleInstance())
            {
                StringArgument silentArg  = new StringArgument("quiet", "Hide application window", "Run application in background");
                StringArgument logFileArg = new StringArgument("log", "Log File", "Path to log file");
                StringArgument verbArg    = new StringArgument("verbose", "Verbose level", "3 - Debug\r\n2 - Normal\r\n1 - Error");
                ArgumentParser argParser  = new ArgumentParser("Vinisandbox", "Analyze static and dynamically file");
                argParser.Add("\\", "\\quiet", silentArg);
                argParser.Add("\\", "\\log", logFileArg);
                argParser.Add("\\", "\\v", verbArg);

                LogManager.VerboseLevel = LogManager.EVerboseLevel.Normal;

                try
                {
                    argParser.Parse(args);

                    if (silentArg.Defined)
                    {
                        HideWindow();
                    }
                    if (logFileArg.Defined)
                    {
                        LogManager.LogPath = (string)logFileArg.ObjectValue;
                        try
                        {
                            File.Create(LogManager.LogPath);
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("Invalid Log File");
                            argParser.WriteShortArgumentsUsage();
                            Console.Read();
                            return;
                        }
                    }
                    if (verbArg.Defined)
                    {
                        try
                        {
                            LogManager.VerboseLevel = (LogManager.EVerboseLevel)Enum.ToObject(typeof(LogManager.EVerboseLevel), (string)verbArg.ObjectValue);
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("Invalid Verbose level");
                            argParser.WriteShortArgumentsUsage();
                            Console.Read();
                            return;
                        }
                    }
                }
                catch (Exception)
                {
                }

                vinisandboxContext cx = new vinisandboxContext();
                cx.Configuration.ProxyCreationEnabled = true;
                cx.Configuration.LazyLoadingEnabled   = true;


                Configuration config  = LoadConfiguration();
                Sandbox       sandbox = new Sandbox(config);

                DirectoryInfo di = new DirectoryInfo(config.TempFolder);
                di.Create();

                /*string pat = @"C:\Users\Vinicius\Downloads\sed-4.2.1-setup.exe";
                 * file_detail fd = new file_detail();
                 * fd.data = File.ReadAllBytes(pat);
                 * fd.files = new List<file>();
                 * fd.files.Add(new file() { name = "sed-4.2.1-setup.exe" });
                 * cx.file_detail.Add(fd);
                 * cx.SaveChanges();*/
                while (true)
                {
                    foreach (var file_det in cx.file_detail.Where(p => p.files.Count(j => j.analyzed == false) > 0).Include("files").ToList())
                    {
                        sandbox.Analyze(file_det);
                        foreach (var file in file_det.files)
                        {
                            file.analyzed = true;
                        }
                        try
                        {
                            cx.SaveChanges();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.ToString());
                        }
                    }
                    Thread.Sleep(10000);
                }
            }
            else
            {
                Console.WriteLine("Ja existe outra instancia do programa rodando.");
            }
            //if (args.Length != 1)
            //{
            //    //Erro
            //    Console.WriteLine("Parametros errados.");
            //    return;
            //}
            //if (!checkFile(args[0]))
            //{
            //    Console.WriteLine(args[0] + " não foi encontrado.");
            //    return;
            //}
            //if (IsSingleInstance())
            //{
            //    StartServer();
            //    Sandbox s = new Sandbox(LoadConfiguration());
            //    listMutex.WaitOne();
            //    files.Add(args[0]);
            //    while (files.Count != 0)
            //    {
            //        listMutex.ReleaseMutex();
            //        s.Analyze(files[0]);
            //        files.RemoveAt(0);
            //        //faz analise
            //        listMutex.WaitOne();
            //    }
            //    ServerRunning = false;
            //    programMutex.Close();
            //}
            //else
            //{
            //    SendPath(args[0]);
            //}
        }
コード例 #47
0
        public void MultipleArgsAndFlag()
        {
            var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -output buildserver -updateAssemblyInfo");

            arguments.Output.ShouldBe(OutputType.BuildServer);
        }
コード例 #48
0
        public void Wrong_number_of_arguments_should_throw()
        {
            var exception = Assert.Throws <WarningException>(() => ArgumentParser.ParseArguments("targetDirectoryPath -l logFilePath extraArg"));

            exception.Message.ShouldBe("Could not parse command line parameter 'extraArg'.");
        }
コード例 #49
0
        public void Unknown_arguments_should_throw(string arguments)
        {
            var exception = Assert.Throws <WarningException>(() => ArgumentParser.ParseArguments(arguments));

            exception.Message.ShouldStartWith("Could not parse command line parameter");
        }
コード例 #50
0
        public ParsedArguments ParseArgumentsAndMerge(string actionName, Dictionary<string, string> arg, ParsedArguments parsedArguments)
        {
            var methodInfo = _controller.GetMethod(actionName);
            var argumentRecognizers = methodInfo.GetArguments()
                .ToList();

            var parser = new ArgumentParser(argumentRecognizers, _allowInferParameter, Culture);
            var parsedMethodArguments = parser.Parse(arg);
            var parsedMethod = Parse(methodInfo, parsedMethodArguments);
            var merged = parsedArguments.Merge(parsedMethod);
            if (!_controller.IgnoreGlobalUnMatchedParameters)
                merged.AssertFailOnUnMatched();
            return merged;
        }
コード例 #51
0
        public void Update_assembly_info_false(string command)
        {
            var arguments = ArgumentParser.ParseArguments(command);

            arguments.UpdateAssemblyInfo.ShouldBe(false);
        }
コード例 #52
0
        public void Unknown_output_should_throw()
        {
            var exception = Assert.Throws <WarningException>(() => ArgumentParser.ParseArguments("targetDirectoryPath -output invalid_value"));

            exception.Message.ShouldBe("Value 'invalid_value' cannot be parsed as output type, please use 'json' or 'buildserver'");
        }
コード例 #53
0
        public void ParseArgumentValues_ParsesValues(string rawValue, List <string> expectedResult)
        {
            var result = ArgumentParser.ParseArgumentValues(rawValue);

            Assert.Equal(expectedResult, result);
        }
コード例 #54
0
 public void BeforeEach()
 {
     _parser = new ArgumentParser();
 }
コード例 #55
0
        public void Output_defaults_to_json()
        {
            var arguments = ArgumentParser.ParseArguments("targetDirectoryPath");

            arguments.Output.ShouldBe(OutputType.Json);
        }
コード例 #56
0
        public void Output_json_can_be_parsed()
        {
            var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -output json");

            arguments.Output.ShouldBe(OutputType.Json);
        }
コード例 #57
0
ファイル: Program.cs プロジェクト: nagyist/QuandlCS
 /// <summary>
 /// Setup the objects that will be used by the main program at startup
 /// </summary>
 /// <param name="args"></param>
 private static void Setup(string[] args)
 {
   arguments = new Arguments();
   argumentParser = new ArgumentParser<Arguments>(arguments, args);
 }