Here are the examples of the csharp api System.Windows.Forms.Control.Invoke(System.Delegate) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1060 Examples
19
Source : RansomNote.cs
with GNU General Public License v3.0
from 0x00000FF
with GNU General Public License v3.0
from 0x00000FF
private void Detect()
{
while (true)
{
if (!flag)
{
var Procs = Process.GetProcessesByName("th12");
if (Procs.Length > 0)
{
// Open TH12.exe with PROCESS_VM_READ (0x0010).
_handle = OpenProcess(0x10, false, Procs.FirstOrDefault().Id);
if (_handle != null)
processStatus = true;
}
}
else
{
if (IsScoreReached)
{
break;
}
int bytesRead = 0;
byte[] _buffer = new byte[4]; // Will read 4 bytes of memory
/*
* Read Level
*
* In TH12 ~ Undefined Fantastic Object, Level is stored in
* [base address] + 0xAEBD0, as 4bytes int value.
*
*/
var readLevel = ReadProcessMemory((int)_handle, 0x004AEBD0, _buffer, 2, ref bytesRead);
if (!readLevel)
{
flag = false;
continue;
}
/*
* Level Codes
* 0 - Easy; 1 - Normal; 2 - Hard; 3 - Lunatic; ? - Extra
*
*/
if (BitConverter.ToInt16(_buffer, 0) != 3)
{
ProcStatus.Invoke(new MethodInvoker(() => {
ProcStatus.Text = "NOT LUNATIC LEVEL!";
}));
continue;
}
else
{
ProcStatus.Invoke(new MethodInvoker(() => {
ProcStatus.Text = "Process Working";
}));
}
/*
* Read Score
*
* Once level is detected as LUNATIC,
* rensenWare reads score from process.
*
* Score is stored in
* [base address] + 0xB0C44, as 4bytes int value.
*
*/
var readScore = ReadProcessMemory((int)_handle, 0x004B0C44, _buffer, 4, ref bytesRead);
if (!readScore)
{
flag = false;
continue;
}
ScoreStatus.Invoke(new MethodInvoker(() =>
{
ScoreStatus.Text = (BitConverter.ToInt32(_buffer, 0) * 10).ToString();
}));
/*
* One interesting thing,
* internally, touhou project process prints score as 10 times of original value.
* I don't know why it is.
*/
if (BitConverter.ToInt32(_buffer, 0) > 20000000) // It is 20,000,000
IsScoreReached = true;
else
_buffer = null;
}
// Let CPU rest
Thread.Sleep(100);
}
// Create Random Key/IV File in Desktop of Current User.
File.WriteAllBytes(Program.KeyFilePath, Program.randomKey);
File.WriteAllBytes(Program.IVFilePath, Program.randomIV);
decryptProgress.Maximum = Program.encryptedFiles.Count;
foreach (var path in Program.encryptedFiles)
{
try
{
DecryptStatus.Invoke(new MethodInvoker(() =>
{
DecryptStatus.Text = Path.GetFileName(path);
}));
// Do Decrypt
decryptProgress.Value++;
}
catch
{
continue;
}
}
this.Invoke(new MethodInvoker(() => {
MessageBox.Show("Decryption Complete!\nIf there are encrypted files exists, use manual decrypter with key/IV files saved in desktop!");
ButtonManualDecrypt.Visible = true;
ButtonExit.Visible = true;
}));
}
19
Source : SelectFm.cs
with GNU General Public License v3.0
from a4004
with GNU General Public License v3.0
from a4004
private async Task ListSoftwareOptions(string option)
{
string[] availableFiles = API.GithubManager.GetReleaseNames("spacehuhntech/esp8266_deauther", option);
if (availableFiles == null || availableFiles.Length < 1)
{
MessageBox.Show("The version you selected does not have any precompiled binaries available for it, to use this version you will" +
" need to build the software from source and flash it as a local image from this PC.", "No Files Available", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
return;
}
foreach (string file in availableFiles)
{
try
{
string type = Path.GetExtension(file).Replace(".", "").ToUpper();
Invoke(new Action(() =>
{
listView.Items.Add(new ListViewItem(new string[] { "SpacehuhnTech", Path.GetFileNameWithoutExtension(file), type}));
}));
}
catch (Exception e)
{
Program.Debug("selectfm", $"Failed to parse filename: {file}, error: {e.Message}", Event.Critical);
await Task.Delay(100);
}
}
}
19
Source : MainWindow.cs
with GNU General Public License v3.0
from a4004
with GNU General Public License v3.0
from a4004
private async void Flash()
{
await Task.Delay(1000);
FileMode:
CreateRequest("Device software installation", "You are installing software on your device, you can choose where to get it from.",
"Get the latest image from the Internet (Recommended)", "Use a local image on this PC", out int option);
if (option == 2)
{
Invoke(new Action(() =>
{
OpenFileDialog fileDialog = new OpenFileDialog()
{
Multiselect = false,
SupportMultiDottedExtensions = true,
Filter = "Binary files (*.bin)|*.bin|Hex files (*.hex)|*.hex|All files (*.*)|*.*",
replacedle = "Choose a software image file",
};
if (fileDialog.ShowDialog() == DialogResult.OK)
Program.Settings.Bin = fileDialog.FileName;
}));
if (Program.Settings.Bin == default)
goto FileMode;
}
else if (option == 1)
{
if (!CreateSelRequest(out string file))
goto FileMode;
else
{
WaitFm.Debug($"User selected file: {file}");
WaitFm.replacedle("Downloading software");
WaitFm.Caption("");
WaitFm.Debug($"Downloading {file}...");
try
{
WebClient client = new WebClient();
client.DownloadProgressChanged += (s, e) =>
{
WaitFm.Caption($"Downloading {Path.GetFileName(file)} from github.com ({e.ProgressPercentage}%)");
};
client.DownloadFileCompleted += delegate
{
WaitFm.Debug($"Successfully downloaded {Path.GetFileName(file)} from github.com", Event.Success);
};
await client.DownloadFileTaskAsync(file, Path.GetFileName(file));
Program.Settings.Bin = Path.GetFileName(file);
}
catch (Exception ex)
{
WaitFm.Debug($"Download failed due to an error: {ex.Message}", Event.Critical);
await CreateMessage("A problem was encountered", "The required file could not be downloaded. You can try again.");
WaitFm.Host.CloseTask();
WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
TaskManager.ReleaseFLock();
return;
}
}
WaitFm.replacedle("Getting ready");
await Task.Delay(1000);
}
else
throw new Exception($"The selection could not be determined due to an invalid value. {option}");
CreateRequest("Flash Operation", "The program is about to install software to your Espressif device. " +
"Existing data on the device will be PERMANENTLY DELETED, are you sure?", "Allow software installation",
"Cancel flash operation, no changes will be made", out int result);
if (result == 2)
{
WaitFm.Debug("User cancelled the flash operation.", Event.Critical);
await CreateMessage("Software installation aborted", "You've chosen to cancel the installation " +
"of software to your Espressif device. No changes have been made. You can close this window.");
WaitFm.Host.CloseTask();
WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
TaskManager.ReleaseFLock();
return;
}
else if (result == 1)
{
WaitFm.Debug("Flash operation started.");
WaitFm.replacedle("Installing software");
WaitFm.Caption("Checking device connection");
WaitFm.Debug("Checking device connection...");
if (!Program.Settings.PortFix)
WaitFm.Debug($"Connecting to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}...");
string output = string.Empty;
if (!Program.Portable)
{
if (ShellManager.RunCommand(out output, "py", $"-m esptool {(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} read_mac"))
{
if (!Program.Settings.PortFix)
WaitFm.Debug($"Connected to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}", Event.Success);
WaitFm.Debug($"Espressif device MAC: {output.Substring(output.IndexOf("MAC:") + 5, 17).ToUpper()}", Event.Success);
WaitFm.Caption("Connection was successful");
}
else
throw new Exception("Could not connect to the device.");
}
else
{
if (ShellManager.RunCommand(out output, Program.Settings.EsptoolExe, $"{(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} read_mac"))
{
if (!Program.Settings.PortFix)
WaitFm.Debug($"Connected to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}", Event.Success);
WaitFm.Debug($"Espressif device MAC: {output.Substring(output.IndexOf("MAC:") + 5, 17).ToUpper()}", Event.Success);
WaitFm.Caption("Connection was successful");
}
else
throw new Exception("Could not connect to the device.");
}
WaitFm.Caption("Erasing flash memory");
WaitFm.Debug("Erasing flash memory chip...");
if (!Program.Portable)
{
if (ShellManager.RunCommand(out output, "py", $"-m esptool {(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} erase_flash"))
{
WaitFm.Debug("Erase successful!", Event.Success);
WaitFm.Caption("Erased.");
}
else
throw new Exception("Failed to erase the device.");
}
else
{
if (ShellManager.RunCommand(out output, Program.Settings.EsptoolExe, $"{(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} erase_flash"))
{
WaitFm.Debug("Erase successful!", Event.Success);
WaitFm.Caption("Erased.");
}
else
throw new Exception("Failed to erase the device.");
}
WaitFm.Caption("Writing new software image");
WaitFm.Debug("Writing new software image...");
if (!Program.Portable)
{
if (ShellManager.RunCommand(out output, "py", $"-m esptool {(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} write_flash 0x0 \"{Program.Settings.Bin}\""))
{
WaitFm.Debug("Flash complete!", Event.Success);
WaitFm.Caption("Installed.");
}
else
throw new Exception("Failed to flash the device.");
}
else
{
if (ShellManager.RunCommand(out output, Program.Settings.EsptoolExe, $"{(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} write_flash 0x0 \"{Program.Settings.Bin}\""))
{
WaitFm.Debug("Erase successful!", Event.Success);
WaitFm.Caption("Erased.");
}
else
throw new Exception("Failed to flash the device.");
}
await Task.Delay(500);
await CreateMessage("Installation complete", $"The software package {Program.Settings.Bin} has been successfully" +
$" installed on your device. You can close this window.");
WaitFm.Host.CloseTask();
WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
TaskManager.ReleaseFLock();
return;
}
else
{
WaitFm.Debug("Failsafe: the selection was invalid.", Event.Critical);
await CreateMessage("Software installation aborted", "A problem was encountered with the selection. " +
"No changes have been made to your Espressif device. You can close this window.");
WaitFm.Host.CloseTask();
WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
TaskManager.ReleaseFLock();
return;
}
}
19
Source : WindowManager.cs
with GNU General Public License v3.0
from a4004
with GNU General Public License v3.0
from a4004
public static void MountWindow(Control.ControlCollection parent, Form window)
{
if (window.InvokeRequired)
{
Program.Debug("windowmgr", $"Request to mount {window.Name} into {parent.Owner.Name} requires control invokation.");
Program.Debug("windowmgr", "Invoking the request on the UI thread.");
window.Invoke(new Action(() => MountWindow(parent, window)));
return;
}
window.TopLevel = false;
window.Dock = DockStyle.Fill;
parent.Add(window);
window.Show();
window.BringToFront();
Program.Debug("windowmgr", $"Mounted window {window.Name} into {parent.Owner.Name}");
}
19
Source : WaitFm.cs
with GNU General Public License v3.0
from a4004
with GNU General Public License v3.0
from a4004
public static void Debug(string message, Event type = Event.Default)
{
if (Instance == null || Host.StartTime == default)
return;
else
{
if (Instance.InvokeRequired)
{
Instance.Invoke(new Action(() => Debug(message, type)));
return;
}
string debugOut = Host.DebugString(message);
Instance.debugOutput.Items.Add(debugOut);
Instance.debugOutput.SelectedIndex = Instance.debugOutput.Items.Count - 1;
Instance.debugOutput.SelectedIndex = -1;
Program.Debug(Host.Task, debugOut, type);
}
}
19
Source : MainWindow.cs
with GNU General Public License v3.0
from a4004
with GNU General Public License v3.0
from a4004
private async void Init()
{
if (Program.Portable)
goto InitTaskEnd;
InitPyChk:
WaitFm.Caption("Checking if Python is installed");
await Task.Delay(1000);
if (!ShellManager.CheckCommand("py", "--version"))
{
WaitFm.Debug("Python could not be detected on your system. You can choose to install Python or use N2D22 in portable mode.", Event.Warning);
CreateRequest("Python isn't installed on this PC", "You can choose to install Python",
"Install Python 3.9.7 (Recommended)", "Portable mode (Legacy, not recommended)", out int result);
if (result == 1 /*install python*/)
{
WaitFm.Caption("Downloading Python x64 3.9.7");
try
{
WebClient client = new WebClient();
client.DownloadProgressChanged += (s, e) =>
{
WaitFm.Caption($"Downloading Python x64 3.9.7 from python.org ({e.ProgressPercentage}%)");
};
client.DownloadFileCompleted += delegate
{
WaitFm.Debug("Successfully downloaded python-3.9.7-amd64.exe from python.org", Event.Success);
WaitFm.Caption("Installing Python x64 3.9.7");
};
WaitFm.Debug("Downloading python-3.9.7-amd64.exe from python.org");
await client.DownloadFileTaskAsync("https://www.python.org/ftp/python/3.9.7/python-3.9.7-amd64.exe", "python-3.9.7-amd64.exe");
WaitFm.Caption("Installing Python");
WaitFm.Debug("Installing Python x64 3.9.7");
if (ShellManager.RunCommand(out string output, "python-3.9.7-amd64.exe", "/quiet InstallAllUsers=1 PrependPath=1"))
{
WaitFm.Caption("Verifying Python is installed");
WaitFm.Debug("Verifying Python x64 3.9.7", Event.Success);
WaitFm.replacedle("Preparing");
await Task.Delay(1000);
goto InitPyChk;
}
else
throw new Exception(output == default ? "Process not started." : output);
}
catch (Exception ex)
{
WaitFm.Debug($"Python could not be installed due to an error. {ex.Message}", Event.Critical);
await CreateMessage("We couldn't install Python", "Something went wrong during the install process. You can try again.");
WaitFm.Host.CloseTask();
WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
TaskManager.ReleaseFLock();
return;
}
}
else if (result == 2 /*run in portable mode*/)
{
Process.Start(Application.ExecutablePath, string.Join(" ", Environment.GetCommandLineArgs()) + " --portable");
Program.Terminate();
return;
}
else
throw new Exception($"The selection could not be determined due to an invalid value. {result}");
}
else
{
if (ShellManager.RunCommand(out string filePath, "py", "-c \"import sys; print(sys.executable)\""))
WaitFm.Debug($"Python is installed on this PC at \"{filePath}\".", Event.Success);
else
WaitFm.Debug("Could not get the executable path of the Python binary.", Event.Warning);
Program.Settings.PythonExe = filePath;
WaitFm.replacedle("Getting ready");
WaitFm.Caption("Checking for esptool.py");
await Task.Delay(1000);
if (!ShellManager.CheckCommand("py", "-m esptool --help"))
{
WaitFm.Debug("esptool.py isn't installed in the default Python environment. " +
"You can choose to install esptool or use N2D22 in portable mode.");
CreateRequest("esptool.py is missing", "You can choose to install it right now",
"Install esptool.py (Recommended)", "Portable mode (Legacy, not recommended)", out int result);
if (result == 1 /*install esptool*/)
{
WaitFm.Debug("Installing esptool.py");
WaitFm.Caption("Installing esptool.py");
if (ShellManager.RunCommand(out string output, "py", "-m pip install esptool"))
{
WaitFm.Debug("esptool.py was installed successfully.");
WaitFm.replacedle("Preparing");
await Task.Delay(3000);
goto InitPyChk;
}
}
else if (result == 2 /*run in portable mode*/)
{
Process.Start(Application.ExecutablePath, string.Join(" ", Environment.GetCommandLineArgs()) + " --portable");
Program.Terminate();
return;
}
else
throw new Exception($"The selection could not be determined due to an invalid value. {result}");
}
else
{
WaitFm.Caption("Making sure you're ready to flash");
WaitFm.Debug("esptool.py is installed in the default Python environment.");
Program.Settings.EsptoolPy = true;
await Task.Delay(1000);
WaitFm.Debug("Searching for device drivers.");
await Task.Delay(1000);
string silabserPath = Directory.GetDirectories(Environment.SystemDirectory + "\\DriverStore\\FileRepository\\")
.ToList().Where(o => o.Contains("silabser")).FirstOrDefault();
WaitFm.Debug($"Check \"{Environment.SystemDirectory}\\DriverStore\\FileRepository\\\" for \"silabser\"");
string ch34serPath = Directory.GetDirectories(Environment.SystemDirectory + "\\DriverStore\\FileRepository\\")
.ToList().Where(o => o.Contains("ch341ser")).FirstOrDefault();
WaitFm.Debug($"Check \"{Environment.SystemDirectory}\\DriverStore\\FileRepository\\\" for \"ch34ser\"");
string ftdiPortPath = Directory.GetDirectories(Environment.SystemDirectory + "\\DriverStore\\FileRepository\\")
.ToList().Where(o => o.Contains("ftdiport")).FirstOrDefault();
WaitFm.Debug($"Check \"{Environment.SystemDirectory}\\DriverStore\\FileRepository\\\" for \"ftdiport\"");
string ftdiBusPath = Directory.GetDirectories(Environment.SystemDirectory + "\\DriverStore\\FileRepository\\")
.ToList().Where(o => o.Contains("ftdibus")).FirstOrDefault();
WaitFm.Debug($"Check \"{Environment.SystemDirectory}\\DriverStore\\FileRepository\\\" for \"ftdibus\"");
if (silabserPath == default && ch34serPath == default && ftdiPortPath == default && ftdiBusPath == default)
{
WaitFm.Debug("Driver files not found in FileRepository.", Event.Warning);
await CreateMessage("Device drivers not found", "We could not detect any Espressif compatible device drivers " +
"on this PC. You can still try flashing your device as Windows may automatically install the correct drivers " +
"for you.", 10);
}
else if (silabserPath != default && ch34serPath != default && ftdiPortPath != default && ftdiBusPath != default)
{
WaitFm.Debug("Detected drivers: SILABSER, CH34SER, FTDIPORT-FTDIBUS", Event.Success);
await CreateMessage("Found multiple device drivers", "We found device drivers for Silicon Labs, CH34 and FTDI compatible " +
"devices on this PC. The correct driver will automatically take control of your device when flashing.", 10);
}
else
{
if (silabserPath != default)
{
WaitFm.Debug("Detected driver: SILABSER", Event.Success);
await CreateMessage("Found device driver (Silicon Labs)", "We found a device driver for Silicon Labs devices on this PC. " +
"Please ensure it is the correct driver for your device otherwise flashing might not work.", 5);
}
if (ch34serPath != default)
{
WaitFm.Debug("Detected driver: CH34SER", Event.Success);
await CreateMessage("Found device driver (CH34)", "We found a device driver for CH34 devices on this PC. " +
"Please ensure it is the correct driver for your device otherwise flashing might not work.", 5);
}
if (ftdiBusPath != default && ftdiPortPath != default)
{
WaitFm.Debug("Detected driver: FTDIPORT-FTDIBUS", Event.Success);
await CreateMessage("Found device driver (FTDI)", "We found a device driver for FTDI devices on this PC. " +
"Please ensure it is the correct driver for your device otherwise flashing might not work.", 5);
}
else if (ftdiBusPath != default || ftdiPortPath != default)
{
WaitFm.Debug($"Detected partial driver: {(ftdiPortPath != default ? "FTDIPORT" : ftdiBusPath != default ? "FTDIBUS" : "?")}", Event.Warning);
await CreateMessage("Found device driver files (FTDI)", "We found parts of a device driver package for FTDU " +
"devices on this PC. The driver might not be installed correctly. Ensure the driver is correct and/or " +
"installed correctly.", 7);
}
}
}
}
InitTaskEnd:
WaitFm.Caption("");
await Task.Delay(1000);
WaitFm.Host.CloseTask();
WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
TaskManager.ReleaseFLock();
if (Program.Settings.PortFix)
{
Invoke(new Action(() =>
{
mitigationNotice.Show();
CreateForegroundTask("devicescan-patch", new Task(delegate() { }), "", "Please connect your device to this PC. When you've confirmed it's connected, click Continue.");
}));
}
else
{
Invoke(new Action(() =>
{
CreateForegroundTask("devicescan", new Task(Search), "Searching for your device", "You should connect your device now");
}));
}
}
19
Source : WindowManager.cs
with GNU General Public License v3.0
from a4004
with GNU General Public License v3.0
from a4004
public static void UnmountWindow(Control.ControlCollection parent, Form window)
{
if (window.InvokeRequired)
{
Program.Debug("windowmgr", $"Request to unmount {window.Name} into {parent.Owner.Name} requires control invokation.");
Program.Debug("windowmgr", "Invoking the request on the UI thread.");
window.Invoke(new Action(() => UnmountWindow(parent, window)));
return;
}
foreach (Form w in parent.OfType<Form>().Where(a => a.Handle == window.Handle))
{
Program.Debug("windowmgr", $"Removing window {window.Name} from {parent.Owner.Name}");
parent.Remove(w);
w.Close();
w.Dispose();
}
}
19
Source : WaitFm.cs
with GNU General Public License v3.0
from a4004
with GNU General Public License v3.0
from a4004
public static void Caption(string newText)
{
if (Instance == null)
return;
else
{
if (Instance.InvokeRequired)
{
Instance.Invoke(new Action(() => Caption(newText)));
return;
}
//Debug($"Changed caption to \"{newText}\" from \"{Instance.taskCaption.Text}\".");
Instance.taskCaption.Text = newText;
}
}
19
Source : MainWindow.cs
with GNU General Public License v3.0
from a4004
with GNU General Public License v3.0
from a4004
private async void Search()
{
await Task.Delay(1000);
WaitFm.Debug("Searching for devices...");
int threshold = 1;
Rescan:
while (SerialBusManager.SerialPorts.Count() < threshold)
{
await Task.Delay(1000);
WaitFm.Debug($"Searching for devices... {(threshold - 1 == 1 ? "[1 device is connected, but you've chosen to not use it]" : (threshold - 1 > 1 ? $"[{threshold - 1} devices are connected, but you've chosen not to use them]" : ""))}");
}
WaitFm.Debug($"Detected {SerialBusManager.SerialDevices[threshold - 1]} on {SerialBusManager.SerialPorts[threshold - 1]}");
CreateRequest($"Found new device ({SerialBusManager.SerialPorts[threshold - 1]})",
SerialBusManager.SerialDevices[threshold - 1], "Use this device", "Don't use this device", out int option);
if (option == 2)
{
threshold++;
WaitFm.Debug($"The device was rejected by the user, device threshold is now {threshold} (was {threshold - 1})", Event.Warning);
goto Rescan;
}
else if (option == 1)
{
Program.Settings.SelectedPort = SerialBusManager.SerialPorts[threshold - 1];
Program.Settings.SelectedName = SerialBusManager.SerialDevices[threshold - 1];
WaitFm.replacedle("Connecting to your device");
if (!Program.Settings.PortFix)
WaitFm.Caption($"Connecting to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}");
if (!Program.Settings.PortFix)
WaitFm.Debug($"Connecting to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}...");
if (!Program.Portable)
{
if (ShellManager.RunCommand(out string output, "py", $"-m esptool {(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} read_mac"))
{
if (!Program.Settings.PortFix)
WaitFm.Debug($"Connected to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}", Event.Success);
WaitFm.Debug($"Espressif device MAC: {output.Substring(output.IndexOf("MAC:") + 5, 17).ToUpper()}", Event.Success);
WaitFm.Caption("The device is working correctly");
WaitFm.replacedle($"Connected to {Program.Settings.SelectedName}");
await Task.Delay(1000);
WaitFm.Host.CloseTask();
WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
TaskManager.ReleaseFLock();
Invoke(new Action(() =>
{
CreateForegroundTask("flasher", new Task(Flash), "Getting ready", "");
}));
}
else
{
WaitFm.Debug($"Failed to obtain the device MAC, the esptool didn't connect. {output}", Event.Critical);
if (SerialBusManager.SerialPorts.Count() > threshold)
{
await CreateMessage("Couldn't connect", "A connection to the device could not be established. You have multiple devices connected, it might be the next one.", 5);
threshold++;
goto Rescan;
}
else
{
await CreateMessage("There was a problem", "A connection to the device could not be established.");
WaitFm.Host.CloseTask();
WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
TaskManager.ReleaseFLock();
return;
}
}
}
else
{
if (ShellManager.RunCommand(out string output, Program.Settings.EsptoolExe, $"{(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} read_mac"))
{
if (!Program.Settings.PortFix)
WaitFm.Debug($"Connected to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}", Event.Success);
WaitFm.Debug($"Espressif device MAC: {output.Substring(output.IndexOf("MAC:") + 5, 17).ToUpper()}", Event.Success);
WaitFm.Caption("The device is working correctly");
WaitFm.replacedle($"Connected to {Program.Settings.SelectedName}");
await Task.Delay(1000);
WaitFm.Host.CloseTask();
WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
TaskManager.ReleaseFLock();
Invoke(new Action(() =>
{
CreateForegroundTask("flasher", new Task(Flash), "Getting ready", "");
}));
}
else
{
WaitFm.Debug($"Failed to obtain the device MAC, the esptool didn't connect. {output}", Event.Critical);
if (SerialBusManager.SerialPorts.Count() > threshold)
{
await CreateMessage("Couldn't connect", "A connection to the device could not be established. You have multiple devices connected, it might be the next one.", 5);
threshold++;
goto Rescan;
}
else
{
await CreateMessage("There was a problem", "A connection to the device could not be established.");
WaitFm.Host.CloseTask();
WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
TaskManager.ReleaseFLock();
return;
}
}
}
}
else
throw new Exception($"The selection could not be determined due to an invalid value. {option}");
}
19
Source : WaitFm.cs
with GNU General Public License v3.0
from a4004
with GNU General Public License v3.0
from a4004
public static void replacedle(string newText)
{
if (Instance == null)
return;
else
{
if (Instance.InvokeRequired)
{
Instance.Invoke(new Action(() => replacedle(newText)));
return;
}
//Debug($"Changed replacedle to \"{newText}\" from \"{Instance.taskreplacedle.Text}\".");
Instance.taskreplacedle.Text = newText;
}
}
19
Source : MainWindow.cs
with GNU General Public License v3.0
from a4004
with GNU General Public License v3.0
from a4004
private void CreateRequest(string replacedle, string caption, string option1, string option2, out int result)
{
if (InvokeRequired)
{
Invoke(new Action(() =>
{
RequestFm newRequest = new RequestFm(replacedle, caption, option1, option2);
WindowManager.MountWindow(Controls, newRequest);
}));
}
else
{
RequestFm newRequest = new RequestFm(replacedle, caption, option1, option2);
WindowManager.MountWindow(Controls, newRequest);
}
CheckForIllegalCrossThreadCalls = false;
while (!RequestFm.Instance.IsDisposed) ;
CheckForIllegalCrossThreadCalls = true;
result = RequestFm.Option;
}
19
Source : MainWindow.cs
with GNU General Public License v3.0
from a4004
with GNU General Public License v3.0
from a4004
private bool CreateSelRequest(out string file)
{
string[] tags = GithubManager.GetReleaseTags("spacehuhntech/esp8266_deauther");
string latest = GithubManager.GetLatestTag("spacehuhntech/esp8266_deauther");
Program.Debug("github", $"Latest software version: {latest}");
if (InvokeRequired)
{
Invoke(new Action(() =>
{
SelectFm newRequest = new SelectFm(tags, latest);
WindowManager.MountWindow(Controls, newRequest);
}));
}
else
{
SelectFm newRequest = new SelectFm(tags, latest);
WindowManager.MountWindow(Controls, newRequest);
}
CheckForIllegalCrossThreadCalls = false;
while (SelectFm.Instance.DialogResult == DialogResult.None) ;
CheckForIllegalCrossThreadCalls = true;
bool result = SelectFm.Instance.DialogResult == DialogResult.Yes;
file = SelectFm.SelectedOption;
WindowManager.UnmountWindow(Controls, SelectFm.Instance);
return result;
}
19
Source : MainWindow.cs
with GNU General Public License v3.0
from a4004
with GNU General Public License v3.0
from a4004
private async Task CreateMessage(string replacedle, string caption, int expire = 0)
{
Invoke(new Action(() =>
{
MessageFm newMsg = new MessageFm(replacedle, caption);
WindowManager.MountWindow(Controls, newMsg);
}));
if (expire > 0)
{
for (int i = 0; i < expire; i++)
await Task.Delay(1000);
WindowManager.UnmountWindow(Controls, MessageFm.Instance);
}
}
19
Source : UI.cs
with MIT License
from aaaddress1
with MIT License
from aaaddress1
private void compile_Click(object sender, EventArgs e)
{
(new System.Threading.Thread(() =>
{
this.Invoke((MethodInvoker)delegate () {
compile.Enabled = false;
logBox.Clear();
logMsg(demostr, Color.Blue);
this.splitContainer.Panel2Collapsed = false;
this.logPanelBtn.Text = "x";
});
File.WriteAllText(srcPath, this.fastColoredTextBox.Text);
File.Delete(exePath);
File.Delete(asmPath);
File.Delete(obfAsmPath);
logMsg(" --- \n", Color.Blue);
logMsg(string.Format(
"[\tInfo\t] current compile info... \n" +
" - source: {0}\n" +
" - asm path: {1}\n" +
" - obfuscated asm path: {2}\n" +
" - output exe path: {3}\n", srcPath, asmPath, obfAsmPath, exePath), Color.Blue);
if (compiler.geneateAsmSource(srcPath, asmPath))
logMsg("[\tOK\t] generate replacedembly code of source code.", Color.Green);
else
{
logMsg("[\tFail\t] generate replacedembly code of sorce code failure ...", Color.Red);
this.Invoke((MethodInvoker)delegate () { compile.Enabled = true; });
return;
}
if (obfuscator.obfuscaAsm(asmPath, obfAsmPath))
logMsg("[\tOK\t] generate obfuscated replacedembly code of source code.", Color.Green);
else
{
logMsg("[\tFail\t] generate obfuscated replacedembly code of sorce code failure ...", Color.Red);
this.Invoke((MethodInvoker)delegate () { compile.Enabled = true; });
return;
}
if (compiler.generateExe(obfAsmPath, exePath))
{
var arr = System.IO.File.ReadAllBytes(exePath);
var size = arr.Length;
var md5 = BitConverter.ToString(MD5.Create().ComputeHash(arr)).Replace("-", "");
var sha256 = BitConverter.ToString(SHA256.Create().ComputeHash(arr)).Replace("-", "");
logMsg("[\tInfo\t] exe size: " + size + " bytes", Color.Blue);
logMsg("[\tInfo\t] MD5: " + md5, Color.Blue);
logMsg("[\tInfo\t] SHA256: " + sha256, Color.Blue);
logMsg("[\tOK\t] generate executable file successfully :)", Color.Green);
}
else
logMsg("[\tFail\t] generate executable file failure ... o___O", Color.Red);
if (Properties.Settings.Default.clnAftCompile)
{
File.Delete(asmPath);
File.Delete(obfAsmPath);
}
this.Invoke((MethodInvoker)delegate () { compile.Enabled = true; });
})
{ IsBackground = true }).Start();
}
19
Source : ControlBridge.cs
with GNU General Public License v3.0
from AdamWhiteHat
with GNU General Public License v3.0
from AdamWhiteHat
public static void SetControlEnabledState(Control control, bool enabled)
{
if (control.IsDisposed || !control.IsHandleCreated)
{
throw new Exception();
}
if (control.InvokeRequired /* && !GNFSCore.DirectoryLocations.IsLinuxOS()*/)
{
control.Invoke(new Action(() => { SetControlEnabledState(control, enabled); }));
}
else
{
control.Enabled = enabled;
}
}
19
Source : ControlBridge.cs
with GNU General Public License v3.0
from AdamWhiteHat
with GNU General Public License v3.0
from AdamWhiteHat
public static void SetControlVisibleState(Control control, bool visible)
{
if (control.IsDisposed || !control.IsHandleCreated)
{
throw new Exception();
}
if (control.InvokeRequired /* && !GNFSCore.DirectoryLocations.IsLinuxOS()*/)
{
control.Invoke(new Action(() => { SetControlVisibleState(control, visible); }));
}
else
{
control.Visible = visible;
}
}
19
Source : ControlBridge.cs
with GNU General Public License v3.0
from AdamWhiteHat
with GNU General Public License v3.0
from AdamWhiteHat
public static void SetControlText(Control control, string text)
{
if (control.IsDisposed || !control.IsHandleCreated)
{
throw new Exception();
}
if (control.InvokeRequired /* && !GNFSCore.DirectoryLocations.IsLinuxOS()*/)
{
control.Invoke(new Action(() => { SetControlText(control, text); }));
}
else
{
control.Text = text;
}
}
19
Source : Logging.cs
with GNU General Public License v3.0
from AdamWhiteHat
with GNU General Public License v3.0
from AdamWhiteHat
public static void LogTextbox(string message)
{
//if (GNFSCore.DirectoryLocations.IsLinuxOS())
//{
// return;
//}
if (OutputTextbox.IsDisposed || !OutputTextbox.IsHandleCreated)
{
throw new Exception();
}
if (OutputTextbox.InvokeRequired /* && !GNFSCore.DirectoryLocations.IsLinuxOS()*/)
{
OutputTextbox.Invoke(new Action(() => { LogTextbox(message); }));
}
else
{
string toLog = message;
if (PrimaryForm.IsWorking)
{
toLog = "\t" + message;
}
if (OutputTextbox.Lines.Length > MaxLines)
{
OutputTextbox.Clear();
}
OutputTextbox.AppendText(toLog);
}
}
19
Source : MainForm.cs
with GNU General Public License v3.0
from AdamWhiteHat
with GNU General Public License v3.0
from AdamWhiteHat
private static void SetGnfs(MainForm form, GNFS gnfs)
{
if (form.IsDisposed || !form.IsHandleCreated)
{
throw new Exception();
}
if (form.InvokeRequired)
{
form.Invoke(new Action(() => SetGnfs(form, gnfs)));
}
else
{
form._gnfs = gnfs;
form.N = gnfs.N;
form.Degree = gnfs.PolynomialDegree;
form.Base = gnfs.PolynomialBase;
form.Bound = gnfs.PrimeFactorBase.RationalFactorBaseMax;
form.tbRelationQuanreplacedy.Text = gnfs.CurrentRelationsProgress.SmoothRelations_TargetQuanreplacedy.ToString();
form.tbRelationValueRange.Text = gnfs.CurrentRelationsProgress.ValueRange.ToString();
}
}
19
Source : Form1.cs
with The Unlicense
from ADeltaX
with The Unlicense
from ADeltaX
private void T_Tick(object sender, EventArgs e)
{
this.Invoke(new Action(() =>
{
this.Text = "Creating controls....";
Stopwatch sp = Stopwatch.StartNew();
Controls.Clear();
for (int i = 0; i < columnGrid; i++)
{
for (int j = 0; j < columnGrid + 1; j++) // 100 controls instead of 99
{
Control b = new Control();
b.Height = size;
b.Width = size;
b.Padding = Padding.Empty;
b.Margin = Padding.Empty;
//Random may slow down a bit, but it's for visual
//To test controls generation speed properly, please set a fixed color.
b.BackColor = Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256));
b.Location = new Point(i * size, j * size);
Controls.Add(b);
}
}
label1.Visible = false;
sp.Stop();
this.Text = "Controls created in: " + sp.Elapsed.ToString("mm\\:ss\\.fff");
}));
t.Stop();
}
19
Source : EpubViewer.cs
with MIT License
from Aeroblast
with MIT License
from Aeroblast
private void OnLoad(Object sender, EventArgs e)
{
//chromium.ShowDevTools();
refreshForm = new RefreshForm(() =>
{
Activate();
Focus();
});
Invoke(refreshForm);
}
19
Source : Authentication.cs
with Apache License 2.0
from aequabit
with Apache License 2.0
from aequabit
public void Unlock()
{
this.Invoke((MethodInvoker)delegate
{
this.Enabled = true;
});
}
19
Source : Authentication.cs
with Apache License 2.0
from aequabit
with Apache License 2.0
from aequabit
public void Kill()
{
terminate = false;
this.Invoke((MethodInvoker)delegate
{
this.Close();
});
}
19
Source : Loader.cs
with Apache License 2.0
from aequabit
with Apache License 2.0
from aequabit
public void InjectionFinished()
{
this.Invoke((MethodInvoker)delegate
{
UI.MsgBox.Show("Successfully loaded " + lstCheatList.SelectedItem.ToString() + "!", "Injection successful", MessageBoxIcon.Information);
Worker.instance.Shutdown();
});
}
19
Source : Loader.cs
with Apache License 2.0
from aequabit
with Apache License 2.0
from aequabit
public void AddProduct(Product product)
{
this.Invoke((MethodInvoker)delegate
{
products.Add(product);
lstCheatList.Items.Add(product.name);
});
}
19
Source : MainForm.cs
with GNU General Public License v3.0
from AgentRev
with GNU General Public License v3.0
from AgentRev
private void UpdateResponse(IAsyncResult result)
{
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
Stream resStream = response.GetResponseStream();
string tempString;
int count;
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[0x2000];
do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(buf, 0, count);
sb.Append(tempString);
}
}
while (count > 0);
string returnData = sb.ToString();
string dataVer = Regex.Match(returnData, @"FoVChangerVer\[([0-9\.]*?)\]").Groups[1].Value;
string dataSafe = Regex.Match(returnData, @"SafeToUse\[([A-Za-z]*?)\]").Groups[1].Value;
string dataInfo = Regex.Unescape(HttpUtility.HtmlDecode(Regex.Match(returnData, @"UpdateInfo\[(.*?)\]").Groups[1].Value));
string dataDownloadLink = Regex.Match(returnData, @"DownloadLink\[(.*?)\]").Groups[1].Value;
string datareplacedytics = Regex.Match(returnData, @"Googlereplacedytics\[([A-Za-z\-0-9]*?)\]").Groups[1].Value;
string dataIPService = Regex.Match(returnData, @"IPService\[(.*?)\]").Groups[1].Value;
//MessageBox.Show(dataSafe);
if (!String.IsNullOrEmpty(dataSafe) && dataSafe.ToLower() == "vacdetected")
{
this.Invoke(new Action(() =>
{
DialogResult vacResult = MessageBox.Show(this, "It has been reported that this FoV Changer may cause anti-cheat software to trigger a ban. " +
"For any information, please check github.com/AgentRev/CoD-FoV-Changers\n\n" +
"Click 'OK' to exit the program, or 'Cancel' to continue using it AT YOUR OWN RISK.",
"Detection alert", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
if (vacResult == DialogResult.OK)
Application.Exit();
}));
}
//MessageBox.Show(dataVer);
if (!String.IsNullOrEmpty(dataVer) && VersionNum(dataVer) > VersionNum(c_toolVer))
{
this.Invoke(new Action(() =>
{
updateAvailable = true;
if (chkUpdate.Checked && updateNotify)
{
MessageBox.Show(this, "Update v" + dataVer + " is available at MapModNews.com\nClicking the \"Help\" button below will take you to the download page." + (!String.IsNullOrEmpty(dataInfo) ? "\n\nInfos:\n" + dataInfo : ""),
"Update available", MessageBoxButtons.OK, MessageBoxIcon.Information,
MessageBoxDefaultButton.Button1, 0, (!String.IsNullOrEmpty(dataDownloadLink) ? dataDownloadLink : "http://ghostsfov.ftp.sh/"));
lblUpdateAvail.Text = "Update v" + dataVer + " available";
lblUpdateAvail.Enabled = true;
lblUpdateAvail.Visible = true;
TimerBlink.Start();
}
else
{
requestSent = false;
}
}));
}
if (!String.IsNullOrEmpty(datareplacedytics))
{
Greplacedytics.trackingID = datareplacedytics;
}
if (!String.IsNullOrEmpty(dataIPService))
{
Greplacedytics.ipService = dataIPService;
}
}
catch {}
try
{
Greplacedytics.Triggerreplacedytics((string)gameMode.GetValue("c_settingsDirName") + " v" + c_toolVer, firstTime);
}
catch {}
}
19
Source : MainForm.cs
with GNU General Public License v3.0
from AgentRev
with GNU General Public License v3.0
from AgentRev
private void UpdateResponse(IAsyncResult result)
{
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
Stream resStream = response.GetResponseStream();
string tempString;
int count;
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[0x2000];
do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(buf, 0, count);
sb.Append(tempString);
}
}
while (count > 0);
string dataVer = Regex.Match(sb.ToString(), @"FoVChangerVer\[([0-9\.]*?)\]").Groups[1].Value;
string dataSafe = Regex.Match(sb.ToString(), @"SafeToUse\[([A-Za-z]*?)\]").Groups[1].Value;
string dataInfo = Regex.Unescape(HttpUtility.HtmlDecode(Regex.Match(sb.ToString(), @"UpdateInfo\[(.*?)\]").Groups[1].Value));
//MessageBox.Show(dataVer);
if (!String.IsNullOrEmpty(dataSafe) && dataSafe.ToLower() == "vacdetected")
{
this.Invoke(new Action(() =>
{
DialogResult vacResult = MessageBox.Show(this, "It has been reported that this FoV Changer may cause Valve Anti-Cheat to trigger a ban. " +
"For any information, please check MapModNews.com.\n\n" +
"Click 'OK' to exit the program, or 'Cancel' to continue using it AT YOUR OWN RISK.",
"Detection alert", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
if (vacResult == DialogResult.OK)
Application.Exit();
}));
}
//MessageBox.Show(dataVer);
if (!String.IsNullOrEmpty(dataVer) && VersionNum(dataVer) > VersionNum(c_toolVer))
{
this.Invoke(new Action(() =>
{
if (updateChk)
MessageBox.Show(this, "Update v" + dataVer + " for the FoV Changer is available at MapModNews.com, or can be downloaded directly \nby clicking the \"Help\" button below." + (!String.IsNullOrEmpty(dataInfo) ? "\n\nAdditional infos:\n" + dataInfo : ""),
"Update available", MessageBoxButtons.OK, MessageBoxIcon.Information,
MessageBoxDefaultButton.Button1, 0, "http://mw3fov.ftp.sh/");
lblUpdateAvail.Text = " - Update v" + dataVer + " available";
lblUpdateAvail.Enabled = true;
lblUpdateAvail.Visible = true;
TimerBlink.Start();
}));
}
}
catch {}
requestSent = false;
}
19
Source : MainWindow.cs
with GNU General Public License v3.0
from aglab2
with GNU General Public License v3.0
from aglab2
private void SafeInvoke(MethodInvoker updater, bool forceSynchronous = false)
{
if (InvokeRequired)
{
if (forceSynchronous)
{
Invoke((MethodInvoker)delegate { SafeInvoke(updater, forceSynchronous); });
}
else
{
BeginInvoke((MethodInvoker)delegate { SafeInvoke(updater, forceSynchronous); });
}
}
else
{
if (IsDisposed)
{
throw new ObjectDisposedException("Control is already disposed.");
}
updater();
}
}
19
Source : GettingStarted.cs
with MIT License
from AlbertMN
with MIT License
from AlbertMN
public void SendTranslationToWeb() {
//theWebBrowser.Invoke(new Action(() => {
//theWebBrowser.Doreplacedent.InvokeScript("actionWentThrough", objArray);
//}));
//var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
//var json = serializer.Serialize(Translator.languagesArray);
//TODO; check why this crashed once. Have not been able to re-create.
/*
* Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Cannot perform runtime binding on a null reference'
*/
object obj2 = null;
if (Translator.activeLanguage != "English") {
obj2 = Convert.ToString(Translator.fallbackDynamicJsonTranslation["translations"]["getting_started"]);
}
theWebBrowser.Invoke(new Action(() => {
theWebBrowser.Doreplacedent.InvokeScript(
"SetTranslation",
new Object[2] {
Convert.ToString(Translator.dynamicJsonTranslation["translations"]["getting_started"]),
obj2
}
);
}));
}
19
Source : GettingStarted.cs
with MIT License
from AlbertMN
with MIT License
from AlbertMN
public void CloudServiceChosen(string service = "") {
switch (service) {
case "dropbox":
case "onedrive":
case "googledrive":
backgroundCheckerServiceName = service;
break;
default:
return;
}
if (CloudServiceFunctions.GetCloudServicePath(backgroundCheckerServiceName) != "") {
//Cloud service found
MainProgram.DoDebug("Cloud service " + backgroundCheckerServiceName + " is installed");
bool partial = false;
if (backgroundCheckerServiceName == "googledrive") {
partial = CloudServiceFunctions.GetGoogleDriveFolder() != String.Empty;
}
if (theWebBrowser != null) {
IntPtr theHandle = IntPtr.Zero;
try {
theHandle = theWebBrowser.Handle;
} catch {
MainProgram.DoDebug("Failed to get web browser handle.");
MessageBox.Show(Translator.__("cloud_setup_failed", "general"), MainProgram.messageBoxreplacedle);
}
if (theHandle != IntPtr.Zero) {
if (theWebBrowser.Handle != null) {
theWebBrowser.Doreplacedent.InvokeScript("CloudServiceInstalled", new Object[2] { true, partial });
}
}
}
if (partial) {
CheckLocalGoogleDrive();
}
} else {
//Not found
new Thread(() => {
Thread.CurrentThread.IsBackground = true;
string checkValue = "";
stopCheck = false;
MainProgram.DoDebug("Could not find cloud service. Running loop to check");
while (checkValue == "" && !stopCheck) {
checkValue = CloudServiceFunctions.GetCloudServicePath(backgroundCheckerServiceName);
Thread.Sleep(1000);
}
if (stopCheck) {
stopCheck = false;
return;
}
//Cloud service has been installed since we last checked!
MainProgram.DoDebug("Cloud service has been installed since last check. Proceed.");
if (theWebBrowser != null) {
if (theWebBrowser.Handle != null) {
theWebBrowser.Invoke(new Action(() => {
if (backgroundCheckerServiceName == "googledrive") {
bool partial = CloudServiceFunctions.GetGoogleDriveFolder() != String.Empty;
theWebBrowser.Doreplacedent.InvokeScript("CloudServiceInstalled", new Object[2] { true, partial });
if (partial)
CheckLocalGoogleDrive();
} else {
theWebBrowser.Doreplacedent.InvokeScript("CloudServiceInstalled", new Object[1] { true });
}
}));
}
}
}).Start();
}
}
19
Source : GettingStarted.cs
with MIT License
from AlbertMN
with MIT License
from AlbertMN
private void CheckLocalGoogleDrive() {
new Thread(() => {
Thread.CurrentThread.IsBackground = true;
stopCheck = false;
MainProgram.DoDebug("Starting loop to check for Google Drive folder locally");
while (backgroundCheckerServiceName == "googledrive" && CloudServiceFunctions.GetGoogleDriveFolder() == String.Empty && !stopCheck) {
Thread.Sleep(1000);
}
if (stopCheck) {
stopCheck = false;
return;
}
if (backgroundCheckerServiceName == "googledrive") {
//Cloud service has been installed since we last checked!
MainProgram.DoDebug("Google Drive has been added to local PC. Proceed.");
theWebBrowser.Invoke(new Action(() => {
theWebBrowser.Doreplacedent.InvokeScript("CloudServiceInstalled", new Object[2] { true, false });
}));
} else {
MainProgram.DoDebug("Service has since been changed. Stopping the search for Google Drive.");
}
}).Start();
}
19
Source : GettingStarted.cs
with MIT License
from AlbertMN
with MIT License
from AlbertMN
public void SendActionThrough(Object[] objArray) {
/*if ((string)objArray[0] == "success") { //We don't wanna do this...
SetupDone();
}*/
this.Invoke(new Action(() => {
FlashWindow.Flash(this);
if (Application.OpenForms[this.Name] != null) {
Application.OpenForms[this.Name].Activate();
Application.OpenForms[this.Name].Focus();
}
}));
theWebBrowser.Invoke(new Action(() => {
theWebBrowser.Doreplacedent.InvokeScript("actionWentThrough", objArray);
}));
}
19
Source : TestActionWindow.cs
with MIT License
from AlbertMN
with MIT License
from AlbertMN
private void SetImage(Images img, string heading = "", string description = "") {
Object[] objArray = new Object[2];
objArray[0] = heading;
objArray[1] = description;
if (browserLoaded) {
string function;
switch (img) {
case Images.loading:
function = "showLoader";
break;
case Images.success:
function = "showSuccess";
break;
case Images.error:
function = "showError";
break;
default:
return;
}
MainProgram.DoDebug("Executing function; " + function);
if (!this.IsHandleCreated) {
this.CreateHandle();
}
sWebBrowser.Invoke(new Action(() => {
sWebBrowser.Doreplacedent.InvokeScript(function, objArray);
MainProgram.DoDebug("Function '" + function + "' should be executing in the Web Browser window");
}));
}
}
19
Source : MainForm.cs
with MIT License
from AlexanderPro
with MIT License
from AlexanderPro
private void KeyHooked(object sender, EventArgs e)
{
if (InvokeRequired)
{
Invoke(new Action(ShowListerForm));
}
else
{
ShowListerForm();
}
}
19
Source : MainForm.cs
with GNU General Public License v3.0
from alexgracianoarj
with GNU General Public License v3.0
from alexgracianoarj
private void mnuFromDatabase_Click(object sender, EventArgs e)
{
var connectionDialog = new ConnectionDialog();
if (connectionDialog.ShowDialog() == DialogResult.OK)
{
// Initialize the dialog that will contain the progress bar
ProgressDialog progressDialog = new ProgressDialog();
// Set the dialog to operate in indeterminate mode
progressDialog.SetIndeterminate(true);
DatabaseCSharpDiagramGenerator databaseDiagram = null;
DatabaseObjects chooseObjects = null;
bool hasErrors = false;
// Initialize the thread that will handle the background process
Thread backgroundThread = new Thread(
new ThreadStart(() =>
{
try
{
databaseDiagram = new DatabaseCSharpDiagramGenerator(connectionDialog.Connection);
Thread.Sleep(500);
}
catch (Exception ex)
{
hasErrors = true;
Invoke(new MethodInvoker(() =>
{
MessageBox.Show(
this,
ex.Message,
Translations.Strings.Error,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}));
}
finally
{
// Close the dialog if it hasn't been already
if (progressDialog.InvokeRequired)
progressDialog.BeginInvoke(new Action(() => progressDialog.Close()));
}
}));
// Sets to single thread apartment (STA) mode before OLE calls
backgroundThread.SetApartmentState(ApartmentState.STA);
// Start the background process thread
backgroundThread.Start();
// Open the dialog
progressDialog.ShowDialog();
if(!hasErrors)
{
chooseObjects = new DatabaseObjects(databaseDiagram.Tables, databaseDiagram.Views);
if (chooseObjects.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
databaseDiagram.Tables = chooseObjects.Tables;
databaseDiagram.Views = chooseObjects.Views;
databaseDiagram.ConvertToPascalCase = chooseObjects.ConvertToPascalCase;
}
else
{
return;
}
progressDialog = new ProgressDialog();
progressDialog.SetIndeterminate(true);
backgroundThread = new Thread(
new ThreadStart(() =>
{
try
{
databaseDiagram.Generate();
Thread.Sleep(500);
}
catch (Exception ex)
{
Invoke(new MethodInvoker(() =>
{
MessageBox.Show(
this,
ex.Message,
Translations.Strings.Error,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}));
}
finally
{
if (progressDialog.InvokeRequired)
progressDialog.BeginInvoke(new Action(() => progressDialog.Close()));
}
}));
backgroundThread.SetApartmentState(ApartmentState.STA);
backgroundThread.Start();
progressDialog.ShowDialog();
Workspace.Default.AddProject(databaseDiagram.ProjectGenerated);
}
}
}
19
Source : ConnectionDialog.cs
with GNU General Public License v3.0
from alexgracianoarj
with GNU General Public License v3.0
from alexgracianoarj
private void btnConnect_Click(object sender, EventArgs e)
{
if (isProcessRunning)
return;
IList<DatabaseDbSchema> schemas = new List<DatabaseDbSchema>();
string connectionStr = connectionStringTextBox.Text.Trim();
SqlType serverType = (SqlType)serverTypeComboBox.SelectedItem;
// Initialize the dialog that will contain the progress bar
ProgressDialog progressDialog = new ProgressDialog();
// Set the dialog to operate in indeterminate mode
progressDialog.SetIndeterminate(true);
// Initialize the thread that will handle the background process
Thread backgroundThread = new Thread(
new ThreadStart(() =>
{
try
{
isProcessRunning = true;
//Create the database reader object.
var metadataReader = new DatabaseReader(connectionStr, serverType);
schemas = metadataReader.AllSchemas();
if (cboSchema.InvokeRequired)
cboSchema.BeginInvoke(new Action(() =>
{
cboSchema.DataSource = schemas.Select(x => x.Name).ToList();
}));
Thread.Sleep(500);
}
catch (Exception ex)
{
Invoke(new MethodInvoker(() =>
{
MessageBox.Show(
this,
ex.Message,
Translations.Strings.Error,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}));
}
finally
{
isProcessRunning = false;
if (progressDialog.InvokeRequired)
progressDialog.BeginInvoke(new Action(() => progressDialog.Close()));
}
}));
// Sets to single thread apartment (STA) mode before OLE calls
backgroundThread.SetApartmentState(ApartmentState.STA);
// Start the background process thread
backgroundThread.Start();
// Open the dialog
progressDialog.ShowDialog();
}
19
Source : MarketDepthPainter.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
public void StopPaint()
{
try
{
if (_glreplacedBox != null && _glreplacedBox.InvokeRequired)
{
_glreplacedBox.Invoke(new Action(StopPaint));
return;
}
if (_textBoxLimitPrice != null)
{
_textBoxLimitPrice.TextChanged -= _textBoxLimitPrice_TextChanged;
_textBoxLimitPrice = null;
}
if (_hostGlreplaced != null)
{
_hostGlreplaced.Child = null;
_hostGlreplaced = null;
}
}
catch (Exception error)
{
SendNewLogMessage(error.ToString(), LogMessageType.Error);
}
}
19
Source : Log.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
public void Clear()
{
if (_grid != null &&
_grid.InvokeRequired)
{
_grid.Invoke(new Action(Clear));
return;
}
try
{
if (_messageses != null)
{
_messageses.Clear();
}
_incomingMessages = new ConcurrentQueue<LogMessage>();
if (_grid != null)
{
_grid.Rows.Clear();
}
}
catch
{
// ignore
}
}
19
Source : OptimizerDataStorageUi.xaml.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private void PaintGrid()
{
if (_myGridView.InvokeRequired)
{
_myGridView.Invoke(new Action(PaintGrid));
return;
}
SliderFrom.ValueChanged -= SliderFrom_ValueChanged;
SliderTo.ValueChanged -= SliderTo_ValueChanged;
_myGridView.Rows.Clear();
List<SecurityTester> securities = _server.SecuritiesTester;
if (securities != null && securities.Count != 0)
{
for (int i = 0; i < securities.Count; i++)
{
DataGridViewRow nRow = new DataGridViewRow();
nRow.Cells.Add(new DataGridViewTextBoxCell());
nRow.Cells[0].Value = securities[i].FileAdress;
nRow.Cells.Add(new DataGridViewTextBoxCell());
nRow.Cells[1].Value = securities[i].Security.Name;
if (securities[i].DataType == SecurityTesterDataType.Candle)
{
DataGridViewComboBoxCell comboBox = new DataGridViewComboBoxCell();
comboBox.Items.Add(TimeFrame.Day.ToString());
comboBox.Items.Add(TimeFrame.Hour1.ToString());
comboBox.Items.Add(TimeFrame.Hour2.ToString());
comboBox.Items.Add(TimeFrame.Hour4.ToString());
comboBox.Items.Add(TimeFrame.Min1.ToString());
comboBox.Items.Add(TimeFrame.Min2.ToString());
comboBox.Items.Add(TimeFrame.Min5.ToString());
comboBox.Items.Add(TimeFrame.Min3.ToString());
comboBox.Items.Add(TimeFrame.Min10.ToString());
comboBox.Items.Add(TimeFrame.Min15.ToString());
comboBox.Items.Add(TimeFrame.Min30.ToString());
comboBox.Items.Add(TimeFrame.Min45.ToString());
nRow.Cells.Add(comboBox);
nRow.Cells[2].Value = securities[i].TimeFrame.ToString();
}
else
{
nRow.Cells.Add(new DataGridViewTextBoxCell());
nRow.Cells[2].Value = securities[i].DataType;
}
nRow.Cells.Add(new DataGridViewTextBoxCell());
nRow.Cells[3].Value = securities[i].Security.PriceStep.ToStringWithNoEndZero();
nRow.Cells.Add(new DataGridViewTextBoxCell());
nRow.Cells[4].Value = securities[i].TimeStart;
nRow.Cells.Add(new DataGridViewTextBoxCell());
nRow.Cells[5].Value = securities[i].TimeEnd;
_myGridView.Rows.Add(nRow);
}
}
TextBoxFrom.Text = _server.TimeStart.ToString(new CultureInfo("RU-ru"));
TextBoxTo.Text = _server.TimeEnd.ToString(new CultureInfo("RU-ru"));
SliderFrom.Minimum = (_server.TimeMin - DateTime.MinValue).TotalMinutes;
SliderFrom.Maximum = (_server.TimeMax - DateTime.MinValue).TotalMinutes;
SliderFrom.Value = (_server.TimeStart - DateTime.MinValue).TotalMinutes;
SliderTo.Minimum = (_server.TimeMin - DateTime.MinValue).TotalMinutes;
SliderTo.Maximum = (_server.TimeMax - DateTime.MinValue).TotalMinutes;
SliderTo.Value = (_server.TimeMin - DateTime.MinValue).TotalMinutes;
SliderFrom.ValueChanged += SliderFrom_ValueChanged;
SliderTo.ValueChanged += SliderTo_ValueChanged;
}
19
Source : TesterServerUi.xaml.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private void PaintGrid()
{
if (_myGridView.InvokeRequired)
{
_myGridView.Invoke(new Action(PaintGrid));
return;
}
SliderFrom.ValueChanged -= SliderFrom_ValueChanged;
SliderTo.ValueChanged -= SliderTo_ValueChanged;
ProgressBar.Maximum = (_server.TimeMax - DateTime.MinValue).TotalMinutes;
ProgressBar.Minimum = (_server.TimeMin - DateTime.MinValue).TotalMinutes;
ProgressBar.Value = (_server.TimeNow - DateTime.MinValue).TotalMinutes;
_myGridView.Rows.Clear();
List<SecurityTester> securities = _server.SecuritiesTester;
if (securities != null && securities.Count != 0)
{
for (int i = 0; i < securities.Count; i++)
{
DataGridViewRow nRow = new DataGridViewRow();
nRow.Cells.Add(new DataGridViewTextBoxCell());
nRow.Cells[0].Value = securities[i].FileAdress;
nRow.Cells.Add(new DataGridViewTextBoxCell());
nRow.Cells[1].Value = securities[i].Security.Name;
if (securities[i].DataType == SecurityTesterDataType.Candle)
{
DataGridViewComboBoxCell comboBox = new DataGridViewComboBoxCell();
comboBox.Items.Add(TimeFrame.Day.ToString());
comboBox.Items.Add(TimeFrame.Hour1.ToString());
comboBox.Items.Add(TimeFrame.Hour2.ToString());
comboBox.Items.Add(TimeFrame.Hour4.ToString());
comboBox.Items.Add(TimeFrame.Min1.ToString());
comboBox.Items.Add(TimeFrame.Min2.ToString());
comboBox.Items.Add(TimeFrame.Min5.ToString());
comboBox.Items.Add(TimeFrame.Min3.ToString());
comboBox.Items.Add(TimeFrame.Min10.ToString());
comboBox.Items.Add(TimeFrame.Min20.ToString());
comboBox.Items.Add(TimeFrame.Min15.ToString());
comboBox.Items.Add(TimeFrame.Min30.ToString());
comboBox.Items.Add(TimeFrame.Min45.ToString());
comboBox.Items.Add(TimeFrame.Sec1.ToString());
comboBox.Items.Add(TimeFrame.Sec2.ToString());
comboBox.Items.Add(TimeFrame.Sec5.ToString());
comboBox.Items.Add(TimeFrame.Sec10.ToString());
comboBox.Items.Add(TimeFrame.Sec15.ToString());
comboBox.Items.Add(TimeFrame.Sec20.ToString());
comboBox.Items.Add(TimeFrame.Sec30.ToString());
nRow.Cells.Add(comboBox);
nRow.Cells[2].Value = securities[i].TimeFrame.ToString();
}
else
{
nRow.Cells.Add(new DataGridViewTextBoxCell());
nRow.Cells[2].Value = securities[i].DataType;
}
nRow.Cells.Add(new DataGridViewTextBoxCell());
nRow.Cells[3].Value = securities[i].Security.PriceStep.ToStringWithNoEndZero();
nRow.Cells.Add(new DataGridViewTextBoxCell());
nRow.Cells[4].Value = securities[i].TimeStart;
nRow.Cells.Add(new DataGridViewTextBoxCell());
nRow.Cells[5].Value = securities[i].TimeEnd;
_myGridView.Rows.Add(nRow);
}
}
TextBoxFrom.Text = _server.TimeStart.ToString(new CultureInfo("RU-ru"));
TextBoxTo.Text = _server.TimeEnd.ToString(new CultureInfo("RU-ru"));
SliderFrom.Minimum = (_server.TimeMin - DateTime.MinValue).TotalMinutes;
SliderFrom.Maximum = (_server.TimeMax - DateTime.MinValue).TotalMinutes;
SliderFrom.Value = (_server.TimeStart - DateTime.MinValue).TotalMinutes;
SliderTo.Minimum = (_server.TimeMin - DateTime.MinValue).TotalMinutes;
SliderTo.Maximum = (_server.TimeMax - DateTime.MinValue).TotalMinutes;
SliderTo.Value = (_server.TimeMin - DateTime.MinValue).TotalMinutes;
if (_server.TimeEnd != DateTime.MinValue &&
SliderFrom.Minimum + SliderTo.Maximum - (_server.TimeEnd - DateTime.MinValue).TotalMinutes > 0)
{
SliderTo.Value =
SliderFrom.Minimum + SliderTo.Maximum - (_server.TimeEnd - DateTime.MinValue).TotalMinutes;
}
SliderFrom.ValueChanged += SliderFrom_ValueChanged;
SliderTo.ValueChanged += SliderTo_ValueChanged;
}
19
Source : ServerMasterUi.xaml.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private void RePaintSourceGrid()
{
if (_gridSources.InvokeRequired)
{
_gridSources.Invoke(new Action(RePaintSourceGrid));
return;
}
_gridSources.Rows.Clear();
List<IServer> servers = ServerMaster.GetServers();
if (servers != null)
{
servers = servers.FindAll(s => s != null && s.ServerType != ServerType.Optimizer);
}
List<ServerType> serverTypes = ServerMaster.ServersTypes;
for (int i = 0; servers != null && i < servers.Count; i++)
{
DataGridViewRow row1 = new DataGridViewRow();
row1.Cells.Add(new DataGridViewTextBoxCell());
row1.Cells[0].Value = servers[i].ServerType;
row1.Cells.Add(new DataGridViewTextBoxCell());
row1.Cells[1].Value = servers[i].ServerStatus;
_gridSources.Rows.Add(row1);
serverTypes.Remove(serverTypes.Find(s => s == servers[i].ServerType));
if (servers[i].ServerStatus == ServerConnectStatus.Connect)
{
DataGridViewCellStyle style = new DataGridViewCellStyle();
style.BackColor = Color.MediumSeaGreen;
style.SelectionBackColor = Color.Green;
style.ForeColor = Color.Black;
style.SelectionForeColor = Color.Black;
row1.Cells[1].Style = style;
row1.Cells[0].Style = style;
}
else
{
DataGridViewCellStyle style = new DataGridViewCellStyle();
style.BackColor = Color.Coral;
style.SelectionBackColor = Color.Chocolate;
style.ForeColor = Color.Black;
style.SelectionForeColor = Color.Black;
row1.Cells[1].Style = style;
row1.Cells[0].Style = style;
}
}
for (int i = 0; i < serverTypes.Count; i++)
{
DataGridViewRow row1 = new DataGridViewRow();
row1.Cells.Add(new DataGridViewTextBoxCell());
row1.Cells[0].Value = serverTypes[i].ToString();
row1.Cells.Add(new DataGridViewTextBoxCell());
row1.Cells[1].Value = "Disabled";
_gridSources.Rows.Add(row1);
}
}
19
Source : OsDataMaster.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private void RePaintSourceGrid()
{
if (_gridSources.InvokeRequired)
{
_gridSources.Invoke(new Action(RePaintSourceGrid));
return;
}
_gridSources.Rows.Clear();
List<ServerType> servers = ServerMaster.ServersTypes;
List<IServer> serversCreate = ServerMaster.GetServers();
if (serversCreate == null)
{
serversCreate = new List<IServer>();
}
for (int i = 0; i < servers.Count; i++)
{
DataGridViewRow row1 = new DataGridViewRow();
row1.Cells.Add(new DataGridViewTextBoxCell());
row1.Cells[0].Value = servers[i];
row1.Cells.Add(new DataGridViewTextBoxCell());
IServer server = serversCreate.Find(s => s.ServerType == servers[i]);
if (server == null)
{
row1.Cells[1].Value = "Disabled";
}
else if (server != null && server.ServerStatus == ServerConnectStatus.Connect)
{
row1.Cells[1].Value = "Connect";
DataGridViewCellStyle style = new DataGridViewCellStyle();
style.BackColor = Color.MediumSeaGreen;
style.SelectionBackColor = Color.Green;
style.ForeColor = Color.Black;
style.SelectionForeColor = Color.Black;
row1.Cells[1].Style = style;
row1.Cells[0].Style = style;
}
else
{
row1.Cells[1].Value = "Disconnect";
DataGridViewCellStyle style = new DataGridViewCellStyle();
style.BackColor = Color.Coral;
style.SelectionBackColor = Color.Chocolate;
style.ForeColor = Color.Black;
style.SelectionForeColor = Color.Black;
row1.Cells[1].Style = style;
row1.Cells[0].Style = style;
}
_gridSources.Rows.Add(row1);
}
_gridSources[1, 0].Selected = true; // Select an invisible line to remove the default selection from the grid./Выбрать невидимую строку, чтобы убрать выделение по умолчанию с грида.
_gridSources.ClearSelection();
}
19
Source : OsDataMaster.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private void RePaintSetGrid()
{
try
{
if (_gridset.InvokeRequired)
{
_gridset.Invoke(new Action(RePaintSetGrid));
return;
}
_gridset.Rows.Clear();
for (int i = 0; _sets != null && i < _sets.Count; i++)
{
DataGridViewRow nRow = new DataGridViewRow();
nRow.Cells.Add(new DataGridViewTextBoxCell());
nRow.Cells[0].Value = _sets[i].SetName;
nRow.Cells.Add(new DataGridViewTextBoxCell());
nRow.Cells[1].Value = _sets[i].Regime;
if (_sets[i].Regime == DataSetState.On)
{
DataGridViewCellStyle style = new DataGridViewCellStyle();
style.BackColor = Color.MediumSeaGreen;
style.SelectionBackColor = Color.Green;
style.ForeColor = Color.Black;
style.SelectionForeColor = Color.Black;
nRow.Cells[1].Style = style;
nRow.Cells[0].Style = style;
}
_gridset.Rows.Add(nRow);
}
if (_gridset.Rows.Count != 0)
{
_gridset[0, 0].Selected = true; // Select an invisible line to remove the default selection from the grid./Выбрать невидимую строку, чтобы убрать выделение по умолчанию с грида.
_gridset.ClearSelection();
}
}
catch (Exception error)
{
SendNewLogMessage(error.ToString(), LogMessageType.Error);
}
}
19
Source : PatternControllerUi.xaml.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private void PaintGridPatternsToOpen()
{
if (_gridPatternsToOpen.InvokeRequired)
{
_gridPatternsToOpen.Invoke(new Action(PaintGridPatternsToOpen));
return;
}
_gridPatternsToOpen.CellValueChanged -= _gridPatternsToOpen_CellValueChanged;
_gridPatternsToOpen.Rows.Clear();
for (int i = 0; i < _pattern.PatternsToOpen.Count; i++)
{
_gridPatternsToOpen.Rows.Add(GetRow(_pattern.PatternsToOpen[i],i+1));
}
_gridPatternsToOpen.CellValueChanged += _gridPatternsToOpen_CellValueChanged;
}
19
Source : PatternControllerUi.xaml.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private void PaintGridPatternsToClose()
{
if (_gridPatternsToOpen.InvokeRequired)
{
_gridPatternsToOpen.Invoke(new Action(PaintGridPatternsToClose));
return;
}
_gridPatternsToClose.CellValueChanged -= _gridPatternsToClose_CellValueChanged;
_gridPatternsToClose.Rows.Clear();
for (int i = 0; i < _pattern.PatternsToClose.Count; i++)
{
_gridPatternsToClose.Rows.Add(GetRow(_pattern.PatternsToClose[i], i + 1));
}
_gridPatternsToClose.CellValueChanged += _gridPatternsToClose_CellValueChanged;
}
19
Source : PatternControllerUi.xaml.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private void PaintGridDataSeries()
{
if (_myGridView.InvokeRequired)
{
_myGridView.Invoke(new Action(PaintGridDataSeries));
return;
}
_myGridView.Rows.Clear();
List<MinerCandleSeries> securities = _dataServer.SecuritiesTester;
if (securities != null && securities.Count != 0)
{
for (int i = 0; i < securities.Count; i++)
{
DataGridViewRow nRow = new DataGridViewRow();
nRow.Cells.Add(new DataGridViewTextBoxCell());
nRow.Cells[0].Value = securities[i].FileAdress;
nRow.Cells.Add(new DataGridViewTextBoxCell());
nRow.Cells[1].Value = securities[i].Security.Name;
nRow.Cells.Add(new DataGridViewTextBoxCell());
nRow.Cells[2].Value = SecurityTesterDataType.Candle;
nRow.Cells.Add(new DataGridViewTextBoxCell());
nRow.Cells[3].Value = securities[i].Security.PriceStep;
nRow.Cells.Add(new DataGridViewTextBoxCell());
nRow.Cells[4].Value = securities[i].TimeStart;
nRow.Cells.Add(new DataGridViewTextBoxCell());
nRow.Cells[5].Value = securities[i].TimeEnd;
_myGridView.Rows.Add(nRow);
}
}
}
19
Source : OptimizerReportUi.xaml.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private void PaintTableResults()
{
if (_gridResults == null)
{
return;
}
if (_gridResults.InvokeRequired)
{
_gridResults.Invoke(new Action(PaintTableResults));
return;
}
_gridResults.SelectionChanged -= _gridResults_SelectionChanged;
_gridResults.CellMouseClick -= _gridResults_CellMouseClick;
UpdateHeaders();
_gridResults.Rows.Clear();
if (_reports == null)
{
return;
}
if (_gridFazesEnd.CurrentCell == null)
{
return;
}
int num = 0;
num = _gridFazesEnd.CurrentCell.RowIndex;
if (num >= _reports.Count)
{
return;
}
OptimazerFazeReport fazeReport = _reports[num];
if (fazeReport == null)
{
return;
}
for (int i = 0; i < fazeReport.Reports.Count; i++)
{
OptimizerReport report = fazeReport.Reports[i];
if (report == null ||
report.TabsReports.Count == 0 ||
!_master.IsAcceptedByFilter(report))
{
continue;
}
DataGridViewRow row = new DataGridViewRow();
row.Cells.Add(new DataGridViewTextBoxCell());
//if (report.TabsReports.Count == 1)
//{
row.Cells[0].Value = report.BotName;
//}
//else
//{
// row.Cells[0].Value = "Сводные";
//}
DataGridViewTextBoxCell cell2 = new DataGridViewTextBoxCell();
cell2.Value = report.GetParamsToDataTable();
row.Cells.Add(cell2);
DataGridViewTextBoxCell cell3 = new DataGridViewTextBoxCell();
cell3.Value = report.PositionsCount;
row.Cells.Add(cell3);
DataGridViewTextBoxCell cell4 = new DataGridViewTextBoxCell();
cell4.Value = report.TotalProfit.ToStringWithNoEndZero() + " (" + report.TotalProfitPersent.ToStringWithNoEndZero() + "%)";
row.Cells.Add(cell4);
DataGridViewTextBoxCell cell5 = new DataGridViewTextBoxCell();
cell5.Value = report.MaxDrowDawn.ToStringWithNoEndZero();
row.Cells.Add(cell5);
DataGridViewTextBoxCell cell6 = new DataGridViewTextBoxCell();
cell6.Value = report.AverageProfit.ToStringWithNoEndZero();
row.Cells.Add(cell6);
DataGridViewTextBoxCell cell7 = new DataGridViewTextBoxCell();
cell7.Value = report.AverageProfitPercent.ToStringWithNoEndZero();
row.Cells.Add(cell7);
DataGridViewTextBoxCell cell8 = new DataGridViewTextBoxCell();
cell8.Value = report.ProfitFactor.ToStringWithNoEndZero();
row.Cells.Add(cell8);
DataGridViewTextBoxCell cell9 = new DataGridViewTextBoxCell();
cell9.Value = report.PayOffRatio.ToStringWithNoEndZero();
row.Cells.Add(cell9);
DataGridViewTextBoxCell cell10 = new DataGridViewTextBoxCell();
cell10.Value = report.Recovery.ToStringWithNoEndZero();
row.Cells.Add(cell10);
DataGridViewButtonCell cell11 = new DataGridViewButtonCell();
cell11.Value = OsLocalization.Optimizer.Message40;
row.Cells.Add(cell11);
_gridResults.Rows.Add(row);
/* if (report.TabsReports.Count > 1)
{
for (int i2 = 0; i2 < report.TabsReports.Count; i2++)
{
_gridResults.Rows.Add(GetRowResult(report.TabsReports[i2]));
}
}*/
}
_gridResults.SelectionChanged += _gridResults_SelectionChanged;
_gridResults.CellMouseClick += _gridResults_CellMouseClick;
}
19
Source : OptimizerReportCharting.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private void UpdatePie()
{
if (_gridDep.InvokeRequired)
{
_gridDep.Invoke(new Action(UpdatePie));
return;
}
int countProfitBots = 0;
int countLossBots = 0;
if (_reports == null)
{
return;
}
if (_reports.Count <= 1)
{
return;
}
if (_reports.Count == 2 &&
_reports[1].Reports.Count == 0)
{
return;
}
int num = 0;
OptimizerReport inSampleReport = null;
for (int i = 0; i < _reports.Count; i++)
{
OptimazerFazeReport curReport = _reports[i];
if (curReport == null ||
curReport.Reports == null ||
curReport.Reports.Count == 0)
{
continue;
}
if (curReport.Faze.TypeFaze == OptimizerFazeType.InSample)
{
inSampleReport = curReport.Reports[0];
}
if (curReport.Faze.TypeFaze == OptimizerFazeType.OutOfSample)
{
string botName = inSampleReport.BotName.Replace(" InSample", "");
// reportToPaint = curReport.Reports.Find(rep => rep.BotName.StartsWith(botName));
for (int i2 = 0; i2 < curReport.Reports.Count; i2++)
{
if (curReport.Reports[i2].BotName.StartsWith(botName))
{
if (curReport.Reports[i2].TotalProfit > 0)
{
countProfitBots += 1;
}
else
{
countLossBots += 1;
}
break;
}
}
}
}
if (countProfitBots + countLossBots == 0)
{
return;
}
decimal profitPercent = Math.Round((Convert.ToDecimal(countProfitBots) / (countProfitBots + countLossBots) * 100), 0);
decimal lossPercent = Math.Round((Convert.ToDecimal(countLossBots) / (countProfitBots + countLossBots) * 100), 0);
_chartPie.Series[0].Points.Clear();
DataPoint point1 = new DataPoint(1, countProfitBots);
point1.AxisLabel = "Profit " + profitPercent + " %";
point1.Color = Color.FromArgb(57, 157, 54);
_chartPie.Series[0].Points.Add(point1);
if (countLossBots != 0)
{
DataPoint point2 = new DataPoint(2, countLossBots);
point2.AxisLabel = "Loss " + lossPercent + " %";
point2.Color = Color.FromArgb(255, 83, 0);
_chartPie.Series[0].Points.Add(point2);
}
}
19
Source : TabIndexOptimizerUi.xaml.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private void PaintTable()
{
if (_securitiesNamesGrid.InvokeRequired)
{
_securitiesNamesGrid.Invoke(new Action(PaintTable));
return;
}
_securitiesNamesGrid.CellValueChanged -= _securitiesNamesGrid_CellValueChanged;
_securitiesNamesGrid.Rows.Clear();
List<string> strings = Index.NamesSecurity;
if (strings == null ||
strings.Count == 0)
{
return;
}
for (int i = 0; i < strings.Count; i++)
{
DataGridViewRow row = new DataGridViewRow();
row.Cells.Add(new DataGridViewTextBoxCell());
row.Cells[0].Value = "A" + i;
DataGridViewComboBoxCell cell = new DataGridViewComboBoxCell();
cell.ReadOnly = false;
for (int i2 = 0; i2 < _securities.Count; i2++)
{
bool isInTheArray = false;
for (int i3 = 0; i3 < cell.Items.Count; i3++)
{
if (cell.Items[i3].ToString() == _securities[i2].Security.Name)
{
isInTheArray = true;
break;
}
}
if (isInTheArray)
{
continue;
}
cell.Items.Add(_securities[i2].Security.Name);
}
cell.Value = strings[i];
row.Cells.Add(cell);
_securitiesNamesGrid.Rows.Add(row);
}
_securitiesNamesGrid.CellValueChanged += _securitiesNamesGrid_CellValueChanged;
}
19
Source : GlobalPosition.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
public void ClearJournals()
{
try
{
if (_grid.InvokeRequired)
{
_grid.Invoke(new Action(ClearJournals));
return;
}
for (int i = 0; _journals != null && i < _journals.Count; i++)
{
_journals[i].PositionStateChangeEvent -= journal_PositionChangeEvent;
}
_journals = null;
_grid.Rows.Clear();
}
catch (Exception error)
{
SendNewLogMessage(error.ToString(), LogMessageType.Error);
}
}
See More Examples