Ejemplo n.º 1
0
 /// <summary>
 /// Generates a grid specified by user
 /// </summary>
 /// <param name="sender">Button Click, not used.</param>
 /// <param name="e">Button Click, not used.</param>
 protected void Generate(object sender, EventArgs e)
 {
     int r, c;
     //Try to convert the text in text boxes to ints
     try
     {
         r = Convert.ToInt32(entryRows.Text);
         c = Convert.ToInt32(entryCols.Text);
     }
     //if it fails, log it, but dont close. Maybe user just mistyped.
     catch (FormatException ex)
     {
         Console.WriteLine(ex.ToString());
         return;
     }
     if (CheckBounds(r, c))
     {
         board = new GameBoard(r, c);
         GridConstructor gc = new GridConstructor(r, c, this);
         gc.Show();
         gc.SetGrid();
     }
     else
     {
         //if bounds check is not met, then display a specific dialog.
         ErrorDialog error = new ErrorDialog(2);
         error.Show();
     }
 }
        public void HandleError(string errorMessage)
        {
            ErrorDialog errorDialog = new ErrorDialog(errorMessage);

            using (errorDialog)
            {
                // TODO NKO: Do something with the result.
                DialogResult result = errorDialog.ShowDialog();
            }
        }
Ejemplo n.º 3
0
		// Unhandled Exception Handler
		void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
		{
			ExtendedArgumentException ex = e.Exception as ExtendedArgumentException;
			if (ex != null)
			{
				// Show error dialog
				ErrorDialog dialog = new ErrorDialog(ex);
				dialog.Show();

				DataUtil.WriteCrashToErrorLogsFolder<ExtendedArgumentException>(ex, ex.message);
			}
			else
				DataUtil.WriteCrashToErrorLogsFolder<Exception>(e.Exception, "Unhandled Exception");

			e.Handled = true;
		}
Ejemplo n.º 4
0
        internal bool CanCreateBond()
        {
            List <PIF> pifs = BondedPIFs;

            bool will_disturb_primary    = NetworkingHelper.ContainsPrimaryManagement(pifs);
            bool will_disturb_secondary  = NetworkingHelper.ContainsSecondaryManagement(pifs);
            bool will_disturb_clustering = NetworkingHelper.ContainsClusteringPif(pifs);

            // It is not allowed to bond primary and secondary interfaces together.
            if (will_disturb_primary && will_disturb_secondary)
            {
                using (var dlg = new ErrorDialog(Messages.BOND_CREATE_WILL_DISTURB_BOTH)
                {
                    WindowTitle = Messages.BOND_CREATE
                })
                {
                    dlg.ShowDialog(this);
                }

                return(false);
            }

            // Only primary management interface.
            // In this case, clustering interface warning is hidden if it happens to be the management interface.
            if (will_disturb_primary)
            {
                Pool pool = Helpers.GetPool(Connection);
                if (pool != null && pool.ha_enabled)
                {
                    using (var dlg = new ErrorDialog(string.Format(Messages.BOND_CREATE_HA_ENABLED, pool.Name()))
                    {
                        WindowTitle = Messages.BOND_CREATE
                    })
                    {
                        dlg.ShowDialog(this);
                    }

                    return(false);
                }

                DialogResult dialogResult;
                using (var dlg = new WarningDialog(Messages.BOND_CREATE_WILL_DISTURB_PRIMARY,
                                                   new ThreeButtonDialog.TBDButton(Messages.BOND_CREATE_CONTINUE, DialogResult.OK),
                                                   ThreeButtonDialog.ButtonCancel)
                {
                    HelpName = "BondConfigError",
                    WindowTitle = Messages.BOND_CREATE
                })
                {
                    dialogResult = dlg.ShowDialog(this);
                }
                return(dialogResult == DialogResult.OK);
            }

            // Only secondary interface.
            // If there is clustering interface, shows clustering warning. Otherwise, shows secondary interface warning.
            if (will_disturb_secondary)
            {
                DialogResult dialogResult;
                if (will_disturb_clustering)
                {
                    using (var dlg = new WarningDialog(Messages.BOND_CREATE_WILL_DISTURB_CLUSTERING,
                                                       ThreeButtonDialog.ButtonOK, ThreeButtonDialog.ButtonCancel)
                    {
                        WindowTitle = Messages.BOND_CREATE
                    })
                    {
                        dialogResult = dlg.ShowDialog(this);
                    }
                }

                else
                {
                    using (var dlg = new WarningDialog(Messages.BOND_CREATE_WILL_DISTURB_SECONDARY,
                                                       ThreeButtonDialog.ButtonOK, ThreeButtonDialog.ButtonCancel)
                    {
                        WindowTitle = Messages.BOND_CREATE
                    })
                    {
                        dialogResult = dlg.ShowDialog(this);
                    }
                }

                return(dialogResult == DialogResult.OK);
            }

            return(true);
        }
        public override void Bind(IEditorService service)
        {
            try
            {
                _init  = true;
                _edsvc = service;
                _edsvc.RegisterCustomNotifier(this);

                var res = service.GetEditedResource() as ILayerDefinition;
                Debug.Assert(res != null);

                _vl = res.SubLayer as IVectorLayerDefinition;
                Debug.Assert(_vl != null);

                txtFeatureClass.Text = _vl.FeatureName;
                txtGeometry.Text     = _vl.Geometry;
                ResetErrorState();

                if (string.IsNullOrEmpty(txtFeatureClass.Text) || string.IsNullOrEmpty(txtGeometry.Text))
                {
                    TryFillUIFromNewFeatureSource(_vl.ResourceId);
                    if (!_edsvc.CurrentConnection.ResourceService.ResourceExists(_vl.ResourceId))
                    {
                        errorProvider.SetError(txtFeatureSource, Strings.LayerEditorFeatureSourceNotFound);
                        MessageBox.Show(Strings.LayerEditorHasErrors);
                    }
                }
                else
                {
                    bool bShowErrorMessage = false;
                    txtFeatureSource.Text = _vl.ResourceId;
                    string featureClass = txtFeatureClass.Text;
                    string geometry     = txtGeometry.Text;
                    BusyWaitDialog.Run(null, () =>
                    {
                        var errors = new List <string>();
                        if (!_edsvc.CurrentConnection.ResourceService.ResourceExists(_vl.ResourceId))
                        {
                            errors.Add(Strings.LayerEditorFeatureSourceNotFound);
                        }
                        if (!string.IsNullOrEmpty(featureClass))
                        {
                            ClassDefinition clsDef = null;
                            try
                            {
                                clsDef = _edsvc.CurrentConnection.FeatureService.GetClassDefinition(_vl.ResourceId, featureClass);
                            }
                            catch
                            {
                                errors.Add(Strings.LayerEditorFeatureClassNotFound);
                                //These property mappings will probably be bunk if this is the case, so clear them
                                _vl.ClearPropertyMappings();
                            }

                            if (clsDef != null)
                            {
                                GeometricPropertyDefinition geom = clsDef.FindProperty(geometry) as GeometricPropertyDefinition;
                                if (geom == null)
                                {
                                    errors.Add(Strings.LayerEditorGeometryNotFound);
                                }
                            }
                            else
                            {
                                //This is probably true
                                errors.Add(Strings.LayerEditorGeometryNotFound);
                            }
                        }
                        return(errors);
                    }, (result, ex) =>
                    {
                        if (ex != null)
                        {
                            ErrorDialog.Show(ex);
                        }
                        else
                        {
                            var list = (List <string>)result;
                            foreach (var err in list)
                            {
                                if (err == Strings.LayerEditorGeometryNotFound)
                                {
                                    errorProvider.SetError(txtGeometry, err);
                                    bShowErrorMessage = true;
                                }
                                else if (err == Strings.LayerEditorFeatureSourceNotFound)
                                {
                                    errorProvider.SetError(txtFeatureSource, err);
                                    //Don't show error message here if this is the only error as the user
                                    //will get a repair feature source prompt down the road
                                }
                                else if (err == Strings.LayerEditorFeatureClassNotFound)
                                {
                                    errorProvider.SetError(txtFeatureClass, err);
                                    bShowErrorMessage = true;
                                }
                            }
                            if (bShowErrorMessage)
                            {
                                MessageBox.Show(Strings.LayerEditorHasErrors);
                            }
                        }
                    });
                }

                txtFilter.Text = _vl.Filter;

                //Loose bind this one because 2.4 changes this behaviour making it
                //unsuitable for databinding via TextBoxBinder
                txtHyperlink.Text = _vl.Url;

                txtTooltip.Text = _vl.ToolTip;

                //This is not the root object so no change listeners have been subscribed
                _vl.PropertyChanged += WeakEventHandler.Wrap <PropertyChangedEventHandler>(OnVectorLayerPropertyChanged, (eh) => _vl.PropertyChanged -= eh);
            }
            finally
            {
                _init = false;
            }
        }
Ejemplo n.º 6
0
        public static void Main(string[] args)
        {
            //foreach(string str in args)
            //	Logger.Log("arg ->{0}",str);

            Application.Init();
            Logger.Log(Languages.Translate("start_app"));

            ExceptionManager.UnhandledException += delegate(UnhandledExceptionArgs argsum)
            {
                StringBuilder sb = new StringBuilder();

                Exception ex = (Exception)argsum.ExceptionObject;

                sb.AppendLine(ex.Message);
                sb.AppendLine(ex.StackTrace);
                Logger.Error(ex.Message);
                Logger.Error(ex.StackTrace);
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);

                if (ex.InnerException != null)
                {
                    Logger.Error(ex.InnerException.Message);
                    Logger.Error(ex.InnerException.StackTrace);
                    Logger.Error(ex.InnerException.Source);
                    Console.WriteLine(ex.InnerException.Message);
                    Console.WriteLine(ex.InnerException.StackTrace);
                    Console.WriteLine(ex.InnerException.Source);
                    sb.AppendLine(ex.InnerException.Message);
                    sb.AppendLine(ex.InnerException.StackTrace);
                    sb.AppendLine(ex.InnerException.Source);
                }

                ErrorDialog ed = new ErrorDialog();
                ed.ErrorMessage = sb.ToString();
                ed.Run();
                ed.Destroy();

                argsum.ExitApplication = true;
            };

            Gdk.Global.InitCheck(ref args);
            if (Platform.IsWindows)
            {
                string themePath = Paths.DefaultTheme;
                if (System.IO.File.Exists(themePath))
                {
                    Gtk.Rc.AddDefaultFile(themePath);
                    Gtk.Rc.Parse(themePath);
                }
            }

            mainWindow = new MainWindow(args);
            MainWindow.Show();

            if ((MainClass.Settings.Account == null) || (String.IsNullOrEmpty(MainClass.Settings.Account.Token)))
            {
                LoginRegisterDialog ld = new LoginRegisterDialog(null);
                ld.Run();
                ld.Destroy();
            }
            else
            {
                LoggingInfo log = new LoggingInfo();
                log.LoggWebThread(LoggingInfo.ActionId.IDEStart);
            }

            if (!String.IsNullOrEmpty(Paths.TempDir))
            {
                Application.Run();
            }
        }
