public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     var mobileServiceFile = new MobileServiceFile();
     serializer.Populate(reader, mobileServiceFile);
     
     return mobileServiceFile;
 }
Example #2
0
        public async static Task UploadAsync(this IMobileServiceClient client, MobileServiceFile file, IMobileServiceFileDataSource dataSource)
        {
            MobileServiceFileMetadata metadata = MobileServiceFileMetadata.FromFile(file);

            IMobileServiceFilesClient filesClient = GetFilesClient(client);
            await filesClient.UploadFileAsync(metadata, dataSource);
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var mobileServiceFile = new MobileServiceFile();

            serializer.Populate(reader, mobileServiceFile);

            return(mobileServiceFile);
        }
        public async static Task <IEnumerable <MobileServiceFile> > GetFilesAsync <T>(this IMobileServiceSyncTable <T> table, T dataItem)
        {
            IFileSyncContext context = table.MobileServiceClient.GetFileSyncContext();

            var fileMetadata = await context.MetadataStore.GetMetadataAsync(table.TableName, GetDataItemId(dataItem));

            return(fileMetadata.Where(m => !m.PendingDeletion).Select(m => MobileServiceFile.FromMetadata(m)));
        }
        public async static Task <MobileServiceFile> AddFileAsync <T>(this IMobileServiceSyncTable <T> table, T dataItem, string fileName)
        {
            MobileServiceFile file = CreateFile(table, dataItem, fileName);

            await AddFileAsync(table, file);

            return(file);
        }
Example #6
0
        public async Task DeleteFileAsync(MobileServiceFile file)
        {
            var operation = new DeleteMobileServiceFileOperation(Guid.NewGuid().ToString(), file.Id);

            await QueueOperationAsync(operation);

            NotifyFileOperationCompletion(file, FileOperationKind.Delete, FileOperationSource.Local);
        }
        private static MobileServiceFile GetFileReference(Models.Image image, string param)
        {
            var toDownload = new MobileServiceFile(image.File.Id, image.File.Name, image.File.TableName, image.File.ParentId) {
                StoreUri = image.File.StoreUri.Replace("lg", param)
            };

            return toDownload;
        }
        public AddNewFileScenario()
        {
            this.inputFile = new MobileServiceFile("id", "name", "tableName", "parentId");
            this.inputFile.ContentMD5 = "md5";
            this.inputFile.Length = 12345;
            this.inputFile.LastModified = new DateTimeOffset(new DateTime(2015, 1, 1, 1, 1, 1));

            SyncContext.AddFileAsync(inputFile).Wait();
        }
        /// <summary>
        /// Convert a <see cref="MobileServiceFileMetadata"/> into a <see cref="MobileServiceFile"/>
        /// </summary>
        /// <param name="metadata">The <see cref="MobileServiceFileMetadata"/> instance</param>
        /// <returns>An equivalent <see cref="MobileServiceFile"/> instance</returns>
        internal static MobileServiceFile FromMetadata(MobileServiceFileMetadata metadata)
        {
            var file = new MobileServiceFile(metadata.FileId, metadata.ParentDataItemType, metadata.ParentDataItemId);

            file.ContentMD5 = metadata.ContentMD5;
            file.LastModified = metadata.LastModified;
            file.Length = metadata.Length;
            file.Metadata = metadata.ToDictionary();
            return file;
        }
        internal static MobileServiceFile FromMetadata(MobileServiceFileMetadata metadata)
        {
            var file = new MobileServiceFile(metadata.FileId, metadata.ParentDataItemType, metadata.ParentDataItemId);

            file.ContentMD5   = metadata.ContentMD5;
            file.LastModified = metadata.LastModified;
            file.Length       = metadata.Length;
            file.Metadata     = metadata.ToDictionary();
            return(file);
        }
        public TodoItemImageViewModel(MobileServiceFile file, TodoItem todoItem, Action<TodoItemImageViewModel> deleteHandler)
        {
            this.deleteHandler = deleteHandler;
            this.uri = FileHelper.GetLocalFilePath(todoItem.Id, file.Name);
            this.name = file.Name;

            this.File = file;

            InitializeCommands();
        }
 public async Task ProcessFileSynchronizationAction(MobileServiceFile file, FileSynchronizationAction action)
 {
     if (action == FileSynchronizationAction.Delete)
     {
         await FileHelper.DeleteLocalFileAsync(file);
     }
     else // Create or update. We're aggressively downloading all files.
     {
         await this.todoItemManager.DownloadFileAsync(file);
     }
 }
        private async Task<StorageToken> GetStorageToken(IMobileServiceClient client, MobileServiceFile file, StoragePermissions permissions)
        {

            var tokenRequest = new StorageTokenRequest();
            tokenRequest.Permissions = permissions;
            tokenRequest.TargetFile = file;

            string route = string.Format("/tables/{0}/{1}/StorageToken", file.TableName, file.ParentId);

            return await this.client.InvokeApiAsync<StorageTokenRequest, StorageToken>(route, tokenRequest);
        }
