IsolatedStorageFile giving exception - windows

In windows phone 7, I am trying to write to a file and then trying to read from a file, but while reading it is giving the exception below.
public static void writeToFile(String videoUrl)
{
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
store.CreateDirectory("MyFolder");
IsolatedStorageFileStream stream = new IsolatedStorageFileStream("MyFolder\\data.txt", FileMode.Append,
FileAccess.Write, store);
StreamWriter writer = new StreamWriter(stream);
writer.WriteLine(videoUrl);
}
public static void readFromFile()
{
try
{
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream stream = new IsolatedStorageFileStream("MyFolder\\data.txt", FileMode.Open,
store);
StreamReader reader = new StreamReader(stream);
string line;
while ((line = reader.ReadLine()) != null)
{
Debug.WriteLine("kkkkkk-----------------" + line); // Write to console.
}
}
catch (Exception ex)
{
Debug.WriteLine("ESPNGoalsUtil::readFromFile : " + ex.ToString());
}
}
Exception:
System.IO.IsolatedStorage.IsolatedStorageException: Operation not permitted on IsolatedStorageFileStream.
at System.IO.IsolatedStorage.IsolatedStorageFileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, IsolatedStorageFile isf)
at System.IO.IsolatedStorage.IsolatedStorageFileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, IsolatedStorageFile isf)
at System.IO.IsolatedStorage.IsolatedStorageFileStream..ctor(String path, FileMode mode, IsolatedStorageFile isf)
at ESPNGoals.Utility.ESPNGoalsUtil.readFromFile()
I am writing the file and then reading the file in the same method and not closing the emulator.

You need to call Close on the StreamWriter before writeToFile returns (or better still wrap the code in a using block).
The same applies to StreamReader in readFromFile.

Related

Writing to a file in S3 from jar on EMR on AWS

Is there any way in which I can write to a file from my Java jar to an S3 folder where my reduce files would be written ? I have tried something like:
FileSystem fs = FileSystem.get(conf);
FSDataOutputStream FS = fs.create(new Path("S3 folder output path"+"//Result.txt"));
PrintWriter writer = new PrintWriter(FS);
writer.write(averageDelay.toString());
writer.close();
FS.close();
Here Result.txt is the new file which I would want to write.
Answering my own question:-
I found my mistake.I should be passing the URI of S3 folder path to the fileSystem Object like below:-
FileSystem fileSystem = FileSystem.get(URI.create(otherArgs[1]),conf);
FSDataOutputStream fsDataOutputStream = fileSystem.create(new Path(otherArgs[1]+"//Result.txt"));
PrintWriter writer = new PrintWriter(fsDataOutputStream);
writer.write("\n Average Delay:"+averageDelay);
writer.close();
fsDataOutputStream.close();
FileSystem fileSystem = FileSystem.get(URI.create(otherArgs[1]),new JobConf(<Your_Class_Name_here>.class));
FSDataOutputStream fsDataOutputStream = fileSystem.create(new
Path(otherArgs[1]+"//Result.txt"));
PrintWriter writer = new PrintWriter(fsDataOutputStream);
writer.write("\n Average Delay:"+averageDelay);
writer.close();
fsDataOutputStream.close();
This is how I handled the conf variable in the above code block and it worked like charm.
Here's another way to do it in Java by using the AWS S3 putObject directly with a string buffer.
... AmazonS3 s3Client;
public void reduce(Text key, java.lang.Iterable<Text> values, Reducer<Text, Text, Text, Text>.Context context) throws Exception {
UUID fileUUID = UUID.randomUUID();
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String fileName = String.format("nightly-dump/%s/%s-%s",sdf.format(new Date()), key, fileUUID);
log.info("Filename = [{}]", fileName);
String content = "";
int count = 0;
for (Text value : values) {
count++;
String s3Line = value.toString();
content += s3Line + "\n";
}
log.info("Count = {}, S3Lines = \n{}", count, content);
PutObjectResult putObjectResult = s3Client.putObject(S3_BUCKETNAME, fileName, content);
log.info("Put versionId = {}", putObjectResult.getVersionId());
reduceWriteContext("1", "1");
context.setStatus("COMPLETED");
}

Definition of resource ID not found when trying to write to IsolatedStorageFile

