ProgressDialog.xaml の相互作用ロジック
Inheritance: UserControl
Exemplo n.º 1
0
		/// <summary>
		/// This constructor provides the option of making the ProgressDialog modal.
		/// </summary>
		/// <param name="parentForm">The parent, or owning form for the ProgressDialog</param>
		/// <param name="command">The AsyncCommand c</param>
		/// <param name="progressTitleText">The title to use on the ProgressDialog</param>
		/// <param name="showModally">true if you want to use this modally, false otherwise. If you pass true, you must use ShowModal later to show the ProgressDialog</param>
		public ProgressDialogHandler(Form parentForm, BasicCommand command, string progressTitleText, bool showModally)
		{
			_parentForm = parentForm;
			_currentCommand = command;
			command.InitializeCallback = InitializeProgress;
			command.ProgressCallback = UpdateProgress;
			command.PrimaryStatusTextCallback = UpdateStatus1;
			command.SecondaryStatusTextCallback = UpdateOverview;

			_currentCommand.BeginCancel += OnCommand_BeginCancel;
			_currentCommand.EnabledChanged += OnCommand_EnabledChanged;
			_currentCommand.Error += OnCommand_Error;
			_currentCommand.Finish += OnCommand_Finish;

			_progressDialog = new ProgressDialog
								{
									Text = progressTitleText
								};
			_progressDialog.CancelRequested += _progressDialog_Cancelled;
			_progressDialog.Owner = parentForm;
			_progressDialog.CanCancel = true;
			//To use this progress in a modal way you need to call ShowModal after you have setup the ProgressDialogState
			if (!showModally)
			{
				//if it is not modal then we can show the dialog and it won't inhibit the rest of the setup and calling.
				_progressDialog.Show();
			}
		}
	public bool Execute (Photo [] photos)
	{
		ProgressDialog progress_dialog = null;

		if (photos.Length > 1) {
			progress_dialog = new ProgressDialog ("Updating Thumbnails",
							      ProgressDialog.CancelButtonType.Stop,
							      photos.Length, parent_window);
		}

		int count = 0;
		foreach (Photo p in photos) {
			if (progress_dialog != null
			    && progress_dialog.Update (String.Format ("Updating picture \"{0}\"", p.Name)))
				break;

			foreach (uint version_id in p.VersionIds) {
				Gdk.Pixbuf thumb = FSpot.ThumbnailGenerator.Create (p.VersionUri (version_id));
				if (thumb !=  null)
					thumb.Dispose ();
			}
			
			count++;
		}

		if (progress_dialog != null)
			progress_dialog.Destroy ();

		return true;
	}
Exemplo n.º 3
0
        private async void CreateAccount_Click(object sender, RoutedEventArgs e)
        {
            var message = new ProgressDialog();

            await DialogHost.Show(message, "CreateAccountDialogHost", OpenedEventHandler, ClosingEventHandler);
            
        }
Exemplo n.º 4
0
 private void btnMerge_Click(object sender, RoutedEventArgs e)
 {
     var dlg = new ProgressDialog();
     dlg.Owner = this;
     object[] args = new object[] { lstAssemblies.Assemblies, fileMainAssembly.FileName, fnaOutput.FileName , fnaLog.FileName};
     dlg.RunWorkerThread(args, Merge);
 }
    public bool Execute(IPhoto [] photos)
    {
        ProgressDialog progress_dialog = null;
        var loader = ThumbnailLoader.Default;
        if (photos.Length > 1) {
            progress_dialog = new ProgressDialog (Mono.Unix.Catalog.GetString ("Updating Thumbnails"),
                                  ProgressDialog.CancelButtonType.Stop,
                                  photos.Length, parent_window);
        }

        int count = 0;
        foreach (IPhoto photo in photos) {
            if (progress_dialog != null
                && progress_dialog.Update (String.Format (Mono.Unix.Catalog.GetString ("Updating picture \"{0}\""), photo.Name)))
                break;

            foreach (IPhotoVersion version in photo.Versions) {
                loader.Request (version.Uri, ThumbnailSize.Large, 10);
            }

            count++;
        }

        if (progress_dialog != null)
            progress_dialog.Destroy ();

        return true;
    }
Exemplo n.º 6
0
        RuleIndex(string fileName, XDocument document, ProgressDialog dialog)
        {
            this.name = fileName;
            if (dialog != null) { dialog.SetDescription("Building elements..."); }

            int max = document.Root.Elements().Count();
            int current = 0;

            foreach (XElement element in document.Root.Elements())
            {
                if (dialog != null) { dialog.SetProgress(current++, max); }
                RuleElement re = new RuleElement(element);
                this.elements.Add(re.Id, re);
            }

            current = 0;
            if (dialog != null) { dialog.SetDescription("Binding categories..."); }
            foreach (RuleElement element in this.elements.Values)
            {
                if (dialog != null) { dialog.SetProgress(current++, this.elements.Count); }
                element.BindCategories(this);
            }

            current = 0;
            if (dialog != null) { dialog.SetDescription("Binding rules..."); }
            foreach (RuleElement element in this.elements.Values)
            {
                if (dialog != null) { dialog.SetProgress(current++, this.elements.Count); }
                element.BindRules(this);
            }

            if (dialog != null) { dialog.SetDescription("Reticulating splines..."); }
            this.elementsByName = this.elements.Values.ToLookup(e => e.Name);
            this.elementsByFullName = this.elements.Values.ToLookup(e => e.FullName);
        }
Exemplo n.º 7
0
        public async Task<ProgressDialog> CreateProgressDialog(string title, bool isindeterminate)
        {
            var prg = new ProgressDialog();
            if (Configuration.ShowFullscreenDialogs)
            {
                var progresscontroller = await BaseWindow.ShowProgressAsync(title, string.Empty);
                progresscontroller.SetIndeterminate();
                prg.MessageChanged = ev =>
                    progresscontroller.SetMessage(ev);
                prg.TitleChanged = ev =>
                    progresscontroller.SetTitle(ev);
                prg.ProgressChanged = ev =>
                    progresscontroller.SetProgress(ev);
                prg.CloseRequest = () =>
                 progresscontroller.CloseAsync();
            }
            else
            {
                var progressWindow = new ProgressWindow(title, isindeterminate) { Owner = BaseWindow };
                prg.MessageChanged = ev => progressWindow.SetText(ev);
                prg.TitleChanged = ev => progressWindow.SetTitle(ev);
                prg.ProgressChanged = ev => progressWindow.SetProgress(ev);
                prg.CloseRequest = () => { progressWindow.Close(); return null; };
                Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => progressWindow.ShowDialog()));

            }
            return prg;
        }
Exemplo n.º 8
0
        private void btnSettings_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            var dlg = new ProgressDialog();
            dlg.Owner = this;
            dlg.ShowDialog();
        	var form = new SettingsWindow();
            form.Owner = this;
			form.ShowDialog();
        }
Exemplo n.º 9
0
 private async void SignIn_Click(object sender, RoutedEventArgs e)
 {
     /*AppearanceManager.Current.AccentColor = Color.FromRgb(130, 177, 255);
     AppearanceManager.Current.ThemeSource = new Uri("pack://application:,,,/Resources/Themes/BlueMist.xaml");*/
     var message = new ProgressDialog();
     
     await DialogHost.Show(message, "LoginDialogHost", OpenedEventHandler,ClosingEventHandler);
     
 }
Exemplo n.º 10
0
        public frm_FolderBackup()
        {
            Thread.CurrentThread.CurrentUICulture = Properties.Settings.Default.Language;
            generalResourceManager = new SingleAssemblyResourceManager("General", Assembly.GetExecutingAssembly());

            progressDialog = new ProgressDialog();
            progressDialog.DisplayCounts = false;
            progressDialog.DisplayIntervalSeconds = 1;
            progressDialog.DisplayTimeEstimates = false;

            InitializeComponent();
        }
		public override void Run (object o, EventArgs e)
		{
			ProgressDialog pdialog = new ProgressDialog(Catalog.GetString ("Developing photos"),
														ProgressDialog.CancelButtonType.Cancel,
														MainWindow.Toplevel.SelectedPhotos ().Length,
														MainWindow.Toplevel.Window);
			Log.Information ("Executing DevelopInUFRaw extension in batch mode");

			foreach (Photo p in MainWindow.Toplevel.SelectedPhotos ()) {
				bool cancelled = pdialog.Update(String.Format(Catalog.GetString ("Developing {0}"), p.Name));
				if (cancelled) {
					break;
				}

				DevelopPhoto (p);
			}
			pdialog.Destroy();
		}
Exemplo n.º 12
0
 public IPodChooseWindow(Store s)
     : base(IntPtr.Zero)
 {
     store = s;
     Glade.XML gxml = new Glade.XML (null, "IPodWindow.glade", "window", null);
     gxml.Autoconnect (this);
     Raw = window.Handle;
     combo = new DeviceCombo ();
     combo.Changed += OnDeviceChanged;
     combo_container.PackStart (combo, true, true, 0);
     update_button.Clicked += OnUpdateClicked;
     window.Icon = MainClass.program_pixbuf48;
     notify = new ThreadNotify (new ReadyEvent (OnNotify));
     progress = new ProgressDialog (this);
     SetDevice ();
     window.Response += OnWindowResponse;
     window.DeleteEvent += OnWindowDeleteEvent;
     combo.ShowAll ();
 }
Exemplo n.º 13
0
		private bool PopulateDefinitionsWithUI()
		{
			using (ProgressDialog dlg = new ProgressDialog())
			{
				dlg.Overview = "Please wait while WeSay preprocesses your LIFT file.";
				BackgroundWorker preprocessWorker = new BackgroundWorker();
				preprocessWorker.DoWork += DoPopulateDefinitionsWork;
				dlg.BackgroundWorker = preprocessWorker;
				dlg.CanCancel = true;
				dlg.ShowDialog();
				if (dlg.ProgressStateResult.ExceptionThatWasEncountered != null)
				{
					ErrorReport.NotifyUserOfProblem(
							String.Format(
									"WeSay encountered an error while preprocessing the file '{0}'.  Error was: {1}",
									_liftFilePath,
									dlg.ProgressStateResult.ExceptionThatWasEncountered.Message));
				}
				return (dlg.DialogResult == DialogResult.OK);
			}
		}
        /// <summary>
        /// Creates a report config with user's choices
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_CreateReport_Click(object sender, EventArgs e)
        {
            reportHandler.Name = "Specification coverage report";

            reportHandler.AddSpecification = CB_AddSpecification.Checked;
            reportHandler.ShowFullSpecification = CB_ShowFullSpecification.Checked;

            reportHandler.AddCoveredParagraphs = CB_AddCoveredParagraphs.Checked;
            reportHandler.ShowAssociatedReqRelated = CB_ShowAssociatedReqRelated.Checked;

            reportHandler.AddNonCoveredParagraphs = CB_AddNonCoveredParagraphs.Checked;

            reportHandler.AddReqRelated = CB_AddReqRelated.Checked;
            reportHandler.ShowAssociatedParagraphs = CB_ShowAssociatedParagraphs.Checked;

            Hide();

            ProgressDialog dialog = new ProgressDialog("Generating report", reportHandler);
            dialog.ShowDialog(Owner);
        }
Exemplo n.º 15
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            this.SetContentView(IslamicHadithAND.Resource.Layout.Book);

            //ActionBar
            ActionBar.NavigationMode = ActionBarNavigationMode.Standard;

            progress = ProgressDialog.Show(this, "انتظر من فضلك", "يتم تحميل الأحاديث ...", true);

            new Thread(new ThreadStart(() =>
            {
                Thread.Sleep(1);
                this.RunOnUiThread(() =>
                {
                    try
                    {
                        string content;
                        using (StreamReader streamReader = new StreamReader(Assets.Open("hadeeth.sqlite")))
                        {
                            content = streamReader.ReadToEnd();
                        }
                        string dbName = "hadeeth.sqlite";
                        string dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), dbName);
                        if (!File.Exists(dbPath))
                        {
                            using (Stream source = new StreamReader(Assets.Open("hadeeth.sqlite")).BaseStream)
                            {
                                using (var destination = System.IO.File.Create(dbPath))
                                {
                                    source.CopyTo(destination);
                                }
                            }
                        }
                        DataTable dataTableBook = new DataTable();

                        var connectionString = string.Format("Data Source={0};Version=3;", dbPath);
                        using (var conn = new SqliteConnection((connectionString)))
                        {
                            using (var command = conn.CreateCommand())
                            {
                                conn.Open();
                                command.CommandText = @"SELECT hadeeth.*" +
                                                      "FROM Books INNER JOIN hadeeth ON Books.ID = hadeeth.BID" +
                                                      " where hadeeth.hadeeth like '%<%' and " +
                                                      "books.title like '%سنن ابن ماجه‏%'";

                                command.CommandType           = CommandType.Text;
                                SqliteDataAdapter dataAdapter = new SqliteDataAdapter();
                                dataAdapter.SelectCommand     = command;
                                dataAdapter.Fill(dataTableBook);
                            }
                        }

                        var data = new List <string>();
                        for (int i = 0; i < dataTableBook.Rows.Count; i++)
                        {
                            data.Add(unBold((dataTableBook.Rows[i]["hadeeth"].ToString())));
                            if (dataTableBook.Rows.Count == 0)
                            {
                                new AlertDialog.Builder(this)
                                .SetTitle("خطأ")
                                .SetMessage("لا يوجد نتائج")
                                .SetPositiveButton("عودة", (senderaa, args) =>
                                {
                                    // Back
                                })
                                .Show();
                            }
                        }

                        var listView     = FindViewById <ListView>(IslamicHadithAND.Resource.Id.listBook);
                        listView.Adapter = new ArrayAdapter(this, Resource.Layout.ListViewContents, data);

                        listView.ItemClick += (sender, e) =>
                        {
                            var position      = e.Position;
                            var HadithBrowser = new Intent(this, typeof(HadithBrowser));
                            HadithBrowser.PutExtra("Hadith", listView.GetItemAtPosition(position).ToString());
                            if (!listView.GetItemAtPosition(position + 1).Equals(null))
                            {
                                position++;
                                HadithBrowser.PutExtra("HadithNext1", listView.GetItemAtPosition(position).ToString());
                            }
                            if (!listView.GetItemAtPosition(position - 1).Equals(null))
                            {
                                position--;
                                HadithBrowser.PutExtra("HadithPrevious1", listView.GetItemAtPosition(position).ToString());
                            }
                            StartActivity(HadithBrowser);
                        };
                    }
                    catch (Exception ex)
                    {
                        new AlertDialog.Builder(this)
                        .SetPositiveButton("عودة", (sendera, args) =>
                        {
                            // Back
                        })
                        .SetTitle("خطأ")
                        .SetMessage("خطأ في قاعدة البيانات ( " + ex.ToString() + " )")
                        .Show();
                    }

                    progress.Dismiss();
                });
            })).Start();
        }
