FileNotFoundException when starting a background download even though file clearly exists - windows-runtime

In my WinRT application I have the following code:
resultingFile = await downloadFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);
var downloader = new BackgroundDownloader();
var operation = downloader.CreateDownload(new Uri(rendition.Url), resultingFile);
await operation.StartAsync();
After the CreateFileAsync call I can verify that I do have a 0byte file at the filename path (and double verified by pulling the location out of the resultingFile itself.
However, when operation.StartAsync() is called I get a FileNotFoundException claiming the system could not find the file specified. Unfortunately, that's all it tells me and there is no inner exception.
I have also verified that rendition.Url gives me a valid url that downloads the content I'm expecting to be downloading.
Am I doing something wrong here?

Apparently this code isn't what is throwing the error but it's some code the BackgroundDownloader uses to coordinate things that can't find it's own file.
Uninstalling the application and redeploying it fixed it.
Good waste of 3 hours :(

Related

Cannot download file from Google Storage inside Cloud Function?

Im trying to perform a simple download of a .docx file info a buffer so I can handle it latter inside my Cloud Function. I've been using the whole Google Platform for multiple projects but never faced the need to download in server side, and now I need to, I just cant.
The following piece of code is not working, it just sends timeout as a response (I don't even get an error If I try to catch it or something):
var bucket = admin.storage().bucket("gs://myBucket.com");
return bucket.file("001Lineales/4x3-1/1000.docx").download().then((contents)=>{
var buffer = contents[0];
//I never get into this point
}).catch((error)=>{
//No error
})
I tried in a local NodeJs script and worked as expected. Also tried to perform a readStream() download but no luck, the function gets hang up in any try of downloading the file.
return new Promise((resolve,reject)=>{
var archivo = bucket.file(selectedCategory).createReadStream();
var array = [];
//Under here, never happens
archivo.on('data', (d) => {array.push(d)}).on("end",()=>{
var newbuff = Buffer.concat(array);
resolve(newbuff)
})
})
The file permissions read/write are public. And the main problem is that debugging is difficult cause Im not able to perform this function in local emulator.
What can I do? Thanks in advance.
EDIT:
Double checking a local call with emulator, I get the following error:
Anonymous caller does not have storage.objects.get access to the Google Cloud Storage object.
Double check the service account hat you've assigned to the Cloud Function and that you've given it the permission it needs.
I think Storage Object Viewer will give you what you need to read a file into the buffer.
By default, if you haven't changed it, the AppEngine's default service account gets used, which I don't think has access to Storage.

Trouble with getting script to recognize a JSON file in the directory (Google API)

So I am attempting to learn how to use the Google Sheets API with Node.js. In order to get an understanding, I followed along with the node.js quick start guide supplied by Google. I attempted to run it, nearly line for line a copy of the guide, just without documentation. I wind up encountering this: cmd console output that definitely didn't work.
Just in case anyone wants to see if I am not matching the guide, which is entirely possible since I am fairly new to this, here is a link to the Google page and my code.
https://developers.google.com/sheets/api/quickstart/nodejs
var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'sheets.googleapis.com-nodejs-quickstart.json';
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
}
authorize(JSON.parse(content), listMajors);
});
I have tried placing the JSON file in each and every part of the directory, but it still won't see it. I've been pulling hairs all day, and a poke in the right direction would be immensely appreciated.
From your command output:
Error loading client secret file
So your if (err) line is being triggered. But since you don't throw the error, the script continues anyway (which is dangerous in general).
SyntaxError: Unexpected token u in JSON at position 0
This means that the data you are passing to JSON.parse() is undefined. It is not a valid JSON string.
You could use load-json-file (or the thing it uses, parse-json) to get more helpful error messages. But it's caused by the fact that your content variable has nothing since the client_secret.json you tried to read could not be found.
As for why the file could not be found, there could be a typo in either the script or the filename you saved the JSON in. Or it may have to do with the current working directory. You may want to use something like this to ensure you end up with the same path regardless of the current working directory.
path.join(__dirname, 'client_secret.json')
Resources
path.join()
__dirname

Getting IsolatedStorageException when trying to create directory in windows phone application

Here is my code.
var storage = IsolatedStorageFile.GetUserStoreForApplication();
if (!directoryPath.StartsWith("/"))
directoryPath = "/" + directoryPath;
if (!storage.DirectoryExists(directoryPath))
{
storage.CreateDirectory(directoryPath);
}
Sometimes I am getting following exception when I call this method.
[Type]:[IsolatedStorageException]
[ExceptionMessage]:[Unable to create directory.]
I don't know why I am getting this exception. Is there any problem in my code? It is working fine many times but some times I am getting exception.
Please let me know what is the problem in my code.
I was getting this error message. It turns out that I was using the full directory path when I should have just been using the folder name.
After I changed it to just the last folder name it stopped throwing this exception.

How to read data files included in the app

