Silverlight 5 operation is not allowed on isolated storage - silverlight

I create a file in isolated storage and then the same file is accessed and be edited on the click of button. But sometime an Exception occured with detail that operation is not allowed on isolated storage. This exception has no fixed time sometimes occured on first click of button some times it occuered after 5th or 6th click etc. ISOFileProcess(String module, String operation, String xmlObj) function in the below code is called on click of button.
public static void ISOFileProcess(String module, String operation, String xmlObj)
{
var store = IsolatedStorageFile.GetUserStoreForApplication();
if (store.FileExists(IsolatedMemFileHandlingCon.fileName) == false)
{
StreamWriter sw = new StreamWriter(store.OpenFile(IsolatedMemFileHandlingCon.fileName, FileMode.OpenOrCreate));
CreateXML(sw,module,operation,xmlObj);
sw.Close();
MessageBox.Show("File Created.");
}
else
{
//store.OpenFile(IsolatedMemFileHandlingCon.fileName, FileMode.Append);
IsolatedStorageFileStream isoStream =
new IsolatedStorageFileStream(IsolatedMemFileHandlingCon.fileName, FileMode.Append, FileAccess.ReadWrite, store);
EditXML(isoStream, module, operation, xmlObj);
isoStream.Close();
}
}
#endregion
#region XML Creation And Editing
private static void CreateXML(StreamWriter sw, String mname, String operation, String xmlObj)
{
XmlWriter xWrt = XmlWriter.Create(sw);
xWrt.WriteStartElement("ocs");
// xWrt.WriteStartElement("module");
xWrt.WriteStartElement("operation");
xWrt.WriteAttributeString("mode", operation);
xWrt.WriteAttributeString("mname", mname);
xWrt.WriteRaw(xmlObj);
xWrt.WriteEndElement();
//xWrt.WriteEndElement();
xWrt.WriteEndElement();
xWrt.Close();
}
private static void EditXML(IsolatedStorageFileStream sw, String mname, String operation, String xmlObj)
{
sw.Seek(sw.Length - 6, SeekOrigin.Begin);
XmlWriterSettings wrSettings = new XmlWriterSettings();
wrSettings.OmitXmlDeclaration = true;
XmlWriter xWrt = XmlWriter.Create(sw,wrSettings);
//xWrt.WriteStartElement("module");
xWrt.WriteStartElement("operation");
xWrt.WriteAttributeString("mode", operation);
xWrt.WriteAttributeString("mname", mname);
xWrt.WriteRaw(xmlObj);
xWrt.WriteEndElement();
//xWrt.WriteEndElement();
xWrt.WriteRaw("</ocs>");
xWrt.Close();
}

You specify FileMode.Append here:
IsolatedStorageFileStream isoStream =
new IsolatedStorageFileStream(
IsolatedMemFileHandlingCon.fileName,
FileMode.Append,
FileAccess.ReadWrite, store);
Append does not combine with FileAccess.ReadWrite and with moving the cursor before the end of the file.
In the code you use random access, moving the cursor back:
sw.Seek(sw.Length - 6, SeekOrigin.Begin);
From the MSDN:
Append Opens the file if it exists and seeks to the end of the file,
or creates a new file. FileMode.Append can only be used in conjunction
with FileAccess.Write. Attempting to seek to a position before the end
of the file will throw an IOException and any attempt to read fails
and throws an NotSupportedException.

Related

C# Image via Memorystream error (but only second time through)

