예제 #1
0
        /// <summary>
        /// Return current size of user isolated storage
        /// </summary>
        /// <returns></returns>
        public static long GetCurretnSize(this IsolatedStorageFile store)
        {
            List <String> files = store.GetAllFiles();
            long          res   = 0;

            foreach (string name in files)
            {
                //FileInfo f = new FileInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), name));
                IsolatedStorageFileStream fs = store.OpenFile(name, FileMode.Open, FileAccess.Read);
                res += fs.Length;
                fs.Close();
            }
            return(res);
        }
예제 #2
0
        /// <summary>
        /// Returns an enumerable of paths of savegames that don't belong to any cartridge tag.
        /// </summary>
        /// <returns></returns>
        public IEnumerable <string> GetOrphanSavegameFiles()
        {
            List <string> files;

            // Gets all savegame files in the isolated storage.
            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                files = isf.GetAllFiles("*.gws").Select(s => "/" + s).ToList();
            }

            // Removes all savegame files that are associated to this tag.
            foreach (CartridgeTag tag in this)
            {
                foreach (CartridgeSavegame cs in tag.Savegames)
                {
                    files.Remove(cs.SavegameFile);
                }
            }

            return(files);
        }
예제 #3
0
        private void OnLiveClientGetRootChildrenCompleted(System.Threading.Tasks.Task <LiveOperationResult> task)
        {
            if (!CheckTaskCompleted(task, "Get root children failed."))
            {
                EndSyncDownloads();
                return;
            }

            LiveOperationResult res = task.Result;

            // No result? Nothing to do.
            if (res.Result == null)
            {
                Log("Get root children returned no results.");
                EndSyncDownloads();
                return;
            }

            // Sync Step 2: We are getting results for the app root folder.
            // We need to enumerate through all file entries to download GWC and GWS files.

            List <object> data = (List <object>)res.Result["data"];

            // Enumerates through all the file entries.
            List <OneDriveFile> cartFiles  = new List <OneDriveFile>();
            List <OneDriveFile> extraFiles = new List <OneDriveFile>();

            foreach (IDictionary <string, object> content in data)
            {
                // Is it a cartridge file?
                string name  = (string)content["name"];
                string lname = name.ToLower();
                object type  = content["type"];
                try
                {
                    Log("Found " + type + " called " + lname);
                }
                catch (Exception)
                {
                }
                if ("file".Equals(type))
                {
                    if (lname.EndsWith(".gwc"))
                    {
                        // Adds the file to the list of cartridges.
                        Log("Marked as cartridge to download: " + name);
                        cartFiles.Add(new OneDriveFile((string)content["id"], name, IsoStoreCartridgesPath));
                    }
                    else if (lname.EndsWith(".gws"))
                    {
                        // Adds the file to the list of extra files.
                        Log("Marked as extra file to download: " + name);
                        extraFiles.Add(new OneDriveFile((string)content["id"], name, IsoStoreCartridgeContentPath));
                    }
                }
            }

            // Creates the list of cartridges in the isostore that do not exist on OneDrive anymore.
            // These will be removed. Extra files are not removed even if they are not on OneDrive anymore.
            List <string> isoStoreFiles;
            List <string> toRemoveFiles;
            List <string> isoStoreExtraFiles;

            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                isoStoreExtraFiles = isf.GetAllFiles(IsoStoreCartridgeContentPath + "/*.gws");

                isoStoreFiles =
                    isf
                    .GetFileNames(GetIsoStorePath("*.gwc", IsoStoreCartridgesPath))
                    .Select(s => IsoStoreCartridgesPath + "/" + s)
                    .ToList();

                toRemoveFiles =
                    isoStoreFiles
                    .Where(s => !cartFiles.Any(sd => sd.Name == System.IO.Path.GetFileName(s)))
                    .ToList();
            }

            // Clears from the list of extra files to download those which
            // are already somewhere in the isolated storage.
            foreach (OneDriveFile ef in extraFiles.ToList())
            {
                if (isoStoreExtraFiles.Any(s => s.EndsWith("/" + ef.Name, StringComparison.InvariantCultureIgnoreCase)))
                {
                    // The file needn't be downloaded.
                    Log("Unmarked download because it exists locally: " + ef);
                    extraFiles.Remove(ef);
                }
            }

            // Creates the list of cartridges and extra files that are on OneDrive but
            // not in the isolated storage.
            List <OneDriveFile> toDlFiles = cartFiles
                                            .Where(sd => !isoStoreFiles.Contains(GetIsoStorePath(sd.Name, sd.DownloadDirectory)))
                                            .Union(extraFiles)
                                            .ToList();

            foreach (OneDriveFile file in toDlFiles)
            {
                Log("Scheduled to download: " + file);
            }
            Log("Total count of scheduled downloads: " + toDlFiles.Count);

            foreach (string fileName in toRemoveFiles)
            {
                Log("Scheduled to remove locally: " + fileName);
            }
            Log("Total count of scheduled local removals: " + toRemoveFiles.Count);

            // Bakes an event for when the sync will be over.
            lock (_syncRoot)
            {
                _syncEventArgs = new CartridgeProviderSyncEventArgs()
                {
                    AddedFiles = toDlFiles
                                 .Select(sd => GetIsoStorePath(sd.Name, sd.DownloadDirectory))
                                 .ToList(),
                    ToRemoveFiles = toRemoveFiles
                };
            }

            // Sends a progress event for removing the files marked to be removed.
            if (toRemoveFiles.Count > 0)
            {
                RaiseSyncProgress(toRemoveFiles: toRemoveFiles);
            }

            // Starts downloading all new files, or terminate the sync if no new file is to be downloaded.
            if (toDlFiles.Count > 0)
            {
                toDlFiles.ForEach(sd => BeginDownloadFile(sd));
            }
            else
            {
                EndSyncDownloads();
            }
        }