I'm trying to write a string to an IsolatedStorageFile, but I'm getting an IsolatedStorageException, the link in the exception is this one:
http://www.microsoft.com/getsilverlight/DllResourceIDs/Default.aspx?Version=4.0.50829.0&File=mscorlib.dll&Key=IsolatedStorage_Operation_ISFS
And it states that the definition of 'resource ID' could not be found. I have no idea why this exception occurs, here's my code:
private void writeListToStorage(List<PlanningItemModel> items)
{
IsolatedStorageFile myIsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication();
if(myIsolatedStorageFile.FileExists("Zomerparkfeesten\\" + filePath))
{
IsolatedStorageFileStream iStream = myIsolatedStorageFile.OpenFile("Zomerparkfeesten\\" + filePath, FileMode.Open, FileAccess.Write);
string json = Converter.convertListOfItemsToJson(items);
StreamWriter writeFile = new StreamWriter(iStream);
try
{
writeFile.WriteLine(json);
writeFile.Close();
iStream.Close();
}
catch (IOException)
{
writeFile.Close();
iStream.Close();
}
}
else
{
myIsolatedStorageFile.CreateFile("Zomerparkfeesten\\" + filePath);
this.writeListToStorage(items);
}
}
Any ideas?
And it states that the definition of 'resource ID' could not be found
No, that's not what it says. Odd problem, might have something to do with you speaking Dutch instead of English. Looks like they fumbled the Dutch localization of this particular exception. When I visit that URL from the USA, I get:
Operation not permitted on IsolatedStorageFileStream
Which of course makes a lot more sense, given the code snippet. I can't get you a lot more help beyond that, basic issue is that your program doesn't have write access to isolated storage. You'll need to give it access.
One nasty failure mode that's hard to diagnose, this code will always blow up with "Operation not permitted" when you pass an empty string for "filePath". That will make the code try to write a file that has the same name as an existing directory, that's never permitted.
Try to use this code:
using (IsolatedStorageFile myIsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!myIsolatedStorageFile.DirectoryExists("Zomerparkfeesten"))
{
myIsolatedStorageFile.CreateDirectory("Zomerparkfeesten");
myIsolatedStorageFile.CreateFile("Zomerparkfeesten//" + filePath);
}
else
{
if (!myIsolatedStorageFile.FileExists("Zomerparkfeesten//" + filePath))
{
myIsolatedStorageFile.CreateFile("Zomerparkfeesten//" + filePath);
}
}
using (Stream stream = new IsolatedStorageFileStream("Zomerparkfeesten//" + filePath, FileMode.Append, FileAccess.Write, myIsolatedStorageFile))
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.WriteLine("Test");// some your data
writer.Close();
stream.Close();
}
}
}

storing a project folder in isolated storage

I am creating a windows phone project with static html files in a folder called "webapplication". i want to store all contents of "webapplication" folder in the isolated storage. Can some one help to resolve this?
Check out windows phone geek at http://windowsphonegeek.com/tips/all-about-wp7-isolated-storage-files-and-folders for information on Isolated Storage.
To create a folder do the following:
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
myIsolatedStorage.CreateDirectory("NewFolder");
If you want to create a file inside the folder then:
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("NewFolder\\SomeFile.txt", FileMode.CreateNew, myIsolatedStorage));
If you are looking to copy the files to IsolatedStorage, then you need to run the following code the 1st time your application executes:
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
string[] files = System.IO.Directory.GetFiles(folderPath);
foreach (var _fileName in files)
{
if (!storage.FileExists(_fileName))
{
string _filePath = _fileName;
StreamResourceInfo resource = Application.GetResourceStream(new Uri(_filePath, UriKind.Relative));
using (IsolatedStorageFileStream file = storage.CreateFile("NewFolder\\SomeFile.txt", FileMode.CreateNew, Storage))
{
int chunkSize = 102400;
byte[] bytes = new byte[chunkSize];
int byteCount;
while ((byteCount = resource.Stream.Read(bytes, 0, chunkSize)) > 0)
{
file.Write(bytes, 0, byteCount);
}
}
}
}
}

EPPLUS - Unable to save in different folder