Exemplo n.º 16
0
        private string[] MoveResourcesWithinConnection(string connectionName, ICollection <string> resIds, string folderId)
        {
            var wb = Workbench.Instance;
            var notMovedToTarget   = new List <string>();
            var notMovedFromSource = new List <string>();
            var omgr = ServiceRegistry.GetService <OpenResourceManager>();
            var conn = _connManager.GetConnection(connectionName);

            var dlg    = new ProgressDialog();
            var worker = new ProgressDialog.DoBackgroundWork((w, e, args) =>
            {
                LengthyOperationProgressCallBack cb = (sender, cbe) =>
                {
                    w.ReportProgress(cbe.Progress, cbe.StatusMessage);
                };

                var f           = (string)args[0];
                var resourceIds = (ICollection <string>)args[1];

                foreach (var r in resourceIds)
                {
                    if (ResourceIdentifier.IsFolderResource(r))
                    {
                        //IMPORTANT: We need to tweak the target resource id
                        //otherwise the content *inside* the source folder is
                        //moved instead of the folder itself!
                        var rid    = new ResourceIdentifier(r);
                        var target = $"{folderId + rid.Name}/"; //NOXLATE
                        conn.ResourceService.MoveResourceWithReferences(r, target, null, cb);
                    }
                    else
                    {
                        var rid    = new ResourceIdentifier(r);
                        var target = $"{folderId + rid.Name}.{rid.Extension}"; //NOXLATE
                        if (omgr.IsOpen(r, conn))
                        {
                            notMovedFromSource.Add(r);
                            continue;
                        }

                        if (!omgr.IsOpen(target, conn))
                        {
                            conn.ResourceService.MoveResourceWithReferences(r, target, null, cb);
                        }
                        else
                        {
                            notMovedToTarget.Add(r);
                        }
                    }
                }

                //Collect affected folders and refresh them
                Dictionary <string, string> folders = new Dictionary <string, string>();
                folders.Add(folderId, folderId);
                foreach (var n in resourceIds)
                {
                    var ri     = new ResourceIdentifier(n);
                    var parent = ri.ParentFolder;
                    if (parent != null && !folders.ContainsKey(parent))
                    {
                        folders.Add(parent, parent);
                    }
                }

                return(folders.Keys);
            });

            var affectedFolders = (IEnumerable <string>)dlg.RunOperationAsync(wb, worker, folderId, resIds);

            if (notMovedToTarget.Count > 0 || notMovedFromSource.Count > 0)
            {
                MessageService.ShowMessage(string.Format(
                                               Strings.NotCopiedOrMovedDueToOpenEditors,
                                               Environment.NewLine + string.Join(Environment.NewLine, notMovedToTarget.ToArray()) + Environment.NewLine,
                                               Environment.NewLine + string.Join(Environment.NewLine, notMovedFromSource.ToArray()) + Environment.NewLine));
            }

            return(new List <string>(affectedFolders).ToArray());
        }
        private void PerformAction(string actionName, Project project, Cloud cloud, ProjectDirectories dir,
            Action<IVcapClient, DirectoryInfo> action)
        {
            var worker = new BackgroundWorker();

            Messenger.Default.Register<NotificationMessageAction<string>>(this,
                message =>
                {
                    if (message.Notification.Equals(Messages.SetProgressData))
                        message.Execute(actionName);
                });

            var window = new ProgressDialog();
            var dispatcher = window.Dispatcher;
            var helper = new WindowInteropHelper(window);
            helper.Owner = (IntPtr)(dte.MainWindow.HWnd);
            worker.WorkerSupportsCancellation = true;
            worker.DoWork += (s, args) =>
            {
                if (worker.CancellationPending) { args.Cancel = true; return; }

                Messenger.Default.Send(new ProgressMessage(0, "Starting " + actionName));

                if (worker.CancellationPending) { args.Cancel = true; return; }

                if (!Directory.Exists(dir.StagingPath))
                {
                    dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressMessage(10, "Creating Staging Path"))));
                    Directory.CreateDirectory(dir.StagingPath);
                }

                if (worker.CancellationPending) { args.Cancel = true; return; }

                if (Directory.Exists(dir.DeployFromPath))
                {
                    dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressMessage(10, "Creating Precompiled Site Path"))));
                    Directory.Delete(dir.DeployFromPath, true);
                }

                if (worker.CancellationPending) { args.Cancel = true; return; }

                dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressMessage(30, "Preparing Compiler"))));

                VsWebSite.VSWebSite site = project.Object as VsWebSite.VSWebSite;
                if (site != null)
                {
                    site.PreCompileWeb(dir.DeployFromPath, true);
                }
                else
                {
                    string frameworkPath = (site == null) ? project.GetFrameworkPath() : String.Empty;

                    if (worker.CancellationPending) { args.Cancel = true; return; }
                    string objDir = Path.Combine(dir.ProjectDirectory, "obj");
                    if (Directory.Exists(objDir))
                    {
                        Directory.Delete(objDir, true); // NB: this can cause precompile errors
                    }

                    var process = new System.Diagnostics.Process()
                    {
                        StartInfo = new ProcessStartInfo()
                        {
                            FileName = Path.Combine(frameworkPath, "aspnet_compiler.exe"),
                            Arguments = String.Format("-nologo -v / -p \"{0}\" -f -u -c \"{1}\"", dir.ProjectDirectory, dir.DeployFromPath),
                            CreateNoWindow = true,
                            ErrorDialog = false,
                            UseShellExecute = false,
                            RedirectStandardOutput = true
                        }
                    };

                    if (worker.CancellationPending) { args.Cancel = true; return; }
                    dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressMessage(40, "Precompiling Site"))));
                    process.Start();
                    string output = process.StandardOutput.ReadToEnd();
                    process.WaitForExit();
                    if (process.ExitCode != 0)
                    {
                        string message = "Asp Compile Error";
                        if (false == String.IsNullOrEmpty(output))
                        {
                            message += ": " + output;
                        }
                        dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressError(message))));
                        return;
                    }
                }

                dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressMessage(50, "Logging in to Cloud Foundry"))));

                if (worker.CancellationPending) { args.Cancel = true; return; }

                var client = new VcapClient(cloud);
                try
                {
                    client.Login();
                }
                catch (Exception e)
                {
                    dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressError("Failure: " + e.Message))));
                    return;
                }

                dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressMessage(75, "Sending to " + cloud.Url))));
                if (worker.CancellationPending) { args.Cancel = true; return; }

                try
                {
                    action(client, new DirectoryInfo(dir.DeployFromPath));
                }
                catch (Exception e)
                {
                    dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressError("Failure: " + e.Message))));
                    return;
                }
                dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressMessage(100, actionName + " complete."))));
            };

            worker.RunWorkerAsync();
            if (!window.ShowDialog().GetValueOrDefault())
            {
                worker.CancelAsync();
            }
        }
Exemplo n.º 18
0
        // TODO refactor this method to a helper / class of some kind
        private DialogResult ConnectToAllDevices(List <ConnectionSearchResult> connectionSearchResults, out List <Connection> resultConnections)
        {
            if (connectionSearchResults.Count == 0)
            {
                resultConnections = new List <Connection>();

                return(DialogResult.OK);
            }

            List <Connection> connections = new List <Connection>();

            DialogResult result = System.Windows.Forms.DialogResult.Cancel;

            // Begin
            ProgressDialog progress = new ProgressDialog();

            progress.Text  = "Connecting";
            progress.Style = ProgressBarStyle.Continuous;

            progress.ProgressMessage = "";
            progress.Progress        = 0;
            progress.ProgressMaximum = (connectionSearchResults.Count * 4) - 1;

            Reporter reporter = new Reporter();

            bool canceled        = false;
            int  currentProgress = 0;

            string currentConnectionString = "";

            Thread connectingToMultipleConnections = new Thread(() =>
            {
                progress.OnCancel += (o, args) =>
                {
                    canceled = true;
                };

                EventHandler <MessageEventArgs> reportInfo = (o, args) =>
                {
                    progress.UpdateProgress(currentProgress, currentConnectionString + args.Message);
                };

                reporter.Info += reportInfo;

                try
                {
                    progress.UpdateProgress(0);

                    for (int i = 0; i < connectionSearchResults.Count; i++)
                    {
                        if (canceled == true)
                        {
                            progress.UpdateProgress(currentProgress, string.Empty);

                            return;
                        }

                        ConnectionSearchResult autoConnectionInfo = connectionSearchResults[i];

                        currentConnectionString = "Connecting to " + autoConnectionInfo.DeviceDescriptor + ". ";

                        progress.UpdateProgress(currentProgress++, autoConnectionInfo.DeviceDescriptor);

                        Connection connection = null;

                        if (autoConnectionInfo.ConnectionType == ConnectionType.Udp)
                        {
                            #region Configure Unique Connection

                            bool retryThis = true;

                            do
                            {
                                try
                                {
                                    UdpConnectionInfo udpConnectionInfo =
                                        NgimuApi.Connection.ConfigureUniqueUdpConnection(
                                            autoConnectionInfo.ConnectionInfo as UdpConnectionInfo, reporter);

                                    connection = new Connection(udpConnectionInfo);

                                    break;
                                }
                                catch (Exception ex)
                                {
                                    StringBuilder fullMessageString = new StringBuilder();

                                    fullMessageString.AppendLine("Error while connecting to " + autoConnectionInfo.DeviceDescriptor + ".");
                                    fullMessageString.AppendLine();

                                    fullMessageString.Append("Could not configure a unique UDP connection.");

                                    switch (this.InvokeShowError(fullMessageString.ToString(), MessageBoxButtons.AbortRetryIgnore))
                                    {
                                    case DialogResult.Abort:
                                        CloseAllConnections(connections);

                                        progress.DialogResult = DialogResult.Cancel;

                                        return;

                                    case DialogResult.Retry:
                                        break;

                                    case DialogResult.Ignore:
                                        retryThis = false;
                                        break;

                                    default:
                                        break;
                                    }
                                }
                            }while (retryThis == true);

                            #endregion
                        }
                        else
                        {
                            connection = new Connection(autoConnectionInfo);
                        }

                        if (connection == null)
                        {
                            currentProgress += 3;
                            progress.UpdateProgress(currentProgress);

                            continue;
                        }

                        progress.UpdateProgress(currentProgress++);

                        if (canceled == true)
                        {
                            progress.UpdateProgress(currentProgress);

                            return;
                        }

                        #region Read Settings

                        try
                        {
                            connection.Connect();

                            progress.UpdateProgress(currentProgress++);


                            bool retryThis = false;

                            do
                            {
                                if (connection.Settings.Read(reporter) != CommunicationProcessResult.Success)
                                {
                                    bool allValuesFailed;
                                    bool allValuesSucceeded;

                                    string messageString =
                                        Settings.GetCommunicationFailureString(connection.Settings.Values, 20,
                                                                               out allValuesFailed, out allValuesSucceeded);

                                    StringBuilder fullMessageString = new StringBuilder();

                                    fullMessageString.AppendLine("Error while connecting to " + autoConnectionInfo.DeviceDescriptor + ".");
                                    fullMessageString.AppendLine();

                                    if (allValuesFailed == true)
                                    {
                                        fullMessageString.Append("Failed to read all settings.");
                                    }
                                    else
                                    {
                                        fullMessageString.Append("Failed to read the following settings:" + messageString);
                                    }

                                    switch (this.InvokeShowError(fullMessageString.ToString(), MessageBoxButtons.AbortRetryIgnore))
                                    {
                                    case DialogResult.Abort:
                                        connection.Dispose();

                                        CloseAllConnections(connections);

                                        progress.DialogResult = DialogResult.Cancel;

                                        return;

                                    case DialogResult.Retry:
                                        retryThis = true;
                                        break;

                                    case DialogResult.Ignore:
                                        retryThis = false;
                                        break;

                                    default:
                                        break;
                                    }
                                }

                                connections.Add(connection);
                            }while (retryThis);
                        }
                        catch (Exception ex)
                        {
                            connection?.Dispose();
                        }

                        #endregion

                        progress.UpdateProgress(currentProgress++);
                    }

                    progress.DialogResult = System.Windows.Forms.DialogResult.OK;
                }
                finally
                {
                    reporter.Info -= reportInfo;
                }
            });

            connectingToMultipleConnections.Name = "Connecting to multiple connections";
            connectingToMultipleConnections.Start();

            result = progress.ShowDialog(this);

            resultConnections = new List <Connection>(connections);

            return(result);
        }
Exemplo n.º 19
0
        private void DisconnectAll()
        {
            synchronisationMasterListener?.Dispose();
            sendCommandToolStripMenuItem.Enabled = false;

            if (connectionsRows.Count == 0)
            {
                return;
            }

            dataLogger?.Stop();
            dataLogger?.ActiveConnections.Clear();
            dataLogger?.UpdateConnections();

            sendRates?.ActiveConnections.Clear();
            sendRates?.UpdateColumns();

            ProgressDialog progress = new ProgressDialog();

            progress.Text  = "Disconnecting";
            progress.Style = ProgressBarStyle.Continuous;

            progress.CancelButtonEnabled = false;
            progress.ProgressMessage     = "";
            progress.Progress            = 0;
            progress.ProgressMaximum     = connectionsRows.Count;

            ManualResetEvent dialogDoneEvent = new ManualResetEvent(false);

            Thread disconnectThread = new Thread(() =>
            {
                try
                {
                    int index = 0;
                    foreach (ConnectionRow connection in connectionsRows)
                    {
                        if (progress.Visible == true)
                        {
                            Invoke(new MethodInvoker(() =>
                            {
                                progress.ProgressMessage = "Disconnecting from " + connection.Connection.Settings.GetDeviceDescriptor() + ".";
                                progress.Progress        = ++index;
                            }));
                        }

                        connection.Connection.Message -= Connection_Message;
                        connection.Connection.Dispose();
                    }

                    Thread.CurrentThread.Join(100);
                }
                finally
                {
                    dialogDoneEvent.Set();
                }

                Invoke(new MethodInvoker(() => { progress.Close(); }));
            });

            disconnectThread.Name = "Disconnecting from " + connectionsRows.Count + " Devices";
            disconnectThread.Start();

            progress.ShowDialog(this);

            dialogDoneEvent.WaitOne();

            connectionsRows.Clear();
            dataGridView1.Rows.Clear();

            SetTitle();
        }
Exemplo n.º 20
0
        private void Import()
        {
            ClearStatusMessage();
            try
            {
                ImportSetting importSetting = null;
                var           task          = Util.GetMasterImportSettingAsync(Login, ImportFileType.Department);
                ProgressDialog.Start(ParentForm, task, false, SessionKey);
                importSetting = task.Result;

                var definition = new DepartmentFileDefinition(new DataExpression(ApplicationControl));
                definition.StaffIdField.GetModelsByCode = val =>
                {
                    StaffsResult result = null;
                    ServiceProxyFactory.LifeTime(factory =>
                    {
                        var staffMaster = factory.Create <StaffMasterClient>();
                        result          = staffMaster.GetByCode(SessionKey, CompanyId, val);
                    });

                    if (result.ProcessResult.Result)
                    {
                        return(result.Staffs
                               .ToDictionary(c => c.Code));
                    }
                    return(new Dictionary <string, Staff>());
                };

                //その他
                definition.DepartmentCodeField.ValidateAdditional = (val, param) =>
                {
                    var reports = new List <WorkingReport>();
                    if (((ImportMethod)param) != ImportMethod.Replace)
                    {
                        return(reports);
                    }

                    MasterDatasResult resultstaff = null;
                    MasterDatasResult resultsectionWithDepartment = null;
                    MasterDatasResult resultbilling = null;
                    ServiceProxyFactory.LifeTime(factory =>
                    {
                        var departmentMaster        = factory.Create <DepartmentMasterClient>();
                        var codes                   = val.Values.Where(x => !string.IsNullOrEmpty(x.Code)).Select(x => x.Code).Distinct().ToArray();
                        resultstaff                 = departmentMaster.GetImportItemsStaff(SessionKey, CompanyId, codes);
                        resultsectionWithDepartment = departmentMaster.GetImportItemsSectionWithDepartment(SessionKey, CompanyId, codes);
                        resultbilling               = departmentMaster.GetImportItemsBilling(SessionKey, CompanyId, codes);//
                    });
                    foreach (MasterData ca in resultstaff.MasterDatas.Where(p => !val.Any(a => a.Value.Code == p.Code)))
                    {
                        reports.Add(new WorkingReport
                        {
                            LineNo    = null,
                            FieldNo   = definition.DepartmentCodeField.FieldIndex,
                            FieldName = definition.DepartmentCodeField.FieldName,
                            Message   = $"営業担当者マスターに存在する{ ca.Code }:{ ca.Name }が存在しないため、インポートできません。",
                        });
                    }
                    foreach (MasterData ca in resultsectionWithDepartment.MasterDatas.Where(p => !val.Any(a => a.Value.Code == p.Code)))
                    {
                        reports.Add(new WorkingReport
                        {
                            LineNo    = null,
                            FieldNo   = definition.DepartmentCodeField.FieldIndex,
                            FieldName = definition.DepartmentCodeField.FieldName,
                            Message   = $"入金・請求部門名対応マスターに存在する{ca.Code}:{ca.Name}が存在しないため、インポートできません。",
                        });
                    }
                    foreach (MasterData ca in resultbilling.MasterDatas.Where(p => !val.Any(a => a.Value.Code == p.Code)))
                    {
                        reports.Add(new WorkingReport
                        {
                            LineNo    = null,
                            FieldNo   = definition.DepartmentCodeField.FieldIndex,
                            FieldName = definition.DepartmentCodeField.FieldName,
                            Message   = $"請求データに存在する{ca.Code}:{ca.Name}が存在しないため、インポートできません。",
                        });
                    }

                    return(reports);
                };

                var importer = definition.CreateImporter(m => m.Code);
                importer.UserId      = Login.UserId;
                importer.UserCode    = Login.UserCode;
                importer.CompanyId   = CompanyId;
                importer.CompanyCode = Login.CompanyCode;
                importer.LoadAsync   = async() => await LoadListAsync();

                importer.RegisterAsync = async unitOfWork => await RegisterForImportAsync(unitOfWork);

                var importResult = DoImport(importer, importSetting);

                if (!importResult)
                {
                    return;
                }
                Clear();
                var departmentProgress = new List <Department>();
                departmentProgress.Clear();
                Task <List <Department> > loadTask = LoadListAsync();
                ProgressDialog.Start(ParentForm, loadTask, false, SessionKey);
                departmentProgress.AddRange(loadTask.Result);
                grdDepartment.DataSource = new BindingSource(departmentProgress, null);
            }
            catch (Exception ex)
            {
                Debug.Fail(ex.ToString());
                NLogHandler.WriteErrorLog(this, ex, SessionKey);
                ShowWarningDialog(MsgErrImportErrorWithoutLog);
            }
        }
        private async void SubmitBtn_Clicked(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(otpTxt.Text))
            {
                var pd = await ProgressDialog.Show("Please wait...");

                string endpoint = "Spay/DebitAnyBankCardWithOTP";
                string url      = BaseURL + endpoint;

                try
                {
                    dbcOTPMOdel = new DebitAnyBankCardWithOTP()
                    {
                        pin           = fundModel.pin,
                        expiry_date   = fundModel.expiry_date,
                        cvv2          = fundModel.cvv,
                        pan           = fundModel.pan,
                        otp           = otpTxt.Text.Trim(),
                        CreditAccount = fundModel.CreditAccount,
                        paymentId     = paymentID,
                        amount        = fundModel.amount.ToString()
                    };


                    var response = await apiRequest.Post(dbcOTPMOdel, "", BaseURL, endpoint, "FundAccountOTPPage", true);

                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        await pd.Dismiss();

                        var jsonString = await response.Content.ReadAsStringAsync();

                        jsonString = jsonString.JsonCleanUp();
                        var responseObj = JsonConvert.DeserializeObject <FundAccountOTPResponse>(jsonString);
                        if (responseObj.message == "Successful")
                        {
                            MessageDialog.Show("Success", $"Account funding of {responseObj.amount} was successful.", DialogType.Success, "OK", null);
                            Navigation.PushAsync(new Dashboard.Dashboard());
                        }
                        else
                        {
                            MessageDialog.Show("Failure", "Sorry we are unable to process your request at the moment. Kindly try again later.", DialogType.Error, "DISMISS", null);
                        }
                    }
                    else
                    {
                        await pd.Dismiss();

                        var jsonString = await response.Content.ReadAsStringAsync();

                        MessageDialog.Show("Error", "Sorry, We are unable to credit recipient's account at the moment. Kindly try again later", DialogType.Error, "OK", null);
                        await BusinessLogic.Log("", "", url, "**SENSITIVE**", jsonString, "FundAccountOTPPage");
                    }
                }
                catch (Exception ex)
                {
                    await pd.Dismiss();

                    MessageDialog.Show("Error", "Sorry, We are unable to credit recipient's account at the moment. Kindly try again later", DialogType.Error, "OK", null);
                    await BusinessLogic.Log(ex.ToString(), "", url, "**SENSITIVE**", "", "FundAccountOTPPage");
                }
            }
            else
            {
                MessageDialog.Show("Fund Account", "Kindly enter the OTP sent to your phone number and/or email address to continue", DialogType.Info, "OK", null);
            }
        }
        /// <summary>
        ///     Executes the operation in background using a progress handler
        /// </summary>
        /// <param name="mainForm">The enclosing form</param>
        /// <param name="message">The message to display on the dialog window</param>
        /// <param name="allowCancel">Indicates that the opeation can be canceled</param>
        public virtual void ExecuteUsingProgressDialog(Form mainForm, string message, bool allowCancel = true)
        {
            DateTime start = DateTime.Now;

            Util.DontNotify(() =>
            {
                try
                {
                    SynchronizerList.SuspendSynchronization();

                    if (ShowDialog)
                    {
                        Dialog = new ProgressDialog(message, this, allowCancel);
                        mainForm.Invoke((MethodInvoker) (() => Dialog.ShowDialog(mainForm)));
                    }
                    else
                    {
                        ExecuteWork();
                    }
                }
                catch (ThreadAbortException)
                {
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message + @"\n" + e.StackTrace, @"Exception raised");
                    // DefaultDesktopOnly option is added in order to avoid exceptions during nightbuild execution
                    MessageBox.Show (e.Message + @"\n" + e.StackTrace, @"Exception raised", MessageBoxButtons.OK,
                                     MessageBoxIcon.Error, MessageBoxDefaultButton.Button1,
                                     MessageBoxOptions.DefaultDesktopOnly);
                }
                finally
                {
                    Span = DateTime.Now.Subtract(start);
                    SynchronizerList.ResumeSynchronization();
                }
            });
        }