Ejemplo n.º 7
0
 public static void ShowErrorDialog(string errorString)
 {
     ErrorDialog errorDialog = new ErrorDialog(errorString);
     errorDialog.Activate();
     errorDialog.ShowDialog();
  }
Ejemplo n.º 8
0
        private static void Main(string[] ps)
        {
            if (ps.Length <= 1)
            {
                SplashForm.ShowSplash(11);

                SplashForm.StepDone();
                InitializeUtils.Initialize(Assembly.GetExecutingAssembly());
                SplashForm.StepDone();

                ErrorDialog.Initialize();
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                SplashForm.StepDone();

                var mainForm = Forms.Main = new MainForm();
                SplashForm.StepDone();
                var docPanel = mainForm.DockingPanel;
                SplashForm.StepDone();
                Forms.ManifestBrowser = new ManifestBrowser(docPanel);
                SplashForm.StepDone();
                Forms.PropertyEditor = new PropertyEditor(docPanel);
                SplashForm.StepDone();
                Forms.CourseExplorer = new CourseExplorer(docPanel);
                SplashForm.StepDone();
                Forms.CourseDesigner = new CourseDesigner(docPanel);
                SplashForm.StepDone();

                if (ps.Length == 1)
                {
                    mainForm.OpenCourse(ps[0], true);
                }
                SplashForm.StepDone();

                Application.Run(mainForm);
            }
            else
            {
                InitializeUtils.Initialize(Assembly.GetExecutingAssembly());
                AllocOrAttachConsole();
                if (ps[0].Equals("--upgrade", StringComparison.InvariantCultureIgnoreCase))
                {
                    for (var i = 1; i < ps.Length; i++)
                    {
                        var dirName  = Path.GetDirectoryName(ps[i]);
                        var fileMask = Path.GetFileName(ps[i]);
                        var files    = Directory.GetFiles(dirName, fileMask);
                        foreach (var file in files)
                        {
                            try
                            {
                                Console.Write("Upgrading '{0}'... ", file);
                                if (Course.Course.OpenZipPackage(file))
                                {
                                    Course.Course.SaveToZipPackage(file);
                                }
                                else
                                {
                                    Console.WriteLine("ERROR ON OPENNING");
                                }
                                Console.WriteLine("[DONE]");
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine("[ERROR]");
                                Console.WriteLine(e.Message);
                            }
                        }
                    }
                }
                FreeConsole();
            }
        }
Ejemplo n.º 9
0
        private bool ExamineIscsiProbeResults(SR.SRTypes currentSrType, List <SR.SRInfo> srs)
        {
            _srToIntroduce = null;

            if (srs == null)
            {
                return(false);
            }

            // There should be 0 or 1 SRs on the LUN
            System.Diagnostics.Debug.Assert(srs.Count == 0 || srs.Count == 1);

            try
            {
                if (!string.IsNullOrEmpty(SrWizardType.UUID))
                {
                    // Check LUN contains correct SR
                    if (srs.Count == 1 && srs[0].UUID == SrWizardType.UUID)
                    {
                        _srToIntroduce = srs[0];
                        SrType         = currentSrType; // the type of the existing SR
                        return(true);
                    }

                    ShowError(errorIconAtTargetLUN, errorLabelAtTargetLUN, string.Format(Messages.INCORRECT_LUN_FOR_SR, SrWizardType.SrName));
                    return(false);
                }

                if (srs.Count == 0)
                {
                    if (!SrWizardType.AllowToCreateNewSr)
                    {
                        using (var dlg = new ErrorDialog(Messages.NEWSR_LUN_HAS_NO_SRS))
                            dlg.ShowDialog(this);

                        return(false);
                    }

                    if (Program.RunInAutomatedTestMode)
                    {
                        return(true);
                    }

                    // SR creation is allowed; ask the user if they want to proceed and format.
                    using (var dlog = new LVMoIsciWarningDialog(Connection, null, currentSrType, SrType))
                    {
                        dlog.ShowDialog(this);
                        return(dlog.SelectedOption == LVMoHBAWarningDialog.UserSelectedOption.Format);
                    }
                }

                if (Program.RunInAutomatedTestMode)
                {
                    return(true);
                }

                // offer to attach it, or format it to create a new SR, or cancel
                SR.SRInfo srInfo = srs[0];

                using (var dlog = new LVMoIsciWarningDialog(Connection, srInfo, currentSrType, SrType))
                {
                    dlog.ShowDialog(this);

                    switch (dlog.SelectedOption)
                    {
                    case LVMoHBAWarningDialog.UserSelectedOption.Reattach:
                        _srToIntroduce = srInfo;
                        SrType         = currentSrType; // the type of the existing SR
                        return(true);

                    case LVMoHBAWarningDialog.UserSelectedOption.Format:
                        return(true);

                    default:
                        return(false);
                    }
                }
            }
            catch
            {
                // We really want to prevent the user getting to the next step if there is any kind of
                // exception here, since clicking 'finish' might destroy data: require another probe.
                return(false);
            }
        }
Ejemplo n.º 10
0
        // Opens a CameraDevice. The result is listened to by 'mStateListener'.
        private void OpenCamera()
        {
            Activity activity = Activity;

            if (activity == null || activity.IsFinishing || mOpeningCamera)
            {
                return;
            }
            mOpeningCamera = true;
            CameraManager manager = (CameraManager)activity.GetSystemService(Context.CameraService);

            try
            {
                bool front = Arguments.GetBoolean(EXTRA_USE_FRONT_FACING_CAMERA);
                if (front)
                {
                    Log.Debug("VoiceCamera", "Front specified");
                }
                else
                {
                    Log.Debug("VoiceCamera", "Back Specified");
                }

                Log.Debug("VoiceCamera", "Front ID: " + (int)LensFacing.Front + " Back ID: " + (int)LensFacing.Back);

                foreach (var cameraId in manager.GetCameraIdList())
                {
                    // To get a list of available sizes of camera preview, we retrieve an instance of
                    // StreamConfigurationMap from CameraCharacteristics
                    var characteristics = manager.GetCameraCharacteristics(cameraId);
                    var lens            = characteristics.Get(CameraCharacteristics.LensFacing);
                    Log.Debug("VoiceCamera", "LensFacing: " + lens.ToString());
                    if (!IsCameraSpecified)
                    {
                        Log.Debug("VoiceCamera", "camera not specified");
                        if ((int)lens == (int)LensFacing.Front)
                        {
                            Log.Debug("VoiceCamera", "Skip front facing camera");
                            //we don't use a front facing camera in this sample.
                            continue;
                        }
                    }
                    else if (!ShouldUseCamera((int)lens))
                    {
                        Log.Debug("VoiceCamera", "Skipping over camera, should not use");
                        //TODO: Handle case where there is no camera match
                        continue;
                    }

                    Log.Debug("VoiceCamera", "Using this camera");


                    StreamConfigurationMap map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap);
                    mPreviewSize = map.GetOutputSizes(Java.Lang.Class.FromType(typeof(SurfaceTexture)))[0];
                    Android.Content.Res.Orientation orientation = Resources.Configuration.Orientation;
                    if (orientation == Android.Content.Res.Orientation.Landscape)
                    {
                        mTextureView.SetAspectRatio(mPreviewSize.Width, mPreviewSize.Height);
                    }
                    else
                    {
                        mTextureView.SetAspectRatio(mPreviewSize.Height, mPreviewSize.Width);
                    }

                    // We are opening the camera with a listener. When it is ready, OnOpened of mStateListener is called.
                    manager.OpenCamera(cameraId, mStateListener, null);
                    return;
                }
            }
            catch (CameraAccessException ex) {
                Toast.MakeText(activity, "Cannot access the camera.", ToastLength.Short).Show();
                Activity.Finish();
            } catch (NullPointerException) {
                var dialog = new ErrorDialog();
                dialog.Show(FragmentManager, "dialog");
            }
        }
