Simple silverlight open-file-dialog errors - c#

A while back I wrote a silverlight user control which had a csv import/export feature. This has been working fine, until recently I discovered it erroring in one scenario. This may have been due to moving to Silverlight 3.
The Error:
Message: Unhandled Error in Silverlight 2 Application
Code: 4004
Category: ManagedRuntimeError
Message: System.Security.SecurityException: Dialogs must be user-initiated.
at System.Windows.Controls.OpenFileDialog.ShowDialog()
at MyControl.OpenImportFileDialog()
at ...
The Code:
private void BrowseFileButton_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(lblFileName.Text))
{
if (MessageBox.Show("Are you sure you want to change the Import file?", "Import", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
{
return;
}
}
EnableDisableImportButtons(false);
var fileName = OpenImportFileDialog();
lblFileName.Text = fileName ?? string.Empty;
EnableDisableImportButtons(true);
}
private string OpenImportFileDialog()
{
var dlg = new OpenFileDialog { Filter = "CSV Files (*.csv)|*.csv" };
if (dlg.ShowDialog() ?? false)
{
using (var reader = dlg.File.OpenText())
{
string fileName;
//process the file here and store fileName in variable
return fileName;
}
}
}
I can open an import file, but if i want to change the import file, and re-open the file dialog, it errors. Does anyone know why this is the case?
Also, I am having trouble debugging because placing a breakpoint on the same line (or prior) to the dlg.ShowDialog() call seems to cause this error to appear as well.
Any help would be appreciated?

You do two actions on one user click.
You show a messagebox which effectively uses your permission to show a dialog on user action.
You then try to show the dialog, since this is a second dialog on user action it's not allowed.
Get rid of the confirmation dialog and you'll be fine.

Remove Break Points before if (dlg.ShowDialog() ?? false) code will run its work for me.

Related

Xamarin Media Plugin Crashes when second photo is taken

I am using the Plugin.Media (jamesmontemagno/MediaPlugin) plugin for Xamarin and I am having an issue with accepting a picture. When I take the second picture (the first picture works fine) and I click to accept the image the whole app crashes with no output as to the error. I have tried trapping the error but cannot find where it is occurring. I have as suggested removing the min SDK from Android manifest, but the crash still happens.
I have tried looking through the output in visual studio but it is always different. I am assuming the code works as it takes the image and gives me data back, to be clear, it only happens when trying to accept the second image.
private string GetTimestamp(DateTime value)
{
string timestamp = value.ToString("yyyyMMddHHmmssfff");
string filename = timestamp + ".jpg";
return filename;
}
public Command CaptureImage => new Command(TakePicture);
private async void TakePicture()
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
//Some message
return;
}
var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory = "FoodSnap",
Name = GetTimestamp(DateTime.Now) //Gets a unique file name,
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Custom,
CustomPhotoSize = 50
});
if (file == null)
return;
FilePath = file.Path;
}
I am completely stumped as to why this is happening. I am also having trouble refreshing my ViewModel when data changes in the page I am using to take the image. I can't help wondering if this has something to do with it.
I solved the problem by testing each line of code. Once I removed PhotoSize = Plugin.Media.Abstractions.PhotoSize.Custom I could take as many pictures as I need. I did use the Github information for the plugin.
I would be interested to know what I did wrong to cause the error. I would suggest that I have misunderstood the tutorial on Github.

Open link in browser from code behind of installed application C#

I have made a winform application. When I run the app in visual studio, following code works to open a link from DataGridView link column.
System.Diagnostics.Process.Start("chrome.exe",
grdRelLinks.Rows[e.RowIndex].Cells[2].Value.ToString());
But when I install the build and try to do the same thing, nothing happens. Is there any other setting that I need to make.
Please help.
If you want to open link link from your DataGridView, you should actually pass url not web browser, ie.:
System.Diagnostics.Process.Start(grdRelLinks.Rows[e.RowIndex].Cells[2].Value.ToString());
It will end up trying to open given url with default browser for OS.
Ofc make sure that link of url from url is properly formatted.
If chrome.exe doesn't work for launching, maybe try shortened one: chrome?
Can you also confirm that Win+R (a.k.a. Run...) and then chrome.exe actually opens up Chrome?
If not, can you check if
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\ contains chrome.exe entry?
If so, maybe url formatting is wrong?
You can open a URL in browser with the following snippets:
Process process = new Process();
process.StartInfo.UseShellExecute = true;
process.StartInfo.FileName = "http://google.com";
process.Start();
or
System.Diagnostics.Process.Start("http://google.com");
In your example, to allow users to launch it from the DataGridView, you should simply define a click event like this:
private void grdRelLinks_CellContentClick(object pSender, DataGridViewCellEventArgs pArgs)
{
if (pArgs.RowIndex > -1 && pArgs.ColumnIndex == 2)
{
string url = grdRelLinks.Rows[pArgs.RowIndex].Cells[pArgs.ColumnIndex].Value.ToString();
if(!string.IsNullOrWhiteSpace(url))
System.Diagnostics.Process.Start(url);
}
}
This worked for me.
private void OnGridViewContentClick(object sender, EventArgs e)
{
string chromeExePath = CheckIfChromeIsInstalled();
if (!string.IsNullOrEmpty(chromeExePath))
{
MessageBox.Show("Yayy Chrome.exe was found !");
//Path is not null:
Process.Start(chromeExePath, "http://www.google.de");//Here you can also enter the URL you get from your GridView
string url = grdRelLinks.Rows[e.RowIndex].Cells[2].Value.ToString();
if(!url.StartsWith("http")
{
url = $"http://{url}";
}
Process.Start(chromeExePath, url);
}
else
{
MessageBox.Show("Chrome.exe not found");
}
}
private string CheckIfChromeIsInstalled()
{
DirectoryInfo programFiles = new DirectoryInfo(Environment.GetEnvironmentVariable("PROGRAMFILES"));//Find your Programs folder
DirectoryInfo[] dirs = programFiles.GetDirectories();
List<FileInfo> files = new List<FileInfo>();
Parallel.ForEach(dirs, (dir) =>
{
files.AddRange(dir.GetFiles("chrome.exe", SearchOption.AllDirectories)); //Search for Chrome.exe
});
//files should only contain 1 entry
//Return path of chrom.exe or null
return (files.Count > 0) ? files[0].FullName : null;
}
NOTE: Starting this in an extra Thread could be useful !
EDIT :
Can you please check if cmd.exe works with start chrome.exe "your URL" ?!

Open PDF using C#-- Windows 8 Store Application

I want to be able to open a PDF using the native Windows Reader Application when a user clicks on a button. So far I am able to use the following code to successfully open files that end with the (.PNG) extension. However, when I let the link to open the (.PDF) file I get the following error.
The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
The file destination is correct.
Here is my code:
private async void btnLoad_Click(object sender, RoutedEventArgs e)
{
// Path to the file in the app package to launch
string imageFile = #"Data\Healthcare-Flyer.pdf";
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);
if (file != null)
{
// Set the option to show the picker
var options = new Windows.System.LauncherOptions();
options.DisplayApplicationPicker = true;
// Launch the retrieved file
bool success = await Windows.System.Launcher.LaunchFileAsync(file, options);
if (success)
{
// File launched
}
else
{
// File launch failed
}
}
else
{
// Could not find file
}
}
}
When you add PDF document in project, you have to change it's build action.
Right click on PDF document.
Click on properties.
Change Build Action from None to Content

