Added separate notification class
[pithos-ms-client] / trunk / Pithos.Client.WPF / Shell / ShellViewModel.cs
1 using System.Collections.Concurrent;
2 using System.Diagnostics;
3 using System.Diagnostics.Contracts;
4 using System.IO;
5 using System.Net;
6 using System.Reflection;
7 using System.Runtime.InteropServices;
8 using System.ServiceModel;
9 using System.Threading.Tasks;
10 using System.Windows;
11 using Caliburn.Micro;
12 using Hardcodet.Wpf.TaskbarNotification;
13 using Pithos.Client.WPF.Configuration;
14 using Pithos.Client.WPF.FileProperties;
15 using Pithos.Client.WPF.Preferences;
16 using Pithos.Client.WPF.SelectiveSynch;
17 using Pithos.Client.WPF.Services;
18 using Pithos.Client.WPF.Shell;
19 using Pithos.Core;
20 using Pithos.Core.Agents;
21 using Pithos.Interfaces;
22 using System;
23 using System.Collections.Generic;
24 using System.Linq;
25 using Pithos.Network;
26 using StatusService = Pithos.Client.WPF.Services.StatusService;
27
28 namespace Pithos.Client.WPF {
29         using System.ComponentModel.Composition;
30
31         
32         ///<summary>
33         /// The "shell" of the Pithos application displays the taskbar  icon, menu and notifications.
34         /// The shell also hosts the status service called by shell extensions to retrieve file info
35         ///</summary>
36         ///<remarks>
37         /// It is a strange "shell" as its main visible element is an icon instead of a window
38         /// The shell subscribes to the following events:
39         /// * Notification:  Raised by components that want to notify the user. Usually displayed in a balloon
40         /// * SelectiveSynchChanges: Notifies that the user made changes to the selective synch folders for an account. Raised by the Selective Synch dialog. Located here because the monitors are here
41         /// * ShowFilePropertiesEvent: Raised when a shell command requests the display of the file/container properties dialog
42         ///</remarks>           
43         //TODO: CODE SMELL Why does the shell handle the SelectiveSynchChanges?
44         [Export(typeof(IShell))]
45         public class ShellViewModel : Screen, IStatusNotification, IShell,
46                 IHandle<Notification>, IHandle<SelectiveSynchChanges>, IHandle<ShowFilePropertiesEvent>
47         {
48                 //The Status Checker provides the current synch state
49                 //TODO: Could we remove the status checker and use events in its place?
50                 private readonly IStatusChecker _statusChecker;
51                 private readonly IEventAggregator _events;
52
53                 public PithosSettings Settings { get; private set; }
54
55
56         private readonly ConcurrentDictionary<string, PithosMonitor> _monitors = new ConcurrentDictionary<string, PithosMonitor>();
57                 ///<summary>
58                 /// Dictionary of account monitors, keyed by account
59                 ///</summary>
60                 ///<remarks>
61                 /// One monitor class is created for each account. The Shell needs access to the monitors to execute start/stop/pause commands,
62                 /// retrieve account and boject info            
63                 ///</remarks>
64                 // TODO: Does the Shell REALLY need access to the monitors? Could we achieve the same results with a better design?
65                 // TODO: The monitors should be internal to Pithos.Core, even though exposing them makes coding of the Object and Container windows easier
66         public ConcurrentDictionary<string, PithosMonitor> Monitors
67                 {
68                         get { return _monitors; }
69                 }
70
71
72             ///<summary>
73             /// The status service is used by Shell extensions to retrieve file status information
74             ///</summary>
75             //TODO: CODE SMELL! This is the shell! While hosting in the shell makes executing start/stop commands easier, it is still a smell
76             private ServiceHost _statusService;
77
78                 //Logging in the Pithos client is provided by log4net
79                 private static readonly log4net.ILog Log = log4net.LogManager.GetLogger("Pithos");
80
81                 ///<summary>
82                 /// The Shell depends on MEF to provide implementations for windowManager, events, the status checker service and the settings
83                 ///</summary>
84                 ///<remarks>
85                 /// The PithosSettings class encapsulates the app's settings to abstract their storage mechanism (App settings, a database or registry)
86                 ///</remarks>
87                 [ImportingConstructor]          
88                 public ShellViewModel(IWindowManager windowManager, IEventAggregator events, IStatusChecker statusChecker, PithosSettings settings)
89                 {
90                         try
91                         {
92
93                                 _windowManager = windowManager;
94                                 //CHECK: Caliburn doesn't need explicit command construction
95                                 //OpenPithosFolderCommand = new PithosCommand(OpenPithosFolder);
96                                 _statusChecker = statusChecker;
97                                 //The event subst
98                                 _events = events;
99                                 _events.Subscribe(this);
100
101                                 Settings = settings;
102
103                                 StatusMessage = "In Synch";
104
105                                 _accounts.CollectionChanged += (sender, e) =>
106                                                                                                    {
107                                                                                                            NotifyOfPropertyChange(() => OpenFolderCaption);
108                                                                                                            NotifyOfPropertyChange(() => HasAccounts);
109                                                                                                    };
110
111                         }
112                         catch (Exception exc)
113                         {
114                                 Log.Error("Error while starting the ShellViewModel",exc);
115                                 throw;
116                         }
117                 }
118
119
120                 protected override void OnActivate()
121                 {
122                         base.OnActivate();
123
124                         StartMonitoring();                    
125                 }
126
127
128                 private async void StartMonitoring()
129                 {
130                         try
131                         {
132                                 var accounts = Settings.Accounts.Select(MonitorAccount);
133                                 await TaskEx.WhenAll(accounts);
134                                 _statusService = StatusService.Start();
135
136 /*
137                                 foreach (var account in Settings.Accounts)
138                                 {
139                                         await MonitorAccount(account);
140                                 }
141 */
142                                 
143                         }
144                         catch (AggregateException exc)
145                         {
146                                 exc.Handle(e =>
147                                 {
148                                         Log.Error("Error while starting monitoring", e);
149                                         return true;
150                                 });
151                                 throw;
152                         }
153                 }
154
155                 protected override void OnDeactivate(bool close)
156                 {
157                         base.OnDeactivate(close);
158                         if (close)
159                         {
160                                 StatusService.Stop(_statusService);
161                                 _statusService = null;
162                         }
163                 }
164
165                 public Task MonitorAccount(AccountSettings account)
166                 {
167                         return Task.Factory.StartNew(() =>
168                         {                                                
169                                 PithosMonitor monitor;
170                                 var accountName = account.AccountName;
171
172                                 if (_monitors.TryGetValue(accountName, out monitor))
173                                 {
174                                         //If the account is active
175                                         if (account.IsActive)
176                                                 //Start the monitor. It's OK to start an already started monitor,
177                                                 //it will just ignore the call                        
178                                                 StartMonitor(monitor).Wait();                        
179                                         else
180                                         {
181                                                 //If the account is inactive
182                                                 //Stop and remove the monitor
183                                                 RemoveMonitor(accountName);
184                                         }
185                                         return;
186                                 }
187
188                                 //Create a new monitor/ Can't use MEF here, it would return a single instance for all monitors
189                                 monitor = new PithosMonitor
190                                                           {
191                                                                   UserName = accountName,
192                                                                   ApiKey = account.ApiKey,                                  
193                                                                   StatusNotification = this,
194                                                                   RootPath = account.RootPath
195                                                           };
196                                 //PithosMonitor uses MEF so we need to resolve it
197                                 IoC.BuildUp(monitor);
198
199                             monitor.AuthenticationUrl = account.ServerUrl;
200
201                                 _monitors[accountName] = monitor;
202
203                                 if (account.IsActive)
204                                 {
205                                         //Don't start a monitor if it doesn't have an account and ApiKey
206                                         if (String.IsNullOrWhiteSpace(monitor.UserName) ||
207                                                 String.IsNullOrWhiteSpace(monitor.ApiKey))
208                                                 return;
209                                         StartMonitor(monitor);
210                                 }
211                         });
212                 }
213
214
215                 protected override void OnViewLoaded(object view)
216                 {
217                         UpdateStatus();
218                         var window = (Window)view;            
219                         TaskEx.Delay(1000).ContinueWith(t => Execute.OnUIThread(window.Hide));
220                         base.OnViewLoaded(view);
221                 }
222
223
224                 #region Status Properties
225
226                 private string _statusMessage;
227                 public string StatusMessage
228                 {
229                         get { return _statusMessage; }
230                         set
231                         {
232                                 _statusMessage = value;
233                                 NotifyOfPropertyChange(() => StatusMessage);
234                         }
235                 }
236
237                 private readonly ObservableConcurrentCollection<AccountInfo> _accounts = new ObservableConcurrentCollection<AccountInfo>();
238                 public ObservableConcurrentCollection<AccountInfo> Accounts
239                 {
240                         get { return _accounts; }
241                 }
242
243                 public bool HasAccounts
244                 {
245                         get { return _accounts.Count > 0; }
246                 }
247
248
249                 public string OpenFolderCaption
250                 {
251                         get
252                         {
253                                 return (_accounts.Count == 0)
254                                                 ? "No Accounts Defined"
255                                                 : "Open Pithos Folder";
256                         }
257                 }
258
259                 private string _pauseSyncCaption="Pause Synching";
260                 public string PauseSyncCaption
261                 {
262                         get { return _pauseSyncCaption; }
263                         set
264                         {
265                                 _pauseSyncCaption = value;
266                                 NotifyOfPropertyChange(() => PauseSyncCaption);
267                         }
268                 }
269
270                 private readonly ObservableConcurrentCollection<FileEntry> _recentFiles = new ObservableConcurrentCollection<FileEntry>();
271                 public ObservableConcurrentCollection<FileEntry> RecentFiles
272                 {
273                         get { return _recentFiles; }
274                 }
275
276
277                 private string _statusIcon="../Images/Pithos.ico";
278                 public string StatusIcon
279                 {
280                         get { return _statusIcon; }
281                         set
282                         {
283                 //TODO: Ensure all status icons use the Pithos logo
284                                 _statusIcon = value;
285                                 NotifyOfPropertyChange(() => StatusIcon);
286                         }
287                 }
288
289                 #endregion
290
291                 #region Commands
292
293                 public void ShowPreferences()
294                 {
295                         Settings.Reload();
296                         var preferences = new PreferencesViewModel(_windowManager,_events, this,Settings);            
297                         _windowManager.ShowDialog(preferences);
298                         
299                 }
300
301                 public void AboutPithos()
302                 {
303                         var about = new AboutViewModel();
304                         _windowManager.ShowWindow(about);
305                 }
306
307                 public void SendFeedback()
308                 {
309                         var feedBack =  IoC.Get<FeedbackViewModel>();
310                         _windowManager.ShowWindow(feedBack);
311                 }
312
313                 //public PithosCommand OpenPithosFolderCommand { get; private set; }
314
315                 public void OpenPithosFolder()
316                 {
317                         var account = Settings.Accounts.FirstOrDefault(acc => acc.IsActive);
318                         if (account == null)
319                                 return;
320                         Process.Start(account.RootPath);
321                 }
322
323                 public void OpenPithosFolder(AccountInfo account)
324                 {
325                         Process.Start(account.AccountPath);
326                 }
327
328                 
329 /*
330                 public void GoToSite()
331                 {            
332                         var site = Properties.Settings.Default.PithosSite;
333                         Process.Start(site);            
334                 }
335 */
336
337                 public void GoToSite(AccountInfo account)
338                 {
339                         /*var site = String.Format("{0}/ui/?token={1}&user={2}",
340                                 account.SiteUri,account.Token,
341                                 account.UserName);*/
342                         Process.Start(account.SiteUri);
343                 }
344
345                 public void ShowFileProperties()
346                 {
347                         var account = Settings.Accounts.First(acc => acc.IsActive);            
348                         var dir = new DirectoryInfo(account.RootPath + @"\pithos");
349                         var files=dir.GetFiles();
350                         var r=new Random();
351                         var idx=r.Next(0, files.Length);
352                         ShowFileProperties(files[idx].FullName);            
353                 }
354
355                 public void ShowFileProperties(string filePath)
356                 {
357                         if (String.IsNullOrWhiteSpace(filePath))
358                                 throw new ArgumentNullException("filePath");
359                         if (!File.Exists(filePath) && !Directory.Exists(filePath))
360                                 throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
361                         Contract.EndContractBlock();
362
363                         var pair=(from monitor in  Monitors
364                                                            where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
365                                                                    select monitor).FirstOrDefault();
366                     var accountMonitor = pair.Value;
367
368                         if (accountMonitor == null)
369                                 return;
370
371                         var infoTask=Task.Factory.StartNew(()=>accountMonitor.GetObjectInfo(filePath));
372
373                         
374
375                         var fileProperties = new FilePropertiesViewModel(this, infoTask,filePath);
376                         _windowManager.ShowWindow(fileProperties);
377                 } 
378                 
379                 public void ShowContainerProperties()
380                 {
381                         var account = Settings.Accounts.First(acc => acc.IsActive);            
382                         var dir = new DirectoryInfo(account.RootPath);
383                         var fullName = (from folder in dir.EnumerateDirectories()
384                                                         where (folder.Attributes & FileAttributes.Hidden) == 0
385                                                         select folder.FullName).First();
386                         ShowContainerProperties(fullName);            
387                 }
388
389                 public void ShowContainerProperties(string filePath)
390                 {
391                         if (String.IsNullOrWhiteSpace(filePath))
392                                 throw new ArgumentNullException("filePath");
393                         if (!Directory.Exists(filePath))
394                                 throw new ArgumentException(String.Format("Non existent file {0}",filePath),"filePath");
395                         Contract.EndContractBlock();
396
397                         var pair=(from monitor in  Monitors
398                                                            where filePath.StartsWith(monitor.Value.RootPath, StringComparison.InvariantCultureIgnoreCase)
399                                                                    select monitor).FirstOrDefault();
400                     var accountMonitor = pair.Value;            
401                         var info = accountMonitor.GetContainerInfo(filePath);
402
403                         
404
405                         var containerProperties = new ContainerPropertiesViewModel(this, info,filePath);
406                         _windowManager.ShowWindow(containerProperties);
407                 }
408
409         public void SynchNow()
410         {
411             var agent = IoC.Get<NetworkAgent>();
412             agent.SynchNow();
413         }
414
415                 public ObjectInfo RefreshObjectInfo(ObjectInfo currentInfo)
416                 {
417                         if (currentInfo==null)
418                                 throw new ArgumentNullException("currentInfo");
419                         Contract.EndContractBlock();
420
421                         var monitor = Monitors[currentInfo.Account];
422                         var newInfo=monitor.CloudClient.GetObjectInfo(currentInfo.Account, currentInfo.Container, currentInfo.Name);
423                         return newInfo;
424                 }
425
426                 public ContainerInfo RefreshContainerInfo(ContainerInfo container)
427                 {
428                         if (container == null)
429                                 throw new ArgumentNullException("container");
430                         Contract.EndContractBlock();
431
432                         var monitor = Monitors[container.Account];
433                         var newInfo = monitor.CloudClient.GetContainerInfo(container.Account, container.Name);
434                         return newInfo;
435                 }
436
437
438                 public void ToggleSynching()
439                 {
440                         bool isPaused=false;
441                         foreach (var pair in Monitors)
442                         {
443                                 var monitor = pair.Value;
444                                 monitor.Pause = !monitor.Pause;
445                                 isPaused = monitor.Pause;
446                         }
447
448                         PauseSyncCaption = isPaused ? "Resume syncing" : "Pause syncing";
449                         var iconKey = isPaused? "TraySyncPaused" : "TrayInSynch";
450                         StatusIcon = String.Format(@"../Images/{0}.ico", iconKey);
451                 }
452
453                 public void ExitPithos()
454                 {
455                         foreach (var pair in Monitors)
456                         {
457                                 var monitor = pair.Value;
458                                 monitor.Stop();
459                         }
460
461                         ((Window)GetView()).Close();
462                 }
463                 #endregion
464
465
466                 private readonly Dictionary<PithosStatus, StatusInfo> _iconNames = new List<StatusInfo>
467                         {
468                                 new StatusInfo(PithosStatus.InSynch, "All files up to date", "TrayInSynch"),
469                                 new StatusInfo(PithosStatus.Syncing, "Syncing Files", "TraySynching"),
470                                 new StatusInfo(PithosStatus.SyncPaused, "Sync Paused", "TraySyncPaused")
471                         }.ToDictionary(s => s.Status);
472
473                 readonly IWindowManager _windowManager;
474
475
476                 ///<summary>
477                 /// Updates the visual status indicators of the application depending on status changes, e.g. icon, stat                
478                 ///</summary>
479                 public void UpdateStatus()
480                 {
481                         var pithosStatus = _statusChecker.GetPithosStatus();
482
483                         if (_iconNames.ContainsKey(pithosStatus))
484                         {
485                                 var info = _iconNames[pithosStatus];
486                                 StatusIcon = String.Format(@"../Images/{0}.ico", info.IconName);
487
488                                 Assembly assembly = Assembly.GetExecutingAssembly();                               
489                                 var fileVersion = FileVersionInfo.GetVersionInfo(assembly.Location);
490
491
492                                 StatusMessage = String.Format("Pithos {0}\r\n{1}", fileVersion.FileVersion,info.StatusText);
493                         }
494                         
495                         _events.Publish(new Notification { Title = "Start", Message = "Start Monitoring", Level = TraceLevel.Info});
496                 }
497
498
499            
500                 private Task StartMonitor(PithosMonitor monitor,int retries=0)
501                 {
502                         return Task.Factory.StartNew(() =>
503                         {
504                                 using (log4net.ThreadContext.Stacks["Monitor"].Push("Start"))
505                                 {
506                                         try
507                                         {
508                                                 Log.InfoFormat("Start Monitoring {0}", monitor.UserName);
509
510                                                 monitor.Start();
511                                         }
512                                         catch (WebException exc)
513                                         {
514                                                 if (AbandonRetry(monitor, retries))
515                                                         return;
516
517                         HttpStatusCode statusCode =HttpStatusCode.OK;
518                                     var response = exc.Response as HttpWebResponse;
519                         if(response!=null)
520                                                 statusCode = response.StatusCode;
521
522                         switch (statusCode)
523                         {
524                             case HttpStatusCode.Unauthorized:
525                                 var message = String.Format("API Key Expired for {0}. Starting Renewal",
526                                                             monitor.UserName);
527                                 Log.Error(message, exc);
528                                 TryAuthorize(monitor, retries).Wait();
529                                 break;
530                             case HttpStatusCode.ProxyAuthenticationRequired:
531                                 TryAuthenticateProxy(monitor,retries);
532                                 break;
533                             default:
534                                 TryLater(monitor, exc, retries);
535                                 break;
536                         }
537                                         }
538                                         catch (Exception exc)
539                                         {
540                                                 if (AbandonRetry(monitor, retries)) 
541                                                         return;
542
543                                                 TryLater(monitor,exc,retries);
544                                         }
545                                 }
546                         });
547                 }
548
549             private void TryAuthenticateProxy(PithosMonitor monitor,int retries)
550             {
551                 Execute.OnUIThread(() =>
552                                        {
553                                            var proxyAccount = new ProxyAccountViewModel(this.Settings);
554                                            if (true == _windowManager.ShowDialog(proxyAccount))
555                                            {
556                                            
557                                                StartMonitor(monitor, retries);
558                                                NotifyOfPropertyChange(() => Accounts);
559                                            }
560                                        });
561             }
562
563             private bool AbandonRetry(PithosMonitor monitor, int retries)
564                 {
565                         if (retries > 1)
566                         {
567                                 var message = String.Format("Monitoring of account {0} has failed too many times. Will not retry",
568                                                                                         monitor.UserName);
569                                 _events.Publish(new Notification
570                                                                         {Title = "Account monitoring failed", Message = message, Level = TraceLevel.Error});
571                                 return true;
572                         }
573                         return false;
574                 }
575
576
577                 private async Task TryAuthorize(PithosMonitor monitor,int retries)
578                 {
579                         _events.Publish(new Notification { Title = "Authorization failed", Message = "Your API Key has probably expired. You will be directed to a page where you can renew it", Level = TraceLevel.Error });
580
581                         try
582                         {
583
584                                 var credentials = await PithosAccount.RetrieveCredentials(Settings.PithosLoginUrl);
585
586                                 var account = Settings.Accounts.First(act => act.AccountName == credentials.UserName);
587                                 account.ApiKey = credentials.Password;
588                                 monitor.ApiKey = credentials.Password;
589                                 Settings.Save();
590                                 await TaskEx.Delay(10000);
591                                 StartMonitor(monitor, retries + 1);
592                                 NotifyOfPropertyChange(()=>Accounts);
593                         }
594                         catch (AggregateException exc)
595                         {
596                                 string message = String.Format("API Key retrieval for {0} failed", monitor.UserName);
597                                 Log.Error(message, exc.InnerException);
598                                 _events.Publish(new Notification { Title = "Authorization failed", Message = message, Level = TraceLevel.Error });
599                         }
600                         catch (Exception exc)
601                         {
602                                 string message = String.Format("API Key retrieval for {0} failed", monitor.UserName);
603                                 Log.Error(message, exc);
604                                 _events.Publish(new Notification { Title = "Authorization failed", Message = message, Level = TraceLevel.Error });
605                         }
606
607                 }
608
609                 private static bool IsUnauthorized(WebException exc)
610                 {
611                         if (exc==null)
612                                 throw new ArgumentNullException("exc");
613                         Contract.EndContractBlock();
614
615                         var response = exc.Response as HttpWebResponse;
616                         if (response == null)
617                                 return false;
618                         return (response.StatusCode == HttpStatusCode.Unauthorized);
619                 }
620
621                 private void TryLater(PithosMonitor monitor, Exception exc,int retries)
622                 {
623                         var message = String.Format("An exception occured. Can't start monitoring\nWill retry in 10 seconds");
624                         Task.Factory.StartNewDelayed(10000, () => StartMonitor(monitor,retries+1));
625                         _events.Publish(new Notification
626                                                                 {Title = "Error", Message = message, Level = TraceLevel.Error});
627                         Log.Error(message, exc);
628                 }
629
630
631                 public void NotifyChange(string status, TraceLevel level=TraceLevel.Info)
632                 {
633                         StatusMessage = status;
634                         
635                         _events.Publish(new Notification { Title = "Pithos", Message = status, Level = level });
636                 }
637
638                 public void NotifyChangedFile(string filePath)
639                 {
640                         var entry = new FileEntry {FullPath=filePath};
641                         IProducerConsumerCollection<FileEntry> files=RecentFiles;
642                         FileEntry popped;
643                         while (files.Count > 5)
644                                 files.TryTake(out popped);
645                         files.TryAdd(entry);
646                 }
647
648                 public void NotifyAccount(AccountInfo account)
649                 {
650                         if (account== null)
651                                 return;
652                         //TODO: What happens to an existing account whose Token has changed?
653                         account.SiteUri= String.Format("{0}/ui/?token={1}&user={2}",
654                                 account.SiteUri, Uri.EscapeUriString(account.Token),
655                                 Uri.EscapeUriString(account.UserName));
656
657                         if (Accounts.All(item => item.UserName != account.UserName))
658                                 Accounts.TryAdd(account);
659
660                 }
661
662             public void NotifyConflicts(IEnumerable<FileSystemInfo> conflictFiles, string message)
663             {
664             if (conflictFiles == null)
665                 return;
666             if (!conflictFiles.Any())
667                 return;
668
669             UpdateStatus();
670             //TODO: Create a more specific message. For now, just show a warning
671             NotifyForFiles(conflictFiles,message,TraceLevel.Warning);
672
673             }
674
675             public void NotifyForFiles(IEnumerable<FileSystemInfo> files, string message,TraceLevel level=TraceLevel.Info)
676             {
677             if (files == null)
678                 return;
679             if (!files.Any())
680                 return;
681
682             StatusMessage = message;
683
684             _events.Publish(new Notification { Title = "Pithos", Message = message, Level = level});
685         }
686
687         public void Notify(Notification notification)
688         {
689             _events.Publish(notification);
690         }
691
692
693             public void RemoveMonitor(string accountName)
694                 {
695                         if (String.IsNullOrWhiteSpace(accountName))
696                                 return;
697
698                         var accountInfo=_accounts.FirstOrDefault(account => account.UserName == accountName);
699                         _accounts.TryRemove(accountInfo);
700
701                         PithosMonitor monitor;
702                         if (Monitors.TryRemove(accountName, out monitor))
703                         {
704                                 monitor.Stop();
705                         }
706                 }
707
708                 public void RefreshOverlays()
709                 {
710                         foreach (var pair in Monitors)
711                         {
712                                 var monitor = pair.Value;
713
714                                 var path = monitor.RootPath;
715
716                                 if (String.IsNullOrWhiteSpace(path))
717                                         continue;
718
719                                 if (!Directory.Exists(path) && !File.Exists(path))
720                                         continue;
721
722                                 IntPtr pathPointer = Marshal.StringToCoTaskMemAuto(path);
723
724                                 try
725                                 {
726                                         NativeMethods.SHChangeNotify(HChangeNotifyEventID.SHCNE_UPDATEITEM,
727                                                                                                  HChangeNotifyFlags.SHCNF_PATHW | HChangeNotifyFlags.SHCNF_FLUSHNOWAIT,
728                                                                                                  pathPointer, IntPtr.Zero);
729                                 }
730                                 finally
731                                 {
732                                         Marshal.FreeHGlobal(pathPointer);
733                                 }
734                         }
735                 }
736
737                 #region Event Handlers
738                 
739                 public void Handle(SelectiveSynchChanges message)
740                 {
741                         var accountName = message.Account.AccountName;
742                         PithosMonitor monitor;
743                         if (_monitors.TryGetValue(accountName, out monitor))
744                         {
745                                 monitor.AddSelectivePaths(message.Added);
746                                 monitor.RemoveSelectivePaths(message.Removed);
747
748                         }
749                         
750                 }
751
752
753         //SMELL: Doing so much work for notifications in the shell is wrong
754         //The notifications should be moved to their own view/viewmodel pair
755         //and different templates should be used for different message types
756         //This will also allow the addition of extra functionality, eg. actions
757         //
758                 public void Handle(Notification notification)
759                 {
760             UpdateStatus();
761
762                         if (!Settings.ShowDesktopNotifications)
763                                 return;
764                         BalloonIcon icon;
765                         switch (notification.Level)
766                         {
767                                 case TraceLevel.Error:
768                                         icon = BalloonIcon.Error;
769                                         break;
770                                 case TraceLevel.Info:
771                                 case TraceLevel.Verbose:
772                                         icon = BalloonIcon.Info;
773                                         break;
774                                 case TraceLevel.Warning:
775                                         icon = BalloonIcon.Warning;
776                                         break;
777                                 default:
778                                         icon = BalloonIcon.None;
779                                         break;
780                         }
781
782                         if (Settings.ShowDesktopNotifications)
783                         {
784                                 var tv = (ShellView) GetView();
785                                 tv.TaskbarView.ShowBalloonTip(notification.Title, notification.Message, icon);
786                         }
787                 }
788                 #endregion
789
790                 public void Handle(ShowFilePropertiesEvent message)
791                 {
792                         if (message == null)
793                                 throw new ArgumentNullException("message");
794                         if (String.IsNullOrWhiteSpace(message.FileName) )
795                                 throw new ArgumentException("message");
796                         Contract.EndContractBlock();
797
798                         var fileName = message.FileName;
799             //TODO: Display file properties for non-container folders
800                         if (File.Exists(fileName))
801                 //Retrieve the full name with exact casing. Pithos names are case sensitive                             
802                 ShowFileProperties(FileInfoExtensions.GetProperFilePathCapitalization(fileName));
803                         else if (Directory.Exists(fileName))
804                 //Retrieve the full name with exact casing. Pithos names are case sensitive
805                         {
806                 var path = FileInfoExtensions.GetProperDirectoryCapitalization(fileName);
807                 if (IsContainer(path))
808                                 ShowContainerProperties(path);
809                 else
810                     ShowFileProperties(path);
811                         }
812                 }
813
814             private bool IsContainer(string path)
815             {
816                 var matchingFolders = from account in _accounts
817                                       from rootFolder in Directory.GetDirectories(account.AccountPath)
818                                       where rootFolder.Equals(path, StringComparison.InvariantCultureIgnoreCase)
819                                       select rootFolder;
820                 return matchingFolders.Any();
821             }
822
823             public FileStatus GetFileStatus(string localFileName)
824             {
825             if (String.IsNullOrWhiteSpace(localFileName))
826                 throw new ArgumentNullException("localFileName");
827             Contract.EndContractBlock();
828             
829                 var statusKeeper = IoC.Get<IStatusKeeper>();
830                 var status=statusKeeper.GetFileStatus(localFileName);
831                 return status;
832             }
833         }
834 }