SetupStub.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. using System;
  2. using System.IO;
  3. using System.IO.Compression;
  4. using System.Text;
  5. using System.Windows.Forms;
  6. namespace ComputerShopWpfInstaller
  7. {
  8. internal static class SetupStub
  9. {
  10. private const string AppName = "ComputerShopWpf";
  11. private const string DisplayName = "Продажа компьютерной техники";
  12. private static readonly byte[] Marker = Encoding.ASCII.GetBytes("CSWPF_SETUP_PAYLOAD_V1");
  13. [STAThread]
  14. private static int Main()
  15. {
  16. Application.EnableVisualStyles();
  17. Application.SetCompatibleTextRenderingDefault(false);
  18. try
  19. {
  20. string installDir = Path.Combine(
  21. Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
  22. AppName);
  23. DialogResult confirm = MessageBox.Show(
  24. "Будет установлено приложение \"" + DisplayName + "\".\n\nПапка установки:\n" + installDir + "\n\nПродолжить?",
  25. DisplayName + " - установщик",
  26. MessageBoxButtons.YesNo,
  27. MessageBoxIcon.Question);
  28. if (confirm != DialogResult.Yes)
  29. {
  30. return 0;
  31. }
  32. byte[] payload = ReadPayload();
  33. ExtractPayload(payload, installDir);
  34. CreateDesktopShortcut(installDir);
  35. DialogResult launch = MessageBox.Show(
  36. "Установка завершена.\n\nЯрлык создан на рабочем столе.\nЗапустить приложение сейчас?",
  37. DisplayName + " - установщик",
  38. MessageBoxButtons.YesNo,
  39. MessageBoxIcon.Information);
  40. if (launch == DialogResult.Yes)
  41. {
  42. System.Diagnostics.Process.Start(Path.Combine(installDir, "ComputerShopWpf.exe"));
  43. }
  44. return 0;
  45. }
  46. catch (Exception ex)
  47. {
  48. MessageBox.Show(
  49. "Не удалось выполнить установку.\n\n" + ex.Message,
  50. DisplayName + " - ошибка установки",
  51. MessageBoxButtons.OK,
  52. MessageBoxIcon.Error);
  53. return 1;
  54. }
  55. }
  56. private static byte[] ReadPayload()
  57. {
  58. byte[] exeBytes = File.ReadAllBytes(Application.ExecutablePath);
  59. int markerStart = exeBytes.Length - Marker.Length;
  60. if (markerStart <= 8 || !Matches(exeBytes, markerStart, Marker))
  61. {
  62. throw new InvalidOperationException("В установщике не найден пакет файлов приложения.");
  63. }
  64. long payloadLength = BitConverter.ToInt64(exeBytes, markerStart - 8);
  65. if (payloadLength <= 0 || payloadLength > markerStart - 8)
  66. {
  67. throw new InvalidOperationException("Пакет файлов приложения поврежден.");
  68. }
  69. int payloadStart = markerStart - 8 - (int)payloadLength;
  70. byte[] payload = new byte[payloadLength];
  71. Buffer.BlockCopy(exeBytes, payloadStart, payload, 0, payload.Length);
  72. return payload;
  73. }
  74. private static bool Matches(byte[] data, int start, byte[] pattern)
  75. {
  76. for (int i = 0; i < pattern.Length; i++)
  77. {
  78. if (data[start + i] != pattern[i])
  79. {
  80. return false;
  81. }
  82. }
  83. return true;
  84. }
  85. private static void ExtractPayload(byte[] payload, string installDir)
  86. {
  87. Directory.CreateDirectory(installDir);
  88. string fullInstallDir = Path.GetFullPath(installDir);
  89. using (MemoryStream stream = new MemoryStream(payload))
  90. using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Read))
  91. {
  92. foreach (ZipArchiveEntry entry in archive.Entries)
  93. {
  94. string targetPath = Path.GetFullPath(Path.Combine(installDir, entry.FullName));
  95. if (!targetPath.StartsWith(fullInstallDir, StringComparison.OrdinalIgnoreCase))
  96. {
  97. throw new InvalidOperationException("Пакет содержит недопустимый путь: " + entry.FullName);
  98. }
  99. if (entry.FullName.EndsWith("/", StringComparison.Ordinal))
  100. {
  101. Directory.CreateDirectory(targetPath);
  102. continue;
  103. }
  104. string directory = Path.GetDirectoryName(targetPath);
  105. if (!String.IsNullOrEmpty(directory))
  106. {
  107. Directory.CreateDirectory(directory);
  108. }
  109. entry.ExtractToFile(targetPath, true);
  110. }
  111. }
  112. }
  113. private static void CreateDesktopShortcut(string installDir)
  114. {
  115. string exePath = Path.Combine(installDir, "ComputerShopWpf.exe");
  116. string desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
  117. CreateShortcut(
  118. Path.Combine(desktop, DisplayName + ".lnk"),
  119. exePath,
  120. installDir,
  121. DisplayName,
  122. exePath);
  123. string uninstallScript = Path.Combine(installDir, "uninstall.ps1");
  124. if (File.Exists(uninstallScript))
  125. {
  126. CreateShortcut(
  127. Path.Combine(desktop, DisplayName + " - удалить.lnk"),
  128. "powershell.exe",
  129. installDir,
  130. "Удалить " + DisplayName,
  131. "powershell.exe",
  132. "-NoProfile -ExecutionPolicy Bypass -File \"" + uninstallScript + "\"");
  133. }
  134. }
  135. private static void CreateShortcut(
  136. string shortcutPath,
  137. string targetPath,
  138. string workingDirectory,
  139. string description,
  140. string iconPath,
  141. string arguments = "")
  142. {
  143. Type shellType = Type.GetTypeFromProgID("WScript.Shell");
  144. if (shellType == null)
  145. {
  146. throw new InvalidOperationException("Не удалось создать ярлык: WScript.Shell недоступен.");
  147. }
  148. object shell = Activator.CreateInstance(shellType);
  149. object shortcut = shellType.InvokeMember(
  150. "CreateShortcut",
  151. System.Reflection.BindingFlags.InvokeMethod,
  152. null,
  153. shell,
  154. new object[] { shortcutPath });
  155. Type shortcutType = shortcut.GetType();
  156. shortcutType.InvokeMember("TargetPath", System.Reflection.BindingFlags.SetProperty, null, shortcut, new object[] { targetPath });
  157. shortcutType.InvokeMember("WorkingDirectory", System.Reflection.BindingFlags.SetProperty, null, shortcut, new object[] { workingDirectory });
  158. shortcutType.InvokeMember("Description", System.Reflection.BindingFlags.SetProperty, null, shortcut, new object[] { description });
  159. shortcutType.InvokeMember("IconLocation", System.Reflection.BindingFlags.SetProperty, null, shortcut, new object[] { iconPath });
  160. if (!String.IsNullOrEmpty(arguments))
  161. {
  162. shortcutType.InvokeMember("Arguments", System.Reflection.BindingFlags.SetProperty, null, shortcut, new object[] { arguments });
  163. }
  164. shortcutType.InvokeMember("Save", System.Reflection.BindingFlags.InvokeMethod, null, shortcut, null);
  165. }
  166. }
  167. }