Flush() public méthode

public Flush ( ) : void
Résultat void
        void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error == null && !e.Cancelled)
            {
                string iconPath = "1.txt";

                using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    var isfs = new IsolatedStorageFileStream(iconPath, FileMode.Create, isf);
                    int bytesRead;
                    byte[] bytes = new byte[e.Result.Length];
                    while ((bytesRead = e.Result.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        isfs.Write(bytes, 0, bytesRead);
                    }
                    isfs.Flush();
                    isfs.Close();
                }


                this.Dispatcher.BeginInvoke(() =>
                {
                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                });
            }
        }
Exemple #2
0
        /// <summary>
        /// If there is no database file in isolated storage, copy it from xap to isolated storage.
        /// It performs read/write access to db.
        /// Also check database for possible update if version has been changed.
        /// </summary>
        private void CheckDbVersion()
        {
            bool dbExists = false;
            using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                dbExists = storage.FileExists(DbFilePath);
                if (!dbExists)
                {
                    Stream resourceFile = Application.GetResourceStream(new Uri(DbFilePath, UriKind.Relative)).Stream;
                    IsolatedStorageFileStream isolatedStorageFile = new IsolatedStorageFileStream(DbFilePath, FileMode.CreateNew, storage);
                    resourceFile.CopyTo(isolatedStorageFile);
                    isolatedStorageFile.Flush();
                    resourceFile.Close();
                    isolatedStorageFile.Close();
                }
            }

            if (dbExists)
            {
                DatabaseSchemaUpdater updater = this.CreateDatabaseSchemaUpdater();
                if (updater.DatabaseSchemaVersion < 2)
                {
                }
            }
        }
        private static string CopyFile(string filename)
        {
            IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();

            Stream input = null;
            Stream output = null;

            string absoulutePath = Windows.Storage.ApplicationData.Current.LocalFolder.Path + '\\' + filename;

            if (!File.Exists(absoulutePath))
            {
                input = Application.GetResourceStream(new Uri(filename, UriKind.Relative)).Stream;
                output = new IsolatedStorageFileStream(filename, FileMode.CreateNew, isoStore);

                CopyFile(input, output);

                input.Close();
                input = null;

                output.Flush();
                output.Close();
                output = null;
            }

            return absoulutePath;
        }
 private void CopyFromContentToStorage(IsolatedStorageFile ISF, String SourceFile, String DestinationFile)
 {
     Stream Stream = Application.GetResourceStream(new Uri(SourceFile, UriKind.Relative)).Stream;
     IsolatedStorageFileStream ISFS = new IsolatedStorageFileStream(DestinationFile, System.IO.FileMode.Create, System.IO.FileAccess.Write, ISF);
     CopyStream(Stream, ISFS);
     ISFS.Flush();
     ISFS.Close();
     Stream.Close();
     ISFS.Dispose();
 }
 public static void CopyToIsolatedStorage(string packageFilename, string isoFilename)
 {
     using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
         if (!store.FileExists(isoFilename))
             using (var stream = System.Windows.Application.GetResourceStream(new Uri(packageFilename, UriKind.Relative)).Stream)
             using (IsolatedStorageFileStream dest = new IsolatedStorageFileStream(isoFilename, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, store))
             {
                 stream.Position = 0;
                 stream.CopyTo(dest);
                 dest.Flush();
             }
 }
        public static void SerializeObject(string filename, object obj)
        {
            //Stream stream = File.Open(filename, FileMode.Create);
            IsolatedStorageFile isof = IsolatedStorageFile.GetUserStoreForApplication();
            IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(filename, FileMode.Create, isof);
            byte[] b = BusinessLib.SilverlightSerializer.Serialize(obj);
            isfs.Write(b, 0, b.Length);
            isfs.Flush();

            isfs.Close();
            isof.Dispose();
        }
Exemple #7
0
 private void decode(object sender, RoutedEventArgs e)
 {
     IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
     LibmadWrapper Libmad = new LibmadWrapper();
     
     IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(Mp3bytes, 0, Mp3bytes.Length);
     PCMStream = isf.CreateFile("decoded_pcm.pcm");
    
     bool init = Libmad.DecodeMp32Pcm_Init(buffer);
     if (init)
     {
         List<short> samples = new List<short>();
         RawPCMContent rpcc = null;
         try
         {
             while ((rpcc = Libmad.ReadSample()).count != 0)
             {
                 short[] shortBytes = rpcc.PCMData.ToArray<short>();
                 byte[] rawbytes = new byte[shortBytes.Length * 2];
                 for (int i = 0; i < shortBytes.Length; i++)
                 {
                     rawbytes[2 * i] = (byte)shortBytes[i];
                     rawbytes[2 * i + 1] = (byte)(shortBytes[i] >> 8);
                 }
                  PCMStream.Write(rawbytes, 0, rawbytes.Length);
             }
             PCMStream.Flush();
             PCMStream.Close();
             PCMStream.Dispose();
             MessageBox.Show("over");
             Libmad.CloseFile();    
         }
         catch (Exception exception)
         {
             MessageBox.Show(exception.Message);
         }
     }
     isf.Dispose();
 }
