c# forms multiple option using radio buttons and checkboxes - c#

I am a beginner coder in c# and i am having an issue with making multiple choices. basically i want the user to upload a text file with a list of URLs to be tested, (which i have working), then i want the user to be able to select which browser/browsers to perform the test with using the check boxes. and also if the test can run normally or using headless browser config. I have normal tests and headless tests working, but what i can't work out is how to make it so that a user can select which browser to perform the test with and make it so that it then runs it as a normal or headless test. I have attached an image of the form i have created and my form code(i have removed any non-essential parts). if for instance the user wants to select multiple browsers to run the test the code doesn't launch. i hope i have made sense of what i need help with but i have really pushed my coding knowledge to extremes with this and am at wits end
public partial class AtpTester2 : Form
{
private IWebDriver chromeDriver;
private IWebDriver foxDriver;
private IWebDriver edgeDriver;
OpenFileDialog openFileDialog = new OpenFileDialog();
public AtpTester2()
{
InitializeComponent();
TopMost = true;
}
private void StartBtn_Click(object sender, EventArgs e)
{
if (NormalTestRBtn.Checked == true)
{
Console.WriteLine("Normal Chrome Test Selected");
foreach (string url in LSlistBox.Items)
{
//check if URL is valid
Uri uriResult;
bool result = Uri.TryCreate(url, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
//if valid URL call your OpenBrowsers method
if (result)
{
OpenBrowsers(url);
AccChromeTest();
CloseBrowser();
}
}
}
else if (HeadlessTestRBtn.Checked == true)
{
Console.WriteLine("Headless Test Selected");
foreach (string url in LSlistBox.Items)
{
//check if URL is valid
Uri uriResult;
bool result = Uri.TryCreate(url, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
//if valid URL call your OpenBrowsers method
if (result)
{
OpenHeadlessBrowsers(url);
AccChromeTest();
CloseBrowser();
}
}
}
else
{
Console.WriteLine("It won't work!!!!!");
SystemSounds.Beep.Play();
MessageBox.Show("Select a test option first", "Oops", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void UrlFilePickerBtn_Click(object sender, EventArgs e)
{
var filePath = string.Empty;
openFileDialog.InitialDirectory = Application.StartupPath;
openFileDialog.Filter = "txt files (*.txt)|*.txt|All Files (*.*)|*.*";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if(openFileDialog.ShowDialog() == DialogResult.OK)
{
filePath = openFileDialog.FileName;
var fileStream = openFileDialog.OpenFile();
StreamReader reader = new StreamReader(fileStream);
{
string line;
while ((line = reader.ReadLine()) != null) {
LSlistBox.Items.Add(line);
}
}
}
}
private void ExitBtn_Click(object sender, EventArgs e)
{
Close();
}
private void ClrLSBoxBtn_Click(object sender, EventArgs e)
{
LSlistBox.Items.Clear();
}
//
// Any other functions
//
public void OpenBrowsers(string URL)
{
Console.WriteLine("Normal Button Starting Browsers");
if (ChromeChkBox.Checked)
{
chromeDriver = DriverClass.GetDriver("Chrome");
chromeDriver.Navigate().GoToUrl(URL);
chromeDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20);
}
if (FirefoxChkBox.Checked)
{
foxDriver = DriverClass.GetDriver("Firefox");
foxDriver.Navigate().GoToUrl(URL);
foxDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20);
}
if(EdgeChkBox.Checked)
{
edgeDriver = DriverClass.GetDriver("Edge");
edgeDriver.Navigate().GoToUrl(URL);
edgeDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20);
}
}
public void OpenHeadlessBrowsers(string URL)
{
Console.WriteLine("Headless Button Starting Browsers");
chromeDriver = DriverClass.GetDriver("Chrome Headless");
chromeDriver.Navigate().GoToUrl(URL);
chromeDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20);
}
public void AccChromeTest()
{
Console.WriteLine("AccTest started for small test");
string title = chromeDriver.Title;
string url = chromeDriver.Url;
Console.WriteLine(title + " :: " + url);
AxeResult axeResult = new AxeBuilder(chromeDriver).WithTags("wcag2a", "wcag2aa").Analyze();
//Creates the Chrome HTML report and sends it the reports folder
Directory.CreateDirectory(Application.StartupPath + "\\Reports");
string path = Path.Combine(Application.StartupPath + "\\Reports", "AccReport.html");
chromeDriver.CreateAxeHtmlReport(axeResult, path);
Console.WriteLine("Report Printed");
}
public void CloseBrowser()
{
if (ChromeChkBox.Checked)
{
chromeDriver.Quit();
Console.WriteLine("Chrome Browser Closed");
}
if(FirefoxChkBox.Checked)
{
foxDriver.Quit();
Console.WriteLine("Firefox Browser Closed");
}
if (EdgeChkBox.Checked)
{
edgeDriver.Quit();
Console.WriteLine("Edge Browser Closed");
}
}
}
}

