示例#1
0
        public void Build(string indexName)
        {
            var indexExists = UmbracoSearchFactory.Client.IndexExists(indexName)?.Exists ?? false;

            if (!indexExists)
            {
                throw new InvalidOperationException($"'{indexName}' not available, please ensure you have created an index with this name");
            }
            using (BusyStateManager.Start($"Building media for {indexName}", indexName))
            {
                LogHelper.Info <MediaIndexer>($"Started building index [{indexName}]");
                foreach (var indexService in UmbracoSearchFactory.GetMediaIndexServices())
                {
                    try
                    {
                        LogHelper.Info <MediaIndexer>($"Started to index media for {indexService.DocumentTypeName}");
                        BusyStateManager.UpdateMessage($"Indexing {indexService.DocumentTypeName}");
                        indexService.Build(indexName);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error <MediaIndexer>($"Failed to index media for {indexService.DocumentTypeName}", ex);
                    }
                }
                LogHelper.Info <MediaIndexer>(
                    $"Finished building index [{indexName}] : elapsed {BusyStateManager.Elapsed:g}");
            }
        }
示例#2
0
        /// <summary>
        /// Exporting the selected WiFi XML profile to file. The profile retrieved from
        /// Windows is formatted using _profileProvider.Format before saving.
        /// </summary>
        private async Task ExportProfileAsync()
        {
            BusyStateManager.EnterBusy();
            BusyStateManager.SetMessage(SeverityType.Info, "Opening SaveFileDialog.");

            await Task.Run(() =>
            {
                SaveFileDialog dlg   = new SaveFileDialog();
                dlg.FileName         = SelectedWiFiProfile.ProfileName; // Default file name
                dlg.DefaultExt       = ".xml";                          // Default file extension
                dlg.Filter           = "XML file (*.xml) | *.xml";      // Filter files by extension
                dlg.InitialDirectory = _configurationProvider.ExportDir;
                dlg.Title            = "Save profile As";

                bool result = dlg.ShowDialog() ?? false;

                if (result)
                {
                    BusyStateManager.SetMessage(SeverityType.Info, "Exporting profile.");
                    File.WriteAllText(dlg.FileName, _profileService.Format(SelectedWiFiProfile.Xml));
                    /* Save last visited directory. */
                    _configurationProvider.ExportDir = Path.GetDirectoryName(dlg.FileName);
                }
            });

            BusyStateManager.SetMessage(SeverityType.None);
            BusyStateManager.ExitBusy();
        }
示例#3
0
        /// <summary>
        /// Remove the selected profile.
        /// </summary>
        private async Task RemoveProfileAsync()
        {
            BusyStateManager.EnterBusy();
            BusyStateManager.SetMessage(SeverityType.Info, "Removing selected profile.");

            /* Temporary store selected interface and WiFi profile so they can be restored after deletion. */
            Guid selectedInterfaceId = SelectedInterface.Id;
            int  profilePosition     = SelectedWiFiProfile.Position;

            await _mainController.DeleteProfileAsync(SelectedWiFiProfile);

            await DownloadProfilesAsync();

            /* Restore selected interface and position of selected WiFi profile. */
            Profile selectedWifiProfile = WiFiProfiles.Where(x => x.Id == selectedInterfaceId &&
                                                             x.Position == profilePosition).FirstOrDefault();

            if (selectedWifiProfile == default(Profile))
            {
                selectedWifiProfile = WiFiProfiles.Where(x => x.Id ==
                                                         selectedInterfaceId).OrderByDescending(x => x.Position).FirstOrDefault();
            }

            Interface selectedInterface = Interfaces.Where(x => x.Id == selectedInterfaceId).FirstOrDefault();

            SelectedInterface = selectedInterface == default(Interface) ?
                                Interfaces.FirstOrDefault() : selectedInterface;
            if (selectedWifiProfile != default(Profile))
            {
                SelectedWiFiProfile = selectedWifiProfile;
            }

            BusyStateManager.SetMessage(SeverityType.None);
            BusyStateManager.ExitBusy();
        }
 /// <summary>
 /// Cleanup when this view is deactivated.
 /// </summary>
 protected override void OnDeactivate(bool close)
 {
     BusyStateManager.PropertyChanged -= BusyStateManagerPropertyChanged;
     /* Clear status messages from current Dialog Window. */
     BusyStateManager.SetMessage(SeverityType.None);
     base.OnDeactivate(close);
 }
        /// <summary>
        /// Passwords generator using the specified regular expression.
        /// </summary>
        /// <param name="token">CancellationToken to stop string generation.</param>
        private async Task GenerateStrings(CancellationToken token)
        {
            List <string> matches = new List <string>();

            BusyStateManager.EnterBusy();
            BusyStateManager.SetMessage(SeverityType.Info, "Generating strings that match the specified RegEx.");

            await Task.Run(() =>
            {
                int count    = 0;
                string match = null;

                /* Set regular expression and add matches to collection. */
                if (_regExService.SetRegEx(RegEx))
                {
                    while (!token.IsCancellationRequested &&
                           count++ < MaxRows &&
                           (match = _regExService.GetNext()) != null)
                    {
                        matches.Add(match);
                    }
                }
            });

            RegExMatches = new ObservableCollection <string>(matches);

            BusyStateManager.SetMessage(SeverityType.None);
            BusyStateManager.ExitBusy();
        }