Exemple #8
0
        /// <summary>
        /// 保存信息至本地文件,SilverLight缓存中
        /// </summary>
        /// <param name="rFileName"></param>
        /// <param name="buffer"></param>
        public static void WriteSlByteFile(string rFileName, byte[] buffer)
        {
            System.IO.IsolatedStorage.IsolatedStorageFile isf = null;
            System.IO.Stream stream = null;
            try
            {
                isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();

                if (rFileName.IndexOf(':') >= 0)
                {
                    rFileName = rFileName.Substring(rFileName.LastIndexOf(':') + 1);
                }
                ClearSlFile(rFileName);
                string rPath = System.IO.Path.GetDirectoryName(rFileName);
                if (rPath != "")
                {
                    isf.CreateDirectory(rPath);
                }

                stream = new System.IO.IsolatedStorage.IsolatedStorageFileStream(rFileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.Write, isf);
                stream.Write(buffer, 0, buffer.Length);
                stream.Flush();
            }
            finally
            {
                try
                {
                    stream.Close(); // Close the stream too
                    stream.Dispose();
                    isf.Dispose();
                }
                catch
                {
                }
            }
        }
        /// <summary>
        /// Saves the audio buffer into isolated storage as a wav-file.
        /// </summary>
        private void saveAudioBuffer()
        {
            IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();

            try
            {
                DateTime dateTime = DateTime.Now;
                string fileName = dateTime.ToString("yyyy_MM_dd_HH_mm_ss.wav");
                using (var isoFileStream = new IsolatedStorageFileStream(
                    fileName,
                    FileMode.OpenOrCreate,
                    myStore))
                {
                    // Write a header before the actual pcm data
                    int sampleBits = 16;
                    int sampleBytes = sampleBits / 8;
                    int byteRate = App.AudioModel.SampleRate * sampleBytes * App.AudioModel.ChannelCount;
                    int blockAlign = sampleBytes * App.AudioModel.ChannelCount;
                    Encoding encoding = Encoding.UTF8;

                    isoFileStream.Write(encoding.GetBytes("RIFF"), 0, 4);                       // "RIFF"
                    isoFileStream.Write(BitConverter.GetBytes(0), 0, 4);                        // Chunk Size
                    isoFileStream.Write(encoding.GetBytes("WAVE"), 0, 4);                       // Format - "Wave"
                    isoFileStream.Write(encoding.GetBytes("fmt "), 0, 4);                       // sub chunk - "fmt"
                    isoFileStream.Write(BitConverter.GetBytes(16), 0, 4);                       // sub chunk size
                    isoFileStream.Write(BitConverter.GetBytes((short)1), 0, 2);                 // audio format
                    isoFileStream.Write(BitConverter.GetBytes((short)App.AudioModel.ChannelCount), 0, 2); // num of channels
                    isoFileStream.Write(BitConverter.GetBytes(App.AudioModel.SampleRate), 0, 4);    // sample rate
                    isoFileStream.Write(BitConverter.GetBytes(byteRate), 0, 4);                 // byte rate
                    isoFileStream.Write(BitConverter.GetBytes((short)(blockAlign)), 0, 2);      // block align
                    isoFileStream.Write(BitConverter.GetBytes((short)(sampleBits)), 0, 2);      // bits per sample
                    isoFileStream.Write(encoding.GetBytes("data"), 0, 4);                       // sub chunk - "data"
                    isoFileStream.Write(BitConverter.GetBytes(0), 0, 4);                        // sub chunk size

                    // write the actual pcm data
                    App.AudioModel.stream.Position = 0;
                    App.AudioModel.stream.CopyTo(isoFileStream);

                    // and fill in the blanks
                    long previousPos = isoFileStream.Position;
                    isoFileStream.Seek(4, SeekOrigin.Begin);
                    isoFileStream.Write(BitConverter.GetBytes((int)isoFileStream.Length - 8), 0, 4);
                    isoFileStream.Seek(40, SeekOrigin.Begin);
                    isoFileStream.Write(BitConverter.GetBytes((int)isoFileStream.Length - 44), 0, 4);
                    isoFileStream.Seek(previousPos, SeekOrigin.Begin);

                    isoFileStream.Flush();
                }
            }
            catch
            {
                MessageBox.Show("Error while trying to store audio stream.");
            }
        }
Exemple #10
0
        private void mountDatabase(IsolatedStorageFile dataStorage, String dbName)
        {
            IsolatedStorageFileStream destStream = new IsolatedStorageFileStream(
                dbName,
                System.IO.FileMode.OpenOrCreate,
                System.IO.FileAccess.ReadWrite,
                dataStorage
            );

            byte[] buffer = new byte[1024];


            if (TestMode) copyStream(string.Format("{0}.{1}", DB_NAME_TEST, DB_UNMOUNT_EXT), destStream, buffer);
            else
            {
                for (int count = 0; count < DB_CHUNCK; count++)
                {
                    copyStream(string.Format("{0}{1}.{2}", DB_NAME, count, DB_UNMOUNT_EXT), destStream, buffer);
                }
            }

            destStream.Flush();
            destStream.Close();
        }
        } // StartVideoRecording()

        private void StopVideoRecording()
        {
            try
            {
                // Stop recording.
                if (captureSource.VideoCaptureDevice != null
                && captureSource.State == CaptureState.Started)
                {
                    captureSource.Stop();

                    // Disconnect fileSink.
                    fileSink.CaptureSource = null;
                    fileSink.IsolatedStorageFileName = null;
                    
                    // Set the button states and the message.
                    UpdateUI(ButtonState.Stopped, "Recording stopped...");

                    viewfinderRectangle.Fill = null;

                    // Create the file stream 
                    isoVideoFile = new IsolatedStorageFileStream(fileName,
                                            FileMode.Open, FileAccess.Read,
                                            IsolatedStorageFile.GetUserStoreForApplication());

                    MemoryStream videoStream = new MemoryStream();
                    using (isoVideoFile)
                    {
                        isoVideoFile.CopyTo(videoStream);
                    }

                    PurposeColor.screens.AddEventsSituationsOrThoughts.ReceiveVideoFromWindows(videoStream, isoVideoFile.Name);
                    
                    isoVideoFile.Flush();
                    isoVideoFile.Dispose();
                    isoVideoFile = null;
                    //videoStream = null;

                    DisposeVideoRecorder();

                }
            }
            // If stop fails, display an error.
            catch (Exception e)
            {
                this.Dispatcher.BeginInvoke(delegate()
                {
                    txtDebug.Text = "ERROR: " + e.Message.ToString();
                });
            }
        }//StopVideoRecording()
 // Code to execute when the application is launching (eg, from Start)
 // This code will not execute when the application is reactivated
 private void Application_Launching(object sender, LaunchingEventArgs e)
 {
     using (var store = IsolatedStorageFile.GetUserStoreForApplication())
     {
         if (!store.FileExists("sample.wmv"))
         {
             using (var stream = Application.GetResourceStream(new Uri("Media/sample.wmv", UriKind.Relative)).Stream)
             using (var fileStream = new IsolatedStorageFileStream("sample.wmv", FileMode.Create, store))
             {
                 byte[] bytesInStream = new byte[stream.Length];
                 stream.Read(bytesInStream, 0, (int)bytesInStream.Length);
                 fileStream.Write(bytesInStream, 0, bytesInStream.Length);
                 fileStream.Flush();
             }
         }
     }
 }