Related

App crash on share file dialog only in release mode

My application crash when I open the file share dialog, happens only in release mode, in debug mode everything works correctly.
this is my code:
private List<IStorageFile> fileSelectedToShare;
private void shareFileAppBarButton_Click(object sender, RoutedEventArgs e)
{
dataTransferManager = DataTransferManager.GetForCurrentView();
dataTransferManager.DataRequested += DataTransferManager_DataRequested;
DataTransferManager.ShowShareUI();
}
private void DataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
if (fileSelectedToShare == null) return;
DataRequest request = args.Request;
if (fileSelectedToShare.Count != 0) {
request.Data.Properties.Title = "Share";
request.Data.Properties.Description = "Share the selected document";
request.Data.SetStorageItems(fileSelectedToShare);
fileSelectedToShare.Clear();
}
dataTransferManager.DataRequested -= DataTransferManager_DataRequested;
}
fileSelectedToShare is initialized and contains files.
this is the exception:
System.Runtime.InteropServices.MissingInteropDataException: 'ComTypeMarshalling_MissingInteropData, System.Collections.Generic.IEnumerable. For more information, visit http://go.microsoft.com/fwlink/?LinkId=623485'
Not sure why, but copying the file references into another collection and passing the latter into request.Data.SetStorageItems() makes your code work:
private void DataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
if (fileSelectedToShare == null) return;
DataRequest request = args.Request;
if (fileSelectedToShare.Count != 0)
{
request.Data.Properties.Title = "Share";
request.Data.Properties.Description = "Share the selected document";
List<IStorageItem> files = new List<IStorageItem>(fileSelectedToShare);
request.Data.SetStorageItems(files);
fileSelectedToShare.Clear();
}
dataTransferManager.DataRequested -= DataTransferManager_DataRequested;
}

