public void CommandLineArgumentsConstructor_NullParameter_EmptyDictionary() { IEnumerable<string> args = null; CommandLineArguments target = new CommandLineArguments(args); Assert.AreEqual(0, target.Count); }
public void CommandLineArgumentsConstructor_AllValuesWithNoArgumentName_ValuesIncludedInOneKey() { IEnumerable<string> args = @"0 1 2 3".Split(' '); CommandLineArguments target = new CommandLineArguments(args); Assert.AreEqual(1, target.Count); }
public void Empty() { CommandLineArguments args = new CommandLineArguments(); string[] cmdLine = new string[] { //@"/path:c:\windows" }; if (!CommandLineParser.ParseArgumentsWithUsage(cmdLine, args)) { Assert.Fail(); } Assert.AreEqual(false, args.AddHost); Assert.AreEqual(null, args.ApplicationPath); Assert.AreEqual(null, args.HostName); Assert.AreEqual(null, args.IPAddress); Assert.AreEqual(IPMode.Loopback, args.IPMode); Assert.AreEqual(false, args.IPv6); Assert.AreEqual(false, args.Nodirlist); Assert.AreEqual(false, args.Ntlm); Assert.AreEqual(0, args.Port); Assert.AreEqual(PortMode.FirstAvailable, args.PortMode); Assert.AreEqual(65535, args.PortRangeEnd); Assert.AreEqual(32768, args.PortRangeStart); Assert.AreEqual(RunMode.Server, args.RunMode); Assert.AreEqual(false, args.Silent); Assert.AreEqual(0, args.TimeOut); Assert.AreEqual("/", args.VirtualPath); Assert.AreEqual(0, args.WaitForPort); Assert.AreEqual("/v:\"/\"", args.ToString()); }
private static CommandLineArguments ProcessArguments(string[] arguments) { var commandLineArguments = new CommandLineArguments(); int current = 0; for (; current < arguments.Length; current++) { string argument = arguments[current]; if (argument.Length > 0 && (argument[0] == '/' || argument[0] == '-')) { string argumentFlag = argument.Substring(1); if (argumentFlag == "debug") { commandLineArguments.Debug = true; } else if (argumentFlag == "profile") { commandLineArguments.Profile = true; } else { break; } } else { break; } } commandLineArguments.ArgumentsStart = current; return commandLineArguments; }
private static void Main(string[] args) { CommandLineArguments commandLineArgs = new CommandLineArguments(args); string hostFormatString = "http://{0}:{1}"; string owinAddress = String.Format(hostFormatString, commandLineArgs.AllowRemote ? "+" : "localhost", commandLineArgs.Port); string visibleHost = (commandLineArgs.AllowRemote) ? Environment.MachineName : "localhost"; string visibleAddress = String.Format(hostFormatString, visibleHost, commandLineArgs.Port); PortManager.OpenPortInFirewall(commandLineArgs.Port); OwinSelfhostStartup.Startup(owinAddress); Console.WriteLine("The Bridge is listening at {0} with remote access {1}", visibleAddress, commandLineArgs.AllowRemote ? "enabled" : "disabled"); Test(visibleHost, commandLineArgs.Port); while (true) { Console.WriteLine("Type \"exit\" to stop the Bridge."); string answer = Console.ReadLine(); if (String.Equals(answer, "exit", StringComparison.OrdinalIgnoreCase)) { break; } } Environment.Exit(0); }
private static void Main(string[] args) { CommandLineArguments commandLineArgs = new CommandLineArguments(args); string hostFormatString = "http://{0}:{1}"; string owinAddress = String.Format(hostFormatString, commandLineArgs.AllowRemote ? "+" : "localhost", commandLineArgs.Port); string visibleHost = (commandLineArgs.AllowRemote) ? Environment.MachineName : "localhost"; string visibleAddress = String.Format(hostFormatString, visibleHost, commandLineArgs.Port); // Configure the remote addresses the firewall rules will accept. // If remote access is not allowed, specifically disallow remote addresses PortManager.RemoteAddresses = commandLineArgs.AllowRemote ? commandLineArgs.RemoteAddresses : String.Empty; // Initialize the BridgeConfiguration from command line. // The first POST to the ConfigController will supply the rest. ConfigController.BridgeConfiguration.BridgeHost = visibleHost; ConfigController.BridgeConfiguration.BridgePort = commandLineArgs.Port; // Remove any pre-existing firewall rules the Bridge may have added // in past runs. We normally cleanup on exit but could have been // aborted. PortManager.RemoveAllBridgeFirewallRules(); // Open the port used to communicate with the Bridge itself PortManager.OpenPortInFirewall(commandLineArgs.Port); Console.WriteLine("Starting the Bridge at {0}", visibleAddress); OwinSelfhostStartup.Startup(owinAddress); Test(visibleHost, commandLineArgs.Port); while (true) { Console.WriteLine("The Bridge is listening at {0}", visibleAddress); if (commandLineArgs.AllowRemote) { Console.WriteLine("Remote access is allowed from '{0}'", commandLineArgs.RemoteAddresses); } else { Console.WriteLine("Remote access is disabled."); } Console.WriteLine("Current configuration is:{0}{1}", Environment.NewLine, ConfigController.BridgeConfiguration.ToString()); Console.WriteLine("Type \"exit\" to stop the Bridge."); string answer = Console.ReadLine(); if (String.Equals(answer, "exit", StringComparison.OrdinalIgnoreCase)) { break; } } Environment.Exit(0); }
/// <summary> /// Parses the command line arguments for valid options and returns them. /// </summary> /// <param name="CommandLineArgs">Array of strings containing the command line arguments</param> /// <returns>CommandLineArguments structure holding the options from the command line</returns> /// <history> /// [Curtis_Beard] 07/26/2006 Created /// [Curtis_Beard] 05/08/2007 ADD: 1590157, support project file /// </history> public static CommandLineArguments Process(string[] CommandLineArgs) { // create the args structure and initialize it CommandLineArguments args = new CommandLineArguments(); InitializeArgs(ref args); // process the command line Arguments myArgs = new Arguments(CommandLineArgs); // check for just a single directory / project file if (CommandLineArgs.Length == 2) { args.AnyArguments = true; // Check command line for a path to start at string arg1 = CommandLineArgs[1]; // remove an extra quote if (a drive letter if (arg1.EndsWith("\"")) arg1 = arg1.Substring(0, arg1.Length - 1); // check for a project file if (arg1.EndsWith(".agproj")) { args.ProjectFile = arg1; args.IsProjectFile = true; } // check for a directory if (!args.IsProjectFile && System.IO.Directory.Exists(arg1)) { args.StartPath = arg1; args.IsValidStartPath = true; } // do this before setting defaults to prevent loading wrong config file. if (!args.IsValidStartPath && !args.IsProjectFile) { // check for some other single setting, such as /local ProcessFlags(myArgs, ref args); } } else if (CommandLineArgs.Length > 1) { args.AnyArguments = true; ProcessFlags(myArgs, ref args); } return args; }
public App() { // Add Ctrl+Shift+Z as a redo command. Don't know why it isn't enabled by default. ApplicationCommands.Redo.InputGestures.Add(new KeyGesture(Key.Z, ModifierKeys.Control | ModifierKeys.Shift)); var cmdArgs = Environment.GetCommandLineArgs().Skip(1); App.CommandLineArguments = new CommandLineArguments(cmdArgs); if (App.CommandLineArguments.SingleInstance ?? true) { cmdArgs = cmdArgs.Select(FullyQualifyPath); string message = string.Join(Environment.NewLine, cmdArgs); if (SendToPreviousInstance("dnSpy:\r\n" + message, !App.CommandLineArguments.NoActivate)) { Environment.Exit(0); } } InitializeComponent(); var catalog = new AggregateCatalog(); catalog.Catalogs.Add(new AssemblyCatalog(typeof(App).Assembly)); // Don't use DirectoryCatalog, that causes problems if the plugins are from the Internet zone // see http://stackoverflow.com/questions/8063841/mef-loading-plugins-from-a-network-shared-folder string appPath = Path.GetDirectoryName(typeof(App).Module.FullyQualifiedName); foreach (string plugin in Directory.GetFiles(appPath, "*.Plugin.dll")) { string shortName = Path.GetFileNameWithoutExtension(plugin); try { var asm = Assembly.Load(shortName); asm.GetTypes(); catalog.Catalogs.Add(new AssemblyCatalog(asm)); } catch (Exception ex) { // Cannot show MessageBox here, because WPF would crash with a XamlParseException // Remember and show exceptions in text output, once MainWindow is properly initialized StartupExceptions.Add(new ExceptionData { Exception = ex, PluginName = shortName }); } } compositionContainer = new CompositionContainer(catalog); Languages.Initialize(compositionContainer); if (!System.Diagnostics.Debugger.IsAttached) { AppDomain.CurrentDomain.UnhandledException += ShowErrorBox; Dispatcher.CurrentDispatcher.UnhandledException += Dispatcher_UnhandledException; } TaskScheduler.UnobservedTaskException += DotNet40_UnobservedTaskException; EventManager.RegisterClassHandler(typeof(Window), Hyperlink.RequestNavigateEvent, new RequestNavigateEventHandler(Window_RequestNavigate)); FixEditorContextMenuStyle(); }
private static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(BridgeUnhandledExceptionHandler); CommandLineArguments commandLineArgs = new CommandLineArguments(args); Console.WriteLine("Bridge.exe was launched with:{0}{1}", Environment.NewLine, commandLineArgs.ToString()); // If asked to ping (not the default), just ping and return an exit code indicating its state if (commandLineArgs.Ping) { string errorMessage = null; if (PingBridge(commandLineArgs.BridgeConfiguration.BridgeHost, commandLineArgs.BridgeConfiguration.BridgePort, out errorMessage)) { Console.WriteLine("The Bridge is running."); Environment.Exit(0); } else { Console.WriteLine("The Bridge is not running: {0}", errorMessage); Environment.Exit(1); } } if (commandLineArgs.StopIfLocal) { StopBridgeIfLocal(commandLineArgs); Environment.Exit(0); } if (commandLineArgs.Stop) { StopBridge(commandLineArgs); Environment.Exit(0); } if (commandLineArgs.Reset) { ResetBridge(commandLineArgs); Environment.Exit(0); } if (commandLineArgs.RequireBridgeTimeoutSeconds.HasValue) { RequireBridge(commandLineArgs); } // Default action is starting the Bridge StartBridge(commandLineArgs); }
public void QuotedValuesInToString() { CommandLineArguments args = new CommandLineArguments(); string[] cmdLine = new string[] { @"/port:32768", @"/path:c:\temp foo", @"/vpath:/myapp with spaces", @"/ntlm", @"/silent", @"/nodirlist" }; if (!CommandLineParser.ParseArgumentsWithUsage(cmdLine, args)) { Assert.Fail(); } Assert.AreEqual(false, args.AddHost); Assert.AreEqual(@"c:\temp foo", args.ApplicationPath); Assert.AreEqual(null, args.HostName); Assert.AreEqual(null, args.IPAddress); Assert.AreEqual(IPMode.Loopback, args.IPMode); Assert.AreEqual(false, args.IPv6); Assert.AreEqual(true, args.Nodirlist); Assert.AreEqual(true, args.Ntlm); Assert.AreEqual(32768, args.Port); Assert.AreEqual(PortMode.FirstAvailable, args.PortMode); Assert.AreEqual(65535, args.PortRangeEnd); Assert.AreEqual(32768, args.PortRangeStart); Assert.AreEqual(RunMode.Server, args.RunMode); Assert.AreEqual(true, args.Silent); Assert.AreEqual(0, args.TimeOut); Assert.AreEqual("/myapp with spaces", args.VirtualPath); Assert.AreEqual(0, args.WaitForPort); Assert.AreEqual("/a:\"c:\\temp foo\" /v:\"/myapp with spaces\" /p:32768 /ntlm /silent /nodirlist", args.ToString()); }
private static void Main(string[] args) { CommandLineArguments commandLineArgs = new CommandLineArguments(args); Console.WriteLine("Specified BridgeConfiguration is:{0}{1}", Environment.NewLine, commandLineArgs.BridgeConfiguration.ToString()); // If asked to ping (not the default), just ping and return an exit code indicating its state if (commandLineArgs.Ping) { string errorMessage = null; if (PingBridge(commandLineArgs.BridgeConfiguration.BridgeHost, commandLineArgs.BridgeConfiguration.BridgePort, out errorMessage)) { Console.WriteLine("The Bridge is running."); Environment.Exit(0); } else { Console.WriteLine("The Bridge is not running: {0}", errorMessage); Environment.Exit(1); } } else if (commandLineArgs.StopIfLocal) { StopBridgeIfLocal(commandLineArgs); } else if (commandLineArgs.Stop) { StopBridge(commandLineArgs); } else { // Default action is starting the Bridge StartBridge(commandLineArgs); } }
public bool Start(CommandLineArguments arguments = null) { var filename = Settings.Default.UseCustomPuttyPath ? Settings.Default.CustomPuttyPath : App.Info.GeneralAppInfo.PuttyPath; return Start(filename, arguments); }
/// <summary> /// Parses the command line arguments and initializes the object. /// </summary> /// <param name="args"> /// Command line arguments. /// </param> /// <returns> /// Parsed command line arguments. /// </returns> private static CommandLineArguments Initialize(string[] args) { const string ErrorMessage = "Incorrect arguments..\nUsage: DelineationSample /Input=<Input file> " + "/ColorMap=<Color Map File> /ColorMapOrientation <Horizontal or Vertical> " + "/ShapeFilePath=<Shape file path> /RegionHvMapPath=<Region map path> /ShapeKey=<string key used to access shape file> " + "/MaxLevel=<Number of levels of tiles to be built.> [/OutputDir=<Output Directory>]"; if (args == null || args.Length < 6) { Trace.TraceError("{0}: " + ErrorMessage, DateTime.Now.TimeOfDay.ToString(@"hh\:mm\:ss")); return null; } CommandLineArguments cmdLine = new CommandLineArguments(); CommandLineParser.ParseArguments(cmdLine, args); if (string.IsNullOrWhiteSpace(cmdLine.Input) || string.IsNullOrWhiteSpace(cmdLine.ColorMap)) { Trace.TraceError("{0}: " + ErrorMessage, DateTime.Now.TimeOfDay.ToString(@"hh\:mm\:ss")); return null; } if (string.IsNullOrWhiteSpace(cmdLine.OutputDir)) { string outputFolderName = string.Format("{0}_{1}", Path.GetFileNameWithoutExtension(cmdLine.Input), DateTime.Now.ToString("yyyyddMM-HHmmss")); cmdLine.OutputDir = Path.Combine(TileHelper.GetDefaultOutputDirectory(), outputFolderName); Trace.TraceInformation("{0}: Output directory {1}", DateTime.Now.TimeOfDay.ToString(@"hh\:mm\:ss"), cmdLine.OutputDir); } if (!Path.IsPathRooted(cmdLine.Input)) { cmdLine.Input = Path.GetFullPath(cmdLine.Input); } if (!Path.IsPathRooted(cmdLine.OutputDir)) { cmdLine.OutputDir = Path.GetFullPath(cmdLine.OutputDir); } if (!Path.IsPathRooted(cmdLine.ColorMap)) { cmdLine.ColorMap = Path.GetFullPath(cmdLine.ColorMap); } if (!string.IsNullOrEmpty(cmdLine.ColorMapOrientation)) { ColorMapOrientation orientation; if (!Enum.TryParse(cmdLine.ColorMapOrientation, true, out orientation)) { Trace.TraceError("{0}: " + ErrorMessage, DateTime.Now.TimeOfDay.ToString(@"hh\:mm\:ss")); return null; } } return cmdLine; }
public DataFlowBuilder(CommandLineArguments arguments, int consumerThreadsCount) { _arguments = arguments; _consumerThreadsCount = consumerThreadsCount; }
/// <summary> /// Parses the command line arguments and initializes the object. /// </summary> /// <param name="args"> /// Command line arguments. /// </param> /// <returns> /// Parsed command line arguments. /// </returns> private static CommandLineArguments Initialize(string[] args) { const string ErrorMessage = "Incorrect arguments...\nUsage: WorldDataSet " + "/Input=<Input file name> " + "/Projection=<Projection Type - Mercator or Toast> " + "/ColorMap=<Color Map File> /ColorMapOrientation=<Horizontal or Vertical>" + "[/OutputDir=<Output Directory>] "; if (args == null || args.Length < 4) { Trace.TraceError("{0}: " + ErrorMessage, DateTime.Now.TimeOfDay.ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture)); return null; } CommandLineArguments cmdLine = new CommandLineArguments(args); if (string.IsNullOrEmpty(cmdLine.Input)) { Trace.TraceError("{0}: " + ErrorMessage, DateTime.Now.TimeOfDay.ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture)); return null; } if (!string.IsNullOrEmpty(cmdLine.Projection)) { ProjectionTypes tmp; if (!Enum.TryParse(cmdLine.Projection, true, out tmp)) { Trace.TraceError("{0}: " + ErrorMessage, DateTime.Now.TimeOfDay.ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture)); return null; } } else { Trace.TraceError("{0}: " + ErrorMessage, DateTime.Now.TimeOfDay.ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture)); return null; } if (string.IsNullOrWhiteSpace(cmdLine.OutputDir)) { string outputFolderName = string.Format(CultureInfo.InvariantCulture, "{0}_{1}_{2}", Path.GetFileNameWithoutExtension(cmdLine.Input), cmdLine.Projection, DateTime.Now.ToString("yyyyddMM-HHmmss", CultureInfo.InvariantCulture)); cmdLine.OutputDir = Path.Combine(TileHelper.DefaultOutputDirectory, outputFolderName); Trace.TraceInformation("{0}: Output directory {1}", DateTime.Now.TimeOfDay.ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture), cmdLine.OutputDir); } if (!Path.IsPathRooted(cmdLine.Input)) { cmdLine.Input = Path.GetFullPath(cmdLine.Input); } if (!Path.IsPathRooted(cmdLine.OutputDir)) { cmdLine.OutputDir = Path.GetFullPath(cmdLine.OutputDir); } if (!string.IsNullOrEmpty(cmdLine.ColorMapOrientation)) { ColorMapOrientation tmp; if (!Enum.TryParse(cmdLine.ColorMapOrientation, true, out tmp)) { Trace.TraceError("{0}: " + ErrorMessage, DateTime.Now.TimeOfDay.ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture)); return null; } } return cmdLine; }
private void ButtonStart_Click(object sender, EventArgs e) { DisableForm(); CommandLineArguments args = new CommandLineArguments { AddHost = AddHost, ApplicationPath = ApplicationPath, HostName = HostName, IPAddress = IPAddress, IPMode = IPMode, IPv6 = IPv6, Port = Port, PortMode = PortMode, PortRangeEnd = PortRangeEnd, PortRangeStart = PortRangeStart, VirtualPath = VirtualPath, TimeOut = TimeOut, WaitForPort = WaitForPort }; Presenter.Start(args); }
public override void Configure(CommandLineArguments Arguments) { base.Configure(Arguments); // Get the command line if (!TryGetCommandArgument(Arguments, out Command)) { StringBuilder Message = new StringBuilder("Missing or invalid command name. Valid commands are:"); foreach (CommandInfo AvailableCommand in Commands) { Message.AppendFormat("\n {0}", AvailableCommand.Name); } throw new CommandLineArgumentException(Message.ToString()); } // Parse the server argument if (String.IsNullOrEmpty(Server)) { const string ServerEnvVarName = "METADATA_SERVER_URL"; Server = Environment.GetEnvironmentVariable(ServerEnvVarName); if (String.IsNullOrEmpty(Server)) { throw new CommandLineArgumentException(String.Format("Missing -Server=... argument or {0} environment variable.", ServerEnvVarName)); } } // Create the command url CommandUrl = new StringBuilder(); CommandUrl.AppendFormat("{0}{1}", Server, Command.Resource); // Replace all the arguments that are embedded into the resource name foreach (string ResourceArg in ParseArgumentNamesFromResource(Command.Resource)) { string Value = Arguments.GetString(String.Format("-{0}=", ResourceArg)); CommandUrl.Replace("{" + ResourceArg + "}", Value); } // Add all the required and optional parameters List <string> QueryParams = new List <string>(); if (Command.OptionalParams != null) { foreach (string OptionalParam in Command.OptionalParams) { string Value = Arguments.GetStringOrDefault(String.Format("-{0}=", OptionalParam), null); if (Value != null) { QueryParams.Add(String.Format("{0}={1}", OptionalParam, Value)); } } } // Append the parameters to the URL for (int Idx = 0; Idx < QueryParams.Count; Idx++) { if (Idx == 0) { CommandUrl.Append("?"); } else { CommandUrl.Append("&"); } CommandUrl.Append(QueryParams[Idx]); } // Parse additional options for the message body if (Command.BodyType != null) { object BodyObject = ParseObject(Arguments, Command.BodyType); BodyText = new JavaScriptSerializer().Serialize(BodyObject); } }
static void Main() { var args = CommandLineArguments.Parse(); var img = EXRFile.FromFile(args[0]); var part = img.Parts[0]; //part.OpenParallel(() => { return new EXRReader(new System.IO.BinaryReader(System.IO.File.OpenRead(args[0]))); }); part.OpenParallel(args[0]); var bmp = new Bitmap(part.DataWindow.Width, part.DataWindow.Height); var data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); var destBytes = part.GetBytes(ImageDestFormat.BGRA8, GammaEncoding.sRGB, data.Stride); Marshal.Copy(destBytes, 0, data.Scan0, destBytes.Length); bmp.UnlockBits(data); part.Close(); var ms = new MemoryStream(); bmp.Save(ms, ImageFormat.Png); var buffer = new byte[ms.Position]; ms.Position = 0; ms.Read(buffer, 0, buffer.Length); ms.Dispose(); var image64 = System.Convert.ToBase64String(buffer); var html = $@" <html> <header><title>{args[0]}</title></header> <body> <img src=""data: image / png; base64,{image64}"" </body> </html> "; var htmlFile = Path.GetTempFileName() + ".html"; File.WriteAllText(htmlFile, html); var openCommand = ""; switch (Environment.OSVersion.Platform) { case PlatformID.Win32NT: openCommand = "start"; break; case PlatformID.MacOSX: openCommand = "open"; break; case PlatformID.Unix: openCommand = "xdg-open"; break; } Console.WriteLine($"{openCommand} {htmlFile}".Sh()); }
internal static SourceReferenceResolver GetSourceReferenceResolver(CommandLineArguments arguments, TouchedFileLogger loggerOpt) { return new CommonCompiler.LoggingSourceFileResolver(arguments.SourcePaths, arguments.BaseDirectory, ImmutableArray<KeyValuePair<string, string>>.Empty, loggerOpt); }
public override int Execute(CommandLineArguments Arguments) { FileReference InputFile = Arguments.GetFileReference("-TimingFile="); // If the tracing argument was passed, hand off to the logic to generate a JSON file compatible with // chrome://tracing if (Arguments.HasOption("-Tracing")) { ParseTimingDataToTracingFiles(InputFile); return(0); } // Break the input file into the various sections for processing. string[] AllLines = FileReference.ReadAllLines(InputFile); List <string> Includes = new List <string>(); List <string> Classes = new List <string>(); List <string> Functions = new List <string>(); TimingDataType CurrentType = TimingDataType.None; foreach (string Line in AllLines) { if (string.IsNullOrWhiteSpace(Line)) { continue; } // Check for a change of type. if (Line.StartsWith("Include Headers:", StringComparison.OrdinalIgnoreCase)) { CurrentType = TimingDataType.Include; continue; } else if (Line.StartsWith("Class Definitions:", StringComparison.OrdinalIgnoreCase)) { CurrentType = TimingDataType.Class; continue; } else if (Line.StartsWith("Function Definitions:", StringComparison.OrdinalIgnoreCase)) { CurrentType = TimingDataType.Function; continue; } // Skip the count line, we don't need it. if (Regex.IsMatch(Line, @"^\tCount\:\s*\d*$")) { continue; } // If we didn't change types and this isn't the count line and it doesn't match the expected output, // clear the current type and move on. Match TimingDataMatch = Regex.Match(Line, TimingDataRegex); if (!TimingDataMatch.Success) { CurrentType = TimingDataType.None; continue; } // If we get to here this is a line we want to parse. Add it to the correct collection. switch (CurrentType) { case TimingDataType.Include: { Includes.Add(Line); break; } case TimingDataType.Class: { Classes.Add(Line); break; } case TimingDataType.Function: { Functions.Add(Line); break; } } } // Build the summary. TimingData Summary = new TimingData() { Name = InputFile.FullName.Replace(".timing.txt", string.Empty), Type = TimingDataType.Summary }; Summary.AddChild(SummarizeParsedTimingData("IncludeTimings", TimingDataType.Include, Includes)); Summary.AddChild(SummarizeParsedTimingData("ClassTimings", TimingDataType.Class, Classes)); Summary.AddChild(SummarizeParsedTimingData("FunctionTimings", TimingDataType.Function, Functions)); // Write out the timing binary file. using (BinaryWriter Writer = new BinaryWriter(File.Open(InputFile.ChangeExtension(".timing.bin").FullName, FileMode.Create))) { Writer.Write(Summary); } return(0); }
public override DatabaseCommand Create(CommandLineArguments args) { return(new ImportAreaLayerCommand(args.DeQueue())); }
/// <summary> /// Initializes values of the given CommandLineArguments structure. /// </summary> /// <param name="args">CommandLineArguments to initialize</param> /// <history> /// [Curtis_Beard] 07/26/2006 Created /// </history> private static void InitializeArgs(ref CommandLineArguments args) { args.AnyArguments = false; args.StartPath = string.Empty; args.IsValidStartPath = false; args.FileTypes = string.Empty; args.IsValidFileTypes = false; args.SearchText = string.Empty; args.IsValidSearchText = false; args.StartSearch = false; // default to all turned off, user must specify each one, or use /d for defaults args.UseRegularExpressions = false; args.IsCaseSensitive = false; args.IsWholeWord = false; args.UseRecursion = false; args.IsNegation = false; args.UseLineNumbers = false; args.IsFileNamesOnly = false; }
/// <summary> /// Main entry point /// </summary> /// <param name="Arguments">Command-line arguments</param> /// <returns>One of the values of ECompilationResult</returns> public override int Execute(CommandLineArguments Arguments) { Arguments.ApplyTo(this); // Create the build configuration object, and read the settings BuildConfiguration BuildConfiguration = new BuildConfiguration(); XmlConfig.ApplyTo(BuildConfiguration); Arguments.ApplyTo(BuildConfiguration); // Parse all the targets being built List <TargetDescriptor> TargetDescriptors = TargetDescriptor.ParseCommandLine(Arguments, BuildConfiguration.bUsePrecompiled, bSkipRulesCompile); if (TargetDescriptors.Count == 0) { throw new BuildException("No targets specified to clean"); } // Also add implicit descriptors for cleaning UnrealBuildTool if (!BuildConfiguration.bDoNotBuildUHT) { const string UnrealHeaderToolTarget = "UnrealHeaderTool"; // Get a list of project files to clean UHT for List <FileReference> ProjectFiles = new List <FileReference>(); foreach (TargetDescriptor TargetDesc in TargetDescriptors) { if (TargetDesc.Name != UnrealHeaderToolTarget && !RemoteMac.HandlesTargetPlatform(TargetDesc.Platform)) { if (ProjectFiles.Count == 0) { ProjectFiles.Add(null); } if (TargetDesc.ProjectFile != null && !ProjectFiles.Contains(TargetDesc.ProjectFile)) { ProjectFiles.Add(TargetDesc.ProjectFile); } } } // Add descriptors for cleaning UHT with all these projects if (ProjectFiles.Count > 0) { UnrealTargetConfiguration Configuration = BuildConfiguration.bForceDebugUnrealHeaderTool ? UnrealTargetConfiguration.Debug : UnrealTargetConfiguration.Development; string Architecture = UEBuildPlatform.GetBuildPlatform(BuildHostPlatform.Current.Platform).GetDefaultArchitecture(null); foreach (FileReference ProjectFile in ProjectFiles) { TargetDescriptors.Add(new TargetDescriptor(ProjectFile, UnrealHeaderToolTarget, BuildHostPlatform.Current.Platform, Configuration, Architecture, null)); } } } // Output the list of targets that we're cleaning Log.TraceInformation("Cleaning {0} binaries...", StringUtils.FormatList(TargetDescriptors.Select(x => x.Name).Distinct())); // Loop through all the targets, and clean them all HashSet <FileReference> FilesToDelete = new HashSet <FileReference>(); HashSet <DirectoryReference> DirectoriesToDelete = new HashSet <DirectoryReference>(); foreach (TargetDescriptor TargetDescriptor in TargetDescriptors) { // Create the rules assembly RulesAssembly RulesAssembly = RulesCompiler.CreateTargetRulesAssembly(TargetDescriptor.ProjectFile, TargetDescriptor.Name, bSkipRulesCompile, BuildConfiguration.bUsePrecompiled, TargetDescriptor.ForeignPlugin); // Create the rules object ReadOnlyTargetRules Target = new ReadOnlyTargetRules(RulesAssembly.CreateTargetRules(TargetDescriptor.Name, TargetDescriptor.Platform, TargetDescriptor.Configuration, TargetDescriptor.Architecture, TargetDescriptor.ProjectFile, TargetDescriptor.AdditionalArguments)); // Find the base folders that can contain binaries List <DirectoryReference> BaseDirs = new List <DirectoryReference>(); BaseDirs.Add(UnrealBuildTool.EngineDirectory); BaseDirs.Add(UnrealBuildTool.EnterpriseDirectory); foreach (FileReference Plugin in Plugins.EnumeratePlugins(Target.ProjectFile)) { BaseDirs.Add(Plugin.Directory); } if (Target.ProjectFile != null) { BaseDirs.Add(Target.ProjectFile.Directory); } // If we're running a precompiled build, remove anything under the engine folder BaseDirs.RemoveAll(x => RulesAssembly.IsReadOnly(x)); // Get all the names which can prefix build products List <string> NamePrefixes = new List <string>(); if (Target.Type != TargetType.Program) { NamePrefixes.Add(UEBuildTarget.GetAppNameForTargetType(Target.Type)); } NamePrefixes.Add(Target.Name); // Get the suffixes for this configuration List <string> NameSuffixes = new List <string>(); if (Target.Configuration == Target.UndecoratedConfiguration) { NameSuffixes.Add(""); } NameSuffixes.Add(String.Format("-{0}-{1}", Target.Platform.ToString(), Target.Configuration.ToString())); if (!String.IsNullOrEmpty(Target.Architecture)) { NameSuffixes.AddRange(NameSuffixes.ToArray().Select(x => x + Target.Architecture)); } // Add all the makefiles and caches to be deleted FilesToDelete.Add(TargetMakefile.GetLocation(Target.ProjectFile, Target.Name, Target.Platform, Target.Configuration)); FilesToDelete.UnionWith(SourceFileMetadataCache.GetFilesToClean(Target.ProjectFile)); FilesToDelete.UnionWith(ActionHistory.GetFilesToClean(Target.ProjectFile, Target.Name, Target.Platform, Target.Type, Target.Architecture)); // Add all the intermediate folders to be deleted foreach (DirectoryReference BaseDir in BaseDirs) { foreach (string NamePrefix in NamePrefixes) { DirectoryReference GeneratedCodeDir = DirectoryReference.Combine(BaseDir, "Intermediate", "Build", Target.Platform.ToString(), NamePrefix, "Inc"); if (DirectoryReference.Exists(GeneratedCodeDir)) { DirectoriesToDelete.Add(GeneratedCodeDir); } DirectoryReference IntermediateDir = DirectoryReference.Combine(BaseDir, "Intermediate", "Build", Target.Platform.ToString(), NamePrefix, Target.Configuration.ToString()); if (DirectoryReference.Exists(IntermediateDir)) { DirectoriesToDelete.Add(IntermediateDir); } } } // List of additional files and directories to clean, specified by the target platform List <FileReference> AdditionalFilesToDelete = new List <FileReference>(); List <DirectoryReference> AdditionalDirectoriesToDelete = new List <DirectoryReference>(); // Add all the build products from this target string[] NamePrefixesArray = NamePrefixes.Distinct().ToArray(); string[] NameSuffixesArray = NameSuffixes.Distinct().ToArray(); foreach (DirectoryReference BaseDir in BaseDirs) { DirectoryReference BinariesDir = DirectoryReference.Combine(BaseDir, "Binaries", Target.Platform.ToString()); if (DirectoryReference.Exists(BinariesDir)) { UEBuildPlatform.GetBuildPlatform(Target.Platform).FindBuildProductsToClean(BinariesDir, NamePrefixesArray, NameSuffixesArray, AdditionalFilesToDelete, AdditionalDirectoriesToDelete); } } // Get all the additional intermediate folders created by this platform UEBuildPlatform.GetBuildPlatform(Target.Platform).FindAdditionalBuildProductsToClean(Target, AdditionalFilesToDelete, AdditionalDirectoriesToDelete); // Add the platform's files and directories to the main list FilesToDelete.UnionWith(AdditionalFilesToDelete); DirectoriesToDelete.UnionWith(AdditionalDirectoriesToDelete); } // Delete all the directories, then all the files. By sorting the list of directories before we delete them, we avoid spamming the log if a parent directory is deleted first. foreach (DirectoryReference DirectoryToDelete in DirectoriesToDelete.OrderBy(x => x.FullName)) { if (DirectoryReference.Exists(DirectoryToDelete)) { Log.TraceVerbose(" Deleting {0}{1}...", DirectoryToDelete, Path.DirectorySeparatorChar); try { FileUtils.ForceDeleteDirectory(DirectoryToDelete); } catch (Exception Ex) { throw new BuildException(Ex, "Unable to delete {0} ({1})", DirectoryToDelete, Ex.Message.TrimEnd()); } } } foreach (FileReference FileToDelete in FilesToDelete.OrderBy(x => x.FullName)) { if (FileReference.Exists(FileToDelete)) { Log.TraceVerbose(" Deleting " + FileToDelete); try { FileUtils.ForceDeleteFile(FileToDelete); } catch (Exception Ex) { throw new BuildException(Ex, "Unable to delete {0} ({1})", FileToDelete, Ex.Message.TrimEnd()); } } } // Also clean all the remote targets for (int Idx = 0; Idx < TargetDescriptors.Count; Idx++) { TargetDescriptor TargetDescriptor = TargetDescriptors[Idx]; if (RemoteMac.HandlesTargetPlatform(TargetDescriptor.Platform)) { RemoteMac RemoteMac = new RemoteMac(TargetDescriptor.ProjectFile); RemoteMac.Clean(TargetDescriptor); } } return(0); }
protected override CompilationOptions CreateCompilationOptions(CommandLineArguments commandLineArguments, ParseOptions newParseOptions) { // Get the base options from command line arguments + common workspace defaults. var options = (CSharpCompilationOptions)base.CreateCompilationOptions(commandLineArguments, newParseOptions); // Now override these with the options from our state. IDictionary <string, ReportDiagnostic> ruleSetSpecificDiagnosticOptions = null; // Get options from the ruleset file, if any, first. That way project-specific // options can override them. ReportDiagnostic?ruleSetGeneralDiagnosticOption = null; if (this.RuleSetFile != null) { ruleSetGeneralDiagnosticOption = this.RuleSetFile.Target.GetGeneralDiagnosticOption(); ruleSetSpecificDiagnosticOptions = new Dictionary <string, ReportDiagnostic>(this.RuleSetFile.Target.GetSpecificDiagnosticOptions()); } else { ruleSetSpecificDiagnosticOptions = new Dictionary <string, ReportDiagnostic>(); } UpdateRuleSetError(this.RuleSetFile?.Target); ReportDiagnostic generalDiagnosticOption; var warningsAreErrors = GetNullableBooleanOption(CompilerOptions.OPTID_WARNINGSAREERRORS); if (warningsAreErrors.HasValue) { generalDiagnosticOption = warningsAreErrors.Value ? ReportDiagnostic.Error : ReportDiagnostic.Default; } else if (ruleSetGeneralDiagnosticOption.HasValue) { generalDiagnosticOption = ruleSetGeneralDiagnosticOption.Value; } else { generalDiagnosticOption = ReportDiagnostic.Default; } // Start with the rule set options IDictionary <string, ReportDiagnostic> diagnosticOptions = new Dictionary <string, ReportDiagnostic>(ruleSetSpecificDiagnosticOptions); // Update the specific options based on the general settings if (warningsAreErrors.HasValue && warningsAreErrors.Value == true) { foreach (var pair in ruleSetSpecificDiagnosticOptions) { if (pair.Value == ReportDiagnostic.Warn) { diagnosticOptions[pair.Key] = ReportDiagnostic.Error; } } } // Update the specific options based on the specific settings foreach (var diagnosticID in ParseWarningCodes(CompilerOptions.OPTID_WARNASERRORLIST)) { diagnosticOptions[diagnosticID] = ReportDiagnostic.Error; } foreach (var diagnosticID in ParseWarningCodes(CompilerOptions.OPTID_WARNNOTASERRORLIST)) { if (ruleSetSpecificDiagnosticOptions.TryGetValue(diagnosticID, out var ruleSetOption)) { diagnosticOptions[diagnosticID] = ruleSetOption; } else { diagnosticOptions[diagnosticID] = ReportDiagnostic.Default; } } foreach (var diagnosticID in ParseWarningCodes(CompilerOptions.OPTID_NOWARNLIST)) { diagnosticOptions[diagnosticID] = ReportDiagnostic.Suppress; } if (!Enum.TryParse(GetStringOption(CompilerOptions.OPTID_PLATFORM, ""), ignoreCase: true, result: out Platform platform)) { platform = Platform.AnyCpu; } if (!int.TryParse(GetStringOption(CompilerOptions.OPTID_WARNINGLEVEL, defaultValue: ""), out var warningLevel)) { warningLevel = 4; } // TODO: appConfigPath: GetFilePathOption(CompilerOptions.OPTID_FUSIONCONFIG), bug #869604 return(options.WithAllowUnsafe(GetBooleanOption(CompilerOptions.OPTID_UNSAFE)) .WithOverflowChecks(GetBooleanOption(CompilerOptions.OPTID_CHECKED)) .WithCryptoKeyContainer(GetStringOption(CompilerOptions.OPTID_KEYNAME, defaultValue: null)) .WithCryptoKeyFile(GetFilePathRelativeOption(CompilerOptions.OPTID_KEYFILE)) .WithDelaySign(GetNullableBooleanOption(CompilerOptions.OPTID_DELAYSIGN)) .WithGeneralDiagnosticOption(generalDiagnosticOption) .WithMainTypeName(_mainTypeName) .WithModuleName(GetStringOption(CompilerOptions.OPTID_MODULEASSEMBLY, defaultValue: null)) .WithOptimizationLevel(GetBooleanOption(CompilerOptions.OPTID_OPTIMIZATIONS) ? OptimizationLevel.Release : OptimizationLevel.Debug) .WithOutputKind(_outputKind) .WithPlatform(platform) .WithSpecificDiagnosticOptions(diagnosticOptions) .WithWarningLevel(warningLevel)); }
// Asks the Bridge to release all its resources but continue running private static void ResetBridge(CommandLineArguments commandLineArgs) { string errorMessage = null; if (!PingBridge(commandLineArgs.BridgeConfiguration.BridgeHost, commandLineArgs.BridgeConfiguration.BridgePort, out errorMessage)) { Console.WriteLine("The Bridge is not running: {0}", errorMessage); Environment.Exit(0); } string bridgeUrl = String.Format("http://{0}:{1}/Resource", commandLineArgs.BridgeConfiguration.BridgeHost, commandLineArgs.BridgeConfiguration.BridgePort); string problem = null; Console.WriteLine("Resetting the Bridge by sending DELETE request to {0}", bridgeUrl); // We reset the Bridge using a DELETE request to the /resource endpoint. using (HttpClient httpClient = new HttpClient()) { try { var response = httpClient.DeleteAsync(bridgeUrl).GetAwaiter().GetResult(); if (!response.IsSuccessStatusCode) { problem = String.Format("{0}Bridge returned unexpected status code='{1}', reason='{2}'", Environment.NewLine, response.StatusCode, response.ReasonPhrase); if (response.Content != null) { string contentAsString = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); if (contentAsString.Length > 1000) { contentAsString = contentAsString.Substring(0, 999) + "..."; } problem = String.Format("{0}, content:{1}{2}", problem, Environment.NewLine, contentAsString); } } } catch (Exception ex) { problem = ex.ToString(); } } if (problem != null) { Console.WriteLine("A problem was encountered resetting the Bridge:{0}{1}", Environment.NewLine, problem); Console.WriteLine("Forcing local resource cleanup..."); } // A successfull DELETE will have cleaned up all firewall rules, // certificates, etc. So when using localhost, this cleanup will // be redundant and harmless. When the Bridge is running remotely, // this cleanup will remove all firewall rules and certificates we // installed on the current machine to talk with that Bridge. BridgeController.ReleaseAllResources(force: false); }
/// <summary> /// Installs this service. /// </summary> private void Install(CommandLineArguments args) { RunInstallerTask(n => n.Install(new Hashtable()), args); EventLog.WriteEntry($"{DisplayName} installed successfully."); }
// TODO (https://github.com/dotnet/roslyn/issues/5854): remove public static ImmutableArray<string> GetImports(CommandLineArguments args) { return args.CompilationOptions.GetImports(); }
private static CommandLineArguments ParseArguments(string[] args) { if (args == null) { return(new CommandLineArguments()); } // If at least four arguments were passed with no argument designator, then assume they're values and // accept them positionally. if ((args.Length >= 4) && (!args[0].StartsWith(CommandLineArguments.ArgumentPrefix)) && (!args[1].StartsWith(CommandLineArguments.ArgumentPrefix)) && (!args[2].StartsWith(CommandLineArguments.ArgumentPrefix)) && (!args[3].StartsWith(CommandLineArguments.ArgumentPrefix))) { var parsed = new CommandLineArguments { EventHubsConnectionString = args[0], EventHub = args[1], StorageConnectionString = args[2], BlobContainer = args[3] }; if ((args.Length >= 5) && (!args[4].StartsWith(CommandLineArguments.ArgumentPrefix))) { parsed.RunDurationHours = args[4]; } if ((args.Length >= 6) && (!args[5].StartsWith(CommandLineArguments.ArgumentPrefix))) { parsed.LogPath = args[4]; } return(parsed); } var parsedArgs = new CommandLineArguments(); // Enumerate the arguments that were passed, stopping one before the // end, since we're scanning forward by an item to retrieve values; if a // command was passed in the last position, there was no accompanying value, // so it isn't useful. for (var index = 0; index < args.Length - 1; ++index) { // Remove any excess spaces to comparison purposes. args[index] = args[index].Trim(); // Since we're evaluating the next token in sequence as a value in the // checks that follow, if it is an argument, we'll skip to the next iteration. if (args[index + 1].StartsWith(CommandLineArguments.ArgumentPrefix)) { continue; } // If the current token is one of our known arguments, capture the next token in sequence as it's // value, since we've already ruled out that it is another argument name. if (args[index].Equals($"{ CommandLineArguments.ArgumentPrefix }{ nameof(CommandLineArguments.EventHubsConnectionString) }", StringComparison.OrdinalIgnoreCase)) { parsedArgs.EventHubsConnectionString = args[index + 1].Trim(); } else if (args[index].Equals($"{ CommandLineArguments.ArgumentPrefix }{ nameof(CommandLineArguments.EventHub) }", StringComparison.OrdinalIgnoreCase)) { parsedArgs.EventHub = args[index + 1].Trim(); } else if (args[index].Equals($"{ CommandLineArguments.ArgumentPrefix }{ nameof(CommandLineArguments.StorageConnectionString) }", StringComparison.OrdinalIgnoreCase)) { parsedArgs.StorageConnectionString = args[index + 1].Trim(); } else if (args[index].Equals($"{ CommandLineArguments.ArgumentPrefix }{ nameof(CommandLineArguments.BlobContainer) }", StringComparison.OrdinalIgnoreCase)) { parsedArgs.BlobContainer = args[index + 1].Trim(); } else if (args[index].Equals($"{ CommandLineArguments.ArgumentPrefix }{ nameof(CommandLineArguments.RunDurationHours) }", StringComparison.OrdinalIgnoreCase)) { parsedArgs.RunDurationHours = args[index + 1].Trim(); } else if (args[index].Equals($"{ CommandLineArguments.ArgumentPrefix }{ nameof(CommandLineArguments.LogPath) }", StringComparison.OrdinalIgnoreCase)) { parsedArgs.LogPath = args[index + 1].Trim(); } } return(parsedArgs); }
internal static MetadataReferenceResolver GetMetadataReferenceResolver(CommandLineArguments arguments, TouchedFileLogger loggerOpt) { return new RuntimeMetadataReferenceResolver( new RelativePathResolver(arguments.ReferencePaths, arguments.BaseDirectory), null, GacFileResolver.IsAvailable ? new GacFileResolver(preferredCulture: CultureInfo.CurrentCulture) : null, (path, properties) => { loggerOpt?.AddRead(path); return MetadataReference.CreateFromFile(path); }); }
static void Main(string[] args) { // Try to enlarge the window. try { Console.SetWindowSize(Console.LargestWindowWidth * 8 / 9, Console.LargestWindowHeight * 8 / 9); } catch (Exception) {} // Create the name of the local working copy. string workingCopy = DateTime.UtcNow.ToString("d", CultureInfo.CreateSpecificCulture("en-US")).Replace('/', '-'); string fullPath = Path.GetFullPath(workingCopy); if (!Directory.Exists(fullPath)) { Directory.CreateDirectory(fullPath); } Environment.CurrentDirectory = WorkingCopy = fullPath; CommandLine.DisplayGoogleSampleHeader("Release Builder: "+workingCopy); CommandLine.EnableExceptionHandling(); // Parse command line arguments. CommandLine.ParseArguments(Arguments = new CommandLineArguments(), args); // 1. Create the local repositories. CheckoutRepositories(); // Clean up the default/ repository by removing cache-files. string toDelete = Default.Combine("_ReSharper.GoogleApisClient"); if (Directory.Exists(toDelete)) { Directory.Delete(toDelete, true); } foreach (string pattern in new[] { "*.dotcover", "*.user", "*.suo" }) { foreach (string file in Directory.GetFiles(Default.WorkingDirectory, pattern)) { File.Delete(file); } } // 2. Create the project/build tasks. FileVersionInfo apiVersion; Project[] allProjects; Project[] baseLibrary = BuildProjects(out apiVersion, out allProjects); Project servicegen = baseLibrary.Where(proj => proj.Name == "GoogleApis.Tools.ServiceGenerator").Single(); // Retrieve tag name. string tag = GetTagName(apiVersion); if (Arguments.IsStableRelease) { UpdateSamples(baseLibrary, servicegen); } // 4. Build contrib. string notes = CreateChangelog(tag); string zipDir; notes = BuildContribRelease(tag, notes, baseLibrary, allProjects, servicegen, out zipDir); // 5. Update the Wiki. if (Arguments.IsStableRelease) { UpdateWiki(notes, zipDir); } // Ask the user whether he wants to continue the release. string res = "no"; CommandLine.WriteLine("{{white}} ======================================="); CommandLine.WriteResult("Version: ", apiVersion.ProductVersion); CommandLine.WriteLine(); if (Arguments.UseLocalRepository) { CommandLine.WriteAction("Local build done."); CommandLine.PressAnyKeyToExit(); return; } // 6. Commit & tag the release CommitAndTagRelease(tag); CommandLine.WriteLine(" {{gray}}In the next step all changes will be commited and tagged."); CommandLine.WriteLine(" {{gray}}Only continue when you are sure that you don't have to make any new changes."); CommandLine.RequestUserInput("Do you want to continue with the release? Type YES.", ref res); CommandLine.WriteLine(); if (res == "YES") { // Check for incoming changes foreach (Hg repository in AllRepositories) { if (repository.HasIncomingChanges) { CommandLine.WriteError( "Repository [{0}] has incoming changes. Run hg pull & update first!", repository.Name); CommandLine.PressAnyKeyToExit(); return; } } // 7. Push PushChanges(); } CommandLine.PressAnyKeyToExit(); }
private async Task <ResolvedReferences> ResolveReferencesAsync(ProjectId id, ProjectFileInfo projectFileInfo, CommandLineArguments commandLineArgs, CancellationToken cancellationToken) { // First, gather all of the metadata references from the command-line arguments. var resolvedMetadataReferences = commandLineArgs.ResolveMetadataReferences( new WorkspaceMetadataFileReferenceResolver( metadataService: GetWorkspaceService <IMetadataService>(), pathResolver: new RelativePathResolver(commandLineArgs.ReferencePaths, commandLineArgs.BaseDirectory))); var builder = new ResolvedReferencesBuilder(resolvedMetadataReferences); var projectDirectory = Path.GetDirectoryName(projectFileInfo.FilePath); // Next, iterate through all project references in the file and create project references. foreach (var projectFileReference in projectFileInfo.ProjectReferences) { var aliases = projectFileReference.Aliases; if (_pathResolver.TryGetAbsoluteProjectPath(projectFileReference.Path, baseDirectory: projectDirectory, _discoveredProjectOptions.OnPathFailure, out var projectReferencePath)) { // The easiest case is to add a reference to a project we already know about. if (TryAddReferenceToKnownProject(id, projectReferencePath, aliases, builder)) { continue; } // If we don't know how to load a project (that is, it's not a language we support), we can still // attempt to verify that its output exists on disk and is included in our set of metadata references. // If it is, we'll just leave it in place. if (!IsProjectLoadable(projectReferencePath) && await VerifyUnloadableProjectOutputExistsAsync(projectReferencePath, builder, cancellationToken).ConfigureAwait(false)) { continue; } // If metadata is preferred, see if the project reference's output exists on disk and is included // in our metadata references. If it is, don't create a project reference; we'll just use the metadata. if (_preferMetadataForReferencesOfDiscoveredProjects && await VerifyProjectOutputExistsAsync(projectReferencePath, builder, cancellationToken).ConfigureAwait(false)) { continue; } // Finally, we'll try to load and reference the project. if (await TryLoadAndAddReferenceAsync(id, projectReferencePath, aliases, builder, cancellationToken).ConfigureAwait(false)) { continue; } } // We weren't able to handle this project reference, so add it without further processing. var unknownProjectId = _projectMap.GetOrCreateProjectId(projectFileReference.Path); var newProjectReference = CreateProjectReference(from: id, to: unknownProjectId, aliases); builder.AddProjectReference(newProjectReference); } // Are there still any unresolved metadata references? If so, remove them and report diagnostics. foreach (var unresolvedMetadataReference in builder.GetUnresolvedMetadataReferences()) { var filePath = unresolvedMetadataReference.Reference; builder.Remove(filePath); _diagnosticReporter.Report(new ProjectDiagnostic( WorkspaceDiagnosticKind.Warning, string.Format(WorkspaceMSBuildResources.Unresolved_metadata_reference_removed_from_project_0, filePath), id)); } return(builder.ToResolvedReferences()); }
private void GetReferences(VisualBasicProjectFileLoader.VisualBasicProjectFile.VisualBasicCompilerInputs compilerInputs, ProjectInstance executedProject, ref IEnumerable <MetadataReference> metadataReferences, ref IEnumerable <AnalyzerReference> analyzerReferences) { // use command line parser to compute references using common logic List <string> list = new List <string>(); if (compilerInputs.LibPaths != null && compilerInputs.LibPaths.Count <string>() > 0) { list.Add("/libpath:\"" + string.Join(";", compilerInputs.LibPaths) + "\""); } // metadata references foreach (var current in compilerInputs.References) { string documentFilePath = base.GetDocumentFilePath(current); list.Add("/r:\"" + documentFilePath + "\""); } // analyzer references foreach (var current in compilerInputs.AnalyzerReferences) { string documentFilePath2 = base.GetDocumentFilePath(current); list.Add("/a:\"" + documentFilePath2 + "\""); } if (compilerInputs.NoStandardLib) { list.Add("/nostdlib"); } if (!string.IsNullOrEmpty(compilerInputs.VbRuntime)) { if (compilerInputs.VbRuntime == "Default") { list.Add("/vbruntime+"); } else if (compilerInputs.VbRuntime == "Embed") { list.Add("/vbruntime*"); } else if (compilerInputs.VbRuntime == "None") { list.Add("/vbruntime-"); } else { list.Add("/vbruntime: " + compilerInputs.VbRuntime); } } if (!string.IsNullOrEmpty(compilerInputs.SdkPath)) { list.Add("/sdkpath:" + compilerInputs.SdkPath); } CommandLineArguments commandLineArguments = this._commandLineArgumentsFactory.CreateCommandLineArguments(list, executedProject.Directory, false, RuntimeEnvironment.GetRuntimeDirectory()); MetadataFileReferenceResolver pathResolver = new MetadataFileReferenceResolver(commandLineArguments.ReferencePaths, commandLineArguments.BaseDirectory); metadataReferences = commandLineArguments.ResolveMetadataReferences(new AssemblyReferenceResolver(pathResolver, this._metadataService.GetProvider())); IAnalyzerAssemblyLoader loader = this._analyzerService.GetLoader(); foreach (var path in commandLineArguments.AnalyzerReferences.Select((r) => r.FilePath)) { loader.AddDependencyLocation(path); } analyzerReferences = commandLineArguments.ResolveAnalyzerReferences(loader); }
private static int Main(string[] sArgs) { string str; X509Certificate2 certificate; Application.EnableVisualStyles(); if (sArgs.Length < 1) { MessageBox.Show("Syntax:\r\n\tTrustCert.exe [-noprompt] [-u] (CertSubject | -path=PathToCertificate)", "Incorrect Parameters"); return(1); } CommandLineArguments arguments = ParseCommandLineArguments(sArgs, out str); bool flag = arguments.HasFlag(CommandLineArguments.Uninstall); if (arguments.HasFlag(CommandLineArguments.RootSubject)) { StoreLocation storeLocation = flag ? StoreLocation.LocalMachine : StoreLocation.CurrentUser; X509Certificate2Collection certificates = FindCertsBySubject(StoreName.Root, storeLocation, str); if (certificates.Count < 1) { MessageBox.Show($"Failed to find the root certificate in {flag ? "Machine" : "User"} Root List.", "TrustCert Failed"); if (flag) { return(0); } return(2); } certificate = certificates[0]; } else { if (arguments.HasFlag(CommandLineArguments.PathToCertificate)) { if (!File.Exists(str)) { MessageBox.Show("No certificate found at the following path:" + Environment.NewLine + Environment.NewLine + str, "Certificate not found"); return(5); } try { certificate = new X509Certificate2(str); goto Label_0119; } catch (Exception exception) { MessageBox.Show("Error reading certificate from path - " + exception.Message, "Error reading certificate"); return(6); } } MessageBox.Show("In order to add/remove a certificate to/from the Machine Root list you must provide either CertSubject or -path=PathToCertificate as last parameter."); return(7); } Label_0119: if (!setMachineTrust(certificate, !flag, !arguments.HasFlag(CommandLineArguments.NoPrompt))) { MessageBox.Show($"Failed to {flag ? "remove" : "add"} the root certificate {flag ? "from" : "to"} the Machine Root List.", "TrustCert Failed"); if (!flag) { return(3); } return(4); } MessageBox.Show($"{flag ? "Removed" : "Added"} Fiddler's root certificate {flag ? "from" : "to"} the Machine Root List.", "TrustCert Success"); return(0); }
/// <summary> /// Execute the tool mode /// </summary> /// <param name="Arguments">Command line arguments</param> /// <returns>Exit code</returns> public override int Execute(CommandLineArguments Arguments) { // Output a warning if there are any arguments that are still unused Arguments.CheckAllArgumentsUsed(); return(0); }
/// <summary> /// Constructs a TargetInfo for passing to the TargetRules constructor. /// </summary> /// <param name="Name">Name of the target being built</param> /// <param name="Platform">The platform that the target is being built for</param> /// <param name="Configuration">The configuration being built</param> /// <param name="Architecture">The architecture being built for</param> /// <param name="ProjectFile">Path to the project file containing the target</param> /// <param name="Arguments">Additional command line arguments for this target</param> public TargetInfo(string Name, UnrealTargetPlatform Platform, UnrealTargetConfiguration Configuration, string Architecture, FileReference ProjectFile, CommandLineArguments Arguments) { this.Name = Name; this.Platform = Platform; this.Configuration = Configuration; this.Architecture = Architecture; this.ProjectFile = ProjectFile; this.Arguments = Arguments; }
/// <summary> /// Parse the given string for valid command line option flags. /// </summary> /// <param name="myArgs">String containing potential options.</param> /// <param name="args">CommandLineArguments structure to hold found options.</param> /// <history> /// [Curtis_Beard] 07/26/2006 Created /// [Curtis_Beard] 05/18/2007 CHG: use new command line arguments /// [Curtis_Beard] 09/26/2012 ADD: display help option /// [Curtis_Beard] 04/08/2014 CHG: 74, add missing search options, exit, save /// [Curtis_Beard] 06/02/2015 CHG: 97, remove /local since portable version created /// [Curtis_Beard] 01/08/2019 FIX: 104, allow any path to be passed to UI and UI will validate /// </history> private static void ProcessFlags(Arguments myArgs, ref CommandLineArguments args) { if (myArgs["s"] != null) { args.StartSearch = true; } if (myArgs["e"] != null) { args.UseRegularExpressions = true; } if (myArgs["c"] != null) { args.IsCaseSensitive = true; } if (myArgs["w"] != null) { args.IsWholeWord = true; } if (myArgs["r"] != null) { args.UseRecursion = true; } if (myArgs["n"] != null) { args.IsNegation = true; } if (myArgs["l"] != null) { args.UseLineNumbers = true; } if (myArgs["f"] != null) { args.IsFileNamesOnly = true; } if (myArgs["cl"] != null) { try { int num = int.Parse(myArgs["cl"]); if (num >= 0 && num <= Constants.MAX_CONTEXT_LINES) { args.ContextLines = num; } } catch {} } if (myArgs["sh"] != null) { args.SkipHiddenFile = true; args.SkipHiddenDirectory = true; } if (myArgs["ss"] != null) { args.SkipSystemFile = true; args.SkipSystemDirectory = true; } if (myArgs["shf"] != null) { args.SkipHiddenFile = true; } if (myArgs["shd"] != null) { args.SkipHiddenDirectory = true; } if (myArgs["ssf"] != null) { args.SkipSystemFile = true; } if (myArgs["ssd"] != null) { args.SkipSystemDirectory = true; } if (myArgs["spath"] != null) { args.IsValidStartPath = true; args.StartPath = myArgs["spath"]; } if (myArgs["stypes"] != null) { args.IsValidFileTypes = true; args.FileTypes = myArgs["stypes"]; } if (myArgs["stext"] != null) { args.IsValidSearchText = true; args.SearchText = myArgs["stext"]; } if (myArgs["h"] != null || myArgs["?"] != null || myArgs["help"] != null) { args.DisplayHelp = true; } if (myArgs["opath"] != null) { args.OutputPath = myArgs["opath"]; // default to txt (override by supplying outputtype) args.OutputType = "txt"; // since they want to save results, then we have to start search args.StartSearch = true; } if (myArgs["otype"] != null) { args.OutputType = myArgs["otype"].ToLower(); // set default path if not defined if (string.IsNullOrEmpty(args.OutputPath)) { args.OutputPath = System.IO.Path.Combine(Environment.CurrentDirectory, string.Format("results.{0}", args.OutputType)); } // since they want to save results, then we have to start search args.StartSearch = true; } if (myArgs["exit"] != null) { args.ExitAfterSearch = true; } if (myArgs["dmf"] != null) { string[] values = myArgs["dmf"].Split('|'); if (values.Length == 2) { libAstroGrep.FilterType.ValueOptions valueOption = GetValueOptionFromOperator(values[0]); DateTime value = DateTime.MinValue; if (DateTime.TryParse(values[1], out value) && valueOption != libAstroGrep.FilterType.ValueOptions.None) { args.DateModifiedFile = new ValueOptionPair() { Value = value, ValueOption = valueOption }; } } } if (myArgs["dmd"] != null) { string[] values = myArgs["dmd"].Split('|'); if (values.Length == 2) { libAstroGrep.FilterType.ValueOptions valueOption = GetValueOptionFromOperator(values[0]); DateTime value = DateTime.MinValue; if (DateTime.TryParse(values[1], out value) && valueOption != libAstroGrep.FilterType.ValueOptions.None) { args.DateModifiedDirectory = new ValueOptionPair() { Value = value, ValueOption = valueOption }; } } } if (myArgs["dcf"] != null) { string[] values = myArgs["dcf"].Split('|'); if (values.Length == 2) { libAstroGrep.FilterType.ValueOptions valueOption = GetValueOptionFromOperator(values[0]); DateTime value = DateTime.MinValue; if (DateTime.TryParse(values[1], out value) && valueOption != libAstroGrep.FilterType.ValueOptions.None) { args.DateCreatedFile = new ValueOptionPair() { Value = value, ValueOption = valueOption }; } } } if (myArgs["dcd"] != null) { string[] values = myArgs["dcd"].Split('|'); if (values.Length == 2) { libAstroGrep.FilterType.ValueOptions valueOption = GetValueOptionFromOperator(values[0]); DateTime value = DateTime.MinValue; if (DateTime.TryParse(values[1], out value) && valueOption != libAstroGrep.FilterType.ValueOptions.None) { args.DateCreatedDirectory = new ValueOptionPair() { Value = value, ValueOption = valueOption }; } } } if (myArgs["minfsize"] != null) { string[] values = myArgs["minfsize"].Split('|'); if (values.Length == 2) { libAstroGrep.FilterType.ValueOptions valueOption = GetValueOptionFromOperator(values[0]); long value = 0; if (Int64.TryParse(values[1], out value) && valueOption != libAstroGrep.FilterType.ValueOptions.None) { args.MinFileSize = new ValueOptionPair() { Value = value, ValueOption = valueOption }; } } } if (myArgs["maxfsize"] != null) { string[] values = myArgs["maxfsize"].Split('|'); if (values.Length == 2) { libAstroGrep.FilterType.ValueOptions valueOption = GetValueOptionFromOperator(values[0]); long value = 0; if (Int64.TryParse(values[1], out value) && valueOption != libAstroGrep.FilterType.ValueOptions.None) { args.MaxFileSize = new ValueOptionPair() { Value = value, ValueOption = valueOption }; } } } if (myArgs["minfc"] != null) { int value = 0; if (Int32.TryParse(myArgs["minfc"], out value)) { args.MinFileCount = value; } } if (myArgs["srf"] != null) { args.ReadOnlyFile = true; } }
/// <summary> /// Starts this service instance. /// </summary> /// <param name="args">The <see cref="CommandLineArguments" /> provided to the start command.</param> protected abstract void StartService(CommandLineArguments args);
static void Main(string[] args) { CommandLineArguments arguments = null; try { arguments = CommandLineHelper.Parse <CommandLineArguments>(args); } catch (Exception) { return; } /*try * {*/ var gameStateManager = new GameStateManager(); var blockSimples = new[] { new Tuple <byte, string, bool>(1, "Stone", true), new Tuple <byte, string, bool>(2, "Grass block", true), new Tuple <byte, string, bool>(3, "Dirt", true), new Tuple <byte, string, bool>(4, "Cobblestone", true), new Tuple <byte, string, bool>(5, "Wooden planks", true), new Tuple <byte, string, bool>(7, "Bedrock", true), new Tuple <byte, string, bool>(12, "Sand", true), new Tuple <byte, string, bool>(13, "Gravel", true), new Tuple <byte, string, bool>(14, "Gold Ore", true), new Tuple <byte, string, bool>(15, "Iron Ore", true), new Tuple <byte, string, bool>(16, "Coal Ore", true), new Tuple <byte, string, bool>(17, "Oak Wood", true), new Tuple <byte, string, bool>(24, "Sandstone", true), new Tuple <byte, string, bool>(31, "Grass", false), new Tuple <byte, string, bool>(35, "Wool", true), }; var blocksProvider = new BlocksProvider(); var blockSelector = new BlockSelector(); for (int i = 0; i < blockSimples.Length; i++) { blocksProvider.RegisterBlock(blockSimples[i].Item1, new BlockSimple(blockSimples[i].Item2, blockSimples[i].Item3)); blockSelector.AddSelectableBlock(blockSimples[i].Item1); } var chunkManager = new ChunkManager(); var chunkGenerator = new ChunkGeneratorSurface(chunkManager); var worldManager = new WorldManager(blocksProvider, chunkManager, chunkGenerator); var chunkPartManager = new ChunkPartManager(worldManager, chunkManager, blocksProvider); var world = new World("world", (arguments?.Seed ?? 0) != 0 ? arguments.Seed : new Random().Next()); var window = new MainWindow(gameStateManager, world); gameStateManager.SetGameState(new GameStatePlay(gameStateManager, worldManager, chunkManager, chunkPartManager, blockSelector, blocksProvider, world)); window.Run(60); worldManager.Clean(world); /*} * catch (Exception exception) * { * Console.Error.WriteLine($"Une exception de type {exception.GetType()} est survenue, message : {exception.Message}"); * Console.Error.WriteLine($"Stacktrace:"); * Console.Error.WriteLine(exception.StackTrace); * Console.WriteLine("Sortie..."); * Environment.Exit(1); * }*/ }
/// <summary> /// Uninstalls this service. /// </summary> private void Uninstall(CommandLineArguments args) { RunInstallerTask(n => n.Uninstall(null), args); }
/// <summary> /// Writes a manifest containing all the information needed to create a live coding patch /// </summary> /// <param name="ManifestFile">File to write to</param> /// <param name="Actions">List of actions that are part of the graph</param> /// <param name="OriginalFileToPatchedFile">Map of original object files to patched object files</param> public static void WriteLiveCodingManifest(FileReference ManifestFile, List <Action> Actions, Dictionary <FileReference, FileReference> OriginalFileToPatchedFile) { // Find all the output object files HashSet <FileItem> ObjectFiles = new HashSet <FileItem>(); foreach (Action Action in Actions) { if (Action.ActionType == ActionType.Compile) { ObjectFiles.UnionWith(Action.ProducedItems.Where(x => x.HasExtension(".obj"))); } } // Write the output manifest using (JsonWriter Writer = new JsonWriter(ManifestFile)) { Writer.WriteObjectStart(); Action LinkAction = Actions.FirstOrDefault(x => x.ActionType == ActionType.Link && x.ProducedItems.Any(y => y.HasExtension(".exe") || y.HasExtension(".dll"))); if (LinkAction != null) { FileReference LinkerPath = LinkAction.CommandPath; if (String.Compare(LinkerPath.GetFileName(), "link-filter.exe", StringComparison.OrdinalIgnoreCase) == 0) { string[] Arguments = CommandLineArguments.Split(LinkAction.CommandArguments); for (int Idx = 0; Idx + 1 < Arguments.Length; Idx++) { if (Arguments[Idx] == "--") { LinkerPath = new FileReference(Arguments[Idx + 1]); break; } } } Writer.WriteValue("LinkerPath", LinkerPath.FullName); } Writer.WriteObjectStart("LinkerEnvironment"); foreach (System.Collections.DictionaryEntry Entry in Environment.GetEnvironmentVariables()) { Writer.WriteValue(Entry.Key.ToString(), Entry.Value.ToString()); } Writer.WriteObjectEnd(); Writer.WriteArrayStart("Modules"); foreach (Action Action in Actions) { if (Action.ActionType == ActionType.Link) { FileItem OutputFile = Action.ProducedItems.FirstOrDefault(x => x.HasExtension(".exe") || x.HasExtension(".dll")); if (OutputFile != null && Action.PrerequisiteItems.Any(x => OriginalFileToPatchedFile.ContainsKey(x.Location))) { Writer.WriteObjectStart(); Writer.WriteValue("Output", OutputFile.Location.FullName); Writer.WriteArrayStart("Inputs"); foreach (FileItem InputFile in Action.PrerequisiteItems) { FileReference PatchedFile; if (OriginalFileToPatchedFile.TryGetValue(InputFile.Location, out PatchedFile)) { Writer.WriteValue(PatchedFile.FullName); } } Writer.WriteArrayEnd(); Writer.WriteObjectEnd(); } } } Writer.WriteArrayEnd(); Writer.WriteObjectEnd(); } }
static object ParseObject(CommandLineArguments Arguments, Type ObjectType) { object Instance = Activator.CreateInstance(ObjectType); foreach (FieldInfo Field in Instance.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public)) { string Value = Arguments.GetStringOrDefault(String.Format("-{0}=", Field.Name), null); if (Value == null) { if (!IsOptionalObjectField(Field)) { throw new CommandLineArgumentException(String.Format("Missing -{0}=... argument", Field.Name)); } } else { Type FieldType = Field.FieldType; if (FieldType.IsGenericType && FieldType.GetGenericTypeDefinition() == typeof(Nullable <>)) { FieldType = FieldType.GetGenericArguments()[0]; } if (FieldType == typeof(string)) { Field.SetValue(Instance, Value); } else if (FieldType == typeof(int)) { int IntValue; if (!int.TryParse(Value, out IntValue)) { throw new CommandLineArgumentException(String.Format("Invalid value for '{0}' - {1} is not an integer.", Field.Name, Value)); } Field.SetValue(Instance, IntValue); } else if (FieldType == typeof(long)) { long LongValue; if (!long.TryParse(Value, out LongValue)) { throw new CommandLineArgumentException(String.Format("Invalid value for '{0}' - {1} is not an integer.", Field.Name, Value)); } Field.SetValue(Instance, LongValue); } else if (FieldType == typeof(bool)) { bool BoolValue; if (!bool.TryParse(Value, out BoolValue)) { throw new CommandLineArgumentException(String.Format("Invalid value for '{0}' - {1} is not a boolean.", Field.Name, Value)); } Field.SetValue(Instance, BoolValue); } else if (FieldType.IsEnum) { object EnumValue; try { EnumValue = Enum.Parse(FieldType, Value, true); } catch (ArgumentException) { throw new CommandLineArgumentException(String.Format("Invalid value for '{0}' - should be {1}", Field.Name, String.Join("/", Enum.GetNames(FieldType)))); } Field.SetValue(Instance, EnumValue); } else { throw new NotImplementedException(String.Format("Unsupported type '{0}'", FieldType)); } } } return(Instance); }
/// <summary> /// Execute the command /// </summary> /// <param name="Arguments">List of command line arguments</param> /// <returns>Always zero, or throws an exception</returns> public override int Execute(CommandLineArguments Arguments) { Arguments.ApplyTo(this); Arguments.CheckAllArgumentsUsed(); Log.TraceInformation("{0}", OutputFile.GetFileName()); // Read the input files string[] InputFileLines = FileReference.ReadAllLines(InputFileList); FileReference[] InputFiles = InputFileLines.Select(x => x.Trim()).Where(x => x.Length > 0).Select(x => new FileReference(x)).ToArray(); // Create the combined output file, and print the diagnostics to the log HashSet <string> UniqueItems = new HashSet <string>(); using (StreamWriter RawWriter = new StreamWriter(OutputFile.FullName)) { foreach (FileReference InputFile in InputFiles) { string[] Lines = File.ReadAllLines(InputFile.FullName); for (int LineIdx = 0; LineIdx < Lines.Length; LineIdx++) { string Line = Lines[LineIdx]; if (!String.IsNullOrWhiteSpace(Line) && UniqueItems.Add(Line)) { bool bCanParse = false; string[] Tokens = Line.Split(new string[] { "<#~>" }, StringSplitOptions.None); if (Tokens.Length >= 9) { string Trial = Tokens[1]; string LineNumberStr = Tokens[2]; string FileName = Tokens[3]; string WarningCode = Tokens[5]; string WarningMessage = Tokens[6]; string FalseAlarmStr = Tokens[7]; string LevelStr = Tokens[8]; int LineNumber; bool bFalseAlarm; int Level; if (int.TryParse(LineNumberStr, out LineNumber) && bool.TryParse(FalseAlarmStr, out bFalseAlarm) && int.TryParse(LevelStr, out Level)) { bCanParse = true; // Ignore anything in ThirdParty folders if (FileName.Replace('/', '\\').IndexOf("\\ThirdParty\\", StringComparison.InvariantCultureIgnoreCase) == -1) { // Output the line to the raw output file RawWriter.WriteLine(Line); // Output the line to the log if (!bFalseAlarm && Level == 1) { Log.WriteLine(LogEventType.Warning, LogFormatOptions.NoSeverityPrefix, "{0}({1}): warning {2}: {3}", FileName, LineNumber, WarningCode, WarningMessage); } } } } if (!bCanParse) { Log.WriteLine(LogEventType.Warning, LogFormatOptions.NoSeverityPrefix, "{0}({1}): warning: Unable to parse PVS output line '{2}' (tokens=|{3}|)", InputFile, LineIdx + 1, Line, String.Join("|", Tokens)); } } } } } Log.TraceInformation("Written {0} {1} to {2}.", UniqueItems.Count, (UniqueItems.Count == 1)? "diagnostic" : "diagnostics", OutputFile.FullName); return(0); }
/// <summary> /// Main entry point /// </summary> /// <param name="Arguments">Command-line arguments</param> /// <returns>One of the values of ECompilationResult</returns> public override int Execute(CommandLineArguments Arguments) { Arguments.ApplyTo(this); // Initialize the log system, buffering the output until we can create the log file StartupTraceListener StartupListener = new StartupTraceListener(); Trace.Listeners.Add(StartupListener); // Write the command line Log.TraceLog("Command line: {0}", Environment.CommandLine); // Grab the environment. UnrealBuildTool.InitialEnvironment = Environment.GetEnvironmentVariables(); if (UnrealBuildTool.InitialEnvironment.Count < 1) { throw new BuildException("Environment could not be read"); } // Read the XML configuration files XmlConfig.ApplyTo(this); // Fixup the log path if it wasn't overridden by a config file if (BaseLogFileName == null) { BaseLogFileName = FileReference.Combine(UnrealBuildTool.EngineProgramSavedDirectory, "UnrealBuildTool", "Log.txt").FullName; } // Create the log file, and flush the startup listener to it if (!Arguments.HasOption("-NoLog") && !Log.HasFileWriter()) { FileReference LogFile = new FileReference(BaseLogFileName); foreach (string LogSuffix in Arguments.GetValues("-LogSuffix=")) { LogFile = LogFile.ChangeExtension(null) + "_" + LogSuffix + LogFile.GetExtension(); } TextWriterTraceListener LogTraceListener = Log.AddFileWriter("DefaultLogTraceListener", LogFile); StartupListener.CopyTo(LogTraceListener); } Trace.Listeners.Remove(StartupListener); // Create the build configuration object, and read the settings BuildConfiguration BuildConfiguration = new BuildConfiguration(); XmlConfig.ApplyTo(BuildConfiguration); Arguments.ApplyTo(BuildConfiguration); // Check the root path length isn't too long if (BuildHostPlatform.Current.Platform == UnrealTargetPlatform.Win64 && UnrealBuildTool.RootDirectory.FullName.Length > BuildConfiguration.MaxRootPathLength) { Log.TraceWarning("Running from a path with a long directory name (\"{0}\" = {1} characters). Root paths shorter than {2} characters are recommended to avoid exceeding maximum path lengths on Windows.", UnrealBuildTool.RootDirectory, UnrealBuildTool.RootDirectory.FullName.Length, BuildConfiguration.MaxRootPathLength); } // now that we know the available platforms, we can delete other platforms' junk. if we're only building specific modules from the editor, don't touch anything else (it may be in use). if (!bIgnoreJunk && !UnrealBuildTool.IsEngineInstalled()) { using (Timeline.ScopeEvent("DeleteJunk()")) { JunkDeleter.DeleteJunk(); } } // Parse and build the targets try { // Parse all the target descriptors List <TargetDescriptor> TargetDescriptors; using (Timeline.ScopeEvent("TargetDescriptor.ParseCommandLine()")) { TargetDescriptors = TargetDescriptor.ParseCommandLine(Arguments, BuildConfiguration.bUsePrecompiled, BuildConfiguration.bSkipRulesCompile); } // Hack for single file compile; don't build the ShaderCompileWorker target that's added to the command line for generated project files if (TargetDescriptors.Count >= 2) { TargetDescriptors.RemoveAll(x => (x.Name == "ShaderCompileWorker" || x.Name == "LiveCodingConsole") && x.SingleFileToCompile != null); } // Handle remote builds for (int Idx = 0; Idx < TargetDescriptors.Count; Idx++) { TargetDescriptor TargetDesc = TargetDescriptors[Idx]; if (RemoteMac.HandlesTargetPlatform(TargetDesc.Platform)) { FileReference BaseLogFile = Log.OutputFile ?? new FileReference(BaseLogFileName); FileReference RemoteLogFile = FileReference.Combine(BaseLogFile.Directory, BaseLogFile.GetFileNameWithoutExtension() + "_Remote.txt"); RemoteMac RemoteMac = new RemoteMac(TargetDesc.ProjectFile); if (!RemoteMac.Build(TargetDesc, RemoteLogFile)) { return((int)CompilationResult.Unknown); } TargetDescriptors.RemoveAt(Idx--); } } // Handle local builds if (TargetDescriptors.Count > 0) { // Get a set of all the project directories HashSet <DirectoryReference> ProjectDirs = new HashSet <DirectoryReference>(); foreach (TargetDescriptor TargetDesc in TargetDescriptors) { if (TargetDesc.ProjectFile != null) { DirectoryReference ProjectDirectory = TargetDesc.ProjectFile.Directory; FileMetadataPrefetch.QueueProjectDirectory(ProjectDirectory); ProjectDirs.Add(ProjectDirectory); } } // Get all the build options BuildOptions Options = BuildOptions.None; if (bSkipBuild) { Options |= BuildOptions.SkipBuild; } if (bXGEExport) { Options |= BuildOptions.XGEExport; } if (bNoEngineChanges) { Options |= BuildOptions.NoEngineChanges; } // Create the working set provider using (ISourceFileWorkingSet WorkingSet = SourceFileWorkingSet.Create(UnrealBuildTool.RootDirectory, ProjectDirs)) { Build(TargetDescriptors, BuildConfiguration, WorkingSet, Options, WriteOutdatedActionsFile); } } } finally { // Save all the caches SourceFileMetadataCache.SaveAll(); CppDependencyCache.SaveAll(); } return(0); }
internal static SourceReferenceResolver GetSourceReferenceResolver(CommandLineArguments arguments, TouchedFileLogger loggerOpt) { return(new CommonCompiler.LoggingSourceFileResolver(arguments.SourcePaths, arguments.BaseDirectory, ImmutableArray <KeyValuePair <string, string> > .Empty, loggerOpt)); }
static CommandLineOptions ProcessCommandLine(string[] args) { CommandLineOptions myArgs = new CommandLineOptions(); CommandLineArguments parser = new CommandLineArguments(); AddParameters(parser); try { parser.Parse(args, myArgs); } catch (Exception e) { Console.Error.WriteLine("\nException while processing Command Line arguments [{0}]", e.Message); Environment.Exit(-1); } if (myArgs.help) { Console.WriteLine(Resources.MumUtilHelp); Environment.Exit(-1); } /* * Process all the arguments for 'semantic' correctness */ if ((myArgs.maxmatch && myArgs.mum) || (myArgs.maxmatch && myArgs.mumreference) || (myArgs.mum && myArgs.mumreference) ) { Console.Error.WriteLine("\nError: only one of -maxmatch, -mum, -mumreference options can be specified."); Environment.Exit(-1); } if (!myArgs.mumreference && !myArgs.mum && !myArgs.maxmatch) { myArgs.mumreference = true; } if ((myArgs.fileList == null) || (myArgs.fileList.Length < 2)) { Console.Error.WriteLine("\nError: A reference file and at least 1 query file are required."); Environment.Exit(-1); } if ((myArgs.length <= 0) || (myArgs.length >= (8 * 1024))) // TODO: What are real reasonable mum length limits? { Console.Error.WriteLine("\nError: mum length must be between 1 and 1024."); Environment.Exit(-1); } if (myArgs.both && myArgs.reverseOnly) { Console.Error.WriteLine("\nError: only one of -both or -reverseOnly options can be specified."); Environment.Exit(-1); } if (myArgs.c && (!myArgs.both && !myArgs.reverseOnly)) { Console.Error.WriteLine("\nError: c requires one of either /b or /r options."); Environment.Exit(-1); } if (myArgs.outputFile != null) { // redirect stdout twConsoleOutSave = Console.Out; fsConsoleOut = new FileStream(myArgs.outputFile, FileMode.Create); swConsoleOut = new StreamWriter(fsConsoleOut); Console.SetOut(swConsoleOut); swConsoleOut.AutoFlush = true; } return(myArgs); }
/// <summary> /// Parses the command line arguments and initializes the object. /// </summary> /// <param name="args"> /// Command line arguments. /// </param> /// <returns> /// Parsed command line arguments. /// </returns> private static CommandLineArguments Initialize(string[] args) { const string ErrorMessage = "Incorrect arguments...\nUsage: WorldDataSet " + "/Input=<Input file name> " + "/Projection=<Projection Type - Mercator or Toast> " + "/ColorMap=<Color Map File> /ColorMapOrientation=<Horizontal or Vertical>" + "[/OutputDir=<Output Directory>] "; if (args == null || args.Length < 4) { Trace.TraceError("{0}: " + ErrorMessage, DateTime.Now.TimeOfDay.ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture)); return(null); } CommandLineArguments cmdLine = new CommandLineArguments(args); if (string.IsNullOrEmpty(cmdLine.Input)) { Trace.TraceError("{0}: " + ErrorMessage, DateTime.Now.TimeOfDay.ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture)); return(null); } if (!string.IsNullOrEmpty(cmdLine.Projection)) { ProjectionTypes tmp; if (!Enum.TryParse(cmdLine.Projection, true, out tmp)) { Trace.TraceError("{0}: " + ErrorMessage, DateTime.Now.TimeOfDay.ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture)); return(null); } } else { Trace.TraceError("{0}: " + ErrorMessage, DateTime.Now.TimeOfDay.ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture)); return(null); } if (string.IsNullOrWhiteSpace(cmdLine.OutputDir)) { string outputFolderName = string.Format(CultureInfo.InvariantCulture, "{0}_{1}_{2}", Path.GetFileNameWithoutExtension(cmdLine.Input), cmdLine.Projection, DateTime.Now.ToString("yyyyddMM-HHmmss", CultureInfo.InvariantCulture)); cmdLine.OutputDir = Path.Combine(TileHelper.DefaultOutputDirectory, outputFolderName); Trace.TraceInformation("{0}: Output directory {1}", DateTime.Now.TimeOfDay.ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture), cmdLine.OutputDir); } if (!Path.IsPathRooted(cmdLine.Input)) { cmdLine.Input = Path.GetFullPath(cmdLine.Input); } if (!Path.IsPathRooted(cmdLine.OutputDir)) { cmdLine.OutputDir = Path.GetFullPath(cmdLine.OutputDir); } if (!string.IsNullOrEmpty(cmdLine.ColorMapOrientation)) { ColorMapOrientation tmp; if (!Enum.TryParse(cmdLine.ColorMapOrientation, true, out tmp)) { Trace.TraceError("{0}: " + ErrorMessage, DateTime.Now.TimeOfDay.ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture)); return(null); } } return(cmdLine); }
public static string SetLocale(CommandLineArguments cmdLineArgs) { var supportedLocale = new HashSet<string>(new[] { "cs-CZ", "de-DE", "en-US", "es-ES", "fr-FR", "it-IT", "ja-JP", "ko-KR", "pl-PL", "pt-BR", "ru-RU", "zh-CN", "zh-TW" }); string libgLocale = string.Empty; if (!string.IsNullOrEmpty(cmdLineArgs.Locale)) { // Change the application locale, if a locale information is supplied. Thread.CurrentThread.CurrentUICulture = new CultureInfo(cmdLineArgs.Locale); Thread.CurrentThread.CurrentCulture = new CultureInfo(cmdLineArgs.Locale); libgLocale = cmdLineArgs.Locale; } else { // In case no language is specified, libG's locale should be that of the OS. // There is no need to set Dynamo's locale in this case. libgLocale = CultureInfo.InstalledUICulture.ToString(); } // If locale is not supported by Dynamo, default to en-US. if (!supportedLocale.Any(s => s.Equals(libgLocale, StringComparison.InvariantCultureIgnoreCase))) { libgLocale = "en-US"; } // Change the locale that LibG depends on. StringBuilder sb = new StringBuilder("LANGUAGE="); sb.Append(libgLocale.Replace("-", "_")); return sb.ToString(); }
public static int Math(CommandLineArguments arguments) { return CommandLine.Run<MathCommands>(arguments, "Help"); }
/// <summary> /// Parses the command line arguments and initializes the object. /// </summary> /// <param name="args"> /// Command line arguments. /// </param> /// <returns> /// Parsed command line arguments. /// </returns> private static CommandLineArguments Initialize(string[] args) { const string ErrorMessage = "Incorrect arguments..\nUsage: BlueMarbleApp /Input=<Input file>" + " /Projection=<Projection Type - Mercator or Toast> [/OutputDir=<Output Directory>]" + " [/InputBoundary=<Top Left Latitude, Top Left Longitude, Bottom Right Latitude, Bottom Right Longitude>]"; if (args == null || args.Length < 2) { Trace.TraceError("{0}: " + ErrorMessage, DateTime.Now.TimeOfDay.ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture)); return null; } CommandLineArguments cmdLine = new CommandLineArguments(args); if (string.IsNullOrEmpty(cmdLine.Input)) { Trace.TraceError("{0}: " + ErrorMessage, DateTime.Now.TimeOfDay.ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture)); return null; } if (!string.IsNullOrEmpty(cmdLine.Projection)) { ProjectionTypes projection; if (!Enum.TryParse(cmdLine.Projection, true, out projection)) { Trace.TraceError("{0}: " + ErrorMessage, DateTime.Now.TimeOfDay.ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture)); return null; } } else { Trace.TraceError("{0}: " + ErrorMessage, DateTime.Now.TimeOfDay.ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture)); return null; } if (string.IsNullOrWhiteSpace(cmdLine.OutputDir)) { string outputFolderName = string.Format(CultureInfo.InvariantCulture, "{0}_{1}_{2}", Path.GetFileNameWithoutExtension(cmdLine.Input), cmdLine.Projection, DateTime.Now.ToString("yyyyddMM-HHmmss", CultureInfo.InvariantCulture)); cmdLine.OutputDir = Path.Combine(TileHelper.DefaultOutputDirectory, outputFolderName); Trace.TraceInformation("{0}: Output directory {1}", DateTime.Now.TimeOfDay.ToString(@"hh\:mm\:ss", CultureInfo.InvariantCulture), cmdLine.OutputDir); } if (!Path.IsPathRooted(cmdLine.Input)) { cmdLine.Input = Path.GetFullPath(cmdLine.Input); } if (!Path.IsPathRooted(cmdLine.OutputDir)) { cmdLine.OutputDir = Path.GetFullPath(cmdLine.OutputDir); } return cmdLine; }
private static ScriptOptions GetScriptOptions(CommandLineArguments arguments) { // TODO: reference paths, usings from arguments (https://github.com/dotnet/roslyn/issues/5277) // TODO: auto -add facades return ScriptOptions.Default. AddReferences("System", "System.Core", "System.Runtime", "System.IO.FileSystem", "System.IO.FileSystem.Primitives", "System.Collections"). AddNamespaces("System", "System.IO", "System.Threading.Tasks", "System.Linq"); }
private static void StopBridgeIfLocal(CommandLineArguments commandLineArgs) { if (IsBridgeHostLocal(commandLineArgs.BridgeConfiguration)) { StopBridge(commandLineArgs); } else { Console.WriteLine("The Bridge on host {0} is not running locally and will not be stopped.", commandLineArgs.BridgeConfiguration.BridgeHost); Console.WriteLine("Use 'Bridge.exe /stop' to stop a Bridge on another machine."); } }
public static void ProcessLogFilesOnly(Stopwatch Watch, CommandLineArguments ParsedCommandLineArguments) { try { bool _personIdentifierIsNumber = false; if (ParsedCommandLineArguments.Flags.Contains("NUMERICPERSONIDENTIFIER")) { _personIdentifierIsNumber = true; } string _personIdentifier = "PersonIdentifier"; if (ParsedCommandLineArguments.ParameterDictionary.ContainsKey("personidentifier")) { _personIdentifier = ParsedCommandLineArguments.ParameterDictionary["personidentifier"]; } string _language = "ENG"; if (ParsedCommandLineArguments.ParameterDictionary.ContainsKey("language")) { _language = ParsedCommandLineArguments.ParameterDictionary["language"]; } List <string> _listOfXMLFiles = new List <string>(); List <string> _listOfZIPArchivesWithXMLFiles = new List <string>(); foreach (string inFolder in ParsedCommandLineArguments.Transform_InputFolders) { if (File.Exists(inFolder)) { if (inFolder.ToLower().EndsWith(".zip")) { _listOfZIPArchivesWithXMLFiles.Add(inFolder); } else if (inFolder.ToLower().EndsWith(".xml")) { _listOfXMLFiles.Add(inFolder); } } else { if (!Directory.Exists(inFolder)) { if (ParsedCommandLineArguments.Verbose) { Console.WriteLine("Warning: Directory not exists: '" + inFolder + "'."); } continue; } var _tmpXMLFileList = Directory.GetFiles(inFolder, "*.xml", SearchOption.AllDirectories); foreach (string s in _tmpXMLFileList) { _listOfXMLFiles.Add(s); } var _tmpZIPFileList = Directory.GetFiles(inFolder, "*.zip", SearchOption.AllDirectories); foreach (string s in _tmpZIPFileList) { _listOfZIPArchivesWithXMLFiles.Add(s); } } } logXContainer _ret = new logXContainer() { PersonIdentifierIsNumber = _personIdentifierIsNumber, PersonIdentifierName = _personIdentifier }; _ret.LoadCodebookDictionary(ParsedCommandLineArguments.Transform_Dictionary); if (ParsedCommandLineArguments.Transform_ConcordanceTable.Trim() != "") { if (File.Exists(ParsedCommandLineArguments.Transform_ConcordanceTable)) { if (ParsedCommandLineArguments.Verbose) { Console.WriteLine("Read Concordance Table."); } _ret.ReadConcordanceTable(ParsedCommandLineArguments.Transform_ConcordanceTable); } } foreach (string zfilename in _listOfZIPArchivesWithXMLFiles) { using (ZipFile zip = ZipFile.Read(zfilename)) { foreach (var entry in zip) { if (ParsedCommandLineArguments.MaxNumberOfCases > 0 && _ret.GetNumberOfPersons >= ParsedCommandLineArguments.MaxNumberOfCases) { break; } // TODO: Check FitsMask if (1 == 1 || CommandLineArguments.FitsMask(entry.FileName, ParsedCommandLineArguments.Mask)) { if (ParsedCommandLineArguments.Verbose) { Console.Write("Info: Read File '" + entry.FileName + "' "); } using (MemoryStream zipStream = new MemoryStream()) { entry.ExtractWithPassword(zipStream, ""); zipStream.Position = 0; try { StreamReader sr = new StreamReader(zipStream); string _fileContentAsString = sr.ReadToEnd(); if (_fileContentAsString.Trim().Length > 0) { ReadLogDataEEFromXMLString(_fileContentAsString, _ret); } } catch (Exception _ex) { Console.WriteLine("Error processing file '" + entry.FileName + "': " + _ex.Message); return; } } Console.WriteLine("ok."); } } } if (ParsedCommandLineArguments.MaxNumberOfCases > 0 && _ret.GetNumberOfPersons >= ParsedCommandLineArguments.MaxNumberOfCases) { if (ParsedCommandLineArguments.Verbose) { Console.WriteLine("Info: Max number of cases reached."); } break; } } foreach (string xfilename in _listOfXMLFiles) { if (ParsedCommandLineArguments.MaxNumberOfCases > 0 && _ret.GetNumberOfPersons >= ParsedCommandLineArguments.MaxNumberOfCases) { if (ParsedCommandLineArguments.Verbose) { Console.WriteLine("Info: Max number of cases reached."); } break; } if (1 == 1 || CommandLineArguments.FitsMask(Path.GetFileName(xfilename), ParsedCommandLineArguments.Mask)) { if (ParsedCommandLineArguments.Verbose) { Console.WriteLine("Info: Read File '" + Path.GetFileName(xfilename) + "' "); } try { StreamReader sr = new StreamReader(xfilename); string _fileContentAsString = sr.ReadToEnd(); if (_fileContentAsString.Trim().Length > 0) { ReadLogDataEEFromXMLString(_fileContentAsString, _ret); } } catch (Exception _ex) { Console.WriteLine("Error processing file '" + xfilename + "': " + _ex.Message); return; } Console.WriteLine("ok."); } } _ret.UpdateRelativeTimes(); _ret.CreateLookup(); if (ParsedCommandLineArguments.Transform_OutputStata.Trim() != "") { if (ParsedCommandLineArguments.Verbose) { Console.WriteLine("Create ZIP archive with Stata file(s)."); } _ret.ExportStata(ParsedCommandLineArguments.Transform_OutputStata, _language); } if (ParsedCommandLineArguments.Transform_OutputXLSX.Trim() != "") { if (ParsedCommandLineArguments.Verbose) { Console.WriteLine("Create XLSX file."); } _ret.ExportXLSX(ParsedCommandLineArguments); } if (ParsedCommandLineArguments.Transform_OutputZCSV.Trim() != "") { if (ParsedCommandLineArguments.Verbose) { Console.WriteLine("Create ZIP archive with CSV file(s)."); } _ret.ExportCSV(ParsedCommandLineArguments); } if (ParsedCommandLineArguments.Transform_Codebook.Trim() != "") { if (ParsedCommandLineArguments.Verbose) { Console.WriteLine("Create Codebook File."); } _ret.CreateCodebook(ParsedCommandLineArguments.Transform_Codebook, _language); } if (ParsedCommandLineArguments.Transform_ConcordanceTable.Trim() != "") { if (!File.Exists(ParsedCommandLineArguments.Transform_ConcordanceTable)) { if (ParsedCommandLineArguments.Verbose) { Console.WriteLine("Create Concordance Table."); } _ret.CreateConcordanceTable(ParsedCommandLineArguments.Transform_ConcordanceTable); } } if (_ret.ExportErrors.Count > 0) { Console.WriteLine(_ret.ExportErrors.Count + " error(s) creating output files."); if (ParsedCommandLineArguments.Verbose) { for (int i = 0; i < _ret.ExportErrors.Count; i++) { Console.WriteLine(_ret.ExportErrors[i]); } } } } catch (Exception _ex) { Console.WriteLine("Error transforming log data. Details: " + Environment.NewLine + _ex.Message.ToString()); } }
// Starts the Bridge locally if it is not already running. private static void StartBridge(CommandLineArguments commandLineArgs) { string errorMessage = null; if (PingBridge(commandLineArgs.BridgeConfiguration.BridgeHost, commandLineArgs.BridgeConfiguration.BridgePort, out errorMessage)) { Console.WriteLine("The Bridge is already running."); Environment.Exit(0); } // The host is not local so we cannot start the Bridge if (!IsBridgeHostLocal(commandLineArgs.BridgeConfiguration)) { Console.WriteLine("The Bridge cannot be started from this machine on {0}", commandLineArgs.BridgeConfiguration.BridgeHost); Environment.Exit(1); } string resourceFolder = commandLineArgs.BridgeConfiguration.BridgeResourceFolder; if (String.IsNullOrWhiteSpace(resourceFolder)) { Console.WriteLine("Starting the Bridge requires the BridgeResourceFolder to be specified."); Console.WriteLine("Use either -BridgeResourceFolder:folderName or set it as an environment variable."); Environment.Exit(1); } resourceFolder = Path.GetFullPath(resourceFolder); if (!Directory.Exists(resourceFolder)) { Console.WriteLine("The specified BridgeResourceFolder '{0}' does not exist."); Environment.Exit(1); } commandLineArgs.BridgeConfiguration.BridgeResourceFolder = resourceFolder; int port = commandLineArgs.BridgeConfiguration.BridgePort; string hostFormatString = "http://{0}:{1}"; string owinAddress = String.Format(hostFormatString, commandLineArgs.AllowRemote ? "+" : "localhost", port); string visibleHost = (commandLineArgs.AllowRemote) ? Environment.MachineName : "localhost"; string visibleAddress = String.Format(hostFormatString, visibleHost, port); // Configure the remote addresses the firewall rules will accept. // If remote access is not allowed, specifically disallow remote addresses PortManager.RemoteAddresses = commandLineArgs.AllowRemote ? commandLineArgs.RemoteAddresses : String.Empty; // Initialize the BridgeConfiguration from command line. ConfigController.BridgeConfiguration = commandLineArgs.BridgeConfiguration; ConfigController.BridgeConfiguration.BridgeHost = visibleHost; // Remove any pre-existing firewall rules or certificates the Bridge // may have added in past runs. We normally clean them up on exit but // it is possible a prior Bridge process was terminated prematurely. BridgeController.ReleaseAllResources(force: false); Console.WriteLine("Starting the Bridge at {0}", visibleAddress); OwinSelfhostStartup.Startup(owinAddress); // Now test whether the Bridge is running. Failure cleans up // all resources and terminates the process. if (!PingBridge(visibleHost, port, out errorMessage)) { Console.WriteLine("The Bridge failed to start or is not responding: {0}", errorMessage); BridgeController.StopBridgeProcess(1); } while (true) { Console.WriteLine(); Console.WriteLine("The Bridge is running"); Console.WriteLine(" Listening at {0}/{1}", visibleAddress, BridgeControllerEndpoint); if (commandLineArgs.AllowRemote) { Console.WriteLine(" Remote access is allowed from '{0}'", commandLineArgs.RemoteAddresses); } else { Console.WriteLine(" Remote access is disabled."); } Console.WriteLine(" Commands:"); Console.WriteLine(" \"cls\" to clear the screen"); Console.WriteLine(" \"exit\" to stop the Bridge"); Console.WriteLine(); Console.Write("Bridge> "); string answer = Console.ReadLine(); if (string.Equals(answer, "exit", StringComparison.OrdinalIgnoreCase)) { break; } else if (string.Equals(answer, "cls", StringComparison.OrdinalIgnoreCase)) { Console.Clear(); } } BridgeController.StopBridgeProcess(0); }
static void Main(string[] args) { // Try to enlarge the window. try { Console.SetWindowSize(Console.LargestWindowWidth * 8 / 9, Console.LargestWindowHeight * 8 / 9); } catch (Exception) {} // Create the name of the local working copy. string workingCopy = DateTime.UtcNow.ToString("d", CultureInfo.CreateSpecificCulture("en-US")).Replace('/', '-'); string fullPath = Path.GetFullPath(workingCopy); if (!Directory.Exists(fullPath)) { Directory.CreateDirectory(fullPath); } Environment.CurrentDirectory = WorkingCopy = fullPath; CommandLine.DisplayGoogleSampleHeader("Release Builder: " + workingCopy); CommandLine.EnableExceptionHandling(); // Parse command line arguments. CommandLine.ParseArguments(Arguments = new CommandLineArguments(), args); // 1. Create the local repositories. CheckoutRepositories(); // Clean up the default/ repository by removing cache-files. string toDelete = Default.Combine("_ReSharper.GoogleApisClient"); if (Directory.Exists(toDelete)) { Directory.Delete(toDelete, true); } foreach (string pattern in new[] { "*.dotcover", "*.user", "*.suo" }) { foreach (string file in Directory.GetFiles(Default.WorkingDirectory, pattern)) { File.Delete(file); } } // 2. Create the project/build tasks. FileVersionInfo apiVersion; Project[] allProjects; Project[] baseLibrary = BuildProjects(out apiVersion, out allProjects); Project servicegen = baseLibrary.Where(proj => proj.Name == "GoogleApis.Tools.ServiceGenerator").Single(); // Retrieve tag name. string tag = GetTagName(apiVersion); if (Arguments.IsStableRelease) { UpdateSamples(baseLibrary, servicegen); } // 4. Build contrib. string notes = CreateChangelog(tag); string zipDir; notes = BuildContribRelease(tag, notes, baseLibrary, allProjects, servicegen, out zipDir); // 5. Update the Wiki. if (Arguments.IsStableRelease) { UpdateWiki(notes, zipDir); } // Ask the user whether he wants to continue the release. string res = "no"; CommandLine.WriteLine("{{white}} ======================================="); CommandLine.WriteResult("Version: ", apiVersion.ProductVersion); CommandLine.WriteLine(); if (Arguments.UseLocalRepository) { CommandLine.WriteAction("Local build done."); CommandLine.PressAnyKeyToExit(); return; } // 6. Commit & tag the release CommitAndTagRelease(tag); CommandLine.WriteLine(" {{gray}}In the next step all changes will be commited and tagged."); CommandLine.WriteLine(" {{gray}}Only continue when you are sure that you don't have to make any new changes."); CommandLine.RequestUserInput("Do you want to continue with the release? Type YES.", ref res); CommandLine.WriteLine(); if (res == "YES") { // Check for incoming changes foreach (Hg repository in AllRepositories) { if (repository.HasIncomingChanges) { CommandLine.WriteError( "Repository [{0}] has incoming changes. Run hg pull & update first!", repository.Name); CommandLine.PressAnyKeyToExit(); return; } } // 7. Push PushChanges(); } CommandLine.PressAnyKeyToExit(); }
private static ScriptOptions GetScriptOptions(CommandLineArguments arguments, string scriptPathOpt, CommonMessageProvider messageProvider, List<DiagnosticInfo> diagnostics) { var touchedFilesLoggerOpt = (arguments.TouchedFilesPath != null) ? new TouchedFileLogger() : null; var metadataResolver = GetMetadataReferenceResolver(arguments, touchedFilesLoggerOpt); var sourceResolver = GetSourceReferenceResolver(arguments, touchedFilesLoggerOpt); var resolvedReferences = new List<MetadataReference>(); if (!arguments.ResolveMetadataReferences(metadataResolver, diagnostics, messageProvider, resolvedReferences)) { // can't resolve some references return null; } return new ScriptOptions( filePath: scriptPathOpt ?? "", references: ImmutableArray.CreateRange(resolvedReferences), namespaces: CommandLineHelpers.GetImports(arguments), metadataResolver: metadataResolver, sourceResolver: sourceResolver); }
/// <summary> /// Used to ask and then print out extended information about a specific frame /// </summary> /// <param name="hParsedFrame">Parsed Frame</param> /// <param name="frameNumber">Frame Number to Display</param> /// <param name="command">Command Line Parameters</param> private static void PrintParsedFrameInformation(IntPtr hParsedFrame, uint frameNumber, CommandLineArguments command) { uint errno; uint ulFieldCount; string ds = "Frame #" + (frameNumber + 1); // Is Selected if (command.IsSelected(frameNumber)) { ds += " (Selected)"; } // Get Frame Timestamp ulong timestamp; errno = NetmonAPI.NmGetFrameTimeStamp(hParsedFrame, out timestamp); if (errno == ERROR_SUCCESS) { ds += " " + DateTime.FromFileTimeUtc((long)timestamp).ToString(); } else { ds += " Timestamp Couldn't be Retrieved."; } Console.WriteLine(ds); Console.Write("Print Frame Info? (y/n) "); char key = Console.ReadKey().KeyChar; Console.WriteLine(); if (key == 'y' || key == 'Y') { errno = NetmonAPI.NmGetFieldCount(hParsedFrame, out ulFieldCount); for (uint fid = 0; fid < ulFieldCount; fid++) { // Get Field Name char[] name = new char[BUFFER_SIZE * 2]; unsafe { fixed(char *pstr = name) { errno = NetmonAPI.NmGetFieldName(hParsedFrame, fid, NmParsedFieldNames.NamePath, BUFFER_SIZE * 2, pstr); } } if (errno == ERROR_SUCCESS) { Console.Write(new string(name).Replace("\0", string.Empty) + ": "); } else { Console.WriteLine("Error Retrieving Field, NmGetFieldName Returned: " + errno); continue; } // Get Field Value as displayed in Netmon UI name = new char[BUFFER_SIZE]; unsafe { fixed(char *pstr = name) { errno = NetmonAPI.NmGetFieldName(hParsedFrame, fid, NmParsedFieldNames.FieldDisplayString, BUFFER_SIZE, pstr); } } if (errno == ERROR_SUCCESS) { Console.WriteLine(new string(name).Replace("\0", string.Empty)); } else if (errno == ERROR_NOT_FOUND) { Program.PrintParsedFrameFieldValue(hParsedFrame, fid); } else { Console.WriteLine("Error Retrieving Value, NmGetFieldName Returned: " + errno); continue; } } Console.WriteLine(); } }
private static ScriptOptions GetScriptOptions(CommandLineArguments arguments, string scriptPathOpt, CommonMessageProvider messageProvider, List<DiagnosticInfo> diagnostics) { var touchedFilesLoggerOpt = (arguments.TouchedFilesPath != null) ? new TouchedFileLogger() : null; var metadataResolver = GetMetadataReferenceResolver(arguments, touchedFilesLoggerOpt); var sourceResolver = GetSourceReferenceResolver(arguments, touchedFilesLoggerOpt); var resolvedReferences = new List<MetadataReference>(); if (!arguments.ResolveMetadataReferences(metadataResolver, diagnostics, messageProvider, resolvedReferences)) { // can't resolve some references return null; } // TODO: https://github.com/dotnet/roslyn/issues/5854 var importedNamespaces = arguments.CompilationOptions.GetImports(); return new ScriptOptions( filePath: scriptPathOpt ?? "", references: ImmutableArray.CreateRange(resolvedReferences), namespaces: importedNamespaces, metadataResolver: metadataResolver, sourceResolver: sourceResolver); }
public static void Main(string[] args) { // Load API try { initialized = Program.InitializeNMAPI(); } catch (BadImageFormatException) { Console.WriteLine("There was an error loading the NMAPI.\n\nPlease ensure you have the correct version installed for your platform."); } catch (DllNotFoundException) { Console.WriteLine("There was an error loading the NMAPI DLL.\n\nPlease ensure you have Network Monitor 3.3 installed or try rebooting."); } CommandLineArguments commandReader = new CommandLineArguments(); if (commandReader.ParseCommandLineArguments(args)) { if (commandReader.IsNoArguments) { Console.WriteLine(CommandLineArguments.GetUsage("ExpertExample")); } else if (commandReader.IsRequestingHelp) { Console.WriteLine(CommandLineArguments.GetUsage("ExpertExample")); } else if (initialized) { Console.WriteLine("Running Test Application with Arguments:"); Console.WriteLine("\tCapture File: " + commandReader.CaptureFileName); Console.WriteLine("\tDisplay Filter: " + commandReader.DisplayFilter); Console.WriteLine("\tConversation Filter: " + commandReader.ConversationFilter); Console.WriteLine("\tSelected Frames: " + commandReader.SelectedFramesString); Console.WriteLine(); bool loadedparserengine = false; // Configure Parser Engine uint errno; IntPtr hNplParser = IntPtr.Zero; IntPtr hFrameParserConfig = IntPtr.Zero; uint conversationFilterId = 0; uint displayFilterId = 0; IntPtr hFrameParser = IntPtr.Zero; // Only load the parsing engine if we have to if (!string.IsNullOrEmpty(commandReader.ConversationFilter) || !string.IsNullOrEmpty(commandReader.DisplayFilter)) { Console.WriteLine("Loading Parser Engine..."); // Passing in null for the path will use the default configuration as specified in the Netmon UI errno = NetmonAPI.NmLoadNplParser(null, NmNplParserLoadingOption.NmAppendRegisteredNplSets, pErrorCallBack, IntPtr.Zero, out hNplParser); if (errno == ERROR_SUCCESS) { // Configure Frame Parser errno = NetmonAPI.NmCreateFrameParserConfiguration(hNplParser, pErrorCallBack, IntPtr.Zero, out hFrameParserConfig); if (errno == ERROR_SUCCESS) { // Enable Conversations errno = NetmonAPI.NmConfigConversation(hFrameParserConfig, NmConversationConfigOption.None, true); if (errno == ERROR_SUCCESS) { // Add Filters if (!string.IsNullOrEmpty(commandReader.ConversationFilter)) { Console.WriteLine("Adding Conversation Filter..."); errno = NetmonAPI.NmAddFilter(hFrameParserConfig, commandReader.ConversationFilter, out conversationFilterId); } if (errno == ERROR_SUCCESS) { if (!string.IsNullOrEmpty(commandReader.DisplayFilter)) { Console.WriteLine("Adding Display Filter..."); errno = NetmonAPI.NmAddFilter(hFrameParserConfig, commandReader.DisplayFilter, out displayFilterId); } if (errno == ERROR_SUCCESS) { errno = NetmonAPI.NmCreateFrameParser(hFrameParserConfig, out hFrameParser, NmFrameParserOptimizeOption.ParserOptimizeNone); if (errno == ERROR_SUCCESS) { Console.WriteLine("Parser Engine Loaded Successfully!"); Console.WriteLine(); loadedparserengine = true; } else { Console.WriteLine("Parser Creation Error Number = " + errno); } } else { Console.WriteLine("Display Filter Creation Error Number = " + errno); } } else { Console.WriteLine("Conversation Filter Creation Error Number = " + errno); } } else { Console.WriteLine("Conversation Error Number = " + errno); } if (!loadedparserengine) { NetmonAPI.NmCloseHandle(hFrameParserConfig); } } else { Console.WriteLine("Parser Configuration Error Number = " + errno); } if (!loadedparserengine) { NetmonAPI.NmCloseHandle(hNplParser); } } else { Console.WriteLine("Error Loading NMAPI Parsing Engine Error Number = " + errno); } } // Wait for confirmation Console.WriteLine("Press any key to continue"); Console.ReadKey(true); // Let's open the capture file // Open Capture File IntPtr captureFile = IntPtr.Zero; errno = NetmonAPI.NmOpenCaptureFile(commandReader.CaptureFileName, out captureFile); if (errno == ERROR_SUCCESS) { // Retrieve the number of frames in this capture file uint frameCount; errno = NetmonAPI.NmGetFrameCount(captureFile, out frameCount); if (errno == ERROR_SUCCESS) { // Loop through capture file for (uint ulFrameNumber = 0; ulFrameNumber < frameCount; ulFrameNumber++) { // Get the Raw Frame data IntPtr hRawFrame = IntPtr.Zero; errno = NetmonAPI.NmGetFrame(captureFile, ulFrameNumber, out hRawFrame); if (errno != ERROR_SUCCESS) { Console.WriteLine("Error Retrieving Frame #" + (ulFrameNumber + 1) + " from file"); continue; } // Need to parse once to get similar results to the UI if (loadedparserengine) { // Parse Frame IntPtr phParsedFrame; IntPtr phInsertedRawFrame; errno = NetmonAPI.NmParseFrame(hFrameParser, hRawFrame, ulFrameNumber, NmFrameParsingOption.FieldDisplayStringRequired | NmFrameParsingOption.FieldFullNameRequired | NmFrameParsingOption.DataTypeNameRequired, out phParsedFrame, out phInsertedRawFrame); if (errno == ERROR_SUCCESS) { // Check against Filters if (!string.IsNullOrEmpty(commandReader.ConversationFilter)) { bool passed; errno = NetmonAPI.NmEvaluateFilter(phParsedFrame, conversationFilterId, out passed); if (errno == ERROR_SUCCESS) { if (passed) { if (!string.IsNullOrEmpty(commandReader.DisplayFilter)) { bool passed2; errno = NetmonAPI.NmEvaluateFilter(phParsedFrame, displayFilterId, out passed2); if (errno == ERROR_SUCCESS) { if (passed2) { PrintParsedFrameInformation(phParsedFrame, ulFrameNumber, commandReader); } } } else { PrintParsedFrameInformation(phParsedFrame, ulFrameNumber, commandReader); } } } } else if (!string.IsNullOrEmpty(commandReader.DisplayFilter)) { bool passed; errno = NetmonAPI.NmEvaluateFilter(phParsedFrame, displayFilterId, out passed); if (errno == ERROR_SUCCESS) { if (passed) { PrintParsedFrameInformation(phParsedFrame, ulFrameNumber, commandReader); } } } else { PrintParsedFrameInformation(phParsedFrame, ulFrameNumber, commandReader); } NetmonAPI.NmCloseHandle(phInsertedRawFrame); NetmonAPI.NmCloseHandle(phParsedFrame); } else { Console.WriteLine("Error Parsing Frame #" + (ulFrameNumber + 1) + " from file"); } } else { // Just print what I just deleted... uint pulLength; errno = NetmonAPI.NmGetRawFrameLength(hRawFrame, out pulLength); if (errno == ERROR_SUCCESS) { if (commandReader.IsSelected(ulFrameNumber)) { Console.WriteLine("Frame #" + (ulFrameNumber + 1) + " (Selected) Frame Length(bytes): " + pulLength); } else { Console.WriteLine("Frame #" + (ulFrameNumber + 1) + " Frame Length(bytes): " + pulLength); } } else { Console.WriteLine("Error Getting Frame Length for Frame #" + (ulFrameNumber + 1)); } } NetmonAPI.NmCloseHandle(hRawFrame); } } else { Console.WriteLine("Error Retrieving Capture File Length"); } // Close Capture File to Cleanup NetmonAPI.NmCloseHandle(captureFile); } else { Console.WriteLine("Could not open capture file: " + commandReader.CaptureFileName); Console.WriteLine(CommandLineArguments.GetUsage("ExpertExample")); } if (loadedparserengine) { NetmonAPI.NmCloseHandle(hFrameParser); NetmonAPI.NmCloseHandle(hFrameParserConfig); NetmonAPI.NmCloseHandle(hNplParser); } } } else { Console.WriteLine(commandReader.LastErrorMessage); Console.WriteLine(CommandLineArguments.GetUsage("ExpertExample")); } // Pause so we can see the results when launched from Network Monitor Console.WriteLine(); Console.WriteLine("Press any key to continue"); Console.ReadKey(); if (initialized) { CloseNMAPI(); } }
internal static SourceReferenceResolver GetSourceReferenceResolver(CommandLineArguments arguments, TouchedFileLogger loggerOpt) { return new CommonCompiler.LoggingSourceFileResolver(arguments.SourcePaths, arguments.BaseDirectory, loggerOpt); }
/// <summary> /// Serves as the main entry point of the application. /// </summary> /// /// <param name="args">The set of command line arguments passed.</param> /// public static async Task Main(string[] args) { // Parse the command line arguments determine if help was explicitly requested or if the // needed information was passed. CommandLineArguments parsedArgs = ParseArguments(args); if (parsedArgs.Help) { DisplayHelp(); return; } // Display the welcome message. Console.WriteLine(); Console.WriteLine("========================================="); Console.WriteLine("Welcome to the Event Hubs client library!"); Console.WriteLine("========================================="); Console.WriteLine(); ISample sample = RetrieveSample(); if (sample == null) { Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Quitting..."); Console.WriteLine(); return; } else { Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("-------------------------------------------------------------------------"); Console.WriteLine($"Running: { sample.Name }"); Console.WriteLine("-------------------------------------------------------------------------"); Console.WriteLine(); } // Run the chosen sample if (sample is IEventHubsSample eventHubsSample) { PromptConnectionStringIfMissing(parsedArgs); PromptEventHubNameIfMissing(parsedArgs); await eventHubsSample.RunAsync(parsedArgs.ConnectionString, parsedArgs.EventHub); } else if (sample is IEventHubsIdentitySample identitySample) { PromptFullyQualifiedNamespaceIfMissing(parsedArgs); PromptEventHubNameIfMissing(parsedArgs); PromptTenantIdIfMissing(parsedArgs); PromptClientIdIfMissing(parsedArgs); PromptSecretIfMissing(parsedArgs); await identitySample.RunAsync(parsedArgs.FullyQualifiedNamespace, parsedArgs.EventHub, parsedArgs.Tenant, parsedArgs.Client, parsedArgs.Secret); } }