-
Notifications
You must be signed in to change notification settings - Fork 0
/
Form1.cs
433 lines (375 loc) · 17.1 KB
/
Form1.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
using System;
using Microsoft.VisualBasic.ApplicationServices;
using Newtonsoft.Json.Linq;
using System.Text;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.AspNet.SignalR.Messaging;
using System.Drawing;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.AspNet.SignalR.Hosting;
namespace CalculateLeftTime
{
public partial class Form1 : Form
{
public static HubConnection SignalRConn;
private static int WM_QUERYENDSESSION = 0x11;
public static int tenantId,userId;
private static System.Windows.Forms.Timer timer;
public static string accessToken = "";
public Form1()
{
InitializeComponent();
this.FormClosing += Form1_FormClosingAsync;
this.Activated += new System.EventHandler(this.Form1_Activated);
/* PostUserStatusToWeb();*/
}
private void Form1_Activated(object sender, EventArgs e)
{
/*this.Hide()*/
;
}
private void btnReadFile_Click()
{
// Get the path of the application's startup folder
string appFolderPath = Application.StartupPath;
// Specify the filename you want to read (change it accordingly)
string filename = "userDetails.dat";
// Combine the folder path and filename to get the full file path
string filePath = Path.Combine(appFolderPath, filename);
Console.WriteLine(filePath);
try
{
// Check if the file exists
if (File.Exists(filePath))
{
// Read the contents of the file
string fileContent = File.ReadAllText(filePath);
JObject jsonObject = JObject.Parse(fileContent);
string userIdString = jsonObject["userId"]?.ToString();
string tenantIdString = jsonObject["tenantId"]?.ToString();
if (!string.IsNullOrEmpty(userIdString) && !string.IsNullOrEmpty(tenantIdString))
{
userId = int.Parse(userIdString);
tenantId = int.Parse(tenantIdString);
accessToken = jsonObject["accessToken"]?.ToString();
Console.Write($" userid {userId}");
System.Diagnostics.Debug.WriteLine($" userid {userId}");
ConnectSignalRServer();
// TrigerSignalRServerUserStatus("SignalRAgentUserStatus");
} else
{
Console.Write($" userid/tenantid null");
System.Diagnostics.Debug.WriteLine($"userid/tenantid null");
AddLogs(" userid/tenantid null");
}
// Process accessToken
HideApp();
}
else
{
// MessageBox.Show("File not found.", "File Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error);
System.Diagnostics.Debug.WriteLine($" userid not found");
HideApp();
AddLogs(" userid/tenantid null");
}
}
catch (Exception ex)
{
/*MessageBox.Show("An error occurred: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);*/
}
}
private void HideApp()
{
this.Hide();
this.Visible = false;
this.Opacity = 0;
this.ShowInTaskbar = false;
this.ShowIcon = false;
}
/* protected override void WndProc(ref System.Windows.Forms.Message m)
{
if (m.Msg == WM_QUERYENDSESSION)
{
PostUserStatusToWeb();
System.Threading.Timer timer = new System.Threading.Timer(TimerCallback, null, 10000, System.Threading.Timeout.Infinite);
// MessageBox.Show("queryendsession: this is a logoff, shutdown, or reboot");
}
base.WndProc(ref m);
}*/
/* private void TimerCallback(object state)
{
// Code to execute after 10 seconds
// This can include any additional logic or actions you want to perform
// For example, you can display a message, close the application, etc.
// Make sure to use Invoke if you need to update UI elements from a different thread
this.Invoke((MethodInvoker)delegate {
// Your code to be executed after the delay
System.Diagnostics.Debug.WriteLine("Code executed after 10 seconds.");
string message = "System is shutting down or user is logging off.1 WndProc";
// Get the path to the Documents folder
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
// Specify the file path in the Documents folder
string filePath = Path.Combine(documentsPath, "shutdown_log1.txt");
// Write the message to a text file
using (StreamWriter writer = new StreamWriter(filePath, true))
{
writer.WriteLine($"{DateTime.Now} - {message}");
}
System.Diagnostics.Debug.WriteLine("System is shutting down or user is logging off.1 WndProc");
});
}*/
/* private void Form1_Load(object sender, EventArgs e)
{
Console.WriteLine("Hello");
this.Hide();
}*/
private static async Task Form1_FormClosedAsync(object sender, FormClosedEventArgs e)
{
PostUserStatusToWeb(5);
Console.WriteLine("Hello Form1_FormClosed");
string message = "System is shutting down or user is logging off.2 WndProc";
// Get the path to the Documents folder
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
// Specify the file path in the Documents folder
string filePath = Path.Combine(documentsPath, "shutdown_log2.txt");
// Write the message to a text file
using (StreamWriter writer = new StreamWriter(filePath, true))
{
writer.WriteLine($"{DateTime.Now} - {message}");
}
// MessageBox.Show("queryendsession: this is a logoff, shutdown, or reboot");
System.Diagnostics.Debug.WriteLine("System is shutting down or user is logging off.2 WndProc");
}
private void Timer_Tick(object sender, EventArgs e)
{
// Code to be executed when the timer ticks
// MessageBox.Show("Timeout reached!");
System.Diagnostics.Debug.WriteLine("Timeout reached!");
// Stop the timer
timer.Stop();
}
private static async void Form1_FormClosingAsync(Object sender, FormClosingEventArgs e)
{
PostUserStatusToWeb(5);
//In case windows is trying to shut down, don't hold the process up
if (e.CloseReason == CloseReason.UserClosing)
{
timer.Start();
/* MessageBox.Show("queryendsession: this is a logoff, shutdown, or reboot UserClosing");*/
AddLogs("Hello Form1_FormClosing UserClosing");
}
// Prompt user to save his data
if (e.CloseReason == CloseReason.WindowsShutDown)
{
Console.WriteLine("Hello Form1_FormClosing WindowsShutDown");
string message = "System is shutting down or user is logging off.4 Form1_FormClosingAsync";
AddLogs(message);
// Get the path to the Documents folder
System.Diagnostics.Debug.WriteLine("System is shutting down or user is logging off.4 Form1_FormClosingAsync");
/* MessageBox.Show("queryendsession: this is a logoff, shutdown, or reboot WindowsShutDown");*/
}
}
private void Form1_Load_1(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("Form1_Load_1");
this.Hide();
this.Visible = false;
this.Opacity = 0;
btnReadFile_Click();
}
private static async void ConnectSignalRServer()
{
try
{
//string signalRUrl = "https://localhost:44301/notifyclient";
// string signalRUrl = "https://stagapi.intimepro.io/notifyclient";
// string signalRUrl = "https://uatapi.intimepro.io/notifyclient";
string signalRUrl = "https://api.intimepro.io/notifyclient";
//-------------------
SignalRConn = new HubConnectionBuilder()
.WithUrl(signalRUrl)
.Build();
var data = new RegisterSignalRDto();
SignalRConn.Closed += async (error) =>
{
await Task.Delay(new Random().Next(0, 5) * 1000);
await SignalRConn.StartAsync();
data.userId = userId;
data.tenantId = tenantId;
data.device = "L";
await SignalRConn.SendAsync("RegisterClientId", data);
System.Diagnostics.Debug.WriteLine("RegisterClientId");
AddLogs("RegisterClientId");
};
try
{
data.userId = userId;
data.tenantId = tenantId;
data.device = "L";
await SignalRConn.StartAsync();
await SignalRConn.SendAsync("RegisterClientId", data);
System.Diagnostics.Debug.WriteLine("StartAsync RegisterClientId");
AddLogs($"StartAsync RegisterClientId {data.device}");
TrigerSignalRServerUserStatus("SignalRAgentUserStatus");
PostUserStatusToWeb(4);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("RegisterClientId" + ex);
AddLogs("RegisterClientId" + ex);
}
//-------------------
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(" RegisterClientId" + ex);
AddLogs("StartAsync RegisterClientId" + ex);
}
}
public static void AddLogs(string message)
{
try
{
// Get the path to the Documents folder
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
// Specify the file path in the Documents folder
string filePath = Path.Combine(documentsPath, "IsSuccessStatusCode.txt");
// Check if the file exists
bool fileExists = File.Exists(filePath);
// Write the message to a text file
using (StreamWriter writer = new StreamWriter(filePath, true))
{
// If the file already exists and it's not empty, move to the next line
if (fileExists && new FileInfo(filePath).Length > 0)
{
writer.WriteLine();
}
writer.WriteLine($"{DateTime.Now} - {message}");
}
}
catch (Exception ex)
{
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
// Specify the file path in the Documents folder
string filePath = Path.Combine(documentsPath, "IsSuccessStatusCode.txt");
// Write the message to a text file
using (StreamWriter writer = new StreamWriter(filePath, true))
{
writer.WriteLine($"{DateTime.Now} - {ex.Message} ");
}
}
}
public static void TrigerSignalRServerUserStatus(string SignalREvent)
{
try
{
AddLogs("in TrigerSignalRServerUserStatus");
#region snippet_ConnectionOn
if (SignalRConn == null)
{
AddLogs("SignalRConn null TrigerSignalRServerUserStatus");
return;
}
SignalRConn.On<UserStatusDto>(SignalREvent, (data) =>
{
Console.WriteLine("gfgggjfjhgjhghjgjhgjhgkg");
System.Diagnostics.Debug.WriteLine("gfgggjfjhgjhghjgjhgjhgkg");
AddLogs("TrigerSignalRServerUserStatus");
});
AddLogs("endregion SignalRConn null TrigerSignalRServerUserStatus");
#endregion
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("TrigerSignalRServerUserStatus" + ex);
AddLogs("TrigerSignalRServerUserStatus" + ex);
}
}
/* public static async Task<HttpResponseMessage> PostUserStatusToWeb(int UserStatus)
{
try
{
if (tenantId != 0 && userId != 0)
{
UserStatusDto userStatusDto = new UserStatusDto();
userStatusDto.TenantId = tenantId;
userStatusDto.UserId = userId;
userStatusDto.UserStatus = UserStatus;
await SignalRConn.InvokeAsync("SignalRetOrUpdateUserStatusFromAgent", userStatusDto);
System.Diagnostics.Debug.WriteLine("SignalRetOrUpdateUserStatusFromAgent");
AddLogs("Signal R status send");
return new HttpResponseMessage();
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("SignalRetOrUpdateUserStatusFromAgent" + ex);
AddLogs("SignalRetOrUpdateUserStatusFromAgent" + ex);
}
return null;
}
*/
public static async Task<HttpResponseMessage> PostUserStatusToWeb(int UserStatus)
{
try
{
if (SignalRConn.State == HubConnectionState.Disconnected)
{
// Reconnect to SignalR server
var data = new RegisterSignalRDto();
await SignalRConn.StartAsync();
data.userId = userId;
data.tenantId = tenantId;
data.device = "L";
await SignalRConn.SendAsync("RegisterClientId", data);
System.Diagnostics.Debug.WriteLine("PostUserStatusToWeb RegisterClientId");
AddLogs("PostUserStatusToWeb vRegisterClientId");
// Wait for the connection to become active
while (SignalRConn.State != HubConnectionState.Connected)
{
await Task.Delay(500); // Wait for 500 milliseconds
}
}
if (SignalRConn.State == HubConnectionState.Connected)
{
if (tenantId != 0 && userId != 0)
{
UserStatusDto userStatusDto = new UserStatusDto();
userStatusDto.TenantId = tenantId;
userStatusDto.UserId = userId;
userStatusDto.UserStatus = UserStatus;
await SignalRConn.InvokeAsync("SignalRetOrUpdateUserStatusFromAgent", userStatusDto);
System.Diagnostics.Debug.WriteLine("SignalRetOrUpdateUserStatusFromAgent");
AddLogs("Signal R status send");
return new HttpResponseMessage();
}
}
else
{
System.Diagnostics.Debug.WriteLine("Failed to reconnect to SignalR server. Cannot send user status.");
AddLogs("Failed to reconnect to SignalR server. Cannot send user status.");
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Error sending user status to SignalR server: " + ex.Message);
AddLogs("Error sending user status to SignalR server: " + ex.Message);
}
return null;
}
}
public class RegisterSignalRDto
{
public long userId { get; set; }
public int tenantId { get; set; }
public string device { get; set; }
}
public class UserStatusDto
{
public long TenantId { get; set; }
public long UserId { get; set; }
public int UserStatus { get; set; }
}
}