Example #14
0
        public async Task PullFilesAsync(string tableName, string itemId)
        {
            IEnumerable <MobileServiceFile> files = await this.mobileServiceFilesClient.GetFilesAsync(tableName, itemId);

            foreach (var file in files)
            {
                FileSynchronizationAction syncAction = FileSynchronizationAction.Update;

                MobileServiceFileMetadata metadata = await this.metadataStore.GetFileMetadataAsync(file.Id);

                if (metadata == null)
                {
                    syncAction = FileSynchronizationAction.Create;

                    metadata = MobileServiceFileMetadata.FromFile(file);

                    metadata.ContentMD5   = null;
                    metadata.LastModified = null;
                }

                if (string.Compare(metadata.ContentMD5, file.ContentMD5, StringComparison.Ordinal) != 0 ||
                    (metadata.LastModified == null || metadata.LastModified.Value.ToUniversalTime() != file.LastModified.Value.ToUniversalTime()))
                {
                    metadata.LastModified = file.LastModified;
                    metadata.ContentMD5   = file.ContentMD5;

                    await this.metadataStore.CreateOrUpdateAsync(metadata);

                    await this.syncHandler.ProcessFileSynchronizationAction(file, syncAction);

                    NotifyFileOperationCompletion(file, syncAction.ToFileOperationKind(), FileOperationSource.ServerPull);
                }
            }

            var fileMetadata = await this.metadataStore.GetMetadataAsync(tableName, itemId);

            var deletedItemsMetadata = fileMetadata.Where(m => !files.Any(f => string.Compare(f.Id, m.FileId) == 0));

            foreach (var metadata in deletedItemsMetadata)
            {
                IMobileServiceFileOperation pendingOperation = await this.operationsQueue.GetOperationByFileIdAsync(metadata.FileId);

                // TODO: Need to call into the sync handler for conflict resolution here...
                if (pendingOperation == null || pendingOperation is DeleteMobileServiceFileOperation)
                {
                    await metadataStore.DeleteAsync(metadata);

                    await this.syncHandler.ProcessFileSynchronizationAction(MobileServiceFile.FromMetadata(metadata), FileSynchronizationAction.Delete);

                    NotifyFileOperationCompletion(MobileServiceFile.FromMetadata(metadata), FileOperationKind.Delete, FileOperationSource.ServerPull);
                }
            }
        }
        public static async Task<TodoItemImageViewModel> CreateAsync(MobileServiceFile file, TodoItem todoItem, Action<TodoItemImageViewModel> deleteHandler)
        {
            var result = new TodoItemImageViewModel();

            result.deleteHandler = deleteHandler;
            result.name = file.Name;
            result.File = file;
            result.uri = await FileHelper.GetLocalFilePathAsync(todoItem.Id, file.Name);

            result.InitializeCommands();

            return result;
        }
        public async Task UploadFileAsync(MobileServiceFileMetadata metadata, IMobileServiceFileDataSource dataSource)
        {
            if (metadata == null)
            {
                throw new ArgumentNullException("metadata");
            }

            if (dataSource == null)
            {
                throw new ArgumentNullException("dataSource");
            }

            StorageToken token = await GetStorageToken(this.client, MobileServiceFile.FromMetadata(metadata), StoragePermissions.Write);

            await this.storageProvider.UploadFileAsync(metadata, dataSource, token);
        }
        public async Task ProcessFileSynchronizationAction(MobileServiceFile file, FileSynchronizationAction action)
        {
            try {
                if (action == FileSynchronizationAction.Delete) {
                    await FileHelper.DeleteLocalFileAsync(file, theApp.DataFilesPath);
                }
                else { // Create or update - download large format image by looking for 'lg' in the StoreUri parameter
                    Trace.WriteLine(string.Format("File - storeUri: {1}", file.Name, file.StoreUri));

                    if (file.StoreUri.Contains("lg")) {
                        await this.theApp.DownloadFileAsync(file);
                    }
                }
            }
            catch (Exception e) { // should catch WrappedStorageException, but this type is internal in the Storage SDK!
                Trace.WriteLine("Exception while downloading blob, blob probably does not exist: " + e);
            }
        }
        private async Task DownloadAndDisplayImage(MobileServiceFile file, string imageSize)
        {
            try {
                var path = await FileHelper.GetLocalFilePathAsync(file.ParentId, imageSize + "-" + file.Name, App.Instance.DataFilesPath);
                await App.Instance.imageTableSync.DownloadFileAsync(file, path);
                await Navigation.PushAsync(CreateDetailsPage(path));

                // delete the file
                var fileRef = await FileSystem.Current.LocalStorage.GetFileAsync(path);
                await fileRef.DeleteAsync();
            }
            catch (Exception e) {
                // Note: we should be catching a WrappedStorageException and StorageException here, but WrappedStorageException is
                // internal in the current version of the Azure Storage library
                Debug.WriteLine("Exception downloading file: " + e.Message);
                await DisplayAlert("Error downloading image", "Error downloading, image size might not be available yet", "OK");
            }
        }