示例#6
0
        /// <summary>
        /// Retrieves access points and interfaces from the device and updates the view.
        /// </summary>
        private async Task DownloadAccessPointsAsync()
        {
            BusyStateManager.EnterBusy();
            BusyStateManager.SetMessage(SeverityType.Info, "Retrieving access points and interfaces.");

            /* Temporary store selected interface and access point so they can be restored after download. */
            Guid?  interfaceId = SelectedInterface?.Id;
            string profileName = SelectedAccessPoint?.ProfileName;
            string ssid        = SelectedAccessPoint?.Ssid;

            /* Scan and download access points and interfaces. */
            await _mainController.ScanNetworkAsync(TimeSpan.FromSeconds(_configurationProvider.Timeout),
                                                   CancellationToken.None);

            IEnumerable <AccessPoint> accessPoints = await _mainController.GetWiFiAccessPointsAsync();

            IEnumerable <Interface> interfaces = await _mainController.GetWiFiInterfacesAsync();

            if (accessPoints == default(IEnumerable <AccessPoint>) || interfaces == default(IEnumerable <Interface>))
            {
                AccessPoints = new ObservableCollection <AccessPoint>(Enumerable.Empty <AccessPoint>());
                WiFiAccessPointViewSource.Source = AccessPoints;
                Interfaces = new ObservableCollection <Interface>(Enumerable.Empty <Interface>());
            }
            else
            {
                /* User specified threshold is used to filter access points that meet this threshold. */
                AccessPoints = new ObservableCollection <AccessPoint>(accessPoints
                                                                      .Where(x => x.LinkQuality > _configurationProvider.Threshold));
                WiFiAccessPointViewSource.Source = AccessPoints;
                Interfaces = new ObservableCollection <Interface>(interfaces);
            }

            /* Restore selected interface and access point. */
            Interface   selectedInterface   = Interfaces.Where(x => x.Id == interfaceId).FirstOrDefault();
            AccessPoint selectedAccessPoint = default(AccessPoint);

            if (!string.IsNullOrEmpty(profileName))
            {
                selectedAccessPoint = AccessPoints.Where(x => x.Id == interfaceId &&
                                                         x.ProfileName == profileName).FirstOrDefault();
            }
            else if (!string.IsNullOrEmpty(ssid))
            {
                selectedAccessPoint = AccessPoints.Where(x => x.Id == interfaceId &&
                                                         x.Ssid.Equals(ssid, StringComparison.Ordinal)).FirstOrDefault();
            }

            SelectedInterface = selectedInterface == default(Interface) ?
                                Interfaces.FirstOrDefault() : selectedInterface;

            if (selectedAccessPoint != default(AccessPoint))
            {
                SelectedAccessPoint = selectedAccessPoint;
            }

            BusyStateManager.SetMessage(SeverityType.None);
            BusyStateManager.ExitBusy();
        }
 public async Task DeleteIndexAsync(string indexName)
 {
     using (
         BusyStateManager.Start(
             $"Deleting {indexName} triggered by '{UmbracoContext.Current.Security.CurrentUser.Name}'", indexName))
     {
         await client.DeleteIndexAsync(indexName);
     }
 }
 /// <summary>
 /// Select specified RegEx and return true to the parent view.
 /// </summary>
 public void SelectCmd()
 {
     if (_regExService.SetRegEx(RegEx))
     {
         TryClose(true);
     }
     else
     {
         BusyStateManager.SetMessage(SeverityType.Info, "Please enter a valid regular expression.");
     }
 }
 /// <summary>
 /// Starts generating passwords using specified RegEx.
 /// </summary>
 public void StartCmd()
 {
     if (_regExService.SetRegEx(RegEx))
     {
         cts = new CancellationTokenSource();
         GenerateStrings(cts.Token).FireAndForgetSafeAsync(_errorHandler);
     }
     else
     {
         BusyStateManager.SetMessage(SeverityType.Info, "Please enter a valid regular expression.");
     }
 }