Exemplo n.º 23
0
        private async Task <string> DownloadWithProgress(SourceRepository sourceRepository, PackageIdentity packageIdentity)
        {
            var progressDialogText = Resources.Dialog_DownloadingPackage;

            if (packageIdentity.HasVersion)
            {
                progressDialogText = string.Format(CultureInfo.CurrentCulture, progressDialogText, packageIdentity.Id, packageIdentity.Version);
            }
            else
            {
                progressDialogText = string.Format(CultureInfo.CurrentCulture, progressDialogText, packageIdentity.Id, string.Empty);
            }

            string description = null;
            int?   percent     = null;
            var    updated     = false;

            var progressDialogLock = new object();
            var progressDialog     = new ProgressDialog
            {
                Text              = progressDialogText,
                WindowTitle       = Resources.Dialog_Title,
                ShowTimeRemaining = true,
                CancellationText  = "Canceling download..."
            };

            // polling for Cancel button being clicked
            var cts   = new CancellationTokenSource();
            var timer = new DispatcherTimer
            {
                Interval = TimeSpan.FromMilliseconds(200)
            };

            timer.Tick += (o, e) =>
            {
                lock (progressDialogLock)
                {
                    if (progressDialog.CancellationPending)
                    {
                        timer.Stop();
                        cts.Cancel();
                    }
                    else if (updated)
                    {
                        if (!progressDialog.IsOpen)
                        {
                            progressDialog.ProgressBarStyle = percent.HasValue ? ProgressBarStyle.ProgressBar : ProgressBarStyle.MarqueeProgressBar;
                            progressDialog.ShowDialog(MainWindow.Value);
                        }
                        progressDialog.ReportProgress(percent.GetValueOrDefault(), null, description);
                        updated = false;
                    }
                }
            };
            timer.Start();

            try
            {
                var httpProgressProvider = new ProgressHttpHandlerResourceV3Provider(OnProgress);
                var additionalProviders  = new[] { new Lazy <INuGetResourceProvider>(() => httpProgressProvider) };

                var repository       = PackageRepositoryFactory.CreateRepository(sourceRepository.PackageSource, additionalProviders);
                var downloadResource = await repository.GetResourceAsync <DownloadResource>(cts.Token);

                using (var sourceCacheContext = new SourceCacheContext()
                {
                    NoCache = true
                })
                {
                    var context = new PackageDownloadContext(sourceCacheContext, Path.GetTempPath(), true);

                    using (var result = await downloadResource.GetDownloadResourceResultAsync(packageIdentity, context, string.Empty, NullLogger.Instance, cts.Token))
                    {
                        if (result.Status == DownloadResourceResultStatus.Cancelled)
                        {
                            throw new OperationCanceledException();
                        }
                        if (result.Status == DownloadResourceResultStatus.NotFound)
                        {
                            throw new Exception(string.Format("Package '{0} {1}' not found", packageIdentity.Id, packageIdentity.Version));
                        }

                        var tempFilePath = Path.GetTempFileName();

                        using (var fileStream = File.OpenWrite(tempFilePath))
                        {
                            await result.PackageStream.CopyToAsync(fileStream);
                        }

                        return(tempFilePath);
                    }
                }
            }
            catch (OperationCanceledException)
            {
                return(null);
            }
            catch (Exception exception)
            {
                OnError(exception);
                return(null);
            }
            finally
            {
                timer.Stop();

                // close progress dialog when done
                lock (progressDialogLock)
                {
                    progressDialog.Close();
                    progressDialog = null;
                }

                MainWindow.Value.Activate();
            }

            void OnProgress(long bytesReceived, long?totalBytes)
            {
                if (totalBytes.HasValue)
                {
                    percent     = (int)((bytesReceived * 100L) / totalBytes);
                    description = string.Format(
                        CultureInfo.CurrentCulture,
                        "Downloaded {0} of {1}...",
                        FileSizeConverter.Convert(bytesReceived, typeof(string), null, CultureInfo.CurrentCulture),
                        FileSizeConverter.Convert(totalBytes.Value, typeof(string), null, CultureInfo.CurrentCulture));
                }
                else
                {
                    percent     = null;
                    description = string.Format(
                        CultureInfo.CurrentCulture,
                        "Downloaded {0}...",
                        FileSizeConverter.Convert(bytesReceived, typeof(string), null, CultureInfo.CurrentCulture));
                }
                updated = true;
            }
        }
Exemplo n.º 24
0
 protected override void OnPreExecute()
 {
     base.OnPreExecute();
     p = ProgressDialog.Show(activity, "", "Please wait");
 }
Exemplo n.º 25
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            (ViewModel as BaseViewModel).BaseView = this;
            mToastToken = Mvx.Resolve <IMvxMessenger>().SubscribeOnMainThread <ToastMessage>((ToastMessage message) =>
            {
                if (message.Sender != ViewModel)
                {
                    return;
                }

                if (!string.IsNullOrEmpty(message.Message))
                {
                    try
                    {
                        Toast.MakeText(this, message.Message, ToastLength.Short).Show();
                    }
                    catch (Exception ex)
                    {
                    }
                }
            });

            mProgressToken = Mvx.Resolve <IMvxMessenger>().SubscribeOnMainThread <ProgressMessage>(message =>
            {
                try
                {
                    if (message.Sender != ViewModel)
                    {
                        return;
                    }
                    if (message.IsShow)
                    {
                        if (mProgressDialog != null)
                        {
                            mProgressDialog.Dismiss();
                            mProgressDialog = null;
                        }

                        if (!string.IsNullOrEmpty(message.Message))
                        {
                            mProgressDialog = ProgressDialog.Show(this, null, message.Message, true, true);
                            mProgressDialog.SetCancelable(false);
                            mProgressDialog.SetCanceledOnTouchOutside(false);
                        }
                        else
                        {
                            mProgressDialog = new Dialog(this);
                            mProgressDialog.RequestWindowFeature((int)WindowFeatures.NoTitle);
                            mProgressDialog.SetContentView(Resource.Layout.CustomProgressDialog);
                            mProgressDialog.Window.SetBackgroundDrawableResource(Android.Resource.Color.Transparent);
                            mProgressDialog.SetCancelable(false);
                            mProgressDialog.SetCanceledOnTouchOutside(false);
                            mProgressDialog.Show();
                        }
                    }
                    else
                    {
                        if (mProgressDialog != null)
                        {
                            mProgressDialog.Dismiss();
                            mProgressDialog = null;
                        }
                    }
                }
                catch (Exception ex)
                {
                }
            });

            mAlertToken = Mvx.Resolve <IMvxMessenger>().SubscribeOnMainThread <AlertMessage>(message =>
            {
                try
                {
                    if (message.Sender != ViewModel)
                    {
                        return;
                    }
                    //show alert view with more than 1 buttons (e.g OK and Cancel )
                    if (message.OtherTitles != null && message.OtherActions != null)
                    {
                        // if (message.OtherTitles.Count() >= 2)
                        {
                            Dialog mDialog = new Dialog(this);
                            mDialog.Window.SetBackgroundDrawable(new ColorDrawable(Color.Transparent));
                            mDialog.RequestWindowFeature((int)WindowFeatures.NoTitle);
                            mDialog.SetContentView(Resource.Layout.CustomDialog);
                            mDialog.SetCancelable(false);
                            TextView Title   = mDialog.FindViewById <TextView>(Resource.Id.title);
                            TextView Message = mDialog.FindViewById <TextView>(Resource.Id.message);
                            if (!string.IsNullOrEmpty(message.Title))
                            {
                                Title.Text = message.Title;
                            }
                            if (!string.IsNullOrEmpty(message.Message))
                            {
                                Message.Text = message.Message;
                            }

                            TextView option1      = mDialog.FindViewById <TextView>(Resource.Id.option1);
                            TextView option2      = mDialog.FindViewById <TextView>(Resource.Id.option2);
                            TextView option3      = mDialog.FindViewById <TextView>(Resource.Id.option3);
                            TextView option4      = mDialog.FindViewById <TextView>(Resource.Id.option4);
                            TextView option5      = mDialog.FindViewById <TextView>(Resource.Id.option5);
                            TextView option6      = mDialog.FindViewById <TextView>(Resource.Id.option6);
                            TextView option7      = mDialog.FindViewById <TextView>(Resource.Id.option7);
                            TextView option8      = mDialog.FindViewById <TextView>(Resource.Id.option8);
                            TextView optionCancel = mDialog.FindViewById <TextView>(Resource.Id.optionCancel);

                            View view1      = mDialog.FindViewById <View>(Resource.Id.view1);
                            View view2      = mDialog.FindViewById <View>(Resource.Id.view2);
                            View view3      = mDialog.FindViewById <View>(Resource.Id.view3);
                            View view4      = mDialog.FindViewById <View>(Resource.Id.view4);
                            View view5      = mDialog.FindViewById <View>(Resource.Id.view5);
                            View view6      = mDialog.FindViewById <View>(Resource.Id.view6);
                            View view7      = mDialog.FindViewById <View>(Resource.Id.view7);
                            View view8      = mDialog.FindViewById <View>(Resource.Id.view8);
                            View viewCancel = mDialog.FindViewById <View>(Resource.Id.viewCancel);

                            if (!string.IsNullOrEmpty(message.CancelTitle))
                            {
                                optionCancel.Text       = message.CancelTitle;
                                optionCancel.Visibility = ViewStates.Visible;
                                viewCancel.Visibility   = ViewStates.Visible;
                                optionCancel.Click     += (sender, args) =>
                                {
                                    if (message.CancelAction != null)
                                    {
                                        message.CancelAction();
                                    }

                                    if (mDialog != null)
                                    {
                                        mDialog.Dismiss();
                                    }
                                };
                            }

                            for (int i = 0; i < message.OtherTitles.Length; i++)
                            {
                                int index = i;
                                switch (index)
                                {
                                case 0:
                                    view1.Visibility   = ViewStates.Visible;
                                    option1.Visibility = ViewStates.Visible;
                                    option1.Text       = message.OtherTitles[index].ToString();
                                    option1.Click     += (sender, args) =>
                                    {
                                        if (message.OtherActions[index] != null)
                                        {
                                            message.OtherActions[index]();
                                        }
                                        mDialog.Dismiss();
                                    };
                                    break;

                                case 1:
                                    view2.Visibility   = ViewStates.Visible;
                                    option2.Visibility = ViewStates.Visible;
                                    option2.Text       = message.OtherTitles[index].ToString();
                                    option2.Click     += (sender, args) =>
                                    {
                                        if (message.OtherActions[index] != null)
                                        {
                                            message.OtherActions[index]();
                                        }
                                        mDialog.Dismiss();
                                    };
                                    break;

                                case 2:
                                    view3.Visibility   = ViewStates.Visible;
                                    option3.Visibility = ViewStates.Visible;
                                    option3.Text       = message.OtherTitles[index].ToString();
                                    option3.Click     += (sender, args) =>
                                    {
                                        if (message.OtherActions[index] != null)
                                        {
                                            message.OtherActions[index]();
                                        }
                                        mDialog.Dismiss();
                                    };
                                    break;

                                case 3:
                                    view4.Visibility   = ViewStates.Visible;
                                    option4.Visibility = ViewStates.Visible;
                                    option4.Text       = message.OtherTitles[index].ToString();
                                    option4.Click     += (sender, args) =>
                                    {
                                        if (message.OtherActions[index] != null)
                                        {
                                            message.OtherActions[index]();
                                        }
                                        mDialog.Dismiss();
                                    };
                                    break;

                                case 4:
                                    view5.Visibility   = ViewStates.Visible;
                                    option5.Visibility = ViewStates.Visible;
                                    option5.Text       = message.OtherTitles[index].ToString();
                                    option5.Click     += (sender, args) =>
                                    {
                                        if (message.OtherActions[index] != null)
                                        {
                                            message.OtherActions[index]();
                                        }
                                        mDialog.Dismiss();
                                    };
                                    break;

                                case 5:
                                    view6.Visibility   = ViewStates.Visible;
                                    option6.Visibility = ViewStates.Visible;
                                    option6.Text       = message.OtherTitles[index].ToString();
                                    option6.Click     += (sender, args) =>
                                    {
                                        if (message.OtherActions[index] != null)
                                        {
                                            message.OtherActions[index]();
                                        }
                                        mDialog.Dismiss();
                                    };
                                    break;

                                case 6:
                                    view7.Visibility   = ViewStates.Visible;
                                    option7.Visibility = ViewStates.Visible;
                                    option7.Text       = message.OtherTitles[index].ToString();
                                    option7.Click     += (sender, args) =>
                                    {
                                        if (message.OtherActions[index] != null)
                                        {
                                            message.OtherActions[index]();
                                        }
                                        mDialog.Dismiss();
                                    };
                                    break;

                                case 7:
                                    view8.Visibility   = ViewStates.Visible;
                                    option8.Visibility = ViewStates.Visible;
                                    option8.Text       = message.OtherTitles[index].ToString();
                                    option8.Click     += (sender, args) =>
                                    {
                                        if (message.OtherActions[index] != null)
                                        {
                                            message.OtherActions[index]();
                                        }
                                        mDialog.Dismiss();
                                    };
                                    break;
                                }
                            }

                            mDialog.Show();
                        }
                    }
                    // this is just a normal alert view :)
                    else
                    {
                        try
                        {
                            if (dialog != null)
                            {
                                dialog.Dismiss();
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.ToString());
                        }
                        builder = new AlertDialog.Builder(this);
                        dialog  = builder.Create();
                        dialog.SetTitle(message.Title);
                        dialog.SetMessage(message.Message);
                        dialog.SetCancelable(false);
                        dialog.SetButton(message.CancelTitle, (s, ev) =>
                        {
                            if (message.CancelAction != null)
                            {
                                message.CancelAction();
                            }
                            dialog.Dismiss();
                        });

                        dialog.Show();
                    }
                }
                catch (Exception ex)
                {
                }
            });
        }