Example #19
0
        public async Task AddFileAsync(MobileServiceFile file)
        {
            var metadata = new MobileServiceFileMetadata
            {
                FileId             = file.Id,
                FileName           = file.Name,
                Length             = file.Length,
                Location           = FileLocation.Local,
                ContentMD5         = file.ContentMD5,
                ParentDataItemType = file.TableName,
                ParentDataItemId   = file.ParentId
            };

            await metadataStore.CreateOrUpdateAsync(metadata);

            var operation = new CreateMobileServiceFileOperation(Guid.NewGuid().ToString(), file.Id);

            await QueueOperationAsync(operation);

            NotifyFileOperationCompletion(file, FileOperationKind.Create, FileOperationSource.Local);
        }
        public async Task AddFileAsync(MobileServiceFile file)
        {
            var metadata = new MobileServiceFileMetadata
            {
                FileId = file.Id,
                FileName = file.Name,
                Length = file.Length,
                Location = FileLocation.Local,
                ContentMD5 = file.ContentMD5,
                ParentDataItemType = file.TableName,
                ParentDataItemId = file.ParentId,
                LastModified = DateTimeOffset.Now
            };

            await metadataStore.CreateOrUpdateAsync(metadata);

            var operation = new CreateMobileServiceFileOperation(Guid.NewGuid().ToString(), file.Id);

            await QueueOperationAsync(operation);

            NotifyFileOperationCompletion(file, FileOperationKind.Create, FileOperationSource.Local);
        }
        public static async Task<TodoItemImageViewModel> CreateAsync(MobileServiceFile file, TodoItem todoItem, Action<TodoItemImageViewModel> deleteHandler)
        {
            var result = new TodoItemImageViewModel();

            result.deleteHandler = deleteHandler;
            result.name = file.Name;
            result.File = file;

            var uri = await FileHelper.GetLocalFilePathAsync(todoItem.Id, file.Name);

            // hack until I figure out how to do this cross-platform
            if (Device.OS == TargetPlatform.Windows) {
                result.uri = new Uri(uri).AbsoluteUri;
            }
            else {
                result.uri = uri;
            }

            result.InitializeCommands();

            return result;
        }
