Esempio n. 1
0
    public static void DisplayFile(string path)
    {
        IsolatedStorageFileStream stream = new IsolatedStorageFileStream(path, FileMode.Create, store);
        if (stream != null)
        {
            try
            {
                using (StreamReader reader = new StreamReader(stream, Encoding.Unicode))
                {
                    string content = reader.ReadToEnd();
                }
            }
            catch
            {
                // silence IO error in case running from read-only media (CD/DVD)
            }
        }

        // display content here will not word for security resaons
        string fullpath = Path.GetFullPath(path);
        if (File.Exists(fullpath))
        {
            System.Diagnostics.Process.Start("Notepad.exe", fullpath);
        }
    }
Esempio n. 2
0
	private bool parseXMLFile(IsolatedStorageFileStream xmlFile)
	{
		values.Clear();

		string key = "";

		// Create an XmlReader
		using (XmlReader reader = XmlReader.Create(xmlFile)) {
			XmlWriterSettings ws = new XmlWriterSettings();
			ws.Indent = false;
				// Parse the file and display each of the nodes.
				while (reader.Read()) {
					switch (reader.NodeType) {
						case XmlNodeType.Element:
							key = reader.Name;
							break;
						case XmlNodeType.Text:
							values.Add(key, reader.Value);
							break;
						case XmlNodeType.XmlDeclaration:
						case XmlNodeType.ProcessingInstruction:
							break;
						case XmlNodeType.Comment:
							break;
						case XmlNodeType.EndElement:
							break;
					}
				}
		}
		return true;
	}
Esempio n. 3
0
 public static void SaveText(string path, string text)
 {
     IsolatedStorageFileStream stream = new IsolatedStorageFileStream(path, FileMode.Create, store);
     try
     {
         using (StreamWriter writer = new StreamWriter(stream, Encoding.Unicode))
         {
             writer.WriteLine(text);
         }
     }
     catch
     {
         // silence IO error in case running from read-only media (CD/DVD)
     }
 }
Esempio n. 4
0
 public static void SaveValues(string path, List<long> values)
 {
     IsolatedStorageFileStream stream = new IsolatedStorageFileStream(path, FileMode.Create, store);
     try
     {
         using (StreamWriter writer = new StreamWriter(stream, Encoding.Unicode))
         {
             foreach (long value in values)
             {
                 writer.WriteLine(value.ToString("000"));
             }
         }
     }
     catch
     {
         // silence IO error in case running from read-only media (CD/DVD)
     }
 }
Esempio n. 5
0
        /* Load highscores */
        public static HighScoreData LoadHighScores(string filename)
        {
            HighScoreData data;

            // Get the path of the save game
            string fullpath = "highscores.dat";

            #if WINDOWS

            // Open the file
            FileStream stream = File.Open(fullpath, FileMode.OpenOrCreate, FileAccess.Read);
            try
            {
                // Read the data from the file
                XmlSerializer serializer = new XmlSerializer(typeof(HighScoreData));
                data = (HighScoreData)serializer.Deserialize(stream);
            }
            finally
            {
                // Close the file
                stream.Close();
            }

            return (data);

            #elif XBOX

            using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fullpath, FileMode.Open,iso))
                {
                    // Read the data from the file
                    XmlSerializer serializer = new XmlSerializer(typeof(HighScoreData));
                    data = (HighScoreData)serializer.Deserialize(stream);
                }
            }

            return (data);

            #endif
        }
Esempio n. 6
0
 public static void SaveLetters(string path, char[] characters)
 {
     IsolatedStorageFileStream stream = new IsolatedStorageFileStream(path, FileMode.Create, store);
     try
     {
         using (StreamWriter writer = new StreamWriter(stream, Encoding.Unicode))
         {
             foreach (char character in characters)
             {
                 if (character == '\0')
                 {
                     break;
                 }
                 writer.Write(character);
             }
         }
     }
     catch
     {
         // silence IO error in case running from read-only media (CD/DVD)
     }
 }
Esempio n. 7
0
        public MainWindow()
        {
            IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForAssembly();

            InitializeComponent();
            string color;

            try
            {
                IsolatedStorageFileStream isolatedStorageFileStream =
                    new IsolatedStorageFileStream("ColorLabel.cfg",
                                                  FileMode.Open, FileAccess.Read, FileShare.Read);
                StreamReader reader = new StreamReader(isolatedStorageFileStream);
                color             = reader.ReadLine();
                Label1.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(color));
                Label1.Content    = color;
                reader.Close();
            }
            catch (Exception e)
            {
                Label1.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#00000000"));
                Label1.Content    = "#00000000";
            }
        }
Esempio n. 8
0
        private static string ReadFromFile(string endpointName, string fileName)
        {
            using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForAssembly())
            {
                if (!store.DirectoryExists(endpointName))
                {
                    return(null);
                }

                string path = endpointName + "\\" + fileName;
                if (!store.FileExists(path))
                {
                    return(null);
                }

                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(path, FileMode.Open, store))
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        return(reader.ReadToEnd());
                    }
                }
            }
        }
Esempio n. 9
0
        public static void UploadFile()
        {
            if (skyDriveFolderID != string.Empty) //the folder must exist, it should have already been created
            {
                client.UploadCompleted
                    += new EventHandler <LiveOperationCompletedEventArgs>(ISFile_UploadCompleted);

                try
                {
                    var fotoToSync = App.ViewModel.GetAllFotoToSync();

                    foreach (Foto ft in fotoToSync)
                    {
                        object[] state = new object[1];
                        state[0] = ft.FotoId;


                        using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile(ft.FotoPath, System.IO.FileMode.Create))
                            {
                                stream.Write(ft.FotoImage, 0, ft.FotoImage.Length);
                            }

                            readStream = myIsolatedStorage.OpenFile(ft.FotoPath, FileMode.Open);
                            client.UploadAsync(skyDriveFolderID, ft.FotoPath, true, readStream, ft.FotoId);
                        }
                    }
                }

                catch
                {
                    MessageBox.Show("Błąd dostępu IsolatedStorage. Proszę zamknąć aplikację i otworzyć ją ponownie, a następnie spróbuj ponownie stworzenie kopii zapasowyej!", "Backup Failed", MessageBoxButton.OK);
                }
            }
        }
Esempio n. 10
0
        public Entity.Configure Read()
        {
            Entity.Configure EntityConfig = new Entity.Configure();

            var ConfigFile = IsolatedStorageFile.GetUserStoreForApplication();

            if (!IsolatedStorageFileExists(_ConfigFileName))
            {
                CreateConfigFIle();
            }

            using (IsolatedStorageFileStream StrageFileStream = ConfigFile.OpenFile(_ConfigFileName, FileMode.Open))
                using (StreamReader reader = new StreamReader(StrageFileStream))
                {
                    var JsonConfig = JsonConvert.DeserializeObject <Entity.Configure>(reader.ReadToEnd());
                    EntityConfig.UriAdress  = JsonConfig.UriAdress;
                    EntityConfig.FolderName = JsonConfig.FolderName;
                    EntityConfig.User       = JsonConfig.User;
                    EntityConfig.Password   = JsonConfig.Password;
                    EntityConfig.Domain     = JsonConfig.Domain;
                }

            return(EntityConfig);
        }
    private static void WriteIsolatedStorage()
    {
        // Attempt to create a storage file that is isolated by user and assembly.
        // IsolatedStorageFilePermission granted to the attribute at the top of this file
        // allows CLR to load this assembly and execution of this statement.
        using (Stream s = new IsolatedStorageFileStream("AssemblyData", FileMode.Create, IsolatedStorageFile.GetUserStoreForAssembly()))
        {
            // Write some data out to the isolated file.
            using (StreamWriter sw = new StreamWriter(s))
            {
                sw.Write("This is some test data.");
            }
        }

        // Attempt to open the file that was previously created.
        using (Stream s = new IsolatedStorageFileStream("AssemblyData", FileMode.Open, IsolatedStorageFile.GetUserStoreForAssembly()))
        {
            // Read the data from the file and display it.
            using (StreamReader sr = new StreamReader(s))
            {
                Console.WriteLine(sr.ReadLine());
            }
        }
    }