For my program I have to include huge index and data files in the program bundle. Because it is an universal app, I have included these files in a folder named "Data" within the "Shared" Project.
Now I try to read:
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("Data/"+fileName);
Stream stream = (await file.OpenReadAsync()).AsStreamForRead();
BinaryReader reader = new BinaryReader(stream);
Windows.Storage.FileProperties.BasicProperties x = await file.GetBasicPropertiesAsync();
I get a System.ArgumentException "mscorlib.ni.dll" at the first line. What's wrong?
If somebody can help me and I get the file, I want to find the filesize. I hope, I can find this Information within the FileProperties (last line of code).
Then I want to set a FilePointer within that file and to read a defined number of binary data. Can I do that without reading the whole file in memory?
What you are trying to do is to access LocalFolder, which is not the same as Package.Current.InstalledLocation.
If you want to access files that are included with your package, you can do for example like this - by using URI schemes:
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(#"ms-appx:///Data/"+fileName));
using (Stream stream = (await file.OpenReadAsync()).AsStreamForRead())
using (BinaryReader reader = new BinaryReader(stream))
{
Windows.Storage.FileProperties.BasicProperties x = await file.GetBasicPropertiesAsync();
}
or like this - by getting file from your Package, which you can access as StorageFolder - also pay attention here to use correct slashes (as it may be a source of exception):
StorageFile file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(#"Data\" + fileName);
using (Stream stream = (await file.OpenReadAsync()).AsStreamForRead())
using (BinaryReader reader = new BinaryReader(stream))
{
Windows.Storage.FileProperties.BasicProperties x = await file.GetBasicPropertiesAsync();
}
Note also that I've put your Stream and BinaryReader into using, as they are IDisposable and it's suitable to release those resources as they are no longer needed.
Note also that when your shared project has a name MySharedProject, you will have to modify the Path of above URI:
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(#"ms-appx:///MySharedProject/Data/"+fileName));
or obtain the suitable StorageFolder:
StorageFile file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(#"MySharedProject\Data\" + fileName);
One remark after discussion:
When you add a file with .txt extension to your project, its Build Action by default is set to Content. But when you add file with .idx extension, as I've checked, its Build Action is set to None by default. To include those files in your package, change them to Content.
After Romasz has brought me to the right path, I can see the problem is quite different there.
My data files were involved in the correct place in the project, but Visual Studio does not bind all what you want.
In my project I need large data files to be firmly integrated into the program. These are between 13 KB and 41 MB in size and have file types .idx and .dat. These names are part of the problem.
What I know so far:
I may add .txt files with seemingly arbitrary size. Tested with 41 MB - no problem.
The same file with changed file type .idx is not added. The file is simply not included in the compiled project. No error message.
Of course I can rename the .idx files to another file type (tested with .id), but I want to know why idx files are treated differently. And why I got no error indication.

How to put\save files into your application directory? (adobe air)

How to put\save files into your application directory? (adobe air) (code example, please)
It's not recomended but it is possible. Construct your File reference like this:
var pathToFile:String = File.applicationDirectory.resolvePath('file.txt').nativePath;
var someFile:File = new File(pathToFile);
You can't write to your AIR app's Application Directory, it's not allowed. You can however write to a folder that your AIR app creates in the user's directory, called the Application Storage Directory. If you need config files and the like, that's probably the best place to put them. See 'applicationDirectory' in the docs link below:
http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/
#glendon
if you try to save directly to applicationDirectory it will indeed throw an error, but it seems you can move the file in the filesystem. i used the code below after yours:
var sourceFile:File = File.applicationStorageDirectory.resolvePath ("file.txt");
var pathToFile:String = File.applicationDirectory.resolvePath ('file.txt').nativePath;
var destination:File = new File (pathToFile);
sourceFile.moveTo (destination, true);
the reason why you 'shouldnt' use the application folder is because not all users have rights to save files in such folder, while everyone will in applicationStorageDirectory.
The accepted answer works!
But if I do this instead:
var vFile = File.applicationDirectory.resolvePath('file.txt');
var vStream = new FileStream();
vStream.open(vFile, FileMode.WRITE);
vStream.writeUTFBytes("Hello World");
vStream.close();
It will give SecurityError: fileWriteResource. However, if I use applicationStorageDirectory instead, the above code will work. It'll only NOT work if it's applicationDirectory. Moreover, Adobe's documentation also says that an AIR app cannot write to its applicationDirectory.
Now, I wonder if it's a bug on Adobe's part that they allow writing to the applicationDirectory using the way suggested by the accepted answer.
try this.
var objFile:File = new File(“file:///”+File.applicationDirectory.resolvePath(strFilePath).nativePath);
the output would be like this…
file:///c:\del\userConf.xml
This will work fine.
If you want write file into ApplicationDirectory, right?
Please don't forget for write for nativeprocess via powershell with registry key for your currect adobe application ( example: C:\Program Files (x86)\AirApp\AirApp.exe with RunAsAdmin )
nativeprocess saves new registry file
AirApp will restarts into RunASAdmin
AirApp can be writable possible with file :)
Don't worry!
I know that trick like sometimes application write frist via registry file and calls powershell by writing nativeprocess into registry file into registry structures.
Look like my suggestion from adobe system boards / forum was better than access problem with writing stream with file :)
I hope you because you know my nice trick with nativeprocess via powershell + regedit /s \AirApp.reg
and AirApp changes into administratived AirApp than it works fine with Administratived mode :)
Than your solution should write and you try - Make sure for your writing process by AirApp.
this function gives your current air application folder which bypasses the security problem:
function SWFName(): String {
var swfName: String;
var mySWF = new File(this.loaderInfo.url).nativePath;
swfName= this.loaderInfo.loaderURL;
swfName = swfName.slice(swfName.lastIndexOf("/") + 1); // Extract the filename from the url
swfName = new URLVariables("path=" + swfName).path; // this is a hack to decode URL-encoded values
mySWF = mySWF.replace(swfName, "");
return mySWF;
}