示例#10
0
        /// <summary>
        /// Decrease the priority of the selected profile.
        /// </summary>
        private async Task DecreasePriorityAsync()
        {
            BusyStateManager.EnterBusy();
            BusyStateManager.SetMessage(SeverityType.Info, "Decreasing priority of the selected profile.");

            await _mainController.MoveDownProfileAsync(SelectedWiFiProfile);

            await DownloadProfilesAsync();

            BusyStateManager.SetMessage(SeverityType.None);
            BusyStateManager.ExitBusy();
        }
示例#11
0
        /// <summary>
        /// Set the selected profile as default connection profile (position 0).
        /// </summary>
        private async Task MakeProfileDefaultAsync()
        {
            BusyStateManager.EnterBusy();
            BusyStateManager.SetMessage(SeverityType.Info,
                                        "Setting the selected profile as the default connection profile.");

            await _mainController.SetProfileAsDefaultAsync(SelectedWiFiProfile);

            await DownloadProfilesAsync();

            BusyStateManager.SetMessage(SeverityType.None);
            BusyStateManager.ExitBusy();
        }
示例#12
0
 /// <summary>
 /// Show properties of selected access point and interface in properties view.
 /// </summary>
 public void PropertiesCmd()
 {
     try
     {
         _propertiesViewModel.SetAccessPoint(SelectedInterface, SelectedAccessPoint);
         _windowManager.ShowDialog(_propertiesViewModel);
     }
     catch (Exception ex)
     {
         BusyStateManager.SetMessage(SeverityType.Error, ex.Message);
         BusyStateManager.ClearBusy();
     }
 }
        public async Task ActivateIndexAsync(string indexName)
        {
            using (BusyStateManager.Start($"Activating {indexName} triggered by '{UmbracoContext.Current.Security.CurrentUser.Name}'", indexName))
            {
                var client         = UmbracoSearchFactory.Client;
                var indexAliasName = UmbracoSearchFactory.ActiveIndexName;
                await client.AliasAsync(a => a
                                        .Remove(r => r.Alias(indexAliasName).Index($"{indexAliasName}*"))
                                        .Add(aa => aa.Alias(indexAliasName).Index(indexName))
                                        );

                UmbracoSearchFactory.HasActiveIndex = true;
            }
        }
示例#14
0
        /// <summary>
        /// The SelectCmd() method checks if profile generation is implemented for selected access point.
        /// If profile generation is not implemented an error will be thrown in the
        /// _profileService.CreateProfileXml() method. If profile generation is implemented,
        /// the current view will be closed and true will be returned to parent view.
        /// </summary>
        /// <remarks>
        /// Enterprise networks wpa/wpa2 are currently not supported.
        /// </remarks>
        public void SelectCmd()
        {
            try
            {
                _profileService.CreateProfileXml(SelectedAccessPoint, null);

                TryClose(true);
            }
            catch (Exception ex)
            {
                BusyStateManager.SetMessage(SeverityType.Error, ex.Message);
                BusyStateManager.ClearBusy();
            }
        }