Ejemplo n.º 11
0
 void ShowErrorDialog(string message)
 {
     if (errorDialog == null)
     {
         errorDialog = new ErrorDialog(Screen)
         {
             Message = new TextBlock(Screen)
             {
                 ForegroundColor = Color.White,
                 BackgroundColor = Color.Black
             }
         };
     }
     (errorDialog.Message as TextBlock).Text = message;
     errorDialog.Show();
 }
        // Opens a CameraDevice. The result is listened to by 'mStateListener'.
        private void OpenCamera()
        {
            Activity activity = Activity;
            if (activity == null || activity.IsFinishing || mOpeningCamera) {
                return;
            }
            mOpeningCamera = true;
            CameraManager manager = (CameraManager)activity.GetSystemService (Context.CameraService);
            try
            {

                bool front = Arguments.GetBoolean(EXTRA_USE_FRONT_FACING_CAMERA);
                if(front)
                    Log.Debug("VoiceCamera", "Front specified");
                else
                    Log.Debug("VoiceCamera", "Back Specified");

                Log.Debug("VoiceCamera", "Front ID: " + (int)LensFacing.Front + " Back ID: " + (int)LensFacing.Back);

                foreach(var cameraId in manager.GetCameraIdList())
                {

                    // To get a list of available sizes of camera preview, we retrieve an instance of
                    // StreamConfigurationMap from CameraCharacteristics
                    var characteristics = manager.GetCameraCharacteristics(cameraId);
                    var lens = characteristics.Get(CameraCharacteristics.LensFacing);
                    Log.Debug("VoiceCamera", "LensFacing: " + lens.ToString());
                    if(!IsCameraSpecified)
                    {
                        Log.Debug("VoiceCamera", "camera not specified");
                        if((int)lens == (int)LensFacing.Front)
                        {
                            Log.Debug("VoiceCamera", "Skip front facing camera");
                            //we don't use a front facing camera in this sample.
                            continue;
                        }
                    }
                    else if(!ShouldUseCamera((int)lens))
                    {
                        Log.Debug("VoiceCamera", "Skipping over camera, should not use");
                        //TODO: Handle case where there is no camera match
                        continue;
                    }

                    Log.Debug("VoiceCamera", "Using this camera");

                    StreamConfigurationMap map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap);
                    mPreviewSize = map.GetOutputSizes(Java.Lang.Class.FromType(typeof(SurfaceTexture)))[0];
                    Android.Content.Res.Orientation orientation = Resources.Configuration.Orientation;
                    if (orientation == Android.Content.Res.Orientation.Landscape)
                    {
                        mTextureView.SetAspectRatio(mPreviewSize.Width, mPreviewSize.Height);
                    }
                    else
                    {
                        mTextureView.SetAspectRatio(mPreviewSize.Height, mPreviewSize.Width);
                    }

                    // We are opening the camera with a listener. When it is ready, OnOpened of mStateListener is called.
                    manager.OpenCamera(cameraId, mStateListener, null);
                    return;
                }
            }
            catch (CameraAccessException ex) {
                Toast.MakeText (activity, "Cannot access the camera.", ToastLength.Short).Show ();
                Activity.Finish ();
            } catch (NullPointerException) {
                var dialog = new ErrorDialog ();
                dialog.Show (FragmentManager, "dialog");
            }
        }
Ejemplo n.º 13
0
 private bool ShowIPodFull()
 {
     ErrorDialog ed = new ErrorDialog (
         Catalog.GetString ("Not Enough Space - Monopod Podcast Client"),
         Catalog.GetString ("Not enough space on iPod"),
         Catalog.GetString ("Monopod automatically removes podcasts you have listened to. ") +
         Catalog.GetString ("Try clearing space by removing other music from your iPod.")
         );
     ed.Run ();
     ed.Destroy ();
     return false;
 }
Ejemplo n.º 14
0
        static void ShowMessageBox(string message, MessageBoxImage icon, string stackTrace)
        {
            //determine an icon
            string iconName = icon == MessageBoxImage.Error ? "TextBoxErrorIcon" :
                icon == MessageBoxImage.Warning ? "WarningValidationIcon" : string.Empty;

            //set properties
            var dlg = new ErrorDialog()
            {
                ErrorDescription = message ?? "<null>",
                Icon = EditorResources.GetIcons()[iconName],
                StackTrace = stackTrace,
                StackTraceVisibility = string.IsNullOrEmpty(stackTrace) ? Visibility.Collapsed : Visibility.Visible,
                Context = null != ActiveDesignerView ? ActiveDesignerView.Context : null,
                Owner = ActiveDesignerView,
            };
            //show error window
            dlg.Show();
        }
Ejemplo n.º 15
0
		// Opens a CameraDevice. The result is listened to by 'mStateListener'.
		private void OpenCamera(string targetCamera)
		{
			Activity activity = Activity;
			if (activity == null || activity.IsFinishing || mOpeningCamera)
			{
				return;
			}

			if (CameraStarted)
			{
				CloseCamera();
			}

			mOpeningCamera = true;

			try
			{
				CameraManager manager = (CameraManager)activity.GetSystemService(Context.CameraService);

				// To get a list of available sizes of camera preview, we retrieve an instance of StreamConfigurationMap from CameraCharacteristics
				CameraCharacteristics characteristics = manager.GetCameraCharacteristics(targetCamera);
				StreamConfigurationMap map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap);
				mPreviewSize = map.GetOutputSizes(Java.Lang.Class.FromType(typeof(SurfaceTexture)))[0];
				Android.Content.Res.Orientation orientation = Resources.Configuration.Orientation;
				if (orientation == Android.Content.Res.Orientation.Landscape)
				{
					mTextureView.SetAspectRatio(mPreviewSize.Width, mPreviewSize.Height);
				}
				else
				{
					mTextureView.SetAspectRatio(mPreviewSize.Height, mPreviewSize.Width);
				}
				// We are opening the camera with a listener. When it is ready, OnOpened of mStateListener is called.
				manager.OpenCamera(targetCamera, mStateListener, null);
			}
			catch (CameraAccessException ex)
			{
				Toast.MakeText(activity, "Cannot access the camera.", ToastLength.Short).Show();
				Activity.Finish();
			}
			catch (NullPointerException)
			{
				var dialog = new ErrorDialog();
				dialog.Show(FragmentManager, "dialog");
			}
		}
Ejemplo n.º 16
0
        /// <summary>
        /// Stops the recording or the Pre-Start countdown.
        /// </summary>
        private async void Stop()
        {
            try
            {
                StopButton.IsEnabled = false;

                _captureTimer.Stop();
                FrameRate.Stop();
                _capture?.Stop();

                if (Stage != Stage.Stopped && Stage != Stage.PreStarting && Project.Any)
                {
                    #region Stop

                    if (UserSettings.All.AsyncRecording)
                    {
                        _stopRequested = true;
                    }

                    await Task.Delay(100);

                    Close();

                    #endregion
                }
                else if ((Stage == Stage.PreStarting || Stage == Stage.Snapping) && !Project.Any)
                {
                    #region if Pre-Starting or in Snapmode and no Frames, Stops

                    if (Stage == Stage.PreStarting)
                    {
                        //Stop the pre-start timer to kill pre-start warming up
                        _preStartTimer.Stop();
                    }

                    //Only returns to the stopped stage if it was recording.
                    Stage = Stage == Stage.Snapping ? Stage.Snapping : Stage.Stopped;

                    //Enables the controls that are disabled while recording;
                    FpsIntegerUpDown.IsEnabled  = true;
                    RecordPauseButton.IsEnabled = true;
                    HeightIntegerBox.IsEnabled  = true;
                    WidthIntegerBox.IsEnabled   = true;

                    IsRecording = false;
                    Topmost     = true;

                    Title = "ScreenToGif";

                    AutoFitButtons();

                    #endregion
                }
            }
            catch (NullReferenceException nll)
            {
                LogWriter.Log(nll, "NullPointer on the Stop function");

                ErrorDialog.Ok("ScreenToGif", "Error while stopping", nll.Message, nll);
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Error on the Stop function");

                ErrorDialog.Ok("ScreenToGif", "Error while stopping", ex.Message, ex);
            }
            finally
            {
                if (IsLoaded)
                {
                    StopButton.IsEnabled = true;
                }
            }
        }
Ejemplo n.º 17
0
        private void Snap()
        {
            if (Project == null || Project.Frames.Count == 0)
            {
                try
                {
                    DiscardButton.BeginStoryboard(FindResource("ShowDiscardStoryboard") as Storyboard, HandoffBehavior.Compose);

                    Project = new ProjectInfo().CreateProjectFolder(ProjectByType.ScreenRecorder);

                    PrepareNewCapture();

                    IsRecording = true;
                }
                catch (Exception ex)
                {
                    LogWriter.Log(ex, "Impossible to start the screencasting.");
                    ErrorDialog.Ok(Title, LocalizationHelper.Get("S.Recorder.Warning.CaptureNotPossible"), ex.Message, ex);
                    return;
                }
            }

            if (_capture != null)
            {
                _capture.SnapDelay = UserSettings.All.SnapshotDefaultDelay;
            }

            #region Take Screenshot (All possibles types)

            var limit = 0;
            do
            {
                if (UserSettings.All.ShowCursor)
                {
                    if (UserSettings.All.AsyncRecording)
                    {
                        CursorAsync_Elapsed(null, null);
                    }
                    else
                    {
                        Cursor_Elapsed(null, null);
                    }
                }
                else
                {
                    if (UserSettings.All.AsyncRecording)
                    {
                        NormalAsync_Elapsed(null, null);
                    }
                    else
                    {
                        Normal_Elapsed(null, null);
                    }
                }

                if (limit > 5)
                {
                    ErrorDialog.Ok(Title, LocalizationHelper.Get("S.Recorder.Warning.CaptureNotPossible"), LocalizationHelper.Get("S.Recorder.Warning.CaptureNotPossible.Info"), null);
                    return;
                }

                limit++;
            }while (FrameCount == 0);

            #endregion
        }
Ejemplo n.º 18
0
        public static void Application_ThreadException(object sender, ThreadExceptionEventArgs args)
        {
            Exception e = (Exception)args.Exception;

            if (e is TargetInvocationException)
            {
                while (e.InnerException != null)
                {
                    e = e.InnerException;
                }
            }
            string serverstatck = e.InnerException == null ? string.Empty : e.InnerException.StackTrace;
            ErrorDialog fError = new ErrorDialog(e.Message, e.StackTrace, serverstatck);
            fError.ShowDialog();
            fError.Dispose();
        }