Example #22
0
 /// <summary>
 /// Downloads a <paramref name="file"/> and saves it to the local device using the provided <paramref name="targetPath"/>.
 /// </summary>
 /// <typeparam name="T">The type of the instances in the table.</typeparam>
 /// <param name="table">The table instance that contains the record associated with the <see cref="MobileServiceFile"/>.</param>
 /// <param name="file">The <see cref="MobileServiceFile"/> instance representing the file to be downloaded.</param>
 /// <param name="targetPath">The path that will be used to save the downloaded file.</param>
 /// <returns>A <see cref="Task"/> that completes when the download has finished.</returns>
 public async static Task DownloadFileAsync <T>(this IMobileServiceTable <T> table, MobileServiceFile file, string targetPath)
 {
     using (IO.Stream stream = await File.CreateAsync(targetPath))
     {
         await table.DownloadFileToStreamAsync(file, stream);
     }
 }
Example #23
0
        /// <summary>
        /// Uploads a <paramref name="file"/> from a local file specified in the <paramref name="filePath"/>
        /// </summary>
        /// <typeparam name="T">The type of the instances in the table.</typeparam>
        /// <param name="table">The table instance that contains the record associated with the <see cref="MobileServiceFile"/>.</param>
        /// <param name="file">The <see cref="MobileServiceFile"/> instance.</param>
        /// <param name="filePath">The path of the file to be uploaded.</param>
        /// <returns>A <see cref="Task"/> that completes when the upload has finished.</returns>
        public async static Task UploadFileAsync <T>(this IMobileServiceTable <T> table, MobileServiceFile file, string filePath)
        {
            IMobileServiceFileDataSource dataSource = new PathMobileServiceFileDataSource(filePath);

            await table.UploadFileAsync(file, dataSource);
        }
        public async Task DownloadToStreamAsync(MobileServiceFile file, Stream stream)
        {
            StorageToken token = await GetStorageToken(this.client, file, StoragePermissions.Read);

            await this.storageProvider.DownloadFileToStreamAsync(file, stream, token);
        }
        public async Task<Uri> GetFileUriAsync(MobileServiceFile file, StoragePermissions permissions)
        {
            StorageToken token = await GetStorageToken(this.client, file, permissions);

            return await this.storageProvider.GetFileUriAsync(token, file.Name);
        }
 internal async Task DownloadFileAsync(MobileServiceFile file)
 {
     await this.todoTable.DownloadFileAsync(file, FileHelper.GetLocalFilePath(file.ParentId, file.Name));
 }
        public async Task DeleteFileAsync(MobileServiceFile file)
        {
            var operation = new DeleteMobileServiceFileOperation(Guid.NewGuid().ToString(), file.Id);

            await QueueOperationAsync(operation);

            NotifyFileOperationCompletion(file, FileOperationKind.Delete, FileOperationSource.Local);
        }
        public async static Task DeleteFileAsync <T>(this IMobileServiceSyncTable <T> table, MobileServiceFile file)
        {
            IFileSyncContext context = table.MobileServiceClient.GetFileSyncContext();

            await context.DeleteFileAsync(file);

            MobileServiceFileMetadata metadata = await context.MetadataStore.GetFileMetadataAsync(file.Id);

            metadata.PendingDeletion = true;

            await context.MetadataStore.CreateOrUpdateAsync(metadata);
        }
Example #29
0
        public async static Task UploadFromStreamAsync <T>(this IMobileServiceTable <T> table, MobileServiceFile file, Stream fileStream)
        {
            IMobileServiceFileDataSource dataSource = new StreamMobileServiceFileDataSource(fileStream);

            await UploadAsync(table.MobileServiceClient, file, dataSource);
        }
