forked from microsoft/XamarinAzure_ShoppingDemoApp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImagesFileSyncHandler.cs
executable file
·75 lines (60 loc) · 2.51 KB
/
ImagesFileSyncHandler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
namespace Shopping.DemoApp
{
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.MobileServices.Eventing;
using Microsoft.WindowsAzure.MobileServices.Files;
using Microsoft.WindowsAzure.MobileServices.Files.Metadata;
using Microsoft.WindowsAzure.MobileServices.Files.Sync;
using Microsoft.WindowsAzure.MobileServices.Sync;
using PCLStorage;
using Shopping.DemoApp.Events;
using Shopping.DemoApp.Models;
using Shopping.DemoApp.Services;
public class ImagesFileSyncHandler : IFileSyncHandler
{
private static object currentDownloadTaskLock = new object();
private static Task currentDownloadTask = Task.FromResult(0);
private IMobileServiceSyncTable<SaleItem> saleItemsTable;
public ImagesFileSyncHandler(IMobileServiceSyncTable<SaleItem> table)
{
saleItemsTable = table;
}
public async Task<IMobileServiceFileDataSource> GetDataSource(MobileServiceFileMetadata metadata)
{
string filePath = await FileHelper.GetLocalFilePathAsync(metadata.ParentDataItemId);
return new PathMobileServiceFileDataSource(filePath);
}
public async Task ProcessFileSynchronizationAction(MobileServiceFile file, FileSynchronizationAction action)
{
if (action == FileSynchronizationAction.Delete)
{
// You can remove images for delete items here
}
else
{
await DownloadFileAsync(file);
}
}
private Task DownloadFileAsync(MobileServiceFile file)
{
lock (currentDownloadTaskLock)
{
return currentDownloadTask =
currentDownloadTask.ContinueWith(x => DoFileDownloadAsync(file)).Unwrap();
}
}
private async Task DoFileDownloadAsync(MobileServiceFile file)
{
var filepath = await FileHelper.GetLocalFilePathAsync(file.ParentId);
var storagePath = FileSystem.Current.LocalStorage.Path;
var fullpath = Path.Combine(storagePath, filepath);
using (System.IO.Stream stream = File.Create(fullpath)) { }
await saleItemsTable.DownloadFileAsync(file, fullpath);
await SaleItemDataService.Instance.MobileService.EventManager
.PublishAsync(new FileDownloadedEvent { Name = file.ParentId });
}
}
}