public virtual void HideLoading()
 {
     if (this.loading != null) {
         this.loading.Dispose();
         this.loading = null;
     }
 }
        /// <summary>
        /// Warning, if the book already exists in the location, this is going to delete it an over-write it. So it's up to the caller to check the sanity of that.
        /// </summary>
        /// <param name="storageKeyOfBookFolder"></param>
        public string DownloadBook(string bucketName, string storageKeyOfBookFolder, string pathToDestinationParentDirectory,
			IProgressDialog downloadProgress = null)
        {
            //review: should we instead save to a newly created folder so that we don't have to worry about the
            //other folder existing already? Todo: add a test for that first.

            // We need to download individual files to avoid downloading unwanted files (PDFs and thumbs.db to
            // be specific).  See https://silbloom.myjetbrains.com/youtrack/issue/BL-2312.  So we need the list
            // of items, not just the count.
            var matching = GetMatchingItems(bucketName, storageKeyOfBookFolder);
            var totalItems = CountDesiredFiles(matching);
            if(totalItems == 0)
                throw new DirectoryNotFoundException("The book we tried to download is no longer in the BloomLibrary");

            Debug.Assert(matching.S3Objects[0].Key.StartsWith(storageKeyOfBookFolder + "/"));

            // Get the top-level directory name of the book from the first object key.
            var bookFolderName = matching.S3Objects[0].Key.Substring(storageKeyOfBookFolder.Length + 1);
            while(bookFolderName.Contains("/"))
                bookFolderName = Path.GetDirectoryName(bookFolderName);

            // Amazon.S3 appears to truncate titles at 50 characters when building directory and filenames.  This means
            // that relative paths can be as long as 117 characters (2 * 50 + 2 for slashes + 15 for .BloomBookOrder).
            // So our temporary folder must be no more than 140 characters (allow some margin) since paths can be a
            // maximum of 260 characters in Windows.  (More margin than that may be needed because there's no guarantee
            // that image filenames are no longer than 65 characters.)  See https://jira.sil.org/browse/BL-1160.
            using(var tempDestination = new TemporaryFolder("BDS_" + Guid.NewGuid()))
            {
                var tempDirectory = Path.Combine(tempDestination.FolderPath, bookFolderName);
                if(downloadProgress != null)
                    downloadProgress.Invoke((Action) (() => { downloadProgress.ProgressRangeMaximum = totalItems; }));
                int booksDownloaded = 0;
                using(var transferUtility = new TransferUtility(_amazonS3))
                {
                    for(int i = 0; i < matching.S3Objects.Count; ++i)
                    {
                        var objKey = matching.S3Objects[i].Key;
                        if(AvoidThisFile(objKey))
                            continue;
                        // Removing the book's prefix from the object key, then using the remainder of the key
                        // in the filepath allows for nested subdirectories.
                        var filepath = objKey.Substring(storageKeyOfBookFolder.Length + 1);
                        // Download this file then bump progress.
                        var req = new TransferUtilityDownloadRequest()
                        {
                            BucketName = bucketName,
                            Key = objKey,
                            FilePath = Path.Combine(tempDestination.FolderPath, filepath)
                        };
                        transferUtility.Download(req);
                        ++booksDownloaded;
                        if(downloadProgress != null)
                            downloadProgress.Invoke((Action) (() => { downloadProgress.Progress = booksDownloaded; }));
                    }
                    var destinationPath = Path.Combine(pathToDestinationParentDirectory, bookFolderName);

                    //clear out anything existing on our target
                    var didDelete = false;
                    if(Directory.Exists(destinationPath))
                    {
                        try
                        {
                            SIL.IO.RobustIO.DeleteDirectory(destinationPath, true);
                            didDelete = true;
                        }
                        catch(IOException)
                        {
                            // can't delete it...see if we can copy into it.
                        }
                    }

                    //if we're on the same volume, we can just move it. Else copy it.
                    // It's important that books appear as nearly complete as possible, because a file watcher will very soon add the new
                    // book to the list of downloaded books the user can make new ones from, once it appears in the target directory.
                    bool done = false;
                    if(didDelete && PathUtilities.PathsAreOnSameVolume(pathToDestinationParentDirectory, tempDirectory))
                    {
                        try
                        {
                            SIL.IO.RobustIO.MoveDirectory(tempDirectory, destinationPath);
                            done = true;
                        }
                        catch(IOException)
                        {
                            // If moving didn't work we'll just try copying
                        }
                        catch(UnauthorizedAccessException)
                        {
                        }
                    }
                    if(!done)
                        done = CopyDirectory(tempDirectory, destinationPath);
                    if(!done)
                    {
                        var msg = LocalizationManager.GetString("Download.CopyFailed",
                            "Bloom downloaded the book but had problems making it available in Bloom. Please restart your computer and try again. If you get this message again, please click the 'Details' button and report the problem to the Bloom developers");
                        // The exception doesn't add much useful information but it triggers a version of the dialog with a Details button
                        // that leads to the yellow box and an easy way to send the report.
                        ErrorReport.NotifyUserOfProblem(new ApplicationException("File Copy problem"), msg);
                    }
                    return destinationPath;
                }
            }
        }
        internal void HandleBloomBookOrder(string order)
        {
            _downloadRequest = order;
            using (var progressDialog = new ProgressDialog())
            {
                _progressDialog                     = new ProgressDialogWrapper(progressDialog);
                progressDialog.CanCancel            = true;
                progressDialog.Overview             = LocalizationManager.GetString("Download.DownloadingDialogTitle", "Downloading book");
                progressDialog.ProgressRangeMaximum = 14;                 // a somewhat minimal file count. We will fine-tune it when we know.
                if (IsUrlOrder(order))
                {
                    var link = new BloomLinkArgs(order);
                    progressDialog.StatusText = link.Title;
                }
                else
                {
                    progressDialog.StatusText = Path.GetFileNameWithoutExtension(order);
                }

                // We must do the download in a background thread, even though the whole process is doing nothing else,
                // so we can invoke stuff on the main thread to (e.g.) update the progress bar.
                BackgroundWorker worker = new BackgroundWorker();
                worker.DoWork += OnDoDownload;
                progressDialog.BackgroundWorker = worker;
                progressDialog.ShowDialog();                 // hidden automatically when task completes
                if (progressDialog.ProgressStateResult != null &&
                    progressDialog.ProgressStateResult.ExceptionThatWasEncountered != null)
                {
                    SIL.Reporting.ErrorReport.ReportFatalException(
                        progressDialog.ProgressStateResult.ExceptionThatWasEncountered);
                }
            }
        }
 public void Bind(IProgressDialog dialog)
 {
     dialog.CurrentTaskInfo     = string.Empty;
     dialog.CurrentTaskProgress = 0;
     dialog.UserCancellable     = true;
     UpdateLocalization(dialog);
 }
