private void SaveIndexIfDirty()
        {
            if (!_indexNeedsSaving)
            {
                return;
            }

            RunSyncWithLock(() =>
            {
                List <Entry> toSave = _entriesByHttpUrl.Values.ToList();
                _indexNeedsSaving   = false;

                try
                {
                    var textConvert = TextConvert;
                    if (textConvert == null)
                    {
                        return;
                    }
                    var text = TextConvert.SerializeObject(toSave);

                    var store = MvxFileStoreHelper.SafeGetFileStore();
                    store.WriteFile(IndexFilePath, text);
                }
                catch (Exception exception)
                {
                    MvxTrace.Warning("Failed to save cache index {0} - reason {1}", _cacheFolder,
                                     exception.ToLongString());
                }
            });
        }
        private void DeleteNextUnneededFile()
        {
            string nextFileToDelete = "";

            RunSyncWithLock(() =>
            {
                nextFileToDelete = _toDeleteFiles.FirstOrDefault();
            });

            if (string.IsNullOrEmpty(nextFileToDelete))
            {
                return;
            }

            try
            {
                var fileService = MvxFileStoreHelper.SafeGetFileStore();
                if (fileService.Exists(nextFileToDelete))
                {
                    fileService.DeleteFile(nextFileToDelete);
                }
            }
            catch (Exception exception)
            {
                MvxTrace.Warning("Problem seen deleting file {0} problem {1}", nextFileToDelete,
                                 exception.ToLongString());
            }
        }
        private Dictionary <string, Entry> LoadIndexEntries()
        {
            try
            {
                var    store = MvxFileStoreHelper.SafeGetFileStore();
                string text;
                if (store.TryReadTextFile(IndexFilePath, out text))
                {
                    var textConvert = TextConvert;
                    if (textConvert == null)
                    {
                        return(new Dictionary <string, Entry>());
                    }

                    var list = textConvert.DeserializeObject <List <Entry> >(text);
                    return(list.ToDictionary(x => x.HttpSource, x => x));
                }
            }
            //catch (ThreadAbortException)
            //{
            //    throw;
            //}
            catch (Exception exception)
            {
                MvxTrace.Warning("Failed to read cache index {0} - reason {1}", _cacheFolder,
                                 exception.ToLongString());
            }

            return(new Dictionary <string, Entry>());
        }
        private void QueueUnindexedFilesForDelete()
        {
            var store = MvxFileStoreHelper.SafeGetFileStore();
            var files = store.GetFilesIn(_cacheFolder);

            // we don't use Linq because of AOT/JIT problem on MonoTouch :/
            //var cachedFiles = _entriesByHttpUrl.ToDictionary(x => x.Value.DownloadedPath);
            var cachedFiles = new Dictionary <string, Entry>();

            foreach (var e in _entriesByHttpUrl)
            {
                cachedFiles[store.NativePath(e.Value.DownloadedPath)] = e.Value;
            }

            var toDelete = new List <string>();

            foreach (var file in files)
            {
                if (!cachedFiles.ContainsKey(file))
                {
                    if (!file.EndsWith(CacheIndexFileName))
                    {
                        toDelete.Add(file);
                    }
                }
            }

            RunSyncOrAsyncWithLock(() =>
            {
                _toDeleteFiles.AddRange(toDelete);
            });
        }
 public void ClearAll()
 {
     RunSyncWithLock(() =>
     {
         var service = MvxFileStoreHelper.SafeGetFileStore();
         foreach (var entries in _entriesByHttpUrl)
         {
             service.DeleteFile(entries.Value.DownloadedPath);
         }
         _entriesByHttpUrl.Clear();
         _indexNeedsSaving = true;
     });
 }
        private void DoRequestLocalFilePath(string httpSource, Action <string> success, Action <Exception> error)
        {
            RunSyncOrAsyncWithLock(() =>
            {
                Entry diskEntry;
                if (_entriesByHttpUrl.TryGetValue(httpSource, out diskEntry))
                {
                    var service = MvxFileStoreHelper.SafeGetFileStore();
                    if (!service.Exists(diskEntry.DownloadedPath))
                    {
                        _entriesByHttpUrl.Remove(httpSource);
                    }
                    else
                    {
                        diskEntry.WhenLastAccessedUtc = DateTime.UtcNow;
                        DoFilePathCallback(diskEntry, success, error);
                        return;
                    }
                }

                List <CallbackPair> currentlyRequested;
                if (_currentlyRequested.TryGetValue(httpSource, out currentlyRequested))
                {
                    currentlyRequested.Add(new CallbackPair(success, error));
                    return;
                }

                currentlyRequested = new List <CallbackPair>
                {
                    new CallbackPair(success, error)
                };
                _currentlyRequested.Add(httpSource, currentlyRequested);
                var downloader      = Mvx.Resolve <IMvxHttpFileDownloader>();
                var fileService     = MvxFileStoreHelper.SafeGetFileStore();
                var pathForDownload = fileService.PathCombine(_cacheFolder, Guid.NewGuid().ToString("N"));
                downloader.RequestDownload(httpSource, pathForDownload,
                                           () => OnDownloadSuccess(httpSource, pathForDownload),
                                           exception => OnDownloadError(httpSource, exception));
            });
        }
        private void ProcessResponse(WebRequest request, IAsyncResult result)
        {
            try
            {
                var fileService  = MvxFileStoreHelper.SafeGetFileStore();
                var tempFilePath = DownloadPath + ".tmp";

                using (var resp = request.EndGetResponse(result))
                {
                    using (var s = resp.GetResponseStream())
                    {
                        fileService.WriteFile(tempFilePath,
                                              fileStream =>
                        {
                            var buffer = new byte[4 * 1024];
                            int count;
                            while ((count = s.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                fileStream.Write(buffer, 0, count);
                            }
                        });
                    }
                }
                fileService.TryMove(tempFilePath, DownloadPath, true);
            }
            //#if !NETFX_CORE
            //            catch (ThreadAbortException)
            //            {
            //                throw;
            //            }
            //#endif
            catch (Exception exception)
            {
                FireDownloadFailed(exception);
                return;
            }

            FireDownloadComplete();
        }
        private void EnsureCacheFolderExists()
        {
            var store = MvxFileStoreHelper.SafeGetFileStore();

            store.EnsureFolderExists(_cacheFolder);
        }