Esempio n. 12
0
        /// <summary>
        /// Retrieves Key from File
        /// </summary>
        /// <param name="fileName">Name of file which contains key</param>
        private string GetValueFromIsolatedStorage(string fileName)
        {
            string value = null;

            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null))
            {
                try
                {
                    using (var iStream = new IsolatedStorageFileStream(fileName, FileMode.Open, isoStore))
                    {
                        using (var reader = new StreamReader(iStream))
                        {
                            value = reader.ReadLine();
                        }
                    }
                }
                catch (FileNotFoundException)
                {
                    value = null;
                }
            }

            return(value);
        }
Esempio n. 13
0
 private void SaveLogToFile()
 {
     using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
     {
         IsolatedStorageFileStream fs = null;
         try
         {
             if (storage != null)
             {
                 fs = storage.CreateFile(_logFile);
                 using (StreamWriter writer = new StreamWriter(fs))
                 {
                     Logger.Save(writer);
                     fs = null;
                 }
             }
         }
         finally
         {
             //if (fs != null)
             //    fs.Dispose();
         }
     }
 }
Esempio n. 14
0
        private void LoadLauncherConfig()
        {
            try
            {
                //try and load a launcher configuration from isolated storage
                using (var isoStore = IsolatedStorageFile.GetUserStoreForAssembly())
                {
                    var configFile = new IsolatedStorageFileStream(ConfigFile, FileMode.Open, FileAccess.Read, isoStore);
                    using (var sr = new StreamReader(configFile))
                    {
                        //read the concrete type to deserialize
                        var launcherTypeName = sr.ReadLine();
                        var launcherType     = Type.GetType(launcherTypeName, true);

                        //read the actual object
                        XmlSerializer serializer = new XmlSerializer(launcherType);
                        m_launcher = (ILauncher)serializer.Deserialize(sr);

                        //select the correct item in the combo box
                        foreach (TypeEntry item in m_appTypeCombo.Items)
                        {
                            if (item.Type == launcherType)
                            {
                                m_appTypeCombo.SelectedItem = item;
                                break;
                            }
                        }
                    }
                    isoStore.Close();
                }
            }
            catch
            {
                //couldn't load the launcher, for whatever reason
            }
        }
Esempio n. 15
0
    //</snippet3>

    //<snippet2>
    public double SetPrefsForUser()
    {
        try
        {
            //<snippet10>
            IsolatedStorageFile isoFile;
            isoFile = IsolatedStorageFile.GetUserStoreForDomain();

            // Open or create a writable file.
            IsolatedStorageFileStream isoStream =
                new IsolatedStorageFileStream(this.userName,
                                              FileMode.OpenOrCreate,
                                              FileAccess.Write,
                                              isoFile);

            StreamWriter writer = new StreamWriter(isoStream);
            writer.WriteLine(this.NewsUrl);
            writer.WriteLine(this.SportsUrl);
            // Calculate the amount of space used to record the user's preferences.
            double d = isoFile.CurrentSize / isoFile.MaximumSize;
            Console.WriteLine("CurrentSize = " + isoFile.CurrentSize.ToString());
            Console.WriteLine("MaximumSize = " + isoFile.MaximumSize.ToString());
            // StreamWriter.Close implicitly closes isoStream.
            writer.Close();
            isoFile.Dispose();
            isoFile.Close();
            return(d);
            //</snippet10>
        }
        catch (IsolatedStorageException ex)
        {
            // Add code here to handle the exception.
            Console.WriteLine(ex);
            return(0.0);
        }
    }
Esempio n. 16
0
        /// <summary>
        /// Retreive encrypted Data from the isolated storage
        /// </summary>
        /// <param name="dataIdentifier">identifier for the data to read</param>
        /// <returns>Decrypted string or null if no value has been stored for the given dataIdentifier</returns>
        public string RetrieveProtectedString(string dataIdentifier)
        {
            IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();

            byte[] protectedData;
            try
            {
                using (IsolatedStorageFileStream readstream = new IsolatedStorageFileStream(dataIdentifier + ".crypt", FileMode.Open, FileAccess.Read, file))
                {
                    using (Stream reader = new StreamReader(readstream).BaseStream)
                    {
                        protectedData = new byte[reader.Length];
                        reader.Read(protectedData, 0, protectedData.Length);
                    }
                }
            }
            catch (IsolatedStorageException)
            {
                return(null);
            }

            byte[] dataBytes = ProtectedData.Unprotect(protectedData, Encoding.UTF8.GetBytes("hockeyAppIsCool"));
            return(Encoding.UTF8.GetString(dataBytes, 0, dataBytes.Length));
        }
Esempio n. 17
0
        public Boolean IsStale(TimeSpan shelfLife)
        {
            Boolean result = true;

            if (!this.lastModifiedFileName.Equals(String.Empty))
            {
                TextReader textReader = null;
                try
                {
                    IsolatedStorageFile       isoStorage = IsolatedStorageFile.GetUserStoreForApplication();
                    IsolatedStorageFileStream file       = isoStorage.OpenFile(this.lastModifiedFileName, FileMode.OpenOrCreate);
                    textReader = new StreamReader(file);
                    DateTime lastModifiedDate;
                    if (DateTime.TryParse(textReader.ReadLine(), out lastModifiedDate))
                    {
                        if ((DateTime.Now - lastModifiedDate) < shelfLife)
                        {
                            result = false;
                        }
                    }
                    textReader.Close();
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(e.Message);
                }
                finally
                {
                    if (textReader != null)
                    {
                        textReader.Dispose();
                    }
                }
            }
            return(result);
        }
Esempio n. 18
0
        public void SaveAll(List <T> genericList)
        {
            TextWriter textWriter = null;

            try
            {
                IsolatedStorageFile       isoStorage = IsolatedStorageFile.GetUserStoreForApplication();
                IsolatedStorageFileStream file       = isoStorage.OpenFile(this.fileName, FileMode.Create);
                textWriter = new StreamWriter(file);
                DataContractSerializer serializer = new DataContractSerializer(typeof(List <T>));
                serializer.WriteObject(file, genericList);
                textWriter.Close();

                if (this.lastModifiedFileName != null)
                {
                    if (!this.lastModifiedFileName.Equals(String.Empty))
                    {
                        IsolatedStorageFileStream lastModifiedFile = isoStorage.OpenFile(this.lastModifiedFileName, FileMode.Create);
                        textWriter = new StreamWriter(lastModifiedFile);
                        textWriter.WriteLine(DateTime.Now.ToString());
                        textWriter.Close();
                    }
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
            }
            finally
            {
                if (textWriter != null)
                {
                    textWriter.Dispose();
                }
            }
        }
Esempio n. 19
0
        public void Save()
        {
            try
            {
                XDocument doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), new XElement("root"));

                XElement settingsNode = new XElement("Settings");
                doc.Root.Add(settingsNode);

                settingsNode.Add(
                    new XElement("IsFullScreen", IsFullScreen.ToString()),
                    new XElement("EnableMusic", EnableMusic.ToString()),
                    new XElement("ControlType1", ControlType1.ToString()),
                    new XElement("ShowSpawnTimer", ShowSpawnTimer.ToString()),
                    new XElement("SkipTutorial", ShowSpawnTimer.ToString()),
                    new XElement("ShowRoundGUI", ShowRoundGUI.ToString()),
                    new XElement("RoundGUIAlpha", RoundGUIAlpha.ToString())
                    );


                // Save
#if WINDOWS
                doc.Save(Path, SaveOptions.None);
#endif
#if XBOX
                if (FileStorage.FileExists(Path))
                {
                    FileStorage.DeleteFile(Path);
                }
                IsolatedStorageFileStream stream = FileStorage.CreateFile(Path);
                doc.Save(stream);
                stream.Close();
#endif
            }
            catch { }
        }
        public void CompressIsolatedStorageFileTest()
        {
            string inputString = "".PadRight(1000, 'z');

            byte[] inputBytes = Encoding.UTF8.GetBytes(inputString);

            IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForDomain();

            //Create the input file
            string inputFilePath = "InputFile.txt";

            using (IsolatedStorageFileStream outputStream = new IsolatedStorageFileStream(inputFilePath, FileMode.Create, FileAccess.Write, FileShare.None, store))
            {
                outputStream.Write(inputBytes, 0, inputBytes.Length);
            }

            //Compress it
            string      compressedPath = "Compressed.txt";
            Compression compression    = new Compression(store);

            compression.CompressIsolatedStorageFile(CompressionType.MiniLZO, inputFilePath, compressedPath);

            //Decompress
            string uncompressedPath = "Uncompressed.txt";

            compression.DecompressIsolatedStorageFile(CompressionType.MiniLZO, compressedPath, uncompressedPath);

            byte[] decompressedBytes = new byte[inputBytes.Length];

            using (IsolatedStorageFileStream inputStream = new IsolatedStorageFileStream(uncompressedPath, FileMode.Open, FileAccess.Read, FileShare.Read, store))
            {
                inputStream.Read(decompressedBytes, 0, inputBytes.Length);
            }

            Assert.AreEqual(inputBytes, decompressedBytes);
        }