Exemple #5
0
        /// <summary>
        /// Displays the progress dialog and starts the timer.
        /// </summary>
        /// <param name="parent">The dialog box's parent window.</param>
        public void Show(IWin32Window parent)
        {
            // Throw an exception if we are already running
            if (_state != ProgressDialogState.Stopped)
            {
                throw new InvalidOperationException("Timer is already running.");
            }

            // Get parent window handle
            if (parent == null)
            {
                parent = Form.ActiveForm;
            }
            IntPtr handle = (parent == null) ? IntPtr.Zero : parent.Handle;

            // Setup the window
            _nativeProgressDialog = (IProgressDialog)Activator.CreateInstance(_progressDialogType);
            _nativeProgressDialog.SetTitle(_title);
            _nativeProgressDialog.SetCancelMsg(_cancelMessage, null);
            if (ShowTimeRemaining)
            {
                _nativeProgressDialog.SetLine(3, "Estimating time remaining...", false, IntPtr.Zero);
            }

            // Create Window
            _nativeProgressDialog.StartProgressDialog(handle, null, _flags, IntPtr.Zero);

            _value = 0;
            _state = ProgressDialogState.Running;
            _nativeProgressDialog.Timer(PDTIMER.Reset, null);
        }
        private async void _hubConnection_StateChanged(StateChange obj)
        {
            if (obj.NewState == ConnectionState.Connected)
            {
                _dialog?.Dispose();
                _dialog = null;

                if (_autoLoginUser != null)
                {
                    await CreateOrUpdateAsync(_autoLoginUser);

                    _autoLoginUser = null;

                    if (Settings.LoginUser != null)
                    {
                        await NavigationService.Navigate <MenuViewModel>();
                    }
                }
            }
            else
            {
                if (_viewAppeared)
                {
                    _dialog?.Dispose();
                    _dialog = UserDialogs.Instance.Loading("接続中");
                }
            }
        }
 public virtual void ShowLoading(string title, MaskType?maskType)
 {
     if (this.loading == null)
     {
         this.loading = this.Loading(title, null, null, true, maskType);
     }
 }
Exemple #8
0
        async void OnRecord(object sender, EventArgs e)
        {
            using (_progress = UserDialogs.Instance.Loading("Verbinden...", maskType: MaskType.Clear))
            {
                try
                {
                    var now  = DateTime.Now;
                    var name = $"Trip_{now.Year}{now.Month:00}{now.Day:00}_{now.Hour:00}.{now.Minute:00}.{now.Second:00}.{now.Millisecond:0000}";
                    _logger = new LoggerFile(Path.Combine(Folder.Personal, $"{name}.log"))
                    {
                        Overwrite = false
                    };

                    if (await Connect() == false)
                    {
                        await DisplayAlert("CarAssist", "Es konnte keine Verbindung aufgebaut werden. Überprüfen Sie unter Einstellungen die Bluetooth- oder WLAN-Verbindungsdaten", "Ok");

                        return;
                    }
                    TripViewModel.IsRecording = true;
                    Start();
                }
                catch (ObdException ex)
                {
                    await DisplayAlert("CarAssist", ex.Message, "Ok");

                    return;
                }
            }
        }
Exemple #9
0
        protected async override void OnAppearing()
        {
            if (IsBusy)
            {
                return;
            }

            IsBusy = true;
            ViewModel.ErrorMessage = "";
            base.OnAppearing();
            IProgressDialog progress = null;

            try
            {
                progress = UserDialogs.Instance.Loading(TranslateServices.GetResourceString(CommonConstants.DialogLoading), maskType: MaskType.Clear);
                progress.Show();

                InitContributionType();
                await BindContributionAreas();

                BindingSelectors();
            }
            catch (Exception ex)
            {
                await UserDialogs.Instance.AlertAsync(string.Format(CommonConstants.DialogDescriptionForCheckNetworkFormat, ex.Message), TranslateServices.GetResourceString(CommonConstants.DialogOK));
            }
            finally
            {
                progress?.Hide();
                IsBusy = false;
            }
        }
        /// <summary>
        /// Shows the progress.
        /// </summary>
        /// <param name="visible">If set to <c>true</c> visible.</param>
        /// <param name="title">Title.</param>
        /// <param name="subtitle">Subtitle.</param>
        public void UpdateProgress(bool visible, string title = "", string subtitle = "")
        {
            if (_progressDialog == null && visible == false)
            {
                return;
            }

            if (_progressDialog == null)
            {
                _progressDialog = UserDialogs.Instance.Progress();
                _progressDialog.IsDeterministic = false;
            }

            _progressDialog.Title = title ?? string.Empty;

            if (visible)
            {
                if (!_progressDialog.IsShowing)
                {
                    _progressDialog.Show();
                }
            }
            else
            {
                if (_progressDialog.IsShowing)
                {
                    _progressDialog.Hide();
                }

                _progressDialog = null;
            }
        }
        public async void OnCommUserSelectedItemChanged()
        {
            if (CommUserSelectedItem != null)
            {
                using (IProgressDialog fooIProgressDialog = UserDialogs.Instance.Loading($"請稍後,更新資料中...", null, null, true, MaskType.Black))
                {
                    var fooResult = await commUserGroupItemsManager.PostAsync(new CommUserGroupItemRequestDTO()
                    {
                        Id = CommUserSelectedItem.Id
                    });

                    CommUserItemItemsSource.Clear();
                    foreach (var item in commUserGroupItemsManager.Items)
                    {
                        CommUserGroupItemModel commUserGroupItemModel = new CommUserGroupItemModel()
                        {
                            Id     = item.Id,
                            Email  = item.Email,
                            Name   = item.Name,
                            Mobile = item.Mobile,
                            Phone  = item.Phone,
                        };
                        CommUserItemItemsSource.Add(commUserGroupItemModel);
                    }
                }
            }
        }
        public HRESULT CreatePlaylist(IShellItemArray psia)
        {
            _ppd = new IProgressDialog();
            _ppd.StartProgressDialog(dwFlags: PROGDLG.PROGDLG_AUTOTIME);
            _ppd.SetTitle("Building Playlist");
            _ppd.SetLine(1, "Finding music files...", false);

            var pnsw = new INamespaceWalk();

            pnsw.Walk(psia, NAMESPACEWALKFLAG.NSWF_TRAVERSE_STREAM_JUNCTIONS | NAMESPACEWALKFLAG.NSWF_DONT_ACCUMULATE_RESULT, 4, this);
            _fCountingFiles = false;
            _ppd.SetLine(1, "Adding files...", false);
            _pstm = _GetPlaylistStream();
            var hr = WriteHeader();

            if (hr.Succeeded)
            {
                pnsw.Walk(psia, NAMESPACEWALKFLAG.NSWF_TRAVERSE_STREAM_JUNCTIONS | NAMESPACEWALKFLAG.NSWF_DONT_ACCUMULATE_RESULT | NAMESPACEWALKFLAG.NSWF_SHOW_PROGRESS, 4, this);
                hr = WriteFooter();
            }

            _pstm.Commit(0);

            if (hr.Succeeded)
            {
                var psiCreated = _GetPlaylistItem <IShellItem>();
                hr = OpenFolderAndSelectItem(psiCreated);
            }
            _ppd.StopProgressDialog();
            _ExitMessageLoop();
            return(0);
        }
