예제 #1
0
        private Task <MediaFile> TakeMediaAsync(string type, string action, StoreMediaOptions options, CancellationToken token = default(CancellationToken))
        {
            int id = GetRequestId();

            if (token.IsCancellationRequested)
            {
                return(Task.FromResult((MediaFile)null));
            }

            var ntcs = new TaskCompletionSource <MediaFile>(id);

            if (Interlocked.CompareExchange(ref completionSource, ntcs, null) != null)
            {
                throw new InvalidOperationException("Only one operation can be active at a time");
            }

            context.StartActivity(CreateMediaIntent(id, type, action, options));

            EventHandler <MediaPickedEventArgs> handler = null;

            handler = (s, e) =>
            {
                var tcs = Interlocked.Exchange(ref this.completionSource, null);

                MediaPickerActivity.MediaPicked -= handler;

                if (e.RequestId != id)
                {
                    return;
                }

                if (e.IsCanceled)
                {
                    tcs.SetResult(null);
                }
                else if (e.Error != null)
                {
                    tcs.SetException(e.Error);
                }
                else
                {
                    tcs.SetResult(e.Media);
                }
            };

            token.Register(() =>
            {
                var tcs = Interlocked.Exchange(ref this.completionSource, null);

                MediaPickerActivity.MediaPicked -= handler;
                CancelRequested?.Invoke(null, EventArgs.Empty);
                CancelRequested = null;

                tcs.SetResult(null);
            });

            MediaPickerActivity.MediaPicked += handler;

            return(completionSource.Task);
        }
예제 #2
0
        private void Save()
        {
            try
            {
                if (IsNewTable == false)
                {
                    Data.Table table = _tablesRepository.GetTableById(ManipulatedTable.Id);
                    table.Name     = ManipulatedTable.Name;
                    table.Capacity = ManipulatedTable.Capacity;

                    _tablesRepository.UpdateTable(table);
                    CancelRequested?.Invoke();
                    MessageHandler.InvokeSuccessMessage(Resources.InformationUpdateTable, Resources.InformationTableUpdated);
                }
                else
                {
                    _tablesRepository.AddTable(new Table
                    {
                        Capacity = ManipulatedTable.Capacity, Name = ManipulatedTable.Name, IsOccupied = ManipulatedTable.IsOccupied, Id = ManipulatedTable.Id
                    });

                    ToTableViewRequested?.Invoke();
                    MessageHandler.InvokeSuccessMessage(Resources.InformationAddTable, Resources.InformationTableAdded);
                }
            }

            catch (Exception e)
            {
                ErrorHandler.ThrowError(0, e.Message);
            }
        }
예제 #3
0
파일: Promise.cs 프로젝트: andeart/promises
 public void RequestCancel()
 {
     if (State == PromiseState.Pending)
     {
         CancelRequested?.Invoke(this, new PromiseCancelRequestedEventArgs());
     }
 }
        /// <summary>
        /// Show the dialogue displaying the scan progress and start the scan
        /// </summary>
        /// <param name="manager"></param>
        public static void ShowFragment(FragmentManager manager, string libraryToScan, CancelRequested callback, BindDialog bindCallback)
        {
            // Save the parameters so that they are available after a configuration change
            libraryName = libraryToScan;
            reporter    = callback;
            binder      = bindCallback;

            new ScanProgressDialogFragment().Show(manager, "fragment_scan_progress");
        }
예제 #5
0
        /// <inheritdoc />
        public void Cancel()
        {
            int value = Interlocked.Increment(ref _cancelling);

            if (value == 0)
            {
                CancelRequested?.Invoke(this, EventArgs.Empty);
            }
        }