How can I get the CommonOpenFileDialog's InitialDirectory to be the user's MyDocuments path, instead of Libraries\Documents?

I'm using the CommonOpenFileDialog in the Windows API Code Pack as a folder picker dialog. I'm setting the InitialDirectory property to Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments). However, when I display the dialog, the path in the address bar is Libraries\Documents (not C:\users\craig\my documents as I'd expect). Additionally, if I just press the Select Folder button, I get a dialog saying that 'You've selected a library. Please choose a folder instead.'
Does someone know why my file path is being ignored, in favor of 'libraries\documents'? More importantly, how can I get the dialog to respect the InitialDirectory value I passed in?
The code I'm using for the dialog is:
if (CommonFileDialog.IsPlatformSupported)
{
var folderSelectorDialog = new CommonOpenFileDialog();
folderSelectorDialog.EnsureReadOnly = true;
folderSelectorDialog.IsFolderPicker = true;
folderSelectorDialog.AllowNonFileSystemItems = false;
folderSelectorDialog.Multiselect = false;
folderSelectorDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
folderSelectorDialog.Title = "Project Location";
if (folderSelectorDialog.ShowDialog() == CommonFileDialogResult.Ok)
{
ShellContainer shellContainer = null;
try
{
// Try to get a valid selected item
shellContainer = folderSelectorDialog.FileAsShellObject as ShellContainer;
}
catch
{
MessageBox.Show("Could not create a ShellObject from the selected item");
}
FilePath = shellContainer != null ? shellContainer.ParsingName : string.Empty;
}
}
Thanks,
-Craig
First of all, I'm sorry it took me so long to understand your question.
The message I see is when I try this is:
Cannot operate on
'Libraries\Documents' because it is
not part of the file system.
There's not much more to say. A library is a virtual folder that is an amalgamation of various different real folders.
There's no real way to avoid this error. You have asked the dialog to return a folder and the user has not selected a folder. The dialog therefore cannot fulfil its part of the deal.
If you descend further into the folder structure, into real folders, then the dialog will return you a real value.
Instead of
folderSelectorDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
try
folderSelectorDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);

Getting an exception as "The parameter is incorrect.\r\n" while moving file

I have written a code to move a file as follows
private void Move_Click(object sender, EventArgs e)
{
string strOrgpath = string.Empty, strNewpath = string.Empty;
strOrgpath = tvwACH.SelectedNode.ToString();
string strPath = strOrgpath.Substring(10);
FolderBrowserDialog folderborwser1 = new FolderBrowserDialog();
if (folderborwser1.ShowDialog() == DialogResult.OK)
{
try
{
strNewpath = folderborwser1.SelectedPath;
File.Move(strPath, strNewpath);
}
catch (Exception ex)
{
}
}
}
But i am getting the exception as i mentioned can any one tell why and some times i am getting the error as access to the path is denied
Make sure your substring call returns the correct result. If possible, use static methods from the Path class instead. Take a look at the MSDN page for File.Move and pay attention to what parameters are expected -- you should provide two valid full file names (e.g. C:\Blah\myFile.txt).
"Access denied" error message might happen if the user picks a folder they don't have write access to in the folder browser dialog. That's a scenario you'll have to handle in your code, perhaps by catching the UnauthorizedAccessException.
Update: the destination file should also point to a filename. So you'll need to do something like this:
var origFileName = Path.GetFileName(strPath);
strNewpath = Path.Combine(folderborwser1.SelectedPath, origFileName);
File.Move(strPath, strNewpath);
Without seeing the values that are being used in your application at run-time, I'm guessing tvwACH.SelecteNode.ToString() or strOrgpath.Substring(10) is not a valid File System path.
You should Debug your application and set a breakpoint to see what those values are (and post them if it's not obvious what your problem is at that point).

Categories