예제 #4
0
        private async void BeginUploads()
        {
            // Makes a list of files to upload.
            Dictionary <string, DateTime> uploadCandidates;

            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                uploadCandidates = isf.GetAllFiles("/*.gws")
                                   .Union(isf.GetAllFiles("/*.gwl")
                                          .Where(s => ("/" + s).StartsWith(IsoStoreCartridgeContentPath)))
                                   .ToDictionary(s => s, s => isf.GetLastWriteTime(s).DateTime.ToUniversalTime());
            }

            // Returns if there is nothing to upload.
            if (uploadCandidates.Count < 1)
            {
                EndSync();
                return;
            }

            // Creates or fetches the upload folder.
            if (_uploadsFolderId == null)
            {
                try
                {
                    _uploadsFolderId = await CreateDirectoryAsync(UploadFolderName, _rootFolderId);
                }
                catch (Exception)
                {
                    Log("Error while ensuring Uploads folder.");
                    EndSync();
                    return;
                }
            }

            // Gets the list of files currently in the Uploads folder and removes from the upload candidates
            // the files that are identical to their remote counterpart.
            LiveOperationResult r = await _liveClient.GetAsync(_uploadsFolderId + "/files", CreateTimeoutCancellationToken(GetRequestTimeoutTimeSpan));

            dynamic result = r.Result;

            foreach (dynamic file in result.data)
            {
                // We only consider files in the upload directory.
                if (file.type != "file")
                {
                    continue;
                }

                // If the file name has no match in the upload candidates, go on.
                KeyValuePair <string, DateTime> candidate = uploadCandidates
                                                            .FirstOrDefault(kvp => Path.GetFileName(kvp.Key) == file.name);
                if (candidate.Key == null)
                {
                    continue;
                }

                // We have a match. If the remote file is more recent than the local file,
                // removes the candidate from the list of candidates.
                try
                {
                    DateTime remoteLastModified = DateTime.Parse(file.updated_time).ToUniversalTime();
                    if (remoteLastModified >= candidate.Value)
                    {
                        uploadCandidates.Remove(candidate.Key);
                        Log("Won't upload " + candidate.Key + " because it is same as, or older than remote file.");
                    }
                }
                catch (Exception)
                {
                    // We ignore exceptions and let this file be uploaded.
                }
            }

            // Returns if there is nothing to upload.
            if (uploadCandidates.Count < 1)
            {
                EndSync();
                return;
            }

            // Stores the list of files to upload.
            lock (_syncRoot)
            {
                _ulFiles = uploadCandidates.Keys.ToList();
            }

            foreach (string item in uploadCandidates.Keys)
            {
                Log("Scheduled for upload " + item);
            }

            // Starts uploading the first file. The next ones will be triggered once it finished uploading.
            string firstFile = _ulFiles[0];

            BeginUpload(firstFile);
        }