Ejemplo n.º 19
0
        internal bool InstallUpdate(bool wasPromptedManually = false)
        {
            try
            {
                //No new release available.
                if (Global.UpdateAvailable == null)
                {
                    return(false);
                }

                //TODO: Check if Windows is not turning off.

                //Prompt if:
                //Not configured to download the update automatically OR
                //Configured to download but set to prompt anyway OR
                //Download not completed (perharps because the notification was triggered by a query on Fosshub).
                if (UserSettings.All.PromptToInstall || !UserSettings.All.InstallUpdates || string.IsNullOrWhiteSpace(Global.UpdateAvailable.InstallerPath))
                {
                    var download = new DownloadDialog {
                        WasPromptedManually = wasPromptedManually
                    };
                    var result = download.ShowDialog();

                    if (!result.HasValue || !result.Value)
                    {
                        return(false);
                    }
                }

                //Only try to install if the update was downloaded.
                if (!File.Exists(Global.UpdateAvailable.InstallerPath))
                {
                    return(false);
                }

                var files              = Directory.EnumerateFiles(AppDomain.CurrentDomain.BaseDirectory).ToList();
                var isInstaller        = files.Any(x => x.ToLowerInvariant().EndsWith("screentogif.visualelementsmanifest.xml"));
                var hasSharpDx         = files.Any(x => x.ToLowerInvariant().EndsWith("sharpdx.dll"));
                var hasGifski          = files.Any(x => x.ToLowerInvariant().EndsWith("gifski.dll"));
                var hasMenuShortcut    = File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Microsoft", "Windows", "Start Menu", "Programs", "ScreenToGif.lnk"));
                var hasDesktopShortcut = File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Desktop", "ScreenToGif.lnk"));

                var startInfo = new ProcessStartInfo
                {
                    FileName  = "msiexec",
                    Arguments = $" {(isInstaller ? "/i" : "/a")} \"{Global.UpdateAvailable.InstallerPath}\"" +
                                $" {(isInstaller ? "INSTALLDIR" : "TARGETDIR")}=\"{AppDomain.CurrentDomain.BaseDirectory}\" INSTALLAUTOMATICALLY=yes INSTALLPORTABLE={(isInstaller ? "no" : "yes")}" +
                                $" ADDLOCAL=Binary{(isInstaller ? ",Auxiliar" : "")}{(hasSharpDx ? ",SharpDX" : "")}{(hasGifski ? ",Gifski" : "")}" +
                                $" {(wasPromptedManually ? "RUNAFTER=yes" : "")}" +
                                (isInstaller ? $" INSTALLDESKTOPSHORTCUT={(hasDesktopShortcut ? "yes" : "no")} INSTALLSHORTCUT={(hasMenuShortcut ? "yes" : "no")}" : ""),
                    Verb = "runas"
                };

                using (var process = new Process {
                    StartInfo = startInfo
                })
                    process.Start();

                return(true);
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Impossible to automatically install update");

                ErrorDialog.Ok("ScreenToGif", "It was not possible to install the update", ex.Message, ex);
                return(false);
            }
        }
Ejemplo n.º 20
0
    // Adding stuff:
    //   Get URL from user
    //   Then run AddNewChannel
    private void OnChannelAdded(Channel c)
    {
        ListStore store = (ListStore) list.Model;

        if (c.Error != "") {
            c.Delete ();

            ErrorDialog ed = new ErrorDialog (
                Catalog.GetString ("Error Adding Channel - Monopod Podcast Client"),
                Catalog.GetString ("Channel could not be added"),
                Catalog.GetString ("The channel either could not be found or contains errors."));
            ed.Run ();
            ed.Destroy ();
        } else {
            if (TestInclusion (c, showbox.Active)) {
                store.AppendValues (c);
            }
        }
    }
Ejemplo n.º 21
0
 /// <summary>
 /// Show error dialog for non-exceptions.
 /// </summary>
 /// <param name="message">Error message to show</param>
 public static void ShowError(string message)
 {
     ErrorDialog dialog = new ErrorDialog(null);
     dialog.dialog.Title = "Supertux-Editor Error";
     dialog.Message = message;
     dialog.Show();
 }
Ejemplo n.º 22
0
        private void OpenCamera()
        {
            Activity activity = Activity;
            if (activity == null || activity.IsFinishing || mOpeningCamera)
                return;

            mOpeningCamera = true;
            mCameraManager = (CameraManager)activity.GetSystemService (Context.CameraService);
            try
            {
                string cameraId = mCameraManager.GetCameraIdList()[0];

                CameraCharacteristics characteristics = mCameraManager.GetCameraCharacteristics(cameraId);

                StreamConfigurationMap map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap);
                mPreviewSize = map.GetOutputSizes(Java.Lang.Class.FromType(typeof(SurfaceTexture)))[0];
                Android.Content.Res.Orientation orientation = Resources.Configuration.Orientation;

                mCameraManager.OpenCamera(cameraId, mStateListner, null);

                cCharacteristics = characteristics;
            }
            catch(CameraAccessException ex)
            {
                Toast.MakeText (activity, "Cannot access the camera.", ToastLength.Short).Show ();
                Activity.Finish ();
            }
            catch (NullPointerException)
            {
                var dialog = new ErrorDialog ();
                dialog.Show (FragmentManager, "dialog");
            }
        }
		//Tries to open a CameraDevice
		public void openCamera(int width, int height)
		{
			if (null == Activity || Activity.IsFinishing) 
				return;

			CameraManager manager = (CameraManager)Activity.GetSystemService (Context.CameraService);
			try {
				if(!cameraOpenCloseLock.TryAcquire(2500,TimeUnit.Milliseconds))
					throw new RuntimeException("Time out waiting to lock camera opening.");
				string cameraId = manager.GetCameraIdList()[0];
				CameraCharacteristics characteristics = manager.GetCameraCharacteristics(cameraId);
				StreamConfigurationMap map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap);
				videoSize = ChooseVideoSize(map.GetOutputSizes(Class.FromType(typeof(MediaRecorder))));
				previewSize = ChooseOptimalSize(map.GetOutputSizes(Class.FromType(typeof(MediaRecorder))),width,height,videoSize);
				int orientation = (int)Resources.Configuration.Orientation;
				if(orientation == (int)Android.Content.Res.Orientation.Landscape){
					textureView.SetAspectRatio(previewSize.Width,previewSize.Height);
				} else {
					textureView.SetAspectRatio(previewSize.Height,previewSize.Width);
				}
				configureTransform(width,height);
				mediaRecorder = new MediaRecorder();
				manager.OpenCamera(cameraId,stateListener,null);

			} catch (CameraAccessException) {
				Toast.MakeText (Activity, "Cannot access the camera.", ToastLength.Short).Show ();
				Activity.Finish ();
			} catch (NullPointerException) {
				var dialog = new ErrorDialog ();
				dialog.Show (FragmentManager, "dialog");
			} catch (InterruptedException) {
				throw new RuntimeException ("Interrupted while trying to lock camera opening.");
			}
		}
Ejemplo n.º 24
0
 private static void ShowFatalError(Exception e)
 {
     // NB. This could be called on any thread, at any time, so avoid
     // touching the main form.
     ErrorDialog.Show(e);
 }
Ejemplo n.º 25
0
 public void SetUp()
 {
     _errorDialog = new ErrorDialog(string.Empty);
 }
Ejemplo n.º 26
0
 private static void ShowErrorMessageBox(string message)
 {
     using (var dlg = new ErrorDialog(message))
         dlg.ShowDialog(Program.MainWindow);
 }
Ejemplo n.º 27
0
        protected void FindClick(Object sender, EventArgs e)
        {
            SetButtons(true);
            _cancelled = false;

            SearchInvalidate(null);

            TraceUtil.WriteLineInfo(this, "Looking for: " + _findWhat.Text);

            int compareType = 0;

            if (_fullName.Checked)
            {
                compareType = BrowserFinder.COMPARE_FULL;
            }
            else if (_startsWith.Checked)
            {
                compareType = BrowserFinder.COMPARE_STARTS;
            }
            else if (_contains.Checked)
            {
                compareType = BrowserFinder.COMPARE_CONTAINS;
            }

            bool useName  = true;
            bool useValue = false;

            TreeView tree = null;

            if (_treeObj.Checked)
            {
                tree     = ObjectBrowser.ObjTree;
                useName  = _objTreeName.Checked;
                useValue = _objTreeValue.Checked;
            }
            else if (_treeAssy.Checked)
            {
                tree = AssemblySupport.AssyTree;
            }
            else if (_treeAx.Checked)
            {
                tree = ComSupport.ComTree;
            }

            // Got to have one of them
            if (!(useName || useValue))
            {
                ErrorDialog.Show
                    (StringParser.Parse("${res:ComponentInspector.FindDialog.SelectNameOrValueMessage}"),
                    StringParser.Parse("${res:ComponentInspector.FindDialog.SelectNameOrValueDialogTitle}"),
                    MessageBoxIcon.Error);
                SetButtons(false);
                return;
            }

            int maxLevel;

            if (_levelAll.Checked)
            {
                maxLevel = BrowserFinder.ALL_LEVELS;
            }
            else if (!Int32.TryParse(_levelSelectNum.Text, out maxLevel))
            {
                ErrorDialog.Show
                    ("Please input a valid number for the number of levels to search.",
                    String.Empty,
                    MessageBoxIcon.Error);
            }

            _finder = new BrowserFinder
                          ((String)_findWhat.Text,
                          compareType,
                          maxLevel,
                          useName,
                          useValue,
                          (BrowserTreeNode)_startingNode.Tag,
                          _nodeFound,
                          _nodeLooking,
                          _searchStatus,
                          _searchInvalidate);

            tree.BeginUpdate();

            _finder.Search();

            tree.EndUpdate();

            if (_foundList.Items.Count == 0)
            {
                ListViewItem li = new ListViewItem();
                li.Text = StringParser.Parse("${res:ComponentInspector.FindDialog.NoItemsFoundMessage}");
                _foundList.Items.Add(li);
            }

            // Save the last search, only if its different than
            // what has already been saved
            bool found = false;

            foreach (String s in _findWhat.Items)
            {
                if (s.Equals(_findWhat.Text))
                {
                    found = true;
                    break;
                }
            }
            if (!found)
            {
                _findWhat.Items.Insert(0, _findWhat.Text);
            }

            _lookingNodeCount  = 0;
            _lookingLabel.Text = null;
            _lookingNode.Text  = null;
            SetButtons(false);
        }