예제 #6
0
        Task <List <MediaFile> > TakeMediasAsync(string type, string action, StoreMediaOptions options, CancellationToken token = default(CancellationToken))
        {
            var id = GetRequestId();

            if (token.IsCancellationRequested)
            {
                return(Task.FromResult((List <MediaFile>)null));
            }

            var ntcs = new TaskCompletionSource <List <MediaFile> >(id);

            if (Interlocked.CompareExchange(ref CompletionSourceMulti, ntcs, null) != null)
            {
                throw new InvalidOperationException("Only one operation can be active at a time");
            }

            context.StartActivity(CreateMediaIntent(id, type, action, options));

            void handler(object s, MediaPickedEventArgs e)
            {
                var tcs = Interlocked.Exchange(ref CompletionSourceMulti, null);

                MediaPickerActivity.MediaPicked -= handler;

                if (e.RequestId != id)
                {
                    return;
                }

                if (e.IsCanceled)
                {
                    tcs.SetResult(null);
                }
                else if (e.Error != null)
                {
                    tcs.SetException(e.Error);
                }
                else
                {
                    tcs.SetResult(e.Media);
                }
            }

            token.Register(() =>
            {
                var tcs = Interlocked.Exchange(ref CompletionSourceMulti, null);
                MediaPickerActivity.MediaPicked -= handler;
                CancelRequested?.Invoke(null, EventArgs.Empty);
                CancelRequested = null;

                tcs.SetResult(null);
            });

            MediaPickerActivity.MediaPicked += handler;

            return(CompletionSourceMulti.Task);
        }
예제 #7
0
 internal void Cancel()
 {
     lock (sync) {
         if (!IsFinished)
         {
             IsCancelRequested = true;
             State             = JobState.Cancelled;
             CancelRequested?.Invoke(this, EventArgs.Empty);
         }
     }
     Log.Debug("Canceled", Title);
 }
예제 #8
0
 private void CancelButton_Click(object sender, EventArgs e)
 {
     if (DidCancel)
     {
         return;
     }
     DidCancel = true;
     _timer.Stop();
     _infoTxt.Text          = "Cancelling...";
     _progressLabel.Visible = false;
     _cancelButton.Enabled  = false;
     CancelRequested?.Invoke(this, EventArgs.Empty);
 }
예제 #9
0
        public override void Close()
        {
            switch (State)
            {
            case ProgressNotificationState.Cancelled:
                base.Close();
                break;

            case ProgressNotificationState.Active:
            case ProgressNotificationState.Queued:
                if (CancelRequested?.Invoke() != false)
                {
                    State = ProgressNotificationState.Cancelled;
                }
                break;
            }
        }
예제 #10
0
        /// <summary>
        /// Scan a directory held at the FTP server
        /// </summary>
        /// <param name="directoryName"></param>
        /// <returns></returns>
        public async Task ScanDirectory(string directoryName)
        {
            if ((CancelRequested?.Invoke() ?? false) == false)
            {
                // Access the directory details
                DirectoryInfo info = new DirectoryInfo(directoryName);

                // Make sure it exists
                if (info.Exists == true)
                {
                    // Use a list to collect all the songs in this folder
                    List <ScannedSong> songs = new List <ScannedSong>();

                    foreach (FileInfo fi in info.GetFiles())
                    {
                        // Only process MP3 files
                        if (fi.Name.ToUpper().EndsWith(".MP3"))
                        {
                            Logger.Log(string.Format("Processing song no {1} : {0}", fi.FullName, ++songCount));

                            // At this point if the library is only being rescanned then there may be no reason to actually start downloading the file
                            if (storageInterface.DoesSongRequireScanning(fi.FullName.Replace(rootDirectory, ""), fi.LastWriteTime) == true)
                            {
                                songs.Add(await GetFileTags(fi));
                            }
                        }
                    }

                    // If any songs are available pass them back via the delegate
                    if (songs.Count > 0)
                    {
                        await storageInterface.SongsScanned(songs);
                    }

                    // Now process the subdirectories
                    foreach (DirectoryInfo diSubDir in info.GetDirectories())
                    {
                        await ScanDirectory(diSubDir.FullName);
                    }
                }
            }
        }