Example #30
0
        public async static Task AddFileAsync <T>(this IMobileServiceTable <T> table, MobileServiceFile file, Stream fileStream)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }

            if (fileStream == null)
            {
                throw new ArgumentNullException("fileStream");
            }

            IMobileServiceFileDataSource dataSource = new StreamMobileServiceFileDataSource(fileStream);

            IMobileServiceFilesClient client = GetFilesClient(table.MobileServiceClient);
            await client.UploadFileAsync(MobileServiceFileMetadata.FromFile(file), dataSource);
        }
Example #31
0
        public async static Task <Uri> GetFileUri <T>(this IMobileServiceTable <T> table, MobileServiceFile file, StoragePermissions permissions)
        {
            IMobileServiceFilesClient filesClient = GetFilesClient(table.MobileServiceClient);

            return(await filesClient.GetFileUriAsync(file, permissions));
        }
Example #32
0
        private async Task DoFileDownloadAsync(MobileServiceFile file)
        {
            Debug.WriteLine("Starting file download - " + file.Name);

            IPlatform platform = DependencyService.Get<IPlatform>();
            var path = await FileHelper.GetLocalFilePathAsync(file.ParentId, file.Name, DataFilesPath);
            var tempPath = Path.ChangeExtension(path, ".temp");

            await platform.DownloadFileAsync(imageTableSync, file, tempPath);

            var fileRef = await FileSystem.Current.LocalStorage.GetFileAsync(tempPath);
            await fileRef.RenameAsync(path, NameCollisionOption.ReplaceExisting);
            Debug.WriteLine("Renamed file to - " + path);

            await MobileService.EventManager.PublishAsync(new ImageDownloadEvent(file.ParentId));
        }
        public async static Task DownloadFileAsync <T>(this IMobileServiceSyncTable <T> table, MobileServiceFile file, string targetPath)
        {
            using (IO.Stream stream = await File.CreateAsync(targetPath))
            {
                IFileSyncContext context = table.MobileServiceClient.GetFileSyncContext();

                await context.MobileServiceFilesClient.DownloadToStreamAsync(file, stream);
            }
        }
 public DeleteFileScenario()
 {
     this.inputFile = new MobileServiceFile("id", "name", "tableName", "parentId");
     
     SyncContext.DeleteFileAsync(inputFile).Wait();
 }
        internal async Task DeleteImage(TodoItem todoItem, MobileServiceFile file)
        {
            // FILES: Deleting file
            await this.todoTable.DeleteFileAsync(file);

            // "Touch" the record to mark it as updated
            await this.todoTable.UpdateAsync(todoItem);
        }
        internal async Task DownloadFileAsync(MobileServiceFile file)
        {
            var todoItem = await todoTable.LookupAsync(file.ParentId);
            Debug.WriteLine ("++ Downloading file: " + todoItem.Name);

            IPlatform platform = DependencyService.Get<IPlatform>();

            string filePath = await FileHelper.GetLocalFilePathAsync(file.ParentId, file.Name); 
            await platform.DownloadFileAsync(this.todoTable, file, filePath);
        }
        public async static Task AddFileAsync <T>(this IMobileServiceSyncTable <T> table, MobileServiceFile file)
        {
            IFileSyncContext context = table.MobileServiceClient.GetFileSyncContext();

            await context.AddFileAsync(file);
        }
        public async Task DownloadFileToStreamAsync(MobileServiceFile file, Stream stream, StorageToken storageToken)
        {
            CloudBlockBlob blob = GetBlobReference(storageToken, file.Name);

            await blob.DownloadToStreamAsync(stream);
        }
Example #39
0
 public async static Task UploadFileAsync <T>(this IMobileServiceTable <T> table, MobileServiceFile file, IMobileServiceFileDataSource dataSource)
 {
     await UploadAsync(table.MobileServiceClient, file, dataSource);
 }
Example #40
0
        public async static Task DeleteFileAsync <T>(this IMobileServiceTable <T> table, MobileServiceFile file)
        {
            MobileServiceFileMetadata metadata = MobileServiceFileMetadata.FromFile(file);

            IMobileServiceFilesClient client = GetFilesClient(table.MobileServiceClient);
            await client.DeleteFileAsync(metadata);
        }