Esempio n. 21
0
        /// <summary>
        /// Saves user settings to isolated storage.  The data is stored with the user's roaming profile.
        /// </summary>
        /// <remarks>
        /// Non-critical exceptions are handled by writing an error message in the output window.
        /// </remarks>
        public static void Save(object userSettings, string providerId, string name, Action onSaved, ConnectedServiceLogger logger)
        {
            var fileName = UserSettingsPersistenceHelper.GetStorageFileName(providerId, name);

            UserSettingsPersistenceHelper.ExecuteNoncriticalOperation(
                () =>
            {
                using (var file = UserSettingsPersistenceHelper.GetIsolatedStorageFile())
                {
                    IsolatedStorageFileStream stream = null;
                    try
                    {
                        // note: this overwrites existing settings file if it exists
                        stream = file.OpenFile(fileName, FileMode.Create);
                        using (var writer = XmlWriter.Create(stream))
                        {
                            stream = null;

                            var dcs = new DataContractSerializer(userSettings.GetType());
                            dcs.WriteObject(writer, userSettings);

                            writer.Flush();
                        }
                    }
                    finally
                    {
                        stream?.Dispose();
                    }
                }

                onSaved?.Invoke();
            },
                logger,
                "Failed loading the {0} user settings",
                fileName);
        }
Esempio n. 22
0
        /// <summary>
        /// 프로그램 시작시 즐겨찾기 목록 파일에서 불러와 초기화
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInitialized(EventArgs e)
        {
            base.OnInitialized(e);

            IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForAssembly();

            using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("myFile", FileMode.OpenOrCreate, file))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    while (reader.Peek() > -1)
                    {
                        AddFavorite(reader.ReadLine());
                    }
                }
            }

            if (!trvFavoriteData.HasItems)
            {
                AddFavorite(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures));
            }

            (trvFavoriteData.Items[0] as TreeViewItem).IsSelected = true;
        }
Esempio n. 23
0
        public static void WriteTextToIsolatedStorageFile(string fileName, string writeThis)
        {
            IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();

            if (!myIsolatedStorage.FileExists(fileName))
            {
                //Write to new file
                using (StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream(fileName, FileMode.Create, FileAccess.Write, myIsolatedStorage)))
                {
                    writeFile.WriteLine(writeThis);
                    writeFile.Close();
                }
            }
            else
            {
                //Write to existing file
                IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(fileName, FileMode.Open, FileAccess.Write);
                using (StreamWriter writer = new StreamWriter(fileStream))
                {
                    writer.Write(writeThis);
                    writer.Close();
                }
            }
        }
Esempio n. 24
0
        private void SalvarFoto(BitmapImage img)
        {
            using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
            {
                WriteableBitmap bmp = new WriteableBitmap(img);

                if (!iso.DirectoryExists("Imagens"))
                {
                    iso.CreateDirectory("Imagens");
                }

                using (IsolatedStorageFileStream stream = iso.OpenFile(@"Imagens\foto.jpg", FileMode.OpenOrCreate))
                {
                    Extensions.SaveJpeg(
                        bmp,
                        stream,
                        bmp.PixelWidth,
                        bmp.PixelHeight,
                        0,
                        100
                        );
                }
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Saves a BitmapImage as a JPEG file in the local storage
        /// </summary>
        /// <param name="image">The bitmap image to save</param>
        /// <param name="fileName">The file's name to use</param>
        /// <returns>true if the operation succeeds</returns>
        public static string SaveImageInLocalFolder(BitmapImage image, string fileName)
        {
            try
            {
                using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (!store.DirectoryExists(LOCAL_IMAGES_PATH))
                    {
                        store.CreateDirectory(LOCAL_IMAGES_PATH);
                    }
                    string filePath = Path.Combine(LOCAL_IMAGES_PATH, fileName);
                    if (store.FileExists(filePath))
                    {
                        store.DeleteFile(filePath);
                    }

                    using (IsolatedStorageFileStream file = store.CreateFile(filePath))
                    {
                        WriteableBitmap bitmap = new WriteableBitmap(image);
                        Extensions.SaveJpeg(bitmap, file, bitmap.PixelWidth, bitmap.PixelHeight, 0, LOCAL_IMAGES_QUALITY);
                        file.Flush();
                        string hash = GetRandomHash();
                        file.Close();
                        bitmap = null;
                        string newFilePath = Path.Combine(LOCAL_IMAGES_PATH, hash + Path.GetExtension(filePath));
                        store.MoveFile(filePath, newFilePath);
                        IsolatedStorageFileStream newFile = store.OpenFile(newFilePath, FileMode.Open);
                        fileName = newFile.Name;
                        newFile.Close();
                        return(fileName);
                    }
                }
            }
            catch { }
            return(null);
        }
            public CacheIsolatedStorageItem(ResultClass value, IsolatedStorageFile isf, long key, DateTime expireAt) : base(value)
            {
                IsolatedStorageFileStream isfsValue, isfsExpire, isfsKey;

                string path = Path.Combine("cache", key.GetHashCode().ToString());

                isf.CreateDirectory(path);


                long   keyCandidate = ResolveKeyCollision(path, isf, key);
                string suffix       = "-" + keyCandidate;



                isfsKey = new IsolatedStorageFileStream(Path.Combine(path, "key" + suffix),
                                                        FileMode.Create, FileAccess.Write, isf);
                StreamWriter sWriter = new StreamWriter(isfsKey);

                sWriter.Write(key.ToString());
                sWriter.Close();

                this.expireAt = expireAt;
                isfsExpire    = new IsolatedStorageFileStream(Path.Combine(path, "expireAt" + suffix),
                                                              FileMode.Create, FileAccess.Write, isf);
                sWriter = new StreamWriter(isfsExpire);
                sWriter.Write(expireAt.ToBinary());
                sWriter.Close();


                isfsValue = new IsolatedStorageFileStream(Path.Combine(path, "value" + suffix), FileMode.Create,
                                                          FileAccess.Write, isf);
                BinaryFormatter bf = new BinaryFormatter();

                bf.Serialize(isfsValue, value);
                isfsValue.Close();
            }
Esempio n. 27
0
        public static Settings Load()
        {
            Settings result = null;

            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream("Settings.xml", FileMode.OpenOrCreate, isf))
                {
                    using (StreamReader Reader = new StreamReader(isfs))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(Settings));
                        try
                        {
                            result = (Settings)serializer.Deserialize(Reader);
                        }
                        catch
                        {
                            result = new Settings();
                        }
                    }
                }
            }
            return(result);
        }