예제 #11
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (createTime_ != null)
            {
                hash ^= CreateTime.GetHashCode();
            }
            if (endTime_ != null)
            {
                hash ^= EndTime.GetHashCode();
            }
            if (Target.Length != 0)
            {
                hash ^= Target.GetHashCode();
            }
            if (Verb.Length != 0)
            {
                hash ^= Verb.GetHashCode();
            }
            if (StatusDetail.Length != 0)
            {
                hash ^= StatusDetail.GetHashCode();
            }
            if (CancelRequested != false)
            {
                hash ^= CancelRequested.GetHashCode();
            }
            if (ApiVersion.Length != 0)
            {
                hash ^= ApiVersion.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
예제 #12
0
        public void OpenCameraAsync(Action <byte[]> pictureHandler, CancellationToken token = default(CancellationToken))
        {
            if (!IsCameraAvailable)
            {
                throw new NotSupportedException();
            }

            var id = GetRequestId();

            void handler(object s, OnPictureTakenEventArgs e)
            {
                FaceCameraActivity.OnPictureTaken -= handler;

                if (e.RequestId != id)
                {
                    return;
                }

                if (!e.IsCanceled && e.Error == null)
                {
                    pictureHandler(e.Data);
                }
            }

            token.Register(() =>
            {
                FaceCameraActivity.OnPictureTaken -= handler;

                CancelRequested?.Invoke(null, EventArgs.Empty);
                CancelRequested = null;
            }, true);

            FaceCameraActivity.OnPictureTaken += handler;

            context.StartActivity(CreateMediaIntent(id));
        }
예제 #13
0
 public ProgressViewModel()
 {
     CancelCommand = new RelayCommand(() => CancelRequested?.Invoke(this, EventArgs.Empty), () => CanCancel);
 }
예제 #14
0
        /// <summary>
        /// Scan a directory held at the FTP server
        /// </summary>
        /// <param name="directoryName"></param>
        /// <returns></returns>
        public async Task ScanDirectory(string directoryName)
        {
            // Get the directory contents from the server
            FtpWebResponse response = await new FtpRequest(ftpHeader + directoryName, WebRequestMethods.Ftp.ListDirectoryDetails, false).MakeRequestAsync();

            // Read the response into a string
            string rawDirectoryListing = "";

            using (Stream responseStream = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    rawDirectoryListing = await reader.ReadToEndAsync();
                }

            // Parse the response into a list of DirectoryItem ( include files )
            List <DirectoryItem> items = new List <DirectoryItem>();

            foreach (string line in rawDirectoryListing.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries))
            {
                // Parse date
                DateTime dateTime = DateTime.MinValue;
                try
                {
                    dateTime = DateTime.ParseExact(line.Substring(0, 17), "MM-dd-yy  hh:mmtt", CultureInfo.InvariantCulture);
                }
                catch (FormatException)
                {
                }

                // Add to list
                items.Add(new DirectoryItem {
                    Created     = dateTime,
                    IsDirectory = (line.Substring(24, 5).ToUpper() == "<DIR>"),
                    Name        = line.Substring(39),
                    Base        = directoryName
                });
            }

            // Use a list to collect all the songs in this folder
            List <ScannedSong> songs = new List <ScannedSong>();

            // Use a while loop and check for cancellation
            int itemIndex = 0;

            while ((itemIndex < items.Count) && ((CancelRequested?.Invoke() ?? false) == false))
            {
                DirectoryItem item = items[itemIndex++];

                // If this is a directory then scan it
                if (item.IsDirectory == true)
                {
                    await ScanDirectory(item.AbsolutePath);
                }
                else
                {
                    // Only process MP3 files
                    if (item.Name.ToUpper().EndsWith(".MP3"))
                    {
                        Logger.Log(string.Format("Processing song no {1} : {0}", item.AbsolutePath, ++songCount));

                        // At this point if the library is only being rescanned then there may be no reason to actually start downloading the file
                        if (storageInterface.DoesSongRequireScanning(item.AbsolutePath, item.Created) == true)
                        {
                            songs.Add(await GetFileTags(item));
                        }
                    }
                }
            }

            // If any songs are available pass them back via the delegate
            if (songs.Count > 0)
            {
                await storageInterface.SongsScanned(songs);
            }
        }