示例#15
0
        /// <summary>
        /// Disconnects from the selected interface.
        /// </summary>
        public async Task DisconnectAsync()
        {
            BusyStateManager.EnterBusy();
            BusyStateManager.SetMessage(SeverityType.Info,
                                        $"Disconnecting from interface [{SelectedInterface.Description}].");

            await _mainController.DisconnectNetworkAsync(SelectedInterface,
                                                         TimeSpan.FromSeconds(_configurationProvider.Timeout), CancellationToken.None);

            await RefreshAccessPointAsync();

            BusyStateManager.SetMessage(SeverityType.None);
            BusyStateManager.ExitBusy();
        }
 /// <summary>
 /// Move dictionary down the list.
 /// </summary>
 public void MoveDownCmd()
 {
     try
     {
         int index = Dictionaries.IndexOf(SelectedDictionary);
         Dictionaries.Swap(index, index + 1);
         SelectedDictionary = Dictionaries[index + 1];
     }
     catch (Exception ex)
     {
         BusyStateManager.SetMessage(SeverityType.Error, ex.Message);
         BusyStateManager.ClearBusy();
     }
 }
示例#17
0
 /// <summary>
 /// Move RegEx down the list.
 /// </summary>
 public void MoveDownCmd()
 {
     try
     {
         int index = PasswordRegExs.IndexOf(SelectedRegEx);
         PasswordRegExs.Swap(index, index + 1);
         SelectedRegEx = PasswordRegExs[index + 1];
     }
     catch (Exception ex)
     {
         BusyStateManager.SetMessage(SeverityType.Error, ex.Message);
         BusyStateManager.ClearBusy();
     }
 }
示例#18
0
        /// <summary>
        /// Manually connects to the selected access point.
        /// The user will be prompted for a password (if required).
        /// </summary>
        public async Task ConnectAsync()
        {
            bool   dialogResult = false;
            string password     = null;
            string msg          = null;

            BusyStateManager.EnterBusy();
            BusyStateManager.SetMessage(SeverityType.Info,
                                        $"Connecting to access point [{SelectedAccessPoint.Ssid}].");

            /* Check if profile generation is implemented for Access Point. */
            /* If profile generation is not implemented an Exception will be thrown. */
            _profileService.CreateProfileXml(SelectedAccessPoint, password);
            if (SelectedAccessPoint.IsPasswordRequired)
            {
                _passwordViewModel.SelectedAccessPoint = SelectedAccessPoint;
                dialogResult = _windowManager.ShowDialog(_passwordViewModel) ?? false;
                if (dialogResult)
                {
                    password = _passwordViewModel.Password;
                }
            }

            if ((SelectedAccessPoint.IsPasswordRequired && dialogResult) ||
                !SelectedAccessPoint.IsPasswordRequired)
            {
                bool isConnected = await _mainController.ConnectNetworkAsync(SelectedAccessPoint,
                                                                             password, TimeSpan.FromSeconds(_configurationProvider.Timeout), CancellationToken.None);

                await DownloadAccessPointsAsync();

                if (isConnected)
                {
                    msg = $"Successfully connected to access point [{SelectedAccessPoint.Ssid}].";
                }
                else
                {
                    msg = $"Failed to connect to access point [{SelectedAccessPoint.Ssid}].";
                }

                BusyStateManager.SetMessage(SeverityType.Info, msg);
            }

            if (SelectedAccessPoint.IsPasswordRequired && !dialogResult)
            {
                BusyStateManager.SetMessage(SeverityType.None);
            }

            BusyStateManager.ExitBusy();
        }