Esempio n. 28
0
        public static void WriteImageToIsolatedStorage(Stream imageStream, List <ImageInfo> images)
        {
            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                BitmapImage bitmap;

                foreach (ImageInfo imgInfo in images)
                {
                    if (!string.IsNullOrEmpty(imgInfo.Directory) && !myIsolatedStorage.DirectoryExists(imgInfo.Directory))
                    {
                        myIsolatedStorage.CreateDirectory(imgInfo.Directory);
                    }

                    string path = System.IO.Path.Combine(imgInfo.Directory, imgInfo.FileName);
                    IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(path);

                    // saves images that are not square in shape
                    if (!imgInfo.IsSquare)
                    {
                        bitmap = new BitmapImage();
                        bitmap.SetSource(imageStream);

                        WriteableBitmap wb = new WriteableBitmap(bitmap);
                        wb.SaveJpeg(fileStream, imgInfo.Width, imgInfo.Height, 0, 85);
                    }
                    else
                    {
                        // resizes images to a square for use with thumbnails
                        WriteableBitmap wb = GeneralMethods.ResizeImageToSquare(imageStream, imgInfo.SquareSize);
                        wb.SaveJpeg(fileStream, imgInfo.SquareSize, imgInfo.SquareSize, 0, 70);
                    }

                    fileStream.Close();
                }
            }
        }
Esempio n. 29
0
        /// <summary>
        /// Loads an audio buffer from isolated storage.
        /// </summary>
        public void LoadAudioBuffer(String fileName)
        {
            // Set the stream back to zero in case there is already something in it
            stream.SetLength(0);

            // Retrieve the named audio file from the storage.
            IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();

            try
            {
                using (var isoFileStream = new IsolatedStorageFileStream(
                           fileName,
                           FileMode.Open,
                           myStore))
                {
                    isoFileStream.CopyTo(stream);
                    stream.Flush();
                }
            }
            catch
            {
                MessageBox.Show("Error while trying to load audio buffer.");
            }
        }
Esempio n. 30
0
        void LoadCredentialsFromIsolatedStorage()
        {
            string tempCredentialsString = null;

            IsolatedStorageFile credentialsStore = IsolatedStorageFile.GetUserStoreForApplication();

            using (var isoFileStream = new IsolatedStorageFileStream("Linq2TwitterCredentials.txt", FileMode.OpenOrCreate, credentialsStore))
            {
                using (var isoFileReader = new StreamReader(isoFileStream))
                {
                    tempCredentialsString = isoFileReader.ReadLine();
                }
            }

            if (tempCredentialsString != null)
            {
                string[] tempCredentialsArr = tempCredentialsString.Split(',');

                for (int i = 0; i < tempCredentialsArr.Length; i++)
                {
                    credentials[i] = tempCredentialsArr[i];
                }
            }
        }
Esempio n. 31
0
	private static void WriteIsolatedStorage()
	{
		// Attempt to create a storage file that is isolated by user and assembly. 
		// IsolatedStorageFilePermission granted to the attribute at the top of this file  
		// allows CLR to load this assembly and execution of this statement. 
		using (Stream s = new IsolatedStorageFileStream("AssemblyData", FileMode.Create, IsolatedStorageFile.GetUserStoreForAssembly()))
		{
			// Write some data out to the isolated file. 
			using (StreamWriter sw = new StreamWriter(s))
			{
				sw.Write("This is some test data.");
			}
		}

		// Attempt to open the file that was previously created. 
		using (Stream s = new IsolatedStorageFileStream("AssemblyData", FileMode.Open, IsolatedStorageFile.GetUserStoreForAssembly()))
		{
			// Read the data from the file and display it. 
			using (StreamReader sr = new StreamReader(s))
			{
				Console.WriteLine(sr.ReadLine());
			}
		}
	}
Esempio n. 32
0
        private static void MoveToIsolatedStorage(string path)
        {
            var store = IsolatedStorageFile.GetUserStoreForApplication();

            if (store.GetFileNames(path).Length != 0)
            {
                return;
            }

            using (var target = new IsolatedStorageFileStream(path, FileMode.Create, store))
            {
                path = string.Format("Demo.WindowsPhone.{0}", path);

                using (var source = Assembly.GetExecutingAssembly().GetManifestResourceStream(path))
                {
                    if (source != null)
                    {
                        var content = new byte[source.Length];
                        source.Read(content, 0, content.Length);
                        target.Write(content, 0, content.Length);
                    }
                }
            }
        }
Esempio n. 33
0
        public static void SavePrefs(string fileName)
        {
            SerializablePrefs prefs = new SerializablePrefs();

            prefs.ffmpegPath               = ffmpegPath.Trim();
            prefs.ffprobePath              = ffprobePath.Trim();
            prefs.cutOutputDir             = cutOutputDir.Trim();
            prefs.cutHighlightOnCompletion = cutHighlightOnCompletion;

            var userStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);

            try
            {
                using (var stream = new IsolatedStorageFileStream(fileName, FileMode.OpenOrCreate, userStore))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(SerializablePrefs));
                    serializer.Serialize(stream, prefs);
                }
            } catch (FileNotFoundException e)
            {
                Debug.WriteLine("Somehow, preferences.xml was not found.");
                Debug.WriteLine(e);
            }
        }
Esempio n. 34
0
 private void Save_Click(object sender, RoutedEventArgs e)
 {
     if (nama.Text != "")
     {
         try
         {
             app.Filename = nama.Text.Trim().ToLower();
             using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
             {
                 IsolatedStorageFileStream location = new IsolatedStorageFileStream(app.Filename,
                                                                                    System.IO.FileMode.Create, storage);
                 System.IO.StreamWriter file = new System.IO.StreamWriter(location);
                 file.Write(app.Content);
                 file.Dispose();
                 location.Dispose();
             }
             NavigationService.GoBack();
         }
         catch
         {
             // Ignore Errors
         }
     }
 }
Esempio n. 35
0
        private async void encode(object sender, RoutedEventArgs e)
        {
            // player.Stop();
            LameWrapper lame = new LameWrapper();

            lame.InitialLame(44100, 44100, 2, 5);
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();

            using (IsolatedStorageFileStream WorkStream = isf.CreateFile("encoded_mp3.mp3"))
            {
                using (PCMStream = isf.OpenFile("/decoded_pcm.pcm", FileMode.Open))
                {
                    int totalread = 0;
                    while (PCMStream.Position < PCMStream.Length)
                    {
                        byte[] rawbytes = new byte[65536];

                        int actualcount = PCMStream.Read(rawbytes, 0, 65536);
                        //  MessageBox.Show("read:" + actualcount);
                        totalread         += actualcount;
                        PCMStream.Position = totalread;
                        IBuffer PCMSampleBuffer = WindowsRuntimeBufferExtensions.AsBuffer(rawbytes, 0, rawbytes.Length);

                        CompressedMp3Content citem = await lame.EncodePcm2Mp3(PCMSampleBuffer);

                        //  MessageBox.Show(citem.Mp3Data.Length+"");
                        WorkStream.Write(citem.Mp3Data, 0, citem.Mp3Data.Length);
                        WorkStream.Flush();
                        statustb.Text = "position: " + PCMStream.Position + " total: " + PCMStream.Length;
                    }
                }
            }

            isf.Dispose();
            lame.CloseLame();
        }
 /// <summary>
 /// 根据键值加载独立存储区的内容
 /// </summary>
 /// <param name="key">独立存储的键值(路径)</param>
 /// <returns></returns>
 public static object Load(string key)
 {
     try
     {
         using (IsolatedStorageFile store = IsolatedStorageFile.GetStore(IsolatedStorageScope.User |
                                                                         IsolatedStorageScope.Assembly | IsolatedStorageScope.Domain, null, null))
         {
             using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(key, FileMode.Open, FileAccess.Read, store))
             {
                 stream.Position = 0;
                 BinaryFormatter deserializer = new BinaryFormatter();
                 return(deserializer.Deserialize(stream));
             }
         }
     }
     catch (FileNotFoundException)
     {
         return(null);
     }
     catch (SerializationException)
     {
         return(null);
     }
 }