Example #41
0
 public async static Task DownloadFileToStreamAsync <T>(this IMobileServiceTable <T> table, MobileServiceFile file, Stream fileStream)
 {
     IMobileServiceFilesClient filesClient = GetFilesClient(table.MobileServiceClient);
     await filesClient.DownloadToStreamAsync(file, fileStream);
 }
Example #42
0
        internal async Task DeleteImage(Monkey monkey, MobileServiceFile file)
        {
            // FILES: Deleting file
            await this.monkeyTable.DeleteFileAsync(file);

            // "Touch" the record to mark it as updated
            await this.monkeyTable.UpdateAsync(monkey);
        }
Example #43
0
        internal void NotifyFileOperationCompletion(MobileServiceFile file, FileOperationKind fileOperationKind, FileOperationSource source)
        {
            var operationCompletedEvent = new FileOperationCompletedEvent(file, fileOperationKind, source);

            this.eventManager.PublishAsync(operationCompletedEvent).ContinueWith(t => t.Exception.Handle(e => true), TaskContinuationOptions.OnlyOnFaulted);
        }
        internal void NotifyFileOperationCompletion(MobileServiceFile file, FileOperationKind fileOperationKind, FileOperationSource source)
        {
            var operationCompletedEvent = new FileOperationCompletedEvent(file, fileOperationKind, source);

            this.eventManager.PublishAsync(operationCompletedEvent).ContinueWith(t => t.Exception.Handle(e => true), TaskContinuationOptions.OnlyOnFaulted);
        }
        public async Task DownloadToStreamAsync(MobileServiceFile file, Stream stream)
        {
            StorageToken token = await GetStorageToken(this.client, file, StoragePermissions.Read);

            await this.storageProvider.DownloadFileToStreamAsync(file, stream, token);
        }
        public async Task <Uri> GetFileUriAsync(MobileServiceFile file, StoragePermissions permissions)
        {
            StorageToken token = await GetStorageToken(this.client, file, permissions);

            return(await this.storageProvider.GetFileUriAsync(token, file.Name));
        }
        public async static Task UploadFileAsync <T>(this IMobileServiceSyncTable <T> table, MobileServiceFile file, string filePath)
        {
            IMobileServiceFileDataSource dataSource = new PathMobileServiceFileDataSource(filePath);

            MobileServiceFileMetadata metadata = MobileServiceFileMetadata.FromFile(file);

            IFileSyncContext context = table.MobileServiceClient.GetFileSyncContext();

            await context.MobileServiceFilesClient.UploadFileAsync(metadata, dataSource);
        }
 private async Task <StorageToken> GetStorageToken(IMobileServiceClient client, MobileServiceFileMetadata metadata, StoragePermissions permissions)
 {
     return(await GetStorageToken(client, MobileServiceFile.FromMetadata(metadata), permissions));
 }
Example #49
0
 internal Task DownloadFileAsync(MobileServiceFile file)
 {
     // should only download one file at a time, since it's possible to get duplicate notifications for the same file
     // ContinueWith is used along with Wait() so that only one thread downloads at a time
     lock (currentDownloadTaskLock) {
         return currentDownloadTask =
             currentDownloadTask.ContinueWith(x => DoFileDownloadAsync(file)).Unwrap();
     }
 }
        private async Task <StorageToken> GetStorageToken(IMobileServiceClient client, MobileServiceFile file, StoragePermissions permissions)
        {
            var tokenRequest = new StorageTokenRequest();

            tokenRequest.Permissions = permissions;
            tokenRequest.TargetFile  = file;

            string route = string.Format("/tables/{0}/{1}/StorageToken", file.TableName, file.ParentId);

            return(await this.client.InvokeApiAsync <StorageTokenRequest, StorageToken>(route, tokenRequest));
        }
Example #51
0
 internal async Task DeleteImageAsync(Models.Image item, MobileServiceFile file)
 {
     await imageTableSync.DeleteFileAsync(file);
 }
        public async Task ProcessFileSynchronizationAction(MobileServiceFile file, FileSynchronizationAction action)
        {

        }