Exemple #13
0
 private void SaveFile(byte[] p_FileData, String p_FileName)
 {
     //MemoryStream ms = new MemoryStream(mp3Data);
     using (IsolatedStorageFileStream file = new IsolatedStorageFileStream(p_FileName, FileMode.OpenOrCreate, IsolatedStorageFile.GetUserStoreForApplication()))
     {
         file.Write(p_FileData, 0, p_FileData.Length);
         file.Flush();
         file.Close();
     }
 }
Exemple #14
0
        private static void SaveScaledBitmap(BitmapImage bitmap, string localFileName, IsolatedStorageFile isoStore, double maxWidth, double maxHeight)
        {
            double scaleWidth = maxWidth / (double)bitmap.PixelWidth;
            double scaleHeight = maxHeight / (double)bitmap.PixelHeight;
            double scale = Math.Min(scaleWidth, scaleHeight);
            int width = (int)Math.Round(scale * (double)bitmap.PixelWidth);
            int height = (int)Math.Round(scale * (double)bitmap.PixelHeight);

            using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(localFileName, FileMode.Create, isoStore))
            {
                WriteableBitmap writable = new WriteableBitmap(bitmap);
                writable.SaveJpeg(isoStream, width, height, 0, 80);
                isoStream.Flush();
            }
        }
Exemple #15
0
 /// <summary>
 /// 写入或更新上传进度记录
 /// </summary>
 /// <param name="key">记录文件名</param>
 /// <param name="data">上传进度数据</param>
 public void set(string key, byte[] data)
 {
     string filePath = Path.Combine(this.dir, StringUtils.urlSafeBase64Encode(key));
     using (IsolatedStorageFileStream stream =
         new IsolatedStorageFileStream(filePath, FileMode.Create, this.storage))
     {
         stream.Write(data, 0, data.Length);
         stream.Flush();
     }
 }