Esempio n. 37
0
        private void Login(object sender, RoutedEventArgs e)
        {
            if (UsrName.Text == "" | PswdBox.Password == "")
            {
                MessageBox.Show("Please fill the username and passwordbox");
            }
            else
            {
                try
                {
                    PhoneApp2.VastariAPI.VastariAPIServiceClient client = new VastariAPI.VastariAPIServiceClient();
                    client.LoginCompleted += clients_login_done;
                    client.LoginAsync(UsrName.Text, PswdBox.Password);
                    client.CloseAsync();
                    using (IsolatedStorageFile isoStorage = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        using (IsolatedStorageFileStream stream = isoStorage.OpenFile("pincode.txt", FileMode.Open))
                        {
                            NavigationService.Navigate(new Uri("/Login.xaml", UriKind.Relative));
                        }
                    }
                }

                catch (IsolatedStorageException)
                {
                    MessageBox.Show("1st time Login", "Please set a 4 digit pincode.", MessageBoxButton.OK);
                    NavigationService.Navigate(new Uri("/PinCode.xaml", UriKind.Relative));
                    NavigationService.Navigate(new Uri("/Login.xaml", UriKind.Relative));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
        }
Esempio n. 38
0
    //    public static int NOPH_ZLib_compress(int i_in_path, int i_in_file_name, int i_out_path, int i_out_file_name, int compression_level)
    //{
    // String in_path = CRunTime.charPtrToString(i_in_path);
    // String in_file_name = CRunTime.charPtrToString(i_in_file_name);
    // String out_path = CRunTime.charPtrToString(i_out_path);
    // String out_file_name = CRunTime.charPtrToString(i_out_file_name);
    // net.rim.device.api.compress.GZIPOutputStream zout = null;
    // javax.microedition.io.file.FileConnection fConnIn = null;
    // javax.microedition.io.file.FileConnection fConnOut = null;
    // Stream os = null;
    // Stream iis = null;
    // try {
    //       long in_file_size;
    //       fConnIn = (javax.microedition.io.file.FileConnection)Connector.open(in_path + "/" + in_file_name);
    //    fConnOut = (javax.microedition.io.file.FileConnection)Connector.open(out_path + "/" + out_file_name);
    //    if (!fConnOut.exists())
    //     fConnOut.create(); // create the file if it doesn't exist
    //    iis = fConnIn.openInputStream();
    //    in_file_size = fConnIn.fileSize();
    //    os = fConnOut.openOutputStream();
    //    zout = new net.rim.device.api.compress.GZIPOutputStream(os, compression_level, net.rim.device.api.compress.GZIPOutputStream.MAX_LOG2_WINDOW_LENGTH);
    //    // write into file
    //    for (long i = 0; i < in_file_size; i++){
    //     zout.write(iis.read());
    //    }
    //    // flush before end
    //    zout.flush();
    //    // success
    //    return 0;
    // }
    // catch (Exception e) {
    //  UIWorker.addUIEventLog("NOPH_ZLib_compress Exception in compressing "+ e.toString());
    // }finally {
    //    // try to close stream
    //    try{
    //    if(zout!=null)
    //          zout.close();
    //       if(fConnIn!=null)
    //       fConnIn.close();
    //       if(fConnOut!=null)
    //       fConnOut.close();
    //       if(os!=null)
    //       os.close();
    //       if(iis!=null)
    //       iis.close();
    //  }catch(Exception e){
    //      Console.WriteLine("zout.close()");
    //  }
    // }
    // return 1;
    //}
    public static int NOPH_ZLib_uncompress(int uncompressedAddr, int uncompressedSizeAddr, int compressedAddr, int compressedSize)
    {
        function_info fi = new function_info("NOPH_ZLib_uncompress");

        //todomt - do better job
        int uncompressedSizeRead = 0;
        FileStream fs = null;
        try
        {
            var store = IsolatedStorageFile.GetUserStoreForApplication();
            CRunTimeMemoryInputStream mis = new CRunTimeMemoryInputStream(compressedAddr, compressedSize);
            fs = new IsolatedStorageFileStream("temp.gz", FileMode.Create, FileAccess.Write, store);
            int b = mis.read();
            while (b != -1)
            {
                fs.WriteByte((byte)b);
                b = mis.read();
            }

            fs.Close();

            fs = new IsolatedStorageFileStream("temp.gz", FileMode.Open, FileAccess.Read, store);
            ZInputStream zis = new ZInputStream(fs);

            int uncompressedSizeAllocated = CRunTime.memoryReadWord(uncompressedSizeAddr);

            int val = 0;
            while (((uncompressedAddr & 0x3) != 0) && (uncompressedSizeAllocated > 0) && ((val = zis.ReadByte()) != -1))
            {
                CRunTime.memoryWriteByte(uncompressedAddr++, val);
                ++uncompressedSizeRead;
                --uncompressedSizeAllocated;
            }

            while ((val != -1) && (uncompressedSizeAllocated > 3))
            {
                int i = 0;
                for (int j = 0; j < 4; j++)
                {
                    i = i << 8;

                    // replace the below with val = zis.ReadByte() & 0xff; if changing zlib implementation
                    val = zis.Read() & 0xff;

                    i |= val;
                }

                CRunTime.memoryWriteWord(uncompressedAddr, i);
                uncompressedAddr += 4;
                uncompressedSizeRead += 4;
                uncompressedSizeAllocated -= 4;
            }

            while ((uncompressedSizeAllocated > 0) && (val = zis.ReadByte()) != -1)
            {
                CRunTime.memoryWriteByte(uncompressedAddr++, val);
                ++uncompressedSizeRead;
                --uncompressedSizeAllocated;
            }

            CRunTime.memoryWriteWord(uncompressedSizeAddr, uncompressedSizeRead);

            return 1;
        }
        catch (Exception ex)
        {
            Logger.log("Exception: " + ex.ToString());
            Logger.log("compressedSize " + compressedSize + " uncompressedSizeRead " + uncompressedSizeRead + " Exception: " + ex);

                    fis.Add(fi.setFinishTime());

            return 0;
        }
        finally
        {
            if (fs != null)
            {
                fs.Close();
            }
        }
                fis.Add(fi.setFinishTime());
    }
Esempio n. 39
0
    private void InitializeFromIsolatedStorage()
    {
        using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForAssembly())
        using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream("UserSettings.xml", System.IO.FileMode.OpenOrCreate, isf))
        {
            System.Xml.XmlDocument xmldoc = new XmlDocument();
            try
            {
                xmldoc.Load(isfs);

                this.textboxPattern.Text = xmldoc.SelectSingleNode(@"/UserSettings/LastPattern").InnerText;
            }
            catch (XmlException ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }
    }
    public double SetPrefsForUser()
    {
        try
        {
            IsolatedStorageFile isoFile;
            isoFile = IsolatedStorageFile.GetUserStoreForDomain();

            // Open or create a writable file.
            IsolatedStorageFileStream isoStream =
                new IsolatedStorageFileStream(this.userName,
                FileMode.OpenOrCreate,
                FileAccess.Write,
                isoFile);

            StreamWriter writer = new StreamWriter(isoStream);
            writer.WriteLine(this.NewsUrl);
            writer.WriteLine(this.SportsUrl);
            // Calculate the amount of space used to record the user's preferences.
            double d = isoFile.CurrentSize / isoFile.MaximumSize;
            Console.WriteLine("CurrentSize = " + isoFile.CurrentSize.ToString());
            Console.WriteLine("MaximumSize = " + isoFile.MaximumSize.ToString());
            // StreamWriter.Close implicitly closes isoStream.
            writer.Close();
            isoFile.Dispose();
            isoFile.Close();
            return d;
        }
        catch (IsolatedStorageException ex)
        {
            // Add code here to handle the exception.
            Console.WriteLine(ex);
            return 0.0;
        }
    }
    private bool GetPrefsForUser()
    {
        try
        {

            // Retrieve an IsolatedStorageFile for the current Domain and Assembly.
            IsolatedStorageFile isoFile =
                IsolatedStorageFile.GetStore(IsolatedStorageScope.User |
                IsolatedStorageScope.Assembly |
                IsolatedStorageScope.Domain,
                null,
                null);

            IsolatedStorageFileStream isoStream =
                new IsolatedStorageFileStream(this.userName,
                FileMode.Open,
                FileAccess.Read,
                FileShare.Read);

            // The code executes to this point only if a file corresponding to the username exists.
            // Though you can perform operations on the stream, you cannot get a handle to the file.

            try
            {

                SafeFileHandle aFileHandle = isoStream.SafeFileHandle;
                Console.WriteLine("A pointer to a file handle has been obtained. "
                    + aFileHandle.ToString() + " "
                    + aFileHandle.GetHashCode());
            }

            catch (Exception e)
            {
                // Handle the exception.
                Console.WriteLine("Expected exception");
                Console.WriteLine(e);
            }

            StreamReader reader = new StreamReader(isoStream);
            // Read the data.
            this.NewsUrl = reader.ReadLine();
            this.SportsUrl = reader.ReadLine();
            reader.Close();
            isoFile.Close();
            return false;
        }
        catch (System.IO.FileNotFoundException)
        {
            // Expected exception if a file cannot be found. This indicates that we have a new user.
            return true;
        }
    }
Esempio n. 42
0
        public static FileStream GetStreamForSavedXamlFile(string savedDataPath, FileMode mode)
        {
#if XamlPadExpressApp
            // Get a store from Isolated Storage and see if xamlpad_saved.xaml exists
            // for this user/application.
            IsolatedStorageFile isoStore;
            try
            {
                isoStore = IsolatedStorageFile.GetUserStoreForApplication();
            }

            catch (SecurityException)
            {
                // Just return null as if the saved file wasn't there.
                return null;
            }

            // Get a stream for this file
            try
            {
                IsolatedStorageFileStream stream = new IsolatedStorageFileStream(
                    savedXamlFileName,
                    mode,
                    isoStore);

                return stream;
            }

            catch (FileNotFoundException)
            {
                // We are trying to open an existing file but it's not there.
                // Just return null and we'll default to the initial content.
                return null;
            }

            catch (IsolatedStorageException e)
            {
                // Isolated Storage permissions may not be granted to this user.
                return null;
            }

#else
            // Use the rules for reading/writing the saved file -- if the app was deployed
            // with ClickOnce, it goes to/from the user's desktop, otherwise the current 
            // directory is used.
            try
            {
                FileStream stream = new FileStream(savedDataPath, mode);
                return stream;
            }

            catch (UnauthorizedAccessException)
            {
                return null;
            }

            catch (SecurityException)
            {
                return null;
            }

            catch (FileNotFoundException)
            {
                return null;
            }
            catch (IOException)
            {
                return null;
            }
#endif
        }
Esempio n. 43
0
 public static void SaveWords(string path, List<string> words)
 {
     IsolatedStorageFileStream stream = new IsolatedStorageFileStream(path, FileMode.Create, store);
     try
     {
         using (StreamWriter writer = new StreamWriter(stream, Encoding.Unicode))
         {
             foreach (string word in words)
             {
                 if (String.IsNullOrEmpty(word))
                 {
                     break;
                 }
                 writer.Write(word);
             }
         }
     }
     catch
     {
         // silence IO error in case running from read-only media (CD/DVD)
     }
 }
Esempio n. 44
0
	public bool CreateIfNotExists()
	{
		bool created = false;
		using (var db = new OmnibussDataContext(OmnibussDataContext.ConnectionString))
		{
			if (!db.DatabaseExists())
			{
				string[] names = this.GetType().Assembly.GetManifestResourceNames();
				string name = names.Where(n => n.EndsWith(FileName)).FirstOrDefault();
				if (name != null)
				{
					using (Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name))
					{
						if (resourceStream != null)
						{
							using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
							{
								using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(FileName, FileMode.Create, myIsolatedStorage))
								{
									using (BinaryWriter writer = new BinaryWriter(fileStream))
									{
										long length = resourceStream.Length;
										byte[] buffer = new byte[32];
										int readCount = 0;
										using (BinaryReader reader = new BinaryReader(resourceStream))
										{
											// read file in chunks in order to reduce memory consumption and increase performance
											while (readCount < length)
											{
												int actual = reader.Read(buffer, 0, buffer.Length);
												readCount += actual;
												writer.Write(buffer, 0, actual);
											}
										}
									}
								}
							}
							created = true;
						}
						else
						{
							db.CreateDatabase();
							created = true;
						}
					}
				}
				else
				{
					db.CreateDatabase();
					created = true;
				}
			}
		}
		return created;
	}