Exemple #13
0
        private void SetupProgressDialog(IKp2aApp app)
        {
            string currentMessage    = "Initializing...";
            string currentSubmessage = "";

            if (_progressDialogStatusLogger != null)
            {
                currentMessage    = _progressDialogStatusLogger.Message;
                currentSubmessage = _progressDialogStatusLogger.SubMessage;
            }

            if (_progressDialog != null)
            {
                var pd = _progressDialog;
                app.UiThreadHandler.Post(() =>
                {
                    pd.Dismiss();
                });
            }

            // Show process dialog
            _progressDialog = app.CreateProgressDialog(_activeActivity);
            _progressDialog.SetTitle(_app.GetResourceString(UiStringKey.progress_title));
            _progressDialogStatusLogger = new ProgressDialogStatusLogger(_app, _handler, _progressDialog);
            _progressDialogStatusLogger.UpdateMessage(currentMessage);
            _progressDialogStatusLogger.UpdateSubMessage(currentSubmessage);
        }
Exemple #14
0
        public async Task <bool> VotarAzure()
        {
            using (IProgressDialog progress = UserDialogs.Instance.Loading("Guardando Voto..", null, null, true, MaskType.Black))
            {
                var  client  = new RestClient("https://eleccionescolombia.azurewebsites.net/api/HttpTriggerCSharp1?code=/rADc6yrO7F2N6lm/C4Ztnz22u0naBlL/K5pOfPgYZJ4avN5c5DEfQ==");
                var  request = new RestRequest("", Method.POST);
                Voto voto    = new Voto();
                voto.llave   = CrossDeviceInfo.Current.Id;
                voto.id      = CandidatoSeleccionado.IdCandidato;
                voto.usuario = CrossDeviceInfo.Current.Id;
                request.AddJsonBody(voto);
                var response = await client.ExecutePostTaskAsync(request);

                if (response.ResponseStatus == ResponseStatus.Completed)
                {
                    if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError)
                    {
                        return(false);
                    }

                    return(true);
                }
                else
                {
                    return(false);
                }
            }
        }
Exemple #15
0
        /// <summary>
        /// Loads the data.
        /// </summary>
        public async void LoadData(int count = 7)
        {
            ProgressDialogConfig config = new ProgressDialogConfig()
                                          .SetTitle("Analyzing results")
                                          .SetIsDeterministic(false)
                                          .SetMaskType(MaskType.Black);

            using (IProgressDialog progress = UserDialogs.Instance.Progress(config))
            {
                await Task.Delay(300);

                sleepViews     = new SleepDiagramView[count];
                commentStrings = new string[count];
                dateStrings    = new string[count];

                for (int i = 0; i < count; i++)
                {
                    dateStrings[i] = DateTime.Now.AddDays(-i).ToString("yyyyMMdd");

                    sleepViews[i] = await GenerateSleepView(dateStrings[i]);

                    commentStrings[i] = "";
                }

                DrawFigures();
            }
        }
        protected async override void OnAppearing()
        {
            if (IsBusy)
            {
                return;
            }

            IsBusy = true;
            ViewModel.ErrorMessage = "";
            base.OnAppearing();
            IProgressDialog progress = null;

            try
            {
                progress = UserDialogs.Instance.Loading("Loading...", maskType: MaskType.Clear);
                progress.Show();

                InitContributionType();
                await BindContributionAreas();

                BindingSelectors();
            }
            catch
            {
            }
            finally
            {
                progress?.Hide();
                IsBusy = false;
            }
        }
Exemple #17
0
 public async Task ShowLoadingAsync(string message)
 {
     if (_Progress == null)
     {
         _Progress = (_Configuration.CustomLoadingDialog != null) ? _Configuration.CustomLoadingDialog(message) : Loading(message, null, null, true);
     }
 }
Exemple #18
0
        async Task ExecuteTapQueueMessageCommandAsync(CloudQueueMessage queueMessage)
        {
            if (queueMessage == null)
            {
                return;
            }

            MessagingService.Current.Subscribe <MessageArgsDeleteQueueMessage>(MessageKeys.DeleteQueueMessage, async(m, argsDeleteQueueMessage) =>
            {
                Navigation.PopAsync();
                IProgressDialog deletingDialog = UserDialogs.Loading("Deleting Queue Message");
                deletingDialog.Show();
                try
                {
                    var message = QueueMessages.Where(qm => qm.Id == argsDeleteQueueMessage.QueueId).FirstOrDefault();

                    if (message == null)
                    {
                        return;
                    }

                    await Queue.BaseQueue.DeleteMessageAsync(message);
                    App.Logger.Track(AppEvent.DeleteQueueMessage.ToString());

                    QueueMessages.Remove(message);
                    QueueMessageCount--;


                    SortQueueMessages();
                }
                catch (Exception ex)
                {
                    Logger.Report(ex, "Method", "HandleMessageArgsDeleteQueueMessage");
                    MessagingService.Current.SendMessage(MessageKeys.Error, ex);
                }
                finally
                {
                    if (deletingDialog != null)
                    {
                        if (deletingDialog.IsShowing)
                        {
                            deletingDialog.Hide();
                        }
                        deletingDialog.Dispose();
                    }
                }
            });

            try
            {
                var queueMessageDetailsPage = new QueueMessageDetailsPage(queueMessage, queue);

                App.Logger.TrackPage(AppPage.QueueMessageDetails.ToString());
                await NavigationService.PushAsync(Navigation, queueMessageDetailsPage);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Ex: " + ex.Message);
            }
        }
		/// <summary>
		/// Shows the progress.
		/// </summary>
		/// <param name="visible">If set to <c>true</c> visible.</param>
		/// <param name="title">Title.</param>
		/// <param name="subtitle">Subtitle.</param>
		public void UpdateProgress(bool visible, string title = "", string subtitle = "")
		{
			if (_progressDialog == null && visible == false)
				return;

			if (_progressDialog == null)
			{
				_progressDialog = UserDialogs.Instance.Progress();
				_progressDialog.IsDeterministic = false;
			}

			_progressDialog.Title = title ?? string.Empty;

			if (visible)
			{
				if(!_progressDialog.IsShowing)
					_progressDialog.Show();
			}
			else
			{
				if(_progressDialog.IsShowing)
					_progressDialog.Hide();

				_progressDialog = null;
			}
		}