Exemplo n.º 26
0
        /// <summary>
        /// Automatically connects to the first x-IMU found using the PortScanner.
        /// </summary>
        private void AutoConnect()
        {
            // Create ProgressDialog object
            autoConnectProgressDialog = new ProgressDialog(this.Handle);
            autoConnectProgressDialog.Title = "Auto Connecting";
            autoConnectProgressDialog.CancelMessage = "Cancelling...";
            autoConnectProgressDialog.Line1 = "Searching for x-IMU";
            autoConnectProgressDialog.Line3 = "Initialising x-IMU port scanner.";
            autoConnectProgressDialog.ShowDialog();
            autoConnectProgressDialog.Value = 101;     // set value >100 after show, for continuous animation.

            // Create PortScanner object
            x_IMU_API.PortScanner portScanner = new x_IMU_API.PortScanner();
            portScanner.AsyncScanProgressChanged += new x_IMU_API.PortScanner.onAsyncScanProgressChanged(portScanner_AsyncScanProgressChanged);
            portScanner.AsyncScanCompleted += new x_IMU_API.PortScanner.onAsyncScanCompleted(portScanner_AsyncScanCompleted);
            portScanner.DontGiveUp = true;
            portScanner.FirstResultOnly = true;
            portScanner.RunAsynsScan();
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
              this.CreateTabContainer("StromaDetection");
              this.TabContainer.Enabled = true;

              (new Button
              {
            Text = "execute cell core segmentation",
            Parent = this.TabContainer,
            Dock = DockStyle.Top
              }).Click += delegate
              {
            if (null == this.DisplayedImage) return;
            ProcessResult result = null;
            var progressDialog = new ProgressDialog { Message = "executing cell core segmentation", ProgressBarStyle = ProgressBarStyle.Marquee, AllowCancel = false };
            progressDialog.BackgroundTask += () =>
            {
              var segmentation = new CellCoreSegmentation();
              var executionParams = new ProcessExecutionParams(this.DisplayedImage);
              result = segmentation.Execute(executionParams);
            };
            progressDialog.CenterToScreen();
            progressDialog.ShowDialog();
            this.SetLayers(result.Layers.ToArray());
              };

              (new Button
              {
            Text = "execute threshold segmentation",
            Parent = this.TabContainer,
            Dock = DockStyle.Top
              }).Click += delegate
              {
            if (null == this.DisplayedImage) return;
            var m = new Map(this.DisplayedImage.Width, this.DisplayedImage.Height);
            using (var gp = new GrayscaleProcessor(this.DisplayedImage.Clone() as Bitmap, RgbToGrayscaleConversion.Mean))
            {
              for (var x = 0; x < this.DisplayedImage.Width; x++)
              {
            for (var y = 0; y < this.DisplayedImage.Height; y++)
            {
              m[x, y] = gp.GetPixel(x, y) < this.threshold.Value ? 1u : 0u;
            }
              }
            }
            var layer = new ConnectedComponentCollector().Execute(m);
            layer.Name = "threshold " + this.threshold.Value + " segmentation";
            var layers = this.GetLayers().ToList();
            layers.Add(layer);
            this.SetLayers(layers.ToArray());
              };

              this.threshold = new NumericUpDown
              {
            Parent = new GroupBox
            {
              Parent = this.TabContainer,
              Dock = DockStyle.Top,
              Text = "threshold",
              Height = 40
            },
            Dock = DockStyle.Fill,
            Minimum = 0,
            Maximum = 255,
            Increment = 16,
            Value = 128,
            DecimalPlaces = 0
              };

              (new Button
              {
            Text = "display edges",
            Parent = this.TabContainer,
            Dock = DockStyle.Top
              }).Click += delegate
              {
            this.SetDisplayedImage(this.edges);
              };

              (new Button
              {
            Text = "execute edge detection",
            Parent = this.TabContainer,
            Dock = DockStyle.Top
              }).Click += delegate
              {
            if (null == this.stainH || null == this.stainE) return;
            this.responseH = Filtering.ExecuteSobel(this.stainH);
            this.responseE = Filtering.ExecuteSobel(this.stainE);
            var substracted = new double[this.responseH.Size.Width, this.responseH.Size.Height];
            var substractedRange = new Range<double>();
            for (var x = 0; x < this.responseH.Size.Width; x++)
            {
              for (var y = 0; y < this.responseH.Size.Height; y++)
              {
            var value = Math.Max(0, this.responseE.Gradient[x, y] - this.responseH.Gradient[x, y]);
            substracted[x, y] = value;
            substractedRange.Add(value);
              }
            }
            this.nonMaximumSupression = Filtering.ExecuteNonMaximumSupression(substracted, this.responseE.Orientation);
            this.edges = Visualization.Visualize(this.nonMaximumSupression, Visualization.CreateColorizing(substractedRange.Maximum));
            this.SetDisplayedImage(this.edges);
              };

              (new Button
              {
            Text = "display haematoxylin",
            Parent = this.TabContainer,
            Dock = DockStyle.Top
              }).Click += delegate
              {
            this.SetDisplayedImage(this.stainH);
              };

              (new Button {
            Text = "display eosin",
            Parent = this.TabContainer,
            Dock = DockStyle.Top
              }).Click += delegate
              {
            this.SetDisplayedImage(this.stainE);
              };

              (new Button {
            Text = "display source",
            Parent = this.TabContainer,
            Dock = DockStyle.Top
              }).Click += delegate
              {
            this.SetDisplayedImage(this.source);
              };

              (new Button {
            Text = "execute deconvolution",
            Parent = this.TabContainer,
            Dock = DockStyle.Top
              }).Click += delegate
              {
            if (null == this.DisplayedImage) return;
            this.source = this.DisplayedImage;
            var gpE = new ColorDeconvolution().Get2ndStain(this.DisplayedImage, ColorDeconvolution.KnownStain.HaematoxylinEosin);
            gpE.Dispose();
            this.stainE = gpE.Bitmap;
            var gpH = new ColorDeconvolution().Get1stStain(this.DisplayedImage, ColorDeconvolution.KnownStain.HaematoxylinEosin);
            gpH.Dispose();
            this.stainH = gpH.Bitmap;
            this.SetDisplayedImage(this.stainE);
              };
        }
Exemplo n.º 28
0
        private void ExportData()
        {
            try
            {
                List <Department> list = null;

                var loadTask = ServiceProxyFactory.LifeTime(async factory =>
                {
                    var service = factory.Create <DepartmentMasterClient>();
                    DepartmentsResult result = await service.GetDepartmentAndStaffAsync(SessionKey, CompanyId);

                    if (result.ProcessResult.Result)
                    {
                        list = result.Departments;
                    }
                });
                ProgressDialog.Start(ParentForm, Task.WhenAll(loadTask), false, SessionKey);

                if (!list.Any())
                {
                    ShowWarningDialog(MsgWngNoExportData);
                    return;
                }

                string serverPath = GetServerPath();

                if (!Directory.Exists(serverPath))
                {
                    serverPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                }

                var filePath = string.Empty;
                var fileName = $"請求部門マスター{DateTime.Today:yyyyMMdd}.csv";
                if (!ShowSaveExportFileDialog(serverPath, fileName, out filePath))
                {
                    return;
                }

                var definition = new DepartmentFileDefinition(
                    new DataExpression(ApplicationControl));
                var exporter = definition.CreateExporter();
                exporter.UserId      = Login.UserId;
                exporter.UserCode    = Login.UserCode;
                exporter.CompanyId   = CompanyId;
                exporter.CompanyCode = Login.CompanyCode;

                ProgressDialog.Start(ParentForm, (cancel, progress) =>
                {
                    return(exporter.ExportAsync(filePath, list, cancel, progress));
                }, true, SessionKey);

                if (exporter.Exception != null)
                {
                    NLogHandler.WriteErrorLog(this, exporter.Exception, SessionKey);
                    ShowWarningDialog(MsgErrExportError);
                    return;
                }

                DispStatusMessage(MsgInfFinishExport);
            }
            catch (Exception ex)
            {
                Debug.Fail(ex.ToString());
                NLogHandler.WriteErrorLog(this, ex, SessionKey);
                DispStatusMessage(MsgErrExportError);
            }
        }
Exemplo n.º 29
0
    public bool Execute(RotateDirection direction, IBrowsableItem [] items)
    {
        ProgressDialog progress_dialog = null;

        if (items.Length > 1)
            progress_dialog = new ProgressDialog (Catalog.GetString ("Rotating photos"),
                                  ProgressDialog.CancelButtonType.Stop,
                                  items.Length, parent_window);

            RotateMultiple op = new RotateMultiple (items, direction);
        int readonly_count = 0;
        bool done = false;
        int index = 0;

        while (!done) {
            if (progress_dialog != null && op.Index != -1 && index < items.Length)
                if (progress_dialog.Update (String.Format (Catalog.GetString ("Rotating photo \"{0}\""), op.Items [op.Index].Name)))
                    break;

            try {
                done = !op.Step ();
            } catch (RotateException re) {
                if (!re.ReadOnly)
                    RunGenericError (re, re.Path, re.Message);
                else
                    readonly_count++;
            } catch (GLib.GException) {
                readonly_count++;
            } catch (DirectoryNotFoundException e) {
                RunGenericError (e, op.Items [op.Index].DefaultVersionUri.LocalPath, Catalog.GetString ("Directory not found"));
            } catch (FileNotFoundException e) {
                RunGenericError (e, op.Items [op.Index].DefaultVersionUri.LocalPath, Catalog.GetString ("File not found"));
            } catch (Exception e) {
                RunGenericError (e, op.Items [op.Index].DefaultVersionUri.LocalPath);
            }
            index ++;
        }

        if (progress_dialog != null)
            progress_dialog.Destroy ();

        if (readonly_count > 0)
            RunReadonlyError (readonly_count);

        return true;
    }
Exemplo n.º 30
0
 public GetCoordinates(MainActivity activity, Context context)
 {
     this.context  = context;
     this.activity = activity;
     dialog        = new ProgressDialog(context);
 }