예제 #15
0
 /// <summary>
 /// Cancel button is clicked
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void btnCancel_Click(object sender, RoutedEventArgs e)
 {
     CancelRequested?.Invoke(this.DataContext as FileEntryWrapper);
 }
예제 #16
0
 /// <summary>
 /// Invoked CancelRequested. (=<inheritdoc cref="CancelRequested"/>)
 /// </summary>
 private void Cancel()
 {
     CancelRequested?.Invoke();
 }
        private void OnCancelRequested()
        {
            EventArgs args = new EventArgs();

            CancelRequested?.Invoke(this, args);
        }
예제 #18
0
 private void LblCancel_Click(object sender, EventArgs e)
 {
     CancelRequested?.Invoke(sender, e);
 }
예제 #19
0
 protected virtual void OnCancelRequested()
 {
     CancelRequested?.Invoke(this, EventArgs.Empty);
 }
예제 #20
0
 void CancelButton_TouchUpInside(object sender, EventArgs e)
 {
     CancelRequested?.Invoke();
 }
예제 #21
0
        private void Save()
        {
            try
            {
                for (int i = 0; i < Users.Count; i++)
                {
                    if (ManipulatedUser.Email == Users[i].Email && ManipulatedUser.ID != Users[i].ID) // als de email van een gebruiker gelijk is aan de email van een al bestaande, maar andere gebruiker dan zichzelf
                    {
                        throw new InvalidOperationException(Properties.Resources.ErrorEmailAlreadyInUse);
                    }
                }

                Data.User user;

                if (!IsNewUser)
                {
                    user = _usersRepository.GetUserById(ManipulatedUser.ID);
                }
                else
                {
                    user = new Data.User();
                }

                user.LastName    = ManipulatedUser.LastName;
                user.FirstName   = ManipulatedUser.FirstName;
                user.Address     = null; // we stop using address
                user.Password    = ManipulatedUser.Password;
                user.Email       = ManipulatedUser.Email;
                user.PhoneNumber = ManipulatedUser.PhoneNumber;
                user.NFCUID      = ManipulatedUser.NFCUID;
                user.Role        = SelectedRole;

                if (IsNewUser == false)
                {
                    if (MainWindowViewModel.User.ID == ManipulatedUser.ID) // check if the user beeing updated is the same as the current logged in user.
                    {
                        if (MainWindowViewModel.User.Role != SelectedRole)
                        {
                            throw new InvalidOperationException(Properties.Resources.ErrorCannotChangeYourOwnRole);
                        }
                    }
                    _usersRepository.UpdateUser(user);
                    CancelRequested?.Invoke();
                }
                else
                {
                    try
                    {
                        System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog();

                        saveFileDialog.Filter           = "txt files (*.txt)|*.txt";
                        saveFileDialog.FilterIndex      = 2;
                        saveFileDialog.RestoreDirectory = true;
                        saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

                        if (saveFileDialog.ShowDialog() == DialogResult.OK)
                        {
                            using (StreamWriter writer = new StreamWriter(saveFileDialog.FileName))
                            {
                                writer.WriteLine(Properties.Resources.WarningChangePassword);
                                writer.WriteLine($"password: {user.Password}");
                                writer.Close();
                            }
                        }
                        else
                        {
                            // show pwd in msbx, because when the pwd cannot be saved in a textfile, the user cannot login.
                            System.Windows.MessageBox.Show(Properties.Resources.ErrorCreateUser.Replace("{password}", ManipulatedUser.Password));
                        }

                        _usersRepository.AddUser(user);
                        CancelRequested?.Invoke();
                    }
                    catch (ArgumentException ex)
                    {
                        ErrorHandler.ThrowError(0, ex.Message);
                    }
                    catch (InvalidOperationException ex)
                    {
                        ErrorHandler.ThrowError(0, ex.Message);
                    }
                    catch (Exception)
                    {
                        // when something goes wrong, show pwd in msbx, because when the pwd cannot be saved in a textfile, the user cannot login.
                        System.Windows.MessageBox.Show(Properties.Resources.ErrorCreateUser.Replace("{password}", ManipulatedUser.Password));
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorHandler.ThrowError(0, ex.Message);
            }
        }