Ejemplo n.º 28
0
        private void TryCalcMpu(string mapDef)
        {
            BusyWaitDialog.Run(Strings.CalculatingMpu, () =>
            {
                var currentPath = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);
                var mpuCalc     = Path.Combine(currentPath, "AddIns/Local/MpuCalc.exe"); //NOXLATE
                if (!File.Exists(mpuCalc) && mapDef.EndsWith(ResourceTypes.MapDefinition.ToString()))
                {
                    int[] cmdTypes = m_connection.Capabilities.SupportedCommands;
                    if (Array.IndexOf(cmdTypes, (int)OSGeo.MapGuide.MaestroAPI.Commands.CommandType.CreateRuntimeMap) < 0)
                    {
                        IMapDefinition mdf = (IMapDefinition)m_connection.ResourceService.GetResource(mapDef);
                        var calc           = m_connection.GetCalculator();
                        return(new MpuCalcResult()
                        {
                            Method = MpuMethod.BuiltIn,
                            Result = Convert.ToDecimal(calc.Calculate(mdf.CoordinateSystem, 1.0))
                        });
                    }
                    else
                    {
                        ICreateRuntimeMap create = (ICreateRuntimeMap)m_connection.CreateCommand((int)OSGeo.MapGuide.MaestroAPI.Commands.CommandType.CreateRuntimeMap);
                        create.MapDefinition     = mapDef;
                        create.RequestedFeatures = (int)RuntimeMapRequestedFeatures.None;
                        var info = create.Execute();
                        return(new MpuCalcResult()
                        {
                            Method = MpuMethod.CreateRuntimeMap,
                            Result = Convert.ToDecimal(info.CoordinateSystem.MetersPerUnit)
                        });
                    }
                }
                else
                {
                    IResource res          = m_connection.ResourceService.GetResource(mapDef);
                    ITileSetDefinition tsd = res as ITileSetDefinition;
                    IMapDefinition mdf     = res as IMapDefinition;

                    string coordSys = null;
                    if (mdf != null)
                    {
                        coordSys = mdf.CoordinateSystem;
                    }
                    else if (tsd != null)
                    {
                        coordSys = tsd.GetDefaultCoordinateSystem();
                    }

                    string output = string.Empty;
                    if (coordSys != null)
                    {
                        var proc = new Process
                        {
                            StartInfo = new ProcessStartInfo
                            {
                                FileName               = mpuCalc,
                                Arguments              = coordSys,
                                UseShellExecute        = false,
                                RedirectStandardOutput = true,
                                CreateNoWindow         = true
                            }
                        };
                        proc.Start();
                        StringBuilder sb = new StringBuilder();
                        while (!proc.StandardOutput.EndOfStream)
                        {
                            string line = proc.StandardOutput.ReadLine();
                            // do something with line
                            sb.AppendLine(line);
                        }
                        output = sb.ToString();
                    }
                    double mpu;
                    if (double.TryParse(output, out mpu))
                    {
                        return new MpuCalcResult()
                        {
                            Method = MpuMethod.MpuCalcExe, Result = Convert.ToDecimal(mpu)
                        }
                    }
                    ;
                    else
                    {
                        return(string.Format(Strings.FailedToCalculateMpu, output));
                    }
                }
            }, (res, ex) =>
            {
                if (ex != null)
                {
                    ErrorDialog.Show(ex);
                }
                else
                {
                    var mres = res as MpuCalcResult;
                    if (mres != null)
                    {
                        MetersPerUnit.Value = mres.Result;
                        if (mres.Method == MpuMethod.BuiltIn)
                        {
                            MessageBox.Show(Strings.ImperfectMpuCalculation);
                        }
                    }
                    else
                    {
                        MessageBox.Show(res.ToString());
                    }
                }
            });
        }
Ejemplo n.º 29
0
    public void OnError_Authenticate(int statusCode, int reasonCode, string statusMessage, object cbObject)
    {
        m_state    = ResponseState.Error;
        m_response = reasonCode + ":" + statusMessage;
        Debug.LogError("OnError_Authenticate: " + statusMessage);

        if (ErrorHandling.SharedErrorHandling(statusCode, reasonCode, statusMessage, cbObject, gameObject))
        {
            return;
        }

        switch (reasonCode)
        {
        case ReasonCodes.MISSING_IDENTITY_ERROR:
        {
            // User's identity doesn't match one existing on brainCloud
            // Reset profile id and re-authenticate
            App.Bc.Client.AuthenticationService.ClearSavedProfileID();
            ReAuthenticate(true);

            // @see WrapperAuthenticateDialog for an example that uses
            // permission dialog before creating the new profile

            break;
        }

        case ReasonCodes.SWITCHING_PROFILES:
        {
            // User profile id doesn't match the identity they are attempting to authenticate
            // Reset profile id and re-authenticate
            App.Bc.Client.AuthenticationService.ClearSavedProfileID();
            ReAuthenticate();

            // @see WrapperAuthenticateDialog for an example that uses
            // permission dialog before swapping
            break;
        }

        case ReasonCodes.TOKEN_DOES_NOT_MATCH_USER:
        {
            // User is receiving  an error that they're username or password is wrong.
            // decide how this will be handled, such as prompting the user to re-enter
            // there login details
            Destroy(gameObject);
            ErrorDialog.DisplayErrorDialog(
                "Incorrect username or password. Please check your information and try again.", m_response);

            break;
        }

        case ReasonCodes.MISSING_PROFILE_ERROR:
        {
            // User is receiving an error that they're trying to authenticate an account that doesn't exist.
            // decide how this will be handled, such as creating the account by setting the forceCreate flag to true
            ReAuthenticate(true);

            break;
        }

        default:
        {
            // log the reasonCode to your own internal error checking
            ErrorHandling.UncaughtError(statusCode, reasonCode, statusMessage, cbObject, gameObject);

            break;
        }
        }
    }
Ejemplo n.º 30
0
        protected sealed override void ExecuteCore(SelectedItemCollection selection)
        {
            //It only supports one item selected for now
            Trace.Assert(selection.Count == 1);

            XenAPI.Network network = (XenAPI.Network)selection.FirstAsXenObject;
            List <PIF>     pifs    = network.Connection.ResolveAll(network.PIFs);

            if (pifs.Count == 0)
            {
                // Should never happen as long as the caller is enabling the button correctly, but
                // it's possible in a tiny window across disconnecting.
                log.Error("Network has no PIFs");
                return;
            }

            // We just want one, so that we can name it.
            PIF pif = pifs[0];

            string msg = string.Format(Messages.DELETE_BOND_MESSAGE, pif.Name());

            bool will_disturb_primary   = NetworkingHelper.ContainsPrimaryManagement(pifs);
            bool will_disturb_secondary = NetworkingHelper.ContainsSecondaryManagement(pifs);

            if (will_disturb_primary)
            {
                Pool pool = Helpers.GetPool(network.Connection);
                if (pool != null && pool.ha_enabled)
                {
                    using (var dlg = new ErrorDialog(string.Format(Messages.BOND_DELETE_HA_ENABLED, pif.Name(), pool.Name()))
                    {
                        WindowTitle = Messages.DELETE_BOND
                    })
                    {
                        dlg.ShowDialog(Parent);
                    }
                    return;
                }

                string message = string.Format(will_disturb_secondary ? Messages.BOND_DELETE_WILL_DISTURB_BOTH : Messages.BOND_DELETE_WILL_DISTURB_PRIMARY, msg);

                DialogResult result;
                using (var dlg = new WarningDialog(message,
                                                   new ThreeButtonDialog.TBDButton(Messages.BOND_DELETE_CONTINUE, DialogResult.OK),
                                                   ThreeButtonDialog.ButtonCancel)
                {
                    HelpName = "NetworkingConfigWarning",
                    WindowTitle = Messages.DELETE_BOND
                })
                {
                    result = dlg.ShowDialog(Parent);
                }
                if (DialogResult.OK != result)
                {
                    return;
                }
            }
            else if (will_disturb_secondary)
            {
                DialogResult dialogResult;
                using (var dlg = new WarningDialog(string.Format(Messages.BOND_DELETE_WILL_DISTURB_SECONDARY, msg),
                                                   ThreeButtonDialog.ButtonOK,
                                                   ThreeButtonDialog.ButtonCancel))
                {
                    dialogResult = dlg.ShowDialog(Parent);
                }
                if (DialogResult.OK != dialogResult)
                {
                    return;
                }
            }
            else
            {
                DialogResult dialogResult;
                using (var dlg = new WarningDialog(msg,
                                                   new ThreeButtonDialog.TBDButton(Messages.OK, DialogResult.OK, selected: true),
                                                   ThreeButtonDialog.ButtonCancel))
                {
                    dialogResult = dlg.ShowDialog(Parent);
                }
                if (DialogResult.OK != dialogResult)
                {
                    return;
                }
            }

            // The UI shouldn't offer deleting a bond in this case, but let's make sure we've
            // done the right thing and that the bond hasn't been deleted in the meantime. (CA-27436).
            Bond bond = pif.BondMasterOf();

            if (bond != null)
            {
                new Actions.DestroyBondAction(bond).RunAsync();
            }
        }
