OpenFile() public method

public OpenFile ( string path, FileMode mode ) : IsolatedStorageFileStream
path string
mode FileMode
return IsolatedStorageFileStream
Exemplo n.º 1
0
 public IsolatedStorageTracer()
 {
     _storageFile = IsolatedStorageFile.GetUserStoreForApplication();
     _storageFileStream = _storageFile.OpenFile("MagellanTrace.log", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
     _streamWriter = new StreamWriter(_storageFileStream);
     _streamWriter.AutoFlush = true;
 }
Exemplo n.º 2
0
 private static void GetFile(IsolatedStorageFile istorage, string filename, Action<File> returns)
 {
     using (var openedFile = istorage.OpenFile(filename, System.IO.FileMode.Open))
     {
         ReadFileFromOpenFile(filename, openedFile, returns);
     }
 }
Exemplo n.º 3
0
 protected static string ReadTextFile(IsolatedStorageFile isf, string path)
 {
     string text;
     using (var fileStream = isf.OpenFile(path, FileMode.Open))
     {
         using (StreamReader sr = new StreamReader(fileStream))
         {
             text = sr.ReadToEnd();
         }
     }
     return text;
 }
Exemplo n.º 4
0
        private void Save()
        {
            store = IsolatedStorageFile.GetUserStoreForApplication();

            IsolatedStorageFileStream stream = store.OpenFile(filterFilename, FileMode.Truncate);
            if (null != stream)
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(FilterViewModel));
                ser.WriteObject(stream, App.ViewModelFilter);
                stream.Close();
            }
        }
Exemplo n.º 5
0
    /**
     * implements of CCUserDefault
     */
    private CCUserDefault()
    {
        myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();

        // only create xml file once if it doesnt exist
        if ((!isXMLFileExist())) {
            createXMLFile();
        }

        using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(XML_FILE_NAME, FileMode.Open, FileAccess.Read)) {
            parseXMLFile(fileStream);
        }
    }
Exemplo n.º 6
0
        private static Stream OpenLogFile(IsolatedStorageFile store)
        {
            if (Profile == null)
            {
                return Stream.Null;
            }

            try
            {
                var fileName = string.Format(LOGFILE_TEMPLATE, DateTime.UtcNow.ToString("yyyy-MM-dd"));
                var folderPath = Path.Combine(Profile.CurrentProfilePath(), LOGFOLDER);

                if (!store.DirectoryExists(folderPath))
                {
                    store.CreateDirectory(folderPath);
                }

                var filePath = Path.Combine(folderPath, fileName);

                if (store.FileExists(filePath))
                {
                    return store.OpenFile(filePath, FileMode.Append);
                }
                else
                {
                    CleanupLogs(store, folderPath);

                    return store.OpenFile(filePath, FileMode.Create);
                }
            }
            catch (Exception ex)
            {
                // Logging Failed, don't kill the process because of it
                Debugger.Break();

                return Stream.Null;
            }
        }