How to load paths into ListBox and afterwards start the file per selected Index

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void cmdAdd_Click(object sender, EventArgs e)
{
OpenFileDialog OP = new OpenFileDialog();
OP.Title = "Please select the wanted .exe";
string FileName = String.Empty;
string PathName = String.Empty;
OP.InitialDirectory = #"C:\Users\" + Environment.UserName.ToString() + #"\Desktop";
OP.DefaultExt = ".exe";
OP.Filter = "Game executable (*.exe) |*.exe";
DialogResult Ergebnis = OP.ShowDialog();
if (Ergebnis == DialogResult.OK)
{
FileInfo File = new FileInfo(OP.FileName);
if (File.Exists)
{
PathName = File.FullName;
}
}
if (PathName != String.Empty)
{
textBox1.Text = PathName;
listBox1.Items.Add(PathName);
}
}
private void cmdStart_Click(object sender, EventArgs e)
{
string SelectedItem = "";
if (listBox1.SelectedItem != null)
{
SelectedItem = listBox1.SelectedItem.ToString();
/*MessageBox.Show(SelectedItem);*/
}
Process Pro = new Process();
Pro.StartInfo.FileName = SelectedItem;
DialogResult Ergebnis2 = MessageBox.Show("Would you like to start the Game right now?", "Game start?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (Ergebnis2.Equals(true))
{
try
{
Pro.Start();
}
catch (Exception)
{
MessageBox.Show("The Start of the Program was aborted!\r\nOr you didn't specify the right Path!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
private void cmdSave_Click(object sender, EventArgs e)
{
StreamWriter SaveFile = new StreamWriter(#"C:\Users\" + Environment.UserName.ToString() + #"\Desktop\savedgames.txt");
foreach (var item in listBox1.Items)
{
SaveFile.WriteLine(item.ToString());
}
SaveFile.Close();
MessageBox.Show("EZPZ");
}
private void cmdLoad_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(#"C:\Users\" + Environment.UserName.ToString() + #"\Desktop\savedgames.txt");
string line = string.Empty;
try
{
line = sr.ReadLine();
while (line != null)
{
this.listBox1.Items.Add(line);
line = sr.ReadLine();
}
sr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
sr.Close();
}
}
}
Hello Stackoverflow-Community,
So i've tried to be able to start the selected File(from the Listbox) by clicking the Start button.The items in the Listbox are loaded in from a .txt-File, But it seems that the path that i get (from the .txt-File) is not actually the same that was written inside.
For example: H:\Exe\556689600.exe is written inside the .txt-File but when i check while pausing the application the value of the SelectedItem is "H:(two backslashes)Exe(two backslashes)556689600.exe" so i'd like it to be H:\Exe\556689600.exe so it can be properly started.
EDIT: The main problem is that i can't start the .exe that i selected (via cmdStart) and i don't know why.
Please keep in mind that i'm (as you can see from the code) not very experienced in programming and that i'm not an native english speaker, so pardon me for any grammatical mistakes/logic mistakes made.
Thanks in advance,
Stephen
The problem is with:
DialogResult Ergebnis2 = MessageBox.Show("Would you like to start the Game right now?", "Game start?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (Ergebnis2.Equals(true))
DialogResult holds the Enum data 'DialogResult.Yes', so you need to compare it to that value, and not (true).
Edit:
I suggest practicing working with debug:
In this case, I plated a breakpoint on the 'cmdstart_Click' method and followed it step by step (Used F10)
I saw that we jump over the 'if' condition, and checked why.

C# Inputbox cancel button does not work

I have below code on my browse button.
How can I write code for inputbox cancel button.
private void btnbrowse_Click(object sender, EventArgs e)
{
String sf_no = Microsoft.VisualBasic.Interaction.InputBox(
"You are uploading File For SF NO. ", "Information", def, -1, -1);
ofd.ShowDialog();
ofd.Multiselect = true;
string[] result = ofd.FileNames;
foreach (string y in result)
{
String path = y.Substring(0, y.LastIndexOf("\\"));
String filename = y.Substring(y.LastIndexOf("\\"));
string[] row = new string[] { sf_no,path, filename };
dataGridView2.Rows.Add(row);
}
}
On Cancellation of InputBox, the return value is an empty string, so your code would be
if (sf_no!="")
{
//ok stuff here, including the showdialog logic as shown below
}
{
//cancel stuff here
}
Since ofd.ShowDialog can also be cancelled your code should be :
if (ofd.ShowDialog()==DialogResult.OK)
{
//do stuff on OK button
}
else
{
//do stuff on Cancel button
}
Either call ofd.Multiselect = true; before calling ShowDialog() or set it on Properties box if you'll always have Multiselect anyway.
Thus, your new code are now :
private void btnbrowse_Click(object sender, EventArgs e)
{
String sf_no = Microsoft.VisualBasic.Interaction.InputBox("You are uploading File For SF NO. ", "Information", def, -1, -1);
if (sf_no!="") //we got the sf_no
{
ofd.Multiselect = true;
if (ofd.ShowDialog()==DialogResult.OK)//user select file(s)
{
string[] result = ofd.FileNames;
foreach (string y in result)
{
String path = System.IO.Path.GetDirectoryName(y);
String filename = System.IO.Path.GetFileName(y);
string[] row = new string[] { sf_no,path, filename };
dataGridView2.Rows.Add(row);
}
}
else
{
//handle what happen if user click cancel while selecting file
}
}
else
{
//handle what happen if user click cancel while entering SF NO
}
}

How cancel Downloading Async?

I've got a problem. How can I cancel a download ?
client.CancelAsync();
Doesn't work for me, because if I cancel a download and start a new one the code still tries to access the old download file. You've to know in my code is a part when a download is done it should unzip the file which has been downloaded. Example.zip like this :)
So, when I cancel my download and start a new one you know my script tries to unzip my old Example.zip, but it should kick this ....
For Unzipping, I'm using Iconic.Zip.dll (http://dotnetzip.codeplex.com/)
How to get it work?
UPDATE:
This is my Downloader Form
private void button3_Click_1(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("This will cancel your current download ! Continue ?", "Warning !", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
cancelDownload = true;
URageMainWindow.isDownloading = false;
this.Close();
}
else if (dialogResult == DialogResult.No)
{
}
}
This is my Main form this happens when you start downloading something
private void checkInstall(object sender, WebBrowserDocumentCompletedEventArgs e)
{
string input = storeBrowser.Url.ToString();
// Test these endings
string[] arr = new string[]
{"_install.html"};
// Loop through and test each string
foreach (string s in arr)
{
if (input.EndsWith(s) && isDownloading == false)
{
// MessageBox.Show("U.Rage is downloading your game");
Assembly asm = Assembly.GetCallingAssembly();
installID = storeBrowser.Document.GetElementById("installid").GetAttribute("value");
// MessageBox.Show("Name: " + installname + " ID " + installID);
installname = storeBrowser.Document.GetElementById("name").GetAttribute("value");
installurl = storeBrowser.Document.GetElementById("link").GetAttribute("value");
isDownloading = true;
string install_ID = installID;
string Install_Name = installname;
// MessageBox.Show("New Update available ! " + " - Latest version: " + updateversion + " - Your version: " + gameVersion);
string url = installurl;
WebClient client = new WebClient();
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_InstallProgressChanged);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_InstallFileCompleted);
client.DownloadFileAsync(new Uri(url), #"C:\U.Rage\Downloads\" + installID + "Install.zip");
if (Downloader.cancelDownload == true)
{
//MessageBox.Show("Downloader has been cancelled");
client.CancelAsync();
Downloader.cancelDownload = false;
}
notifyIcon1.Visible = true;
notifyIcon1.ShowBalloonTip(2, "Downloading !", "U.Rage is downloading " + installname, ToolTipIcon.Info);
System.Media.SoundPlayer player = new System.Media.SoundPlayer(#"c:/U.Rage/Sounds/notify.wav");
player.Play();
storeBrowser.GoBack();
igm = new Downloader();
igm.labelDWGame.Text = installname;
// this.Hide();
igm.Show();
return;
}
if (input.EndsWith(s) && isDownloading == true)
{
System.Media.SoundPlayer player = new System.Media.SoundPlayer(#"c:/U.Rage/Sounds/notify.wav");
player.Play();
MessageBox.Show("Please wait until your download has been finished", "Warning");
storeBrowser.GoBack();
}
}
}
This happens when the download has been finished
void client_InstallFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if(Downloader.cancelDownload == false)
{
using (ZipFile zip = ZipFile.Read(#"C:\U.Rage\Downloads\" + installID + "Install.zip"))
{
//zip.Password = "iliketrains123";
zip.ExtractAll("C:/U.Rage/Games/", ExtractExistingFileAction.OverwriteSilently);
}
System.IO.File.Delete(#"C:/U.Rage/Downloads/" + installID + "Install.zip");
notifyIcon1.Visible = true;
notifyIcon1.ShowBalloonTip(2, "Download Completed !", "Installing was succesful !", ToolTipIcon.Info);
System.Media.SoundPlayer player = new System.Media.SoundPlayer(#"c:/U.Rage/Sounds/notify.wav");
player.Play();
this.Show();
igm.Close();
isDownloading = false;
listView.Items.Clear();
var files = Directory.GetFiles(#"C:\U.Rage\Games\", "*.ugi").Select(f => new ListViewItem(f)).ToArray();
foreach (ListViewItem f in files)
{
this.LoadDataFromXml(f);
}
}
}
Here is the method for async data download that supports cancellation:
private static async Task<byte[]> downloadDataAsync(Uri uri, CancellationToken cancellationToken)
{
if (String.IsNullOrWhiteSpace(uri.ToString()))
throw new ArgumentNullException(nameof(uri), "Uri can not be null or empty.");
if (!Uri.IsWellFormedUriString(uri.ToString(), UriKind.Absolute))
return null;
byte[] dataArr = null;
try
{
using (var webClient = new WebClient())
using (var registration = cancellationToken.Register(() => webClient.CancelAsync()))
{
dataArr = await webClient.DownloadDataTaskAsync(uri);
}
}
catch (WebException ex) when (ex.Status == WebExceptionStatus.RequestCanceled)
{
// ignore this exception
}
return dataArr;
}
When you call CancelAsync, the AsyncCompletedEventArgs object passed to the completed callback will have the Cancelled property set to true. So you could write:
void client_InstallFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if(e.Cancelled)
{
// delete the partially-downloaded file
return;
}
// unzip and do whatever...
using (ZipFile zip = ZipFile.Read(#"C:\U.Rage\Downloads\" + installID + "Install.zip"))
See the documentation for more info.
The selected answer didn't work properly for me. Here's what I did:
When they click the cancel button I call the
Client.CancelAsync();
And then in the Web.Client DownloadFileCompleted:
Client.DownloadFileCompleted += (s, e) =>
{
if (e.Cancelled)
{
//cleanup delete partial file
Client.Dispose();
return;
}
}
And then when you try to re-download just instantiate a new client:
Client = WebClient();
This way the old async parameters won't be maintained.

How do I save the last folder selected by the user?

I have this and this only saves the last folder used when the user closes the application and re-opens it.
private void btnBrowse_Click(object sender, EventArgs e)
{
Properties.Settings.Default.Reload();
fbFolderBrowser.SelectedPath = AppVars.LastSelectedFolder;
if (fbFolderBrowser.ShowDialog() == DialogResult.OK)
{
Properties.Settings.Default.LastSelectedFolder = fbFolderBrowser.SelectedPath.ToString();
Properties.Settings.Default.Save();
}
}
Every time the user selects a folder, I want to save that path. Then, when he clicks the browse button again, I want the default path to be his last selection.
The above is not working. It only saves the last path selected and goes back to it only if I restart the app. How would I go about saving the last path in the same app session?
You need to reload the settings:
Properties.Settings.Default.Reload();
Note that this only works when not running in Debug mode (AFAIK).
I'm gonna post my code here, because none of the answers I had seen addressed all the issues. This will save the location and re-load the settings for a file Browse dialog (file and folder browse dialogs are slightly different when getting path)... the answers above seem to be for the session only(?). Updated with new method to avoid config settings be lost with an update of clickonce app...
Code:
public class ConfigSettingsDictionary
{
public Dictionary<String, String> ConfigSettings = new Dictionary<String, String>();
}
ConfigSettingsDictionary MyConfigurationSettings = new ConfigSettingsDictionary();
private void SaveConfig()
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\YOUR_APP_NAME_PLUS_UNIQUE_VALUE.config"))
{
foreach (var pair in MyConfigurationSettings.ConfigSettings)
{
sw.WriteLine(pair.Key + "=" + pair.Value);
}
}
}
private void LoadConfig()
{
if (System.IO.File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\YOUR_APP_NAME_PLUS_UNIQUE_VALUE.config"))
{
var settingdata = System.IO.File.ReadAllLines(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\YOUR_APP_NAME_PLUS_UNIQUE_VALUE.config");
for (var i = 0; i < settingdata.Length; i++)
{
var setting = settingdata[i];
var sidx = setting.IndexOf("=");
if (sidx >= 0)
{
var skey = setting.Substring(0, sidx);
var svalue = setting.Substring(sidx + 1);
if (!MyConfigurationSettings.ConfigSettings.ContainsKey(skey))
{
MyConfigurationSettings.ConfigSettings.Add(skey, svalue);
}
}
}
}
}
private void UpdateConfig(Dictionary<String, String> keyvaluepairs)
{
foreach (var pair in keyvaluepairs)
{
if (!MyConfigurationSettings.ConfigSettings.ContainsKey(pair.Key))
{
MyConfigurationSettings.ConfigSettings.Add(pair.Key, pair.Value);
}
else
{
MyConfigurationSettings.ConfigSettings[pair.Key] = pair.Value;
}
}
}
then I use it like this (this saves the folder chosen in a file browse dialog and also the file chosen):
string lastused = "";
if (MyConfigurationSettings.ConfigSettings.ContainsKey("openFileDialog2_last_used"))
{
MyConfigurationSettings.ConfigSettings.TryGetValue("openFileDialog2_last_used", out lastused);
}
if (lastused != "")
{
openFileDialog2.InitialDirectory = lastused;
}
else
{
openFileDialog2.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
}
string filestring = "";
if (template_filename == "")
{
try
{
if (openFileDialog2.ShowDialog() == DialogResult.OK)
{
filestring = openFileDialog2.FileName;
String chosenPath = Path.GetDirectoryName(openFileDialog2.FileName);
Dictionary<String, String> settings_to_save = new Dictionary<String, String>();
settings_to_save.Add("openFileDialog2_last_used", chosenPath);
settings_to_save.Add("openFileDialog2_last_used_template_file", filestring);
UpdateConfig(settings_to_save);
}
else return;
}
catch (Exception ex)
{
MessageBox.Show("There was an error.", "Invalid File", MessageBoxButtons.OK);
return;
}
private void YOURFORMNAME_Load(object sender, EventArgs e)
{
// Load configuration file
LoadConfig();
}
private void YOURFORMNAME_FormClosing(object sender, FormClosingEventArgs e)
{
// Save configuration file
SaveConfig();
}

Categories

Resources