-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
221 lines (208 loc) · 7.22 KB
/
Copy pathProgram.cs
File metadata and controls
221 lines (208 loc) · 7.22 KB
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
using System.Diagnostics;
using System.Globalization;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using Newtonsoft.Json;
using Squirrel;
using UGC_App.ErrorReporter;
namespace UGC_App;
internal static class Program
{
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
#pragma warning disable SYSLIB1054
private static extern bool SetForegroundWindow(IntPtr hWnd);
#pragma warning restore SYSLIB1054
private static Mutex? _mutex;
private const string MutexName = "UGC App";
private static readonly SemaphoreSlim Semaphore = new(1,1);
[STAThread]
private static void Main(string[] args)
{
CheckSingleInstance();
SquirrelAwareApp.HandleEvents(
onInitialInstall: OnAppInstall,
onAppUninstall: OnAppUninstall,
onEveryRun: OnAppRun);
UpdateMyApp(args);
Application.ThreadException += Application_ThreadException;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
ApplicationConfiguration.Initialize();
var mainForm = new Mainframe();
if (args.Contains("--autostart"))
{
mainForm.WindowState = FormWindowState.Minimized;
mainForm.ShowInTaskbar = false;
}
Application.Run(mainForm);
}
private static void CheckSingleInstance()
{
_mutex = new Mutex(true, MutexName, out var createdNew);
_ = _mutex.GetType();
if (createdNew) return;
var hWnd = IntPtr.Zero;
var currentProcess = Process.GetCurrentProcess();
foreach (var process in Process.GetProcessesByName(currentProcess.ProcessName))
{
if (process.Id == currentProcess.Id) continue;
hWnd = process.MainWindowHandle;
break;
}
if (hWnd != IntPtr.Zero)
{
SetForegroundWindow(hWnd);
}
var pipeClient = new NamedPipeClientStream(".", "UGC App", PipeDirection.Out);
Task.Run(pipeClient.Connect);
Application.Exit();
Application.ExitThread();
Environment.Exit(0);
}
private static void OnAppInstall(SemanticVersion version, IAppTools tools)
{
tools.CreateShortcutForThisExe();
}
private static void OnAppUninstall(SemanticVersion version, IAppTools tools)
{
tools.RemoveShortcutForThisExe();
SetStartup(false);
}
private static void OnAppRun(SemanticVersion version, IAppTools tools, bool firstRun)
{
tools.SetProcessAppUserModelId();
// show a welcome message when the app is first installed
if (firstRun) MessageBox.Show("UGC APP erfolgreich Installiert");
}
private static void UpdateMyApp(string[] args)
{
if(!Config.Instance.AutoUpdate) return;
try
{
using var mgr = new UpdateManager(Config.Instance.UpdateUrl, "UGC-App");
var newVersion = mgr.UpdateApp().Result;
if (newVersion == null) return;
//MessageBox.Show($"Die neue Version {newVersion.Version} wurde installiert!");
var arg = string.Join(",", args);
UpdateManager.RestartApp(null, arg);
}
catch
{
//Ignored to start Applaction anyways
}
}
internal static void SetStartup(bool enable)
{
var appPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "UGC-App", "UGC App.exe");
var appName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion", true);
var runKey = key?.OpenSubKey("Run", true) ?? key?.CreateSubKey("Run");
if (enable)
{
try
{
runKey?.SetValue(appName, $"\"{appPath}\" --autostart");
}
catch (Exception ex)
{
LogException(ex);
}
}
else
{
try
{
if (appName != null) runKey?.DeleteValue(appName, false);
}
catch (Exception ex)
{
LogException(ex);
}
}
runKey?.Close();
key?.Close();
}
private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
LogException(e.Exception);
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
LogException((Exception)e.ExceptionObject);
}
internal static void LogException(Exception exception)
{
Debug.WriteLine(exception);
if(MailClient.IsDelError)return;
Directory.CreateDirectory(Config.Instance.PathLogs);
var logFilePath = Path.Combine(Config.Instance.PathLogs, "error_log.json");
var errorLog = new
{
Timestamp = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK", CultureInfo.InvariantCulture),
exception.Message,
exception.StackTrace,
exception.Source,
InnerException = exception.InnerException?.ToString()
};
string jsonContent;
if (!File.Exists(logFilePath))
{
var file = File.Create(logFilePath);
file.Close();
}
using (var reader = new StreamReader(logFilePath))
{
jsonContent = reader.ReadToEnd();
reader.Close();
reader.Dispose();
}
if(string.IsNullOrWhiteSpace(jsonContent))jsonContent="[]";
var errorLogs = JsonConvert.DeserializeObject<List<dynamic>>(jsonContent);
errorLogs?.Add(errorLog);
jsonContent = JsonConvert.SerializeObject(errorLogs, Formatting.Indented);
using (var writer = new StreamWriter(logFilePath))
{
writer.Write(jsonContent);
writer.Close();
writer.Dispose();
}
}
internal static void Log(string msg)
{
Debug.WriteLine(msg);
if (MailClient.IsDelLog) return;
Semaphore.Wait();
Directory.CreateDirectory(Config.Instance.PathLogs);
var logFilePath = Path.Combine(Config.Instance.PathLogs, "log.json");
var errorLog = new
{
Timestamp = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK", CultureInfo.InvariantCulture),
Message = msg
};
if (!File.Exists(logFilePath))
{
var file = File.Create(logFilePath);
file.Close();
}
using var reader = new StreamReader(logFilePath);
var jsonContent = reader.ReadToEnd();
reader.Close();
reader.Dispose();
if(string.IsNullOrWhiteSpace(jsonContent))jsonContent="[]";
var errorLogs = JsonConvert.DeserializeObject<List<dynamic>>(jsonContent);
errorLogs?.Add(errorLog);
jsonContent = JsonConvert.SerializeObject(errorLogs, Formatting.Indented);
try
{
using var writer = new StreamWriter(logFilePath);
writer.Write(jsonContent);
writer.Close();
writer.Dispose();
Semaphore.Release();
}
catch
{
Semaphore.Release();
}
}
}