How to stop WPF drag and drop from locking dropped file - wpf

I have a drag and drop application (which allows users to organize their files) that takes files. The app keeps a list of strings that corresponds to the files, but it does not need access to the files themselves. The problem is that the program locks files like the application has them open. How can I release them?
private void File_Dropped(object sender, DragEventArgs e)
{
if (!e.Data.GetDataPresent(DataFormats.FileDrop))
return;
var files = e.Data.GetData(DataFormats.FileDrop, true) as string[];
ImageFile iFile;
foreach (var file in files)
{
if (_Extensions.Contains(IO.Path.GetExtension(file).ToUpper()))
{
iFile = new ExtendedImageFile(new StringBuilder(file).ToString());
LBXFiles.Items.Add(iFile);
}
}
e.Handled = true;
}

Fantastic fix lived up to his name. See the commend on the original post

Related

Best practices for file system of application data JavaFX

I am trying to build an inventory management system and have recently asked a question about how to be able to store images in a package within my src file. I was told that you should not store images where class files are stored but have not been told what the best practices are for file systems. I have created a new page that allows the user to input all the data about a new part that they are adding to the system and upload an image associated with the part. When they save, everything worked fine until you try to reload the parts database. If you 'refresh' eclipse and then update the database, everything was fine because you could see the image pop into the package when refreshed. (All database info was updated properly as well.
I was told not to store these types of 'new' images with the program files but to create a separate file system to store these types of images. Is there a best practice for these types of file systems? My confusion is when the program gets saved where ever it is going to be saved, I can't have it point to an absolute path because it might not be saved on a C drive or K drive and I wouldn't want an images folder just sitting on the C drive that has all of the parts images for anyone to mess with. Please give me some good resources on how to build these file systems. I would like the images folder 'packaged' with the program when I compile it and package all the files together, I have not been able to find any good information on this, thanks!
To answer this question, probably not in the best way, but works pretty well.
I ended up making another menuItem and menu that you can see at the top 'Image Management', where it lets the user set the location that they would like to save all the images as well as a location to back up the images. it creates the directory if it is not there or it will save over the images if the directory is already there. This menu will only appear if the user has admin privileges. I would think that this could be set up with an install wizard, but I have no idea how to make one, where it only runs on installation. I am also going to add an autosave feature to save to both locations if a backup location has been set. This is the best way I can think of managing all the parts images, if anyone has some good input, please let me know. I considered a server, but think that is too much for this application and retrieving images every time the tableView populates would take a lot of time. If interested the code I used is:
public class ImageDirectoryController implements Initializable{
#FXML private AnchorPane imageDirectory;
#FXML private Label imageDirLbl, backupLbl;
#FXML private Button setLocationButton, backupButton;
#FXML private TextField imageDirPathTxtField;
Stage window;
String image_directory;
#Override
public void initialize(URL location, ResourceBundle resources) {
// TODO Auto-generated method stub
}
public void setImageDirectory(String image_address, String backup_address) {
imageDirLbl.setText(image_address);
backupLbl.setText(backup_address);
}
#FXML
public void setLocationButtonClicked () {
String imagesPath = imageDirPathTxtField.getText() + "tolmarImages\\";
File files = new File(imagesPath + "asepticImages");
File generalFiles = new File(imagesPath + "generalImages");
File facilitiesFiles = new File(imagesPath + "facilitiesImages");
boolean answer = ConfirmBox.display("Set Image", "Are you sure you want to set this location?");
if(answer) {
if (!files.exists()) {
if (files.mkdirs() && generalFiles.mkdirs() && facilitiesFiles.mkdirs()) {
JOptionPane.showMessageDialog (null, "New Image directories have been created!", "Image directory created", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog (null, "Failed to create multiple directories!", "Image directory not created", JOptionPane.INFORMATION_MESSAGE);
}
}
DBConnection dBC = new DBConnection();
Connection con = dBC.getDBConnection();
String updateStmt = "UPDATE image_address SET image_address = ? WHERE rowid = ?";
try {
PreparedStatement myStmt = con.prepareStatement(updateStmt);
myStmt.setString(1, imageDirPathTxtField.getText());
myStmt.setInt(2, 1);
myStmt.executeUpdate();
myStmt.close();
imageDirPathTxtField.clear();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#FXML
public void backupButtonClicked () {
String backupStatus = null;
if (backupLbl.getText().equals("")&& !imageDirPathTxtField.getText().equals("")) {
backupStatus = imageDirPathTxtField.getText();
} else if (!imageDirPathTxtField.getText().equals("")) {
backupStatus = imageDirPathTxtField.getText();
} else if (!backupLbl.getText().equals("")){
backupStatus = backupLbl.getText();
} else {
JOptionPane.showMessageDialog(null, "You must create a directory.", "No directory created", JOptionPane.INFORMATION_MESSAGE);
return;
}
boolean answer = ConfirmBox.display("Set Image", "Are you sure you want to backup the images?");
if(answer) {
DBConnection dBC = new DBConnection();
Connection con = dBC.getDBConnection();
String updateStmt = "UPDATE image_address SET image_address = ? WHERE rowid = 2";
try {
PreparedStatement myStmt = con.prepareStatement(updateStmt);
myStmt.setString(1, backupStatus);
myStmt.executeUpdate();
myStmt.close();
String source = imageDirLbl.getText() + "tolmarImages";
File srcDir = new File(source);
String destination = backupStatus + "tolmarImages";
File destDir = new File(destination);
try {
FileUtils.copyDirectory(srcDir, destDir);
JOptionPane.showMessageDialog(null, "Images copied successfully.", "Images copied", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

Winphone8.1 development: Can I get a List of al files stored within the Assets folder?

I am running win8.1 , and VS2013 SP3, trying to create a windows phone app which should retrieve all the document names and paths (for later reference) from the 'Assets' folder.
I added a bunch of word documents in the Assets folder and set the build to content, and copy to always.
Is it possible to get a list of all files (or file names) in the assets folder?
I can't seem to find the way to do it.
What I can do is reference a specific file, but what I would like to do, is list out all the file names/paths within the Assets folder and show the details of these files in a specific view...
I tried the following:
var package = Windows.ApplicationModel.Package.Current.InstalledLocation;
var assetsFolder = await package.GetFolderAsync("Assets");
foreach (var file in await assetsFolder.GetFilesAsync())
{
_documents.Add(new Document() { Category = section, Title = file.Name, Uri = file.Path });
}
This code freezes on the foreach line...?
I would very much appreciate some guidance or references in this matter.
Maybe it's the way you're calling it.
Here's mine with screenshots.
I only call it once the whole page has loaded.
private void Page_Loaded(object sender, RoutedEventArgs e)
{
ReadAssetFolder();
}
public async void ReadAssetFolder()
{
var package = Windows.ApplicationModel.Package.Current.InstalledLocation;
var assetsFolder = await package.GetFolderAsync("Assets");
foreach (var file in await assetsFolder.GetFilesAsync())
{
int debug_var = 1;
}
}
Screenshot of when the debugger hits my breakpoint:
Screenshot of my Asset folder
Finally all my files have these Properties
Hope that helps you.

Silverlight OpenFileDialog Filter Property with Extension and file name

Is there any way when set the filter property of OpenFileDialog control in Silverlight, we can filter file by extension and part of the file name? For example how do I set the filter property if i just want to show files that starts with letter A and have the extension .dat. Please keep in mind i might have other files with same extension by starts with different letter. I don't want to show those. Thanks for your reply.
Well very old question, but i had similar problem and here is how it worked for me:
private void BrowseExcelFileButton_Click(object sender, RoutedEventArgs e)
{
//This needs to be before try statement othervise exception is thrown ("Dialogs must be user-initiated")
OpenFileDialog openFileDialog = new OpenFileDialog();
try
{
openFileDialog.Filter = "Excel Files (*.xls,*.xlsx)|*.xls;*.xlsx|All Files (*.*)|*.*";
openFileDialog.FilterIndex = 1;
if (openFileDialog.ShowDialog() == true)
{
...
}
}
catch (Exception ex)
{
...
}
}

File Uploading in Silverlight

I want to upload a particular file on server in Silverlight 4,
Simply, to upload any file we can use the "Browse" button.
When you click on this button we can get the file directory and choose any file & we can upload the particular file.
i have coded on browse button
private void btnBrowse_Click(object sender, RoutedEventArgs e)
{
var fileDialog =new OpenFileDialog();
fileDialog.ShowDialog();
fileDialog.Multiselect = true;
txtUploader.Text = fileDialog.File.DirectoryName;
fileDialog.File.CopyTo("C:/UploadedFiles");
}
here the problem is, only the dialog box is opening
not able to select multiple file,
not getting path,
not able to upload the file to specified location.
Try changing the order that you are setting up your OpenFileDialog Box.
Also you are returning a FileInfo object. If you are going to return multiple files you need use Files instead of File it will return a collection of FileInfo objects. You can then iterate over the collection to get your information. In testing out the code I was getting a Security Exception on reading the path of the files, you do not have the permissions needed to do what you want to do per #MattGreer's comment.
Edit added from #AnthonyWJones comment.
There is not any way to do what you are trying to do, except to create an OOB with elevated trust, and that will limit you to the users MyDocuments Folder.
private void btnBrowse_Click(object sender, RoutedEventArgs e)
{
var fileDialog =new OpenFileDialog();
fileDialog.Multiselect = true;
fileDialog.ShowDialog();
IEnumerable<System.IO.FileInfo> files = fileDialog.Files;
foreach (System.IO.FileInfo fi in files)
{
txtUploader.Text = fi.DirectoryName;
fi.CopyTo("C:/UploadedFiles");
}
}

Sharepoint 2010 Upload file using Silverlight 4.0

I am trying to do a file upload from Silverlight(Client Object Model) to Sharepoint 2010 library.. Please see the code below..
try{
context = new ClientContext("http://deepu-pc/");
web = context.Web;
context.Load(web);
OpenFileDialog oFileDialog = new OpenFileDialog();
oFileDialog.FilterIndex = 1;
oFileDialog.Multiselect = false;
if (oFileDialog.ShowDialog().Value == true)
{
var localFile = new FileCreationInformation();
localFile.Content = System.IO.File.ReadAllBytes(oFileDialog.File.FullName);
localFile.Url = System.IO.Path.GetFileName(oFileDialog.File.Name);
List docs = web.Lists.GetByTitle("Gallery");
context.Load(docs);
File file = docs.RootFolder.Files.Add(localFile);
context.Load(file);
context.ExecuteQueryAsync(OnSiteLoadSuccess, OnSiteLoadFailure);
}
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
But I am getting the following error
System.Security.SecurityException: File operation not permitted. Access to path '' is denied.
at System.IO.FileSecurityState.EnsureState()
at System.IO.FileSystemInfo.get_FullName()
at ImageUploadSilverlight.MainPage.FileUpload_Click(Object sender, RoutedEventArgs e)
Any help would be appreciated
Thanks
Deepu
Silverlight runs with very restricted access to the client user's filesystem. When using an open-file dialog, you can get the name of the selected file within its parent folder, the length of the file, and a stream from which to read the data in the file, but not much more than that. You can't read the full path of the file selected, and you are getting the exception because you are attempting to do precisely that.
If you want to read the entire content of the file into a byte array, you'll have to replace the line
localFile.Content = System.IO.File.ReadAllBytes(oFileDialog.File.FullName);
with something like
localFile.content = ReadFully(oFileDialog.File.OpenRead());
The ReadFully method reads the entire content of a stream into a byte array. It's not a standard Silverlight method; instead it
is taken from this answer. (I gave this method a quick test on Silverlight, and it appears to work.)

Resources