Exemplo n.º 31
0
        private Task <string?> DownloadWithProgress(SourceRepository sourceRepository, PackageIdentity packageIdentity)
        {
            var progressDialogText = Resources.Dialog_DownloadingPackage;

            if (packageIdentity.HasVersion)
            {
                progressDialogText = string.Format(CultureInfo.CurrentCulture, progressDialogText, packageIdentity.Id, packageIdentity.Version);
            }
            else
            {
                progressDialogText = string.Format(CultureInfo.CurrentCulture, progressDialogText, packageIdentity.Id, string.Empty);
            }

            string?description = null;
            int?   percent     = null;
            var    updated     = 0;

            var            progressDialogLock = new object();
            ProgressDialog?progressDialog     = new ProgressDialog
            {
                Text              = progressDialogText,
                WindowTitle       = Resources.Dialog_Title,
                ShowTimeRemaining = true,
                CancellationText  = "Canceling download..."
            };


            // polling for Cancel button being clicked
            var cts   = new CancellationTokenSource();
            var timer = new System.Timers.Timer(100);

            timer.Elapsed += (o, e) =>
            {
                lock (progressDialogLock)
                {
                    if (progressDialog.CancellationPending)
                    {
                        timer.Stop();
                        cts.Cancel();
                    }
                    else if (Interlocked.CompareExchange(ref updated, 0, 1) == 1)
                    {
                        progressDialog.ReportProgress(percent.GetValueOrDefault(), null, description);
                    }
                }
            };


            var tcs = new TaskCompletionSource <string?>();

            progressDialog.DoWork += (object sender, DoWorkEventArgs args) =>
            {
                var t = DoWorkAsync();
                t.Wait(cts.Token);
                tcs.TrySetResult(t.Result);
            };
            progressDialog.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs args) =>
            {
                MainWindow.Value.Activate();
            };

            progressDialog.ShowDialog(MainWindow.Value);
            timer.Start();

            async Task <string?> DoWorkAsync()
            {
                try
                {
                    var httpProgressProvider = new ProgressHttpHandlerResourceV3Provider(OnProgress);
                    var repository           = PackageRepositoryFactory.CreateRepository(sourceRepository.PackageSource, new[] { new Lazy <INuGetResourceProvider>(() => httpProgressProvider) });
                    var downloadResource     = await repository.GetResourceAsync <DownloadResource>(cts.Token).ConfigureAwait(false);

                    using (var sourceCacheContext = new SourceCacheContext()
                    {
                        NoCache = true
                    })
                    {
                        var context = new PackageDownloadContext(sourceCacheContext, Path.GetTempPath(), true);

                        using (var result = await downloadResource.GetDownloadResourceResultAsync(packageIdentity, context, string.Empty, NullLogger.Instance, cts.Token).ConfigureAwait(false))
                        {
                            if (result.Status == DownloadResourceResultStatus.Cancelled)
                            {
                                throw new OperationCanceledException();
                            }

                            if (result.Status == DownloadResourceResultStatus.NotFound)
                            {
                                throw new Exception(string.Format("Package '{0} {1}' not found", packageIdentity.Id, packageIdentity.Version));
                            }

                            var tempFilePath = Path.GetTempFileName();
                            using (var fileStream = File.OpenWrite(tempFilePath))
                            {
                                await result.PackageStream.CopyToAsync(fileStream).ConfigureAwait(false);
                            }

                            return(tempFilePath);
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    return(null);
                }
                catch (Exception exception)
                {
                    OnError(exception);
                    return(null);
                }
                finally
                {
                    timer.Stop();

                    // close progress dialog when done
                    lock (progressDialogLock)
                    {
                        progressDialog.Dispose();
                        progressDialog = null;
                    }
                }
            }

            void OnProgress(long bytesReceived, long?totalBytes)
            {
                if (totalBytes.HasValue)
                {
                    // TODO: remove ! once https://github.com/dotnet/roslyn/issues/33330 is fixed
                    percent     = (int)((bytesReceived * 100L) / totalBytes) !;
                    description = string.Format(
                        CultureInfo.CurrentCulture,
                        "Downloaded {0} of {1}...",
                        FileSizeConverter.Convert(bytesReceived, typeof(string), null, CultureInfo.CurrentCulture),
                        FileSizeConverter.Convert(totalBytes.Value, typeof(string), null, CultureInfo.CurrentCulture));
                }
                else
                {
                    percent     = null;
                    description = string.Format(
                        CultureInfo.CurrentCulture,
                        "Downloaded {0}...",
                        FileSizeConverter.Convert(bytesReceived, typeof(string), null, CultureInfo.CurrentCulture));
                }
                Interlocked.Exchange(ref updated, 1);
            }

            return(tcs.Task);
        }
Exemplo n.º 32
0
        public void StartProcess(ProgressDialog dialog, DoWorkEventArgs e)
        {
            int count = dialog.Maximum = binds.SelectMany(a => a.BindedBoards).Count(a => a.IsChecked);
            int done  = 0;

            dialog.ReportProgress(-1, null, "Экспорт данных..", null);

            InitializeExcelApplication();

            xlWorkBook = xlApp.Workbooks.Add(System.Reflection.Missing.Value);
            xlApp.ActiveWindow.DisplayGridlines = false;

            try
            {
                var xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.Item[1];
                OfficeHelper.FormatExportBoardsPage(xlWorkSheet);

                int rowNumber = 2;
                foreach (var bind in binds)
                {
                    string bindAddress             = bind.Address.FormattedAddress;
                    string bindDescription         = string.IsNullOrEmpty(bind.Description) ? bind.OriginalAddress : bind.Description;
                    System.Drawing.Color bindColor = bind.Color;

                    foreach (var board in bind.BindedBoards)
                    {
                        if (!board.IsChecked)
                        {
                            continue;
                        }

                        string poiMap = @"https://www.google.com/maps/dir/" + bind.Address.Coordinates.ToString() + @"/" + board.Location.ToString();

                        var distance = (int)(bind.Address.Coordinates.DistanceBetween(board.Location, Geocoding.DistanceUnits.Kilometers).Value * 1000);

                        xlWorkSheet.Range["A" + rowNumber].Value = board.Address.City;
                        xlWorkSheet.Range["B" + rowNumber].Value = board.Supplier;
                        xlWorkSheet.Range["C" + rowNumber].Value = board.Address.Street;
                        xlWorkSheet.Range["D" + rowNumber].Value = board.Address.StreetNumber;
                        xlWorkSheet.Range["E" + rowNumber].Value = board.Address.Description;
                        xlWorkSheet.Range["F" + rowNumber].Value = board.Type;
                        xlWorkSheet.Range["G" + rowNumber].Value = board.Size;
                        xlWorkSheet.Range["H" + rowNumber].Value = board.Side;
                        if (board.MediaParameters != null)
                        {
                            xlWorkSheet.Range["I" + rowNumber].Value = board.MediaParameters.OTS;
                            xlWorkSheet.Range["J" + rowNumber].Value = string.Format("{0:0.00}", board.MediaParameters.GRP);
                        }
                        xlWorkSheet.Range["K" + rowNumber].Value = board.SupplierCode;
                        xlWorkSheet.Range["L" + rowNumber].Value = board.ProviderID;
                        if (board.Lighting)
                        {
                            xlWorkSheet.Range["M" + rowNumber].Value = @"*";
                        }
                        if (!string.IsNullOrEmpty(board.URL_Photo))
                        {
                            xlWorkSheet.Hyperlinks.Add(Anchor: xlWorkSheet.Range["N" + rowNumber], Address: board.URL_Photo, TextToDisplay: "Фото");
                            xlWorkSheet.Range["N" + rowNumber].Font.Size = 9;
                        }
                        if (!string.IsNullOrEmpty(board.URL_Map))
                        {
                            xlWorkSheet.Hyperlinks.Add(Anchor: xlWorkSheet.Range["O" + rowNumber], Address: board.URL_Map, TextToDisplay: "Схема");
                            xlWorkSheet.Range["O" + rowNumber].Font.Size = 9;
                        }

                        xlWorkSheet.Hyperlinks.Add(Anchor: xlWorkSheet.Range["P" + rowNumber], Address: poiMap, TextToDisplay: "Карта");
                        xlWorkSheet.Range["P" + rowNumber].Font.Size = 9;

                        xlWorkSheet.Range["Q" + rowNumber].Value = distance;

                        xlWorkSheet.Range["R" + rowNumber].Value      = bindAddress;
                        xlWorkSheet.Range["S" + rowNumber].Value      = bindDescription;
                        xlWorkSheet.Range["R" + rowNumber].Font.Color = xlWorkSheet.Range["S" + rowNumber].Font.Color = System.Drawing.ColorTranslator.ToOle(bindColor);


                        rowNumber++;
                        done++;
                        dialog.ReportProgress(done, null, $"Выполнено: {done}/{count}");
                    }
                }
            }
            finally
            {
                ExitExcelApplication(false);
            }
        }
Exemplo n.º 33
0
        /// <summary>
        /// GPSボタン(アイコン)クリック
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gpsButton_Click(object sender, EventArgs e)
        {
            object[] ret;

            using (ProgressDialog sg = new ProgressDialog(new DoWorkEventHandler(GetGPS_DoWork)))
            {
                //進行状況ダイアログを表示する
                DialogResult result = sg.ShowDialog(this);

                ret = (object[])sg.Result;
            }

            if (ret != null && (bool)ret[0])
            {
                TabMessageBox.Show2(string.Format("緯度[{0}], 経度[{1}]", ret[1], ret[2]));
            }
            else
            {
                TabMessageBox.Show2("タイムアウト");
            }
        }
        private void ResolveRegister()
        {
            var adb = new IONAlertDialog(this);

            adb.SetTitle(Resource.String.register);
            var view = LayoutInflater.From(this).Inflate(Resource.Layout.dialog_portal_register, null, false);

            adb.SetView(view);
            adb.SetCancelable(true);

            var email           = view.FindViewById <EditText>(Resource.Id.email);
            var password        = view.FindViewById <EditText>(Resource.Id.password);
            var passwordConfirm = view.FindViewById <EditText>(Resource.Id.passwordConfirm);
            var icon            = view.FindViewById <ImageView>(Resource.Id.icon);

            password.TextChanged += (sender, e) => {
                if (password.Text.Equals(passwordConfirm.Text) && ion.portal.IsPasswordValid(password.Text))
                {
                    icon.SetColorFilter(Android.Graphics.Color.Green);
                    icon.SetImageBitmap(cache.GetBitmap(Resource.Drawable.ic_check));
                }
                else
                {
                    icon.SetColorFilter(Android.Graphics.Color.Red);
                    icon.SetImageBitmap(cache.GetBitmap(Resource.Drawable.ic_x));
                }
            };

            passwordConfirm.TextChanged += (sender, e) => {
                if (password.Text.Equals(passwordConfirm.Text) && ion.portal.IsPasswordValid(password.Text))
                {
                    icon.SetColorFilter(Android.Graphics.Color.Green);
                    icon.SetImageBitmap(cache.GetBitmap(Resource.Drawable.ic_check));
                }
                else
                {
                    icon.SetColorFilter(Android.Graphics.Color.Red);
                    icon.SetImageBitmap(cache.GetBitmap(Resource.Drawable.ic_x));
                }
            };

            icon.Click += (sender, e) => {
                var dialog = new IONAlertDialog(this);
                dialog.SetMessage(GetString(Resource.String.portal_error_password_invalid));
                dialog.SetCancelable(true);
                dialog.SetNegativeButton(Resource.String.cancel, (sender2, e2) => {});
                dialog.Show();
            };

            var d = adb.Show();

            view.FindViewById(Resource.Id.cancel).Click += (sender, e) => {
                d.Dismiss();
            };

            view.FindViewById(Resource.Id.register).Click += async(sender, e) => {
                if (string.IsNullOrEmpty(email.Text))
                {
                    Toast.MakeText(this, Resource.String.portal_error_email_invalid, ToastLength.Long).Show();
                    return;
                }

                if (!password.Text.Equals(passwordConfirm.Text))
                {
                    Toast.MakeText(this, Resource.String.portal_error_passwords_dont_match, ToastLength.Long).Show();
                    return;
                }

                if (!ion.portal.IsPasswordValid(password.Text))
                {
                    Toast.MakeText(this, Resource.String.portal_error_password_invalid, ToastLength.Long).Show();
                    return;
                }

                if (password.Text.Equals(passwordConfirm.Text))
                {
                    var pd = new ProgressDialog(this);
                    pd.SetTitle(Resource.String.working);
                    pd.SetMessage(GetString(Resource.String.please_wait));
                    pd.SetCancelable(false);
                    pd.Show();

                    var response = await ion.portal.RegisterUser(email.Text, password.Text);

                    if (response.success)
                    {
                        Toast.MakeText(this, Resource.String.portal_password_reset_sent, ToastLength.Long).Show();
                        this.username.Text = email.Text;
                        this.password.Text = password.Text;
                        d.Dismiss();
                    }
                    else
                    {
                        Toast.MakeText(this, response.message, ToastLength.Long).Show();
                    }

                    pd.Dismiss();
                }
                else
                {
                    Toast.MakeText(this, Resource.String.portal_error_passwords_dont_match, ToastLength.Long).Show();
                }
            };
        }
Exemplo n.º 35
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Init(Context context, string cdn = null, string downloadTitle = null, string downloadMessage = null)
        {
            if (_initialized)
            {
                return;
            }

            if (cdn != null)
            {
                CDNHost = cdn;
            }

            // do all initialization...
            var filesDir = context.FilesDir;

            _ffmpegFile = new Java.IO.File(filesDir + "/ffmpeg");

            FFMpegSource source = FFMpegSource.Get();

            await Task.Run(() =>
            {
                if (_ffmpegFile.Exists())
                {
                    try
                    {
                        if (source.IsHashMatch(System.IO.File.ReadAllBytes(_ffmpegFile.CanonicalPath)))
                        {
                            if (!_ffmpegFile.CanExecute())
                            {
                                _ffmpegFile.SetExecutable(true);
                            }
                            _initialized = true;
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($" Error validating file {ex}");
                    }

                    // file is not same...

                    // delete the file...

                    if (_ffmpegFile.CanExecute())
                    {
                        _ffmpegFile.SetExecutable(false);
                    }
                    _ffmpegFile.Delete();
                    System.Diagnostics.Debug.WriteLine($"ffmpeg file deleted at {_ffmpegFile.AbsolutePath}");
                }
            });

            if (_initialized)
            {
                // ffmpeg file exists...
                return;
            }

            if (_ffmpegFile.Exists())
            {
                _ffmpegFile.Delete();
            }

            // lets try to download
            var dialog = new ProgressDialog(context);

            dialog.SetTitle(downloadMessage ?? "Downloading Video Converter");
            //dlg.SetMessage(downloadMessage ?? "Downloading Video Converter");
            dialog.Indeterminate = false;
            dialog.SetProgressStyle(ProgressDialogStyle.Horizontal);
            dialog.SetCancelable(false);
            dialog.CancelEvent += (s, e) =>
            {
            };

            dialog.SetCanceledOnTouchOutside(false);
            dialog.Show();
            using (var c = new System.Net.Http.HttpClient())
            {
                using (var fout = System.IO.File.OpenWrite(_ffmpegFile.AbsolutePath))
                {
                    string url = source.Url;
                    var    g   = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);

                    var h = await c.SendAsync(g, System.Net.Http.HttpCompletionOption.ResponseHeadersRead);

                    var buffer = new byte[51200];

                    var s = await h.Content.ReadAsStreamAsync();

                    long total = h.Content.Headers.ContentLength.GetValueOrDefault();

                    IEnumerable <string> sl;
                    if (h.Headers.TryGetValues("Content-Length", out sl))
                    {
                        if (total == 0 && sl.Any())
                        {
                            long.TryParse(sl.FirstOrDefault(), out total);
                        }
                    }

                    int count    = 0;
                    int progress = 0;

                    dialog.Max = (int)total;

                    while ((count = await s.ReadAsync(buffer, 0, buffer.Length)) > 0)
                    {
                        await fout.WriteAsync(buffer, 0, count);

                        progress += count;

                        //System.Diagnostics.Debug.WriteLine($"Downloaded {progress} of {total} from {url}");

                        dialog.Progress = progress;
                    }
                    dialog.Hide();
                }
            }

            System.Diagnostics.Debug.WriteLine($"ffmpeg file copied at {_ffmpegFile.AbsolutePath}");

            if (!_ffmpegFile.CanExecute())
            {
                _ffmpegFile.SetExecutable(true);
                System.Diagnostics.Debug.WriteLine($"ffmpeg file made executable");
            }

            _initialized = true;
        }
Exemplo n.º 36
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            _flurryClient = new FlurryClient();


            _context = this;
            SetContentView(Resource.Layout.secondscreenactivitylayout);
            _font = Typeface.CreateFromAsset(this.Assets, "Roboto-Light.ttf");

            _achievementsListView = (ListView)FindViewById(Resource.Id.secondscr_listView);


            _refreshProjectsAndAchTextView = new TextView(this);

            _vibe = (Vibrator)this.GetSystemService(Context.VibratorService);
            _badgesCountDisplay = FindViewById <TextView>(Resource.Id.NavBar_AchievesCountTextView);


            //WrongCodeDialog
            RelativeLayout wrongCodeDialogRelativeLayout = new RelativeLayout(this);
            LayoutInflater wrongCodeDialoglayoutInflater = (LayoutInflater)BaseContext.GetSystemService(LayoutInflaterService);
            View           wrongCodeDialogView           = wrongCodeDialoglayoutInflater.Inflate(Resource.Layout.wrongcodedialoglayout, null);

            _wrongCodeDialogReadyButton = (Button)wrongCodeDialogView.FindViewById(Resource.Id.readyButton);
            _wrongCodeDialogTitle       = (TextView)wrongCodeDialogView.FindViewById(Resource.Id.textView1);
            _wrongCodeDialogMessage     = (TextView)wrongCodeDialogView.FindViewById(Resource.Id.textView2);


            wrongCodeDialogRelativeLayout.AddView(wrongCodeDialogView);
            _wrongCodeDialog = new Dialog(this, Resource.Style.FullHeightDialog);
            _wrongCodeDialog.SetTitle("");
            _wrongCodeDialog.SetContentView(wrongCodeDialogRelativeLayout);

            _wrongCodeDialogReadyButton.Click += delegate { _wrongCodeDialog.Dismiss(); };
            //

            //ProgressDialog
            RelativeLayout progressDialogRelativeLayout = new RelativeLayout(this);
            LayoutInflater progressDialoglayoutInflater = (LayoutInflater)BaseContext.GetSystemService(LayoutInflaterService);
            View           progressDialogView           = progressDialoglayoutInflater.Inflate(Resource.Layout.progressdialoglayout, null);

            _progressDialogMessage = (TextView)progressDialogView.FindViewById(Resource.Id.progressDialogMessageTextView);
            progressDialogRelativeLayout.AddView(progressDialogView);
            _progressDialog = new ProgressDialog(this, Resource.Style.FullHeightDialog);
            _progressDialog.Show();
            _progressDialog.SetContentView(progressDialogRelativeLayout);
            _progressDialog.Dismiss();
            _progressDialog.SetCanceledOnTouchOutside(false);
            //


            ImageButton profileImageButton     = FindViewById <ImageButton>(Resource.Id.secondscr_NavBar_ProfileScreenImageButton);
            ImageButton profileImageButtonFake = FindViewById <ImageButton>(Resource.Id.secondscr_NavBar_ProfileScreenImageButtonFake);

            ImageButton refreshImageButton     = FindViewById <ImageButton>(Resource.Id.secondscr_NavBar_RefreshImageButton);
            ImageButton refreshImageButtonFake = FindViewById <ImageButton>(Resource.Id.secondscr_NavBar_RefreshImageButtonFake);


            _badgesCountDisplay.Text      = AppInfo._badgesCount.ToString();
            profileImageButtonFake.Click += delegate
            {
                if (!_badgePopupWindow.IsShowing)
                {
                    _vibe.Vibrate(50); profileImageButton.StartAnimation(_buttonClickAnimation); StartActivity(typeof(ProfileActivity));
                }
            };

            refreshImageButtonFake.Click += delegate
            {
                if (!_badgePopupWindow.IsShowing)
                {
                    _vibe.Vibrate(50);
                    if (AppInfo.IsLocaleRu)
                    {
                        _progressDialogMessage.Text = "ќбновление...";
                    }
                    else
                    {
                        _progressDialogMessage.Text = "Refreshing...";
                    }
                    _progressDialog.Show();
                    refreshImageButton.StartAnimation(_buttonClickAnimation);
                    OnBadgeListRefresh();
                }
            };



            //.............................................................................
            _refreshAchTextView = new TextView(this);
            _badgePopupWindow   = new PopupWindow(this);
            _vibe = (Vibrator)this.GetSystemService(Context.VibratorService);
            _inactiveListButton = FindViewById <Button>(Resource.Id.secondscr_inactiveListButton);
            _inactiveAllButton  = FindViewById <Button>(Resource.Id.secondscr_inactiveAllButton);


            _inactiveAllButton.Visibility  = ViewStates.Gone;
            _inactiveListButton.Visibility = ViewStates.Gone;

            _buttonClickAnimation          = AnimationUtils.LoadAnimation(this, global::Android.Resource.Animation.FadeIn);
            _fadeoutClickAnimation         = AnimationUtils.LoadAnimation(this, global::Android.Resource.Animation.FadeOut);
            _categoryViewRelativeLayout    = FindViewById <RelativeLayout>(Resource.Id.secondscr_categrowrelativeLayout);
            _subcategoryViewRelativeLayout = FindViewById <RelativeLayout>(Resource.Id.secondscr_projectsrelativeLayout);

            GetCategoryView();
            GetProjectsView();
            GetAchievementsView();
            GetActivationDialog();

            _refreshProjectsAndAchTextView.TextChanged += new EventHandler <Android.Text.TextChangedEventArgs>(_refreshProjectsAndAchTextView_TextChanged);
            _refreshAchTextView.TextChanged            += new EventHandler <Android.Text.TextChangedEventArgs>(_refreshAchTextView_TextChanged);
            _subcategoryViewRelativeLayout.Click       += new EventHandler(_subcategoryViewRelativeLayout_Click);
            _inactiveListButton.Click        += new EventHandler(_inactiveListButton_Click);
            _inactiveAllButton.Click         += new EventHandler(_inactiveAllButton_Click);
            _achievementsListView.ItemClick  += new EventHandler <AdapterView.ItemClickEventArgs>(achievementsListView_ItemClick);
            _categoriesListView.ItemClick    += new EventHandler <AdapterView.ItemClickEventArgs>(_categoriesListView_ItemClick);
            _subcategoriesListView.ItemClick += new EventHandler <AdapterView.ItemClickEventArgs>(_subcategoriesListView_ItemClick);

            _categoryViewRelativeLayout.Click += new EventHandler(_categoryViewRelativeLayout_Click);
        }
Exemplo n.º 37
0
        private void SignUpButtonOnClick(object sender, EventArgs args)
        {
            new Thread(new ThreadStart(() =>
            {
                XUserMethod userMethod  = new XUserMethod();
                ProgressDialog progress = null;

                RunOnUiThread(() =>
                {
                    progress = ProgressDialog.Show(
                        this,
                        Resources.GetString(Resource.String.please_wait),
                        Resources.GetString(Resource.String.please_wait),
                        true,
                        false
                        );
                });

                string username       = FindViewById <EditText>(Resource.Id.edit_text_email_address).Text;
                string password       = FindViewById <EditText>(Resource.Id.edit_text_password).Text;
                string passwordRetype = FindViewById <EditText>(Resource.Id.edit_text_repeat_password).Text;

                if (username.Length == 0 || password.Length == 0)
                {
                    new AlertDialog.Builder(this)
                    .SetTitle(Resource.String.error)
                    .SetMessage(Resource.String.fill_all_fields)
                    .SetPositiveButton(Resource.String.confirm_dialog_ok, delegate { })
                    .Show();
                    return;
                }

                if (password.Length < 6)
                {
                    new AlertDialog.Builder(this)
                    .SetTitle(Resource.String.error)
                    .SetMessage(Resource.String.password_too_short)
                    .SetPositiveButton(Resource.String.confirm_dialog_ok, delegate { })
                    .Show();
                    return;
                }

                if (password != passwordRetype)
                {
                    new AlertDialog.Builder(this)
                    .SetTitle(Resource.String.error)
                    .SetMessage(Resource.String.passwords_dont_match)
                    .SetPositiveButton(Resource.String.confirm_dialog_ok, delegate { })
                    .Show();
                    return;
                }

                userMethod.Register(username, password);

                RunOnUiThread(() =>
                {
                    progress.Hide();
                    if (!userMethod.IsRegisterSuccessful)
                    {
                        new AlertDialog.Builder(this)
                        .SetTitle(Resource.String.error)
                        .SetMessage(Resource.String.register_failed)
                        .SetPositiveButton(Resource.String.confirm_dialog_ok, delegate { })
                        .Show();
                    }
                    else
                    {
                        new AlertDialog.Builder(this)
                        .SetTitle(Resource.String.message)
                        .SetMessage(Resource.String.register_successful)
                        .SetPositiveButton(Resource.String.confirm_dialog_ok, delegate { Finish(); })
                        .SetCancelable(false)
                        .Show();
                    }
                });
            })).Start();
        }