Exemple #16
0
        private static async void captureSnapshot(ushort[] pixeldata, int pitch, string filename)
        {
            WriteableBitmap bitmap = new WriteableBitmap(pitch / 2, (int)pixeldata.Length / (pitch / 2));
            int x = 0;
            int y = 0;
            for (int i = 0; i < bitmap.PixelWidth * bitmap.PixelHeight; i++)
            {
                ushort pixel = pixeldata[i];
                byte r = (byte)((pixel & 0xf800) >> 11);
                byte g = (byte)((pixel & 0x07e0) >> 5);
                byte b = (byte)(pixel & 0x001f);
                r = (byte)((255 * r) / 31);
                g = (byte)((255 * g) / 63);
                b = (byte)((255 * b) / 31);
                bitmap.SetPixel(x, y, r, g, b);
                x++;
                if (x >= bitmap.PixelWidth)
                {
                    y++;
                    x = 0;
                }
            }
            String snapshotName = filename.Substring(0, filename.Length - 3) + "jpg";
            //StorageFolder folder = await ApplicationData.Current.LocalFolder.GetFolderAsync(ROM_DIRECTORY);
            ////StorageFolder saveFolder = await folder.GetFolderAsync(SAVE_DIRECTORY);
            //StorageFolder shared = await folder.GetFolderAsync("Shared");
            //StorageFolder shellContent = await shared.GetFolderAsync("ShellContent");
            //StorageFile file = await shellContent.CreateFileAsync(snapshotName, CreationCollisionOption.ReplaceExisting);

            try
            {
                IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
                using (IsolatedStorageFileStream fs = new IsolatedStorageFileStream("/Shared/ShellContent/" + snapshotName, System.IO.FileMode.Create, iso))
                {
                    bitmap.SaveJpeg(fs, bitmap.PixelWidth, bitmap.PixelHeight, 0, 90);
                    //await fs.FlushAsync();
                    fs.Flush(true);
                }
                ROMDatabase db = ROMDatabase.Current;
                ROMDBEntry entry = db.GetROM(filename);
                entry.SnapshotURI = "Shared/ShellContent/" + snapshotName;
                db.CommitChanges();

                UpdateLiveTile();

                UpdateROMTile(filename);
            }
            catch (Exception)
            {
            }



            //try
            //{
            //    using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            //    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            //    {
            //        bitmap.SaveJpeg(ms, bitmap.PixelWidth, bitmap.PixelHeight, 0, 90);
            //        byte[] bytes = ms.ToArray();
            //        DataWriter writer = new DataWriter(stream);
            //        writer.WriteBytes(bytes);
            //        await writer.StoreAsync();
            //        writer.DetachStream();
            //        await stream.FlushAsync();
            //    }

            //    ROMDatabase db = ROMDatabase.Current;
            //    ROMDBEntry entry = db.GetROM(filename);
            //    entry.SnapshotURI = "Shared/ShellContent/" + snapshotName;
            //    db.CommitChanges();
            //}
            //catch (Exception e)
            //{
            //    MessageBox.Show(e.Message);
            //}

            //await file.CopyAsync(shellContent);
        }
        //protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        //{


        //    AdRequest adRequest = new AdRequest();
        //    adRequest.ForceTesting = true;
        //    interstitialAd.LoadAd(adRequest);
        //    interstitialAd.ReceivedAd += OnAdReceived;




        //    if (p == true)
        //    {


        //        p = false;

        //        q = true;

        //        interstitialAd.ShowAd();

        //    }
        //   // NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative));

        //    // Application.Current.Terminate();

        //}

        
        /// <summary>
        /// Store the page state in case application gets tombstoned.
        /// </summary>
        private void StoreState()
        {
            // Save the currently filtered image into isolated app storage.
            IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
            myStore.CreateDirectory(TombstoneImageDir);

            try
            {
                using (var isoFileStream = new IsolatedStorageFileStream(
                    TombstoneImageFile,
                    FileMode.OpenOrCreate,
                    myStore))
                {
                    DataContext dataContext = FilterEffects.DataContext.Instance;
                    dataContext.FullResolutionStream.Position = 0;
                    dataContext.FullResolutionStream.CopyTo(isoFileStream);
                    isoFileStream.Flush();
                }
            }
            catch
            {
                MessageBox.Show("Error while trying to store temporary image.");
            }

            // Save also the current preview index 
            State[StateIndexKey] = FilterPreviewPivot.SelectedIndex;
        }
Exemple #18
0
        public void ResizeFile()
        {
            const int blocks = 10000;
            int blockcount = Blocks.Count;
            for (int i = 0; i < blocks; i++)
            {
                Blocks.Add(blockcount + i, true);
            }

            using (var fs = new IsolatedStorageFileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, isf))
            {
                fs.SetLength(fs.Length + (blocks * BlockSize));
                fs.Flush();
            }
        }
Exemple #19
0
        private void WriteXmlFile(string fileName, XDocument xdoc)
        {
            using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                //init folder
                if (!store.DirectoryExists(@"cache"))
                {
                    store.CreateDirectory(@"cache");
                }

                if (!store.DirectoryExists(@"cache/xml"))
                {
                    store.CreateDirectory(@"cache/xml");
                }

                //delete existing file
                if (store.FileExists(@"cache/xml/" + fileName + ".xml"))
                {
                    store.DeleteFile(@"cache/xml/" + fileName + ".xml");
                }

                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(@"cache/xml/" + fileName + ".xml", System.IO.FileMode.Create, store))
                {
                    //xdoc.Save(stream);

                    //convert xdoc to byte array
                    byte[] bytes = Encoding.UTF8.GetBytes(xdoc.ToString());

                    //encrypt byte array
                    byte[] encryptedBytes = ProtectedData.Protect(bytes, XmlOptionalEntropy);

                    //write encrypted byte array to file
                    stream.Write(encryptedBytes, 0, encryptedBytes.Length);
                    stream.Flush();
                }
            }
        }