示例#19
0
 /// <summary>
 /// Start password match process. In order to start password match process, user must have selected
 /// a access point and configured a password provider.
 /// </summary>
 public void StartCmd()
 {
     if (SelectedAccessPoint == null)
     {
         BusyStateManager.SetMessage(SeverityType.Info, "No access point selected.");
     }
     else if (SelectedPasswordProvider == null || SelectedPasswordProvider.IsEmpty)
     {
         BusyStateManager.SetMessage(SeverityType.Info, "No password provider configured.");
     }
     else
     {
         cts = new CancellationTokenSource();
         MatchPasswords(cts.Token).FireAndForgetSafeAsync(_errorHandler);
     }
 }
示例#20
0
        /// <summary>
        /// Imports WiFi XML profile from file. After validation, the imported profile is added
        /// to the selected WiFi interface.
        /// </summary>
        private async Task ImportProfileAsync()
        {
            bool isValid = false;

            BusyStateManager.EnterBusy();
            BusyStateManager.SetMessage(SeverityType.Info, "Opening OpenFileDialog.");

            OpenFileDialog dlg = new OpenFileDialog();

            dlg.DefaultExt       = ".xml";                     // Default file extension
            dlg.Filter           = "XML file (*.xml) | *.xml"; // Filter files by extension
            dlg.InitialDirectory = _configurationProvider.ImportDir;
            dlg.Title            = "Import profile.";
            dlg.Multiselect      = false;

            bool result = dlg.ShowDialog() ?? false;

            if (result)
            {
                string profileXml = File.ReadAllText(dlg.FileName);
                /* Validate WiFi XML profile before importing it. */
                Profile profile = new Profile();
                isValid = _profileService.Parse(profileXml, ref profile);

                if (isValid)
                {
                    BusyStateManager.SetMessage(SeverityType.Info, "Importing profile.");
                    isValid = await _mainController.AddProfileAsync(SelectedInterface, profileXml);
                    await DownloadProfilesAsync();
                }

                /* Set dialog initial directory to last visited directory. */
                _configurationProvider.ImportDir = Path.GetDirectoryName(dlg.FileName);
            }

            if (result && !isValid)
            {
                BusyStateManager.SetMessage(SeverityType.Error,
                                            "Failed to validate the profile, please check the file.");
            }
            else
            {
                BusyStateManager.SetMessage(SeverityType.None);
            }

            BusyStateManager.ExitBusy();
        }
示例#21
0
 /// <summary>
 /// Adds a regular expression using addRegexView.
 /// </summary>
 public void AddRegExCmd()
 {
     try
     {
         bool dialogResult = _windowManager.ShowDialog(_addRegexViewModel) ?? false;
         if (dialogResult)
         {
             PasswordRegExs.Add(new PasswordRegEx(_regExService, _addRegexViewModel.RegEx));
             /* Select first RegEx in list. */
             SelectedRegEx = PasswordRegExs.FirstOrDefault();
         }
     }
     catch (Exception ex)
     {
         BusyStateManager.SetMessage(SeverityType.Error, ex.Message);
         BusyStateManager.ClearBusy();
     }
 }
示例#22
0
 /// <summary>
 /// Select access point from the access points in range.
 /// </summary>
 public void SelectAccessPointCmd()
 {
     try
     {
         bool dialogResult = _windowManager.ShowDialog(_wiFiSearchViewModel) ?? false;
         if (dialogResult)
         {
             AccessPoints.Add(_wiFiSearchViewModel.SelectedAccessPoint);
             SelectedAccessPoint = _wiFiSearchViewModel.SelectedAccessPoint;
             SelectedInterface   = _wiFiSearchViewModel.SelectedInterface;
         }
     }
     catch (Exception ex)
     {
         BusyStateManager.SetMessage(SeverityType.Error, ex.Message);
         BusyStateManager.ClearBusy();
     }
 }