Exemple #20
0
        private async void Button_OnClicked(object sender, EventArgs e)
        {
            using (IProgressDialog progress = UserDialogs.Instance.Progress("Progress", null, null, true, MaskType.Black))
            {
                for (int i = 0; i < 100; i++)
                {
                    progress.PercentComplete = i;
                    await Task.Delay(60);
                }
            }

            using (UserDialogs.Instance.Loading("Loading", null, null, true, MaskType.Black))
            {
                await Task.Delay(5000);
            }

            UserDialogs.Instance.ShowError("ShowError (Obselete)", 3000); //Use ShowImage instead

            await Task.Delay(4000);

            UserDialogs.Instance.ShowSuccess("ShowSuccess (Obselete)", 3000); //Use ShowImage instead

            await Task.Delay(4000);

            Toast();

            await Task.Delay(5000);

            await UserDialogs.Instance.DatePromptAsync("DatePrompt", DateTime.Now);
        }
Exemple #21
0
        private void openDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (backgroundWorkerProcess.IsBusy)
            {
                MessageBox.Show("Please wait until the current process is finished and try again.", Application.ProductName);
                return;
            }

            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();

            folderBrowserDialog.SelectedPath = !String.IsNullOrEmpty(Common.Settings.Default.InitialDirectory) && Directory.Exists(Common.Settings.Default.InitialDirectory) ? Common.Settings.Default.InitialDirectory : Directory.GetDirectoryRoot(Directory.GetCurrentDirectory());

            Process.log?.WriteLine("\nOpen Directory");

            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                objectListView.Items.Clear();
                toolStripStatusLabel.Text = "";

                Common.Settings.Default.InitialDirectory = folderBrowserDialog.SelectedPath;
                Common.Settings.Default.Save();

                progressDialog = (IProgressDialog) new ProgressDialog();
                progressDialog.StartProgressDialog(Handle, String.Format("Opening files from directory {0}", folderBrowserDialog.SelectedPath));

                backgroundWorkerProcess.RunWorkerAsync((Worker.Directory, folderBrowserDialog.SelectedPath));
            }
        }
Exemple #22
0
 public ProgressDialog()
     : base()
 {
     coclassObject = new Interop.ProgressDialog();
     instance      = (IProgressDialog)coclassObject;
     Reset();
 }
Exemple #23
0
        private void updateTitleKeysToolStripMenuItem_Click(object sender, EventArgs e)
        {
            progressDialog = (IProgressDialog) new ProgressDialog();
            progressDialog.StartProgressDialog(Handle, "Downloading title keys");

            progressDialog.SetLine(2, String.Format("Downloading from {0}", Common.TITLE_KEYS_URI), true, IntPtr.Zero);

            int count = Process.keyset?.TitleKeys?.Count ?? 0;

            if (Process.updateTitleKeys())
            {
                Process.log?.WriteLine("\nFound {0} updated title keys", (Process.keyset?.TitleKeys?.Count ?? 0) - count);

                progressDialog.StopProgressDialog();
                Activate();

                MessageBox.Show(String.Format("Found {0} updated title keys", (Process.keyset?.TitleKeys?.Count ?? 0) - count), Application.ProductName);
            }
            else
            {
                progressDialog.StopProgressDialog();
                Activate();

                MessageBox.Show("Failed to download title keys", Application.ProductName);
            }
        }
Exemple #24
0
        public static IProgressDialog CreateProgressDialog(IDialogHost dialogHost, DialogMode dialogMode, Dispatcher dispatcher)
        {
            IProgressDialog dialog = null;

            dispatcher.Invoke(new Action(() => dialog = new WaitProgressDialog(dialogHost, dialogMode, false, dispatcher)), DispatcherPriority.DataBind);
            return(dialog);
        }
Exemple #25
0
        private void openFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (backgroundWorkerProcess.IsBusy)
            {
                MessageBox.Show("Please wait until the current process is finished and try again.", Application.ProductName);
                return;
            }

            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Title  = "Open NX Game Files";
            openFileDialog.Filter = String.Format("NX Game Files (*.xci;*.nsp;{0}*.nro)|*.xci;*.nsp;{0}*.nro|Gamecard Files (*.xci{1})|*.xci{1}|Package Files (*.nsp{2})|*.nsp{2}|Homebrew Files (*.nro)|*.nro|All Files (*.*)|*.*",
                                                  Common.Settings.Default.NszExtension ? "*.xcz;*.nsz;" : "", Common.Settings.Default.NszExtension ? ";*.xcz" : "", Common.Settings.Default.NszExtension ? ";*.nsz" : "");
            openFileDialog.Multiselect      = true;
            openFileDialog.InitialDirectory = !String.IsNullOrEmpty(Common.Settings.Default.InitialDirectory) && Directory.Exists(Common.Settings.Default.InitialDirectory) ? Common.Settings.Default.InitialDirectory : Directory.GetDirectoryRoot(Directory.GetCurrentDirectory());

            Process.log?.WriteLine("\nOpen File");

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                objectListView.Items.Clear();
                toolStripStatusLabel.Text = "";

                Common.Settings.Default.InitialDirectory = Path.GetDirectoryName(openFileDialog.FileNames.First());
                Common.Settings.Default.Save();

                progressDialog = (IProgressDialog) new ProgressDialog();
                progressDialog.StartProgressDialog(Handle, "Opening files");

                backgroundWorkerProcess.RunWorkerAsync((Worker.File, openFileDialog.FileNames));
            }
        }
Exemple #26
0
 public ProgressDialog()
     : base()
 {
     coclassObject = new Interop.ProgressDialog();
     instance = (IProgressDialog)coclassObject;
     Reset();
 }
        public LoginPageViewModel(INavigationService navigationService, IPageDialogService dialogService,
                                  LoginManager loginManager, SystemStatusManager systemStatusManager,
                                  AppStatus appStatus, RecordCacheHelper recordCacheHelper)
        {
            this.navigationService   = navigationService;
            this.dialogService       = dialogService;
            this.loginManager        = loginManager;
            this.systemStatusManager = systemStatusManager;
            this.appStatus           = appStatus;
            this.recordCacheHelper   = recordCacheHelper;
            LoginCommand             = new DelegateCommand(async() =>
            {
                using (IProgressDialog fooIProgressDialog = UserDialogs.Instance.Loading($"請稍後,更新資料中...", null, null, true, MaskType.Black))
                {
                    LoginRequestDTO loginRequestDTO = new LoginRequestDTO()
                    {
                        Account  = Account,
                        Password = Password,
                    };
                    var fooResult = await LoginUpdateTokenHelper.UserLoginAsync(dialogService, loginManager, systemStatusManager,
                                                                                loginRequestDTO, appStatus);
                    if (fooResult == false)
                    {
                        return;
                    }
                    await recordCacheHelper.RefreshAsync(fooIProgressDialog);
                }

                //await dialogService.DisplayAlertAsync("Info", "登入成功", "OK");
                await navigationService.NavigateAsync("/MDPage/NaviPage/HomePage");
            });
        }
