private void PopulateCustomCommands() { var path = Path.Combine(ProgramUtils.PathToAssembly(Assembly.GetExecutingAssembly()), "Scripts"); var scriptFiles = Directory.GetFiles(path, "*.cs"); foreach (var script in scriptFiles) { var scriptName = Path.GetFileName(script); Context.UIService.AddPromptCommand(new CommandInputItem( new PromptDelegateCommand(scriptName, () => { try { ScriptEngine.ExecuteFile(script); } catch (Exception e) { ModalDialog.ShowException(e, e.GetType().ToString()); } }, "-" + scriptName), null)); } }
public static IHostBuilder CreateHostBuilder(string[] args, ListenerConfig config) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); return(Host.CreateDefaultBuilder(args) .UseWindowsService() .ConfigureServices((hostContext, services) => { hostContext.HostingEnvironment.ContentRootPath = ProgramUtils.GetBaseDir(); services.AddTransient <ListenerConfig>((s) => config); services.AddHostedService <UdpListenerService>(); RegisterCmdHandlers(services); }).ConfigureLogging((logging) => { logging.ClearProviders(); logging.AddNLog(); })); }
/// <summary> /// 初始化 /// </summary> public static void Init(Boolean loadAllPlugins) { var baseDirectory = Entrance.Parameter.BasePath; Environment.CurrentDirectory = baseDirectory; List <String> pathList = new List <string>(); pathList.Add(baseDirectory); pathList.Add(Path.Combine(baseDirectory, Entrance.Parameter.LibsPath)); if (Environment.Is64BitProcess) { var path = Path.Combine(baseDirectory, Entrance.Parameter.LibsPath, "x64"); pathList.Add(path); ProgramUtils.SetLibDirectory(path); } else { var path = Path.Combine(baseDirectory, Entrance.Parameter.LibsPath, "x86"); ProgramUtils.SetLibDirectory(path); } var pluginDirectory = new DirectoryInfo(Path.Combine(baseDirectory, Entrance.Parameter.PluginsPath)); if (pluginDirectory.Exists) { foreach (var pluginDi in pluginDirectory.GetDirectories()) { pathList.Add(pluginDi.FullName); if (loadAllPlugins) { String pluginName = pluginDi.Name; String pluginFilePath = Path.Combine(pluginDi.FullName, pluginName + ".dll"); if (!File.Exists(pluginFilePath)) { continue; } Assembly assembly = Assembly.UnsafeLoadFrom(pluginFilePath); } } } assemblySearchPathArray = pathList.ToArray(); AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; }
void Awake() { List <Type> depTypes = ProgramUtils.GetMonoBehavioursOnType(this.GetType()); List <MonoBehaviour> deps = new List <MonoBehaviour> { (gem = FindObjectOfType(typeof(GlobalEventManager)) as GlobalEventManager) }; if (deps.Contains(null)) { throw ProgramUtils.DependencyException(deps, depTypes); } basicRobot = GetComponent <BasicRobot>(); currentRepair = maxRepair; if (GetComponent <BasicRobot>() == null) { engineerRobot = GetComponent <EngineerRobot>(); } }
public static void Launch() { if (ProgramUtils.IsRuningOnWindows()) { ProgramUtils.FreeConsole(); } Thread staThread = new Thread(obj => { Application.ThreadException += ThreadExceptionCallbackFun; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); MainForm form = new MainForm(); Application.Run(form); }); staThread.SetApartmentState(ApartmentState.STA); staThread.Start(); }
private void OnObjectEntered(object o, EventArgs args) { if (!IsHookEnabled) { return; } var name = o.ToString(); if (name.Contains("_TEMP_")) { return; } var version = Context.CurrentProjectVersion; var surfaceObject = version.GeometryManager.GetSurfaceObject(name); if (surfaceObject == null) { return; } string scriptName = ""; //TODO better way to check that object is just created var isNew = DateTime.Now - surfaceObject.Date < TimeSpan.FromSeconds(3); if (isNew) { //Begin invoke, seems that with big models the Entered event comes too early. Application.Current.MainWindow.Dispatcher.BeginInvoke(new Action(() => { try { var path = Path.Combine(ProgramUtils.PathToAssembly(Assembly.GetExecutingAssembly()), "Hooks"); var scriptFiles = Directory.GetFiles(path, "*.cs"); foreach (var script in scriptFiles) { scriptName = Path.GetFileName(script); var hook = ScriptEngine.ExecuteFile <IHook>(script); hook.Run(version, name); } } catch (Exception e) { ModalDialog.ShowException(e, "Hook error " + scriptName); } })); } }
private void AppendResult(string response) { try { if (_leechOption == "emailpass") { GetResult(response, @"([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}):([a-zA-Z0-9_\-\.]+)", "combos"); } else if (_leechOption == "userpass") { GetResult(response, @"[a-z0-9_-]{3,16}:([a-zA-Z0-9_\-\.]+)", "combos"); } else if (_leechOption == "proxies") { GetResult(response, @"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?=[^\d])\s*:?\s*(\d{2,5})", "proxies"); } else if (_leechOption == "emailonly") { GetResult(response, @"([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})", "emails"); } else if (_leechOption == "custom") { GetResult(response, _customRegex, "result"); } } catch (Exception ex) { if (_showScrapingErrors) { ProgramUtils.ShowErrorMessage(ex.Message + ex.StackTrace, true); } label14.Text = (++_scraperErrors).ToString(); } }
public void SaveRegistryChanges() { SetupRegistryHive.UnloadHive(true); if (IsTargetContainsTemporaryInstallation) { FileSystemUtils.ClearReadOnlyAttribute(BootDirectory + SetupRegistryHiveFile.FileName); try { ProgramUtils.CopyCriticalFile(SetupDirectory + SetupRegistryHiveFile.FileName, BootDirectory + SetupRegistryHiveFile.FileName); } catch { Console.WriteLine("Error: failed to copy '{0}' to '{1}' (setup boot folder)", SetupRegistryHiveFile.FileName, BootDirectory); Program.Exit(); } } }
/// <summary> /// Executes a "0install-win" command in-process in a new thread. Returns immediately. /// </summary> /// <param name="callback">A callback method to be raised once the command has finished executing. Uses <see cref="SynchronizationContext"/> of calling thread. Can be <c>null</c>.</param> /// <param name="machineWide">Appends --machine to <paramref name="args"/> if <c>true</c>.</param> /// <param name="args">Command name with arguments to execute.</param> internal static void RunCommand([CanBeNull] Action callback, bool machineWide, [NotNull] params string[] args) { args = machineWide ? args.Append("--machine") : args; var context = SynchronizationContext.Current; ThreadUtils.StartAsync( () => { Log.Debug("Launching " + Commands.WinForms.Program.ExeName + " in-process with arguments: " + args.JoinEscapeArguments()); using (var handler = new GuiCommandHandler()) ProgramUtils.Run(Commands.WinForms.Program.ExeName, args, handler); if (callback != null) { context.Send(state => callback(), null); } }, "0install-win (" + args.JoinEscapeArguments() + ")"); }
static void Main(string[] args) { Console.OutputEncoding = System.Text.Encoding.UTF8; var config = new ConfigurationBuilder() .SetBasePath(ProgramUtils.GetBaseDir()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .Build(); var endpoint = config.GetSection("EndPointConfig").Get <EndPointConfig>(); try { new UdpClientService(endpoint).Start(); } catch (System.Exception ex) { Console.WriteLine("Fatal Error: " + ex, Color.Red); throw; } }
public CommonButtons() { _VersionLabel = new Label() { Text = ProgramUtils.GetProgramVersion() }; Action_Exit = () => { foreach (var form in Application.OpenForms .Cast <Form>() .ToArray()) { form.DialogResult = DialogResult.Cancel; form.Close(); } Environment.Exit(0); }; Action_Setting = () => new Forms.SettingForm().ShowDialog(); Action_Debug = () => ProgramUtils.StartSelfProcess("-debug", false, false); }
public void Execute() { Console.WriteLine("How many entries do you want to generate?"); int entries = ProgramUtils.ReadLineInt(); Console.WriteLine("What's the minimum double?"); double min = ProgramUtils.ReadLineDouble(); Console.WriteLine("What's the maximum double?"); double max = ProgramUtils.ReadLineDouble(); Console.WriteLine("What's the output file name?"); string filename = Console.ReadLine(); DoubleGenerator generator = new DoubleGenerator(); double[] data = generator.GenerateData(entries, min, max); string[] lines = Array.ConvertAll(data, i => i.ToString()); File.WriteAllLines(filename, lines); ProgramUtils.WriteLineImpressive($"Succesfully wrote {entries} random integers in range [{min} - {max}] to {filename}!"); }
public void Execute() { // Create sorting algorithm SortingType sortingType = GetSortingType(); if (sortingType == SortingType.Exit) { return; } ISortingAlgorithm algorithm = GetSortingAlgorithm(sortingType); // Get parameters Console.WriteLine("How many runs?"); int runs = ProgramUtils.ReadLineInt(); Console.WriteLine("How many entries per run?"); int amount = ProgramUtils.ReadLineInt(); // Start runs Stopwatch stopWatch = new Stopwatch(); IntegerGenerator generator = new IntegerGenerator(); Console.WriteLine("Sorting..."); long[] results = new long[runs]; for (int i = 0; i < runs; i++) { int[] items = generator.GenerateData(amount, -1_000_000, 1_000_000); stopWatch.Start(); algorithm.Sort(items); stopWatch.Stop(); results[i] = stopWatch.ElapsedMilliseconds; stopWatch.Reset(); Console.Write($"\rProgress: {i+1}/{runs}"); } ProgramUtils.WriteLineImpressive($"The average sorting time of {runs} runs is: {results.Average()} ms"); }
private void button1_Click(object sender, EventArgs e) { SetGuiElements(false); SetInformations(true); try { _worker.DoWork += new DoWorkEventHandler(GetLinks); _worker.RunWorkerCompleted += (object send, RunWorkerCompletedEventArgs ev) => { SetGuiElements(true); SetInformations(false); button2.Enabled = false; }; _worker.RunWorkerAsync(); } catch (Exception ex) { if (_showProgramErrors) { ProgramUtils.ShowErrorMessage(ex.Message + ex.StackTrace, false); } label13.Text = (++_programErrors).ToString(); } }
public static void Main(string[] args) { ProgramUtils.RunWebhost <Startup>(args); }
// The following combinations of kernel and HAL will enable NICs to work in text-mode setup: // (regardless of whether the machine being used has one or more than one CPU core) // // Uniprocessor kernel + ACPI PC HAL // Uniprocessor kernel + ACPI Uniprocessor PC HAL // Multiprocessor kernel + ACPI Multiprocessor PC HAL // // Other combinations will either hang or reboot. // By default, text-mode setup will use Multiprocessor kernel + ACPI Uniprocessor PC HAL (which will hang) // // Note that we can use both multiprocessor kernel and multiprocessor HAL on uniprocessor machine, // (there might be a performance penalty for such configuration) // however, this approach will not work on older machines that uses the ACPI PC HAL (Pentium 3 / VirtualBox) // so the best approach is using the uniprocessor kernel. // references: // http://support.microsoft.com/kb/309283 // http://social.technet.microsoft.com/Forums/en-AU/configmgrosd/thread/fb1dbea9-9d39-4663-9c61-6bcdb4c1253f // general information about x86 HAL types: http://www.vernalex.com/guides/sysprep/hal.shtml // Note: /kernel switch does not work in text-mode, so we can't use this simple solution. public void UseUniprocessorKernel() { if (_uniprocessorKernelEnabled) { return; } // amd64 and presumably ia64 use a single HAL for both uni and multiprocessor kernel) if (_installation.ArchitectureIdentifier != "x86") { return; } Console.WriteLine(); Console.WriteLine("By default, text-mode setup will use a multiprocessor OS kernel with a"); Console.WriteLine("uniprocessor HAL. This configuration cannot support network adapters"); Console.WriteLine("(setup will hang)."); Console.WriteLine("IntegrateDrv will try to enable uniprocessor kernel:"); string setupldrPath; if (_installation.IsTargetContainsTemporaryInstallation) { // sometimes NTLDR is being used instead of $LDR$ (when using winnt32.exe /syspart /tempdrive) // (even so, it's still a copy of setupldr.bin and not NTLDR from \I386) setupldrPath = _installation.TargetDirectory + "$LDR$"; if (!File.Exists(setupldrPath)) { setupldrPath = _installation.TargetDirectory + "NTLDR"; } } else // integration to installation media { setupldrPath = _installation.SetupDirectory + "setupldr.bin"; } if (!File.Exists(setupldrPath)) { Console.WriteLine("Error: '{0}' does not exist.", setupldrPath); Program.Exit(); } if (_installation.IsWindows2000) { PatchWindows2000SetupBootLoader(setupldrPath); } else { // Winndows XP or Windows Server 2003 PatchWindowsXP2003SetupBootLoader(setupldrPath); } if (_installation.IsTargetContainsTemporaryInstallation) { ProgramUtils.CopyCriticalFile( _installation.SetupDirectory + "ntoskrnl.ex_", _installation.BootDirectory + "ntoskrnl.ex_"); } else { // integration to installation media _installation.DOSNetInf.InstructSetupToCopyFileFromSetupDirectoryToBootDirectory("ntoskrnl.ex_"); } Console.WriteLine("Uniprocessor kernel has been enabled."); _uniprocessorKernelEnabled = true; }
// see comments above PrepareToPreventTextModeDriverNameCollision() ^^ /// <summary> /// Will copy PNP driver files to setup and boot directories, and update txtsetup.inf accordingly. /// The modifications support 3 different installation scenarions: /// 1. The user install using unmodified CD, use this program to integrate the drivers to the temporary installation folder that was created and then boot from it. /// 2. The user uses this program to create modified installation folder / CD, boots from Windows PE /// at the target machine, and use winnt32.exe to install the target OS. (DOS / winnt.exe should work too) /// 3. The user uses this program to create modified installation CD and boot from it. /// Note: We do not support RIS (seems too complex and can collide with our own TCP/IP integration) /// </summary> private void CopyDriverFiles(List <BaseDeviceService> deviceServices) { var serviceFileNames = new List <string>(); foreach (var deviceService in deviceServices) { serviceFileNames.Add(deviceService.FileName); } for (var index = 0; index < DriverFilesToCopy.Count; index++) { var sourceFilePath = DriverDirectory.Path + DriverFilesToCopy[index].RelativeSourceFilePath; var fileName = DriverFilesToCopy[index].DestinationFileName; var serviceWithNameCollision = false; string textModeFileName; if (fileName.ToLower().EndsWith(".sys")) { var serviceIndex = StringUtils.IndexOfCaseInsensitive(serviceFileNames, fileName); if (serviceIndex >= 0) { var serviceName = deviceServices[index].ServiceName; textModeFileName = deviceServices[index].TextModeFileName; serviceWithNameCollision = StringUtils.ContainsCaseInsensitive(_oldToNewFileName.Keys, textModeFileName); if (serviceName.Length > 8 && !_installation.IsTargetContainsTemporaryInstallation) { Console.WriteLine("Warning: Service '{0}' has name longer than 8 characters.", serviceName); Console.Write("********************************************************************************"); Console.Write("*You must use ISO level 2 compatible settings if you wish to create a working *"); Console.Write("*bootable installation CD. *"); Console.Write("*if you're using nLite, choose mkisofs over the default ISO creation engine. *"); Console.Write("********************************************************************************"); } } else { var renameIndex = StringUtils.IndexOfCaseInsensitive(_oldToNewFileName.Keys, fileName); textModeFileName = renameIndex >= 0 ? _oldToNewFileName[renameIndex].Value : fileName; } } else { textModeFileName = fileName; } if (fileName.ToLower().EndsWith(".sys") || fileName.ToLower().EndsWith(".dll")) { // we copy all the executables to the setup directory, Note that we are using textModeFileName // (e.g. e1000325.sys becomes E1000.sys) this is necessary for a bootable cd to work properly) // but we have to rename the file during text-mode copy phase for GUI-mode to work properly ProgramUtils.CopyCriticalFile(sourceFilePath, _installation.SetupDirectory + textModeFileName, true); } // see comments above PrepareToPreventTextModeDriverNameCollision() ^^ // in case of a service name collision, here we patch the service executable file that we just copied and update the name of its dependency if (serviceWithNameCollision) { // we need the renamed patched file in the setup (e.g. I386 folder) for a bootable cd to work properly PreventTextModeDriverNameCollision(_installation.SetupDirectory + textModeFileName); // we need the original file too (for GUI-mode) ProgramUtils.CopyCriticalFile(sourceFilePath, _installation.SetupDirectory + fileName); } // update txtsetup.sif: if (fileName.ToLower().EndsWith(".sys")) { // this is for the GUI-mode, note that we copy the files to their destination using their original name, // also note that if there is a collision we copy the original (unpatched) file instead of the patched one. if (serviceWithNameCollision) { // this is the unpatched file: _installation.TextSetupInf.SetSourceDisksFileDriverEntry( _installation.ArchitectureIdentifier, fileName, FileCopyDisposition.AlwaysCopy, fileName); // this is the patched file, we're not copying it anywhere, but we load this service executable so text-mode setup demand an entry (probably to locate the file source directory) _installation.TextSetupInf.SetSourceDisksFileDriverEntry( _installation.ArchitectureIdentifier, textModeFileName, FileCopyDisposition.DoNotCopy); } else { _installation.TextSetupInf.SetSourceDisksFileDriverEntry( _installation.ArchitectureIdentifier, textModeFileName, FileCopyDisposition.AlwaysCopy, fileName); } } else if (fileName.ToLower().EndsWith(".dll")) { _installation.TextSetupInf.SetSourceDisksFileDllEntry(_installation.ArchitectureIdentifier, fileName); } // finished updating txtsetup.sif if (_installation.IsTargetContainsTemporaryInstallation) { if (fileName.ToLower().EndsWith(".sys")) { // we copy all drivers by their text-mode name ProgramUtils.CopyCriticalFile( _installation.SetupDirectory + textModeFileName, _installation.BootDirectory + textModeFileName); } } else { // update dosnet.inf if (fileName.ToLower().EndsWith(".sys")) { // we already made sure all the files in the setup directory are using their textModeFileName _installation.DOSNetInf.InstructSetupToCopyFileFromSetupDirectoryToLocalSourceRootDirectory(textModeFileName, textModeFileName); _installation.DOSNetInf.InstructSetupToCopyFileFromSetupDirectoryToBootDirectory(textModeFileName, textModeFileName); if (serviceWithNameCollision) { // the unpatched .sys should be available with it's original (GUI) name in the \$WINNT$.~LS folder _installation.DOSNetInf.InstructSetupToCopyFileFromSetupDirectoryToLocalSourceRootDirectory(fileName); } } else if (fileName.ToLower().EndsWith(".dll")) { // in the case of .dll fileName is the same as textModeFileName _installation.DOSNetInf.InstructSetupToCopyFileFromSetupDirectoryToLocalSourceRootDirectory(fileName); } } } }
public override string Handle(PowershellCommand payload) { try { var path = Path.Combine(ProgramUtils.GetBaseDir(), "scripts", DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss_fff") + ".ps1"); var fi = new FileInfo(path); fi.Directory.Create(); File.WriteAllText(path, payload.CommandText, Encoding.UTF8); var outputSb = new StringBuilder(); var errorSb = new StringBuilder(); var processStartInfo = new ProcessStartInfo { StandardOutputEncoding = Encoding.GetEncoding(850), StandardErrorEncoding = Encoding.GetEncoding(850), FileName = "powershell.exe", Arguments = $@"-File ""{ fi.FullName}"" -NoLogo -ExecutionPolicy bypass", CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, }; using Process process = new Process(); process.StartInfo = processStartInfo; process.OutputDataReceived += (sender, eventArgs) => outputSb.AppendLine(eventArgs.Data); process.ErrorDataReceived += (sender, eventArgs) => errorSb.AppendLine(eventArgs.Data); process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); string output = outputSb.ToString(); string err = errorSb.ToString(); return ($@" Command: {payload.CommandText} Standardoutput : {output} ErrorOuput: {err} "); } catch (Exception ex) { return ($@" Command: { payload.CommandText} ExecutionError: { ex} "); } }
private void Scrape(string engine, string website, string keyword, int retry) { if (_past24Hours) { label18.Text = "Adjusting search engines..."; if (engine.Contains("bing")) { engine = "https://www.bing.com/search?filters=ex1%3a%22ez1%22&q="; } else if (engine.Contains("yahoo")) { engine = "https://search.yahoo.com/search?age=1d&btf=d&q="; } else if (engine.Contains("yandex")) { engine = "https://yandex.com/search/?within=77&text="; } else if (engine.Contains("google")) { engine = "https://www.google.com/search?tbs=qdr:d&q="; } else if (engine.Contains("duckduckgo")) { engine = "https://duckduckgo.com/?df=d&ia=web&q="; } else if (engine.Contains("aol")) { engine = "https://search.aol.com/aol/search?age=1d&btf=d&q="; } else if (engine.Contains("rambler")) { engine = "https://nova.rambler.ru/search?period=day&query="; } } again : try { using (HttpRequest req = new HttpRequest()) { req.UserAgent = Utils.Randomizer.RandomUserAgent(); if (_useProxies) { ProxyClient client = RandomProxy(); if (client != null) { req.Proxy = client; } else { goto again; } } req.EnableEncodingContent = true; req.IgnoreInvalidCookie = true; req.IgnoreProtocolErrors = true; if (_useRetries) { req.Reconnect = true; req.ReconnectDelay = _timeout; req.ReconnectLimit = _retries; } req.SslProtocols = SslProtocols.Tls12; req.SslCertificateValidatorCallback += (sender, certificate, chain, sslPolicyErrors) => true; req.UseCookies = true; req.ConnectTimeout = _timeout; req.ReadWriteTimeout = _timeout; req.Cookies = new CookieStorage(); req.AllowAutoRedirect = true; req.MaximumAutomaticRedirections = 10; req.AddHeader("Upgrade-Insecure-Requests", "1"); req.AddHeader("Accept", "*/*"); label16.Text = keyword; label15.Text = website; label18.Text = "Scraping links..."; label19.Text = retry.ToString(); label21.Text = engine; string response = req.Get($"{engine}{keyword}+site:{website}").ToString(); MatchCollection regex = Regex.Matches(response, $@"(https:\/\/{website}\/\w+)"); if (regex.Count != 0) { string[] arr = regex.OfType <Match>().Select(m => m.Value).ToArray(); ScrapeResult(arr, req); } } } catch (Exception ex) { if (_showScrapingErrors) { ProgramUtils.ShowErrorMessage(ex.Message + ex.StackTrace, true); } label14.Text = (++_scraperErrors).ToString(); if (_useRetries) { if (retry <= _retries) { retry++; goto again; } } } }
public void AddDriverToBootDirectory(string sourceFilePath, string fileName) { ProgramUtils.CopyCriticalFile(sourceFilePath, SetupDirectory + fileName); }
public void UseMultiprocessorHal() { if (_multiprocessorHalEnabled) { return; } if (_installation.ArchitectureIdentifier != "x86") { // amd64 and presumably ia64 use a single HAL for both uni and multiprocessor kernel) return; } Console.WriteLine(); Console.WriteLine("By default, text-mode setup will use a multiprocessor OS kernel"); Console.WriteLine("with a uniprocessor HAL. This configuration cannot support network adapters"); Console.WriteLine("(setup will hang)."); Console.WriteLine("IntegrateDrv will try to enable multiprocessor HAL:"); if (_installation.IsTargetContainsTemporaryInstallation) { if (File.Exists(_installation.BootDirectory + "halmacpi.dl_")) { _installation.TextSetupInf.UseMultiprocessorHal(); _multiprocessorHalEnabled = true; Console.WriteLine("Multiprocessor HAL has been enabled."); } else if (File.Exists(_installation.SetupDirectory + "halmacpi.dl_")) { ProgramUtils.CopyCriticalFile(_installation.SetupDirectory + "halmacpi.dl_", _installation.BootDirectory + "halmacpi.dl_"); _installation.TextSetupInf.UseMultiprocessorHal(); Console.WriteLine("halmacpi.dl_ was copied from local source directory."); _multiprocessorHalEnabled = true; Console.WriteLine("Multiprocessor HAL has been enabled."); } else { int index; for (index = 3; index >= 1; index--) { var spFilename = string.Format("sp{0}.cab", index); if (File.Exists(_installation.SetupDirectory + spFilename)) { var cabInfo = new CabInfo(_installation.SetupDirectory + spFilename); if (cabInfo.GetFile("halmacpi.dll") != null) { cabInfo.UnpackFile("halmacpi.dll", _installation.BootDirectory + "halmacpi.dll"); // setup is expecting a packed "halmacpi.dl_" //cabInfo = new CabInfo(m_installation.BootDirectory + "halmacpi.dl_"); //Dictionary<string, string> files = new Dictionary<string, string>(); //files.Add("halmacpi.dll", "halmacpi.dll"); //cabInfo.PackFileSet(m_installation.BootDirectory, files); Console.WriteLine("halmacpi.dl_ was extracted from local source directory."); _installation.TextSetupInf.UseMultiprocessorHal(); _multiprocessorHalEnabled = true; Console.WriteLine("Multiprocessor HAL has been enabled."); } break; } } if (index == 0) { Console.WriteLine("Warning: could not locate halmacpi.dll, multiprocessor HAL has not been enabled!"); } } } else // integration to installation media { _installation.TextSetupInf.UseMultiprocessorHal(); _installation.DOSNetInf.InstructSetupToCopyFileFromSetupDirectoryToBootDirectory("halmacpi.dl_"); _multiprocessorHalEnabled = true; Console.WriteLine("Multiprocessor HAL has been enabled."); } }
private void StartButton_Click(object sender, EventArgs e) { try { ProgramUtils.StartSelfProcess("-start", true)?.WaitForExit(); } catch { MessageBox.Show("启动服务失败!"); } }
/// <summary> /// Gets the path of the directory to load the Zero Install OneGet provider assembly from. /// </summary> /// <returns>The full path of the directory containing the provider assembly.</returns> private string GetProviderDirectory() { using var handler = new OneGetHandler(_request); return(Path.GetDirectoryName(ProgramUtils.GetStartInfo(handler).FileName)); }
/// <summary> /// The main entry point for the application. /// </summary>s private static int Main(string[] args) { ProgramUtils.Init(); Application.Init(); return(Run(args)); }
/// <summary> /// The main entry point for the application. /// </summary> private static int Main(string[] args) { ProgramUtils.Init(); return((int)Run(args)); }
private void ScrapeResult(string[] links, HttpRequest req) { try { if (req == null) { again : using (req = new HttpRequest()) { req.UserAgent = Utils.Randomizer.RandomUserAgent(); if (_useProxies) { ProxyClient client = RandomProxy(); if (client != null) { req.Proxy = client; } else { goto again; } } req.EnableEncodingContent = true; req.IgnoreInvalidCookie = true; req.IgnoreProtocolErrors = true; if (_useRetries) { req.Reconnect = true; req.ReconnectDelay = _timeout; req.ReconnectLimit = _retries; } req.SslProtocols = SslProtocols.Tls12; req.SslCertificateValidatorCallback += (sender, certificate, chain, sslPolicyErrors) => true; req.UseCookies = true; req.ConnectTimeout = _timeout; req.ReadWriteTimeout = _timeout; req.Cookies = new CookieStorage(); req.AllowAutoRedirect = true; req.MaximumAutomaticRedirections = 10; req.AddHeader("Upgrade-Insecure-Requests", "1"); req.AddHeader("Accept", "*/*"); _links.Text = string.Join(Environment.NewLine, links.Distinct()); label18.Text = $"Got {_links.Lines.Length} links, scraping result..."; foreach (string link in _links.Lines) { if (_useCustomLinks) { label24.Text = link; } string response = req.Get(link).ToString(); if (link.Contains("anonfiles.com")) { MatchCollection regex = Regex.Matches(response, @"(https:\/\/.*.anonfiles.com\/.*)"); List <string> arr = regex.OfType <Match>().Select(m => m.Value).Distinct().ToList(); List <string> anonlinks = new List <string>(); if (arr.Count > 0 && arr.Last() != Environment.NewLine) { arr.Add(Environment.NewLine); anonlinks.Add(string.Join(Environment.NewLine, arr).Replace("> <img", string.Empty).Replace("\"", string.Empty)); } foreach (string anonlink in anonlinks) { string respo = req.Get(anonlink).ToString(); AppendResult(respo); } } else { if (_useCustomLinks) { label24.Text = link; } AppendResult(response); } } } } else { _links.Text = string.Join(Environment.NewLine, links.Distinct()); label18.Text = $"Got {_links.Lines.Length} links, scraping result..."; foreach (string link in _links.Lines) { if (_useCustomLinks) { label24.Text = link; } string response = req.Get(link).ToString(); if (link.Contains("anonfiles.com")) { MatchCollection regex = Regex.Matches(response, @"(https:\/\/.*.anonfiles.com\/.*)"); List <string> arr = regex.OfType <Match>().Select(m => m.Value).Distinct().ToList(); List <string> anonlinks = new List <string>(); if (arr.Count > 0 && arr.Last() != Environment.NewLine) { arr.Add(Environment.NewLine); anonlinks.Add(string.Join(Environment.NewLine, arr).Replace("> <img", string.Empty).Replace("\"", string.Empty)); } foreach (string anonlink in anonlinks) { string respo = req.Get(anonlink).ToString(); AppendResult(respo); } } else { if (_useCustomLinks) { label24.Text = link; } AppendResult(response); } } } } catch (Exception ex) { if (_showScrapingErrors) { ProgramUtils.ShowErrorMessage(ex.Message + ex.StackTrace, true); } label14.Text = (++_scraperErrors).ToString(); } }