示例#23
0
        /// <summary>
        /// Retrieves the WiFi profiles and interfaces and updates the View.
        /// </summary>
        private async Task DownloadProfilesAsync()
        {
            BusyStateManager.EnterBusy();
            BusyStateManager.SetMessage(SeverityType.Info, "Retrieving profiles and interfaces.");

            /* Temporary store selected interface and wifi profile so they can be restored after download. */
            Guid?  interfaceId = SelectedInterface?.Id;
            string profileName = SelectedWiFiProfile?.ProfileName;

            /* Download wifi profiles and interfaces. */
            IEnumerable <Profile> profiles = await _mainController.GetWiFiProfilesAsync();

            IEnumerable <Interface> interfaces = await _mainController.GetWiFiInterfacesAsync();

            if (profiles == default(IEnumerable <Profile>) || interfaces == default(IEnumerable <Interface>))
            {
                WiFiProfiles = new ObservableCollection <Profile>(Enumerable.Empty <Profile>());
                WiFiProfilesViewSource.Source = WiFiProfiles;
                Interfaces = new ObservableCollection <Interface>(Enumerable.Empty <Interface>());
            }
            else
            {
                WiFiProfiles = new ObservableCollection <Profile>(profiles);
                WiFiProfilesViewSource.Source = WiFiProfiles;
                Interfaces = new ObservableCollection <Interface>(interfaces);
            }

            /* Restore selected interface and wifi profile. */
            Interface selectedInterface   = Interfaces.Where(x => x.Id == interfaceId).FirstOrDefault();
            Profile   selectedWifiProfile = WiFiProfiles.Where(x => x.Id == interfaceId &&
                                                               x.ProfileName == profileName).FirstOrDefault();

            SelectedInterface = selectedInterface == default(Interface) ?
                                Interfaces.FirstOrDefault() : selectedInterface;
            if (selectedWifiProfile != default(Profile))
            {
                SelectedWiFiProfile = selectedWifiProfile;
            }

            BusyStateManager.SetMessage(SeverityType.None);
            BusyStateManager.ExitBusy();
        }
示例#24
0
        public MainViewModel(
            BusyStateManager busyStateManager,
            INavigationService navigationService,
            MvvmDialogs.IDialogService dialogService)
        {
            Title = Assembly.GetEntryAssembly().GetName().Name;

            BusyStateManager     = busyStateManager;
            _navigationService   = navigationService;
            SelectedIndexManager = _navigationService;
            SelectedIndexManager.SelectedIndex = (int)HamburgerNavItemsIndex.Login;

            DialogService = dialogService;

            StoryFilterCmd      = new RelayCommand(OnStoryFilter, () => CanExecuteStoryFilter);
            ClearStoryFilterCmd = new RelayCommand(OnClearStoryFilter, () => CanExecuteStoryFilter);
            FullScreenCmd       = new RelayCommand(OnFullScreen, () => CanExecuteFullScreenToggle);
            ExitCmd             = new RelayCommand(OnExit);

            MessengerInstance.Register <AuthenticatedMessage>(this, OnAuthenticated);
        }