Esempio n. 45
0
            /**
             * Validates a property based on the property name and property value.
             * @param propertyName The name of the property to be checked.
             * @param propertyValue The value of the property to be checked.
             * @returns true if the property is valid, false otherwise.
             */
            public static new bool ValidateProperty(string propertyName, string propertyValue)
            {
                bool isPropertyValid = WidgetBaseWindowsPhone.ValidateProperty(propertyName, propertyValue);

                if (propertyName.Equals("scaleMode"))
                {
                    if (!(propertyValue.Equals("none") ||
                        propertyValue.Equals("scaleXY") ||
                        propertyValue.Equals("scalePreserveAspect")))
                    {
                        isPropertyValid = false;
                    }
                }
                else if (propertyName.Equals("imagePath"))
                {
                    //Take the store for the application (an image of the sandbox)
                    IsolatedStorageFile f = IsolatedStorageFile.GetUserStoreForApplication();

                    //Verify that the file exists on the isolated storage
                    if (f.FileExists(propertyValue))
                    {
                        try
                        {
                            //Create a file stream for the required file
                            IsolatedStorageFileStream fs = new IsolatedStorageFileStream(propertyValue, System.IO.FileMode.Open, f);
                        }
                        catch
                        {
                            // There was a problem reading the image file.
                            isPropertyValid = false;
                        }
                    }
                    else
                    {
                        isPropertyValid = false;
                    }
                }

                return isPropertyValid;
            }
Esempio n. 46
0
 public static void SaveTweets(IEnumerable<Tweet> tweets2Save)
 {
     using (var isoStream = new IsolatedStorageFileStream(_tweetsDbFileName, FileMode.Create))
         using (var streamWriter = new StreamWriter(isoStream))
         {
             var xmlSerializer = new XmlSerializer(typeof(Tweet[]));
             var tweetArray = tweets2Save.ToArray();
             xmlSerializer.Serialize(streamWriter, tweetArray);
         }
 }
Esempio n. 47
0
        /* Save highscores */
        public static void SaveHighScores(HighScoreData data, string filename, StorageDevice device)
        {
            // Get the path of the save game
            string fullpath = "highscores.dat";

            #if WINDOWS
            // Open the file, creating it if necessary
            FileStream stream = File.Open(fullpath, FileMode.OpenOrCreate);
            try
            {
                // Convert the object to XML data and put it in the stream
                XmlSerializer serializer = new XmlSerializer(typeof(HighScoreData));
                serializer.Serialize(stream, data);
            }
            finally
            {
                // Close the file
                stream.Close();
            }

            #elif XBOX

            using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
                {

                    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fullpath, FileMode.Create, iso))
                    {

                        XmlSerializer serializer = new XmlSerializer(typeof(HighScoreData));
                        serializer.Serialize(stream, data);

                    }

                }

            #endif
        }
Esempio n. 48
0
 public void SaveToIsolatedStorage(IEnumerable<TwitterAccountAuth> accts)
 {
     // simple squished text format
     //var isoStream = isolatedStorageFile.CreateFile("users.db"); this one sucks
     using (var isoStream = new IsolatedStorageFileStream("users.db", FileMode.Create))
         using (var streamWriter = new StreamWriter(isoStream))
             foreach (var acct in accts)
                 streamWriter.WriteLine(acct.ToString());
 }
Esempio n. 49
0
 public static void CopyFileFromStream(Stream SourceStream, string destFilename)
 {
     using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
     {
         if (myIsolatedStorage.FileExists(destFilename))
         {
             myIsolatedStorage.DeleteFile(destFilename);
         }
         using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(destFilename, FileMode.Create, myIsolatedStorage))
         {
             using (BinaryWriter writer = new BinaryWriter(fileStream))
             {
                 long length = SourceStream.Length;
                 byte[] buffer = new byte[4096];
                 int readCount = 0;
                 using (BinaryReader reader = new BinaryReader(SourceStream))
                 {
                     // read file in chunks in order to reduce memory consumption and increase performance
                     while (readCount < length)
                     {
                         int actual = reader.Read(buffer, 0, buffer.Length);
                         readCount += actual;
                         writer.Write(buffer, 0, actual);
                     }
                 }
             }
         }
     }
 }