Exemplo n.º 38
0
        private void HandleResponse(object sender, Gtk.ResponseArgs args)
        {
            int  size          = 0;
            bool UserCancelled = false;
            bool rotate        = true;

            // Lets remove the mail "create mail" dialog
            Dialog.Destroy();

            if (args.ResponseId != Gtk.ResponseType.Ok)
            {
                return;
            }
            ProgressDialog progress_dialog = null;

            progress_dialog = new ProgressDialog(Catalog.GetString("Preparing email"),
                                                 ProgressDialog.CancelButtonType.Stop,
                                                 selection.Count,
                                                 parent_window);

            size = GetScaleSize();             // Which size should we scale to. 0 --> Original

            // evaluate mailto command and define attachment args for cli
            System.Text.StringBuilder attach_arg = new System.Text.StringBuilder();
            switch (Preferences.Get <string> (Preferences.GNOME_MAILTO_COMMAND))
            {
            case "thunderbird %s":
            case "mozilla-thunderbird %s":
            case "seamonkey -mail -compose %s":
            case "icedove %s":
                attach_arg.Append(",");
                break;

            case "kmail %s":
                attach_arg.Append(" --attach ");
                break;

            default:                      //evolution falls into default, since it supports mailto uri correctly
                attach_arg.Append("&attach=");
                break;
            }

            rotate = rotate_check.Active;              // Should we automatically rotate original photos.
            Preferences.Set(Preferences.EXPORT_EMAIL_ROTATE, rotate);

            // Initiate storage for temporary files to be deleted later
            tmp_paths = new System.Collections.ArrayList();

            // Create a tmp directory.
            tmp_mail_dir = System.IO.Path.GetTempFileName();                    // Create a tmp file
            System.IO.File.Delete(tmp_mail_dir);                                // Delete above tmp file
            System.IO.Directory.CreateDirectory(tmp_mail_dir);                  // Create a directory with above tmp name

            System.Text.StringBuilder mail_attach = new System.Text.StringBuilder();

            FilterSet filters = new FilterSet();

            if (size != 0)
            {
                filters.Add(new ResizeFilter((uint)size));
            }
            else if (rotate)
            {
                filters.Add(new OrientationFilter());
            }
            filters.Add(new UniqueNameFilter(tmp_mail_dir));


            for (int i = 0; i < selection.Count; i++)
            {
                Photo photo = selection [i] as Photo;
                if ((photo != null) && (!UserCancelled))
                {
                    if (progress_dialog != null)
                    {
                        UserCancelled = progress_dialog.Update(String.Format
                                                                   (Catalog.GetString("Exporting picture \"{0}\""), photo.Name));
                    }

                    if (UserCancelled)
                    {
                        break;
                    }

                    try {
                        // Prepare a tmp_mail file name
                        FilterRequest request = new FilterRequest(photo.DefaultVersionUri);

                        filters.Convert(request);
                        request.Preserve(request.Current);

                        mail_attach.Append(attach_arg.ToString() + request.Current.ToString());

                        // Mark the path for deletion
                        tmp_paths.Add(request.Current.LocalPath);
                    } catch (Exception e) {
                        Console.WriteLine("Error preparing {0}: {1}", selection[photo_index].Name, e.Message);
                        HigMessageDialog md = new HigMessageDialog(parent_window,
                                                                   DialogFlags.DestroyWithParent,
                                                                   MessageType.Error,
                                                                   ButtonsType.Close,
                                                                   Catalog.GetString("Error processing image"),
                                                                   String.Format(Catalog.GetString("An error occured while processing \"{0}\": {1}"), selection[photo_index].Name, e.Message));
                        md.Run();
                        md.Destroy();
                        UserCancelled = true;
                    }
                }
            }             // foreach

            if (progress_dialog != null)
            {
                progress_dialog.Destroy();                  // No need to keep this window
            }
            if (UserCancelled)
            {
                DeleteTempFile();
            }
            else
            {
                // Send the mail :)
                string mail_subject = Catalog.GetString("my photos");
                switch (Preferences.Get <string> (Preferences.GNOME_MAILTO_COMMAND))
                {
                // openSuSE
                case "thunderbird %s":
                    System.Diagnostics.Process.Start("thunderbird", " -compose \"subject=" + mail_subject + ",attachment='" + mail_attach + "'\"");
                    break;

                case "icedove %s":
                    System.Diagnostics.Process.Start("icedove", " -compose \"subject=" + mail_subject + ",attachment='" + mail_attach + "'\"");
                    break;

                case "mozilla-thunderbird %s":
                    System.Diagnostics.Process.Start("mozilla-thunderbird", " -compose \"subject=" + mail_subject + ",attachment='" + mail_attach + "'\"");
                    break;

                case "seamonkey -mail -compose %s":
                    System.Diagnostics.Process.Start("seamonkey", " -mail -compose \"subject=" + mail_subject + ",attachment='" + mail_attach + "'\"");
                    break;

                case "kmail %s":
                    System.Diagnostics.Process.Start("kmail", "  --composer --subject \"" + mail_subject + "\"" + mail_attach);
                    break;

                default:
                    GnomeUtil.UrlShow("mailto:?subject=" + System.Web.HttpUtility.UrlEncode(mail_subject) + mail_attach);
                    break;
                }

                // Check if we have any temporary files to be deleted
                if (tmp_paths.Count > 0)
                {
                    // Fetch timeout value from preferences. In seconds. Needs to be multiplied with 1000 to get msec
                    uint delete_timeout;
                    delete_timeout = (uint)(Preferences.Get <int> (Preferences.EXPORT_EMAIL_DELETE_TIMEOUT_SEC));
                    delete_timeout = delete_timeout * 1000;                     // to get milliseconds.

                    // Start a timer and when it occurs, delete the temp files.
                    GLib.Timeout.Add(delete_timeout, new GLib.TimeoutHandler(DeleteTempFile));
                }
            }
        }
Exemplo n.º 39
0
 /// <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;
 }
Exemplo n.º 40
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            Typeface tf = Typeface.CreateFromAsset(Assets, "Fonts/ROBOTO-LIGHT.TTF");

            this.RequestWindowFeature(WindowFeatures.NoTitle);
            SetContentView(Resource.Layout.Main_Search_A);
            StartSetup();
            _fab             = FindViewById <Fab> (Resource.Id.btnOpenCreateProjectPopUp);
            _fab.FabColor    = Color.ParseColor("#3597d4");
            _fab.FabDrawable = Resources.GetDrawable(Resource.Drawable.CreateProject);
            _fab.Show();
            prefs     = PreferenceManager.GetDefaultSharedPreferences(this);
            editor    = prefs.Edit();
            projectid = prefs.GetLong("ProjectID", 0);
            long empid = prefs.GetLong("EmpID", 5);

            EmpID      = prefs.GetLong("EmpID", 0);
            UserType   = prefs.GetLong("UserType", 1);
            UserPlan   = prefs.GetString("UserPlan", "");
            IsInternal = prefs.GetLong("IsInternal", 0);
            if (IsInternal == 1)
            {
                _fab.Visibility = ViewStates.Gone;
            }
            else
            {
                _fab.Visibility = ViewStates.Visible;
            }
            _fab.Click += delegate {
                if (UserType == 1)
                {
                    OpenInAppPurchasePopUp();
                }
                else
                {
                    showcreateprojectdialog();
                }
            };
            WebService objime = new WebService();

            projectloadingdialog = ProgressDialog.Show(this, "Loading", "Please wait.....");
            objime.ProjectListAsync("", empid.ToString());
            objime.ProjectListCompleted += getempxml;
            //	listView=listView = FindViewById<ListView>(Resource.Id.List);
            if (IMApplication.player != null)
            {
                IMApplication.player.Stop();
                IMApplication.player = null;
            }
            ImageView Cam1 = FindViewById <ImageView> (Resource.Id.imgSearchBack);
            ImageView imgDeleteVoiceSearch = FindViewById <ImageView> (Resource.Id.imgDeleteVoiceSearch);
            ImageView imgVoiceSearch       = FindViewById <ImageView> (Resource.Id.imgVoiceSearch);
            EditText  txtsearchproject     = FindViewById <EditText> (Resource.Id.txtsearchproject);

            listView                = FindViewById <ListView> (Resource.Id.List);
            listView.ItemClick     += OnListItemClick;
            listView.ItemLongClick += DeleteProject;
            db = this.OpenOrCreateDatabase("ImInventory", FileCreationMode.Private, null);
            txtsearchproject.TextChanged += delegate {
                int projectidcolumn;
                int ProjectID;

                string           text = txtsearchproject.Text;
                ICursor          c1   = db.RawQuery("SELECT * FROM " + "tbl_Inventory WHERE EmpID = " + empid + " AND (ItemDescription like '%" + text + "%' OR BarCodeNumber like '%" + text + "%') GROUP BY ProjectName ORDER BY  ID  ", null);
                var              projectitemsitems         = filterdtableItems;
                List <TableItem> serceitemsbyprojectidlist = new List <TableItem>();
                if (c1.Count > 0)
                {
                    projectidcolumn = c1.GetColumnIndex("ProjectID");
                    c1.MoveToFirst();
                    if (c1 != null)
                    {
                        // Loop through all Results
                        do
                        {
                            ProjectID = c1.GetInt(projectidcolumn);
                            List <TableItem> serceitemsbyprojectid = projectitemsitems.Where(x => x.ProjectID == Convert.ToString(ProjectID)).ToList();
                            serceitemsbyprojectidlist = serceitemsbyprojectidlist.Concat(serceitemsbyprojectid).ToList();
                        }while (c1.MoveToNext());
                    }
                }

                if (text.Trim() != "")
                {
                    imgVoiceSearch.Visibility       = ViewStates.Gone;
                    imgDeleteVoiceSearch.Visibility = ViewStates.Visible;
                    List <TableItem> serceitemsbyprojectname = projectitemsitems.Where(x => x.Projectname.ToLower().Contains(text.Trim().ToLower())).ToList();
                    List <TableItem> serceitemsbyclientname  = projectitemsitems.Where(x => x.ClientName.ToLower().Contains(text.Trim().ToLower())).ToList();
                    projectitemsitems = serceitemsbyprojectname.Concat(serceitemsbyclientname).ToList();
                    projectitemsitems = projectitemsitems.Concat(serceitemsbyprojectidlist).ToList();
                    projectitemsitems = projectitemsitems.OrderBy(x => x.ProjectID).ToList();
                    var projectitemsitem = projectitemsitems.GroupBy(x => new { x.ProjectID }).OrderBy(g => g.Key.ProjectID).ThenBy(g => g.Key.ProjectID).ToList();
                    projectitemsitems = new List <TableItem>();
                    foreach (var group in projectitemsitem)
                    {
                        List <TableItem> cps = group.ToList();
                        projectitemsitems = projectitemsitems.Concat(group).ToList();
                    }
                    tableItems = projectitemsitems;
                }
                else
                {
                    imgVoiceSearch.Visibility       = ViewStates.Visible;
                    imgDeleteVoiceSearch.Visibility = ViewStates.Gone;
                    projectitemsitems = filterdtableItems;
                }

                listView.Adapter = new ProjectScreenAdapter(this, projectitemsitems);
            };

            imgDeleteVoiceSearch.Click += delegate {
                listView = FindViewById <ListView> (Resource.Id.List);
                imgVoiceSearch.Visibility       = ViewStates.Visible;
                imgDeleteVoiceSearch.Visibility = ViewStates.Gone;
                txtsearchproject.SetText("", TextView.BufferType.Editable);
                //listView = FindViewById<ListView>(Resource.Id.List);
                listView.Adapter = new ProjectScreenAdapter(this, filterdtableItems);
                tableItems       = filterdtableItems;
                //listView.ItemClick += OnListItemClick;
            };
            Cam1.Click += delegate {
                this.Finish();
                //StartActivity (typeof(Main));
            };
        }
Exemplo n.º 41
0
    protected void OnSearchClicked(object o, EventArgs args)
    {
        searchEngine = (SearchEngine)searchEngines [comboBoxSearchEngine.Active];

        if (entryTitle.Text.Trim().Equals("")) {
            string message = (Mono.Posix.Catalog.GetString ("You must write something to search."));

            MessageDialog dialog = new MessageDialog (null,
                    DialogFlags.Modal | DialogFlags.DestroyWithParent,
                    MessageType.Warning,
                    ButtonsType.Close,
                    message);
            dialog.Run ();
            dialog.Destroy ();

        }
        else {
            progressDialog = new ProgressDialog(searchEngine.Name);
            progressDialog.ShowAll();
            progressDialog.Response += OnProgressDialogResponse;

            thread = new Thread(new ThreadStart (doQuery));
            notify = new ThreadNotify (new ReadyEvent (CreateSelectionDialog));

            thread.Start();
        }
    }
Exemplo n.º 42
0
        private async Task OnActivatePresetCommand(Preset preset)
        {
            using (var dialog = new ProgressDialog(true))
            {
                _ = dialog.OpenAsync();

                // Deactivate all other presets
                foreach (var other in Presets.Where(x => x.Name != preset.Name))
                {
                    if (other.IsActive)
                    {
                        _logger.Info($"Deactivating preset {preset.Name}");

                        try
                        {
                            await _presetManager.DeactivatePresetAsync(_game.InstalledLocation, other);
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                            _logger.Error(ex);
                        }

                        other.IsActive = false;
                    }
                }

                // If preset was activated
                if (preset.IsActive)
                {
                    // If binaries are missing, add them
                    if (_configurationManager.Settings.ManageBinaries &&
                        _gameService.VerifyBinaries(Paths.GetBinariesBackupDirectory(_game.Module), _game.Binaries) &&
                        !_gameService.VerifyBinaries(_game.InstalledLocation, _game.Binaries))
                    {
                        try
                        {
                            _logger.Info($"Copying binaries");
                            _gameService.CopyBinaries(Paths.GetBinariesBackupDirectory(_game.Module), _game.InstalledLocation, _game.Binaries);
                        }
                        catch (IOException ex)
                        {
                            _logger.Warn(ex.Message);
                            await new MessageDialog(Strings.ERROR_MAKE_SURE_THE_GAME_IS_NOT_RUNNING_AND_TRY_AGAIN).OpenAsync();

                            preset.IsActive = false;
                            return;
                        }
                    }

                    // Activate preset
                    try
                    {
                        _logger.Info($"Activating preset {preset.Name}");
                        await _presetManager.ActivatePresetAsync(_game.InstalledLocation, preset);
                    }
                    catch (IOException ex)
                    {
                        _logger.Error(ex);
                        await new MessageDialog(Strings.ERROR_PRESET_COULD_NOT_BE_ACTIVATED).OpenAsync();

                        preset.IsActive = false;
                        await OnActivatePresetCommand(preset);

                        return;
                    }

                    _eventAggregator.GetEvent <ShowSnackbarMessageEvent>().Publish($"{preset.Name} {Strings.PRESET_ACTIVATED}");
                }
                // If preset was deactivated
                else
                {
                    // If managing binaries, remove them from game dir
                    if (_configurationManager.Settings.ManageBinaries)
                    {
                        try
                        {
                            _logger.Info($"Deleting binaries");

                            _gameService.DeleteBinaries(_game.InstalledLocation, _game.Binaries);
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                            _logger.Warn(ex.Message);
                            await new MessageDialog(Strings.ERROR_MAKE_SURE_THE_GAME_IS_NOT_RUNNING_AND_TRY_AGAIN).OpenAsync();

                            preset.IsActive = true;
                            return;
                        }
                    }

                    // Deactivate preset
                    _logger.Info($"Deactivating preset {preset.Name}");
                    await _presetManager.DeactivatePresetAsync(_game.InstalledLocation, preset);

                    _eventAggregator.GetEvent <ShowSnackbarMessageEvent>().Publish(Strings.NO_PRESET_ACTIVE);
                }

                // Save active preset
                if (preset.IsActive)
                {
                    _game.Settings.ActivePreset = preset.Name;
                }
                else
                {
                    _game.Settings.ActivePreset = string.Empty;
                }

                var configManager = new ConfigurationManager <GameSettings>(_game.Settings);
                configManager.SaveSettings();
            }
        }