示例#25
0
        /// <summary>
        /// Refresh selected access point properties.
        /// </summary>
        private async Task RefreshAccessPointAsync()
        {
            BusyStateManager.EnterBusy();
            BusyStateManager.SetMessage(SeverityType.Info,
                                        $"Refreshing the status of access point [{SelectedAccessPoint.Ssid}].");

            IEnumerable <AccessPoint> accessPoints = await _mainController.GetWiFiAccessPointsAsync();

            AccessPoint accessPoint = accessPoints.Where(x => x.Id == SelectedAccessPoint.Id &&
                                                         x.Ssid == SelectedAccessPoint.Ssid &&
                                                         x.ProfileName == SelectedAccessPoint.Ssid).FirstOrDefault();

            /* If access point not found, repeat search without specifying profile name. */
            if (accessPoint == default(AccessPoint))
            {
                accessPoint = accessPoints.Where(x => x.Id == SelectedAccessPoint.Id &&
                                                 x.Ssid == SelectedAccessPoint.Ssid).FirstOrDefault();
            }

            /* Update access point in view. */
            if (accessPoint != default(AccessPoint))
            {
                AccessPoints.Clear();
                AccessPoints.Add(accessPoint);
                SelectedAccessPoint = accessPoint;
            }

            /* Update SelectedInterface status, (isConnected). */
            IEnumerable <Interface> interfaces = await _mainController.GetWiFiInterfacesAsync();

            Interface wiFiInterface = interfaces.Where(x => x.Id == SelectedInterface.Id).FirstOrDefault();

            if (wiFiInterface != default(Interface))
            {
                SelectedInterface = wiFiInterface;
            }

            BusyStateManager.SetMessage(SeverityType.None);
            BusyStateManager.ExitBusy();
        }
        /// <summary>
        /// Imports a dictionary, the imported dictionary is added to the dictionaries collection.
        /// </summary>
        private async Task AddDictionaryAsync()
        {
            BusyStateManager.EnterBusy();
            BusyStateManager.SetMessage(SeverityType.Info, "Opening OpenFileDialog.");

            await Task.Run(() =>
            {
                OpenFileDialog dlg   = new OpenFileDialog();
                dlg.DefaultExt       = ".txt";                                        // Default file extension
                dlg.Filter           = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; // Filter files by extension
                dlg.InitialDirectory = _configurationProvider.DictionariesDir;
                dlg.Title            = "Import dictionaries";
                dlg.Multiselect      = true;

                bool dialogResult = dlg.ShowDialog() ?? false;
                if (dialogResult)
                {
                    foreach (string FileName in dlg.FileNames)
                    {
                        App.Current.Dispatcher.BeginInvoke(new System.Action(() =>
                        {
                            Dictionaries.Add(new Dictionary(FileName, Encoding.UTF8));
                        }));
                    }

                    /* Set dialog initial directory to last visited directory. */
                    string file = dlg.FileNames.FirstOrDefault();
                    if (file != default(string))
                    {
                        _configurationProvider.DictionariesDir = Path.GetDirectoryName(file);
                    }
                }
            });

            /* Select first dictionary in list. */
            SelectedDictionary = Dictionaries.FirstOrDefault();
            BusyStateManager.SetMessage(SeverityType.None);
            BusyStateManager.ExitBusy();
        }
示例#27
0
        /// <summary>
        /// Manually connects to the selected access point.
        /// The user will be prompted for a password.
        /// </summary>
        public async Task ConnectAsync()
        {
            bool   dialogResult = false;
            string password     = null;
            string msg          = null;

            BusyStateManager.EnterBusy();
            BusyStateManager.SetMessage(SeverityType.Info,
                                        $"Connecting to access point [{SelectedAccessPoint.Ssid}].");

            _passwordViewModel.SelectedAccessPoint = SelectedAccessPoint;
            dialogResult = _windowManager.ShowDialog(_passwordViewModel) ?? false;

            if (dialogResult)
            {
                password = _passwordViewModel.Password;
                bool isConnected = await _mainController.ConnectNetworkAsync(SelectedAccessPoint,
                                                                             password, TimeSpan.FromSeconds(_configurationProvider.Timeout), CancellationToken.None);

                if (isConnected)
                {
                    msg = $"Successfully connected to access point [{SelectedAccessPoint.Ssid}].";
                    await RefreshAccessPointAsync();
                }
                else
                {
                    msg = $"Failed to connect to access point [{SelectedAccessPoint.Ssid}].";
                }
                BusyStateManager.SetMessage(SeverityType.Info, msg);
            }
            else
            {
                BusyStateManager.SetMessage(SeverityType.None);
            }

            BusyStateManager.ExitBusy();
        }
        /// <summary>
        /// Remove selected dictionary and restore selected dictionary to previous or
        /// next dictionary in the list.
        /// </summary>
        public void RemoveDictionaryCmd()
        {
            try
            {
                /* Index needed to restore the selected dictionary. */
                int index = Dictionaries.IndexOf(SelectedDictionary);
                Dictionaries.Remove(SelectedDictionary);

                /* Restore the selected dictionary. */
                if (Dictionaries.Count > 0 && index < Dictionaries.Count)
                {
                    SelectedDictionary = Dictionaries[index];
                }
                else if (Dictionaries.Count > 0 && index == Dictionaries.Count)
                {
                    SelectedDictionary = Dictionaries[index - 1];
                }
            }
            catch (Exception ex)
            {
                BusyStateManager.SetMessage(SeverityType.Error, ex.Message);
                BusyStateManager.ClearBusy();
            }
        }