Exemplo n.º 7
0
        private static void CopyToIsolatedStorage(string file, IsolatedStorageFile store, bool overwrite = true)
        {
            if (store.FileExists(file) && !overwrite)
                return;

            using (Stream resourceStream = Application.GetResourceStream(new Uri(file, UriKind.Relative)).Stream)
            using (IsolatedStorageFileStream fileStream = store.OpenFile(file, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                int bytesRead;
                var buffer = new byte[resourceStream.Length];
                while ((bytesRead = resourceStream.Read(buffer, 0, buffer.Length)) > 0)
                    fileStream.Write(buffer, 0, bytesRead);
            }
        }
        private BitmapImage getThumbnail(string file, IsolatedStorageFile iso)
        {
            BitmapImage bmp = new BitmapImage();

            if (iso.FileExists(file))
            {
                using (IsolatedStorageFileStream stream = iso.OpenFile(file, FileMode.Open, FileAccess.Read))
                {
                    bmp.SetSource(stream);
                }
            }
            else
                bmp = null;

            return bmp;
        }
Exemplo n.º 9
0
        private void Load()
        {
            store = IsolatedStorageFile.GetUserStoreForApplication();

            IsolatedStorageFileStream stream = store.OpenFile(filterFilename, FileMode.OpenOrCreate);
            if (null != stream)
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(FilterViewModel));
                App.ViewModelFilter = (FilterViewModel)ser.ReadObject(stream);
                stream.Close();

                if (null == App.ViewModelFilter)
                {   // First time app was run since installation
                    App.ViewModelFilter = new FilterViewModel();
                }
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// 读取指定的story.
        /// </summary>
        /// <param name="storyName">story名称.</param>
        /// <param name="userStore">如果参数为null, 创建一个新的.</param>
        internal static void ReadStoryFile(string storyName, IsolatedStorageFile userStore = null)
        {
            if (userStore == null)
            {
                userStore = IsolatedStorageFile.GetUserStoreForApplication();
            }
            using (IsolatedStorageFileStream fileStream = userStore.OpenFile(storyName + ".xml", System.IO.FileMode.Open))
            {
                XDocument xdoc = XDocument.Load(fileStream);
                var picturesLibrary = new MediaLibrary().Pictures;

                // Load all photos.
                foreach (XElement photoElement in xdoc.Root.Elements())
                {
                    try
                    {
                        Photo photo = new Photo()
                        {
                            Name = photoElement.Attribute("Name").Value,
                        };
                        string photoDurationString = photoElement.Attribute("PhotoDuration").Value;
                        int photoDuration = int.Parse(photoDurationString);
                        photo.PhotoDuration = TimeSpan.FromSeconds(photoDuration);
                        XElement transitionElement = photoElement.Element("Transition");
                        if (transitionElement != null)
                        {
                            photo.Transition = TransitionBase.Load(photoElement.Element("Transition"));
                        }
                        Picture picture = picturesLibrary.Where(p => p.Name == photo.Name).FirstOrDefault();
                        if (picture == null)
                        {
                            // 如果找不到原文件,可能已经被删除了
                            // TODO: 我们需要记录错误吗? 我们是继续下一个图片还是抛出异常?
                            continue;
                        }
                        photo.ThumbnailStream = picture.GetThumbnail();
                        App.MediaCollection.Add(photo);
                    }
                    catch
                    {
                        // TODO: 我们需要记录错误吗? 我们是继续下一个图片还是抛出异常?
                        continue;
                    }
                }
            }
        }
Exemplo n.º 11
0
        private void signInButton_SessionChanged_1(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
        {
            if (e.Status != LiveConnectSessionStatus.Connected)
                return;


            manager.AllRoadMapsReceived += (o, eventAllRoadMaps) =>
            {
                if (eventAllRoadMaps.RoadMaps.Count  == 0)
                {
                    Debug.WriteLine("Aucun rendez-vous n'existe pour les jours sélectionnés");
                    return;
                }

                try
                {
                    //SaveTableur();
                    SpreadSheetRoadmapGenerator.GenerateXLS("feuilles-de-route.xlsx", eventAllRoadMaps.RoadMaps, 5.5f, 1.6f);
                    if (e.Session != null && e.Status == LiveConnectSessionStatus.Connected)
                    {
                        myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
                        fileStream = myIsolatedStorage.OpenFile("feuilles-de-route.xlsx", FileMode.Open, FileAccess.Read);
                        reader = new StreamReader(fileStream);
                        App.Session = e.Session;
                        LiveConnectClient client = new LiveConnectClient(e.Session);
                        client.UploadCompleted += client_UploadCompleted;
                        client.UploadAsync("me/skydrive", "feuilles-de-route.xlsx", reader.BaseStream, OverwriteOption.Overwrite);
                    }
                }
                catch (Exception exception)
                {
                    Debug.WriteLine(exception.Message);
                }
            };
            ReferenceMeeting start = new ReferenceMeeting(new DateTime(2013, 1, 2, 8, 30, 0), new Location()
            {
                Latitude = 48.85693,
                Longitude = 2.3412
            }) { City = "Paris", Subject = "Start" };
            ReferenceMeeting end = start;
            end.Subject = "End";

            manager.GetAllRoadMapsAsync(new DateTime(2013, 1, 2), new DateTime(2013, 2, 10), start, end);

        }
Exemplo n.º 12
0
    /**
     * implements of CCUserDefault
     */
    private CCUserDefault()
    {
        #if WINDOWS || MACOS || LINUX
        // only create xml file once if it doesnt exist
        if ((!isXMLFileExist())) {
            createXMLFile();
        }
        using (FileStream fileStream = new FileInfo(XML_FILE_NAME).OpenRead()){
            parseXMLFile(fileStream);
        }
        #else
        myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();

        // only create xml file once if it doesnt exist
        if ((!isXMLFileExist())) {
            createXMLFile();
        }

        using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(XML_FILE_NAME, FileMode.Open, FileAccess.Read)) {
            parseXMLFile(fileStream);
        }
        #endif
    }
Exemplo n.º 13
0
        /// <summary>
        /// Gets the saved password.
        /// </summary>
        /// <returns></returns>
        private static DbPersistentData GetSavedPassword(
            IsolatedStorageFile store, string protectPath,
            string parsedXmlPath, string masterPassPath)
        {
            var result = new DbPersistentData();
            if (!store.FileExists(protectPath))
            {
                throw new FileNotFoundException(protectPath);
            }
            if (!store.FileExists(parsedXmlPath))
            {
                throw new FileNotFoundException(parsedXmlPath);
            }
            if (!store.FileExists(masterPassPath))
            {
                throw new FileNotFoundException(masterPassPath);
            }
            using (var fs = store.OpenFile(protectPath, FileMode.Open))
            using (var buffer = new MemoryStream((int)fs.Length))
            {
                BufferEx.CopyStream(fs, buffer);
                result.Protection = buffer.ToArray();
            }

            using (var fs = store.OpenFile(parsedXmlPath, FileMode.Open))
            using (var buffer = new MemoryStream((int)fs.Length))
            {
                BufferEx.CopyStream(fs, buffer);
                result.Xml = buffer.ToArray();
            }

            using (var fs = store.OpenFile(masterPassPath, FileMode.Open))
            using (var buffer = new MemoryStream((int)fs.Length))
            {
                BufferEx.CopyStream(fs, buffer);
                result.MasterKey = buffer.ToArray();
            }

            return result;
        }
Exemplo n.º 14
0
        private byte[] GetKeyFile(IsolatedStorageFile store)
        {
            var path = KeyFilePath;
            if (!store.FileExists(path))
                return null;

            using (var fs = store.OpenFile(path, FileMode.Open))
            {
                var length = (int)fs.Length;
                var keyFile = new byte[length];
                fs.Read(keyFile, 0, length);

                return keyFile;
            }
        }
Exemplo n.º 15
0
        public override BitmapSource Load( string url )
        {
            string fileName = GetFileName( url );
            BitmapSource retBitmap = null;
            if ( _memCache.ContainsKey( fileName ) ) {
                retBitmap = _memCache[fileName];
            }
            if ( retBitmap != null ) {
                return retBitmap;
            }

            // 内存中无缓存
            fileName = GetFilePath( GetFileName( url ) );
            using ( _storage = IsolatedStorageFile.GetUserStoreForApplication() ) {
                if ( !_storage.FileExists( fileName ) ) {
                    return BitmapCache.DEFAULT_IMAGE;
                }
                BitmapImage bitmap = null;
                try {
                    IsolatedStorageFileStream fileStream = _storage.OpenFile( fileName, System.IO.FileMode.Open );
                    Deployment.Current.Dispatcher.BeginInvoke( () => {
                        bitmap = new BitmapImage();
                        bitmap.SetSource( fileStream );
                        fileStream.Dispose();
                    } );
                }
                catch ( Exception e ) {
                    e.ToString();
                }
                return bitmap;
            }
        }
Exemplo n.º 16
0
        private static void Upgrade(IsolatedStorageFile store)
        {
            var files = new List<string>(
                store.GetFileNames());

            if (!files.Contains("Database.kdbx"))
                return;

            var appSettings = IsolatedStorageSettings
                .ApplicationSettings;

            string url;
            if (!appSettings.TryGetValue("Url", out url))
                url = null;

            var info = new DatabaseInfo();

            using (var fs = store.OpenFile("Database.kdbx", FileMode.Open))
            {
                var source = string.IsNullOrEmpty(url)
                    ? "WinPass" : DatabaseUpdater.WEB_UPDATER;

                var details = new DatabaseDetails
                {
                    Url = url,
                    Source = source,
                    Type = SourceTypes.OneTime,
                    Name = "WinPass 1.x database",
                };

                info.SetDatabase(fs, details);
            }

            store.DeleteFile("Database.kdbx");
            store.DeleteFile("Protection.bin");
            store.DeleteFile("Decrypted.xml");
        }
Exemplo n.º 17
0
        private static long GetAvailableSpace(string xapName, IsolatedStorageFile iso)
        {
            var availableSpace = iso.AvailableFreeSpace;

            if (iso.FileExists(xapName))
            {
                using (var file = iso.OpenFile(xapName, FileMode.Open))
                {
                    availableSpace += file.Length;
                }
            }

            return availableSpace;
        }
Exemplo n.º 18
0
        /// <summary>
        /// Imports a savegame from metadata associated to a savegame
        /// file.
        /// </summary>
        /// <param name="gwsFilePath">Path to the GWS savegame file.</param>
        /// <param name="isf">Isostore file to use to load.</param>
        /// <returns>The cartridge savegame.</returns>
        public static CartridgeSavegame FromIsoStore(string gwsFilePath, IsolatedStorageFile isf)
        {
            // Checks that the metadata file exists.
            string mdFile = gwsFilePath + ".mf";
            if (!(isf.FileExists(mdFile)))
            {
                throw new System.IO.FileNotFoundException(mdFile + " does not exist.");
            }
            
            // Creates a serializer.
            DataContractSerializer serializer = new DataContractSerializer(typeof(CartridgeSavegame));

            // Reads the object.
            CartridgeSavegame cs;
            using (IsolatedStorageFileStream fs = isf.OpenFile(mdFile, System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                // Reads the object.
                object o = serializer.ReadObject(fs);

                // Casts it.
                cs = (CartridgeSavegame)o;
            }

            // Adds non-serialized content.
            cs.SavegameFile = gwsFilePath;
            cs.MetadataFile = mdFile;

            // Returns it.
            return cs;
        }
Exemplo n.º 19
0
        private void UploadFile()
        {
            var updateIe = App.ViewModel.AllToUpdateItems.AsQueryable();

            client.UploadCompleted += client_UploadCompleted;
            System.IO.IsolatedStorage.IsolatedStorageFile isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
            foreach (ToDoItem uploadItem in updateIe)
            {
                infoTextBlock.Text = "Uploading...";



                byte[]       b2   = System.Text.Encoding.UTF8.GetBytes(uploadItem.TxtFile);
                MemoryStream file = new MemoryStream(b2);
                //不同difference
                client.UploadAsync(skyDriveFolderID, uploadItem.ItemName, file, OverwriteOption.Overwrite);
                string imagename = uploadItem.ItemName + ".jpg";
                if (isf.FileExists(imagename))
                {
                    System.IO.IsolatedStorage.IsolatedStorageFileStream PhotoStream = isf.OpenFile(imagename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                    client.UploadAsync(skyDriveFolderID_image, imagename, PhotoStream, OverwriteOption.Overwrite);
                }
            }
        }
Exemplo n.º 20
0
        private void LoadDetails(IsolatedStorageFile store)
        {
            using (var fs = store.OpenFile(InfoPath, FileMode.Open))
            {
                var serializer = new JsonSerializer();
                var reader = new JsonTextReader(
                    new StreamReader(fs));

                var details = serializer.Deserialize
                    <DatabaseDetails>(reader);

                Details = details;
                reader.Close();
            }
        }
Exemplo n.º 21
0
        private void LoadAuth(IsolatedStorageFile isoStore)
        {
            if (isoStore.FileExists(AuthFilename))
            {
                try
                {
                    using (var stream = isoStore.OpenFile(AuthFilename, FileMode.Open, FileAccess.Read))
                    using (var br = new BinaryReader(stream))
                    {
                        var fileVer = br.ReadInt32();
                        var unameLen = br.ReadInt32();
                        var unameEncrypted = br.ReadBytes(unameLen);
                        var pwordLen = br.ReadInt32();
                        var pwordEncrypted = br.ReadBytes(pwordLen);
                        var unamePlain = ProtectedData.Unprotect(unameEncrypted, null);
                        var pwordPlain = ProtectedData.Unprotect(pwordEncrypted, null);
                        _username = System.Text.Encoding.UTF8.GetString(unamePlain, 0, unamePlain.Length);
                        _password = System.Text.Encoding.UTF8.GetString(pwordPlain, 0, pwordPlain.Length);
                        IsAuthenticated = true;
                        InitAuth(_username, _password);

                        var numContexts = br.ReadInt32();
                        Contexts.Clear();
                        for (int i = 0; i < numContexts; i++)
                        {
                            var usr = new User();
                            usr.Load(br, fileVer);
                            Contexts.Add(new Context() { User = usr });
                        }
                        AuthenticatedUser = Contexts[0].User;

                        br.Close();
                    }
                }
                catch (EndOfStreamException)
                {
                    isoStore.DeleteFile(AuthFilename);
                }
            }
            else
            {
                IsAuthenticated = false;
            }
        }
Exemplo n.º 22
0
        private void UpdateSavedPassword(IsolatedStorageFile store)
        {
            using (var fs = store.OpenFile(DatabasePath, FileMode.Open))
            {
                Data = DatabaseReader.GetXml(
                    fs, Data.MasterKey);
            }

            Save(store, Data);
        }
Exemplo n.º 23
0
        private void SaveAuth(IsolatedStorageFile isoStore)
        {
            using (var stream = isoStore.OpenFile(AuthFilename, FileMode.Create, FileAccess.Write))
            using (var bw = new BinaryWriter(stream))
            {
                bw.Write(AuthFileVersion);
                byte[] unamePlainData = System.Text.Encoding.UTF8.GetBytes(_username);
                byte[] pwordPlainData = System.Text.Encoding.UTF8.GetBytes(_password);
                byte[] unameEncrypted = ProtectedData.Protect(unamePlainData, null);
                byte[] pwordEncrypted = ProtectedData.Protect(pwordPlainData, null);
                bw.Write(unameEncrypted.Length);
                bw.Write(unameEncrypted, 0, unameEncrypted.Length);
                bw.Write(pwordEncrypted.Length);
                bw.Write(pwordEncrypted, 0, pwordEncrypted.Length);

                bw.Write(Contexts.Count);
                for (int i = 0; i < Contexts.Count; i++)
                    Contexts[i].User.Save(bw);

                bw.Close();
            }
        }
Exemplo n.º 24
0
        private void SendCrashes(IsolatedStorageFile store, string[] filenames)
        {
            foreach (String filename in filenames)
            {
                try
                {
                    Stream fileStream = store.OpenFile(Path.Combine(CrashDirectoryName, filename), FileMode.Open);
                    string log = "";
                    using (StreamReader reader = new StreamReader(fileStream))
                    {
                        log = reader.ReadToEnd();
                    }
                    string body = "";
                    body += "raw=" + HttpUtility.UrlEncode(log);
                    body += "&sdk=" + SdkName;
                    body += "&sdk_version=" + SdkVersion;
                    fileStream.Close();

                    WebRequest request = WebRequestCreator.ClientHttp.Create(new Uri("https://rink.hockeyapp.net/api/2/apps/" + identifier + "/crashes"));
                    request.Method = "POST";
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.Headers[HttpRequestHeader.UserAgent] = "Hockey/WP7";

                    request.BeginGetRequestStream(requestResult =>
                    {
                        try
                        {
                            Stream stream = request.EndGetRequestStream(requestResult);
                            byte[] byteArray = Encoding.UTF8.GetBytes(body);
                            stream.Write(byteArray, 0, body.Length);
                            stream.Close();

                            request.BeginGetResponse(responseResult =>
                            {
                                Boolean deleteCrashes = true;
                                try
                                {
                                    request.EndGetResponse(responseResult);
                                }
                                catch (WebException e)
                                {
                                    if ((e.Status == WebExceptionStatus.ConnectFailure) ||
                                        (e.Status == WebExceptionStatus.ReceiveFailure) ||
                                        (e.Status == WebExceptionStatus.SendFailure) ||
                                        (e.Status == WebExceptionStatus.Timeout) ||
                                        (e.Status == WebExceptionStatus.UnknownError))
                                    {
                                        deleteCrashes = false;
                                    }
                                }
                                catch (Exception)
                                {
                                }
                                finally
                                {
                                    if (deleteCrashes)
                                    {
                                        DeleteCrashes(store, filenames);
                                    }
                                }
                            }, null);
                        }
                        catch (Exception)
                        {
                        }
                    }, null);
                }
                catch (Exception)
                {
                    store.DeleteFile(Path.Combine(CrashDirectoryName, filename));
                }
            }
        }
Exemplo n.º 25
0
        private void showImage()
        {
            if (App.ViewModel.forShare != null)
            {
                imagePicker.Content = App.ViewModel.forShare.ItemName;
                imagePicker.Opacity = 0.5;
                System.IO.IsolatedStorage.IsolatedStorageFile isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
                //点击超链接后图片存在
                if (isf.FileExists(App.ViewModel.forShare.ItemName + ".jpg"))
                {
                    isf.CopyFile(App.ViewModel.forShare.ItemName + ".jpg", "abc.jpg", true);
                    System.IO.IsolatedStorage.IsolatedStorageFileStream PhotoStream = isf.OpenFile("abc.jpg", System.IO.FileMode.Open, System.IO.FileAccess.Read);
                    System.Windows.Media.Imaging.BitmapImage            bmp1        = new System.Windows.Media.Imaging.BitmapImage();
                    bmp1.SetSource(PhotoStream); //把文件流转换为图片
                    PhotoStream.Close();         //读取完毕,关闭文件流

                    System.Windows.Media.ImageBrush ib = new System.Windows.Media.ImageBrush();
                    ib.ImageSource = bmp1;
                    tip.Background = ib;      //把图片设置为控件的背景图
                    //imageTip.Visibility = System.Windows.Visibility.Collapsed;
                }
            }
            //如果存在背景,则显示关联按钮
            if (tip.Background != null)
            {
                appBar3();
            }
        }
Exemplo n.º 26
0
 /// <summary>
 /// Creates or replaces the underlying savegame file and opens a writing
 /// stream for it.
 /// </summary>
 /// <param name="isf">Isolated storage to use.</param>
 /// <returns>The stream to write the savegame on.</returns>
 public System.IO.Stream CreateOrReplace(IsolatedStorageFile isf)
 {
     // Makes sure the containing directory exists.
     isf.CreateDirectory(System.IO.Path.GetDirectoryName(SavegameFile));
     
     // Returns the stream to SavegameFile.
     return isf.OpenFile(SavegameFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);
 }
Exemplo n.º 27
0
        private static DateTime? LoadCompletionTimeStampIfPresent(IsolatedStorageFile Iso, string SnapshotDir) {
            var completionMarkerPath = Path.Combine(SnapshotDir, COMPLETED_MARKER);
            var isCompleted = Iso.FileExists(completionMarkerPath);

            if (isCompleted) {
                using (var completionFile = Iso.OpenFile(completionMarkerPath, FileMode.Open, FileAccess.Read))
                using (var reader = new StreamReader(completionFile)) {
                    var timeString = reader.ReadToEnd();
                    DateTime readTime;
                    if (DateTime.TryParse(timeString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out readTime)) {
                        return readTime.ToLocalTime();
                    }
                }
            }
            return null;
        }
Exemplo n.º 28
0
        private static void saveImageToCache(ExtendedImage image, string filename, IsolatedStorageFile storage)
        {
            try
            {
                using (IsolatedStorageFileStream cachedFile = storage.OpenFile(filename, FileMode.Create))
                {
                    WriteableBitmap bitmap = ImageExtensions.ToBitmap(image);
                    bitmap.SaveJpeg(cachedFile, bitmap.PixelWidth, bitmap.PixelHeight, 0, 80);

#if DEBUG
                    App.logger.log("Created cached file {0}", filename);
#endif
                }
            }
            catch (Exception)
            {
#if DEBUG
                throw;
#endif
            }
        }
Exemplo n.º 29
0
Arquivo: File.cs Projeto: Jypy/zmNinja
        private byte[] readFileBytes(string filePath,int startPos,int endPos, IsolatedStorageFile isoFile)
        {
            byte[] buffer;
            using (IsolatedStorageFileStream reader = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read))
            {
                if (startPos < 0)
                {
                    startPos = Math.Max((int)reader.Length + startPos, 0);
                }
                else if (startPos > 0)
                {
                    startPos = Math.Min((int)reader.Length, startPos);
                }
                if (endPos > 0)
                {
                    endPos = Math.Min((int)reader.Length, endPos);
                }
                else if (endPos < 0)
                {
                    endPos = Math.Max(endPos + (int)reader.Length, 0);
                }

                buffer = new byte[endPos - startPos];
                reader.Seek(startPos, SeekOrigin.Begin);
                reader.Read(buffer, 0, buffer.Length);
            }

            return buffer;
        }
Exemplo n.º 30
0
        private void LoadRepos(IsolatedStorageFile iso)
        {
            if (!iso.FileExists(RepoFilename))
                return;

            try
            {
                using (var stream = iso.OpenFile(RepoFilename, FileMode.Open, FileAccess.Read))
                using (var br = new BinaryReader(stream))
                {
                    var fileVer = br.ReadInt32();
                    var numContexts = br.ReadInt32();
                    for (int i = 0; i < numContexts; i++)
                    {
                        var login = br.ReadString();
                        foreach (var context in Contexts)
                        {
                            if (context.User.Login.Equals(login))
                            {
                                var numMyRepos = br.ReadInt32();
                                context.Repositories.Clear();
                                for (int j = 0; j < numMyRepos; j++)
                                {
                                    var repo = new Repo();
                                    repo.Load(br, fileVer);
                                    context.Repositories.Add(repo);
                                }
                                break;
                            }
                        }
                    }

                    br.Close();
                }
            }
            catch (EndOfStreamException)
            {
                iso.DeleteFile(RepoFilename);
            }
        }
Exemplo n.º 31
0
        /// <summary>
        /// Appel une fois que l'utilisateur est connecté à Skydrive
        /// Génère et Upload le fichier XLS
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void auth_LoginCompleted(object sender, LoginCompletedEventArgs e)
        {
            if (!App.IsConnected())
            {
                MessageBox.Show("Vous n'êtes pas connecté à internet");
                return;
            }

            try
            {
                List<RoadMap> _roadmaps = new List<RoadMap>();
                _roadmaps.Add(this.myRoadM);

                string filename = "rapport-planmyway-" + myRoadM.Date.ToShortDateString().Replace("/", "-") + ".xlsx";
                Debug.WriteLine(filename);
                //SaveTableur();
                SpreadSheetRoadmapGenerator.GenerateXLS(filename, _roadmaps, (double)settings["ConsoCarburant"], (double)settings["PrixCarburant"]);
                if (e.Session != null && e.Status == LiveConnectSessionStatus.Connected)
                {
                    myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
                    fileStream = myIsolatedStorage.OpenFile(filename, FileMode.Open, FileAccess.Read);
                    reader = new StreamReader(fileStream);
                    App.Session = e.Session;
                    LiveConnectClient client = new LiveConnectClient(e.Session);
                    client.UploadCompleted += client_UploadCompleted;
                    client.UploadAsync("me/skydrive", filename, reader.BaseStream, OverwriteOption.Overwrite);

                }
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception.Message);
                MessageBox.Show(exception.Message);
                //this.enableInterface();
            }
        }
Exemplo n.º 32
0
        private void SaveRepos(IsolatedStorageFile iso)
        {
            using (var stream = iso.OpenFile(RepoFilename, FileMode.Create, FileAccess.Write))
            using (var bw = new BinaryWriter(stream))
            {
                bw.Write(RepoFileVersion);

                bw.Write(Contexts.Count);
                foreach (var context in Contexts)
                {
                    bw.Write(context.User.Login);
                    // Detect repos that are watched/owned so we only save those out (and forget the others in the process)
                    // This handles changes to repo watched status
                    int numRepos = 0;
                    foreach (var repo in context.Repositories)
                    {
                        if (repo.Type != RepoType.None)
                            ++numRepos;
                    }
                    bw.Write(numRepos);
                    for (int i = 0; i < context.Repositories.Count; i++)
                    {
                        if (context.Repositories[i].Type != RepoType.None)
                            context.Repositories[i].Save(bw);
                    }
                }

                bw.Close();
            }
        }
Exemplo n.º 33
0
 public override Task <System.IO.Stream> OpenFileAsync(string path, FileMode mode, FileAccess access, FileShare share)
 {
     return(Task <System.IO.Stream> .Factory.StartNew(() => (System.IO.Stream) file.OpenFile(path, (System.IO.FileMode)mode, (System.IO.FileAccess)access, (System.IO.FileShare)share)));
 }