Ejemplo n.º 31
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            #region Unhandled Exceptions

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            #endregion

            #region Arguments

            try
            {
                if (e.Args.Length > 0)
                {
                    Argument.Prepare(e.Args);
                }
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Generic Exception - Arguments");

                ErrorDialog.Ok("ScreenToGif", "Generic error - arguments", ex.Message, ex);
            }

            #endregion

            #region Language

            try
            {
                LocalizationHelper.SelectCulture(UserSettings.All.LanguageCode);
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Language Settings Exception.");

                ErrorDialog.Ok("ScreenToGif", "Generic error - language", ex.Message, ex);
            }

            #endregion

            #region Net Framework

            var array  = Type.GetType("System.Array");
            var method = array?.GetMethod("Empty");

            if (array == null || method == null)
            {
                var ask = Dialog.Ask("Missing Dependency", "Net Framework 4.6.1 is not present", "In order to properly use this app, you need to download the correct version of the .Net Framework. Open the web page to download?");

                if (ask)
                {
                    Process.Start("https://www.microsoft.com/en-us/download/details.aspx?id=49981");
                    return;
                }
            }

            //try
            //{
            //    //If there's no Array.Empty, means that there's no .Net Framework 4.6.1
            //    //This is not the best way...
            //    Array.Empty<int>();
            //}
            //catch (MissingMethodException ex)
            //{
            //    var ask = Dialog.Ask("Missing Dependency", "Net Framework 4.6.1 is not present", "In order to properly use this app, you need to download the correct version of the .Net Framework. Open the web page to download?");

            //    if (ask)
            //    {
            //        Process.Start("https://www.microsoft.com/en-us/download/details.aspx?id=49981");
            //        return;
            //    }

            //    LogWriter.Log(ex, "Missing .Net Framework 4.6.1");
            //}

            //if (Environment.Version.Build < 30319 && Environment.Version.Revision < 42000)
            //{
            //    var ask = Dialog.Ask("Missing Dependency", "Net Framework 4.6.1 is not present", "In order to properly use this app, you need to download the correct version of the .Net Framework. Open the page to download?");

            //    if (ask)
            //    {
            //        Process.Start("https://www.microsoft.com/en-us/download/details.aspx?id=49981");
            //        return;
            //    }
            //}

            #endregion

            //var select = new GhostRecorder();
            //var select = new SelectFolderDialog();
            //var select = new TestField();
            //var select = new Encoder();

            //select.ShowDialog();
            //return;

            try
            {
                #region Startup

                if (UserSettings.All.StartUp == 0)
                {
                    var startup = new Startup();
                    Current.MainWindow = startup;
                    startup.ShowDialog();
                }
                else if (UserSettings.All.StartUp == 4 || Argument.FileNames.Any())
                {
                    var edit = new Editor();
                    Current.MainWindow = edit;
                    edit.ShowDialog();
                }
                else
                {
                    var         editor  = new Editor();
                    ProjectInfo project = null;
                    var         exitArg = ExitAction.Exit;
                    bool?       result  = null;

                    #region Recorder, Webcam or Border

                    switch (UserSettings.All.StartUp)
                    {
                    case 1:
                        var rec = new Recorder(true);
                        Current.MainWindow = rec;

                        result  = rec.ShowDialog();
                        exitArg = rec.ExitArg;
                        project = rec.Project;
                        break;

                    case 2:
                        var web = new Windows.Webcam(true);
                        Current.MainWindow = web;

                        result  = web.ShowDialog();
                        exitArg = web.ExitArg;
                        project = web.Project;
                        break;

                    case 3:
                        var board = new Board();
                        Current.MainWindow = board;

                        result  = board.ShowDialog();
                        exitArg = board.ExitArg;
                        project = board.Project;
                        break;
                    }

                    #endregion

                    if (result.HasValue && result.Value)
                    {
                        #region If Close

                        Environment.Exit(0);

                        #endregion
                    }
                    else if (result.HasValue)
                    {
                        #region If Backbutton or Stop Clicked

                        if (exitArg == ExitAction.Recorded)
                        {
                            editor.Project     = project;
                            Current.MainWindow = editor;
                            editor.ShowDialog();
                        }

                        #endregion
                    }
                }

                #endregion
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Generic Exception - Root");

                ErrorDialog.Ok("ScreenToGif", "Generic error", ex.Message, ex);
            }
        }
Ejemplo n.º 32
0
 internal TesteableErrorDialog(ErrorDialog dialog)
 {
     mErrorDialog = dialog;
     mHelper      = new TestHelper(mErrorDialog);
 }
Ejemplo n.º 33
0
        /// <summary>
        /// Method that starts or pauses the recording
        /// </summary>
        internal async void RecordPause()
        {
            try
            {
                switch (Stage)
                {
                case Stage.Stopped:

                    #region To Record

                    _captureTimer = new Timer {
                        Interval = 1000 / FpsIntegerUpDown.Value
                    };

                    Project = new ProjectInfo().CreateProjectFolder(ProjectByType.ScreenRecorder);

                    _keyList.Clear();
                    FrameCount = 0;

                    await Task.Factory.StartNew(UpdateScreenDpi);

                    PrepareNewCapture();

                    HeightIntegerBox.IsEnabled = false;
                    WidthIntegerBox.IsEnabled  = false;
                    FpsIntegerUpDown.IsEnabled = false;

                    IsRecording = true;
                    Topmost     = true;

                    FrameRate.Start(_captureTimer.Interval);
                    UnregisterEvents();

                    #region Start

                    if (UserSettings.All.UsePreStart)
                    {
                        Title = $"ScreenToGif ({LocalizationHelper.Get("Recorder.PreStart")} {UserSettings.All.PreStartValue}s)";
                        RecordPauseButton.IsEnabled = false;

                        Stage          = Stage.PreStarting;
                        _preStartCount = UserSettings.All.PreStartValue - 1;

                        _preStartTimer.Start();
                    }
                    else
                    {
                        if (UserSettings.All.ShowCursor)
                        {
                            #region If Show Cursor

                            if (UserSettings.All.AsyncRecording)
                            {
                                _captureTimer.Tick += CursorAsync_Elapsed;
                            }
                            else
                            {
                                _captureTimer.Tick += Cursor_Elapsed;
                            }

                            _captureTimer.Start();

                            Stage = Stage.Recording;

                            AutoFitButtons();

                            #endregion
                        }
                        else
                        {
                            #region If Not

                            if (UserSettings.All.AsyncRecording)
                            {
                                _captureTimer.Tick += NormalAsync_Elapsed;
                            }
                            else
                            {
                                _captureTimer.Tick += Normal_Elapsed;
                            }

                            _captureTimer.Start();

                            Stage = Stage.Recording;

                            AutoFitButtons();

                            #endregion
                        }
                    }
                    break;

                    #endregion

                    #endregion

                case Stage.Recording:

                    #region To Pause

                    _captureTimer.Stop();
                    FrameRate.Stop();

                    Stage = Stage.Paused;
                    Title = LocalizationHelper.Get("Recorder.Paused");

                    DiscardButton.BeginStoryboard(FindResource("ShowDiscardStoryboard") as Storyboard, HandoffBehavior.Compose);

                    AutoFitButtons();
                    break;

                    #endregion

                case Stage.Paused:

                    #region To Record Again

                    Stage = Stage.Recording;
                    Title = "ScreenToGif";

                    DiscardButton.BeginStoryboard(FindResource("HideDiscardStoryboard") as Storyboard, HandoffBehavior.Compose);

                    AutoFitButtons();

                    FrameRate.Start(_captureTimer.Interval);
                    _captureTimer.Start();
                    break;

                    #endregion
                }
            }
            catch (Exception e)
            {
                LogWriter.Log(e, "Impossible to start the recording.");
                ErrorDialog.Ok(Title, LocalizationHelper.Get("S.Recorder.Warning.StartPauseNotPossible"), e.Message, e);
            }
        }