Esempio n. 50
0
        public static IEnumerable<Tweet> RestoreTweets()
        {
            try
            {
                var isoStream = new IsolatedStorageFileStream(_tweetsDbFileName, FileMode.Open);
                using (var streamReader = new StreamReader(isoStream))
                {
                    var xmlSerializer = new XmlSerializer(typeof(Tweet[]));
                    var deserialized = (Tweet[]) xmlSerializer.Deserialize(streamReader);

                    // just incase, prune duplicates..
                    var final = new List<Tweet>();
                    var seenIds = new HashSet<long>();
                    foreach (var nt in deserialized.Where(nt => !seenIds.Contains(nt.Id)))
                    {
                        seenIds.Add(nt.Id);
                        final.Add(nt);
                    }
                    return final;
                }
            }
            catch (FileNotFoundException)
            {
                return Enumerable.Empty<Tweet>();
            }
        }
Esempio n. 51
0
 public IEnumerable<TwitterAccountAuth> Restore()
 {
     try
     {
         var isoStream = new IsolatedStorageFileStream("users.db", FileMode.Open);
         using (var streamReader = new StreamReader(isoStream))
             return streamReader.ReadToEnd().Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
                                             .Select(TwitterAccountAuth.FromString).Where(attemptNew => attemptNew != null).ToList();
     }
     catch (FileNotFoundException)
     {
         return Enumerable.Empty<TwitterAccountAuth>();
     }
 }
Esempio n. 52
0
            /**
             * Validates a property based on the property name and property value.
             * @param propertyName The name of the property to be checked.
             * @param propertyValue The value of the property to be checked.
             * @returns true if the property is valid, false otherwise.
             */
            public static new bool ValidateProperty(string propertyName, string propertyValue)
            {
                bool isPropertyValid = WidgetBaseWindowsPhone.ValidateProperty(propertyName, propertyValue);

                if (propertyName.Equals("imagePath") ||
                    propertyName.Equals("backgroundImagePath") ||
                    propertyName.Equals("pressedImagePath"))
                {
                    //Take the store for the application (an image of the sandbox)
                    IsolatedStorageFile f = IsolatedStorageFile.GetUserStoreForApplication();

                    //Verify that the file exists on the isolated storage
                    if (f.FileExists(propertyValue))
                    {
                        try
                        {
                            //Create a file stream for the required file
                            IsolatedStorageFileStream fs = new IsolatedStorageFileStream(propertyValue, System.IO.FileMode.Open, f);
                        }
                        catch
                        {
                            // There was a problem reading the image file.
                            isPropertyValid = false;
                        }
                    }
                    else
                    {
                        isPropertyValid = false;
                    }
                }
                else if (propertyName.Equals("fontColor"))
                {
                    try
                    {
                        System.Windows.Media.SolidColorBrush brush;
                        MoSync.Util.ConvertStringToColor(propertyValue, out brush);
                    }
                    catch (InvalidPropertyValueException)
                    {
                        isPropertyValid = false;
                    }
                }
                else if (propertyName.Equals("textVerticalAlignment"))
                {
                    if (!(propertyValue.Equals("MoSync.Constants.MAW_ALIGNMENT_TOP") ||
                        propertyValue.Equals("MoSync.Constants.MAW_ALIGNMENT_BOTTOM") ||
                        propertyValue.Equals("MoSync.Constants.MAW_ALIGNMENT_CENTER")))
                    {
                        isPropertyValid = false;
                    }
                }
                else if (propertyName.Equals("textHorizontalAlignment"))
                {
                    if (!(propertyValue.Equals("MoSync.Constants.MAW_ALIGNMENT_LEFT") ||
                        propertyValue.Equals("MoSync.Constants.MAW_ALIGNMENT_RIGHT") ||
                        propertyValue.Equals("MoSync.Constants.MAW_ALIGNMENT_CENTER")))
                    {
                        isPropertyValid = false;
                    }
                }

                return isPropertyValid;
            }
Esempio n. 53
0
 public static TwitterAccountAuth RestoreAccount()
 {
     try
     {
         var isoStream = new IsolatedStorageFileStream(_userDbFileName, FileMode.Open);
         using (var streamReader = new StreamReader(isoStream))
             return TwitterAccountAuth.FromString(streamReader.ReadToEnd());
     }
     catch (FileNotFoundException)
     {
         return null;
     }
 }
Esempio n. 54
0
    public static Stream GetFileStream(string filename, FileMode mode)
    {
        string name;
        FileType file_type;

        GetFileTypeAndName(filename, out file_type, out name);

        if (file_type == FileType.RESOURCE)
        {
            var res = App.GetResourceStream(new Uri(name, UriKind.Relative));
            if (res == null)
                return null;
            return res.Stream;
        }
        else if (file_type == FileType.USER_STORE)
        {
            var store = IsolatedStorageFile.GetUserStoreForApplication();
            try
            {
                if (store.FileExists(name) || mode == FileMode.OpenOrCreate)
                {
                    var ret = new IsolatedStorageFileStream(name, mode, FileAccess.ReadWrite, FileShare.Read, store);
                    return ret;
                }
                else
                {
                    return null;
                }
            }
            catch (IsolatedStorageException e)
            {
                Logger.log("Name: " + name + " Exception: " + e.ToString());
                return null;
            }
            catch (FileNotFoundException ee)
            {
                Logger.log("Name: " + name + " Exception: " + ee.ToString());
                return null;
            }
            catch (ArgumentException eee)
            {
                Logger.log("Name: " + name + " Exception: " + eee.ToString());
                return null;
            }

        }

        return null;
    }
Esempio n. 55
0
 public static void SaveAccount(TwitterAccountAuth acct)
 {
     using (var isoStream = new IsolatedStorageFileStream(_userDbFileName, FileMode.Create))
         using (var streamWriter = new StreamWriter(isoStream))
             streamWriter.WriteLine(acct.ToString());
 }
Esempio n. 56
0
    private void PersistToIsolatedStorage()
    {
        using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForAssembly())
        using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream("UserSettings.xml", System.IO.FileMode.Create, isf))
        {
            System.Xml.XmlTextWriter xtw = new XmlTextWriter(isfs, System.Text.Encoding.Default);

            xtw.WriteStartDocument();
            xtw.WriteStartElement("UserSettings");
            xtw.WriteStartElement("LastPattern");
            xtw.WriteString(this.textboxPattern.Text);
            xtw.WriteEndElement();
            xtw.WriteEndElement();
            xtw.WriteEndDocument();

            xtw.Close();
        }
    }
