Can't read files from BlobStore - google-app-engine

I have been trying to write and read files directly from the BlobStore, but it just doesnt work.
The issue is I open the file like file = fileService.getBlobFile(blobKey); and it doesn't throw any exception but right in the next line I call readChannel = fileService.openReadChannel(file, false); and that one throws a FileNotFoundException.
I'm confused as to why the first line did not throw the exception.
Here is the same issue
Unfortunately no one answered that question.

I haven't had any problems with writes or deletes, but I too get a FileNotFoundException when using openReadChannel(...) with an AppEngineFile.
I've tried using an AppEngineFile created from its constructor taking a complete path. I've tried using an AppEngineFile obtained from getBlobFile(...) like you do above. Either way, when the AppEngineFile is passed to openReadChannel(...) a FileNotFoundException is thrown.
My workaround was to let BlobstoreService.serve(...) do all the work of reading and sending the file. I suspect that using the FileService to read from an AppEngineFile isn't supported yet (I'm using 1.6.0), so reads must be done via the BlobstoreService (serve(...), fetchData(...), BlobstoreInputStream).

Related

Visual basic closing a file

I'm using Visual basic 2012, and I'm experimenting with manipulating .txt files. I've managed to make a button to create them, but the button I made to delete them always runs into and error, claiming the file is still in use. I've tried to write code to close the file, but no success. The closest I've gotten was when I tried
FileStream.Close("C:\Testfile")
But I get an error saying that It needs to be linked to an object. I don't have the faintest idea what it mean by object, and I don't have any other ideas
Can someone tell me what I need to do to fix this, or alternatively, another solution
You must make sure that the code you have for creating the file, closes that file as well after the job is done:
Dim sw As StreamWriter = New StreamWriter("C:\Testfile")
' write to the file here, like:
sw.Write("...")
' ...etc, and at the end of the job, close the file:
sw.Close()
To actually delete a file from the file system, use:
File.Delete("C:\Testfile")
I suspect the problem that you are having could be because the file is still open when you are trying to delete it.
Add your file manipulation code inside a Using block as explained in this MSDN article. By using this technique you will not have to remember to close files yourself as it will happen automatically once you have left the Using block.
Dim filePath As String = "hello.txt"
Using openedFile As FileStream = File.Open(filePath, FileMode.OpenOrCreate)
'File is OPEN
Dim bytes() As Byte = Encoding.ASCII.GetBytes("Hello World")
openedFile.Write(bytes, 0, bytes.Length)
End Using
'File is CLOSED and can be deleted
File.Delete(filePath)
You can also use this technique for any other objects that implement IDisposable such as StreamReader and StreamWriter.

First chance FileNotFoundException when calling IsolatedStorageFile.OpenFile

Somewhere in my code, I have this line:
return _store.OpenFile(path, fileMode);
With fileMode being sometimes FileMode.Create and sometimes FileMode.Open.
Everything works well, I always get a valid stream and if necessary, the file is correctly created.
But, I've just discovered in my VS output that I have the following message every time I call the method where the above line is:
A first chance exception of type 'System.IO.FileNotFoundException'
occurred in mscorlib.dll
I get this error when the file is created and I also get this error when the file is overwritten (and obviously exists).
I'm just curious about these errors since everything works perfectly.
Thanks,
EDIT: Same thing with new IsolatedStorageFileStream(...). Everything works fine but I still get the "first chance exception" message.
var isf = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isfs;
if (!isf.FileExists(_filename))
isfs = new IsolatedStorageFileStream(_filename, System.IO.FileMode.Create, isf);
else
isfs = new IsolatedStorageFileStream(_filename, System.IO.FileMode.Open, isf);
var writer = XmlWriter.Create(isfs);
xml.Save(writer);
writer.Close();
isfs.Close();
isfs.Dispose();
isf.Dispose();
Found the answer.
It's just how VS debugger works: for every exception caught by a {{catch}} block, a "first chance exception" message appears in the VS output.
So here, we can guess that, internally, the {{OpenFile}} method uses a try/catch block to check if the file exists.

Download file with JSF

everyone!
I have a trouble. I tried to save excel file in jsf web application.
I generated file by my utils and trying to get "save" window, but I failed.
Here is my code:
<div>
<h:commandButton value="Apply" actionListener="#{hornPhonesBean.generateReport}"/>
</div>
and:
public void generateReport(ActionEvent event) {
System.out.println("GENERATE REPORT FROM = " + this.dateFrom + "; TO = " + this.dateTo);
try {
XSSFWorkbook workbook = (XSSFWorkbook) HornReportGenerator.getWorkbook(null, null);
String fileName = "1.xlsx";
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
// Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
ec.responseReset();
// Check http://www.w3schools.com/media/media_mimeref.asp for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
ec.setResponseContentType("application/vnd.ms-excel");
// Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
//ec.setResponseContentLength(contentLength);
// The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
OutputStream output = ec.getResponseOutputStream();
workbook.write(output);
output.flush();
output.close();
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
System.out.println("END");
} catch (Exception e) {
e.printStackTrace();
}
}
I read suggestions here and from another forums - everyone says I shouldnt use , but I didn't use it at all.
Then I thought that the problem could be in the
<ice:form>,
where I kept the
<h:commandButton>,
and I changed to
<h:form>,
but it didn't help.
Maybe the problem in the request - it has header Faces-Request partial/ajax. But I am not sure.
Please give me some ideas - I already spent 4 hours for this crazy jsf download issue)
Maybe the problem in the request - it has header Faces-Request partial/ajax. But I am not sure.
This suggests that the request is an ajax request. You can't download files by ajax. Ajax requests are processed by JavaScript which has for obvious security reasons no facilities to programmatically pop a Save As dialogue nor to access/manipulate client's disk file system.
Your code snippet does however not show that you're using ajax. Perhaps you oversimplified it too much or you're using ICEfaces which silently auto-enables ajax on all standard JSF command components.
In any case, you need to make sure that it's not sending an ajax request.
See also:
How to provide a file download from a JSF backing bean?
ICEfaces libary in classpath prevents Save As dialog from popping up on file download

