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

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.

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();
}
}
}
}

Android studio how delete downloaded files parse?

I am new in android studio and I am using Parse to store images. I am creating an image gallery and I am able to display downloaded images from parse to gridview. The problem is everytime I restart the app, my SDcard will download the exact same files from Parse. Is there a way to delete these unnecessary files? Or how can I put these Downloaded image files into a temporary storage where they will be deleted once the user is finished with the app?
This is my code for downloading the images and store them in gridview:
for (ParseObject imageOb : objects) {
final ParseFile file = (ParseFile) imageOb.get("image");
file.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if (e == null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
Uri uri = getImageUri(getApplicationContext(), bitmap);
File imageFiles = new File(getRealPathFromURI(uri));
imageAdapter.add(imageFiles.toString());
}
imageAdapter.notifyDataSetChanged();
}
});
}
There are some answers already on Stack overflow about temporary files, for example What is the best way to create temporary files
You could also manually delete the downloaded files when the application doesn't need them anymore. If you download them in onCreate you should delete them in onDestroy. Otherwise, check out this Article about the Android lifecycle

Accessing the images folder in wpf app

I have a wpf application in which I want to save a file in the Images folder, which is on the same level with the bin folder.
How do I access that folder?
I try like this:
using (var imageFile = new FileStream((new Uri(#"pack://application:,,,/Images/Application/")).ToString(), FileMode.Create))
{
//
}
and I get the error that "The given path's format is not supported.". How can I access that folder?
Your path refers to resources within the project assembly. You should use relative or absolute file system paths:
var path = Path.Combine(
Path.DirectorySeparatorChar.ToString(),
AppDomain.CurrentDomain.BaseDirectory,
"Images"); // Result could be for example: "C:\MyWorkspace\MyProject\bin\Debug\Images"
using (var imageFile = new FileStream(path, FileMode.Create)) { }
How about using double dots(..) to get to parent directory.
using (var imageFile = new FileStream("..\..\[Path goes here]", FileMode.Create))
{
//
}

How to write logs data in a local txt file?

I have an AIR-app and I want it to write down logs to a txt file in its application directory.
I have this class:
public class Logger
{
public static function log(message:String):void
{
var logFile:File = File.applicationDirectory;
logFile = logFile.resolvePath("log/Logs.txt");
var fileStream:FileStream = new FileStream();
fileStream.open(logFile, FileMode.APPEND);
fileStream.writeUTFBytes("\n" + message);
fileStream.close();
}
}
}
After installation my app has this file structure
log
--Logs.txt
META-INF
xml
airapp.exe
airapp.swf
mimetype
So the path I'm using is correct.
But no writes happen to the file!
Could you help me with that please?
Thanks
Upd. Ok, I'm stupid. I should have read documentation properly first.
You cannot edit data in application directory.
So I should use applicationStorageDirectory.
But how can I create a file in that directory once (on app installation) and then append logs in it?
Try the following....
function saveLog(logStr:String):void
{
var myFile:File = File.applicationStorageDirectory.resolvePath("my_logs.txt");
var fs:FileStream = new FileStream();
if(!myFile.exists){
fs.open(myFile, FileMode.WRITE);
}
else{
fs.open(myFile, FileMode.APPEND);
}
fs.writeUTFBytes("\n" + logStr);
fs.close();
}
call this function on creation complete and then from where to add logs.
If you want the real log than you should use third party installer rather than native run time of adobe air. Try Wixedit(opensource) or install aware .
You have to export your project into captive run time format that is provided in flash builder.
try this link
http://www.adobe.com/devnet/air/articles/customize-setup-for-AIR-app-with-captive-runtime.html
Try something like:
function saveLog(content:String):void
{
var data:ByteArray = new ByteArray();
data.writeMultiByte(content, "utf-8");
file.save(data, "Logs.txt");
}
saveLog('testing :)');
To open and edit your log file, try to follow this tutorial

silverlight 4, dynamically loading xap modules

I know that it is possible to load xap modules dynamically using Prism or MEF framework. However, I'd like not to use those frameworks; instead load my xap files manually. So, I created the following class (adapted from internet):
public class XapLoader
{
public event XapLoadedEventHandler Completed;
private string _xapName;
public XapLoader(string xapName)
{
if (string.IsNullOrWhiteSpace(xapName))
throw new ArgumentException("Invalid module name!");
else
_xapName = xapName;
}
public void Begin()
{
Uri uri = new Uri(_xapName, UriKind.Relative);
if (uri != null)
{
WebClient wc = new WebClient();
wc.OpenReadCompleted += onXapLoadingResponse;
wc.OpenReadAsync(uri);
}
}
private void onXapLoadingResponse(object sender, OpenReadCompletedEventArgs e)
{
if ((e.Error == null) && (e.Cancelled == false))
initXap(e.Result);
if (Completed != null)
{
XapLoadedEventArgs args = new XapLoadedEventArgs();
args.Error = e.Error;
args.Cancelled = e.Cancelled;
Completed(this, args);
}
}
private void initXap(Stream stream)
{
string appManifest = new StreamReader(Application.GetResourceStream(
new StreamResourceInfo(stream, null), new Uri("AppManifest.xaml",
UriKind.Relative)).Stream).ReadToEnd();
XElement deploy = XDocument.Parse(appManifest).Root;
List<XElement> parts = (from assemblyParts in deploy.Elements().Elements()
select assemblyParts).ToList();
foreach (XElement xe in parts)
{
string source = xe.Attribute("Source").Value;
AssemblyPart asmPart = new AssemblyPart();
StreamResourceInfo streamInfo = Application.GetResourceStream(
new StreamResourceInfo(stream, "application/binary"),
new Uri(source, UriKind.Relative));
asmPart.Load(streamInfo.Stream);
}
}
}
public delegate void XapLoadedEventHandler(object sender, XapLoadedEventArgs e);
public class XapLoadedEventArgs : EventArgs
{
public Exception Error { get; set; }
public bool Cancelled { get; set; }
}
The above code works fine; I can load any xap the following way:
XapLoader xapLoader = new XapLoader("Sales.xap");
xapLoader.Completed += new XapLoadedEventHandler(xapLoader_Completed);
xapLoader.Begin();
Now, I have a UserControl called InvoiceView in the Sales.xap project, so I would like to instantiate the class. In the current project (Main.xap) I added reference to Sales.xap project, however, since I load it manually I set "Copy Local = False". But when executed, the following code throws TypeLoadException:
Sales.InvoiceView view = new Sales.InvoiceView();
It seems the code can't find InvoiceView class. But I checked that XapLoader's initXap() method was successfully executed. So why the code can't find InvoiceView class? Can someone help me with this problem?
This is based on the asker's self-answer below, rather than the question.
If you delete a project/module the output DLLs/XAP files do hang around. If you click the "show all files" button you will see some these left-over output files in your clientbin, bin and obj folders of related projects.
You can delete them individually from the project, or, when in doubt, search for all BIN and OBJ (e.g. using desktop explorer) and delete all those folders. The BIN/CLIENTBIN/OBJ folders will be recreated when needed (this the job that the "clean" option in Visual Studio should have done!)
Hope this helps.
Ok, I found the cause. The above code works. After creating a new silverlight project (Sales.xap) I happened to compile my solution once. Then I deleted App class in the Sales.xap and renamed default MainPage class to SalesView. However, no matter how many times I compile my solution, Visual Studio's development web server was loading the first version of Sales.xap (where from?), so my code couldn't find SalesView. In my host Asp.Net project I set development server's port to a different port number, and the problem gone. So the problem was with Visual Studio's development server. Apparently it is keeping compiled xap files in some temporary folder, and doesn't always update those xap files when source code changed.
What I do to avoid such problems when executing freshly compiled Silverlight is clear the browser cache, chrome even has a clear silverlight cache ;)
this XAP Cache phenomena is often due to the visual studio embedded web server (ASP.NET Development Server).
Just stop the occurence of this server and the cache will be cleared.
Start again your project and the latest build of your xap is called.

Resources