Exemple #28
0
        protected override async void OnAppearing()
        {
            try
            {
                _busy = UserDialogs.Instance.Loading(MessageHelper.Loading);
                var service = DependencyService.Get <IDueService>();
                var result  = await Task.Run(() => service.GetDuereceipts(_houseId));

                var reciptViewModel = result.Receipts.Select(i => new ReceiptsViewModel
                {
                    Id          = i.Id,
                    Date        = i.Date,
                    Description = i.Description,
                    Advance     = i.Advance ? "ok.png" : "wrong.png",
                    Source      = i.Source,
                    Amount      = i.Amount,
                });
                AccountStatementView.ItemsSource = reciptViewModel;
                StackVisibility.IsVisible        = true;
            }
            catch (Exception ex)
            {
                if (!CrossConnectivity.Current.IsConnected)
                {
                    UserDialogs.Instance.ErrorToast(MessageHelper.NoInternet);
                }
            }
            finally
            {
                _busy.Hide();
            }
            base.OnAppearing();
        }
Exemple #29
0
        /// <summary>
        /// Entry point of connection thread
        /// </summary>
        private async Task ConnectThreadRunAsync(PairedFoxDTO foxToConnect)
        {
            Exception lastException = null;

            using (IProgressDialog progress = UserDialogs.Instance.Progress("Connecting...", null, null, true, MaskType.Clear))
            {
                for (var attempt = 0; attempt < ConnectionAttemptsCount; attempt++)
                {
                    progress.PercentComplete = (int)Math.Round(100 * attempt / (double)ConnectionAttemptsCount);

                    try
                    {
                        await _bluetoothCommunicator.ConnectAsync(foxToConnect);

                        // We survived till here, so connection is estabilished
                        lastException = null;
                        break;
                    }
                    catch (Exception ex)
                    {
                        lastException = ex;
                    }
                }
            }

            if (lastException != null)
            {
                _onConnectionFailed(lastException);
                await _userNotifier.ShowErrorMessageAsync("Failed to connect!", $"Reason: { lastException.Message }");
            }
        }
Exemple #30
0
        public void ShowDialog(params ProgressDialogBehavior[] flags)
        {
            if (_progressDialog != null)
            {
                return;
            }

            _progressDialog = new Win32ProgressDialog() as IProgressDialog;

            _progressDialog.SetTitle(_title);
            _progressDialog.SetCancelMsg(_cancelMessage, null);
            _progressDialog.SetLine(1, _line1, false, IntPtr.Zero);
            _progressDialog.SetLine(2, _line2, false, IntPtr.Zero);
            _progressDialog.SetLine(3, _line3, false, IntPtr.Zero);

            ProgressDialogBehavior dialogFlags = ProgressDialogBehavior.Normal;

            if (flags.Length != 0)
            {
                dialogFlags = flags[0];
                for (var i = 1; i < flags.Length; i++)
                {
                    dialogFlags = dialogFlags | flags[i];
                }
            }

            _progressDialog.StartProgressDialog(_parentHandle, null, dialogFlags, IntPtr.Zero);
        }
Exemple #31
0
        private async void Button_Clicked(object sender, EventArgs e)
        {
            Random r = new Random();

            using (IProgressDialog progress = UserDialogs.Instance.Progress("Envoi de l'incident", null, null, true, MaskType.Black))
            {
                for (int i = 0; i < 100; i++)
                {
                    progress.PercentComplete = i;
                    await Task.Delay(r.Next(30, 50));
                }
            }

            //using (UserDialogs.Instance.Loading("Loading", null, null, true, MaskType.Black))
            //{
            //    await Task.Delay(5000);
            //}
            var error = r.Next(0, 2);

            if (error == 0)
            {
                UserDialogs.Instance.HideLoading();

                UserDialogs.Instance.ShowError("Erreur dans l'envoi de l'incident", 3000); //Use ShowImage instead
            }
            else
            {
                UserDialogs.Instance.HideLoading();

                UserDialogs.Instance.ShowSuccess("Incident envoyé !", 3000); //Use ShowImage instead
            }
        }
        async Task ExecuteTapFileShareCommandAsync(ASECloudFileShare fileShare)
        {
            if (fileShare == null)
            {
                return;
            }


            MessagingService.Current.Subscribe <MessageArgsDeleteFileShare>(MessageKeys.DeleteFileShare, async(m, argsDeleteFileShare) =>
            {
                Navigation.PopAsync();
                IProgressDialog deletingDialog = UserDialogs.Loading("Deleting FileShare");
                deletingDialog.Show();
                try
                {
                    var aseFileShare = FileShares.Where(fs => fs.FileShareName == argsDeleteFileShare.FileShareName &&
                                                        fs.StorageAccountName == argsDeleteFileShare.StorageAccountName).FirstOrDefault();
                    if (aseFileShare == null)
                    {
                        return;
                    }

                    await aseFileShare.BaseFileShare.DeleteAsync();

                    App.Logger.Track(AppEvent.DeleteFileShare.ToString());

                    FileShares.Remove(aseFileShare);
                    SortFileShares();
                    var realm = App.GetRealm();
                    await realm.WriteAsync(temprealm =>
                    {
                        temprealm.Remove(temprealm.All <RealmCloudFileShare>()
                                         .Where(fs => fs.FileShareName == argsDeleteFileShare.FileShareName &&
                                                fs.StorageAccountName == argsDeleteFileShare.StorageAccountName).First());
                    });
                }
                catch (Exception ex)
                {
                    Logger.Report(ex, "Method", "HandleMessageArgsDeleteFileShare");
                    MessagingService.Current.SendMessage(MessageKeys.Error, ex);
                }
                finally
                {
                    if (deletingDialog != null)
                    {
                        if (deletingDialog.IsShowing)
                        {
                            deletingDialog.Hide();
                        }
                        deletingDialog.Dispose();
                    }
                }
            });

            var filesPage = new FilesPage(fileShare);

            App.Logger.TrackPage(AppPage.Files.ToString());
            await NavigationService.PushAsync(Navigation, filesPage);
        }
Exemple #33
0
 public virtual void HideLoading()
 {
     if (this.loading != null)
     {
         this.loading.Dispose();
         this.loading = null;
     }
 }
Exemple #34
0
 public void Close()
 {
     if (_ProgressDialog != null)
     {
         _ProgressDialog.StopProgressDialog();
         _ProgressDialog = null;
     }
 }
 protected void HideDialog(IProgressDialog dialog)
 {
     try
     {
         dialog.Hide();
     }
     catch (Exception)
     {
         //todo: needs to be refactored to catch correct exception.
         //not handled on purpose, can crash during app rotation
     }
 }
		public Add_Remote_Button ()
		{
			InitializeComponent ();

			waitRemoteDialog = UserDialogs.Instance.Loading("Press Remote...",null,null,false,MaskType.Gradient);

			MessagingCenter.Subscribe<Add_Remote_Button> (this, "remote_code_success", (sender) => {

				//waitRemoteDialog.Hide();
				UserDialogs.Instance.ShowSuccess ("Success!");

			});
		}