Exemplo n.º 43
0
        /// <summary>
        /// Button Click event disables form control and starts binary file conversion in new thread.
        /// </summary>
        private void button_convertBinaryFileConvert_Click(object sender, EventArgs e)
        {
            // Error if file not exist
            if (!File.Exists(textBox_convertBinaryFileFilePath.Text))
            {
                MessageBox.Show("File does not exist.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Disable SD card form controls
            textBox_convertBinaryFileFilePath.Enabled = false;
            button_convertBinaryFileBrowse.Enabled = false;
            button_convertBinaryFileConvert.Enabled = false;
            button_convertBinaryFileConvert.Text = "Converting...";

            // Create process dialog
            binaryFileConverterProgressDialog = new ProgressDialog(this.Handle);
            binaryFileConverterProgressDialog.Title = "Converting Binary File";
            binaryFileConverterProgressDialog.CancelMessage = "Cancelling...";
            binaryFileConverterProgressDialog.Line1 = "Converting to binary file to CSV files";
            binaryFileConverterProgressDialog.Line3 = "Initialising x-IMU file reader.";
            binaryFileConverterProgressDialog.ShowDialog();
            binaryFileConverterProgressDialog.Value = 0;

            // Create file converter objects
            binaryFileConverterCSVfileWriter = new x_IMU_API.CSVfileWriter(Path.GetDirectoryName(textBox_convertBinaryFileFilePath.Text) + "\\" + Path.GetFileNameWithoutExtension(textBox_convertBinaryFileFilePath.Text));
            x_IMU_API.xIMUfile xIMUfile = new x_IMU_API.xIMUfile(textBox_convertBinaryFileFilePath.Text);
            xIMUfile.xIMUdataRead += new x_IMU_API.xIMUfile.onxIMUdataRead(xIMUfile_xIMUdataRead);
            xIMUfile.AsyncReadProgressChanged += new x_IMU_API.xIMUfile.onAsyncReadProgressChanged(xIMUfile_AsyncReadProgressChanged);
            xIMUfile.AsyncReadCompleted += new x_IMU_API.xIMUfile.onAsyncReadCompleted(xIMUfile_AsyncReadCompleted);
            xIMUfile.RunAnsycRead();
        }
Exemplo n.º 44
0
 public RegistrationInBackGround(RegistrationModel reg, Activity activity)
 {
     this.reg      = reg;
     this.activity = activity;
     p             = ProgressDialog.Show(activity, "", "Please wait...");
 }
Exemplo n.º 45
0
		private void Finish()
		{
			Debug.WriteLine("ProgressDialogHandler:Finish");

			_progressDialog.ForceClose();
			_progressDialog = null;
			if (Finished != null)
			{
				Finished.BeginInvoke(this, null, null, null); //jh changed this from Invoke()
				// Finished.Invoke(this, null);//jh changed this from Invoke()
			}

			/* if (ParentFormIsClosing)
			{
				_parentForm.Close();
			}
			else
			*/
			{
				_currentCommand.Enabled = true;
			}
		}
        public async void CalculateVolume()
        {
            // Update the viewmodel with values
            await FrameworkApplication.SetCurrentToolAsync("esri_mapping_exploreTool");

            // Check for an active mapview
            if (MapView.Active == null)
            {
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("No MapView currently active. Exiting...", "Info");
                return;
            }

            // Prompt before proceeding with calculation work
            var response = ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Save edits and calculate volume on selected features?", "Calculate Volume", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Question);

            if (response == MessageBoxResult.No)
            {
                return;
            }

            // Save edits for reading by GP Tool
            await Project.Current.SaveEditsAsync();

            try
            {
                await QueuedTask.Run((Func <Task>)(async() =>
                {
                    var featLayer = MapView.Active.Map.FindLayers("Clip_Polygon_Asphalt").FirstOrDefault() as FeatureLayer;

                    // Get the selected records, and check/exit if there are none:
                    var featSelectionOIDs = featLayer.GetSelection().GetObjectIDs();
                    if (featSelectionOIDs.Count == 0)
                    {
                        ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("No records selected for layer, " + featLayer.Name + ". Exiting...", "Info");
                        return;
                    }

                    // Ensure value for reference plane direction combobox
                    else if (SceneCalcVM.ReferencePlaneDirection == string.Empty)
                    {
                        ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Choose the reference plane direction for volume calculation. Exiting...", "Value Needed");
                        return;
                    }

                    // Ensure there is a valid reference plane height/elevation value for all selected records
                    RowCursor cursorPolygons = featLayer.GetSelection().Search(null);
                    while (cursorPolygons.MoveNext())
                    {
                        using (Row currentRow = cursorPolygons.Current)
                        {
                            // Get values for dockpane
                            if (currentRow["PlaneHeight"] == null || Convert.ToDouble(currentRow["PlaneHeight"]) == 0)
                            {
                                string currentObjectID = Convert.ToString(currentRow["ObjectID"]);
                                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Empty or invalid Plane Height value for polygon ObjectID: " + currentObjectID + ". Exiting...", "Value Needed");
                                return;
                            }
                        }
                    }

                    // Get the name of the attribute to update, and the value to set:
                    double refPlaneElevation = SceneCalcVM.ReferencePlaneElevation;
                    string refPlaneDirection = SceneCalcVM.ReferencePlaneDirection;

                    // Start progress dialog
                    var progDialog = new ProgressDialog("Calculating Volume");
                    var progSource = new ProgressorSource(progDialog);
                    progDialog.Show();

                    // Prepare for run of GP tool -- Get the path to the LAS point layer
                    string surfaceLASDataset = "Asphalt3D_132_point_cloud.las";
                    var inspector            = new ArcGIS.Desktop.Editing.Attributes.Inspector(true);
                    inspector.Load(featLayer, featSelectionOIDs);
                    inspector["PlaneDirection"]    = refPlaneDirection;
                    inspector["DateOfCapture"]     = DateTime.Today;
                    inspector["ElevationMeshFile"] = "Asphalt3D_132_3d_mesh.slpk";
                    inspector["PointCloudFile"]    = surfaceLASDataset;

                    var editOp  = new EditOperation();
                    editOp.Name = "Edit " + featLayer.Name + ", " + Convert.ToString(featSelectionOIDs.Count) + " records.";
                    editOp.Modify(inspector);
                    await editOp.ExecuteAsync();
                    await Project.Current.SaveEditsAsync();

                    // Get the path to the layer's feature class
                    string infc = featLayer.Name;
                    // Place parameters into an array
                    var parameters = Geoprocessing.MakeValueArray(surfaceLASDataset, infc, "PlaneHeight", refPlaneDirection);
                    // Place environment settings in an array, in this case, OK to over-write
                    var environments = Geoprocessing.MakeEnvironmentArray(overwriteoutput: true);
                    // Execute the GP tool with parameters
                    var gpResult = await Geoprocessing.ExecuteToolAsync("PolygonVolume_3d", parameters, environments);
                    // Save edits again
                    await Project.Current.SaveEditsAsync();

                    // var selFeatures = featLayer.GetSelection().GetCount();
                    RowCursor cursorPolygons2 = featLayer.GetSelection().Search(null);

                    double totalVolumeValue  = 0;
                    double totalAreaValue    = 0;
                    double totalWeightInTons = 0;
                    double currentVolume;
                    double currentSArea;
                    double currentWeightInTons;
                    long currentOID;

                    while (cursorPolygons2.MoveNext())
                    {
                        using (Row currentRow = cursorPolygons2.Current)
                        {
                            // Get values for dockpane
                            currentOID = currentRow.GetObjectID();
                            // Convert volume in cubic meters from source data to cubic feet:
                            currentVolume = Convert.ToDouble(currentRow["Volume"]) * 35.3147;
                            // Convert surface area value from square meters from source data to square feet:
                            currentSArea = Convert.ToDouble(currentRow["SArea"]) * 10.7639;
                            // Calculate estimated weight in tons = (volume in square foot * 103.7 pounds per square foot) / 2000 pounds per ton
                            currentWeightInTons = (currentVolume * 103.7) / 2000;

                            // Update the new cubic feet and square feet values for the feature:
                            inspector.Load(featLayer, currentOID);
                            inspector["Volume"]          = currentVolume;
                            inspector["SArea"]           = currentSArea;
                            inspector["EstWeightInTons"] = currentWeightInTons;
                            await inspector.ApplyAsync();

                            // Combine values for display of total volume and surface area values in the dockpane:
                            totalVolumeValue  += currentVolume;
                            totalAreaValue    += currentSArea;
                            totalWeightInTons += currentWeightInTons;
                        }
                    }

                    // Apply the values and refresh selection update
                    await Project.Current.SaveEditsAsync();
                    FeatureSelectionChanged();
                    // Close progress dialog
                    progDialog.Hide();
                    progDialog.Dispose();
                }));
            }
            catch (Exception exc)
            {
                // Catch any exception found and display a message box.
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Exception caught while trying to perform update: " + exc.Message);
                return;
            }
        }
        /// <summary>
        /// Creates a report config with user's choices
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_CreateReport_Click(object sender, EventArgs e)
        {
            reportHandler.Name = "Model report";

            reportHandler.AddRanges = CB_AddRanges.Checked;
            reportHandler.AddRangesDetails = CB_AddRangesDetails.Checked;

            reportHandler.AddEnumerations = CB_AddEnumerations.Checked;
            reportHandler.AddEnumerationsDetails = CB_AddEnumerationsDetails.Checked;

            reportHandler.AddStructures = CB_AddStructures.Checked;
            reportHandler.AddStructuresDetails = CB_AddStructuresDetails.Checked;

            reportHandler.AddCollections = CB_AddCollections.Checked;
            reportHandler.AddCollectionsDetails = CB_AddCollectionsDetails.Checked;

            reportHandler.AddFunctions = CB_AddFunctions.Checked;
            reportHandler.AddFunctionsDetails = CB_AddFunctionsDetails.Checked;

            reportHandler.AddProcedures = CB_AddProcedures.Checked;
            reportHandler.AddProceduresDetails = CB_AddProceduresDetails.Checked;

            reportHandler.AddVariables = CB_AddVariables.Checked;
            reportHandler.AddVariablesDetails = CB_AddVariablesDetails.Checked;
            reportHandler.InOutFilter = CB_InOutFilter.Checked;

            reportHandler.AddRules = CB_AddRules.Checked;
            reportHandler.AddRulesDetails = CB_AddRulesDetails.Checked;

            Hide();

            ProgressDialog dialog = new ProgressDialog("Generating report", reportHandler);
            dialog.ShowDialog(Owner);
        }
Exemplo n.º 48
0
        private void btnSend_Click(object sender, EventArgs e)
        {
            if (!Main.Current.CheckNetworkStatus())
            {
                return;
            }

            m_progressDialog = new ProgressDialog("Upload ..."
                                                  , delegate
            {
                string _ids = "[";

                //Upload Image
                if (imageListView.SelectedItems.Count == 0)
                {
                    return("*ERROR*");
                }

                ImageListViewItem _imgItem = imageListView.SelectedItems[0];

                string _imageFile = _imgItem.FileName;
                string _imageURL  = _imgItem.Tag.ToString();

                try
                {
                    MR_attachments_upload _uf = Main.Current.RT.REST.File_UploadFile(_imageURL, _imageFile, "", true);

                    if (_uf == null)
                    {
                        return("*ERROR*");
                    }

                    _ids += "\"" + _uf.object_id + "\"" + ",";
                }
                catch
                {
                    return("*ERROR*");
                }

                m_progressDialog.RaiseUpdateProgress(50);

                if (m_progressDialog.WasCancelled)
                {
                    return("*ERROR*");
                }

                try
                {
                    MR_attachments_upload _uf = Main.Current.RT.REST.File_UploadFile("_RichText_", MyParent.GetHtmlFile(), "", false);

                    if (_uf == null)
                    {
                        return("*ERROR*");
                    }

                    _ids += "\"" + _uf.object_id + "\"" + ",";
                }
                catch
                {
                    return("*ERROR*");
                }

                _ids  = _ids.Substring(0, _ids.Length - 1);         // 去掉最後一個","
                _ids += "]";

                return(_ids);
            });          // This value will be passed to the method

            // Then all you need to do is
            m_progressDialog.ShowDialog();

            if (!m_progressDialog.WasCancelled && ((string)m_progressDialog.Result) != "*ERROR*")
            {
                try
                {
                    if (DoRealPost((string)m_progressDialog.Result))
                    {
                        DialogResult = DialogResult.Yes;
                        Close();
                    }

                    return;
                }
                catch (Exception _e)
                {
                    MessageBox.Show(_e.Message);
                    return;
                }
            }
            else
            {
                MessageBox.Show("Action canceled");
            }
        }
        /// <summary>
        /// Launches the command of importing excel file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Import_Click(object sender, EventArgs e)
        {
            Hide();
            Double.TryParse(CBB_SpeedInterval.Text, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out excelImporter.SpeedInterval);

            excelImporter.FrameName = TB_FrameName.Text;
            excelImporter.FileName = TB_FileName.Text;
            excelImporter.FillEBD = CB_EBD.Checked;
            excelImporter.FillSBD = CB_SBD.Checked;
            excelImporter.FillEBI = CB_EBI.Checked;
            excelImporter.FillSBI1 = CB_SBI1.Checked;
            excelImporter.FillSBI2 = CB_SBI2.Checked;
            excelImporter.FillFLOI = CB_FLOI.Checked;
            excelImporter.FillWarning = CB_Warning.Checked;
            excelImporter.FillPermitted = CB_Permitted.Checked;
            excelImporter.FillIndication = CB_Indication.Checked;

            ProgressDialog dialog = new ProgressDialog("Importing excel file....", excelImporter);
            dialog.ShowDialog(Owner);
        }
		/// <summary>
		/// Sets the global references to UI elements and event handlers for those elements.
		/// </summary>
		private void setupViewElements()
		{
			mVideoView = (SurfaceView) findViewById(R.id.video);
			mTitleText = (TextView) findViewById(R.id.titleText);
			mPositionText = (TextView) findViewById(R.id.positionText);
			mDurationText = (TextView) findViewById(R.id.durationText);
			mSubtitlesText = (TextView) findViewById(R.id.subtitlesText);
			mSeekBar = (SeekBar) findViewById(R.id.videoPosition);
			mPlayButton = (ImageButton) findViewById(R.id.playPause);
			mMuteButton = (ImageButton) findViewById(R.id.mute);
			mSeekBar.OnSeekBarChangeListener = this;
			mPlayButton.OnClickListener = this;
			mPositionText.Text = "00:00";

			mProgressDialog = new ProgressDialog(this);
			mProgressDialog.Message = "Buffering...";
			mProgressDialog.Cancelable = true;
			mProgressDialog.OnCancelListener = new OnCancelListenerAnonymousInnerClassHelper(this);

			View stopButton = findViewById(R.id.stop);
			stopButton.OnClickListener = this;
			mMuteButton.OnClickListener = this;

			mDevicePicker = (DevicePicker) FragmentManager.findFragmentById(R.id.playerPicker);
			mDevicePicker.DeviceType = SmcDevice.TYPE_AVPLAYER;
			mDevicePicker.DeviceSelectedListener = this;
		}
        private void SaveProduct(ProgressDialog dialog, Activity curActivity, CommonModuleResponse obj)
        {
            try
            {
                string mStringLoginInfo    = string.Empty;
                string mStringSessionToken = string.Empty;
                try
                {
                    objdb = new DBaseOperations();
                    var lstu = objdb.selectTable();
                    if (lstu != null && lstu.Count > default(int))
                    {
                        var uobj = lstu.FirstOrDefault();
                        if (uobj.Password == " ")
                        {
                            throw new Exception("Please login again");
                        }
                        mStringLoginInfo    = uobj.EmailId;
                        mStringSessionToken = uobj.AuthToken;
                    }
                }
                catch { }

                //var x = Newtonsoft.Json.JsonConvert.SerializeObject(obj);

                var client  = new RestClient(Common.UrlBase);
                var request = new RestRequest("Product/CreateSubCategory", Method.POST);
                request.AddHeader("Content-Type", "application/json");
                request.AddHeader("TokenKey", mStringSessionToken);
                //request.AddJsonBody(obj);
                request.AddParameter(new Parameter {
                    Name = "application/json", Type = ParameterType.RequestBody, Value = Newtonsoft.Json.JsonConvert.SerializeObject(obj, new NoColonIsoDateTimeConverter())
                });
                IRestResponse response    = client.Execute(request);
                var           content     = response.Content;
                var           responseObj = Newtonsoft.Json.JsonConvert.DeserializeObject <CommonModuleResponse>(content);
                if (responseObj != null && responseObj.productdata != null && !string.IsNullOrEmpty(responseObj.productdata.ProductId))
                {
                    curActivity.RunOnUiThread(() =>
                    {
                        Android.App.AlertDialog.Builder alertDiag = new Android.App.AlertDialog.Builder(curActivity);
                        alertDiag.SetTitle(Resource.String.DialogHeaderGeneric);
                        alertDiag.SetMessage(string.Format("Your product '{0}' has been saved successfully", obj.productdata.ProductName));
                        alertDiag.SetIcon(Resource.Drawable.success);
                        alertDiag.SetPositiveButton(Resource.String.DialogButtonOk, (senderAlert, args) =>
                        {
                            var siteparam = new List <ItemPayloadModelWithBase64>();
                            siteparam.Add(objSelectedItem.FirstOrDefault());
                            Bundle utilBundle = new Bundle();
                            utilBundle.PutString("siteparam", Newtonsoft.Json.JsonConvert.SerializeObject(siteparam));
                            AddActivityFragment objFragment = new AddActivityFragment();
                            objFragment.Arguments           = utilBundle;
                            Android.Support.V4.App.FragmentTransaction tx = FragmentManager.BeginTransaction();
                            tx.Replace(Resource.Id.m_main, objFragment, Constants.dashboard);
                            tx.Commit();
                        });
                        Dialog diag = alertDiag.Create();
                        diag.Show();
                        diag.SetCanceledOnTouchOutside(false);
                    });
                }
                else
                {
                    if (responseObj != null && !string.IsNullOrEmpty(responseObj.Error))
                    {
                        throw new Exception(responseObj.Error);
                    }
                    else
                    {
                        throw new Exception("Unable to save product right now. Please try again later");
                    }
                }
            }
            catch (Exception ex)
            {
                curActivity.RunOnUiThread(() =>
                {
                    Android.App.AlertDialog.Builder alertDiag = new Android.App.AlertDialog.Builder(curActivity);
                    alertDiag.SetTitle(Resource.String.DialogHeaderError);
                    alertDiag.SetMessage(ex.Message);
                    alertDiag.SetIcon(Resource.Drawable.alert);
                    alertDiag.SetPositiveButton(Resource.String.DialogButtonOk, (senderAlert, args) =>
                    {
                    });
                    Dialog diag = alertDiag.Create();
                    diag.Show();
                    diag.SetCanceledOnTouchOutside(false);
                });
            }
            finally
            {
                if (dialog != null && dialog.IsShowing)
                {
                    dialog.Hide();
                    dialog.Dismiss();
                }
            }
        }
Exemplo n.º 52
0
 internal void Fire(Func <string, IEnumerable <PCommand> > makeCommand, bool normalize = true)
 {
     var result = ProgressDialog.Execute(null, "Formatting", () => _Fire(makeCommand, normalize), ProgressDialogSettings.WithSubLabelAndCancel);
 }
Exemplo n.º 53
0
		/// <summary>
		///
		/// </summary>
		/// <returns>true if everything is ok, false if something went wrong</returns>
		public bool MigrateIfNeeded()
		{
			if (Migrator.IsMigrationNeeded(_liftFilePath))
			{
				using (ProgressDialog dlg = new ProgressDialog())
				{
					dlg.Overview =
							"Please wait while WeSay migrates your lift database to the required version.";
					BackgroundWorker migrationWorker = new BackgroundWorker();
					migrationWorker.DoWork += DoMigrateLiftFile;
					dlg.BackgroundWorker = migrationWorker;
					dlg.CanCancel = false;

					dlg.ShowDialog();
					if (dlg.DialogResult != DialogResult.OK)
					{
						Exception err = dlg.ProgressStateResult.ExceptionThatWasEncountered;
						if (err != null)
						{
							ErrorReport.ReportFatalException(err);
						}
						else if (dlg.ProgressStateResult.State ==
								 ProgressState.StateValue.StoppedWithError)
						{
							ErrorReport.ReportNonFatalMessageWithStackTrace(
									"Failed. " + dlg.ProgressStateResult.LogString);
						}
						return false;
					}
				}
			}
			return true;
		}
Exemplo n.º 54
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.NewMessage);

            preferences = PreferenceManager.GetDefaultSharedPreferences(ApplicationContext);
            token       = JsonConvert.DeserializeObject <AuthenticationToken>(preferences.GetString("token", null));

            mTimeTextView       = FindViewById <TextView>(Resource.Id.timeTextView);
            mStartPlaceEditText = FindViewById <EditText>(Resource.Id.startPlaceEditText);
            mEndPlaceEditText   = FindViewById <EditText>(Resource.Id.endPlaceEditText);
            mAddButton          = FindViewById <Button>(Resource.Id.addButton);

            mTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, 0);
            mTimeTextView.Text = $"Czas: {mTime.ToString("HH:mm")}";

            mTimeTextView.Click += (object sender, EventArgs e) =>
            {
                var timePickerFragment = new TimePickerDialogFragment(this, mTime, this);
                timePickerFragment.Show(FragmentManager, null);
            };

            mAddButton.Click += async(object sender, EventArgs e) =>
            {   //sprawdzenie poprawnoœci wprowadzonych przez u¿ytkownika danych
                if (!mStartPlaceEditText.Text.Equals("") && !mEndPlaceEditText.Text.Equals(""))
                {
                    mStartPlace = mStartPlaceEditText.Text;
                    mEndPlace   = mEndPlaceEditText.Text;
                    var traveler = JsonConvert.DeserializeObject <Traveler>(preferences.GetString("traveler", null));
                    if (traveler == null || token == null)
                    {
                        Toast.MakeText(this, GetString(Resource.String.LoginTokenOrTravelerFailure), ToastLength.Long).Show();
                        Finish();
                        StartActivity(typeof(LoginActivity));
                    }
                    else
                    {
                        //utworzenie nowego obiektu - wiadomoœci
                        newMessage = new Information
                        {
                            TravelerId = traveler.Id,
                            StartPlace = mStartPlace,
                            EndPlace   = mEndPlace,
                            Time       = mTime
                        };
                        //sprawdzenie, czy œrodowisko jest po³¹czone z sieci¹ Internet
                        var connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);
                        var activeNetworkInfo   = connectivityManager.ActiveNetworkInfo;
                        if (activeNetworkInfo == null || !activeNetworkInfo.IsConnected)
                        {
                            Toast.MakeText(this, GetString(Resource.String.NoConnectionInfo), ToastLength.Long).Show();
                            return;
                        }
                        //wywo³anie okna dialogowego progresu
                        var loadingMessage = ProgressDialog.Show(this, GetString(Resource.String.SendingMessageTitle),
                                                                 GetString(Resource.String.SendingMessageContent), true, false);

                        //wywo³anie metody obs³uguj¹cej ¿¹danie http i oczekiwanie na wiadomoœæ
                        var apiMessage = await SaveMyMessage(newMessage);

                        loadingMessage.Dismiss();
                        if (apiMessage.IsSuccessStatusCode)
                        {
                            //ustawienie pozytywnego rezultatu operacji i zakoñczenie aktywnoœci
                            SetResult(Result.Ok);
                        }
                        Finish();
                    }
                }
                else
                {
                    Toast.MakeText(this, GetString(Resource.String.NewMessageNoDataInfo), ToastLength.Long).Show();
                }
            };
        }
