summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Platform.WinRT/WindowsBasePlatformServices.cs
blob: 614a0972f8a46ff9ba47d49ff72e340c42140de4 (plain)
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
´╗┐using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Reflection;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Core;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage;
using Windows.Storage.Search;
using Windows.Storage.Streams;
using Windows.System;
using Windows.UI.Core;
using Windows.UI.Xaml;

#if WINDOWS_UWP

namespace Xamarin.Forms.Platform.UWP
#else

namespace Xamarin.Forms.Platform.WinRT
#endif
{
	internal abstract class WindowsBasePlatformServices : IPlatformServices
	{
		 CoreDispatcher _dispatcher;

		public WindowsBasePlatformServices(CoreDispatcher dispatcher)
		{
			if (dispatcher == null)
				throw new ArgumentNullException("dispatcher");

			_dispatcher = dispatcher;
		}

		public void BeginInvokeOnMainThread(Action action)
		{
			_dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => action()).WatchForError();
		}

		public ITimer CreateTimer(Action<object> callback)
		{
			return new WindowsTimer(new Timer(o => callback(o), null, Timeout.Infinite, Timeout.Infinite));
		}

		public ITimer CreateTimer(Action<object> callback, object state, int dueTime, int period)
		{
			return new WindowsTimer(new Timer(o => callback(o), state, dueTime, period));
		}

		public ITimer CreateTimer(Action<object> callback, object state, long dueTime, long period)
		{
			return CreateTimer(callback, state, TimeSpan.FromMilliseconds(dueTime), TimeSpan.FromMilliseconds(period));
		}

		public ITimer CreateTimer(Action<object> callback, object state, TimeSpan dueTime, TimeSpan period)
		{
			return new WindowsTimer(new Timer(o => callback(o), state, dueTime, period));
		}

		public ITimer CreateTimer(Action<object> callback, object state, uint dueTime, uint period)
		{
			return CreateTimer(callback, state, TimeSpan.FromMilliseconds(dueTime), TimeSpan.FromMilliseconds(period));
		}

		public virtual Assembly[] GetAssemblies()
		{
			var options = new QueryOptions { FileTypeFilter = { ".exe", ".dll" } };

			StorageFileQueryResult query = Package.Current.InstalledLocation.CreateFileQueryWithOptions(options);
			IReadOnlyList<StorageFile> files = query.GetFilesAsync().AsTask().Result;

			var assemblies = new List<Assembly>(files.Count);
			for (var i = 0; i < files.Count; i++)
			{
				StorageFile file = files[i];
				try
				{
					Assembly assembly = Assembly.Load(new AssemblyName { Name = Path.GetFileNameWithoutExtension(file.Name) });

					assemblies.Add(assembly);
				}
				catch (IOException)
				{
				}
				catch (BadImageFormatException)
				{
				}
			}

			Assembly thisAssembly = GetType().GetTypeInfo().Assembly;
			// this happens with .NET Native
			if (!assemblies.Contains(thisAssembly))
				assemblies.Add(thisAssembly);

			return assemblies.ToArray();
		}

		public string GetMD5Hash(string input)
		{
			HashAlgorithmProvider algorithm = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
			IBuffer buffer = algorithm.HashData(Encoding.Unicode.GetBytes(input).AsBuffer());
			return CryptographicBuffer.EncodeToHexString(buffer);
		}

		public double GetNamedSize(NamedSize size, Type targetElementType, bool useOldSizes)
		{
			return size.GetFontSize();
		}

		public async Task<Stream> GetStreamAsync(Uri uri, CancellationToken cancellationToken)
		{
			using (var client = new HttpClient())
			{
				HttpResponseMessage streamResponse = await client.GetAsync(uri.AbsoluteUri).ConfigureAwait(false);
				return streamResponse.IsSuccessStatusCode ? await streamResponse.Content.ReadAsStreamAsync().ConfigureAwait(false) : null;
			}
		}

		public IIsolatedStorageFile GetUserStoreForApplication()
		{
			return new WindowsIsolatedStorage(ApplicationData.Current.LocalFolder);
		}

		public bool IsInvokeRequired => !CoreApplication.MainView.CoreWindow.Dispatcher.HasThreadAccess;

		public void OpenUriAction(Uri uri)
		{
			Launcher.LaunchUriAsync(uri).WatchForError();
		}

		public void StartTimer(TimeSpan interval, Func<bool> callback)
		{
			var timer = new DispatcherTimer { Interval = interval };
			timer.Start();
			timer.Tick += (sender, args) =>
			{
				bool result = callback();
				if (!result)
					timer.Stop();
			};
		}

		internal class WindowsTimer : ITimer
		{
			readonly Timer _timer;

			public WindowsTimer(Timer timer)
			{
				_timer = timer;
			}

			public void Change(int dueTime, int period)
			{
				_timer.Change(dueTime, period);
			}

			public void Change(long dueTime, long period)
			{
				Change(TimeSpan.FromMilliseconds(dueTime), TimeSpan.FromMilliseconds(period));
			}

			public void Change(TimeSpan dueTime, TimeSpan period)
			{
				_timer.Change(dueTime, period);
			}

			public void Change(uint dueTime, uint period)
			{
				Change(TimeSpan.FromMilliseconds(dueTime), TimeSpan.FromMilliseconds(period));
			}
		}
	}
}