Esempio n. 57
0
 public RC xOpen(string zName, VirtualFile pFile, OPEN flags, out OPEN pOutFlags)
 {
     pOutFlags = 0;
     // If argument zPath is a NULL pointer, this function is required to open a temporary file. Use this buffer to store the file name in.
     //var zTmpname = new StringBuilder(MAX_PATH + 1);        // Buffer used to create temp filename
     var rc = RC.OK;
     var eType = (OPEN)((int)flags & 0xFFFFFF00);  // Type of file to open
     var isExclusive = (flags & OPEN.EXCLUSIVE) != 0;
     var isDelete = (flags & OPEN.DELETEONCLOSE) != 0;
     var isCreate = (flags & OPEN.CREATE) != 0;
     var isReadonly = (flags & OPEN.READONLY) != 0;
     var isReadWrite = (flags & OPEN.READWRITE) != 0;
     var isOpenJournal = (isCreate && (eType == OPEN.MASTER_JOURNAL || eType == OPEN.MAIN_JOURNAL || eType == OPEN.WAL));
     // Check the following statements are true:
     //   (a) Exactly one of the READWRITE and READONLY flags must be set, and
     //   (b) if CREATE is set, then READWRITE must also be set, and
     //   (c) if EXCLUSIVE is set, then CREATE must also be set.
     //   (d) if DELETEONCLOSE is set, then CREATE must also be set.
     Debug.Assert((!isReadonly || !isReadWrite) && (isReadWrite || isReadonly));
     Debug.Assert(!isCreate || isReadWrite);
     Debug.Assert(!isExclusive || isCreate);
     Debug.Assert(!isDelete || isCreate);
     // The main DB, main journal, WAL file and master journal are never automatically deleted. Nor are they ever temporary files.
     //Debug.Assert((!isDelete && !string.IsNullOrEmpty(zName)) || eType != OPEN.MAIN_DB);
     Debug.Assert((!isDelete && !string.IsNullOrEmpty(zName)) || eType != OPEN.MAIN_JOURNAL);
     Debug.Assert((!isDelete && !string.IsNullOrEmpty(zName)) || eType != OPEN.MASTER_JOURNAL);
     Debug.Assert((!isDelete && !string.IsNullOrEmpty(zName)) || eType != OPEN.WAL);
     // Assert that the upper layer has set one of the "file-type" flags.
     Debug.Assert(eType == OPEN.MAIN_DB || eType == OPEN.TEMP_DB || eType == OPEN.MAIN_JOURNAL || eType == OPEN.TEMP_JOURNAL ||
         eType == OPEN.SUBJOURNAL || eType == OPEN.MASTER_JOURNAL || eType == OPEN.TRANSIENT_DB || eType == OPEN.WAL);
     pFile.S = null;
     // If the second argument to this function is NULL, generate a temporary file name to use
     if (string.IsNullOrEmpty(zName))
     {
         Debug.Assert(isDelete && !isOpenJournal);
         zName = Path.GetRandomFileName();
     }
     // Convert the filename to the system encoding.
     if (zName.StartsWith("/") && !zName.StartsWith("//"))
         zName = zName.Substring(1);
     var dwDesiredAccess = (isReadWrite ? FileAccess.Read | FileAccess.Write : FileAccess.Read);
     // SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is created. SQLite doesn't use it to indicate "exclusive access" as it is usually understood.
     FileMode dwCreationDisposition;
     if (isExclusive)
         // Creates a new file, only if it does not already exist. */ If the file exists, it fails.
         dwCreationDisposition = FileMode.CreateNew;
     else if (isCreate)
         // Open existing file, or create if it doesn't exist
         dwCreationDisposition = FileMode.OpenOrCreate;
     else
         // Opens a file, only if it exists.
         dwCreationDisposition = FileMode.Open;
     var dwShareMode = FileShare.Read | FileShare.Write;
     #if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE)
     FileOptions dwFlagsAndAttributes;
     #endif
     if (isDelete)
     #if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE)
         dwFlagsAndAttributes = FileOptions.DeleteOnClose;
     #endif
     else
     #if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE)
         dwFlagsAndAttributes = FileOptions.None;
     #endif
     // Reports from the internet are that performance is always better if FILE_FLAG_RANDOM_ACCESS is used.
     FileStream fs = null;
     if (Environment.OSVersion.Platform >= PlatformID.Win32NT)
     {
         // retry opening the file a few times; this is because of a racing condition between a delete and open call to the FS
         var retries = 3;
         while (fs == null && retries > 0)
             try
             {
                 retries--;
     #if WINDOWS_PHONE || SQLITE_SILVERLIGHT
                 fs = new IsolatedStorageFileStream(zConverted, dwCreationDisposition, dwDesiredAccess, dwShareMode, IsolatedStorageFile.GetUserStoreForApplication());
     #elif !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE)
                 fs = new FileStream(zName, dwCreationDisposition, dwDesiredAccess, dwShareMode, 4096, dwFlagsAndAttributes);
     #else
                 fs = new FileStream(zName, dwCreationDisposition, dwDesiredAccess, dwShareMode, 4096);
     #endif
     #if DEBUG
                 SysEx.OSTRACE("OPEN {0} ({1})", fs.GetHashCode(), fs.Name);
     #endif
             }
             catch (Exception) { Thread.Sleep(100); }
     }
     SysEx.OSTRACE("OPEN {0} {1} 0x{2:x} {3}", pFile.GetHashCode(), zName, dwDesiredAccess, fs == null ? "failed" : "ok");
     if (fs == null ||
     #if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE)
      fs.SafeFileHandle.IsInvalid
     #else
      !fs.CanRead
     #endif
     )
     {
     #if SQLITE_SILVERLIGHT
     pFile.lastErrno = 1;
     #else
         pFile.LastErrno = (uint)Marshal.GetLastWin32Error();
     #endif
         VirtualFile.winLogError(RC.CANTOPEN, "winOpen", zName);
         return (isReadWrite ? xOpen(zName, pFile, ((flags | OPEN.READONLY) & ~(OPEN.CREATE | OPEN.READWRITE)), out pOutFlags) : SysEx.SQLITE_CANTOPEN_BKPT());
     }
     pOutFlags = (isReadWrite ? OPEN.READWRITE : OPEN.READONLY);
     pFile.Clear();
     pFile.IsOpen = true;
     pFile.S = fs;
     pFile.LastErrno = 0;
     pFile.Vfs = this;
     pFile.Shm = null;
     pFile.Path = zName;
     pFile.SectorSize = (uint)getSectorSize(zName);
     return rc;
 }
    public double SetNewPrefsForUser()
    {
        try
        {
            byte inputChar;
            IsolatedStorageFile isoFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User |
                IsolatedStorageScope.Assembly |
                IsolatedStorageScope.Domain,
                typeof(System.Security.Policy.Url),
                typeof(System.Security.Policy.Url));

            // If this is not a new user, archive the old preferences and
            // overwrite them using the new preferences.
            if (!this.myNewPrefs)
            {
                if (isoFile.GetDirectoryNames("Archive").Length == 0)
                    isoFile.CreateDirectory("Archive");
                else
                {

                    IsolatedStorageFileStream source =
                        new IsolatedStorageFileStream(this.userName, FileMode.OpenOrCreate,
                        isoFile);
                    // This is the stream from which data will be read.
                    Console.WriteLine("Is the source file readable? " + (source.CanRead ? "true" : "false"));
                    Console.WriteLine("Creating new IsolatedStorageFileStream for Archive.");

                    // Open or create a writable file.
                    IsolatedStorageFileStream target =
                        new IsolatedStorageFileStream("Archive\\ " + this.userName,
                        FileMode.OpenOrCreate,
                        FileAccess.Write,
                        FileShare.Write,
                        isoFile);
                    Console.WriteLine("Is the target file writable? " + (target.CanWrite ? "true" : "false"));
                    // Stream the old file to a new file in the Archive directory.
                    if (source.IsAsync && target.IsAsync)
                    {
                        // IsolatedStorageFileStreams cannot be asynchronous.  However, you
                        // can use the asynchronous BeginRead and BeginWrite functions
                        // with some possible performance penalty.

                        Console.WriteLine("IsolatedStorageFileStreams cannot be asynchronous.");
                    }

                    else
                    {
                        Console.WriteLine("Writing data to the new file.");
                        while (source.Position < source.Length)
                        {
                            inputChar = (byte)source.ReadByte();
                            target.WriteByte(inputChar);
                        }

                        // Determine the size of the IsolatedStorageFileStream
                        // by checking its Length property.
                        Console.WriteLine("Total Bytes Read: " + source.Length);

                    }

                    // After you have read and written to the streams, close them.
                    target.Close();
                    source.Close();
                }
            }

            // Open or create a writable file with a maximum size of 10K.
            IsolatedStorageFileStream isoStream =
                new IsolatedStorageFileStream(this.userName,
                FileMode.OpenOrCreate,
                FileAccess.Write,
                FileShare.Write,
                10240,
                isoFile);
            isoStream.Position = 0;  // Position to overwrite the old data.
            StreamWriter writer = new StreamWriter(isoStream);
            // Update the data based on the new inputs.
            writer.WriteLine(this.NewsUrl);
            writer.WriteLine(this.SportsUrl);

            // Calculate the amount of space used to record this user's preferences.
            double d = isoFile.CurrentSize / isoFile.MaximumSize;
            Console.WriteLine("CurrentSize = " + isoFile.CurrentSize.ToString());
            Console.WriteLine("MaximumSize = " + isoFile.MaximumSize.ToString());
            // StreamWriter.Close implicitly closes isoStream.
            writer.Close();
            isoFile.Close();

            return d;
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
            return 0.0;
        }
    }