IsolatedStorageFileStream exception is throw when file is opened?

when I attempt to open a file in a WP7 app:
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream nameXmlFile = new IsolatedStorageFileStream("Names.xml", System.IO.FileMode.Open, isf);
I recieve the following error:
Operation not permitted on IsolatedStorageFileStream.
I'm not sure why it isn't opening because I used the exact code somewhere else in my app and it works fine.
Any leads as to why this is happening?
EDIT
I used the following code to add the file to isolated storage in the App.xaml.cs Application_Launching Event:
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream feedXmlFile = new IsolatedStorageFileStream("Names.xml",System.IO.FileMode.Create, isf);
One of the problems with using the IsolatedStorageFileStream constructor is that the exception generated has limited info. The alternative OpenFile method has a richer set of exceptions.
As a general rule of thumb if an API allows you to do the same thing with a constructor or with a method go with the method. In this case try this code instead:-
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream nameXmlFile = isf.OpenFile("Names.xml", System.IO.FileMode.Open);
If this fails you will have at least narrowed down the potential cause.
This may seem obvious but in your creation code you have actually written to and closed the file you created?
IsolatedStorage Exception is a known issue whil fires Application_Launching. more details
When you run into an exception during file access, check for two things:
isolated storage is not thread safe, so use a 'lock' when accessing the file system
Isolated storage best practices
Fully read the stream into memory before closing the stream. So don't pass the filestream back to for example an image control.
Reading a bitmap stream from isolated storage

Windows Phone 7 App Quits when I attempt to deserialize JSON

I'm developing my first windows phone 7 app, and I've hit a snag. basically it's just reading a json string of events and binding that to a list (using the list app starting point)
public void Load()
{
// form the URI
UriBuilder uri = new UriBuilder("http://mysite.com/events.json");
WebClient proxy = new WebClient();
proxy.OpenReadCompleted += new OpenReadCompletedEventHandler(OnReadCompleted);
proxy.OpenReadAsync(uri.Uri);
}
void OnReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
var serializer = new DataContractJsonSerializer(typeof(EventList));
var events = (EventList)serializer.ReadObject(e.Result);
foreach (var ev in events)
{
Items.Add(ev);
}
}
}
public ObservableCollection<EventDetails> Items { get; private set; }
EventDetails is my class that wraps the json string. this class has to be correct because it is an exact copy of the class used by that website internally from which the json is generated...
I get the json string correctly from the webclient call (I read the memorystream and the json is indeed there) but as soon as I attempt to deserialize the string, the application exits and the debugger stops.
I get no error message or any indication that anything happen, it just stops. This happens if I type the deserialize method into the watch window as well...
I have already tried using JSON.net in fact I thought maybe it was a problem with JSON.net so I converted it to use the native deserializer in the .net framework but the error is the same either way.
why would the application just quit? shouldn't it give me SOME kind of error message?
what could I be doing wrong?
many thanks!
Firstly, the fact that you have some string there that looks like JSON does not mean that you have a valid JSON. Try converting a simple one.
If your JSON is valid, it might be that your JSON implementation does not know how to convert a list to EventList. Give it a try with ArrayList instead and let me know.
The application closes because an unhandled exception happens. If check the App.xaml.cs file you will find the code that closes your app. What you need to do is try catch your deserialization process and handle it locally. So most likely you have some JSON the DataContractJsonSerializer does not like. I have been having issue with it deserializing WCF JSON and have had to go other routes.
You may want to check to ensure your JSON is valid, just because your website likes it does not mean it is actually valid, the code on your site may be helping to correct the issue. Drop a copy of your JSON object (the string) in http://jsonlint.com/ to see if it is valid or not. Crokford (the guy who created JSON) wrote this site to validate JSON, so I would rely on it more than your site ;) This little site has really helped me out of some issues over the past year.
I ran into this same kind of problem when trying to migrate some existing WM code to run on WP7. I believe that the WP7 app crashes whenever it loads an assembly (or class?) that references something that's not available in WP7. In my case, I think it was Assembly.Load or something in the System.IO namespace, related to file access via paths.
While your case might be something completely different, the symptoms were exactly the same.
The only thing I can recommend is to go through the JSON library and see if it's referencing base classes that are not allowed in WP7. Note that it doesn't even have to hit the line of code that's causing the issue - it'll crash as soon as it tries to hit the class that contains the bad reference.
If you can step into the JSON library, you can get a better idea of which class is causing the problem, because as soon as the code references it, the whole app will crash and the debugger will stop.

Resources