I'm trying to save the excel file. It working fine if i save the file in same location but if i wanted to save different location it throwm me error.
Error:
System.NotSupportedException was unhandled
Message=The given path's format is not supported.
Source=mscorlib
StackTrace:
at System.Security.Util.StringExpressionSet.CanonicalizePath(String path, Boolean needFullPath)
at System.Security.Util.StringExpressionSet.CreateListFromExpressions(String[] str, Boolean needFullPath)
at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList)
at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, AccessControlActions control, String[] pathList, Boolean checkForDuplicates, Boolean needFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.File.Create(String path)
at Report.Form1.ExportToExcelReport(DataTable Tbl, String ExcelFilePath) in C:\SMARTAG_PROJECT\SUREREACH\EXCEL\Report\Report\Form1.cs:line 142
at Report.Form1.button2_Click(Object sender, EventArgs e) in C:\SMARTAG_PROJECT\SUREREACH\EXCEL\Report\Report\Form1.cs:line 113
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at Report.Program.Main() in C:\SMARTAG_PROJECT\SUREREACH\EXCEL\Report\Report\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
My Code
FileInfo newFile = new FileInfo("C:\\Excel\\SampleStockTakeReport.xlsx");
ExcelPackage pck = new ExcelPackage(newFile);
ExcelWorksheet ws = pck.Workbook.Worksheets[1];
var path = "C:\\Excel\\Report\\SampleStockTakeExceptionReport" + DateTime.Now + ".xlsx";
ws.View.ShowGridLines = false;
ws.Cells["G13"].Value = "Rent";
ws.Cells["G14"].Value = "Level 1";
ws.Cells["G15"].Value = "Cell 1";
ws.Cells["V14"].Value = "Level 3";
ws.Cells["V15"].Value = "Cell 3";
ws.Cells["W12"].Value = "Bukit Raja";
ws.Cells["AJ13"].Value = "Row 1";
var tracksql = new TrackingSql();
var numberoftag = tracksql.getNumberofTag();
ws.Cells["S19"].Value = DateTime.Now;
ws.Cells["Y19"].Value = numberoftag.ToString();
var numberoftagscanned = 9;
var diff = numberoftag - numberoftagscanned;
ws.Cells["Q22"].Value = numberoftagscanned;
ws.Cells["X22"].Value = numberoftag;
ws.Cells["AD22"].Value = diff;
var thispath = "testing path for report";
Stream stream = File.Create(path); // throw error here
pck.SaveAs(stream);
System.Diagnostics.Process.Start(path);
MessageBox.Show("Report Generated at " + path + "");
Appreciated if anyone could advice/help on this.
This issue is not related to EPPlus. You get the NotSupportedException at
Stream stream = File.Create(path);
which is documented here: File.Create Method (String)
So this "path is in an invalid format." because of the colons in the time-part of DateTime.Now:
var path = "C:\\Excel\\Report\\SampleStockTakeExceptionReport" + DateTime.Now + ".xlsx";
So this should work:
var dayPart = DateTime.Now.ToString("yyyy-MM-dd");
var path = "C:\\Excel\\Report\\SampleStockTakeExceptionReport" + dayPart + ".xlsx";
If you need the time part, you could create a custom DateTimeFormatInfo:
var timeFormat = (DateTimeFormatInfo)CultureInfo.CurrentCulture.DateTimeFormat.Clone();
timeFormat.TimeSeparator = "_";
var dayPart = DateTime.Now.ToString(timeFormat); // replaces the colons with _ implicitely
You need to format DateTime.Now to something like DateTime.Now.ToString("MMddyyyy");

Phone7, another IsolatedStorageFile problem

I want to save text from a textbox to the internalStorage and load it from there...
The saving-part works fine. But the loading won't work I tried many tutorials already.
private void button2_Click(object sender, RoutedEventArgs e)
{
//get selected FileName from listBox
string selItem = listBox1.SelectedItem.ToString();
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
if (selItem != null)
{
IsolatedStorageFileStream fileStream = store.OpenFile(selItem, FileMode.Open, FileAccess.Read);
using (StreamReader sr = new StreamReader(fileStream))
{
String line = "";
//Debug.WriteLine("ReadLine");
if ((line = sr.ReadLine()) != null)
{
//Debug.WriteLine("ReadLineText");
textBox1.Text = line;
}
sr.Close();
}
fileStream.Close();
}
}
Instead of:
if ((line = sr.ReadLine()) != null)
{
//Debug.WriteLine("ReadLineText");
textBox1.Text = line;
I've tried many possibilities like: textBox1.Text = sr.ReadLine(); and so on..
The curious thing about he code is: If I enter for example:
IsolatedStorageFileStream fileStream = store.OpenFile("text0.txt", FileMode.Open, FileAccess.Read);
It works fine for the single file text0.txt.
Would be really really great if someone give me some tips to fix the code.
Thanks in advance..
this is how I open an ISF Stream
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filename, FileMode.OpenOrCreate, isf); // loads from isolated storage
FYI: don't try to test without phone if you want to work with the isolated storage.
this finally works for me:
private void button2_Click(object sender, RoutedEventArgs e)
{
//get fileName
string filename = listBox1.SelectedItem.ToString();
try
{
IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filename, FileMode.OpenOrCreate, store); // loads from isolated storage
//Debug.WriteLine(stream.CanRead);
StreamReader sr = new StreamReader(stream);
String lines = sr.ReadToEnd().ToString();
if (lines != null)
{
textBox1.Text = lines;
}
stream.Close();
sr.Close();
}
catch (Exception)
{
throw;
}
}
}
Maybe you see I killed the using(..) and put in a little check on "Null". I think the main cause was that there was no phone present to test the code.
Thank you very much indeed :-)))

Resources