Exemple #37
0
        public ProgressTask(IKp2aApp app, Context ctx, RunnableOnFinish task)
        {
            _task = task;
            _handler = app.UiThreadHandler;
            _app = app;

            // Show process dialog
            _progressDialog = app.CreateProgressDialog(ctx);
            _progressDialog.SetTitle(_app.GetResourceString(UiStringKey.progress_title));
            _progressDialog.SetMessage("Initializing...");

            // Set code to run when this is finished
            _task.OnFinishToRun = new AfterTask(task.OnFinishToRun, _handler, _progressDialog);
            _task.SetStatusLogger(new ProgressDialogStatusLogger(_app, _handler, _progressDialog));
        }
Exemple #38
0
		async void OnLogin_Clicked(object sender, EventArgs args)
		{			
			loadingDialog = UserDialogs.Instance.Loading("Connecting...",null,null,false,MaskType.Gradient);

			if (String.IsNullOrEmpty(webSocketUrl.Text))
			{
				await DisplayAlert("Validation Error", "Server URL is required", "Re-try");
			}
			else 
			{
				//if(false){
				if (String.IsNullOrEmpty (username.Text) || String.IsNullOrEmpty (password.Text)) {
					await DisplayAlert ("Validation Error", "Username and Password are required", "Re-try");
				} else {
					await App.Database.Delete_RemoteData_Item ();
					await App.Database.Delete_All_Login_Username_Show_For_Del ();
					loadingDialog.Show ();

					//System.Threading.Tasks.Task.Run (() => 
					//{
							ws_client = new WebSocketClient ();
							ws_client.Opened += websocket_Opened;
							ws_client.Closed += websocket_Closed;
							ws_client.MessageReceived += websocket_MessageReceived;		
							//ws_client.AutoSendPongResponse = true;
					//});



					try 
					{
						Debug.WriteLine ("Websocket Opening.....");
						await ws_client.OpenAsync(webSocketUrl.Text);

					} catch (Exception ex) {
						Debug.WriteLine (ex.ToString());
						Debug.WriteLine ("OpenAsync Exception");
						UserDialogs.Instance.ShowError ("Can not Connect to Websocket Server");
					}
				}

			}


		}
Exemple #39
0
        public void Initialize(Toolbar toolToolBar,
		                        DrawingArea drawingArea,
		                        Window mainWindow,
		                        IProgressDialog progressDialog)
        {
            if (progressDialog == null)
                throw new ArgumentNullException ("progressDialog");

            tool_toolbar = toolToolBar;
            drawing_area = drawingArea;
            main_window = mainWindow;
            progress_dialog = progressDialog;
        }
Exemple #40
0
		public void InitializeProgessDialog (IProgressDialog progressDialog)
		{
			if (progressDialog == null)
				throw new ArgumentNullException ("progressDialog");

			progress_dialog = progressDialog;
		}
 /// <summary>
 /// Disposes the object and releases resources used
 /// </summary>
 public void Dispose()
 {
     if( this.m_disposed )
         return;
     // make sure the dialog is closed
     if( !this.m_dlgClosed )
         this.Stop();
     this.m_ipDialog = null;
     this.m_disposed = true;
 }