Ejemplo n.º 34
0
        private async void querySubmittedZoek(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
        {
            Debug.WriteLine("querysubmittedzoek; " + args.QueryText);
            string input = args.QueryText;
            List <SearchResult> listResults = new List <SearchResult>();

            //Search in Database
            bool        availableInDb = false;
            Task <bool> searchInDb    = Task <bool> .Factory.StartNew(() =>
            {
                List <string> output = new List <string>();
                bool succeeded       = false;

                dbConn dbConnection = new dbConn();

                try
                {
                    MySqlCommand cmd = dbConnection.selectQuery("SELECT * FROM video WHERE title LIKE '%" + input + "%' ORDER BY id DESC LIMIT 0,4");

                    MySqlDataReader reader = cmd.ExecuteReader();

                    string urlx;
                    string titlex;
                    string descriptionx;
                    string genrex;
                    string thumbx;

                    while (reader.Read())
                    {
                        urlx         = (string)reader["url"];
                        titlex       = (string)reader["title"];
                        descriptionx = (string)reader["description"];
                        genrex       = (string)reader["genre"];
                        thumbx       = (string)reader["thumbnail"];
                        urlx        += ";" + titlex + ";" + thumbx;

                        listResults.Add(new SearchResult {
                            url         = urlx,
                            title       = titlex,
                            description = descriptionx,
                            genre       = genrex,
                            thumb       = thumbx
                        });
                        succeeded = true;
                    }

                    reader.Close();
                }
                catch (MySqlException ex)
                {
                    Debug.WriteLine(ex.Message);
                }

                dbConnection.dbClose();
                return(succeeded);
            });

            searchInDb.Wait();
            SearchWordResults.ItemsSource = listResults;
            availableInDb = await searchInDb;
            if (!availableInDb)
            {
                //Cannot be found in database.
                await Search.crawlerSearchterm(input);

                ErrorDialog.showMessage("Crawler is aan het zoeken, probeer het zo weer");
            }
        }
Ejemplo n.º 35
0
        public LinkViewModel()
        {
            Interfaces = new ObservableCollection <string>();

            LinkSelected = AUTDSettings.Instance.ToReactivePropertySlimAsSynchronized(i => i.LinkSelected);
            CycleTicks   = AUTDSettings.Instance.ToReactivePropertySlimAsSynchronized(i => i.CycleTicks);
            EmulatorPort = AUTDSettings.Instance.ToReactivePropertySlimAsSynchronized(i => i.EmulatorPort);

            try
            {
                UpdateInterfacesList();
            }
            catch (DllNotFoundException)
            {
                LinkSelected.Value = LinkSelect.TwinCAT;
            }

            InterfaceName = AUTDSettings.Instance.ToReactivePropertySlimAsSynchronized(i => i.InterfaceName);

            UpdateInterfaces = LinkSelected.Select(s => s == LinkSelect.SOEM).ToAsyncReactiveCommand();
            UpdateInterfaces.Subscribe(async _ =>
            {
                try
                {
                    UpdateInterfacesList();
                }
                catch (DllNotFoundException e)
                {
                    var vm = new ErrorDialogViewModel {
                        Message = { Value = $"{e.Message}.\nDid you install npcap or winpcap?" }
                    };
                    var dialog = new ErrorDialog
                    {
                        DataContext = vm
                    };
                    await DialogHost.Show(dialog, "MessageDialogHost");
                }
            });

            Close = AUTDHandler.Instance.IsOpen.Select(i => i).ToReactiveCommand();
            Close.Subscribe(_ =>
            {
                AUTDHandler.Instance.Close();
            });
            Open = AUTDHandler.Instance.IsOpen.Select(i => !i).ToAsyncReactiveCommand();
            Open.Subscribe(async _ =>
            {
                var res = await Task.Run(() => AUTDHandler.Instance.Open());

                if (res == null)
                {
                    return;
                }

                var vm = new ErrorDialogViewModel {
                    Message = { Value = $"Failed to Open AUTD. {res}" }
                };
                var dialog = new ErrorDialog
                {
                    DataContext = vm
                };
                await DialogHost.Show(dialog, "MessageDialogHost");
            });
        }
        /// <summary>
        /// VRChatアバターインスタンスからVRMインスタンスへ変換します。
        /// </summary>
        /// <param name="instance">ヒエラルキー上のGameObject。</param>
        /// <param name="presetVRChatBindingPairs">各表情への割り当て。</param>
        internal static void Convert(
            string outputPath,
            GameObject instance,
            VRMMetaObject meta,
            IDictionary <ExpressionPreset, VRChatExpressionBinding> presetVRChatBindingPairs
            )
        {
            GameObject clone = null, normalized = null;

            try
            {
                var rootObjectName = instance.name;
                clone = Object.Instantiate(instance);

                // 非表示のオブジェクト・コンポーネントを削除
                // TODO: アクティブ・非アクティブの切り替えをシェイプキーに変換する
                VRChatToVRMConverter.RemoveInactiveObjectsAndDisabledComponents(clone);


                // 表情とシェイプキー名の組み合わせを取得
                var presetShapeKeyNameWeightPairsPairs = presetVRChatBindingPairs.ToDictionary(
                    presetVRChatBindingPair => presetVRChatBindingPair.Key,
                    presetVRChatBindingPair => VRChatExpressionsReplacer.ExtractShapeKeyNames(presetVRChatBindingPair.Value)
                    );

                // VRM設定1
                var temporaryFolder = UnityPath.FromUnityPath(VRChatToVRMConverter.TemporaryFolderPath);
                temporaryFolder.EnsureFolder();
                var temporaryPrefabPath = temporaryFolder.Child(VRChatToVRMConverter.TemporaryPrefabFileName).Value;
                VRMInitializer.Initialize(temporaryPrefabPath, clone);
                VRChatToVRMConverter.SetFirstPersonOffset(clone);
                VRChatToVRMConverter.SetLookAtBoneApplyer(clone);
                var sourceAndDestination = clone.GetComponent <Animator>();
                if (DynamicBones.IsImported())
                {
                    DynamicBonesToVRMSpringBonesConverter.Convert(
                        source: sourceAndDestination,
                        destination: sourceAndDestination
                        );
                    VRChatToVRMConverter.RemoveUnusedColliderGroups(clone);
                }

                // 正規化
                normalized = VRMBoneNormalizer.Execute(clone, forceTPose: true);

                // 全メッシュ結合
                var combinedRenderer = CombineMeshesAndSubMeshes.Combine(
                    normalized,
                    notCombineRendererObjectNames: new List <string>(),
                    destinationObjectName: "vrm-mesh",
                    savingAsAsset: false
                    );

                // 使用していないシェイプキーの削除
                SkinnedMeshUtility.CleanUpShapeKeys(combinedRenderer.sharedMesh, presetShapeKeyNameWeightPairsPairs
                                                    .SelectMany(presetShapeKeyNameWeightPairsPair => presetShapeKeyNameWeightPairsPair.Value.Keys)
                                                    .Distinct());

                // シェイプキーの分離
                Utilities.MeshUtility.SeparationProcessing(normalized);

                // マテリアルの設定・アセットとして保存
                VRChatToVRMConverter.ReplaceShaders(normalized, temporaryPrefabPath);

                // GameObject・メッシュなどをアセットとして保存 (アセットとして存在しないと正常にエクスポートできない)
                normalized.name = rootObjectName;
                var animator = normalized.GetComponent <Animator>();
                animator.avatar = Duplicator.CreateObjectToFolder(animator.avatar, temporaryPrefabPath);
                meta.name       = "Meta";
                normalized.GetComponent <VRMMeta>().Meta = Duplicator.CreateObjectToFolder(meta, temporaryPrefabPath);
                foreach (var renderer in normalized.GetComponentsInChildren <SkinnedMeshRenderer>())
                {
                    renderer.sharedMesh.name = renderer.name;
                    renderer.sharedMesh      = Duplicator.CreateObjectToFolder(renderer.sharedMesh, temporaryPrefabPath);
                }

                // VRM設定2
                VRChatToVRMConverter.SetFirstPersonRenderers(normalized);

                // 表情の設定
                VRChatExpressionsReplacer.SetExpressions(normalized, presetShapeKeyNameWeightPairsPairs);

                var prefab = PrefabUtility
                             .SaveAsPrefabAssetAndConnect(normalized, temporaryPrefabPath, InteractionMode.AutomatedAction);

                // エクスポート
                AssetDatabase.SaveAssets();
                File.WriteAllBytes(
                    outputPath,
                    VRMEditorExporter.Export(prefab, meta: null, ScriptableObject.CreateInstance <VRMExportSettings>())
                    );
            }
            catch (Exception exception)
            {
                ErrorDialog.Open(exception);
                throw;
            }
            finally
            {
                if (clone != null)
                {
                    Object.DestroyImmediate(clone);
                }
                if (normalized != null)
                {
                    Object.DestroyImmediate(normalized);
                }
                AssetDatabase.DeleteAsset("Assets/VRMConverterTemporary");
            }
        }
Ejemplo n.º 37
0
 public MyDialogOnClickListener(ErrorDialog e)
 {
     er = e;
 }
Ejemplo n.º 38
0
        private void buttonAuthorize_Click(object sender, EventArgs e)
        {
            try
            {
                Exception delegateException = null;
                log.Debug("Testing logging in with the new credentials");
                DelegatedAsyncAction loginAction = new DelegatedAsyncAction(connection,
                                                                            Messages.AUTHORIZING_USER,
                                                                            Messages.CREDENTIALS_CHECKING,
                                                                            Messages.CREDENTIALS_CHECK_COMPLETE,
                                                                            delegate
                {
                    try
                    {
                        elevatedSession = connection.ElevatedSession(TextBoxUsername.Text.Trim(), TextBoxPassword.Text);
                    }
                    catch (Exception ex)
                    {
                        delegateException = ex;
                    }
                });

                using (var dlg = new ActionProgressDialog(loginAction, ProgressBarStyle.Marquee, false))
                    dlg.ShowDialog(this);

                // The exception would have been handled by the action progress dialog, just return the user to the sudo dialog
                if (loginAction.Exception != null)
                {
                    return;
                }

                if (HandledAnyDelegateException(delegateException))
                {
                    return;
                }

                if (elevatedSession.IsLocalSuperuser || SessionAuthorized(elevatedSession))
                {
                    elevatedUsername = TextBoxUsername.Text.Trim();
                    elevatedPassword = TextBoxPassword.Text;
                    DialogResult     = DialogResult.OK;
                    Close();
                    return;
                }

                ShowNotAuthorisedDialog();
            }
            catch (Exception ex)
            {
                log.DebugFormat("Exception when attempting to sudo action: {0} ", ex);
                using (var dlg = new ErrorDialog(string.Format(Messages.USER_AUTHORIZATION_FAILED, TextBoxUsername.Text)))
                    dlg.ShowDialog(Parent);

                TextBoxPassword.Focus();
                TextBoxPassword.SelectAll();
            }
            finally
            {
                // Check whether we have a successful elevated session and whether we have been asked to log it out
                // If non successful (most likely the new subject is not authorized) then log it out anyway.
                if (elevatedSession != null && DialogResult != DialogResult.OK)
                {
                    elevatedSession.Connection.Logout(elevatedSession);
                    elevatedSession = null;
                }
            }
        }
 private static void ShowErrDialog(Exception e)
 {
     ErrorDialog.ShowErrorDialog(string.Format("An unhandled exception occurred: {0}", e.Message), e.StackTrace,
                                 e.ToString(), false);
 }
Ejemplo n.º 40
0
        private void ShowErrorDialog(Exception ex, bool showStackTrace, bool internalError, ExceptionInfo info)
        {
            string stackTrace = ex.ToString();
            string message    = GetNestedMessages(ex);

            System.Collections.Specialized.StringDictionary additionalInfo =
                new System.Collections.Specialized.StringDictionary();

            IAnkhSolutionSettings ss = GetService <IAnkhSolutionSettings>();

            if (ss != null)
            {
                additionalInfo.Add("VS-Version", VSVersion.FullVersion.ToString());
            }

            if (info != null && info.CommandArgs != null)
            {
                additionalInfo.Add("Command", info.CommandArgs.Command.ToString());
            }

            IAnkhPackage pkg = GetService <IAnkhPackage>();

            if (pkg != null)
            {
                additionalInfo.Add("Ankh-Version", pkg.UIVersion.ToString());
            }

            additionalInfo.Add("SharpSvn-Version", SharpSvn.SvnClient.SharpSvnVersion.ToString());
            additionalInfo.Add("Svn-Version", SharpSvn.SvnClient.Version.ToString());
            additionalInfo.Add("OS-Version", Environment.OSVersion.Version.ToString());

            using (ErrorDialog dlg = new ErrorDialog())
            {
                dlg.ErrorMessage   = message;
                dlg.ShowStackTrace = showStackTrace;
                dlg.StackTrace     = stackTrace;
                dlg.InternalError  = internalError;

                if (dlg.ShowDialog(Context) == DialogResult.Retry)
                {
                    string subject = _errorReportSubject;

                    if (info != null && info.CommandArgs != null)
                    {
                        subject = string.Format("Error handling {0}", info.CommandArgs.Command);
                    }

                    SvnException sx = ex as SvnException;
                    SvnException ix;

                    while (sx != null &&
                           sx.SvnErrorCode == SvnErrorCode.SVN_ERR_BASE &&
                           (null != (ix = sx.InnerException as SvnException)))
                    {
                        sx = ix;
                    }

                    if (sx != null)
                    {
                        SvnException rc = sx.RootCause as SvnException;
                        if (rc == null || rc.SvnErrorCode == sx.SvnErrorCode)
                        {
                            subject += " (" + ErrorToString(sx) + ")";
                        }
                        else
                        {
                            subject += " (" + ErrorToString(sx) + "-" + ErrorToString(rc) + ")";
                        }
                    }

                    AnkhErrorMessage.SendByMail(_errorReportMailAddress,
                                                subject, ex, typeof(AnkhErrorHandler).Assembly, additionalInfo);
                }
            }
        }
Ejemplo n.º 41
0
    public static void Exception(string Mess, Exception e)
    {
        ErrorDialog dialog = new ErrorDialog(null);

        dialog.Message = Mess + ": " + e.Message;
        do {
            dialog.AddDetails("\"" + e.Message + "\"\n", false);
            dialog.AddDetails(e.StackTrace, false);

            if(e.InnerException != null) {
                dialog.AddDetails("\n\n--Caused by--\n\n", false);
            }
            e = e.InnerException;
        } while(e != null);

        dialog.Show();
    }
Ejemplo n.º 42
0
        // Opens a CameraDevice. The result is listened to by 'cameraStateListener'.
        private void OpenCamera()
        {
            var activity = this.Activity;

            if (activity == null || activity.IsFinishing)
            {
                return;
            }

            this.tracer.Debug("OpenCamera");
            this.tracer.Debug("OpenCamera: this.facing={0}", this.facing.ToString());

            var cameraManager = (CameraManager)activity.GetSystemService(Context.CameraService);

            try
            {
                if (!this.mCameraOpenCloseLock.TryAcquire(2500, TimeUnit.Milliseconds))
                {
                    const string ErrorMessage = "Time out waiting to lock camera opening.";
                    this.tracer.Error(ErrorMessage);
                    throw new RuntimeException(ErrorMessage);
                }

                string   idForOpen  = null;
                string[] camerasIds = cameraManager.GetCameraIdList();
                foreach (string id in camerasIds)
                {
                    CameraCharacteristics cameraCharacteristics = cameraManager.GetCameraCharacteristics(id);
                    var cameraLensFacing = (Integer)cameraCharacteristics.Get(CameraCharacteristics.LensFacing);

                    CameraFacingDirection cameraFacingDirection     = ToCameraFacingDirection(cameraLensFacing);
                    CameraFacingDirection configuredFacingDirection = ToCameraFacingDirection(this.facing);

                    this.tracer.Debug("OpenCamera: cameraFacingDirection={0}, configuredFacingDirection={1}", cameraFacingDirection, configuredFacingDirection);
                    if (cameraFacingDirection == configuredFacingDirection)
                    {
                        idForOpen = id;
                        break;
                    }
                }

                var cameraId = idForOpen ?? camerasIds[0];
                this.tracer.Debug("OpenCamera: idForOpen={0}", idForOpen);
                this.tracer.Debug("OpenCamera: idForOpen={0}", idForOpen);
                this.tracer.Debug("OpenCamera: cameraId={0}", cameraId);

                // To get a list of available sizes of camera preview, we retrieve an instance of
                // StreamConfigurationMap from CameraCharacteristics
                CameraCharacteristics  characteristics = cameraManager.GetCameraCharacteristics(cameraId);
                StreamConfigurationMap map             = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap);
                this.previewSize = map.GetOutputSizes(Class.FromType(typeof(SurfaceTexture)))[0]; // We assume that the top-most element is the one with the best resolution
                Orientation orientation = this.Resources.Configuration.Orientation;
                if (orientation == Orientation.Landscape)
                {
                    this.autoFitTextureView.SetAspectRatio(this.previewSize.Width, this.previewSize.Height);
                }
                else
                {
                    this.autoFitTextureView.SetAspectRatio(this.previewSize.Height, this.previewSize.Width);
                }

                ////this.ConfigureTransform(this.autoFitTextureView.Width, this.autoFitTextureView.Width);

                // We are opening the camera with a listener. When it is ready, OnOpened of cameraStateListener is called.
                cameraManager.OpenCamera(cameraId, this.cameraStateListener, null);
            }
            catch (CameraAccessException caex)
            {
                this.tracer.Exception(caex, "Cannot access the camera.");
                Toast.MakeText(activity, "Cannot access the camera.", ToastLength.Short).Show();
                this.Activity.Finish();
            }
            catch (NullPointerException npex)
            {
                this.tracer.Exception(npex, "This device doesn't support Camera2 API.");

                var dialog = new ErrorDialog();
                dialog.Show(this.FragmentManager, "dialog");
            }
            catch (InterruptedException e)
            {
                const string ErrorMessage = "Interrupted while trying to lock camera opening.";
                this.tracer.Exception(e, ErrorMessage);
                throw new RuntimeException(ErrorMessage);
            }
            catch (Exception ex)
            {
                this.tracer.Exception(ex);
                throw;
            }
        }
