/
Utils.cs
610 lines (527 loc) · 17.2 KB
/
Utils.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
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
#region Copyright (C) 2005-2011 Team MediaPortal
// Copyright (C) 2005-2011 Team MediaPortal
// http://www.team-mediaportal.com
//
// MediaPortal is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// MediaPortal is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with MediaPortal. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Windows.Forms;
using System.IO;
using System.Resources;
using System.Globalization;
using System.Xml;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace MediaPortal.DeployTool
{
public class SimpleCultureInfo
{
public string nativeName;
public string name;
public SimpleCultureInfo(string name, string nativeName)
{
this.name = name;
this.nativeName = nativeName;
}
public override string ToString()
{
return nativeName;
}
}
public sealed class Localizer
{
#region Singleton implementation
private static readonly Localizer _instance = new Localizer();
private Localizer()
{
_rscMan = new ResourceManager("MediaPortal.DeployTool.MediaPortal.DeployTool",
System.Reflection.Assembly.GetExecutingAssembly());
}
public static Localizer Instance
{
get { return _instance; }
}
#endregion
#region Variables
private readonly ResourceManager _rscMan;
#endregion
public string GetString(string id)
{
return _rscMan.GetString(id);
}
public string GetDefaultString(string id)
{
return _rscMan.GetString(id, new CultureInfo("en-US"));
}
public static void SwitchCulture(string cultureId)
{
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo(cultureId);
}
public static string GetBestTranslation(string ID)
{
string _translation = Instance.GetString(ID);
return _translation.Length > 0 ? _translation : Instance.GetDefaultString(ID);
}
}
internal class Utils
{
#region DialogHelper
public static void ErrorDlg(string msg)
{
MessageBox.Show(msg, "MediaPortal Deploy Tool -- Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Environment.Exit(-1);
}
#endregion
#region Download
public static string GetDownloadString(string session_id, string node_id)
{
XmlDocument doc = new XmlDocument();
HTTPDownload dlg = new HTTPDownload();
string XmlFile = Application.StartupPath + "\\ApplicationLocations.xml";
const string XmlUrl = "http://install.team-mediaportal.com/DeployTool/ApplicationLocations.xml";
//HTTP update of the xml file with the application download URLs
if (!File.Exists(XmlFile))
{
dlg.ShowDialog(XmlUrl, XmlFile, GetUserAgentOsString());
}
try
{
doc.Load(XmlFile);
XmlNode node = doc.SelectSingleNode("/Applications/" + session_id + "/" + node_id);
return node.InnerText;
}
catch
{
MessageBox.Show(Localizer.GetBestTranslation("DownloadSettings_failed"), XmlUrl, MessageBoxButtons.OK,
MessageBoxIcon.Stop);
File.Delete(XmlFile);
Environment.Exit(-2);
}
return String.Empty;
}
public static DialogResult DownloadFile(string FileName, string prg)
{
DialogResult result;
if (GetDownloadString(prg, "TYPE") == "Manual")
{
ManualDownload dlg = new ManualDownload();
result = dlg.ShowDialog(GetDownloadString(prg, "URL"), Path.GetFileName(FileName),
Application.StartupPath + "\\deploy");
}
else
{
HTTPDownload dlg = new HTTPDownload();
result = dlg.ShowDialog(GetDownloadString(prg, "URL"), FileName, GetUserAgentOsString());
}
return result;
}
public static DialogResult RetryDownloadFile(string FileName, string prg)
{
DialogResult result = DialogResult.Cancel;
FileInfo FileInfo = new FileInfo(FileName);
for (int i = 0; i < 5; i++)
{
if (File.Exists(FileName))
{
FileInfo.Refresh();
if (FileInfo.Length > 10000)
{
break;
}
result = DownloadFile(FileName, prg);
}
else
result = DownloadFile(FileName, prg);
if (result == DialogResult.Cancel) break;
}
return result;
}
public static string LocalizeDownloadFile(string filename, string downloadtype, string prg)
{
// LangCode = "ITA"
string LangCode = InstallationProperties.Instance["DownloadThreeLetterWindowsLanguageName"];
if (String.IsNullOrEmpty(LangCode))
{
LangCode = CultureInfo.InstalledUICulture.ThreeLetterWindowsLanguageName;
}
// LangCodeExt = "it-IT"
string LangCodeExt = InstallationProperties.Instance["DownloadLanguageName"];
if (String.IsNullOrEmpty(LangCodeExt))
{
LangCodeExt = CultureInfo.InstalledUICulture.Name;
}
string NewFileName = filename;
// WMP11 native language download
if (prg == InstallationChecks.WindowsMediaPlayerChecker.prg)
{
string arch = InstallationProperties.Instance["DownloadArch"];
if (arch == "64")
{
NewFileName = filename.Replace("x86", "x64").Split('.')[0] + "-ENU.exe";
}
else
{
string suffix = LangCode == "ENU" ? LangCode : LangCodeExt;
NewFileName = filename.Split('.')[0] + "-" + suffix + ".exe";
}
}
return NewFileName;
}
private static string GetUserAgentOsString()
{
return "Windows NT " + OSInfo.OSInfo.OSMajorVersion + "." + OSInfo.OSInfo.OSMinorVersion;
}
#endregion
#region Uninstall
public static void UninstallNSIS(string RegistryFullPathName)
{
string FileName = Path.GetFileName(RegistryFullPathName);
string Directory = Path.GetDirectoryName(RegistryFullPathName);
string TempFullPathName = Environment.GetEnvironmentVariable("TEMP") + "\\" + FileName;
File.Copy(RegistryFullPathName, TempFullPathName, true);
Process setup = Process.Start(TempFullPathName, " /S _?=" + Directory);
if (setup != null)
{
setup.WaitForExit();
}
File.Delete(TempFullPathName);
}
public static void UninstallMSI(string clsid)
{
Process setup = Process.Start("msiexec.exe", "/x " + clsid + " /qn");
if (setup != null)
{
setup.WaitForExit();
}
CheckUninstallString(clsid, true);
}
public static string CheckUninstallString(string clsid, bool delete)
{
string keyPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\" + clsid;
RegistryKey key = Registry.LocalMachine.OpenSubKey(keyPath);
if (key != null)
{
string strUninstall = key.GetValue("UninstallString").ToString();
if (File.Exists(strUninstall))
{
key.Close();
return strUninstall;
}
if (delete)
{
key.DeleteSubKeyTree(keyPath);
}
key.Close();
}
return null;
}
public static CheckResult CheckNSISUninstallString(string RegistryPath, string MementoSection)
{
CheckResult result = new CheckResult();
result.state = CheckState.NOT_INSTALLED;
RegistryKey key =
Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\" + RegistryPath);
if (key != null)
{
int _IsInstalled = (int)key.GetValue(MementoSection, 0);
int major = (int)key.GetValue("VersionMajor", 0);
int minor = (int)key.GetValue("VersionMinor", 0);
int revision = (int)key.GetValue("VersionRevision", 0);
key.Close();
Version ver = new Version(major, minor, revision);
#if DEBUG
MessageBox.Show("Registry version = <" + ver + ">, IsUpdatable= " + IsPackageUpdatabled(ver) + ", IsInstalled=" + _IsInstalled,
"Debug information: " + MementoSection, MessageBoxButtons.OK, MessageBoxIcon.Warning);
#endif
if (_IsInstalled == 1)
{
result.state = IsPackageUpdatabled(ver) ? CheckState.VERSION_MISMATCH : CheckState.INSTALLED;
}
else
{
result.state = CheckState.NOT_INSTALLED;
}
}
return result;
}
#endregion
#region Misc checks
public static bool CheckTargetDir(string dir)
{
if (dir == "")
return false;
if (Directory.Exists(dir))
return true;
try
{
Directory.CreateDirectory(dir);
}
catch
{
return false;
}
return true;
}
public static bool CheckFileVersion(string aFilePath, string aMinimumVersion, out Version aCurrentVersion)
{
aCurrentVersion = new Version(0, 0, 0, 0);
try
{
Version desiredVersion = new Version(aMinimumVersion);
FileVersionInfo fileVersion = FileVersionInfo.GetVersionInfo(aFilePath);
if (!string.IsNullOrEmpty(fileVersion.ProductVersion))
{
// Replace "," with "." because of versioning localization issues
aCurrentVersion = new Version(fileVersion.ProductVersion.Replace(',', '.'));
return aCurrentVersion >= desiredVersion;
}
return false;
}
catch (Exception)
{
return false;
}
}
public static bool CheckStartupPath()
{
try
{
if (Directory.GetCurrentDirectory().StartsWith("\\"))
{
MessageBox.Show("Please start installation from a local drive.", Application.StartupPath, MessageBoxButtons.OK,
MessageBoxIcon.Stop);
return false;
}
FileInfo file = new FileInfo(Application.ExecutablePath);
DirectoryInfo dir = file.Directory;
if (dir != null)
{
if ((dir.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
MessageBox.Show("Need write access to startup directory.", Application.StartupPath, MessageBoxButtons.OK,
MessageBoxIcon.Stop);
return false;
}
}
return true;
}
catch
{
MessageBox.Show("Unable to determine startup path. Please try running from a local drive with write access.",
Application.StartupPath, MessageBoxButtons.OK, MessageBoxIcon.Stop);
return false;
}
}
#endregion
#region NotifyReboot
public static bool AutoRunApplication(string action)
{
const string desc = "MediaPortal Installation";
RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (key != null)
{
if (action == "set")
{
key.SetValue(desc, Application.ExecutablePath);
}
else
{
try
{
key.DeleteValue(desc, true);
}
catch
{
return false;
}
}
key.Close();
}
return true;
}
public static void NotifyReboot(string DisplayName)
{
// Write Run registry key
Utils.AutoRunApplication("set");
// Notify about the needed reboot
MessageBox.Show(Localizer.GetBestTranslation("Reboot_Required"), DisplayName, MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
//Close DeployTool
Environment.Exit(-3);
}
#endregion
#region Operation System Version Check
public static void CheckPrerequisites()
{
DialogResult res;
switch (OSInfo.OSInfo.GetOSSupported())
{
case OSInfo.OSInfo.OsSupport.Blocked:
MessageBox.Show(Localizer.GetBestTranslation("OS_Support"), OSInfo.OSInfo.GetOSDisplayVersion(),
MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
break;
case OSInfo.OSInfo.OsSupport.NotSupported:
res = MessageBox.Show(Localizer.GetBestTranslation("OS_Warning"), OSInfo.OSInfo.GetOSDisplayVersion(),
MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
if (res == DialogResult.Cancel) Application.Exit();
break;
}
if (OSInfo.OSInfo.OSServicePackMinor != 0)
{
res = MessageBox.Show(Localizer.GetBestTranslation("OS_Beta"), OSInfo.OSInfo.GetOSDisplayVersion(),
MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
if (res == DialogResult.Cancel) Application.Exit();
}
}
#endregion
#region IsWow64 check
[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsWow64Process(
[In] IntPtr hProcess,
[Out] out bool lpSystemInfo
);
public static bool Check64bit()
{
//IsWow64Process is not supported under Windows2000
if (!OSInfo.OSInfo.XpOrLater())
{
return false;
}
Process p = Process.GetCurrentProcess();
IntPtr handle = p.Handle;
bool isWow64;
bool success = IsWow64Process(handle, out isWow64);
if (!success)
{
throw new System.ComponentModel.Win32Exception();
}
return isWow64;
}
#endregion
#region Aero check
[DllImport("dwmapi.dll")]
public static extern int DwmIsCompositionEnabled(ref int pfEnabled);
public static bool IsAeroEnabled()
{
int enabled = 0;
try
{
DwmIsCompositionEnabled(ref enabled);
}
catch (DllNotFoundException)
{
return false;
}
return (enabled == 1);
}
#endregion
#region Logging
private static readonly string _filePath = Application.StartupPath + "\\deploy\\DeployTool-" +
DateTime.Now.ToString("dd-MM-yyyy HH_mm") + ".log";
public void Log(string message)
{
DateTime dt = DateTime.Now;
if (!File.Exists(_filePath))
{
FileStream fs = File.Create(_filePath);
fs.Close();
}
try
{
StreamWriter sw = File.AppendText(_filePath);
sw.WriteLine(dt.ToString("hh:mm:ss") + " " + message);
sw.Flush();
sw.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
#endregion
#region Version & Registry checks
public static bool IsOfficialBuild(string build)
{
//
// All official releases has "0" as build number
// but 1.1.0 RC2 that was 25546
//
return (build == "0" || build == "25546");
}
public static Version GetPackageVersion(string type)
{
int major = 0;
int minor = 0;
int revision = 0;
switch (type)
{
case "min":
major = 1;
minor = 0;
revision = 5; // 1.0.5 = 1.1.0 RC1
break;
case "max":
major = 1;
minor = 2;
revision = 1;
break;
}
Version ver = new Version(major, minor, revision);
return ver;
}
public static bool IsPackageUpdatabled(Version pkgVer)
{
if (pkgVer.CompareTo(GetPackageVersion("min")) >= 0 &&
pkgVer.CompareTo(GetPackageVersion("max")) <= 0)
{
return true;
}
return false;
}
public static string PathFromRegistry(string regkey)
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(regkey);
string Tv3Path = null;
if (key != null)
{
Tv3Path = (string)key.GetValue("UninstallString");
key.Close();
}
return Tv3Path;
}
public static Version VersionFromRegistry(string regkey)
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(regkey);
int major = 0;
int minor = 0;
int revision = 0;
if (key != null)
{
major = (int)key.GetValue("VersionMajor", 0);
minor = (int)key.GetValue("VersionMinor", 0);
revision = (int)key.GetValue("VersionRevision", 0);
key.Close();
}
return new Version(major, minor, revision);
}
public static string GetDisplayVersion()
{
return "1.2.2";
}
#endregion
}
}