public void EnableControls() { SaveExtractedDocs.CheckState = Properties.Settings.Default.SaveDocs ? CheckState.Checked : CheckState.Unchecked; LibraryGen.CheckState = Properties.Settings.Default.GenLib ? CheckState.Checked : CheckState.Unchecked; Verbose.CheckState = Properties.Settings.Default.Verbose ? CheckState.Checked : CheckState.Unchecked; LibraryGen.Enabled = true; LibraryGen.Update(); SaveExtractedDocs.Enabled = true; SaveExtractedDocs.Update(); Verbose.Enabled = true; Verbose.Update(); FileHistory.Enabled = true; FileHistory.Update(); button1.Enabled = true; button1.Update(); SelectSource.Enabled = true; SelectSource.Update(); CleanUp.Enabled = true; CleanUp.Update(); LaunchPCBNew.Enabled = (PcbnewLocation != "" && FileHistory.Items.Count != 0)?true:false; LaunchPCBNew.Update(); Edit.Enabled = (TextEditorLoc != "" && FileHistory.Items.Count != 0) ? true : false; Edit.Update(); ClearHistory.Enabled = FileHistory.Items.Count != 0; ClearHistory.Update(); }
internal static IDictionary <string, object>?ProduceAdditionalData(this ITemplateInfo template, IReadOnlyList <IAdditionalDataProducer> producers, IEngineEnvironmentSettings environmentSettings) { Dictionary <string, object>?additionalData = new Dictionary <string, object>(); foreach (var producer in producers) { try { var data = producer.CreateDataForTemplate(template, environmentSettings); if (data != null) { additionalData[producer.DataUniqueName] = data; } } catch (TaskCanceledException) { throw; } catch (Exception ex) { Verbose.WriteLine($"Failed to produce additional data for {template.Name} with producer {producer.DataUniqueName}, details: {ex}"); } } if (additionalData.Any()) { return(additionalData); } return(null); }
private void ProcessNonTemplatePackage( IDownloadedPackInfo sourceInfo, string filterReason, Dictionary <string, FilteredPackageInfo> filteredPackages, ScanningStats scanningStats, string?oldTemplatePackageVersion, string?oldNonTemplatePackageVersion) { Verbose.WriteLine($"{sourceInfo.Name}::{sourceInfo.Version} is skipped, {filterReason}"); filteredPackages[sourceInfo.Name] = new FilteredPackageInfo(sourceInfo, filterReason); if (string.IsNullOrWhiteSpace(oldNonTemplatePackageVersion)) { if (string.IsNullOrWhiteSpace(oldTemplatePackageVersion)) { scanningStats.NewNonTemplatePacksCount++; } else { scanningStats.BecameNonTemplatePacksCount++; } } else { if (string.IsNullOrWhiteSpace(oldTemplatePackageVersion)) { scanningStats.UpdatedNonTemplatePacksCount++; } } }
private static async Task DownloadUriToFileAsync(string uri, string filePath, CancellationToken cancellationToken) { try { HttpClientHandler handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }; using (HttpClient client = new HttpClient(handler)) { using (HttpResponseMessage response = await client.GetAsync(uri, cancellationToken).ConfigureAwait(false)) { response.EnsureSuccessStatusCode(); string resultText = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); File.WriteAllText(filePath, resultText); Verbose.WriteLine($"{uri} was successfully downloaded to {filePath}."); return; } } } catch (TaskCanceledException) { throw; } catch (Exception e) { Console.WriteLine("Failed to download {0}, details: {1}", uri, e); throw; } }
/// <summary> /// Handle the Stylesheet command. /// </summary> /// <param name="line">Stylesheet</param> private void CmdStylesheet(string line) { if (line.Length == 0) { Errors.Error("Usage: " + UsStylesheet + " (" + lineNo + ")"); } else { if (styles == null) { if (File.Exists(line)) { styles = line; Verbose.Out("Setting new stylesheet: " + styles); } else { Errors.Error("Cannot read new stylesheet: " + line); } } else { Verbose.Out("Stylesheet already set from command line"); } } }
/// <summary> /// Handle the Phantom command. /// </summary> /// <param name="line">Phantom specification</param> private void CmdPhantom(string line) { if (calculate) { Verbose.Out("Calculation mode - skipping Phantom"); return; } char[] seps = new char[] { ' ' }; string[] a; a = line.Split(seps, StringSplitOptions.RemoveEmptyEntries); if (a.Length < 2) { Errors.Error("Usage: " + UsPhantom + " (" + lineNo + ")"); } else { Phantom p; if (a.Length == 2) { p = new Phantom(this, a[0], res, a[1]); } else { p = new Phantom(this, a[0], res, a[1], a[2]); } p.SetStack(srvsPrPhantom); Verbose.Out("Adding phantom to phantomslist: " + p.name + " (" + lineNo + ")"); AddToPhantomList(p); } }
public static void SaveConfig() { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); SetConfigValue(config, "AzureAccountKey", AzureAccountKey); SetConfigValue(config, "AzureAccountName", AzureAccountName); SetConfigValue(config, "SignatureSize", SignatureSize.ToString()); SetConfigValue(config, "IsDev", IsDev); SetConfigValue(config, "RetryAttemptDelayInSeconds", RetryAttemptDelayInSeconds.ToString()); SetConfigValue(config, "MaxRetryAttempts", MaxRetryAttempts.ToString()); SetConfigValue(config, "DownloadDirectory", DownloadDirectory); SetConfigValue(config, "Verbose", Verbose.ToString()); SetConfigValue(config, "AmDownloading", AmDownloading.ToString()); SetConfigValue(config, "UseBlobCopy", UseBlobCopy.ToString()); SetConfigValue(config, "ListContainer", ListContainer.ToString()); SetConfigValue(config, "MonitorBlobCopy", MonitorBlobCopy.ToString()); SetConfigValue(config, "ParallelFactor", ParallelFactor.ToString()); SetConfigValue(config, "ChunkSizeInMB", ChunkSizeInMB.ToString()); SetConfigValue(config, "SharedAccessSignatureDurationInSeconds", SharedAccessSignatureDurationInSeconds.ToString()); config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); }
public override string ToString() { string tsout = ""; tsout += "Verbose: " + Verbose.ToString() + "\n"; tsout += "Format: " + SqlTableFormat + "\n"; tsout += "Limit: " + SqlTableFormat + "\n"; tsout += "Dump: " + SqlTableFormat + "\n"; tsout += "U2Host: " + U2Host + "\n"; tsout += "U2Login: "******"\n"; tsout += "U2Password: "******"\n"; tsout += "U2Account: " + U2Account + "\n"; tsout += "U2File: " + U2File + "\n"; tsout += "SqlHost: " + SqlHost + "\n"; tsout += "SqlPort: " + SqlPort + "\n"; tsout += "SqlLogin: "******"\n"; tsout += "SqlPassword: "******"\n"; tsout += "SqlDatabase: " + SqlDatabase + "\n"; tsout += "SqlTable: " + SqlTable + "\n"; tsout += "SqlDictTable: " + SqlDictTable + "\n"; tsout += "SqlTableAction: " + SqlTableAction + "\n"; return(tsout); }
public override int GetHashCode() { int hash = 1; if (LedgerId.Length != 0) { hash ^= LedgerId.GetHashCode(); } if (filter_ != null) { hash ^= Filter.GetHashCode(); } if (Verbose != false) { hash ^= Verbose.GetHashCode(); } if (traceContext_ != null) { hash ^= TraceContext.GetHashCode(); } if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return(hash); }
public Executor CreateExecutor() { return(new Executor( Verbose.HasValue(), ConnectionString?.Value(), ProviderName?.Value(), Context?.Value())); }
/// <summary> /// Check if can write the text /// </summary> /// <param name="verb">Verbose test</param> /// <param name="forceWrite">Flag to force write</param> /// <returns>Return if can write</returns> public virtual bool CheckIfWrite(Verbose verb, bool forceWrite) { if (this.Verbose.HasFlag(Verbose.All) || this.Verbose.HasFlag(verb) || forceWrite) { return(true); } return(false); }
public Crawler(string url, int depth, Verbose verbose, string extensions) : this(url) { this.url = url; this.depth = depth; this.verbose = verbose; this.extensions = extensions; this.extensionFilter = new ExtensionFilter(extensions); this.verboseFilter = new VerboseFilter(verbose, baseUri); }
public void WriteVerbose(string text) { CheckForCancellation(); if (Verbose.IsOpen && Verbose.Count < MaxRecords) { Verbose.Add(new VerboseRecord(text)); } }
public override string ToString() { if (!Offset.HasValue) { Offset = 0; Verbose.Warning("{0} : Offset not set", Mnemonic); } return(string.Format("{0} 0x{1}", Mnemonic, Offset.Value.ToString("X"))); }
public Instruction(string aMnemonic) { Mnemonic = aMnemonic; if (Block == null) { Verbose.Warning("Floating Instructions"); return; } Block.Body.Add(this); }
public static void SetLevel(Level level) { Log.level = level; Verbose.ApplyLevel(); Debug.ApplyLevel(); Info.ApplyLevel(); Warn.ApplyLevel(); Error.ApplyLevel(); }
/* * URL : https://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.Ret(v=vs.110).aspx * Description : Returns from the current method, pushing a return value (if present) from the callee's evaluation stack onto the caller's evaluation stack. */ internal override void Execute(Options Config, OpCodeType xOp, MethodBase method, Optimizer Optimizer) { var functionInfo = method as MethodInfo; int stackCount = 0; if (functionInfo != null && functionInfo.ReturnType != typeof(void)) { stackCount = 1; } if (Optimizer.vStack.Count < stackCount) { throw new Exception("Internal Compiler Error: vStack.Count < expected size"); } /* The stack transitional behavior, in sequential order, is: * The return value is popped from the callee evaluation stack. * The return value obtained in step 1 is pushed onto the caller evaluation stack. */ switch (Config.TargetPlatform) { case Architecture.x86: { if (stackCount > 0) { var item = Optimizer.vStack.Pop(); if (!item.SystemStack) { throw new Exception(string.Format("UnImplemented-RegisterType '{0}'", msIL)); } } /* dude! if this happened na, I am going to kill myself :P */ if (Optimizer.vStack.Count != 0) { new Comment("vStack.Count != 0"); Verbose.Error("vStack.Count != 0"); } if (!xOp.IsLastIL) { new Jmp { DestinationRef = ".End" }; } } break; default: throw new Exception(string.Format("Unsupported target platform '{0}' for MSIL '{1}'", Config.TargetPlatform, msIL)); } }
/// <summary> /// Handle the Map command. /// </summary> /// <param name="l">Map</param> private void CmdMap(string l) { if (calculate) { Verbose.Out("Calculation mode - skipping Map"); return; } int i; if ((i = l.IndexOf(']')) == -1) { Errors.Error("Usage: " + UsMap + " (" + lineNo + ")"); } else { string p = l.Substring(0, i); if (phantoms.ContainsKey(p)) { char[] delim = new char[] { ' ' }; Phantom ph = (Phantom)phantoms[p]; string[] a; l = l.Substring(i + 1); a = l.Split(delim, StringSplitOptions.RemoveEmptyEntries); for (i = 0; i < a.Length; i++) { if (iServers.ContainsKey(a[i])) { if (ph.srvs.ContainsKey(a[i]) == true) { Errors.Warning("Server '" + a[i] + "' is already bound to this phantom - skipping (" + lineNo + ")"); } else { Verbose.Out("Binding '" + a[i] + "' to phantom '" + ph.name + "' (" + lineNo + ")"); ph.Stack((Server)iServers[a[i]]); } iServers.Remove(a[i]); } else { Errors.Error("No such server: '" + a[i] + "' (" + lineNo + ")"); } } } else { Errors.Error("No such phantom server: '" + p + "' (" + lineNo + ")"); } } }
public override string ToString() { return($"{nameof(CommandLineOptions)} [{nameof(IpAddress)} = {IpAddress}]\r\n" + $"[{nameof(Port)} = {Port}]\r\n" + $"[{nameof(LogFilePath)} = {LogFilePath}]\r\n" + $"[{nameof(LogFileName)} = {LogFileName}]\r\n" + $"[{nameof(AutoExit)} = {AutoExit.ToString()}]\r\n" + $"[{nameof(Activity)} = {Activity}]\r\n" + $"[{nameof(AdbPath)} = {AdbPath}]\r\n" + $"[{nameof(Verbose)} = {Verbose.ToString()}]\r\n" + $"[{nameof(AdbParams)} = {AdbParams == null ? string.Empty : AdbParams.Aggregate(string.Empty, (text, arg) => string.IsNullOrWhiteSpace(text) ? arg : $"{text} | {arg}")}]\r\n");
public void Main() { if (this.Verbose.HasFlag(Verbose.Quiet)) { this.App.Console.Verbose = Verbose.None; } else { this.App.Console.Verbose = Verbose.Info | this.Verbose; } }
/// <summary> /// Handle the Selectors command. /// </summary> /// <param name="line">Selectors</param> private void CmdSelectors(string line) { if ((line = TrimSelectors(line, lineNo)) == null) { Errors.Error("Usage: " + UsSelectors + " (" + lineNo + ")"); } else { selectors = line; Verbose.Out("Setting selectors to: " + selectors); } }
/// <summary> /// Handle the Phantoms command. /// </summary> /// <param name="line">Phantom specification</param> private void CmdPhantoms(string line) { if (calculate) { Verbose.Out("Calculation mode - skipping Phantoms"); return; } char[] seps = new char[] { ' ' }; string[] a; a = line.Split(seps, StringSplitOptions.RemoveEmptyEntries); if (a.Length < 2) { Errors.Error("Usage: " + UsPhantoms + " (" + lineNo + ")"); } else { int cnt = 0; try { cnt = Int32.Parse(a[0]); if (cnt < 1) { throw new Exception(""); } } catch { Errors.Error("Invalid count (" + lineNo + ")"); } if (cnt > 0) { Phantom p; for (; cnt > 0; cnt--) { if (a.Length == 2) { p = new Phantom(this, "phantom" + phantomIdx, res, a[1]); } else { p = new Phantom(this, "phantom" + phantomIdx, res, a[1], a[2]); } p.SetStack(srvsPrPhantom); Verbose.Out("Adding phantom to phantomslist: " + p.name + " (" + lineNo + ")"); AddToPhantomList(p); phantomIdx++; } } } }
/// <summary> /// Handle the Scenario Name command. /// </summary> /// <param name="line">Scenario name.</param> /// <returns></returns> private void CmdScenarioName(string line) { if (line.Length == 0) { Errors.Error("Usage: " + UsScenarioName + " (" + lineNo + ")"); } else { name = line; Verbose.Out("Setting new scenario name: " + name); } }
private void ProcessTemplatePackage( IDownloadedPackInfo sourceInfo, Dictionary <string, TemplatePackageSearchData> newCache, Dictionary <string, FilteredPackageInfo> filteredPackages, ScanningStats scanningStats, string?oldTemplatePackageVersion, string?oldNonTemplatePackageVersion ) { IEnumerable <TemplateSearchData> foundTemplates = TryGetTemplatesInPack(sourceInfo, _additionalDataProducers); Verbose.WriteLine($"{sourceInfo.Name}::{sourceInfo.Version} is processed"); if (foundTemplates.Any()) { Verbose.WriteLine("Found templates:"); foreach (TemplateSearchData template in foundTemplates) { string shortNames = string.Join(",", template.ShortNameList); Verbose.WriteLine($" - {template.Identity} ({shortNames}) by {template.Author}, group: {(string.IsNullOrWhiteSpace(template.GroupIdentity) ? "<not set>" : template.GroupIdentity)}, precedence: {template.Precedence}"); } newCache[sourceInfo.Name] = new TemplatePackageSearchData(sourceInfo, foundTemplates, sourceInfo.ProduceAdditionalData(_additionalDataProducers)); if (string.IsNullOrWhiteSpace(oldNonTemplatePackageVersion)) { if (string.IsNullOrWhiteSpace(oldTemplatePackageVersion)) { scanningStats.NewTemplatePacks.Add(newCache[sourceInfo.Name]); } else { scanningStats.UpdatedTemplatePacks.Add((newCache[sourceInfo.Name], oldTemplatePackageVersion)); } } else { if (string.IsNullOrWhiteSpace(oldTemplatePackageVersion)) { scanningStats.BecameTemplatePacks.Add((newCache[sourceInfo.Name])); } } } else { ProcessNonTemplatePackage( sourceInfo, "Failed to scan the package for the templates, the package may contain invalid templates.", filteredPackages, scanningStats, oldTemplatePackageVersion, oldNonTemplatePackageVersion); } }
static void Main(string[] args) { string url = RequestInput("Enter URL:", Crawler.ValidateUrl); string path = RequestInput("Enter path:", FolderService.ValidatePath); int depth = Int32.Parse(RequestInput("Enter depth:", Program.ValidateDepth)); Verbose verbose = (Verbose)GetVerboseSelection(); string extensions = RequestInput("Enter comma-separated lists of file extensions:", input => true); folderService = new FolderService(path); folderService.CreateIfNotExists(path); Crawler crawler = new Crawler(url, depth, verbose, extensions); crawler.OnRespose += ProcessResponse; crawler.Start(); }
private async Task ProcessTemplatePackagesUsingSearchAsync( Dictionary <string, TemplatePackageSearchData> newCache, Dictionary <string, FilteredPackageInfo> filteredPackages, ScanningStats scanningStats, CancellationToken cancellationToken) { foreach (IPackProvider packProvider in _packProviders) { int count = -1; Console.WriteLine($"Processing pack provider {packProvider.Name}:"); Console.WriteLine($"{await packProvider.GetPackageCountAsync(cancellationToken).ConfigureAwait(false)} packs discovered, starting processing"); await foreach (ITemplatePackageInfo sourceInfo in packProvider.GetCandidatePacksAsync(cancellationToken).ConfigureAwait(false)) { count = ProcessCount(count); if (newCache.ContainsKey(sourceInfo.Name) || filteredPackages.ContainsKey(sourceInfo.Name)) { Verbose.WriteLine($"Package {sourceInfo.Name}::{sourceInfo.Version} is already processed."); continue; } string?oldTemplateVersion = null; string?oldNonTemplateVersion = null; if (_diffEnabled) { if (CheckIfVersionIsKnownTemplatePackage(sourceInfo, newCache, scanningStats, out oldTemplateVersion)) { continue; } if (CheckIfVersionIsKnownNonTemplatePackage(sourceInfo, filteredPackages, scanningStats, out oldNonTemplateVersion)) { continue; } } IDownloadedPackInfo?packInfo = await packProvider.DownloadPackageAsync(sourceInfo, cancellationToken).ConfigureAwait(false); if (CheckIfPackageIsFiltered(packInfo, filteredPackages, scanningStats, oldTemplateVersion, oldNonTemplateVersion)) { continue; } ProcessTemplatePackage(packInfo, newCache, filteredPackages, scanningStats, oldTemplateVersion, oldNonTemplateVersion); } ProcessCount(count); Console.WriteLine($"All packs from pack provider {packProvider.Name} are processed"); } Console.WriteLine("All packs are processed"); }
public IEnumerable <IntPtr> FindData(IntPtr handle, byte[] data, Encoding enc) { var output = new List <IntPtr>(); var addr = new IntPtr(0x00000000); var end = new IntPtr(0x7F000000); var queue = new Queue <byte>(); var buffsize = 2048; addr = Fill(queue, handle, addr, buffsize, end); var numcorrect = 0; var correctaddress = IntPtr.Zero; while (queue.Count > 0) { if (queue.Count < buffsize / 2) { addr = Fill(queue, handle, addr, buffsize, end); } var b = queue.Dequeue(); if (b == data[numcorrect]) { if (numcorrect == 0) { correctaddress = IntPtr.Subtract(addr, queue.Count + 1); } numcorrect++; } else { numcorrect = 0; } if (numcorrect == data.Length) { // Found! var tempdata = ReadMemory(handle, correctaddress, data.Length * 2); Verbose.WriteLine("{0}:{1}", formatter.FormatAddress(correctaddress), formatter.FormatData(tempdata, enc)); numcorrect = 0; output.Add(correctaddress); } } return(output); }
public static void SaveConfig() { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); SetConfigValue(config, "AzureAccountKey", AzureAccountKey); SetConfigValue(config, "AWSAccessKeyID", AWSAccessKeyID); SetConfigValue(config, "AWSSecretAccessKeyID", AWSSecretAccessKeyID); SetConfigValue(config, "SrcAzureAccountKey", SrcAzureAccountKey); SetConfigValue(config, "SrcAWSAccessKeyID", SrcAWSAccessKeyID); SetConfigValue(config, "SrcAWSSecretAccessKeyID", SrcAWSSecretAccessKeyID); SetConfigValue(config, "TargetAzureAccountKey", TargetAzureAccountKey); SetConfigValue(config, "TargetAWSAccessKeyID", TargetAWSAccessKeyID); SetConfigValue(config, "TargetAWSSecretAccessKeyID", TargetAWSSecretAccessKeyID); SetConfigValue(config, "RetryAttemptDelayInSeconds", RetryAttemptDelayInSeconds.ToString()); SetConfigValue(config, "MaxRetryAttempts", MaxRetryAttempts.ToString()); SetConfigValue(config, "DownloadDirectory", DownloadDirectory); SetConfigValue(config, "Verbose", Verbose.ToString()); SetConfigValue(config, "AmDownloading", AmDownloading.ToString()); SetConfigValue(config, "UseBlobCopy", UseBlobCopy.ToString()); SetConfigValue(config, "ListContainer", ListContainer.ToString()); SetConfigValue(config, "MonitorBlobCopy", MonitorBlobCopy.ToString()); SetConfigValue(config, "ParallelFactor", ParallelFactor.ToString()); SetConfigValue(config, "ChunkSizeInMB", ChunkSizeInMB.ToString()); SetConfigValue(config, "DestinationBlobTypeSelected", DestinationBlobTypeSelected.ToString()); SetConfigValue(config, "SkyDriveCode", SkyDriveCode.ToString()); SetConfigValue(config, "SkyDriveRefreshToken", SkyDriveRefreshToken.ToString()); SetConfigValue(config, "DropBoxAPIKey", DropBoxAPIKey.ToString()); SetConfigValue(config, "DropBoxAPISecret", DropBoxAPISecret.ToString()); SetConfigValue(config, "DropBoxUserSecret", DropBoxUserSecret.ToString()); SetConfigValue(config, "DropBoxUserToken", DropBoxUserToken.ToString()); SetConfigValue(config, "SharepointUsername", SharepointUsername.ToString()); SetConfigValue(config, "SharepointPassword", SharepointPassword.ToString()); SetConfigValue(config, "SharedAccessSignatureDurationInSeconds", SharedAccessSignatureDurationInSeconds.ToString()); SetConfigValue(config, "AWSRegion", AWSRegion.ToString()); SetConfigValue(config, "SrcAWSRegion", SrcAWSRegion.ToString()); SetConfigValue(config, "TargetAWSRegion", TargetAWSRegion.ToString()); SetConfigValue(config, "MaxExecutionTimeInMins", MaxExecutionTimeInMins.ToString()); SetConfigValue(config, "MaxServerTimeoutInMins", MaxServerTimeoutInMins.ToString()); SetConfigValue(config, "BlobCopyBatchSize", BlobCopyBatchSize.ToString()); config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); }
private static IEnumerable <FilteredPackageInfo>?LoadKnownPackagesList(CommandArgs config) { if (!config.DiffMode || config.DiffOverrideKnownPackagesLocation == null) { return(null); } FileInfo?fileLocation = config.DiffOverrideKnownPackagesLocation; Verbose.WriteLine($"Opening {fileLocation.FullName}"); using (var fileStream = fileLocation.OpenRead()) using (var textReader = new StreamReader(fileStream, System.Text.Encoding.UTF8, true)) using (var jsonReader = new JsonTextReader(textReader)) { return(new JsonSerializer().Deserialize <IEnumerable <FilteredPackageInfo> >(jsonReader)); } }
public override void Run() { Verbose.Out("Bosters: Setting selectors to 'c'"); sc.selectors = "c"; Reservation r; if (sc.gRes != null) { r = sc.gRes; } else { r = new Reservation("20%,20%,20%,20%"); } Phantom p; for (int i = 0; i < sc.phantoms.Count; i++) { p = (Phantom)sc.phantoms.GetByIndex(i); p.AdjustReservation(r); } SortServersDescending(); Server s; for (int i = sc.servers.Count - 1; i > 0; i--) { s = (Server)sc.servers[i]; if (s.cpu > 1000) { Errors.Error("Server '" + s.name + "' is too big - cannot stack"); sc.servers.RemoveAt(i); } } Algorithm a = new BestFit(sc); a.Run(); }
static void ParseCommandLine(string[] args) { ArgStates argState = ArgStates.Command; for (int index = 0; index < args.Length; index++) { string arg = args[index]; switch (argState) { case ArgStates.Command: { switch (arg.ToUpper()) { case "VIEW": { command = Command.View; break; } case "IMPORT": { command = Command.Import; break; } case "EXPORT": { command = Command.Export; break; } case "DELETE": { command = Command.Delete; break; } //case "ARCHIVE": // { // command = Command.Archive; // break; // } //case "ACTIVATE": // { // command = Command.Activate; // break; // } default: { throw new UsageException("Error: " + arg + " is not a valid command."); } } argState = ArgStates.Options; break; } case ArgStates.Options: { if (arg.Substring(0, 1) == "-" || arg.Substring(0, 1) == "/") { switch (arg.Substring(1).ToUpper()) { case "L": { argState = ArgStates.Location; break; } case "S": { argState = ArgStates.StoreName; break; } case "A": { openMode = openMode | OpenFlags.IncludeArchived; break; } case "SHA1": { argState = ArgStates.SHA1; break; } case "SUBJECT": { argState = ArgStates.Subject; break; } case "ISSUER": { argState = ArgStates.Issuer; break; } case "SERIAL": { argState = ArgStates.Serial; break; } case "TEMPLATE": { argState = ArgStates.Template; break; } case "EXTENSION": { argState = ArgStates.Extension; break; } case "EKU": { argState = ArgStates.EKU; break; } case "POLICY": { argState = ArgStates.Policy; break; } case "KEYUSAGE": { argState = ArgStates.KeyUsage; break; } case "TIME": { argState = ArgStates.Time; break; } case "EXPIRATION": { argState = ArgStates.Expiration; break; } case "VALIDONLY": { validOnly = true; break; } case "SAVEAS": { argState = ArgStates.SaveAs; break; } case "DELKEY": { delKey = true; break; } case "NOPROMPT": { noPrompt = true; break; } //case "E": // { // keyStorageFlag |= X509KeyStorageFlags.Exportable; // break; // } //case "P": // { // keyStorageFlag |= X509KeyStorageFlags.UserProtected; // break; // } case "V": { argState = ArgStates.Verbose; break; } case "?": { throw new UsageException(string.Empty); } default: { throw new UsageException("Error: " + arg + " is not a valid option."); } } } else { switch (command) { case Command.View: { if (loadFromCertFile) { goto case Command.Export; } goto default; } case Command.Import: case Command.Export: { certFile = arg; argState = ArgStates.Password; break; } default: // Delete, Archive, Activate. { switch (arg) { case "My": storeName = StoreName.My; break; case "Disallowed": storeName = StoreName.Disallowed; break; case "CA": storeName = StoreName.CA; break; } argState = ArgStates.End; break; } } } break; } //case ArgStates.Location: // { // switch (arg.ToUpper()) // { // case "CU": // { // storeLocation = StoreLocation.CurrentUser; // break; // } // case "LM": // { // storeLocation = StoreLocation.LocalMachine; // break; // } // case "FILE": // { // loadFromCertFile = true; // break; // } // default: // { // throw new UsageException("Error: " + arg + " is not a valid location."); // } // } // argState = ArgStates.Options; // break; // } case ArgStates.StoreName: { switch (arg) { case "Disallowed": storeName = StoreName.Disallowed; break; case "CA": storeName = StoreName.CA; break; case "My": default: storeName = StoreName.My; break; } argState = ArgStates.Options; break; } case ArgStates.SHA1: { sha1 = arg; argState = ArgStates.Options; break; } case ArgStates.Subject: { subjects.Add(arg); argState = ArgStates.Options; break; } case ArgStates.Issuer: { issuers.Add(arg); argState = ArgStates.Options; break; } case ArgStates.Serial: { serials.Add(arg); argState = ArgStates.Options; break; } case ArgStates.Template: { templates.Add(arg); argState = ArgStates.Options; break; } case ArgStates.Extension: { extensions.Add(arg); argState = ArgStates.Options; break; } case ArgStates.EKU: { ekus.Add(arg); argState = ArgStates.Options; break; } case ArgStates.Policy: { policies.Add(arg); argState = ArgStates.Options; break; } //case ArgStates.KeyUsage: //{ // try // { // X509KeyUsageFlags keyUsageFlags = (X509KeyUsageFlags) Convert.ToInt32(arg); // keyUsages.Add(keyUsageFlags); // } // catch (FormatException) // { // keyUsages.Add(arg); // } // argState = ArgStates.Options; // break; //} //case ArgStates.Time: //{ // try // { // time = Convert.ToDateTime(arg); // } // catch (FormatException) // { // throw new UsageException("Error: " + arg + " is not a valid time."); // } // performTimeValidityCheck = true; // argState = ArgStates.Options; // break; //} case ArgStates.Expiration: { int expiration; try { expiration = Convert.ToInt32(arg); } catch //(FormatException) { throw new UsageException("Error: " + arg + " is not a valid expiration option."); } switch (expiration) { case 0: { expirationType = X509FindType.FindByTimeNotYetValid; break; } case 1: { expirationType = X509FindType.FindByTimeValid; break; } case 2: { expirationType = X509FindType.FindByTimeExpired; break; } default: { throw new UsageException("Error: " + arg + " is not a valid expiration option."); } } performTimeValidityCheck = true; argState = ArgStates.Options; break; } //case ArgStates.SaveAs: // { // switch (arg.ToUpper()) // { // case "SST": // { // saveAs = X509ContentType.SerializedStore; // break; // } // case "PKCS7": // { // saveAs = X509ContentType.Pkcs7; // break; // } // case "PFX": // { // saveAs = X509ContentType.Pfx; // break; // } // default: // { // throw new UsageException("Error: " + arg + " is not a valid SaveAs type."); // } // } // argState = ArgStates.Options; // break; // } case ArgStates.Verbose: { int level; try { level = Convert.ToInt32(arg); } catch //(FormatException) { throw new UsageException("Error: " + arg + " is not a valid verbose level."); } if (0 > level || 2 < level) { throw new UsageException("Error: " + arg + " is not a valid verbose level."); } verbose = (Verbose)level; argState = ArgStates.Options; break; } case ArgStates.Password: { password = arg; argState = ArgStates.End; break; } case ArgStates.End: { throw new UsageException(string.Empty); } default: { throw new InternalException("Internal error: Unknown argument state (argState = " + argState.ToString() + ")."); } } } // Make sure we are in good state. if (argState != ArgStates.Options && argState != ArgStates.Password && argState != ArgStates.End) { throw new UsageException(string.Empty); } // Make sure all required options are valid. // Note: As stated in the help screen, non-fatal invalid options for // the specific command is ignore. You can add the logic here // to further handle these invalid options if desired. switch (command) { case Command.View: { // If -l FILE specified, then we need to have a CertFile. if (loadFromCertFile && null == certFile) { throw new UsageException("Error: CertFile is not specified."); } break; } case Command.Import: case Command.Export: { // Make sure we do have a certificate file name. if (null == certFile) { throw new UsageException("Error: CertFile is not specified."); } goto case Command.Activate; } case Command.Delete: case Command.Archive: case Command.Activate: { // -l FILE is not allowed. if (loadFromCertFile) { throw new UsageException("Error: -l FILE is not a valid option."); } break; } default: { throw new InternalException("Internal error: Unknown command state (Command = " + command.ToString() + ")."); } } }