Exemple #42
0
        public static void Initialize(Toolbar toolToolBar,
		                               DrawingArea drawingArea,
		                               Window mainWindow,
		                               IProgressDialog progressDialog)
        {
            Chrome.Initialize (toolToolBar,
                               drawingArea,
                               mainWindow,
                               progressDialog);

            Actions.RegisterHandlers ();
        }
        public static void RefreshCharacters(IProgressDialog dialog)
        {
            string path;
            string apiKey;
            int userID;
            DataTable tempChars;
            CacheResult result;

            // this is where we're gonna put the characters while we query and read XML and stuff
            tempChars = m_characters.Clone();

            // progress
            if (dialog != null)
                dialog.Update("Refreshing character lists from API...", 0, Program.ApiKeys.Rows.Count);
            
            foreach (DataRow row in Program.ApiKeys.Rows)
            {
                // grab the account ID and key from the row
                userID = Convert.ToInt32(row["userID"]);
                apiKey = row["apiKey"].ToString();

                // query the API
                result = EveApiHelper.GetCharacters(userID, apiKey);
                if (result.State == CacheState.Uncached)
                {
                    MessageBox.Show("Failed to fetch characters for UserID " + userID.ToString() + result.Exception == null ? "" : "\n\n" + result.Exception.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    continue;
                }
                else
                {
                    path = result.Path;
                }

                // parse the XML
                using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read))
                {
                    XPathDocument doc = new XPathDocument(fs);
                    XPathNavigator nav = doc.CreateNavigator();
                    XPathNodeIterator iter;
                    DataRow charRow, existingRow;

                    iter = nav.Select("/eveapi/result/rowset/row");

                    while (iter.MoveNext())
                    {
                        // create the new row
                        charRow = tempChars.NewRow();
                        charRow["userID"] = userID;
                        charRow["name"] = iter.Current.SelectSingleNode("@name").Value;
                        charRow["characterID"] = iter.Current.SelectSingleNode("@characterID").ValueAsInt;
                        charRow["corporationName"] = iter.Current.SelectSingleNode("@corporationName").Value;
                        charRow["corporationID"] = iter.Current.SelectSingleNode("@corporationID").ValueAsInt;
                        charRow["queryCorp"] = true;

                        // try to find a matching row from the current characters table and keep that queryCorp value if we do
                        existingRow = m_characters.Rows.Find(charRow["characterID"]);
                        if (existingRow != null)
                            charRow["queryCorp"] = existingRow["queryCorp"];

                        // add the row to the temp table
                        tempChars.Rows.Add(charRow);
                    }
                }

                // progress
                if (dialog != null)
                    dialog.Advance();
            }

            // clear our character list and replace it
            m_characters.Rows.Clear();
            foreach (DataRow row in tempChars.Rows)
                m_characters.LoadDataRow(row.ItemArray, true);
        }
 public virtual void ShowLoading(string title) {
     if (this.loading == null) 
         this.loading = this.Loading(title, null, null, true);
 }
        /// <summary>
        /// Displays the progress dialog and starts the timer.
        /// </summary>
        /// <param name="parent">The dialog box's parent window.</param>
        public void Show(IWin32Window parent)
        {
            // Throw an exception if we are already running
            if (_state != ProgressDialogState.Stopped)
                throw new InvalidOperationException("Timer is already running.");

            // Get parent window handle
            if (parent == null) parent = Form.ActiveForm;
            IntPtr handle = (parent == null) ? IntPtr.Zero : parent.Handle;

            // Setup the window
            _nativeProgressDialog = (IProgressDialog)Activator.CreateInstance(_progressDialogType);
            _nativeProgressDialog.SetTitle(_title);
            _nativeProgressDialog.SetCancelMsg(_cancelMessage, null);
            if (ShowTimeRemaining)
                _nativeProgressDialog.SetLine(3, "Estimating time remaining...", false, IntPtr.Zero);

            // Create Window
            _nativeProgressDialog.StartProgressDialog(handle, null, _flags, IntPtr.Zero);

            _value = 0;
            _state = ProgressDialogState.Running;
            _nativeProgressDialog.Timer(PDTIMER.Reset, null);
        }
 public ProgressDialogStatusLogger(IKp2aApp app, Handler handler, IProgressDialog pd)
 {
     _app = app;
     _progressDialog = pd;
     _handler = handler;
 }
        private void RefreshAssets(IProgressDialog dialog)
        {
            Dictionary<string, string> assetFiles = new Dictionary<string, string>();
            List<string> outdatedNames = new List<string>();
            CacheResult result;

            // clear the assets
            m_assets = null;

            // make sure our character list is up to date
            dialog.Update("Refreshing character list...");
            Program.RefreshCharacters();
            dialog.Update(1, 3 + Program.Characters.Rows.Count);

            // fetch the asset XML
            dialog.Update("Querying API for asset lists...");
            foreach (DataRow row in Program.Characters.Rows)
            {
                int userID = Convert.ToInt32(row["userID"]);
                int characterID = Convert.ToInt32(row["characterID"]);
                int corporationID = Convert.ToInt32(row["corporationID"]);
                string apiKey = Program.ApiKeys.Rows.Find(userID)["apiKey"].ToString();
                string characterName = row["name"].ToString();
                string corporationName = row["corporationName"].ToString();
                bool queryCorp = Convert.ToBoolean(row["queryCorp"]);

                // fetch character assets
                if (!assetFiles.ContainsKey(characterName))
                {
                    result = EveApiHelper.GetCharacterAssetList(userID, apiKey, characterID);
                    switch (result.State)
                    {
                        case CacheState.Cached:
                            assetFiles[characterName] = result.Path;
                            break;
                        case CacheState.CachedOutOfDate:
                            assetFiles[characterName] = result.Path;
                            outdatedNames.Add(characterName);
                            break;
                        default:
                            throw new ApplicationException("Failed to retrieve asset data for " + characterName, result.Exception);
                    }
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("Odd, got two records for the same character name... " + characterName);
                }

                // fetch corporation assets?
                if (queryCorp && !assetFiles.ContainsKey(corporationName))
                {
                    // attempt the query
                    result = EveApiHelper.GetCorporationAssetList(userID, apiKey, characterID, corporationID);

                    // check whether we got an eve error about not being a director
                    if (result.Exception != null && result.Exception is EveApiException && ((EveApiException)result.Exception).ErrorCode == 209)
                    {
                        System.Diagnostics.Debug.WriteLine(characterName + " is not a Director or CEO of " + corporationName + ".");
                        row["queryCorp"] = false;
                    }
                    else
                    {
                        switch (result.State)
                        {
                            case CacheState.Cached:
                                assetFiles[corporationName] = result.Path;
                                break;
                            case CacheState.CachedOutOfDate:
                                assetFiles[corporationName] = result.Path;
                                outdatedNames.Add(corporationName);
                                break;
                            default:
                                throw new ApplicationException("Failed to retrieve asset data for " + corporationName, result.Exception);
                        }
                    }
                }

                // progress
                dialog.Advance();
            }

            // inform the user about any files that could not be refreshed
            if (outdatedNames.Count > 0)
            {
                StringBuilder message = new StringBuilder();

                // prepare the semi-friendly message
                message.Append("An error occurred while refreshing assets for the characters and/or\ncorporations listed below. Cached data will be used instead. Your assets might\nbe out of date.\n");
                foreach (string name in outdatedNames)
                {
                    message.Append("\n");
                    message.Append(name);
                }

                // prepare the code to be invoked
                MethodInvoker code = delegate()
                {
                    MessageBox.Show(this, message.ToString(), "Using Cached Assets", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                };

                // invoke it
                if (this.InvokeRequired)
                    this.Invoke(code);
                else
                    code();
            }

            // init the database
            dialog.Update("Initializing local asset database...");
            AssetCache.InitializeDB(true);
            dialog.Advance();

            // parse the files
            dialog.Update("Parsing asset XML...");
            foreach (string characterName in assetFiles.Keys)
            {
                string assetFile = assetFiles[characterName];
                AssetCache.ParseAssets(assetFile, characterName);
            }
            dialog.Advance();
        }
Exemple #48
0
        public static void Initialize(Toolbar toolToolBar,
		                               Label statusTextLabel,
		                               DrawingArea drawingArea,
		                               TreeView historyStack,
		                               Window mainWindow,
		                               IProgressDialog progressDialog,
		                               Viewport viewport)
        {
            Chrome = new ChromeManager ();
            Chrome.Initialize (toolToolBar,
                               statusTextLabel,
                               drawingArea,
                               historyStack,
                               mainWindow,
                               progressDialog);

            Palette = new PaletteManager ();

            Workspace.Initialize (viewport);

            Actions.RegisterHandlers ();
        }
Exemple #49
0
        /// <summary>
        /// Releases the RCW to the native IProgressDialog component.
        /// </summary>
        private void CleanUp()
        {
            if (_nativeProgressDialog != null)
            {
                if (_state != ProgressDialogState.Stopped)
                {
                    try
                    {
                        _nativeProgressDialog.StopProgressDialog();
                    }
                    catch { }
                }

                Marshal.FinalReleaseComObject(_nativeProgressDialog);
                _nativeProgressDialog = null;
            }

            _state = ProgressDialogState.Stopped;
        }
Exemple #50
0
        /// <summary>
        /// Displays the progress dialog and starts the timer.
        /// </summary>
        /// <param name="parent">The dialog box's parent window.</param>
        public void Show(IWin32Window parent)
        {
            if (_state != ProgressDialogState.Stopped)
                throw new InvalidOperationException("Timer is already running.");

            if (_parentForm == null)
                _parentForm = Form.ActiveForm;

            IntPtr handle = parent?.Handle ?? IntPtr.Zero;

            //_nativeProgressDialog = (IProgressDialog)Activator.CreateInstance(_progressDialogType);
            _nativeProgressDialog = (IProgressDialog) new ProgressDialogImpl();
            _nativeProgressDialog.SetTitle(_title);
            _nativeProgressDialog.SetCancelMsg(_cancelMessage, null);
            if (ShowTimeRemaining)
                _nativeProgressDialog.SetLine(3, "Estimating time remaining...", false, IntPtr.Zero);

            _nativeProgressDialog.StartProgressDialog(handle, null, _flags, IntPtr.Zero);

            _value = 0;
            _state = ProgressDialogState.Running;
            _nativeProgressDialog.Timer(PDTIMER.Reset, null);
            _statePollingTimer.Change(TimeSpan.FromMilliseconds(250), TimeSpan.FromMilliseconds(250));
        }
 public virtual void HideLoading()
 {
     this.loading?.Dispose();
     this.loading = null;
 }
        private void UpdateAssetTable(IProgressDialog dialog)
        {
            // update dialog
            dialog.Update("Querying asset database...");

            // yay
            m_assets = AssetCache.GetAssetTable(m_clauses);
            m_assets.DefaultView.Sort = "typeName ASC";
        }
Exemple #53
0
 public Win32ProgressDialog()
 {
     _dialog = (IProgressDialog)new ProgressDialog();
 }
 /// <summary>
 /// .ctor
 /// </summary>
 /// <param name="hWnd">Owner's handle</param>
 public WinProgressDialog( IntPtr hWnd )
 {
     this.m_hwnd = hWnd;
     //	IProgressDialog * ppd;
     //	CoCreateInstance(CLSID_ProgressDialog, NULL, CLSCTX_INPROC_SERVER, IID_IProgressDialog, (void **)&ppd);
     ProgressDialog pDialog	= new ProgressDialog();
     this.m_ipDialog			= (IProgressDialog) pDialog;
 }
		async void OnDelete(object sender, EventArgs e)
		{
			
			var mi = ((MenuItem)sender);
			var remoteData = (RemoteData)mi.BindingContext;

			var answer = await DisplayAlert ("Confirm?", "Would you like to delete " + remoteData.remote_button_name, "Yes", "No");

			if (answer.Equals (true)) {
				
				waitRemoteDialog = UserDialogs.Instance.Loading("Deleteting...",null,null,false,MaskType.Gradient);
				waitRemoteDialog.Show ();

				remoteData.remote_button_name = remoteData.remote_button_name;
				remoteData.node_command = "delete_button_remote";
				string jsonCommandaddRemoteButton = JsonConvert.SerializeObject(remoteData, Formatting.Indented);
				System.Diagnostics.Debug.WriteLine ("{0}",jsonCommandaddRemoteButton);
				await LoginPage.ws_client.SendAsync (jsonCommandaddRemoteButton);

			} else {

			}
		}
        /// <summary>
        /// url is typically something like https://s3.amazonaws.com/BloomLibraryBooks/[email protected]/0a2745dd-ca98-47ea-8ba4-2cabc67022e
        /// It is harmless if there are more elements in it (e.g. address to a particular file in the folder)
        /// Note: if you copy the url from part of the link to a file in the folder from AWS,
        /// you typically need to change %40 to @ in the uploader's email.
        /// </summary>
        /// <param name="url"></param>
        /// <param name="destRoot"></param>
        internal string HandleDownloadWithoutProgress(string url, string destRoot)
        {
            _progressDialog = new ConsoleProgress();
            if (!url.StartsWith(BloomS3UrlPrefix))
            {
                Console.WriteLine("Url unexpectedly does not start with https://s3.amazonaws.com/");
                return "";
            }
            var bookOrder = url.Substring(BloomS3UrlPrefix.Length);
            var index = bookOrder.IndexOf('/');
            var bucket = bookOrder.Substring(0, index);
            var folder = bookOrder.Substring(index + 1);

            return DownloadBook(bucket, folder, destRoot);
        }
Exemple #57
0
        public void Initialize(Toolbar toolToolBar,
		                        Label statusBarText,
		                        DrawingArea drawingArea,
		                        TreeView historyStack,
		                        Window mainWindow,
		                        IProgressDialog progressDialog)
        {
            if (progressDialog == null)
                throw new ArgumentNullException ("progressDialog");

            tool_toolbar = toolToolBar;
            drawing_area = drawingArea;
            main_window = mainWindow;
            progress_dialog = progressDialog;
        }
 private void miHideItems_Click(object sender, RoutedEventArgs e)
 {
     ShellObjectCollection SelItems = Explorer.SelectedItems;
     pd = new IProgressDialog(this.Handle);
     pd.Title = "Applying attributes";
     pd.CancelMessage = "Please wait while the operation is cancelled";
     pd.Maximum = 100;
     pd.Value = 0;
     pd.Line1 = "Applying attributes to:";
     pd.Line3 = "Calculating Time Remaining...";
     pd.ShowDialog(IProgressDialog.PROGDLG.Normal, IProgressDialog.PROGDLG.AutoTime, IProgressDialog.PROGDLG.NoMinimize);
     Thread hthread = new Thread(new ParameterizedThreadStart(DoHideShowWithChilds));
     hthread.Start(SelItems);
 }
        internal void HandleBloomBookOrder(string order)
        {
            _downloadRequest = order;
            using (var progressDialog = new ProgressDialog())
            {
                _progressDialog = new ProgressDialogWrapper(progressDialog);
                progressDialog.CanCancel = false; // one day we may allow this...
                progressDialog.Overview = LocalizationManager.GetString("Download.DownloadingDialogTitle", "Downloading book");
                progressDialog.ProgressRangeMaximum = 14; // a somewhat minimal file count. We will fine-tune it when we know.
                if (IsUrlOrder(order))
                {
                    var link = new BloomLinkArgs(order);
                    progressDialog.StatusText = link.Title;
                }
                else
                {
                    progressDialog.StatusText = Path.GetFileNameWithoutExtension(order);
                }

                // We must do the download in a background thread, even though the whole process is doing nothing else,
                // so we can invoke stuff on the main thread to (e.g.) update the progress bar.
                BackgroundWorker worker = new BackgroundWorker();
                worker.DoWork += OnDoDownload;
                progressDialog.BackgroundWorker = worker;
                //dlg.CancelRequested += new EventHandler(OnCancelRequested);
                progressDialog.ShowDialog(); // hidden automatically when task completes
                if (progressDialog.ProgressStateResult != null &&
                    progressDialog.ProgressStateResult.ExceptionThatWasEncountered != null)
                {
                    SIL.Reporting.ErrorReport.ReportFatalException(
                        progressDialog.ProgressStateResult.ExceptionThatWasEncountered);
                }
            }
        }
Exemple #60
-1
		async void OnRename(object sender, EventArgs e)
		{
			var mi = ((MenuItem)sender);
			var remote = (RemoteData)mi.BindingContext;

			var result = await UserDialogs.Instance.PromptAsync(new PromptConfig {
				Title = "Rename",
				Text = remote.remote_button_name,
				IsCancellable = true,
				Placeholder = "Type new name"

			});

			if(!result.Text.Equals(remote.new_button_name)){

				waitRemoteDialog = UserDialogs.Instance.Loading("Renaming...",null,null,false,MaskType.Gradient);
				waitRemoteDialog.Show ();

				var newName = result.Text;
				RemoteData itemRemote =  new RemoteData();
				itemRemote.remote_button_name = remote.remote_button_name;
				itemRemote.node_command = "ir_remote_rename";
				itemRemote.new_button_name = newName;
				itemRemote.node_addr = remote.node_addr;
				itemRemote.remote_username = remote.remote_username;
				string jsonCommandaddRemoteButton = JsonConvert.SerializeObject(itemRemote, Formatting.Indented);
				System.Diagnostics.Debug.WriteLine ("{0}",jsonCommandaddRemoteButton);
				await LoginPage.ws_client.SendAsync (jsonCommandaddRemoteButton);

			}

			System.Diagnostics.Debug.WriteLine("RenameRemote_Clicked");
		}