示例#29
0
        /// <summary>
        /// Removes the selected regular expression.
        /// </summary>
        public void RemoveRegExCmd()
        {
            try
            {
                /* Index needed to restore the selected RegEx position. */
                int index = PasswordRegExs.IndexOf(SelectedRegEx);
                PasswordRegExs.Remove(SelectedRegEx);

                /* Restore the selected RegEx position. */
                if (PasswordRegExs.Count > 0 && index < PasswordRegExs.Count)
                {
                    SelectedRegEx = PasswordRegExs[index];
                }
                else if (PasswordRegExs.Count > 0 && index == PasswordRegExs.Count)
                {
                    SelectedRegEx = PasswordRegExs[index - 1];
                }
            }
            catch (Exception ex)
            {
                BusyStateManager.SetMessage(SeverityType.Error, ex.Message);
                BusyStateManager.ClearBusy();
            }
        }
示例#30
0
        /// <summary>
        /// Password match process, uses different passwords (provided by the password provider)
        /// to connect to the selected access point. If a password is found that
        /// gains access to the access point, the password will be saved in file.
        /// </summary>
        /// <param name="token">CancellationToken to cancel the password match process.</param>
        private async Task MatchPasswords(CancellationToken token)
        {
            string errorMsg  = null;
            bool   connected = false;
            bool   isValid   = false;
            string msg       = null;

            BusyStateManager.EnterBusy();
            BusyStateManager.SetMessage(SeverityType.Info,
                                        $"Attempting to connect to the specified access point [{SelectedAccessPoint.Ssid}].");

            string password = SelectedPasswordProvider.GetFirst();

            ReportProgress(password, true);

            while (!token.IsCancellationRequested && password != null && !connected)
            {
                /* Validate the entered password, checks if password complies to password rules. */
                isValid = PasswordHelper.IsValid(password, SelectedAccessPoint.Encryption, ref errorMsg);

                /* If the entered password is valid, try to connect. */
                if (isValid)
                {
                    connected = await _mainController.ConnectNetworkAsync(SelectedAccessPoint, password,
                                                                          TimeSpan.FromSeconds(_configurationProvider.Timeout), token);
                }
                /* Invalid password, does not comply to wifi password rules. */
                else
                {
                    BusyStateManager.SetMessage(SeverityType.Info, $"{errorMsg}, password=[{password}].");
                    /* Display error message for 400 ms and continue match process. */
                    await Task.Delay(400);

                    BusyStateManager.SetMessage(SeverityType.Info,
                                                $"Attempting to connect to the specified access point [{SelectedAccessPoint.Ssid}].");
                }

                /* Get next passwords while not connected. */
                if (!connected)
                {
                    password = SelectedPasswordProvider.GetNext();
                    if (password != null)
                    {
                        ReportProgress(password);
                    }
                }
            }

            if (connected)
            {
                /* Save password to file, path is configured in SettingsViewModel. */
                FileMode fileMode = _configurationProvider.OverwriteFile ? FileMode.Create : FileMode.Append;
                string   filePath = string.Format("{0}\\{1}",
                                                  _configurationProvider.PasswordStorageDir, _configurationProvider.FileName);
                await _storageService.WriteToFileAsync(filePath, fileMode,
                                                       $"Ssid={SelectedAccessPoint.Ssid}, password={password}\n");

                /* If connected, retrieve access point and update status (isConnected) of SelectedAccessPoint. */
                await RefreshAccessPointAsync();

                msg = $"Successfully connected to access point [{SelectedAccessPoint.Ssid}] using password [{password}].";
            }
            else if (token.IsCancellationRequested)
            {
                msg = "Password match process was cancelled.";
            }
            else
            {
                msg = $"Failed to connect to the specified access point [{SelectedAccessPoint.Ssid}].";
            }

            BusyStateManager.SetMessage(SeverityType.Info, msg);
            BusyStateManager.ExitBusy();
        }