using (EntityDataContext amdb = new EntityDataContext(StrConnectionString))
{
if (amdb.DatabaseExists())
{
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoStore.FileExists(databaseName))
{
copyDatabase = true;
}
else
{
using (IsolatedStorageFileStream databaseStream = isoStore.OpenFile(databaseName, FileMode.Open, FileAccess.Read)) // error here
{
using (Stream db = Application.GetResourceStream(new Uri(databaseName, UriKind.Relative)).Stream)
{
if (databaseStream.Length < db.Length)
copyDatabase = true;
}
}
}
}
}
else
{
//error with the database that has been packaged
}
if (copyDatabase)
new Worker().Copy(databaseName);
}
Check that you precise, in isolated storage access mode parameters, the possibility to write data in there instead of just be able to read.
Did you test with a device?
From what i can tell you're trying to read the database file, while you still have a database connection open. Since the a DataContext locks the database (and thus the file), you're not allowed to read it at the same time.
In order to close the database connection try to close the EntityDataContext object (by calling amdb.Close() or by closing the using statement
Try something like this:
bool shouldCopyDatabase = false;
bool databaseExists = false;
using (EntityDataContext amdb = new EntityDataContext(StrConnectionString))
{
databaseExists = amdb.DatabaseExists();
}
if (databaseExists == true)
{
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoStore.FileExists(databaseName))
{
copyDatabase = true;
}
else
{
using (IsolatedStorageFileStream databaseStream = isoStore.OpenFile(databaseName, FileMode.Open, FileAccess.Read)) // error here
{
using (Stream db = Application.GetResourceStream(new Uri(databaseName, UriKind.Relative)).Stream)
{
if (databaseStream.Length < db.Length)
copyDatabase = true;
}
}
}
}
}
if (copyDatabase)
new Worker().Copy(databaseName);
By moving the isolated storage access functionality outside of the using (EntityDataContext amdb = new EntityDataContext(StrConnectionString)) scope, you allow the database connection to be closed first.
Related
I am trying to fill and combine multiple forms without flattening(need to keep them interactive for users). However I notice a problem. I have PDF files that contain the forms I am trying to fill. The form fields have their fonts set in adobe PDF. I notice after I combine the forms the fields lose their original fonts. Here is my program.
using iText.Forms;
using iText.Kernel.Pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace PdfCombineTest
{
class Program
{
static void Main(string[] args)
{
Stream file1;
Stream file2;
using (var stream = new FileStream("./pdf-form-1.pdf", FileMode.Open, FileAccess.Read))
{
file1 = Program.Fill(stream, new[] { KeyValuePair.Create("Text1", "TESTING"), KeyValuePair.Create("CheckBox1", "Yes") });
}
using (var stream = new FileStream("./pdf-form-2.pdf", FileMode.Open, FileAccess.Read))
{
file2 = Program.Fill(stream, new[] { KeyValuePair.Create("Text2", "text 2 text") });
}
using (Stream output = Program.Combine(new[] { file1, file2 }))
{
using (var fileStream = File.Create("./output.pdf"))
{
output.CopyTo(fileStream);
}
}
}
public static Stream Combine(params Stream[] streams)
{
MemoryStream copyStream = new MemoryStream();
PdfWriter writer = new PdfWriter(copyStream);
writer.SetSmartMode(true);
writer.SetCloseStream(false);
PdfPageFormCopier formCopier = new PdfPageFormCopier();
using (PdfDocument combined = new PdfDocument(writer))
{
combined.InitializeOutlines();
foreach (var stream in streams)
{
using (PdfDocument document = new PdfDocument(new PdfReader(stream)))
{
document.CopyPagesTo(1, document.GetNumberOfPages(), combined, formCopier);
}
}
}
copyStream.Seek(0, SeekOrigin.Begin);
return copyStream;
}
public static Stream Fill(Stream inputStream, IEnumerable<KeyValuePair<string, string>> keyValuePairs)
{
MemoryStream outputStream = new MemoryStream();
PdfWriter writer = new PdfWriter(outputStream);
writer.SetCloseStream(false);
using (PdfDocument document = new PdfDocument(new PdfReader(inputStream), writer))
{
PdfAcroForm acroForm = PdfAcroForm.GetAcroForm(document, true);
acroForm.SetGenerateAppearance(true);
IDictionary<string, iText.Forms.Fields.PdfFormField> fields = acroForm.GetFormFields();
foreach (var kvp in keyValuePairs)
{
fields[kvp.Key].SetValue(kvp.Value);
}
}
outputStream.Seek(0, SeekOrigin.Begin);
return outputStream;
}
}
}
I've noticed after several hours of debugging that PdfPageFormCopier excludes the default resources which contain fonts when merging form fields, is there a way around this? The project I'm working on currently does this process in ItextSharp and it works as intended. However we are looking to migrate to iText7.
Here are links to some sample pdf's I made I can't upload the actual pdf's I'm working with but these display the same problem.
https://www.dropbox.com/s/pukt91d4xe8gmmo/pdf-form-1.pdf?dl=0
https://www.dropbox.com/s/c52x6bc99gnrvo6/pdf-form-2.pdf?dl=0
So my solution was to modify the PdfPageFormCopier class from iText. The main issue is in the function below.
public virtual void Copy(PdfPage fromPage, PdfPage toPage) {
if (documentFrom != fromPage.GetDocument()) {
documentFrom = fromPage.GetDocument();
formFrom = PdfAcroForm.GetAcroForm(documentFrom, false);
}
if (documentTo != toPage.GetDocument()) {
documentTo = toPage.GetDocument();
formTo = PdfAcroForm.GetAcroForm(documentTo, true);
}
if (formFrom == null) {
return;
}
//duplicate AcroForm dictionary
IList<PdfName> excludedKeys = new List<PdfName>();
excludedKeys.Add(PdfName.Fields);
excludedKeys.Add(PdfName.DR);
PdfDictionary dict = formFrom.GetPdfObject().CopyTo(documentTo, excludedKeys, false);
formTo.GetPdfObject().MergeDifferent(dict);
IDictionary<String, PdfFormField> fieldsFrom = formFrom.GetFormFields();
if (fieldsFrom.Count <= 0) {
return;
}
IDictionary<String, PdfFormField> fieldsTo = formTo.GetFormFields();
IList<PdfAnnotation> annots = toPage.GetAnnotations();
foreach (PdfAnnotation annot in annots) {
if (!annot.GetSubtype().Equals(PdfName.Widget)) {
continue;
}
CopyField(toPage, fieldsFrom, fieldsTo, annot);
}
}
Specifically the line here.
excludedKeys.Add(PdfName.DR);
If you walk the the code in the CopyField() function eventually you will end in the PdfFormField class. You can see the constructor below.
public PdfFormField(PdfDictionary pdfObject)
: base(pdfObject) {
EnsureObjectIsAddedToDocument(pdfObject);
SetForbidRelease();
RetrieveStyles();
}
The function RetrieveStyles() will try to set the font for the field based on the default appearance. However that will not work. Due to the function below.
private PdfFont ResolveFontName(String fontName) {
PdfDictionary defaultResources = (PdfDictionary)GetAcroFormObject(PdfName.DR, PdfObject.DICTIONARY);
PdfDictionary defaultFontDic = defaultResources != null ? defaultResources.GetAsDictionary(PdfName.Font) :
null;
if (fontName != null && defaultFontDic != null) {
PdfDictionary daFontDict = defaultFontDic.GetAsDictionary(new PdfName(fontName));
if (daFontDict != null) {
return GetDocument().GetFont(daFontDict);
}
}
return null;
}
You see it is trying to see if the font exists in the default resources which was explicitly excluded in the PdfPageFormCopier class. It will never find the font.
So my solution was to create my own class that implements the IPdfPageExtraCopier interface. I copied the code from the PdfPageFormCopier class and removed the one line excluding the default resources. Then I use my own copier class in my code. Not the prettiest solution but it works.
I will working on the Recording functionality in my windows phone 7 app.
I implemented the Recording functionality through this reference link.
It completely works fine at there and in my case also.
Actually the scenario is, In my application i created first page that will works as the recording screen as same as above referred link.
and when we stop the recording i redirected to the second page and saved that recording in Isolated storage and at the second page i bound the recorded sounds. At here i played the recorded sounds at it works fine.
Now, when i m again go to the recording screen(first page) and starts another recording. it will some times records fine and some times it will skip the some sounds during recording as like beep sounds and it will looks like a extra noise in recording and not getting properly recording sounds.
My Code is like,
public partial class NikhilRecord : PhoneApplicationPage
{
//XNA Objects for Record And Playback
Microphone mphone;
//Used for Storing captured buffers
List<byte[]> memobuffercollection = new List<byte[]>();
//Used for displaying stored memos
ObservableCollection<MemoInfo> memofiles = new ObservableCollection<MemoInfo>();
SpaceTime spaceTime = new SpaceTime();
public NikhilRecord()
{
InitializeComponent();
//Create new Microphone and set event handler.
mphone = Microphone.Default;
mphone.BufferReady += OnMicrophoneBufferReady;
String FileName = PhoneApplicationService.Current.State["MySelectedSong"].ToString();
using (IsolatedStorageFile IsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
try
{
using (IsolatedStorageFileStream fileStream = IsolatedStorage.OpenFile(FileName, FileMode.Open, FileAccess.Read))
{
MyMedia.SetSource(fileStream);
MyMedia.CurrentStateChanged += new RoutedEventHandler(mediaPlayer_CurrentStateChanged);
fileStream.Close();
fileStream.Dispose();
//Start Recording
OnRecordButtonClick();
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
void UpdateRecording(bool isRecording)
{
if (!isRecording)
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
spaceTime.Space = storage.AvailableFreeSpace;
}
}
else
{
spaceTime.Space = memobuffercollection.Count * mphone.GetSampleSizeInBytes(mphone.BufferDuration);
}
spaceTime.Time = mphone.GetSampleDuration((int)Math.Min(spaceTime.Space, Int32.MaxValue));
}
void OnMicrophoneBufferReady(object sender, EventArgs e)
{
// Get buffer from microphone and add to collection
byte[] buffer = new byte[mphone.GetSampleSizeInBytes(mphone.BufferDuration)];
int bytesreturned = mphone.GetData(buffer);
memobuffercollection.Add(buffer);
UpdateRecording(true);
// To be Continue...
if (spaceTime.Time > TimeSpan.FromMinutes(10))
{
StopRecording();
UpdateRecording(false);
}
}
void OnRecordButtonClick()
{
if (mphone.State == MicrophoneState.Stopped)
{
// Clear the collection for storing the buffers
memobuffercollection.Clear();
// Start Recording
mphone.Start();
MyMedia.Play();
}
else
{
MyMedia.Stop();
//mphone.Stop();
PopUpGrid.Visibility = Visibility.Visible;
RecordGrid.Opacity = 0.5;
RecordGrid.IsHitTestVisible = false;
}
bool isRecording = mphone.State == MicrophoneState.Started;
UpdateRecording(isRecording);
}
void StopRecording()
{
// Get the last partial buffer
int sampleSize = mphone.GetSampleSizeInBytes(mphone.BufferDuration);
byte[] extraBuffer = new byte[sampleSize];
int extraBytes = mphone.GetData(extraBuffer);
// Stop Recording
mphone.Stop();
//Stop the Song
MyMedia.Stop();
// Create MemoInfo object and add at top of collection
int totalSize = memobuffercollection.Count * sampleSize + extraBytes;
TimeSpan duration = mphone.GetSampleDuration(totalSize);
MemoInfo memoInfo = new MemoInfo(DateTime.UtcNow, totalSize, duration);
memofiles.Insert(0, memoInfo);
// Save Data in IsolatedStorage
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
string[] alldirectories = storage.GetDirectoryNames("NikDirectory");
if (alldirectories.Count() == 0)
storage.CreateDirectory("NikDirectory");
try
{
using (IsolatedStorageFileStream stream = storage.CreateFile("NikDirectory\\" + memoInfo.FileName))
{
// Write buffers from collection
foreach (byte[] buffer in memobuffercollection)
stream.Write(buffer, 0, buffer.Length);
// Write partial buffer
stream.Write(extraBuffer, 0, extraBytes);
stream.Close();
stream.Dispose();
}
Uri url = new Uri("/Gallery.xaml", UriKind.Relative);
NavigationService.Navigate(url);
memobuffercollection.Clear();
}
catch (Exception ees)
{
MessageBox.Show(ees.Message);
Uri url = new Uri("/Karaoke.xaml", UriKind.Relative);
NavigationService.Navigate(url);
}
}
bool isRecording = mphone.State == MicrophoneState.Started;
UpdateRecording(isRecording);
}
}
So, please help me out the problem. I heard at somewhere that you have to dispose all the objects of the microphone when you redirect to another screen. is it true ? or anything else.
Please help me.
Looking Forward.
Instead of using a collection, you should use following way to read your recorded bytes.
This should be done into the BufferReady event of your microphone object.
byte[] audioBuffer = new byte[microphone.GetSampleSizeInBytes(microphone.BufferDuration)];
microphone.GetData(audioBuffer);
RecordingStream.Write(audioBuffer, 0, audioBuffer.Length);
RecordingStream is a MemoryStream , should be declared globally.
I am not sure about this but as I have used it and it works completely fine in each case.
Try this.
I have been using Microsoft Live API for uploading & downloading database. but after downloading or uploading if i tried to access the database in anyway my app gives SqlCeException Unhandled & exits.
If i restart the app before accessing database it doesn't give any errors so for now the solution is
Restart the application
This is my code
IsolatedStorageFileStream fileStream = null;
private void Upload_Click(object sender, RoutedEventArgs e)
{
if (client == null || client.Session == null)
{
MessageBox.Show("You Must Sign In First.");
}
else
{
if (MessageBox.Show("Are You Sure? This Will Overwrite Your Old Backup File!", "Backup?", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
{
UploadDatabase();
}
}
}
public void UploadDatabase()
{
if (SDFolderID != string.Empty)
{
WLInfo.Text = "Uploading Backup...";
this.client.UploadCompleted += new EventHandler<LiveOperationCompletedEventArgs>(ISFile_UploadCompleted);
try
{
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
fileStream = store.OpenFile("DB.sdf", FileMode.Open, FileAccess.Read);
client.UploadAsync(SDFolderID, "DB.sdf", fileStream, OverwriteOption.Overwrite);
WLInfo.Text = "Upload Complete.";
}
}
catch
{
WLInfo.Text = "Error: Restart Application.";
}
}
}
private void ISFile_UploadCompleted(object sender, LiveOperationCompletedEventArgs args)
{
if (args.Error == null)
{
client = new LiveConnectClient(session);
client.GetCompleted += new EventHandler<LiveOperationCompletedEventArgs>(GetFiles_GetCompleted);
client.GetAsync(SDFolderID + "/files");
}
else
{
this.WLInfo.Text = "Error Uploading Backup File.";
}
fileStream.Close();
}
void GetFiles_GetCompleted(object sender, LiveOperationCompletedEventArgs e)
{
List<object> data = (List<object>)e.Result["data"];
foreach (IDictionary<string, object> content in data)
{
if (((string)content["name"]).Equals(FileName))
{
FileID = (string)content["id"];
}
}
if (FileID != null)
{
WLInfo.Text = "Backup Found On Sky Drive.";
}
else
{
WLInfo.Text = "Backup Not Found On Sky Drive.";
}
}
I'm guessing it's probably of a Stream not properly closed so your database file is still locked. When you upload or download your database file make sure you use the using statement on all disposable object so that all the Stream are properly disposed automatically
In your code fileStream is not disposed which is probably what is causing the problem (you should "save" this variable in a local filed and call dispose on it in ISFile_UploadCompleted).
Also when if you use using there is no need to call dispose on the object (no need to have store.Dispose();, it's automatically done when you go out of the using scope)
Hello Everyone,
I am working on an application in which i need to save some data in IsolatedStorage .
while my application is running i am able to see data from file. Once i close my application and restarting my application its not showing my data.
public static IsolatedStorageFile isstore = IsolatedStorageFile.GetUserStoreForApplication();
public static IsolatedStorageFileStream xyzStrorageFileStream = new IsolatedStorageFileStream("/category.xml", System.IO.FileMode.OpenOrCreate, isstore);
public static XDocument xmldoc = XDocument.Load("category.xml");
favouriteDoc.Save(rssFavouriteFileStream);
rssFavouriteFileStream.Flush();
Any one having any idea? How to do this?
In order to save structured data you need to use XML Writer or XML Serializer.
For example to save data:
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("People2.xml", FileMode.Create, myIsolatedStorage))
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create(isoStream, settings))
{
writer.WriteStartElement("p", "person", "urn:person");
writer.WriteStartElement("FirstName", "");
writer.WriteString("Kate");
writer.WriteEndElement();
writer.WriteStartElement("LastName", "");
writer.WriteString("Brown");
writer.WriteEndElement();
writer.WriteStartElement("Age", "");
writer.WriteString("25");
writer.WriteEndElement();
// Ends the document
writer.WriteEndDocument();
// Write the XML to the file.
writer.Flush();
}
}
}
To read it back:
try
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile("People2.xml", FileMode.Open);
using (StreamReader reader = new StreamReader(isoFileStream))
{
this.tbx.Text = reader.ReadToEnd();
}
}
}
catch
{ }
Answer is taken from this article, so all the credits go to WindowsPhoneGeek. Also, see other examples in the aforementioned article header.
i have created some files in the IO
in the "car" files, i would like to put some other reference like model, color etc...
so my question is : is it possible to have a multi-lining files in the IO
if yes how can i get them in the streamreader
// i want to storage many parameters in a file and find them again with the streamreader
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
//reception des parametres de la listbox
base.OnNavigatedTo(e);
string parameter = this.NavigationContext.QueryString["parameter"];
this.tbTitre.Text = parameter;
try
{
//Create a new StreamReader
StreamReader editionDevisReader = null;
IsolatedStorageFile probyOrange = IsolatedStorageFile.GetUserStoreForApplication();
//Read the file from the specified location.
editionDevisReader = new StreamReader(new IsolatedStorageFileStream("devis\\"+parameter+".txt", FileMode.Open, probyOrange));
//Read the contents of the file .
string textFile = editionDevisReader.ReadLine();
//Write the contents of the file to the TextBlock on the page.
tbTitre.Text = textFile;
while (editionDevisReader != null)
{
RowDefinition rowdefinition = new RowDefinition();
TextBlock textblock = new TextBlock();
textblock.HorizontalAlignment = new System.Drawing.Size(48, 20);
}
editionDevisReader.Close();
}
catch
{
//If the file hasn't been created yet.
tbTitre.Text = "veuillez d abord creer le fichier";
}
thx a lot all
Yes, you can save anything (up to a point) in a file:
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var isfs = new IsolatedStorageFileStream("myfile.txt", FileMode.OpenOrCreate, store))
{
using (var sw = new StreamWriter(isfs))
{
sw.Write("anything really. Here it's just a string but could be a serialized object, etc.");
sw.Close();
}
}
}
You can then read the file with:
var result = string.Empty;
try
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!store.FileExists("myfile.txt"))
{
return result;
}
using (var isfs = new IsolatedStorageFileStream("myfile.txt", FileMode.Open, store))
{
using (var sr = new StreamReader(isfs))
{
string lineOfData;
while ((lineOfData = sr.ReadLine()) != null)
{
result += lineOfData;
}
}
}
}
}
catch (IsolatedStorageException)
{
result = string.Empty; // may have partial data/file before error
}
return result;
You can use
StreamReader.Writeline
and
StreamRead.ReadLine
to write and read blocks of text seperated by line feeds.