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;
}
Related
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");
}
}
}
}
Description:
So I have this following script to download a file from the internet with a progress bar showing what percentage the download is at and custom message boxes. Now I have the files being saved to the users %TEMP% path. And it uses events to prevent people from clicking on the button again and starting a new download.
Problem:
I want to give the user a choice of where to save the file, but show his temp path as the default location. (Like a Save-file-dialog Box)
I'm still fairly new to coding and don't know where to exactly start.
What I tried:
I didn't try any new code, but I did go around google and try to find a solution. Here are some websites that I found that might be useful:
https://learn.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-save-files-using-the-savefiledialog-component
https://www.c-sharpcorner.com/UploadFile/mahesh/savefiledialog-in-C-Sharp/
They explain it really well. But I don't know how to incorporate it into this script.
And I dont want to write a brand new script. Any Help would be Appreciated!
private bool _isBusy = false;
private void button1_Click(object sender, EventArgs e)
=> DownloadFile("someurl1", "somefilename1.exe");
private void button2_Click(object sender, EventArgs e)
=> DownloadFile("someurl2", "somefilename2.exe");
private void button3_Click(object sender, EventArgs e)
=> DownloadFile("someurl3", "somefilename3.exe");
private void button4_Click(object sender, EventArgs e)
=> DownloadFile("someurl4", "somefilename4.exe");
private void DownloadFile(string url, string fileName)
{
if(_isBusy) return;
_isBusy = true;
var output = Path.Combine(Path.GetTempPath(), fileName);
MessageBox.Show($"{fileName} will start downloading from {url}");
using (WebClient client = new WebClient())
{
client.DownloadFileCompleted += (sender, args) =>
{
MessageBox.Show($"{fileName} Complete!");
Process.Start(output);
_isBusy = false;
};
client.DownloadProgressChanged += (sender, args) => progressBar1.Value = args.ProgressPercentage;
client.DownloadFileAsync(new Uri(url), output);
}
}
Maybe something like?
private SaveFileDialog save = new SaveFileDialog();
private void DownloadFile(string url, string fileName)
{
if (_isBusy) return;
save.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
save.FileName = fileName;
if (save.ShowDialog() == DialogResult.OK)
{
_isBusy = true;
var output = save.FileName;
MessageBox.Show($"{fileName} will start downloading from {url}");
using (WebClient client = new WebClient())
{
client.DownloadFileCompleted += (sender, args) =>
{
MessageBox.Show($"{fileName} Complete!");
Process.Start(output);
_isBusy = false;
};
client.DownloadProgressChanged += (sender, args) => progressBar1.Value = args.ProgressPercentage;
client.DownloadFileAsync(new Uri(url), output);
}
}
}
I try to open System file dialog to select a pic. the code ran normally in my computer. But in another computer cant show the system file dialog.
And here is my simple code:-
private void PicInputBtn_Click(object sender, RoutedEventArgs e)
{
var dialog = new Microsoft.Win32.OpenFileDialog
{
DefaultExt = ".jpg",
Filter = "img file|*.jpg",
};
if (dialog.ShowDialog() != true)
{
return;
}
}
If nothing happens but the mouse pointer turning into a little busy-indicator.
You can try to set your thread to STAThread:
[STAThread]
static void Main(string[] args)
{
var o = new OpenFileDialog();
var r = o .ShowDialog();
}
Howover they are many reasons that can break the OpenFileDialog, you can try to launch your program in admin mode and try to reinstall .net Framework
Change your code to:
private void PicInputBtn_Click(object sender, RoutedEventArgs e)
{
var dialog = new Microsoft.Win32.OpenFileDialog
{
DefaultExt = ".jpg",
Filter = "img file|*.jpg" // You had an extra ',' here.
};
if ((Nullable<bool>dialog.ShowDialog()) == true) // Also you forgot to put Nullable<bool>
{
// string filename = dlg.FileName;
}
else
{
return;
}
}
Before you flag this as a duplicate, yes there are questions just like this, i've looked at all of them and still couldn't get this working. I'm trying to code in a feature that downloads and runs a .exe file but it doesn't download, run or do anything. I even removed the try catches to find an error or error codes but I have non, so I have no idea where i'm going wrong, here is my code for it
public test_Configuration()
{
InitializeComponent();
}
Uri uri = new Uri("http://example.com/files/example.exe");
string filename = #"C:\Users\**\AppData\Local\Temp\example.exe";
private void button1_Click(object sender, EventArgs e)
{
try
{
if(File.Exists(filename))
{
File.Delete(filename);
}
else
{
WebClient wc = new WebClient();
wc.DownloadDataAsync(uri, filename);
wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
if (progressBar1.Value == progressBar1.Maximum)
{
progressBar1.Value = 0;
}
}
private void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if(e.Error == null)
{
MessageBox.Show("Download complete!, running exe", "Completed!");
Process.Start(filename);
}
else
{
MessageBox.Show("Unable to download exe, please check your connection", "Download failed!");
}
Change DownloadDataAsync to DownloadFileAsync.
wc.DownloadFileAsync(uri, filename);
This code helped me out quite a bit with updating a file, so I thought I would show my twist in the hopes that someone else out there has a similar requirement as me.
I needed this code to do the following when a button was clicked:
Grab a file from a sever and store it locally in AppData\Temp.
Keep my user up-to-date of install progress (an installer is downloaded).
If successfully downloaded (note the removal of the else after deleting old file check), launch "daInstaller.exe", whilst terminating the current running program.
And if said file already exist (i.e. the old "daIstaller.exe"), delete prior to copying new file to AppData\Temp.
Don't forget to keep the file names the same, else you'll be leaving more trash in that AppData\Temp folder.
private void button1_Click(object sender, EventArgs e)
{
Uri uri = new Uri("http://example.com/files/example.exe");
filename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Temp/example.exe");
try
{
if (File.Exists(filename))
{
File.Delete(filename);
}
WebClient wc = new WebClient();
wc.DownloadFileAsync(uri, filename);
wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
if (progressBar1.Value == progressBar1.Maximum)
{
progressBar1.Value = 0;
}
}
private void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error == null)
{
Process.Start(filename);
Close();
Application.Exit();
}
else
{
MessageBox.Show("Unable to download exe, please check your connection", "Download failed!");
}
}
I am trying to monitor traffic using FiddlerCore and WebBrowser Controller, I have below code to capture web requests in C#
private void button1_Click(object sender, EventArgs e)
{
List<Fiddler.Session> oAllSessions = new List<Fiddler.Session>();
URLMonInterop.SetProxyInProcess("127.0.0.1:8888", "<-loopback>");
webBrowser1.ScriptErrorsSuppressed = true;
WebProxy myProxy = new WebProxy();
Uri newUri = new Uri("http://localhost:8888");
myProxy.Address = newUri;
Fiddler.FiddlerApplication.Startup(8888, FiddlerCoreStartupFlags.Default);
Fiddler.FiddlerApplication.AfterSessionComplete += delegate(Fiddler.Session oS)
{
Monitor.Enter(oAllSessions);
oAllSessions.Add(oS);
Monitor.Exit(oAllSessions);
};
webBrowser1.Navigate("http://www.test.com/");
while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
{
System.Windows.Forms.Application.DoEvents();
}
var message = string.Join(Environment.NewLine, oAllSessions);
textBox1.Text = textBox1.Text + message;
Fiddler.FiddlerApplication.Shutdown();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Fiddler.FiddlerApplication.Shutdown();
URLMonInterop.ResetProxyInProcessToDefault();
}
It is only returning just one request response (given url in webBroser.Navigate), I can not see requests for images, css and other loaded files on example site. I could not find any info on this, Can someone please help me to understand on how I can capture all GET POST requests when webBroswer.Navigate to given URL?
updated:
delegate void updateUI();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Fiddler.FiddlerApplication.AfterSessionComplete += FiddlerApplication_AfterSessionComplete;
Fiddler.FiddlerApplication.Startup(8888, FiddlerCoreStartupFlags.Default);
webBrowser1.ScriptErrorsSuppressed = true;
WebProxy myProxy = new WebProxy();
Uri newUri = new Uri("http://localhost:8888");
myProxy.Address = newUri;
string[] urls = new string[] { "http://localhost/test/page1",
"http://localhost/test/page2 "
};
foreach (string url in urls)
{
webBrowser1.Navigate(url);
// Capture root url
listBox1.Invoke(new updateUI(() =>
{
listBox1.Items.Add(url);
}));
while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
{
System.Windows.Forms.Application.DoEvents();
}
// Hack as I am not sure what to do here so wait 10 second for webBrowser to load all requests otherwise I only get last url data in listbox
for (int i = 0; i <= 10; i++)
{
System.Windows.Forms.Application.DoEvents();
Thread.Sleep(1000);
}
}
}
void FiddlerApplication_AfterSessionComplete(Session oSession)
{
var regex = new Regex("keywords-in-url-to-match");
// If my desired keyword match then grab request POST body
if (regex.IsMatch(oSession.fullUrl.ToString()))
{
string requestBody = oSession.GetRequestBodyAsString();
// Capture url and request body. This url is not root url
listBox1.Invoke(new updateUI(() =>
{
listBox1.Items.Add(oSession.fullUrl);
listBox1.Items.Add(System.Web.HttpUtility.UrlDecode(requestBody));
}));
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Fiddler.FiddlerApplication.Shutdown();
}
What makes you think that the other items aren't being pulled from the cache?
You shouldn't use FiddlerCoreStartupFlags.Default if you're going to use SetProxyInProcess; the former sets the proxy for every process on the system while the latter sets the proxy only for the current process.