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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media.Imaging;
using Hik.Samples.Scs.IrcChat.Arguments;
using Hik.Samples.Scs.IrcChat.Client;
using Hik.Samples.Scs.IrcChat.Controls;
using Microsoft.Win32;
namespace Hik.Samples.Scs.IrcChat.Windows
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, IChatRoomView, ILoginFormView, IMessagingAreaContainer
{
#region ILoginFormView implementation
/// <summary>
/// IP address of server to be connected.
/// </summary>
public string ServerIpAddress
{
get
{
return (string)Dispatcher.Invoke(new Func<string>(() => txtServerIpAddress.Text));
}
}
/// <summary>
/// TCP Port number of server to be connected.
/// </summary>
public int ServerTcpPort
{
get
{
return (int)Dispatcher.Invoke(new Func<int>(() => Convert.ToInt32(txtServerPort.Text)));
}
}
/// <summary>
/// User Login informations to be used while logging on to the server.
/// </summary>
public UserInfo CurrentUserInfo
{
get
{
return (UserInfo)Dispatcher.Invoke(
new Func<UserInfo>(() => new UserInfo
{
Nick = txtNick.Text,
Status = UserStatus.Available,
AvatarBytes = GetBytesOfCurrentUserAvatar()
}));
}
}
#endregion
#region IChatRoomView implementation
/// <summary>
/// This method is called when a message is sent to chat room.
/// </summary>
/// <param name="nick">Nick of sender</param>
/// <param name="message">Message</param>
public void OnMessageReceived(string nick, ChatMessage message)
{
Dispatcher.Invoke(new Action(() => messagingArea.MessageReceived(nick, message)));
}
/// <summary>
/// This method is called when a private message is sent to the current user.
/// </summary>
/// <param name="nick">Nick of sender</param>
/// <param name="message">The message</param>
public void OnPrivateMessageReceived(string nick, ChatMessage message)
{
Dispatcher.Invoke(new Action(() => OnPrivateMessageReceivedInternal(nick, message)));
}
/// <summary>
/// This method is called when user successfully logged in to chat server.
/// </summary>
public void OnLoggedIn()
{
Dispatcher.Invoke(new Action(OnLoggedInInternal));
}
/// <summary>
/// This method is used to inform view if login is failed.
/// </summary>
/// <param name="errorMessage">Detail of error</param>
public void OnLoginError(string errorMessage)
{
MessageBox.Show(errorMessage, "Login Error!", MessageBoxButton.OK, MessageBoxImage.Error);
}
/// <summary>
/// This method is called when connection to server is closed.
/// </summary>
public void OnLoggedOut()
{
Dispatcher.Invoke(new Action(OnLoggedOutInternal));
}
/// <summary>
/// This methos is used to add a new user to user list in room view.
/// </summary>
/// <param name="userInfo">Informations of new user</param>
public void AddUserToList(UserInfo userInfo)
{
Dispatcher.Invoke(new Action(() => AddUserToListInternal(userInfo)));
}
/// <summary>
/// This metrhod is used to remove a user (that is disconnected from server) from user list in room view.
/// </summary>
/// <param name="nick">Nick of user to remove</param>
public void RemoveUserFromList(string nick)
{
Dispatcher.Invoke(new Action(() => RemoveUserFromListInternal(nick)));
}
/// <summary>
/// This method is called from chat server to inform that a user changed his/her status.
/// </summary>
/// <param name="nick">Nick of the user</param>
/// <param name="newStatus">New status of the user</param>
public void OnUserStatusChange(string nick, UserStatus newStatus)
{
Dispatcher.Invoke(new Action(() => OnUserStatusChangeInternal(nick, newStatus)));
}
#endregion
#region IMessagingAreaContainer implementation
/// <summary>
/// Sends a message to the room.
/// </summary>
public void SendMessage(ChatMessage message)
{
_controller.SendMessageToRoom(message);
}
#endregion
#region Private fields
/// <summary>
/// Reference to the controller object.
/// </summary>
private readonly IChatController _controller;
/// <summary>
/// List of open private chat windows.
/// </summary>
private readonly SortedList<string, PrivateChatWindow> _privateChatWindows;
/// <summary>
/// Reference to the user preferences.
/// </summary>
private readonly UserPreferences _userPreferences;
#endregion
#region Constructor and Initialize methods
/// <summary>
/// Creates a new form with a reference to the controller object.
/// </summary>
/// <param name="controller">Reference to the controller object</param>
public MainWindow(IChatController controller)
{
_controller = controller;
_privateChatWindows = new SortedList<string, PrivateChatWindow>();
_userPreferences = UserPreferences.Current;
InitializeComponent();
InitializeControls();
}
/// <summary>
/// Initializes some controls.
/// </summary>
private void InitializeControls()
{
messagingArea.MessagingAreaContainer = this;
txtNick.Text = _userPreferences.Nick;
txtServerIpAddress.Text = _userPreferences.ServerIpAddress;
txtServerPort.Text = _userPreferences.ServerTcpPort.ToString();
InitializeUserAvatar();
}
/// <summary>
/// Initializes and shows user avatar.
/// </summary>
private void InitializeUserAvatar()
{
try
{
ChangeCurrentUserAvatar(_userPreferences.AvatarFile);
}
catch (Exception ex)
{
MessageBox.Show("Can not load avatar image. Error Detail: " + ex.Message, "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
#endregion
#region Handlers for events of window and controls
/// <summary>
/// Handles Loaded event of this Window.
/// </summary>
/// <param name="sender">Source of event</param>
/// <param name="e">Event arguments</param>
private void Window_Loaded(object sender, RoutedEventArgs e)
{
txtNick.Focus();
txtNick.SelectAll();
}
/// <summary>
/// Hansles Closing event of this window.
/// </summary>
/// <param name="sender">Source of event</param>
/// <param name="e">Event arguments</param>
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
_userPreferences.Save();
_controller.Disconnect();
}
/// <summary>
/// Handles TextChanged event of txtNick (on login screen).
/// </summary>
/// <param name="sender">Source of event</param>
/// <param name="e">Event arguments</param>
private void txtNick_TextChanged(object sender, TextChangedEventArgs e)
{
lblCurrentUserNick.Content = txtNick.Text;
}
/// <summary>
/// Handles Click event of 'Change to female' right menu item of avatar menu.
/// Changes login avatar to default female avatar.
/// </summary>
/// <param name="sender">Source of event</param>
/// <param name="e">Event arguments</param>
private void ChangeToFemale_Click(object sender, RoutedEventArgs e)
{
try
{
ChangeCurrentUserAvatar(Path.Combine(ClientHelper.GetCurrentDirectory(), @"Images\user_female.png"));
}
catch (Exception ex)
{
MessageBox.Show("Can not load avatar image. Error Detail: " + ex.Message, "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
/// <summary>
/// Handles Click event of 'Change to male' right menu item of avatar menu.
/// Changes login avatar to default male avatar.
/// </summary>
/// <param name="sender">Source of event</param>
/// <param name="e">Event arguments</param>
private void ChangeToMale_Click(object sender, RoutedEventArgs e)
{
try
{
ChangeCurrentUserAvatar(Path.Combine(ClientHelper.GetCurrentDirectory(), @"Images\user_male.png"));
}
catch (Exception ex)
{
MessageBox.Show("Can not load avatar image. Error Detail: " + ex.Message, "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
/// <summary>
/// Handles Click event of 'Select a picture...' menu item.
/// </summary>
/// <param name="sender">Source of event</param>
/// <param name="e">Event arguments</param>
private void SelectAvatar_Click(object sender, RoutedEventArgs e)
{
try
{
var avatarSelectDialog = new OpenFileDialog();
avatarSelectDialog.Filter = "JPG Files|*.jpg|JPEG Files|*.jpeg|GIF Files|*.gif|PNG files|*.png|BMP Files|*.bmp";
if (avatarSelectDialog.ShowDialog() == true)
{
var selectedFile = avatarSelectDialog.FileName;
if (ClientHelper.GetFileSize(selectedFile) > (100 * 1024))
{
MessageBox.Show("You can not select avatar file larger than 100 KB.", "Warning!", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
ChangeCurrentUserAvatar(selectedFile);
}
}
catch (Exception ex)
{
MessageBox.Show("Can not load avatar image. Error Detail: " + ex.Message, "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
/// <summary>
/// Handles Client event of Login button.
/// </summary>
/// <param name="sender">Source of event</param>
/// <param name="e">Event arguments</param>
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
ConnectToServer();
}
/// <summary>
/// Handles KeyDown of Login form (actually the Border named brdConnect that contains login controls)
/// </summary>
/// <param name="sender">Source of event</param>
/// <param name="e">Event arguments</param>
private void LoginForm_KeyDown(object sender, KeyEventArgs e)
{
//If user pressed to enter in login form, connect to server
if (e.Key == Key.Enter)
{
ConnectToServer();
}
}
/// <summary>
/// Handles SelectionChanged event of user status combobox
/// </summary>
/// <param name="sender">Source of event</param>
/// <param name="e">Event arguments</param>
private void cmbCurrentUserStatus_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (!IsInitialized || cmbCurrentUserStatus.SelectedIndex < 0 || _controller == null)
{
return;
}
try
{
var newStatus = GetCurrentUserStatus();
_controller.ChangeStatus(newStatus);
//Change user's status on all open private chat windows
foreach (var chatWindow in _privateChatWindows.Values.ToList())
{
chatWindow.CurrentUserStatus = newStatus;
}
}
catch (Exception ex)
{
MessageBox.Show("Can not changes status. Error Detail: " + ex.Message, "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
/// <summary>
/// Handles MouseDoubleClick event of all User cards.
/// </summary>
/// <param name="sender">Source of event</param>
/// <param name="e">Event arguments</param>
private void UserCard_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton != MouseButton.Left)
{
return;
}
var userCard = e.Source as UserCardControl;
if (userCard == null)
{
return;
}
if (_privateChatWindows.ContainsKey(userCard.UserNick))
{
_privateChatWindows[userCard.UserNick].Activate();
}
else
{
_privateChatWindows[userCard.UserNick] = CreatePrivateChatWindow(userCard);
}
}
/// <summary>
/// Handles Closed event of Private chat windows.
/// </summary>
/// <param name="sender">Source of event</param>
/// <param name="e">Event arguments</param>
private void PrivateChatWindow_Closed(object sender, EventArgs e)
{
var privateChatWindow = sender as PrivateChatWindow;
if (privateChatWindow == null)
{
return;
}
if (_privateChatWindows.ContainsKey(privateChatWindow.RemoteUserNick))
{
_privateChatWindows.Remove(privateChatWindow.RemoteUserNick);
}
}
#endregion
#region Private methods
/// <summary>
/// Connects to the server.
/// This method is called on login.
/// </summary>
private void ConnectToServer()
{
if(string.IsNullOrEmpty(txtNick.Text))
{
MessageBox.Show("You must enter a nick to login to server.", "Warning!", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
if (string.IsNullOrEmpty(txtServerIpAddress.Text))
{
MessageBox.Show("You must enter IP address to connect to server.", "Warning!", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
if (string.IsNullOrEmpty(txtServerPort.Text))
{
MessageBox.Show("You must enter TCP port to connect to server.", "Warning!", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
try
{
_controller.Connect();
_userPreferences.Nick = txtNick.Text;
_userPreferences.ServerIpAddress = txtServerIpAddress.Text;
try { _userPreferences.ServerTcpPort = Convert.ToInt32(txtServerPort.Text); } catch { }
_userPreferences.Save();
}
catch (Exception ex)
{
MessageBox.Show("Can not connected to the server. Check Server IP and port. Error Detail: " + ex.Message, "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
/// <summary>
/// This method is used to hide Login form when user succussfully logged into server.
/// </summary>
private void OnLoggedInInternal()
{
grdConnect.Visibility = Visibility.Collapsed;
brdConnect.Visibility = Visibility.Collapsed;
}
/// <summary>
/// This method is used to show Login form when connection to server is broken/closed.
/// </summary>
private void OnLoggedOutInternal()
{
foreach (var privateChatWindow in _privateChatWindows.Values.ToList())
{
privateChatWindow.Close();
}
spUsers.Children.Clear();
grdConnect.Visibility = Visibility.Visible;
brdConnect.Visibility = Visibility.Visible;
}
/// <summary>
/// This method is used to send private message to proper private messaging window.
/// </summary>
/// <param name="nick">Nick of sender</param>
/// <param name="message">Message</param>
private void OnPrivateMessageReceivedInternal(string nick, ChatMessage message)
{
var userCard = FindUserInList(nick);
if (userCard == null)
{
return;
}
if (!_privateChatWindows.ContainsKey(nick))
{
//Create new private chat window
_privateChatWindows[nick] = CreatePrivateChatWindow(userCard);
//Set initial state as minimized
_privateChatWindows[nick].WindowState = WindowState.Minimized;
//Flash the window button on taskbar to inform user
WindowsHelper.FlashWindow(new WindowInteropHelper(_privateChatWindows[nick]).Handle, WindowsHelper.FlashWindowFlags.FLASHW_ALL, 2, 1000);
}
_privateChatWindows[nick].MessageReceived(message);
}
/// <summary>
/// Creates a new PrivateChatWindow from a user card.
/// </summary>
/// <param name="userCard">User card to use while creating window</param>
/// <returns>Created window</returns>
private PrivateChatWindow CreatePrivateChatWindow(UserCardControl userCard)
{
var window = new PrivateChatWindow(_controller)
{
CurrentUserNick = txtNick.Text,
CurrentUserStatus = GetCurrentUserStatus(),
CurrentUserAvatar = imgCurrentUserAvatar.Source,
RemoteUserNick = userCard.UserNick,
RemoteUserStatus = userCard.UserStatus,
RemoteUserAvatar = userCard.AvatarImageSource
};
window.Closed += PrivateChatWindow_Closed;
window.Show();
return window;
}
/// <summary>
/// Adds user to user list in right area of the window.
/// </summary>
/// <param name="userInfo">New user informations</param>
private void AddUserToListInternal(UserInfo userInfo)
{
//Do not add the current user (that is using the application) to user list
if (userInfo.Nick == CurrentUserInfo.Nick)
{
return;
}
//Do not add user to list if it is already exists.
if (FindUserInList(userInfo.Nick) != null)
{
return;
}
//Find correct order (by name) to insert the user
var orderedIndex = 0;
foreach (UserCardControl userCardControl in spUsers.Children)
{
if (userInfo.Nick.CompareTo(userCardControl.UserNick) < 0)
{
break;
}
orderedIndex++;
}
//Create user control
var userCard = new UserCardControl
{
UserNick = userInfo.Nick,
UserStatus = userInfo.Status,
AvatarBytes = userInfo.AvatarBytes,
Height = 60
};
userCard.MouseDoubleClick += UserCard_MouseDoubleClick;
//Insert user to user list
spUsers.Children.Insert(
orderedIndex,
userCard
);
//Enable private messaging window if any open with that user
if (_privateChatWindows.ContainsKey(userInfo.Nick))
{
_privateChatWindows[userInfo.Nick].UserLoggedIn();
_privateChatWindows[userInfo.Nick].RemoteUserStatus = userInfo.Status;
_privateChatWindows[userInfo.Nick].RemoteUserAvatar = userCard.AvatarImageSource;
}
}
/// <summary>
/// Removes an existing user from user list.
/// </summary>
/// <param name="nick"></param>
private void RemoveUserFromListInternal(string nick)
{
//Enable private messaging window is any open with that user
if (_privateChatWindows.ContainsKey(nick))
{
_privateChatWindows[nick].UserLoggedOut();
}
//Find user in list
var userCard = FindUserInList(nick);
//Remove if found
if (userCard != null)
{
spUsers.Children.Remove(userCard);
userCard.MouseDoubleClick -= UserCard_MouseDoubleClick;
}
}
/// <summary>
/// Changes status of a user in user list.
/// </summary>
/// <param name="nick">Nick of the user</param>
/// <param name="newStatus">New status of the user</param>
public void OnUserStatusChangeInternal(string nick, UserStatus newStatus)
{
//Find user in list
var userCard = FindUserInList(nick);
//Change status of user if found
if (userCard != null)
{
userCard.UserStatus = newStatus;
}
//Change status of user if any private chat window is open
if (_privateChatWindows.ContainsKey(nick))
{
_privateChatWindows[nick].RemoteUserStatus = newStatus;
}
}
/// <summary>
/// Searches a user (by nick) in user list and gets user card control of user.
/// </summary>
/// <param name="nick">Nick to search</param>
/// <returns>Found user card of user</returns>
private UserCardControl FindUserInList(string nick)
{
return spUsers.Children.Cast<UserCardControl>().FirstOrDefault(userCardControl => userCardControl.UserNick == nick);
}
/// <summary>
/// Changes avatar of the current user by a file.
/// </summary>
/// <param name="avatarPath">File path of new avatar</param>
private void ChangeCurrentUserAvatar(string avatarPath)
{
imgLoginAvatar.Source = new BitmapImage(new Uri(avatarPath));
imgCurrentUserAvatar.Source = imgLoginAvatar.Source;
_userPreferences.AvatarFile = avatarPath;
}
/// <summary>
/// Gets status of the current user from combobox.
/// </summary>
/// <returns>Status of current user</returns>
private UserStatus GetCurrentUserStatus()
{
switch (cmbCurrentUserStatus.SelectedIndex)
{
case 0:
return UserStatus.Available;
case 1:
return UserStatus.Busy;
default:
return UserStatus.Out;
}
}
/// <summary>
/// Gets bytes of current user avatar.
/// </summary>
/// <returns>Bytes of user avatar file</returns>
private byte[] GetBytesOfCurrentUserAvatar()
{
if (string.IsNullOrEmpty(_userPreferences.AvatarFile))
{
return null;
}
try
{
if (!File.Exists(_userPreferences.AvatarFile))
{
return null;
}
return File.ReadAllBytes(_userPreferences.AvatarFile);
}
catch (Exception)
{
return null;
}
}
#endregion
}
}
|