I need to be able to convert an Image to a byte Array and then back again. I've followed the google results and it seemed to be working..except it doesn't :)
I am pretty sure it has something to do with the Memory stream (I'm getting that GDI+ error) but I'm using the "using" and I thought I was cleanup up after myself.
private void button1_Click(object sender, EventArgs e)
{
System.Drawing.Image myImage = null;
SetImage(ref myImage); //This one works
SetImage(ref myImage); // This call breaks on
//the first myImage.Save line
}
private void SetImage(ref System.Drawing.Image myImage)
{
try
{
byte[] myImageAsBytes = null;
//First time through we don't have an image already so we load from a file
if (myImage == null)
{
myImage = System.Drawing.Image.FromFile("C:\\temp\\test.jpg");
}
//Convert our Image to a Byte Array.
using (System.IO.MemoryStream myMemoryStream = new System.IO.MemoryStream())
{
myImage.Save(myMemoryStream, myImage.RawFormat);
myImageAsBytes = myMemoryStream.ToArray();
}
//Just debugging
myImage.Dispose();
myImage = null;
GC.Collect();
//And convert it back to an image.
//using (System.IO.MemoryStream myMemoryStream = new System.IO.MemoryStream(myImageAsBytes))
//{
// myImage = System.Drawing.Image.FromStream(myMemoryStream);
//}
System.IO.MemoryStream myMemoryStream2 = new System.IO.MemoryStream(myImageAsBytes);
myImage = System.Drawing.Image.FromStream(myMemoryStream2);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The documentation for Image.FromStream: https://msdn.microsoft.com/en-us/library/93z9ee4x(v=vs.110).aspx
Says:
You must keep the stream open for the lifetime of the Image.
When it comes to MemoryStreams there is actually no point in closing/disposing them. It's the only .NET class I can think of that is IDisposable that doesn't need disposing. It accidentally inherits IDisposable from System.IO.Stream, that's why.
So I would recommend that you just create your memory streams and let them be.
If you were to use Image.FromStream on a physical file, however, maybe you wont like to keep it open. What you could do in that case is to make a copy of the bitmap like this:
Bitmap safeBitmap;
using ( var stream = blah-blah-blah )
using ( var img = Image.FromStream(stream) )
safeBitmap = new Bitmap(img);
I know delphi but not C++. I think you have set myimage to null if myimage is an object, so tried to re-create. Or don't set it to null, just redraw on it or myimage.loadfromstream.
System.Drawing.Image myImage = null;
SetImage(ref myImage); //This one works
myimage :=create;
SetImage(ref myImage);
Its as simple as removing "ref" from everywhere
I suggest you read up what that key word is doing, you will then understand why its breaking it.
rather return the new image from the method.
i.e. change it from void to return the new image.
Update
below is a console version of your code basically unmodified at ALL
and it runs fine.... although i don't agree with the programming at ALL either.
Point is where are you getting an error if it seems to run with no errors
class Program
{
static void Main(string[] args)
{
Dosomething();
}
private static void Dosomething()
{
System.Drawing.Image myImage = null;
SetImage(ref myImage); //This one works
SetImage(ref myImage); // This call breaks on
}
private static void SetImage(ref System.Drawing.Image myImage)
{
try
{
byte[] myImageAsBytes = null;
//First time through we don't have an image already so we load from a file
if (myImage == null)
{
myImage = System.Drawing.Image.FromFile("C:\\temp\\test.jpg");
}
//Convert our Image to a Byte Array.
using (System.IO.MemoryStream myMemoryStream = new System.IO.MemoryStream())
{
myImage.Save(myMemoryStream, myImage.RawFormat);
myImageAsBytes = myMemoryStream.ToArray();
}
//Just debugging
myImage.Dispose();
myImage = null;
GC.Collect();
//And convert it back to an image.
//using (System.IO.MemoryStream myMemoryStream = new System.IO.MemoryStream(myImageAsBytes))
//{
// myImage = System.Drawing.Image.FromStream(myMemoryStream);
//}
System.IO.MemoryStream myMemoryStream2 = new System.IO.MemoryStream(myImageAsBytes);
myImage = System.Drawing.Image.FromStream(myMemoryStream2);
}
catch (Exception ex)
{
}
}
}

Hadoop Map Reduce - Read HDFS File - FileAlreadyExists error

I am new to Hadoop. I am trying to read an existing file on HDFS using the below code. The configuration seem file and the file path is correct as well. -
public static class Map extends Mapper<LongWritable, Text, Text, Text> {
private static Text f1, f2, hdfsfilepath;
private static HashMap<String, ArrayList<String>> friendsData = new HashMap<>();
public void setup(Context context) throws IOException {
Configuration conf = context.getConfiguration();
Path path = new Path("hdfs://cshadoop1" + conf.get("hdfsfilepath"));
FileSystem fs = FileSystem.get(path.toUri(), conf);
if (fs.exists(path)) {
BufferedReader br = new BufferedReader(
new InputStreamReader(fs.open(path)));
String line;
line = br.readLine();
while (line != null) {
StringTokenizer str = new StringTokenizer(line, ",");
String friend = str.nextToken();
ArrayList<String> friendDetails = new ArrayList<>();
while (str.hasMoreTokens()) {
friendDetails.add(str.nextToken());
}
friendsData.put(friend, friendDetails);
}
}
}
public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
for (String k : friendsData.keySet()) {
context.write(new Text(k), new Text(friendsData.get(k).toString()));
}
}
}
I am getting the below exception when I run the code -
Exception in thread "main" org.apache.hadoop.mapred.FileAlreadyExistsException: Output directory hdfs://cshadoop1/socNetData/userdata/userdata.txt already exists
at org.apache.hadoop.mapreduce.lib.output.FileOutputFormat.checkOutputSpecs(FileOutputFormat.java:146)
at org.apache.hadoop.mapreduce.JobSubmitter.checkSpecs(JobSubmitter.java:458)
at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:343)
I am just trying to read an existing file. Any ideas what I am missing here? Appreciate any help.
Exception tells you that your output directory already exists but it should not. Delete it or change its name.
Moreover the name of your output directory 'userdata.txt' looks like the name of a file. So check you are not mistaken in your input/output directories.

How to read objects of arrays from a .txt file?

First what i have done is write an ArrayList as ann object to a .txt file, what I am trying to do is read back those objects into an array and display the array(reverse of first step). The arraylist i'm passing to the funnctions are salesman and technicians that extend employees with parameters name,number,target,terriorty etc. I get this error when i try to compile it.
Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to Employee
at FileIO.readObject(FileIO.java:165)
at UseCompany.main(UseCompany.java:61)
Trying to read back objects from text file
ArrayList<Employee> use_company_arraylist2 = FileIO.("C:\\Users\\Saad\\Documents\\writeObjectMethod.txt"");
use_company_arraylist2 = FileIO.readObject("C:\\Users\\Saad\\Documents\\writeObjectMethod.txt");
The writing object to text file code:
public static void writeObject(ArrayList<Employee> array_of_employee, String filename)
{
try{
//create file stream and write array to file using stream using objectoutput stream
FileOutputStream fle = new FileOutputStream("c:\\Users\\Saad\\Documents\\writeObjectMethod.txt");
ObjectOutputStream oos = new ObjectOutputStream(fle);
oos.writeObject(array_of_employee);
oos.close();
fle.close();
}
catch(FileNotFoundException filenotfound)
{
System.out.println("FILE NOTE FOUND");
}
catch(IOException ioerror)
{
System.out.println("input or output error");
}
}//end writeObject
The reading object from text file code:
public static ArrayList<Employee> readObject (String filename)
{
ArrayList<Employee> newArrayList = new ArrayList<Employee>();
try
{
FileInputStream readfle = new FileInputStream(filename);
ObjectInputStream readobjectfile = new ObjectInputStream(new BufferedInputStream(readfle));
newArrayList.add((Employee)readobjectfile.readObject());
}
catch(ClassNotFoundException clasnfd)
{
System.out.println("class error?");
}
catch(IOException ioerror)
{
System.out.println("input or output error");
}
return newArrayList;
}//end readObject
An object of type Arraylist can't be casted to an object of Employee class.
This will work
ArrayList list = new ArrayList();
list.add(new Employee());
// for writing arraylist object to file
new ObjectOutputStream(new FileOutputStream(new File("a.txt"))).writeObject(list);
// for reading array list from file
ArrayList<Employee> anotherList = (ArrayList<Employee>) new ObjectInputStream(new FileInputStream(new File("a.txt"))).readObject();
System.out.println(anotherList.size());

Download a file through the WebBrowser control

I have a WebBrowser control on a form, but for the most part it remains hidden from the user. It is there to handle a series of login and other tasks. I have to use this control because there is a ton of Javascript that handles the login. (i.e., I can't just switch to a WebClient object.)
After hopping around a bit, we end up wanting to download a PDF file. But instead of downloading, the file is displayed within the webBrowser control, which the user can not see.
How can I download the PDF instead of having it load in the browser control?
Add a SaveFileDialog control to your form, then add the following code on your WebBrowser's Navigating event:
private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
if (e.Url.Segments[e.Url.Segments.Length - 1].EndsWith(".pdf"))
{
e.Cancel = true;
string filepath = null;
saveFileDialog1.FileName = e.Url.Segments[e.Url.Segments.Length - 1];
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
filepath = saveFileDialog1.FileName;
WebClient client = new WebClient();
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
client.DownloadFileAsync(e.Url, filepath);
}
}
}
//Callback function
void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("File downloaded");
}
Source: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/d338a2c8-96df-4cb0-b8be-c5fbdd7c9202
The solution I ended up using:
I did everything else as-needed to get the URL where it needed to go. Knowing that all of the login information, required settings, viewstates, etc. were stored in the cookies, I was finally able to grab the file using a hybrid of the web control to navigate then the WebClient object to actually snag the file bytes.
public byte[] GetPDF(string keyValue)
{
DoLogin();
// Ask the source to generate the PDF. The PDF doesn't
// exist on the server until you have visited this page
// at least ONCE. The PDF exists for five minutes after
// the visit, so you have to snag it pretty quick.
LoadUrl(string.Format(
"https://www.theMagicSource.com/getimage.do?&key={0}&imageoutputformat=PDF",
keyValue));
// Now that we're logged in (not shown here), and
// (hopefully) at the right location, snag the cookies.
// We can use them to download the PDF directly.
string cookies = GetCookies();
byte[] fileBytes = null;
try
{
// We are fully logged in, and by now, the PDF should
// be generated. GO GET IT!
WebClient wc = new WebClient();
wc.Headers.Add("Cookie: " + cookies);
string tmpFile = Path.GetTempFileName();
wc.DownloadFile(string.Format(
"https://www.theMagicSource.com/document?id={0}_final.PDF",
keyValue), tmpFile);
fileBytes = File.ReadAllBytes(tmpFile);
File.Delete(tmpFile);
}
catch (Exception ex)
{
// If we can't get the PDF here, then just ignore the error and return null.
throw new WebScrapePDFException(
"Could not find the specified file.", ex);
}
return fileBytes;
}
private void LoadUrl(string url)
{
InternalBrowser.Navigate(url);
// Let the browser control do what it needs to do to start
// processing the page.
Thread.Sleep(100);
// If EITHER we can't continue OR
// the web browser has not been idle for 10 consecutive seconds yet,
// then wait some more.
// ...
// ... Some stuff here to make sure the page is fully loaded and ready.
// ... Removed to reduce complexity, but you get the idea.
// ...
}
private string GetCookies()
{
if (InternalBrowser.InvokeRequired)
{
return (string)InternalBrowser.Invoke(new Func<string>(() => GetCookies()));
}
else
{
return InternalBrowser.Document.Cookie;
}
}
bool documentCompleted = false;
string getInnerText(string url)
{
documentCompleted = false;
web.Navigate(url);
while (!documentCompleted)
Application.DoEvents();
return web.Document.Body.InnerText;
}
private void web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
documentCompleted = true;
}