Exemplo n.º 55
0
 private async void SaveTrans_Click(object sender, RoutedEventArgs e)
 {
     var message = new ProgressDialog();
     await DialogHost.Show(message, "NewTransactionDialogHost", OpenedEventHandler);
 }
Exemplo n.º 56
0
        private void Rename()
        {
            ProgressDialog progress = new ProgressDialog("Renaming Asset(s)", "Please wait while MOG renames the assset(s)...", Rename_Worker, null, true);

            progress.ShowDialog(this);
        }
Exemplo n.º 57
0
        private bool DoEffect(Effect effect, EffectConfigToken token, PdnRegion selectedRegion,
            PdnRegion regionToRender, Surface originalSurface)
        {
            bool oldDirtyValue = AppWorkspace.ActiveDocumentWorkspace.Document.Dirty;
            bool resetDirtyValue = false;

            bool returnVal = false;
            AppWorkspace.ActiveDocumentWorkspace.EnableOutlineAnimation = false;

            try
            {
                using (ProgressDialog aed = new ProgressDialog())
                {
                    if (effect.Image != null)
                    {
                        aed.Icon = Utility.ImageToIcon(effect.Image, Utility.TransparentKey);
                    }

                    aed.Opacity = 0.9;
                    aed.Value = 0;
                    aed.Text = effect.Name;
                    aed.Description = string.Format(PdnResources.GetString("Effects.ApplyingDialog.Description"), effect.Name);

                    invalidateTimer.Enabled = true;

                    using (new WaitCursorChanger(AppWorkspace))
                    {
                        HistoryMemento ha = null;
                        DialogResult result = DialogResult.None;

                        AppWorkspace.Widgets.StatusBarProgress.ResetProgressStatusBar();
                        AppWorkspace.Widgets.LayerControl.SuspendLayerPreviewUpdates();

                        try
                        {
                            ManualResetEvent saveEvent = new ManualResetEvent(false);
                            BitmapHistoryMemento bha = null;

                            // perf bug #1445: save this data in a background thread
                            PdnRegion selectedRegionCopy = selectedRegion.Clone();
                            PaintDotNet.Threading.ThreadPool.Global.QueueUserWorkItem(
                                delegate(object context)
                                {
                                    try
                                    {
                                        ImageResource image;

                                        if (effect.Image == null)
                                        {
                                            image = null;
                                        }
                                        else
                                        {
                                            image = ImageResource.FromImage(effect.Image);
                                        }

                                        bha = new BitmapHistoryMemento(effect.Name, image, this.AppWorkspace.ActiveDocumentWorkspace,
                                            this.AppWorkspace.ActiveDocumentWorkspace.ActiveLayerIndex, selectedRegionCopy, originalSurface);
                                    }

                                    finally
                                    {
                                        saveEvent.Set();
                                        selectedRegionCopy.Dispose();
                                        selectedRegionCopy = null;
                                    }
                                });

                            BackgroundEffectRenderer ber = new BackgroundEffectRenderer(
                                effect,
                                token,
                                new RenderArgs(((BitmapLayer)AppWorkspace.ActiveDocumentWorkspace.ActiveLayer).Surface),
                                new RenderArgs(originalSurface),
                                regionToRender,
                                tilesPerCpu * renderingThreadCount,
                                renderingThreadCount);

                            aed.Tag = ber;
                            ber.RenderedTile += new RenderedTileEventHandler(aed.RenderedTileHandler);
                            ber.RenderedTile += new RenderedTileEventHandler(RenderedTileHandler);
                            ber.StartingRendering += new EventHandler(StartingRenderingHandler);
                            ber.FinishedRendering += new EventHandler(aed.FinishedRenderingHandler);
                            ber.FinishedRendering += new EventHandler(FinishedRenderingHandler);
                            ber.Start();

                            result = Utility.ShowDialog(aed, AppWorkspace);

                            if (result == DialogResult.Cancel)
                            {
                                resetDirtyValue = true;

                                using (new WaitCursorChanger(AppWorkspace))
                                {
                                    ber.Abort();
                                    ber.Join();
                                    ((BitmapLayer)AppWorkspace.ActiveDocumentWorkspace.ActiveLayer).Surface.CopySurface(originalSurface);
                                }
                            }

                            invalidateTimer.Enabled = false;

                            ber.Join();
                            ber.Dispose();

                            saveEvent.WaitOne();
                            saveEvent.Close();
                            saveEvent = null;

                            ha = bha;
                        }

                        catch
                        {
                            using (new WaitCursorChanger(AppWorkspace))
                            {
                                ((BitmapLayer)AppWorkspace.ActiveDocumentWorkspace.ActiveLayer).Surface.CopySurface(originalSurface);
                                ha = null;
                            }
                        }

                        finally
                        {
                            AppWorkspace.Widgets.LayerControl.ResumeLayerPreviewUpdates();
                        }

                        using (PdnRegion simplifiedRenderRegion = Utility.SimplifyAndInflateRegion(selectedRegion))
                        {
                            using (new WaitCursorChanger(AppWorkspace))
                            {
                                AppWorkspace.ActiveDocumentWorkspace.ActiveLayer.Invalidate(simplifiedRenderRegion);
                            }
                        }

                        using (new WaitCursorChanger(AppWorkspace))
                        {
                            if (result == DialogResult.OK)
                            {
                                if (ha != null)
                                {
                                    AppWorkspace.ActiveDocumentWorkspace.History.PushNewMemento(ha);
                                }

                                AppWorkspace.Update();
                                returnVal = true;
                            }
                            else
                            {
                                Utility.GCFullCollect();
                            }
                        }
                    } // using
                } // using
            }

            finally
            {
                AppWorkspace.ActiveDocumentWorkspace.EnableOutlineAnimation = true;

                if (resetDirtyValue)
                {
                    AppWorkspace.ActiveDocumentWorkspace.Document.Dirty = oldDirtyValue;
                }
            }

            AppWorkspace.Widgets.StatusBarProgress.EraseProgressStatusBarAsync();
            return returnVal;
        }
Exemplo n.º 58
0
        internal string[] CopyResourcesToFolder(RepositoryHandle[] data, string targetConnectionName, string folderId)
        {
            string rootSourceParent = GetCommonParent(data);

            //There is an implicit assumption here that all items dropped come from the same connection
            var sourceConn = data.First().Connection;
            var targetConn = _connManager.GetConnection(targetConnectionName);
            var migrator   = new ResourceMigrator(sourceConn, targetConn);

            //Collect all source ids
            var sourceIds = new List <string>();

            foreach (var resId in data.Select(x => x.ResourceId.ToString()))
            {
                if (ResourceIdentifier.IsFolderResource(resId))
                {
                    sourceIds.AddRange(GetFullResourceList(sourceConn, resId));
                }
                else
                {
                    sourceIds.Add(resId);
                }
            }

            var targets = new List <string>();

            foreach (var resId in sourceIds)
            {
                var dstId = resId.Replace(rootSourceParent, folderId);
                System.Diagnostics.Trace.TraceInformation($"{resId} => {dstId}"); //NOXLATE
                targets.Add(dstId);
            }

            bool overwrite = true;
            var  existing  = new List <string>();

            foreach (var resId in targets)
            {
                if (targetConn.ResourceService.ResourceExists(resId))
                {
                    existing.Add(resId);
                }
            }
            if (existing.Count > 0)
            {
                overwrite = MessageService.AskQuestion(string.Format(Strings.PromptOverwriteOnTargetConnection, existing.Count));
            }

            var wb     = Workbench.Instance;
            var dlg    = new ProgressDialog();
            var worker = new ProgressDialog.DoBackgroundWork((w, evt, args) =>
            {
                LengthyOperationProgressCallBack cb = (s, cbe) =>
                {
                    w.ReportProgress(cbe.Progress, cbe.StatusMessage);
                };

                return(migrator.CopyResources(sourceIds.ToArray(), targets.ToArray(), overwrite, new RebaseOptions(rootSourceParent, folderId), cb));
            });

            var result = (string[])dlg.RunOperationAsync(wb, worker);

            RefreshModel(targetConn.DisplayName, folderId);
            ExpandNode(targetConn.DisplayName, folderId);
            return(result);
        }
Exemplo n.º 59
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            // Create your application here
            StatusBarUtil.SetColorStatusBars(this);
            SetToolBarNavBack();

            edit_url             = FindViewById <EditText>(Resource.Id.edit_url);
            edit_title           = FindViewById <EditText>(Resource.Id.edit_title);
            edit_summary         = FindViewById <EditText>(Resource.Id.edit_summary);
            edit_tags            = FindViewById <EditText>(Resource.Id.edit_tags);
            btn_submit           = FindViewById <Button>(Resource.Id.btn_submit);
            ly_expire            = FindViewById <LinearLayout>(Resource.Id.ly_expire);
            tv_startLogin        = FindViewById <TextView>(Resource.Id.tv_startLogin);
            tv_startLogin.Click += (s, e) =>
            {
                StartActivity(new Intent(this, typeof(loginactivity)));
            };
            AlertUtil.ToastLong(this, "当前线程id:" + Thread.CurrentThread.ManagedThreadId);

            string title = Intent.GetStringExtra("title");
            string url   = Intent.GetStringExtra("url");

            mode = Intent.GetStringExtra("mode");

            edit_url.Text   = string.IsNullOrEmpty(url)?"":url;
            edit_title.Text = string.IsNullOrEmpty(title)?"":title;
            Token token = UserTokenUtil.GetToken(this);

            if (mode == "edit")
            {
                string editTitle = Resources.GetString(Resource.String.bookmark_edit);
                btn_submit.Text = editTitle;
                SetToolBarTitle(editTitle);
                string summary = Intent.GetStringExtra("summary");
                string tags    = Intent.GetStringExtra("tags");
                wzLinkId = Intent.GetIntExtra("id", 0);
                if (!string.IsNullOrEmpty(summary))
                {
                    edit_summary.Text = summary;
                }
                if (!string.IsNullOrEmpty(tags))
                {
                    edit_tags.Text = tags;
                }
            }
            else if (mode == "add")
            {
                btn_submit.Text = "添加收藏";
            }
            //判断是否登录
            if (token.IsExpire)
            {
                btn_submit.Enabled   = false;
                ly_expire.Visibility = ViewStates.Visible;
            }
            else
            {
                btn_submit.Enabled   = true;
                ly_expire.Visibility = ViewStates.Gone;
            }
            btn_submit.Click += async(s, e) =>
            {
                var userToken = UserTokenUtil.GetToken(this);
                if (userToken.IsExpire)
                {
                    Android.Support.V7.App.AlertDialog.Builder alertDialog = new Android.Support.V7.App.AlertDialog.Builder(this)
                                                                             .SetTitle("登录提示")
                                                                             .SetMessage("未登录或登录token已经过期")
                                                                             .SetPositiveButton("授权", (s1, e1) =>
                    {
                        StartActivity(new Intent(this, typeof(loginactivity)));
                    })
                                                                             .SetNegativeButton("取消", (s1, e1) =>
                    {
                        return;
                    });
                    alertDialog.Create().Show();
                }
                if (edit_summary.Text.Length > 200)
                {
                    AlertUtil.ToastShort(this, "摘要不能超过200字符");
                    return;
                }
                if (token.IsExpire)
                {
                    AlertUtil.ToastShort(this, "未登录或登录token已经过期,请邓丽");
                    return;
                }
                var model = new BookmarksModel();
                model.Title   = edit_title.Text;
                model.LinkUrl = edit_url.Text;
                model.Summary = edit_summary.Text;
                model.Tags    = edit_tags.Text.Split(',').ToList();
                var dialog = new ProgressDialog(this);
                dialog.SetProgressStyle(ProgressDialogStyle.Spinner);
                dialog.SetCancelable(false);
                dialog.SetCanceledOnTouchOutside(false);
                dialog.SetTitle(Resources.GetString(Resource.String.bookmark_add));
                dialog.SetMessage("提交中.......");
                dialog.Show();
                if (mode == "add")
                {
                    var result = await BookmarksService.Add(token, model);

                    if (result.Success)
                    {
                        btn_submit.Enabled = false;
                        dialog.Hide();
                        AlertUtil.ToastLong(this, result.Message + "添加收藏成功");
                        this.Finish();
                        System.Diagnostics.Debug.Write(result.Message);
                    }
                    else
                    {
                        dialog.Hide();
                        AlertUtil.ToastLong(this, result.Message);
                        System.Diagnostics.Debug.Write(result);
                    }
                }
                if (mode == "edit")
                {
                    model.WzLinkId = wzLinkId;
                    BookmarksService.Edit(token, model, (result) => {
                        if (result.IsSuccess)
                        {
                            RunOnUiThread(() => {
                                dialog.Hide();
                                btn_submit.Enabled = false;
                                AlertUtil.ToastLong(this, result.Message + "编辑收藏成功");
                            });
                            System.Diagnostics.Debug.Write(result.Message);
                        }
                        else
                        {
                            RunOnUiThread(() =>
                            {
                                dialog.Hide();
                                AlertUtil.ToastLong(this, result.Message);
                                System.Diagnostics.Debug.Write(result);
                            });
                        }
                    });
                }
            };
        }
Exemplo n.º 60
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Layout = LayoutInflater.Inflate(Resource.Layout.InformacionPersonal, null);
            SetContentView(Layout);

            nombres               = FindViewById <TextView>(Resource.Id.Nombre);
            apellidos             = FindViewById <TextView>(Resource.Id.Apellido);
            nDocumento            = FindViewById <TextView>(Resource.Id.NDocumento);
            fechaNacimiento       = FindViewById <TextView>(Resource.Id.FechaNacimiento);
            telefonoMovil         = FindViewById <TextView>(Resource.Id.TelefonoMovil);
            telefonoFijo          = FindViewById <TextView>(Resource.Id.TelefonoFijo);
            direccion             = FindViewById <TextView>(Resource.Id.Direccion);
            email                 = FindViewById <TextView>(Resource.Id.Email);
            fechaIngreso          = FindViewById <TextView>(Resource.Id.FechaIngreso);
            departamento          = FindViewById <TextView>(Resource.Id.Departamento);
            profilePhotoImageView = FindViewById <ImageView>(Resource.Id.ImagenPerfil);
            Tareas                = FindViewById <Button>(Resource.Id.TareasPersonal);
            Ubicacion             = FindViewById <Button>(Resource.Id.UbicacionPersonal);
            Mensajeria            = FindViewById <Button>(Resource.Id.MensajeriaPersonal);
            progress              = HelperMethods.setSpinnerDialog("Cargando Coordenadas...", this);

            var toolbar = FindViewById <Toolbar>(Resource.Id.toolbar);

            SetSupportActionBar(toolbar);

            Window.AddFlags(WindowManagerFlags.DrawsSystemBarBackgrounds);
            SupportActionBar.SetHomeButtonEnabled(true);
            SupportActionBar.SetDisplayHomeAsUpEnabled(true);

            // set the activity title and action bar title
            Title = SupportActionBar.Title = "Informacion Personal";

            HelperMethods.SetupAnimations(this);

            // extract the acquaintance id fomr the intent
            IdEmpleado = Intent.GetIntExtra(GetString(Resource.String.InformacionPersonalIntentKey), 0);

            if (IdEmpleado != 0)
            {
                empleadoConsulta = HelperMethods.getUserById(IdEmpleado);
                informacionPerfil(empleadoConsulta);
            }
            else
            {
                informacionPerfil(Perfil_Login.miPerfil);
                IdEmpleado            = Perfil_Login.miPerfil.ID_Login;
                Tareas.Visibility     = ViewStates.Invisible;
                Ubicacion.Visibility  = ViewStates.Invisible;
                Mensajeria.Visibility = ViewStates.Invisible;
            }
            Conexion_Web_Service._client.BajarCoordenadasEmpleadosCompleted += _client_Lista_BajarCoordenadasEmpleadosCompletedPersonal;

            Ubicacion.Click += (sender, e) =>
            {
                Layout.Enabled = false;
                long  fechaFinal           = HelperMethods.ConvertToUnixTimestamp(DateTime.Now);
                long  fechaInicial         = fechaFinal - 3600;
                int[] ID_UsuariosConsultar = { IdEmpleado };

                Conexion_Web_Service._client.BajarCoordenadasEmpleadosAsync(fechaInicial, fechaFinal, ID_UsuariosConsultar);
                progress.Show();
            };

            Mensajeria.Click += (sender, e) =>
            {
                Intent detailIntent = new Intent(this, typeof(ChatActivity));
                detailIntent.PutExtra(Resources.GetString(Resource.String.idChat), empleadoConsulta.ID_Login.ToString());
                detailIntent.PutExtra(Resources.GetString(Resource.String.NombreDestinatarioChat), HelperMethods.DisplayName(empleadoConsulta));
                StartActivity(detailIntent);
            };
        }