Ejemplo n.º 43
0
 /// <summary>
 /// Show error dialog for non-exceptions.
 /// </summary>
 /// <param name="message">Error message to show</param>
 /// <param name="details">Message to put under "details".</param>
 public static void ShowError(string message, string details)
 {
     ErrorDialog dialog = new ErrorDialog(null);
     dialog.dialog.Title = "Supertux-Editor Error";
     dialog.Message = message;
     dialog.AddDetails(details, true);
     dialog.Show();
 }
Ejemplo n.º 44
0
        private void DoProcessRequest(HttpListenerContext context)
        {
            try
            {
                var response = context.Response;
                var url      = context.Request.Url.LocalPath;
                url = url.Replace('/', '\\');
                if (url.EndsWith("\\"))
                {
                    url += "index.html";
                }

                var courseRequested = url.Contains("course");
                var location        = courseRequested ? Course.Course.FullPath : PlayerLocation;
                if (courseRequested)
                {
                    url = url.Remove(0, "/course".Length);
                }

                if (!File.Exists(location + url))
                {
                    response.StatusCode        = 404;
                    response.StatusDescription = "File not found.";
                }
                else
                {
                    try
                    {
                        using (var r = new FileStream(location + url, FileMode.Open, FileAccess.Read))
                        {
                            var buf = new byte[BufSize];
                            int c;
                            do
                            {
                                c = r.Read(buf, 0, BufSize);
                                response.OutputStream.Write(buf, 0, c);
                            }while (c > 0);
                        }

                        response.StatusCode        = 200;
                        response.StatusDescription = "Ok";
                    }
                    catch (Exception e)
                    {
                        response.StatusCode        = 500;
                        response.StatusDescription = "Internal Server error";

                        ErrorDialog.ShowError(e.Message);
                    }
                }
            }
            catch (HttpListenerException e)
            {
                var ec = e.ErrorCode;
                if (ec != 64 && ec != 1236 && ec != 1229)
                {
                    throw;
                }
            }
            finally
            {
                context.Response.Close();
            }
        }
Ejemplo n.º 45
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            Global.StartupDateTime = DateTime.Now;

            //Unhandled Exceptions.
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            //Increases the duration of the tooltip display.
            ToolTipService.ShowDurationProperty.OverrideMetadata(typeof(DependencyObject), new FrameworkPropertyMetadata(int.MaxValue));

            #region Arguments

            try
            {
                if (e.Args.Length > 0)
                {
                    Argument.Prepare(e.Args);
                }
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Generic Exception - Arguments");

                ErrorDialog.Ok("ScreenToGif", "Generic error - arguments", ex.Message, ex);
            }

            #endregion

            #region Language

            try
            {
                LocalizationHelper.SelectCulture(UserSettings.All.LanguageCode);
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Language Settings Exception.");

                ErrorDialog.Ok("ScreenToGif", "Generic error - language", ex.Message, ex);
            }

            #endregion

            #region Net Framework

            var array  = Type.GetType("System.Array");
            var method = array?.GetMethod("Empty");

            if (array == null || method == null)
            {
                var ask = Dialog.Ask("Missing Dependency", "Net Framework 4.6.1 is not present", "In order to properly use this app, you need to download the correct version of the .Net Framework. Open the web page to download?");

                if (ask)
                {
                    Process.Start("https://www.microsoft.com/en-us/download/details.aspx?id=49981");
                    return;
                }
            }

            #endregion

            #region Net Framework HotFixes

            if (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor == 1)
            {
                try
                {
                    var search = new ManagementObjectSearcher("SELECT HotFixID FROM Win32_QuickFixEngineering WHERE HotFixID = 'KB4055002'").Get();
                    Global.IsHotFix4055002Installed = search.Count > 0;
                }
                catch (Exception ex)
                {
                    LogWriter.Log(ex, "Error while trying to know if a hot fix was installed.");
                }
            }

            #endregion

            #region Tray icon and view model

            NotifyIcon = (NotifyIcon)FindResource("NotifyIcon");

            if (NotifyIcon != null)
            {
                NotifyIcon.Visibility = UserSettings.All.ShowNotificationIcon ? Visibility.Visible : Visibility.Collapsed;
            }

            MainViewModel = (ApplicationViewModel)FindResource("AppViewModel") ?? new ApplicationViewModel();

            RegisterShortcuts();

            #endregion

            //var select = new SelectFolderDialog(); select.ShowDialog(); return;
            //var select = new TestField(); select.ShowDialog(); return;
            //var select = new Encoder(); select.ShowDialog(); return;

            try
            {
                #region Startup

                if (UserSettings.All.StartUp == 4 || Argument.FileNames.Any())
                {
                    MainViewModel.OpenEditor.Execute(null);
                    return;
                }

                if (UserSettings.All.StartUp == 0)
                {
                    MainViewModel.OpenLauncher.Execute(null);
                    return;
                }

                if (UserSettings.All.StartUp == 1)
                {
                    MainViewModel.OpenRecorder.Execute(null);
                    return;
                }

                if (UserSettings.All.StartUp == 2)
                {
                    MainViewModel.OpenWebcamRecorder.Execute(null);
                    return;
                }

                if (UserSettings.All.StartUp == 3)
                {
                    MainViewModel.OpenBoardRecorder.Execute(null);
                }

                #endregion
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Generic Exception - Root");

                ShowException(ex);
            }
        }
Ejemplo n.º 46
0
 // Token: 0x0600355B RID: 13659
 // RVA: 0x0016D3DC File Offset: 0x0016B5DC
 public void method_0()
 {
     Class115.smethod_6(true);
     Class115.class114_0.bool_7 = true;
     ErrorDialog errorDialog = new ErrorDialog(this.unhandledExceptionEventArgs_0.ExceptionObject as Exception, true);
     errorDialog.ShowDialog();
     Class809.smethod_27();
     Environment.Exit(-1);
 }
			public MyDialogOnClickListener(ErrorDialog e)
			{
				er = e;
			}
Ejemplo n.º 48
0
        private void ShowErrorDialog(string message)
        {
            var error = new ErrorDialog(message);

            error.ShowAsync().GetAwaiter();
        }