Get stream from java.sql.Blob in Hibernate

I'm trying to use hibernate #Entity with java.sql.Blob to store some binary data. Storing doesn't throw any exceptions (however, I'm not sure if it really stores the bytes), but reading does. Here is my test:
#Test
public void shouldStoreBlob() {
InputStream readFile = getClass().getResourceAsStream("myfile");
Blob blob = dao.createBlob(readFile, readFile.available());
Ent ent = new Ent();
ent.setBlob(blob);
em.persist(ent);
long id = ent.getId();
Ent fromDb = em.find(Ent.class, id);
//Exception is thrown from getBinaryStream()
byte[] fromDbBytes = IOUtils.toByteArray(fromDb.getBlob().getBinaryStream());
}
So it throws an exception:
java.sql.SQLException: could not reset reader
at org.hibernate.engine.jdbc.BlobProxy.getStream(BlobProxy.java:86)
at org.hibernate.engine.jdbc.BlobProxy.invoke(BlobProxy.java:108)
at $Proxy81.getBinaryStream(Unknown Source)
...
Why? Shouldn't it read bytes form DB here? And what can I do for it to work?
Try to refresh entity:
em.refresh(fromDb);
Stream will be reopened. I suspect that find(...) is closing the blob stream.
It is not at all clear how you are using JPA here, but certainly you do not need to deal with Blob data type directly if you are using JPA.
You just need to declare a field in the entity in question of #Lob somewhat like this:
#Lob
#Basic(fetch = LAZY)
#Column(name = "image")
private byte[] image;
Then, when you retrieve your entity, the bytes will be read back again in the field and you will be able to put them in a stream and do whatever you want with them.
Of course you will need a getter and setter methods in your entity to do the byte conversion. In the example above it would be somewhat like:
private Image getImage() {
Image result = null;
if (this.image != null && this.image.length > 0) {
result = new ImageIcon(this.image).getImage();
}
return result;
}
And the setter somewhat like this
private void setImage(Image source) {
BufferedImage buffered = new BufferedImage(source.getWidth(null), source.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffered.createGraphics();
g.drawImage(source, 0, 0, null);
g.dispose();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
ImageIO.write(buffered, "JPEG", stream);
this.image = stream.toByteArray();
}
catch (IOException e) {
assert (false); // should never happen
}
}
}
You need to set a breakpoint on method org.hibernate.engine.jdbc.BlobProxy#getStream on line stream.reset() and examine a reason of IOException:
private InputStream getStream() throws SQLException {
try {
if (needsReset) {
stream.reset(); // <---- Set breakpoint here
}
}
catch ( IOException ioe) {
throw new SQLException("could not reset reader");
}
needsReset = true;
return stream;
}
In my case the reason of IOException was in usage of org.apache.commons.io.input.AutoCloseInputStream as a source for Blob:
InputStream content = new AutoCloseInputStream(stream);
...
Ent ent = new Ent();
...
Blob blob = Hibernate.getLobCreator(getSession()).createBlob(content, file.getFileSize())
ent.setBlob(blob);
em.persist(ent);
While flushing a Session hibernate closes Inpustream content (or rather org.postgresql.jdbc2.AbstractJdbc2Statement#setBlob closes Inpustream in my case). And when AutoCloseInputStream is closed - it rases an IOException in method reset()
update
In your case you use a FileInputStream - this stream also throws an exception on reset method.
There is a problem in test case. You create blob and read it from database inside one transaction. When you create Ent, Postgres jdbc driver closes InputStream while flushing a session. When you load Ent (em.find(Ent.class, id)) - you get the same BlobProxy object, that stores already closed InputStream.
Try this:
TransactionTemplate tt;
#Test
public void shouldStoreBlob() {
final long id = tt.execute(new TransactionCallback<long>()
{
#Override
public long doInTransaction(TransactionStatus status)
{
try
{
InputStream readFile = getClass().getResourceAsStream("myfile");
Blob blob = dao.createBlob(readFile, readFile.available());
Ent ent = new Ent();
ent.setBlob(blob);
em.persist(ent);
return ent.getId();
}
catch (Exception e)
{
return 0;
}
}
});
byte[] fromStorage = tt.execute(new TransactionCallback<byte[]>()
{
#Override
public byte[] doInTransaction(TransactionStatus status)
{
Ent fromDb = em.find(Ent.class, id);
try
{
return IOUtils.toByteArray(fromDb.getBlob().getBinaryStream());
}
catch (IOException e)
{
return new byte[] {};
}
}
});
}
My current and only solution is closing the write session and opening new Hibernate session to get back the streamed data. It works. However I do not know what is the difference. I called inputStream.close(), but that was not enough.
Another way:
I tried to call free() method of blob after session.save(attachment) call too, but it throws another exception:
Exception in thread "main" java.lang.AbstractMethodError: org.hibernate.lob.SerializableBlob.free()V
at my.hibernatetest.HibernateTestBLOB.storeStreamInDatabase(HibernateTestBLOB.java:142)
at my.hibernatetest.HibernateTestBLOB.main(HibernateTestBLOB.java:60)
I am using PostgreSQL 8.4 + postgresql-8.4-702.jdbc4.jar, Hibernate 3.3.1.GA
Is the method IOUtils.toByteArray closing the input stream?

Resources