Exemple #20
0
 /// <summary>
 /// Persists the cache to disk
 /// </summary>
 public void Save()
 {
     App.Log("Persisting cache to file");
     using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
     {
         using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("rssCache.dat", System.IO.FileMode.Create, file))
         {
             DataContractSerializer serializer = new DataContractSerializer(typeof(RSSCache));
             stream.Flush();
             serializer.WriteObject(stream, this);
         }
     }
 }
 /// <summary>
 /// Saves all sections. All data merged from other merged sources will
 /// be included.
 /// </summary>
 public override void Save()
 {
     using ( IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetStore( Scope, null, null ) )
     {
         using ( var isoStream =
             new IsolatedStorageFileStream( _fileName,
                                            FileMode.Truncate,
                                            FileAccess.Write,
                                            FileShare.Read,
                                            isolatedStorageFile ) )
         {
             string xml = XmlConfigurationSource.ToXml( Sections.Values );
             byte[] xmlBytes = Encoding.UTF8.GetBytes( xml );
             isoStream.Write( xmlBytes, 0, xmlBytes.Length );
             isoStream.Flush();
         }
     }
 }
        /// <summary>
        /// 停止录音
        /// </summary>
        private void StopRecordVoice()
        {
            IsRecord = false;
            RecordButton.Content = "Save...";
            RecordButton.Foreground = App.Current.Resources["PhoneForegroundBrush"] as SolidColorBrush;
            RecordButton.Background = App.Current.Resources["PhoneBackgroundBrush"] as SolidColorBrush;
            gSpendTime = 0;

            if (gMicrophone.State == MicrophoneState.Started)
            {
                gMicrophone.Stop();
                gStream.Close();
            }

            MemoryStream m = new MemoryStream();
            int s = gMicrophone.SampleRate / 2;
            WavHeader.WriteWavHeader(m, s);
            byte[] b = NormalizeWaveData(gStream.ToArray());
            m.Write(b, 0, b.Length);
            m.Flush();
            WavHeader.UpdateWavHeader(m);

            using (var tStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                string savepath = DateTime.Now.ToString();
                savepath = savepath.Replace('/', '-');
                savepath = savepath.Replace(':', ' ');
                using (var tFStream = new IsolatedStorageFileStream(savepath + ".wav", FileMode.Create, tStore))
                {
                    byte[] tByteInStream = m.ToArray();
                    tFStream.Write(tByteInStream, 0, tByteInStream.Length);
                    tFStream.Flush();
                }
            }
            gStream = new MemoryStream();

            UpdataListBox();
            RecordButton.Content = "Record";
        } 
		private void Write (string filename)
		{
			byte[] buffer = new byte[8];
			using (IsolatedStorageFileStream write = new IsolatedStorageFileStream (filename, FileMode.Create, FileAccess.Write)) {
				Assert.IsFalse (write.CanRead, "write.CanRead");
				Assert.IsTrue (write.CanSeek, "write.CanSeek");
				Assert.IsTrue (write.CanWrite, "write.CanWrite");
				Assert.IsFalse (write.IsAsync, "write.IsAync");
				write.Write (buffer, 0, buffer.Length);
				write.Position = 0;
				write.WriteByte ((byte)buffer.Length);
				write.SetLength (8);
				write.Flush ();
				write.Close ();
			}
		}
        private void _GetResult(Stream result)
        {
            if (result == null)
            {
                _LoadNext();
            }
            else
            {
                try
                {
                    _isEnoughSpace = CacheHelpers.GetMoreSpace(result.Length);

                    if (_isEnoughSpace)
                    {
                        lock (guard)
                        {
                            IsolatedStorageFile filesystem = null;
                            IsolatedStorageFileStream fs = null;
                            try
                            {
                                filesystem = IsolatedStorageFile.GetUserStoreForApplication();
                                string filename = _currentFileName + ".jpg";

                                if (!filesystem.FileExists(filename))
                                {
                                    fs = new IsolatedStorageFileStream(filename, FileMode.Create, filesystem);
                                    // Save the image to Isolated Storage
                                    Int64 imgLen = (Int64)result.Length;
                                    byte[] b = new byte[imgLen];
                                    result.Read(b, 0, b.Length);
                                    fs.Write(b, 0, b.Length);
                                    fs.Flush();
                                }

                                _numberOfLoaded++;
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine("Save avatar in file system failed: " + ex.Message);
                            }
                            finally
                            {
                                if (filesystem != null)
                                    filesystem.Dispose();

                                if (fs != null)
                                    fs.Dispose();
                            }
                        }

                        _callback(_currentFriendId);

                        _LoadNext();
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Image loading failed." + ex.Message);

                    _LoadNext();
                }
            }
        }
        private void RunSample_Click(object sender, RoutedEventArgs e)
        {
            SampleViewModel svm = DataContext as SampleViewModel;
            if (svm != null)
            {
                SampleOutputInfo[] output = null;
                MemoryStream outputStream = null;

                switch (svm.ID)
                {
                    case "actions":
                        output = Xfinium.Pdf.Samples.Actions.Run();
                        break;
                    case "annotations":
                        StreamResourceInfo flashInput = Application.GetResourceStream(new Uri("support/clock.swf", UriKind.Relative));
                        StreamResourceInfo u3dInput = Application.GetResourceStream(new Uri("support/airplane.u3d", UriKind.Relative));
                        output = Xfinium.Pdf.Samples.Annotations.Run(flashInput.Stream, u3dInput.Stream);
                        flashInput.Stream.Close();
                        u3dInput.Stream.Close();
                        break;
                    case "barcodes":
                        output = Xfinium.Pdf.Samples.Barcodes.Run();
                        break;
                    case "batesnumbers":
                        StreamResourceInfo batesNumbersInput = Application.GetResourceStream(new Uri("support/content.pdf", UriKind.Relative));
                        output = Xfinium.Pdf.Samples.BatesNumbers.Run(batesNumbersInput.Stream);
                        batesNumbersInput.Stream.Close();
                        batesNumbersInput = null;
                        break;
                    case "contentextraction":
                        StreamResourceInfo contentExtractionInput = Application.GetResourceStream(new Uri("support/content.pdf", UriKind.Relative));
                        output = Xfinium.Pdf.Samples.ContentExtraction.Run(contentExtractionInput.Stream);
                        contentExtractionInput.Stream.Close();
                        contentExtractionInput = null;
                        break;
                    case "contentstream":
                        output = Xfinium.Pdf.Samples.ContentStream.Run();
                        break;
                    case "documentappend":
                        StreamResourceInfo file1Input = Application.GetResourceStream(new Uri("support/content.pdf", UriKind.Relative));
                        StreamResourceInfo file2Input = Application.GetResourceStream(new Uri("support/formfill.pdf", UriKind.Relative));
                        output = Xfinium.Pdf.Samples.DocumentAppend.Run(file1Input.Stream, file2Input.Stream);
                        file1Input.Stream.Close();
                        file2Input.Stream.Close();
                        break;
                    case "documentincrementalupdate":
                        outputStream = new MemoryStream();

                        StreamResourceInfo sri = Application.GetResourceStream(new Uri("support/content.pdf", UriKind.Relative));
                        byte[] buffer = new byte[8192];
                        while (true)
                        {
                            int readSize = sri.Stream.Read(buffer, 0, buffer.Length);
                            if (readSize <= 0)
                            {
                                break;
                            }
                            outputStream.Write(buffer, 0, readSize);
                        }
                        sri.Stream.Close();

                        output = Xfinium.Pdf.Samples.DocumentIncrementalUpdate.Run(outputStream);
                        break;
                    case "documentpagebypagesave":
                        outputStream = new MemoryStream();
                        output = Xfinium.Pdf.Samples.DocumentPageByPageSave.Run(outputStream);
                        break;
                    case "documentproperties":
                        output = Xfinium.Pdf.Samples.DocumentProperties.Run();
                        break;
                    case "documentsplit":
                        StreamResourceInfo splitInput = Application.GetResourceStream(new Uri("support/content.pdf", UriKind.Relative));
                        output = Xfinium.Pdf.Samples.DocumentSplit.Run(splitInput.Stream);
                        splitInput.Stream.Close();
                        break;
                    case "encryption":
                        StreamResourceInfo encryptionInput = Application.GetResourceStream(new Uri("support/encrypted.pdf", UriKind.Relative));
                        output = Xfinium.Pdf.Samples.Encryption.Run(encryptionInput.Stream);
                        encryptionInput.Stream.Close();
                        break;
                    case "fileattachments":
                        StreamResourceInfo attachmentStream1 = Application.GetResourceStream(new Uri("support/fileattachments.cs.html", UriKind.Relative));
                        StreamResourceInfo attachmentStream2 = Application.GetResourceStream(new Uri("support/fileattachments.vb.html", UriKind.Relative));
                        output = Xfinium.Pdf.Samples.FileAttachments.Run(attachmentStream1.Stream, attachmentStream2.Stream);
                        attachmentStream1.Stream.Close();
                        attachmentStream2.Stream.Close();
                        break;
                    case "fonts":
                        StreamResourceInfo ttfResource = Application.GetResourceStream(new Uri("support/verdana.ttf", UriKind.Relative));
                        output = Xfinium.Pdf.Samples.Fonts.Run(ttfResource.Stream);
                        ttfResource.Stream.Close();
                        break;
                    case "formattedcontent":
                        output = Xfinium.Pdf.Samples.FormattedContent.Run();
                        break;
                    case "formfill":
                        StreamResourceInfo formStream = Application.GetResourceStream(new Uri("support/formfill.pdf", UriKind.Relative));
                        output = Xfinium.Pdf.Samples.FormFill.Run(formStream.Stream);
                        formStream.Stream.Close();
                        break;
                    case "formgenerator":
                        output = Xfinium.Pdf.Samples.FormGenerator.Run();
                        break;
                    case "grayscaleconversion":
                        StreamResourceInfo grayscaleConversionInput = Application.GetResourceStream(new Uri("support/content.pdf", UriKind.Relative));
                        output = Xfinium.Pdf.Samples.GrayscaleConversion.Run(grayscaleConversionInput.Stream);
                        grayscaleConversionInput.Stream.Close();
                        break;
                    case "images":
                        StreamResourceInfo imageStream = Application.GetResourceStream(new Uri("support/image.jpg", UriKind.Relative));
                        StreamResourceInfo cmykImageStream = Application.GetResourceStream(new Uri("support/cmyk.tif", UriKind.Relative));
                        StreamResourceInfo softMaskStream = Application.GetResourceStream(new Uri("support/softmask.png", UriKind.Relative));
                        StreamResourceInfo stencilMaskStream = Application.GetResourceStream(new Uri("support/stencilmask.png", UriKind.Relative));
                        output = Xfinium.Pdf.Samples.Images.Run(imageStream.Stream, cmykImageStream.Stream, softMaskStream.Stream, stencilMaskStream.Stream);
                        imageStream.Stream.Close();
                        cmykImageStream.Stream.Close();
                        softMaskStream.Stream.Close();
                        stencilMaskStream.Stream.Close();
                        break;
                    case "measurements":
                        output = Xfinium.Pdf.Samples.Measurements.Run();
                        break;
                    case "optionalcontent":
                        output = Xfinium.Pdf.Samples.OptionalContent.Run();
                        break;
                    case "optionalcontentextraction":
                        StreamResourceInfo oceInput = Application.GetResourceStream(new Uri("support/content.pdf", UriKind.Relative));
                        output = Xfinium.Pdf.Samples.OptionalContentExtraction.Run(oceInput.Stream);
                        oceInput.Stream.Close();
                        break;
                    case "outlines":
                        output = Xfinium.Pdf.Samples.Outlines.Run();
                        break;
                    case "pageimposition":
                        StreamResourceInfo pageImpositionInput = Application.GetResourceStream(new Uri("support/content.pdf", UriKind.Relative));
                        output = Xfinium.Pdf.Samples.PageImposition.Run(pageImpositionInput.Stream);
                        pageImpositionInput.Stream.Close();
                        break;
                    case "pageobjects":
                        StreamResourceInfo pageObjectsInput = Application.GetResourceStream(new Uri("support/pageobjects.pdf", UriKind.Relative));
                        output = Xfinium.Pdf.Samples.PageObjects.Run(pageObjectsInput.Stream);
                        pageObjectsInput.Stream.Close();
                        break;
                    case "pdfa":
                        StreamResourceInfo iccInput = Application.GetResourceStream(new Uri("support/rgb.icc", UriKind.Relative));
                        StreamResourceInfo ttfInput = Application.GetResourceStream(new Uri("support/verdana.ttf", UriKind.Relative));
                        output = Xfinium.Pdf.Samples.PDFA.Run(iccInput.Stream, ttfInput.Stream);
                        iccInput.Stream.Close();
                        ttfInput.Stream.Close();
                        break;
                    case "portfolios":
                        StreamResourceInfo imagesStream = Application.GetResourceStream(new Uri("support/image.jpg", UriKind.Relative));
                        StreamResourceInfo pdfStream = Application.GetResourceStream(new Uri("support/content.pdf", UriKind.Relative));
                        StreamResourceInfo csStream = Application.GetResourceStream(new Uri("support/portfolios.cs.html", UriKind.Relative));
                        StreamResourceInfo vbStream = Application.GetResourceStream(new Uri("support/portfolios.vb.html", UriKind.Relative));
                        output = Xfinium.Pdf.Samples.Portfolios.Run(imagesStream.Stream, pdfStream.Stream, csStream.Stream, vbStream.Stream);
                        imagesStream.Stream.Close();
                        pdfStream.Stream.Close();
                        csStream.Stream.Close();
                        vbStream.Stream.Close();
                        break;
                    case "redaction":
                        StreamResourceInfo redactionStream = Application.GetResourceStream(new Uri("support/content.pdf", UriKind.Relative));
                        output = Xfinium.Pdf.Samples.Redaction.Run(redactionStream.Stream);
                        redactionStream.Stream.Close();
                        break;
                    case "removereplaceimages":
                        StreamResourceInfo removeReplaceImagesInput = Application.GetResourceStream(new Uri("support/content.pdf", UriKind.Relative));
                        output = Xfinium.Pdf.Samples.RemoveReplaceImages.Run(removeReplaceImagesInput.Stream);
                        removeReplaceImagesInput.Stream.Close();
                        break;
                    case "searchtext":
                        StreamResourceInfo searchTextInput = Application.GetResourceStream(new Uri("support/content.pdf", UriKind.Relative));
                        output = Xfinium.Pdf.Samples.SearchText.Run(searchTextInput.Stream);
                        searchTextInput.Stream.Close();
                        break;
                    case "svgtopdf":
                        StreamResourceInfo svgInput = Application.GetResourceStream(new Uri("support/tiger.svg", UriKind.Relative));
                        output = Xfinium.Pdf.Samples.SvgToPdf.Run(svgInput.Stream);
                        svgInput.Stream.Close();
                        break;
                    case "text":
                        output = Xfinium.Pdf.Samples.Text.Run();
                        break;
                    case "tifftopdf":
                        StreamResourceInfo tiffStream = Application.GetResourceStream(new Uri("support/sample.tif", UriKind.Relative));
                        output = Xfinium.Pdf.Samples.TiffToPdf.Run(tiffStream.Stream);
                        tiffStream.Stream.Close();
                        break;
                    case "type3fonts":
                        output = Xfinium.Pdf.Samples.Type3Fonts.Run();
                        break;
                    case "vectorgraphics":
                        StreamResourceInfo iccStream = Application.GetResourceStream(new Uri("support/rgb.icc", UriKind.Relative));
                        output = Xfinium.Pdf.Samples.VectorGraphics.Run(iccStream.Stream);
                        iccStream.Stream.Close();
                        break;
                    case "watermarks":
                        StreamResourceInfo watermarksInput = Application.GetResourceStream(new Uri("support/content.pdf", UriKind.Relative));
                        output = Xfinium.Pdf.Samples.Watermarks.Run(watermarksInput.Stream);
                        watermarksInput.Stream.Close();
                        break;
                }

                if (output != null)
                {
                    IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
                    IsolatedStorageFileStream pdfStream = new IsolatedStorageFileStream(output[0].FileName, FileMode.Create, fileStorage);
                    if (svm.ID == "pdfa")
                    {
                        PdfAFormatter.Save(output[0].Document as PdfFixedDocument, pdfStream, PdfAFormat.PdfA1b);
                    }
                    else
                    {
                        output[0].Document.Save(pdfStream, output[0].SecurityHandler);
                    }
                    pdfStream.Flush();
                    pdfStream.Close();

                    MessageBox.Show("Sample completed with success. File " + output[0].FileName + " saved to isolated storage.", "Xfinium.Pdf Samples Explorer", MessageBoxButton.OK);
                }
                if (outputStream != null)
                {
                    string fileName = "";
                    switch (svm.ID)
                    {
                        case "documentincrementalupdate":
                            fileName = "xfinium.pdf.sample.documentincrementalupdate.pdf";
                            break;
                        case "documentpagebypagesave":
                            fileName = "xfinium.pdf.sample.documentpagebypagesave.pdf";
                            break;
                    }

                    IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
                    IsolatedStorageFileStream pdfStream = new IsolatedStorageFileStream(fileName, FileMode.Create, fileStorage);
                    outputStream.WriteTo(pdfStream);
                    pdfStream.Flush();
                    pdfStream.Close();

                    MessageBox.Show("Sample completed with success. File " + fileName + " saved to isolated storage.", "Xfinium.Pdf Samples Explorer", MessageBoxButton.OK);
                }
            }
        }
        /// <summary>
        /// 保存信息至本地文件,SilverLight缓存中
        /// </summary>
        /// <param name="rFileName"></param>
        /// <param name="buffer"></param>
        public static void WriteSlByteFile(string rFileName, byte[] buffer)
        {
            System.IO.IsolatedStorage.IsolatedStorageFile isf = null;
            System.IO.Stream stream = null;
            try
            {
                isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();

                if (rFileName.IndexOf(':') >= 0)
                {
                    rFileName = rFileName.Substring(rFileName.LastIndexOf(':') + 1);
                }
                ClearSlFile(rFileName);
                string rPath = System.IO.Path.GetDirectoryName(rFileName);
                if (rPath != "")
                {
                    isf.CreateDirectory(rPath);
                }

                stream = new System.IO.IsolatedStorage.IsolatedStorageFileStream(rFileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.Write, isf);
                stream.Write(buffer, 0, buffer.Length);
                stream.Flush();
            }
            finally
            {
                try
                {
                    stream.Close(); // Close the stream too
                    stream.Dispose();
                    isf.Dispose();
                }
                catch
                {
                }
            }
        }
        private void Stop()
        {
            if (gMicrophone.State == MicrophoneState.Started)
            {
                gMicrophone.Stop();
                gStream.Close();
            }

            //MessageBox.Show("转存前的PCM数据大小:" + gStream.ToArray().Length.ToString());
            //构造一个MemoryStream先写入WavHeader头信息,待转换数据后再更新头信息中的data字段的值
            MemoryStream m = new MemoryStream();
            int s = gMicrophone.SampleRate / 2;
            WavHeader.WriteWavHeader(m, s);
            byte[] b = NormalizeWaveData(gStream.ToArray());
            m.Write(b, 0, b.Length);
            m.Flush();
            WavHeader.UpdateWavHeader(m);

            using (var tStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (tStore.FileExists("record.wav"))
                {
                    tStore.DeleteFile("record.wav");
                }
                using (var tFStream = new IsolatedStorageFileStream("record.wav", FileMode.Create, tStore))
                {
                    byte[] tByteInStream = m.ToArray();
                    tFStream.Write(tByteInStream, 0, tByteInStream.Length);
                    tFStream.Flush();
                    //MessageBox.Show("record.wav" + "保存成功!增加wavHeader并转存后的大小:" + m.Length.ToString());
                }
            }
            gStream = new MemoryStream();
        }
		public void Flush ()
		{
			IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication ();
			using (IsolatedStorageFileStream fs = new IsolatedStorageFileStream ("moon", FileMode.Create, isf)) {
				fs.Flush ();

				isf.Remove (); // this removed everything
				Assert.Throws (delegate { fs.Flush (); }, typeof (IsolatedStorageException), "Remove/Write"); // Fails in Silverlight 3
				isf.Dispose ();
				Assert.Throws (delegate { fs.Flush (); }, typeof (ObjectDisposedException), "Dispose/Write");
			}
			isf = IsolatedStorageFile.GetUserStoreForApplication ();
			Assert.AreEqual (0, isf.GetFileNames ().Length, "Empty");
		}
Exemple #29
0
        /// <summary>
        /// Enqueue a Web Service record into the record queue
        /// </summary>
        public static void EnqueueRequestRecord(RequestRecord newRecord)
        {
            bool enableQueueOptimization = false;  // turn off the queue optimization (doesn't work with introduction of tags)

            List<RequestRecord> requests = new List<RequestRecord>();
            DataContractJsonSerializer dc = new DataContractJsonSerializer(requests.GetType());

            if (newRecord.SerializedBody == null)
                newRecord.SerializeBody();

            using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
            {
                lock (fileLock)
                {
                    // if the file opens, read the contents
                    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(@"RequestRecords.xml", FileMode.OpenOrCreate, file))
                    {
                        try
                        {
                            // if the file opened, read the record queue
                            requests = dc.ReadObject(stream) as List<RequestRecord>;
                            if (requests == null)
                                requests = new List<RequestRecord>();
                        }
                        catch (Exception)
                        {
                            stream.Position = 0;
                            string s = new StreamReader(stream).ReadToEnd();
                        }

                        if (enableQueueOptimization == true)
                        {
                            OptimizeQueue(newRecord, requests);
                        }
                        else
                        {
                            // this is a new record so add the new record at the end
                            requests.Add(newRecord);
                        }

                        // reset the stream and write the new record queue back to the file
                        stream.SetLength(0);
                        stream.Position = 0;
                        dc.WriteObject(stream, requests);
                        stream.Flush();
                    }
                }
            }
        }
Exemple #30
0
        private static void WriteIsolatedStorage()
        {
            IsolatedStorageFileStream fs =
                new IsolatedStorageFileStream(
                    "thepath",
                    FileMode.Append,
                    FileAccess.Write,
                    FileShare.None);

            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine("hallo");
            sw.Flush();
            fs.Flush();
            sw.Close();
            fs.Close();
        }
        /// <summary>
        /// Copy the database from the resources in the app to the user's Isolated Storage.
        /// </summary>
        /// <param name="assemblyName"></param>
        /// <param name="dbName"></param>
        private void CopyFromContentToStorage()
        {
            //Get assembly for Resource Stream
            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();

            IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
            System.IO.Stream src = Application.GetResourceStream(new Uri("/" + assembly.FullName.Substring(0, assembly.FullName.IndexOf(',')) + ";component/" + Constants.Database.databasePath, UriKind.Relative)).Stream;

            IsolatedStorageFileStream dest = new IsolatedStorageFileStream(Constants.Database.databasePath, System.IO.FileMode.Create, System.IO.FileAccess.Write, store);
            src.Position = 0;
            CopyStream(src, dest);
            dest.Flush();
            dest.Close();
            src.Close();
        }