private void OnRecordUp(object sender, MouseEventArgs e)
        {
            if (!_recorder.IsRecording)
            {
                return;
            }
            try
            {
                _recorder.StopRecordingAndSaveAsWav();
            }
            catch (Exception)
            {
                //swallow it review: initial reason is that they didn't hold it down long enough, could detect and give message
            }

            if (_recorder.LastRecordingMilliseconds < 500)
            {
                if (File.Exists(_path))
                {
                    File.Delete(_path);
                }
                _hint.Text = "Hold down the record button while talking.";
            }
            else
            {
                _hint.Text = "";
            }
            UpdateScreen();
            if (SoundRecorded != null)
            {
                SoundRecorded.Invoke(this, null);
                UsageReporter.SendNavigationNotice("AudioRecorded");
            }
        }
Exemple #2
0
        private void ActivateTab(Control page, bool okTouseTimer)
        {
            var task = (ITask)page.Tag;

            if (ActiveTask == task)
            {
                return;                 //debounce
            }

            if (ActiveTask != null)
            {
                ActiveTask.Deactivate();
                _activeTask = null;
            }
            if (task != null)
            {
                page.Cursor = Cursors.WaitCursor;
                page.Controls.Clear();
                if (Visible && okTouseTimer)
                {
                    ActivateAfterScreenDraw(page, task);
                }
                else
                {
                    ActivateTask(page, task);
                }
                UsageReporter.SendNavigationNotice(task.Label);
            }
        }
Exemple #3
0
        private void DoGripDrag()
        {
            Point mouse = PointToClient(MousePosition);

            if (_gripperBeingDragged.MovesVertically)
            {
                _gripperBeingDragged.Value = mouse.Y - MarginAroundPicture;

                //adjust the vertical position of other axis' grips
                foreach (var grip in HorizontalControlGrips)
                {
                    grip.UpdateRectangle();
                }
            }
            else
            {
                _gripperBeingDragged.Value = mouse.X - MarginAroundPicture;
                foreach (var grip in VerticalControlGrips)
                {
                    grip.UpdateRectangle();
                }
            }
            if (!didReportThatUserCameInHere)
            {
                didReportThatUserCameInHere = true;
                UsageReporter.SendNavigationNotice("ImageToolbox:Cropper");
            }
        }
Exemple #4
0
 private void LibraryView_VisibleChanged(object sender, EventArgs e)
 {
     if (Visible)
     {
         UsageReporter.SendNavigationNotice("Library");
     }
 }
Exemple #5
0
        /// <summary>
        /// Get a new FW project from some Mercurial repository.
        /// The repo may be a lift or full FW repo, but it can be from any source source, as long as the code can create an FW project from it.
        /// </summary>
        /// <returns>Null if the operation was cancelled or otherwise did not work. The full pathname of an fwdata file, if it did work.</returns>
        public static string ObtainProjectFromAnySource(Form parent, IHelpTopicProvider helpTopicProvider, out ObtainedProjectType obtainedProjectType)
        {
            bool   dummy;
            string fwdataFileFullPathname;
            var    liftVersion = "0.13_ldml3";
            var    success     = FLExBridgeHelper.LaunchFieldworksBridge(FwDirectoryFinder.ProjectsDirectory, null, FLExBridgeHelper.Obtain, null,
                                                                         LcmCache.ModelVersion, liftVersion, null, null, out dummy, out fwdataFileFullPathname);

            if (!success)
            {
                ReportDuplicateBridge();
                obtainedProjectType = ObtainedProjectType.None;
                return(null);
            }
            if (string.IsNullOrWhiteSpace(fwdataFileFullPathname))
            {
                obtainedProjectType = ObtainedProjectType.None;
                return(null);                // user canceled.
            }
            obtainedProjectType = ObtainedProjectType.FieldWorks;

            if (fwdataFileFullPathname.EndsWith("lift"))
            {
                fwdataFileFullPathname = CreateProjectFromLift(parent, helpTopicProvider, fwdataFileFullPathname);
                obtainedProjectType    = ObtainedProjectType.Lift;
            }

            UsageReporter.SendEvent("OpenProject", "SendReceive", string.Format("Create from {0} repo", obtainedProjectType.ToString()),
                                    string.Format("vers: {0}, {1}", LcmCache.ModelVersion, liftVersion), 0);
            EnsureLinkedFoldersExist(fwdataFileFullPathname);

            return(fwdataFileFullPathname);
        }
Exemple #6
0
        private void OnButtonClick(object sender, EventArgs e)
        {
            DashboardButton b    = (DashboardButton)sender;
            ITask           task = b.ThingToShowOnDashboard as ITask;

            if (task != null && _currentWorkTaskProvider != null)
            {
                _currentWorkTaskProvider.SetActiveTask(task);
            }
            else
            {
                IWeSayAddin addin = b.ThingToShowOnDashboard as IWeSayAddin;
                if (addin != null)
                {
                    Cursor.Current = Cursors.WaitCursor;

                    try
                    {
                        ProjectInfo projectInfo =
                            WeSayWordsProject.Project.GetProjectInfoForAddin();
                        UsageReporter.SendNavigationNotice(addin.ID);
                        addin.Launch(ParentForm, projectInfo);
                    }
                    catch (Exception error)
                    {
                        ErrorReport.NotifyUserOfProblem(error.Message);
                    }

                    Cursor.Current = Cursors.Default;
                }
            }
        }
 private void _okButton_Click(object sender, EventArgs e)
 {
     //enhance: doesn't tell us all that much.
     UsageReporter.SendNavigationNotice("ImageToolboxDialog/Ok");
     DialogResult = (ImageInfo == null || ImageInfo.Image == null)? DialogResult.Cancel : DialogResult.OK;
     _imageToolboxControl.Closing();
     Close();
 }
Exemple #8
0
 private static void SetupErrorHandling()
 {
     Logger.Init();
     ErrorReport.EmailAddress = "*****@*****.**";
     ErrorReport.AddStandardProperties();
     ExceptionHandler.Init();
     UsageReporter.Init(Properties.Settings.Default.ReportingSettings, "nowhere.palaso.org", "bogusAccountCode", true);
     Settings.Default.Save();
 }
        private void OnCameraClick(object sender, EventArgs e)
        {
#if !MONO
            SetImage(null);
            _cameraButton.Checked = true;
            UsageReporter.SendNavigationNotice("ImageToolbox:GetFromCamera");
            GetFromDevice(ImageAcquisitionService.DeviceKind.Camera);
#endif
        }
        private void OnScannerClick(object sender, EventArgs e)
        {
#if !MONO
            _scannerButton.Checked = true;
            SetImage(null);
            UsageReporter.SendNavigationNotice("ImageToolbox:GetFromScanner");
            GetFromDevice(ImageAcquisitionService.DeviceKind.Scanner);
#endif
        }
 private void OnDeleteClick(object sender, EventArgs e)
 {
     if (File.Exists(_path))
     {
         File.Delete(_path);
         UpdateScreen();
         if (SoundDeleted != null)
         {
             SoundDeleted.Invoke(this, null);
             UsageReporter.SendNavigationNotice("AudioDeleted");
         }
     }
 }
Exemple #12
0
        public void OnPropertyChanged(string name)
        {
            CheckDisposed();

            switch (name)
            {
            default:
                break;

            /* remember, what XCore thinks of as a "Content Control", is what this AreaManager sees as a "tool".
             * with that in mind, this case is invoked when the user chooses a different tool.
             * the purpose of this code is to then store the name of that tool so that
             * next time we come back to this area, we can remember to use this same tool.
             */
            case "currentContentControlObject":
                string toolName = m_propertyTable.GetStringProperty("currentContentControl", "");
                var    c        = m_propertyTable.GetValue <IxCoreContentControl>("currentContentControlObject");
                var    propName = "ToolForAreaNamed_" + c.AreaName;
                m_propertyTable.SetProperty(propName, toolName, true);
                Logger.WriteEvent("Switched to " + toolName);
                // Should we report a tool change?
                if (m_lastToolChange.Date != DateTime.Now.Date)
                {
                    // new day has dawned (or just started up). Reset tool reporting.
                    m_toolsReportedToday.Clear();
                    m_lastToolChange = DateTime.Now;
                }
                string areaNameForReport = m_propertyTable.GetStringProperty("areaChoice", null);
                if (!string.IsNullOrWhiteSpace(areaNameForReport) && !m_toolsReportedToday.Contains(toolName))
                {
                    m_toolsReportedToday.Add(toolName);
                    UsageReporter.SendNavigationNotice("SwitchToTool/{0}/{1}", areaNameForReport, toolName);
                }
                break;

            case "areaChoice":
                string areaName = m_propertyTable.GetStringProperty("areaChoice", null);

                if (string.IsNullOrEmpty(areaName))
                {
                    break;                            //this can happen when we use this property very early in the initialization
                }
                //for next startup
                m_propertyTable.SetProperty("InitialArea", areaName, true);

                ActivateToolForArea(areaName);
                break;
            }
        }
Exemple #13
0
        private static void SetUpReporting()
        {
            if (Settings.Default.Reporting == null)
            {
                Settings.Default.Reporting = new ReportingSettings();
                Settings.Default.Save();
            }
            UsageReporter.Init(Settings.Default.Reporting, "myWorkSafe.palaso.org", "UA-22170471-1",
#if DEBUG
                               true
#else
                               false
#endif
                               );
        }
Exemple #14
0
        public static void ShowHelpTopic(string topicLink)
        {
            string helpFilePath = FileLocator.GetFileDistributedWithApplication("WeSay_Helps.chm");

            if (File.Exists(helpFilePath))
            {
                //var uri = new Uri(helpFilePath);
                Help.ShowHelp(new Label(), helpFilePath, topicLink);
            }
            else
            {
                Process.Start("http://wesay.palaso.org/help/");
            }
            UsageReporter.SendNavigationNotice("Help: " + topicLink);
        }
 private void OnCancelClick(object sender, EventArgs e)
 {
     if (_preparationWorker != null)
     {
         _status.Text = "Cancelling...";
         _preparationWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((x, y) => ChangeState(State.Cancelled));
         _preparationWorker.CancelAsync();
     }
     if (_backupWorker != null)
     {
         _status.Text                      = "Cancelling...";
         syncProgressBar.Visible           = false;
         _backupWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((x, y) => ChangeState(State.Cancelled));
         _backupWorker.CancelAsync();
     }
     UsageReporter.SendEvent("Backup", "Command", "CancelBackup", "", 0);
 }
Exemple #16
0
        ///*something left over from this class's predaccesor, which may be useful*/
        ////seems to help with some, not with others
        //private void TryToFixScaling(Control c)
        //{
        //    //this is part of dealing with .net not adjusting stuff well for different dpis
        //    c.Dock = DockStyle.None;
        //    c.Size = new Size(Width, Height - 25);
        //    // c.BackColor = System.Drawing.Color.Crimson;
        //}
        private void OnAreaButton_Click(object sender, EventArgs e)
        {
            ToolStripButton currentItem = null;

            foreach (ToolStripButton item in _areasToolStrip.Items)
            {
                if (item.Checked)
                {
                    currentItem = item;
                }
                item.Checked = false;
            }
            ToolStripButton button = (ToolStripButton)sender;

            button.Checked = true;

            if (currentItem != null)
            {
                _areaPanel.Controls.Remove((Control)(currentItem.Tag));
            }
            ConfigurationControlBase c = button.Tag as ConfigurationControlBase;

            if (c != null)
            {
                _areaPanel.Controls.Add(c);
                c.Location = new Point(10, _areaHeader.Height + 20);
                c.Width    = _areaPanel.Width - 20;
                c.Height   = _areaPanel.Height - (15 + c.Top);
                c.SetOtherStuff();

                _areaHeader.Text = "";
                _areaHeader.Font = new Font("Tahoma", 10F, FontStyle.Bold);
                _areaHeader.AppendText(button.Text + ": ");
                _areaHeader.SelectionFont = new Font("Tahoma", 10F, FontStyle.Regular);
                _areaHeader.AppendText(c.Header);
                FieldsControl fc = button.Tag as FieldsControl;
                if (fc != null)
                {
                    fc.RefreshFieldDisplayNames();
                }
                c.Focus();

                UsageReporter.SendNavigationNotice("settings/" + c.NameForUsageReporting);
            }
        }
Exemple #17
0
 private static void ReportExceptionToAnalytics(ExceptionReportingData reportingData)
 {
     try
     {
         if (!string.IsNullOrEmpty(reportingData.Message))
         {
             UsageReporter.ReportExceptionString(reportingData.Message);
         }
         else if (reportingData.Error != null)
         {
             UsageReporter.ReportException(reportingData.Error);
         }
     }
     catch
     {
         //swallow
     }
 }
Exemple #18
0
        private static void LaunchBackup(IProgress progress, IProgress fileLogProgress, IUsbDriveInfo drive)
        {
            long   totalSpaceInKilobytes = (long)(drive.TotalSize / 1024);
            long   freeSpaceInKilobytes  = (long)(drive.AvailableFreeSpace / 1024);
            string destinationDeviceRoot = drive.RootDirectory.ToString();
            var    backupControl         = new BackupControl(destinationDeviceRoot, freeSpaceInKilobytes, totalSpaceInKilobytes, progress);

            UsageReporter.SendNavigationNotice("StartBackup");
            Settings.Default.Save();

            using (var form = new MainWindow(backupControl, progress))
            {
                form.ShowDialog();
                if (fileLogProgress != null)
                {
                    fileLogProgress.WriteMessage("Finished showing Dialog");
                }
            }
        }
Exemple #19
0
        public static void ShowHelpTopic(string topicLink)
        {
            string helpFilePath = FileLocator.GetFileDistributedWithApplication(true, "WeSay_Helps.chm");

            if (String.IsNullOrEmpty(helpFilePath))
            {
                string commonDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
                helpFilePath = Path.Combine(commonDataFolder, Path.Combine("wesay", "WeSay_Helps.chm"));
            }
            if (File.Exists(helpFilePath))
            {
                //var uri = new Uri(helpFilePath);
                Help.ShowHelp(new Label(), helpFilePath, topicLink);
            }
            else
            {
                Process.Start("http://wesay.palaso.org/help/");
            }
            UsageReporter.SendNavigationNotice("Help: " + topicLink);
        }
Exemple #20
0
        private static void SetUpReporting()
        {
            if (Settings.Default.Reporting == null)
            {
                Settings.Default.Reporting = new ReportingSettings();
                Settings.Default.Save();
            }
            // If this is a release build, then allow the environment variable to be set to true
            // so that testers are not generating user stats
            string developerSetting  = System.Environment.GetEnvironmentVariable("WESAY_TRACK_AS_DEVELOPER");
            bool   developerTracking = !string.IsNullOrEmpty(developerSetting) && (developerSetting.ToLower() == "yes" || developerSetting.ToLower() == "true" || developerSetting == "1");
            bool   reportAsDeveloper =
#if DEBUG
                true
#else
                developerTracking
#endif
            ;

            UsageReporter.Init(Settings.Default.Reporting, "wesay.palaso.org", "UA-22170471-6", reportAsDeveloper);
            UsageReporter.AppNameToUseInDialogs   = "WeSay Configuration Tool";
            UsageReporter.AppNameToUseInReporting = "WeSayConfig";
        }
        /// <summary>
        /// Get a teammate's shared project from the specified source.
        /// </summary>
        /// <param name="parent">Window that will be parent of progress window</param>
        /// <param name="projectFilter">Function taking a directory path and telling whether it contains the right sort of repo</param>
        /// <param name="hubQuery">String on which to build a URL query to ChorusHub to accomplish the purpose of 'projectFilter'
        /// in the ChorusHub environment</param>
        /// <example>FLExBridge sends "fileExtension=.lift|._custom_properties" to get both LIFT and FLExBridge repos, but not Bloom ones,
        /// for instance. The server looks in the project's .hg/store/data folder for a file ending in .lift.i or ._custom_properties.i</example>
        /// <param name="baseProjectDirForNewClone">The base folder for the new clone, if created.</param>
        /// <param name="baseProjectDirInWhichToSearchForRepositories">The directory which contains projects we already have, and where the result should go</param>
        /// <param name="lowerLevelRepoPath">Optionally specifies another place to look for existing repos: look in this subfolder of each folder in baseProjectDirInWhichToSearchForRepositories.
        /// This is used in FLEx (passing "OtherRepositories") so existing LIFT repos linked to FW projects can be found. Pass null if not used.</param>
        /// <param name="preferredClonedFolderName"></param>
        /// <param name="howToSendReceiveMessageText">This string is appended to the message we build when we have received a repo and can't keep it, because
        /// it has the same hash as an existing project. We think it is likely the user actually intended to Send/Receive that project rather than obtaining
        /// a duplicate. This message thus typically tells him how to do so, in the particular client program. May also be empty.</param>
        /// <returns>
        /// A CloneResult that provides the clone results (e.g., success or failure) and the actual clone location (null if not created).
        /// </returns>
        public CloneResult GetSharedProjectUsing(Form parent, string baseProjectDirForNewClone, string preferredClonedFolderName,
                                                 Func <string, bool> projectFilter, string hubQuery, string baseProjectDirInWhichToSearchForRepositories, string lowerLevelRepoPath,
                                                 string howToSendReceiveMessageText)
        {
            Guard.AgainstNull(parent, "parent");
            Guard.AgainstNullOrEmptyString(baseProjectDirForNewClone, "baseProjectDirForNewClone");
            Guard.AgainstNullOrEmptyString(baseProjectDirInWhichToSearchForRepositories, "baseProjectDirInWhichToSearchForRepositories");
            if (preferredClonedFolderName == string.Empty)
            {
                preferredClonedFolderName = null;
            }

            Dictionary <string, string> existingRepositories;

            try
            {
                existingRepositories = ExtantRepoIdentifiers(baseProjectDirInWhichToSearchForRepositories, lowerLevelRepoPath);
            }
            catch (ApplicationException e)
            {
                // FLEx issue LT-14301: one reason we may throw is that we can't get the identifier of some project because we don't have
                // sufficient permissions.

                // We think this will be very rare...try to get an automatic notification if it happens.
                UsageReporter.SendEvent("UnusualProblems", "Chorus", "ExtantRepoIdentifiersFailed", null, 0);

                MessageBox.Show(
                    string.Format(LocalizationManager.GetString("Messages.CantGetInfo",
                                                                "You can't get a project from a colleague at present, because some required information about the projects you already have is unavailable. "
                                                                + "This may be because you don't have permission to access a file in one of the projects in {0}.\n\n"
                                                                + "You will probably need technical support to resolve this problem. The following information may be helpful to tech support:") + "\n\n{1}",
                                  baseProjectDirInWhichToSearchForRepositories, e.Message),
                    LocalizationManager.GetString("Messages.CantGetProject", "Cannot get project"));
                return(new CloneResult(null, CloneStatus.NotCreated));
            }
            var existingProjectNames = new HashSet <string>(from dir in Directory.GetDirectories(baseProjectDirInWhichToSearchForRepositories) select Path.GetFileName(dir));

            // "existingRepositoryIdentifiers" is currently not used, but the expectation is that the various models/views could use it how they see fit.
            // "Seeing fit' may mean to warn the user they already have some repository, or as a filter to not show ones that already exist.
            // What to do with the list of extant repos is left up to a view+model pair.

            // Select basic source type.
            using (var getSharedProjectDlg = new GetSharedProjectDlg())
            {
                getSharedProjectDlg.InitFromModel(this);
                getSharedProjectDlg.ShowDialog(parent);
                if (getSharedProjectDlg.DialogResult != DialogResult.OK)
                {
                    return(new CloneResult(null, CloneStatus.NotCreated));
                }
            }

            // Make clone from some source.
            string actualCloneLocation = null;
            var    cloneStatus         = CloneStatus.NotCreated;

            switch (RepositorySource)
            {
            case ExtantRepoSource.Internet:
                var cloneFromInternetModel = new GetCloneFromInternetModel(baseProjectDirForNewClone)
                {
                    LocalFolderName = preferredClonedFolderName
                };
                using (var cloneFromInternetDialog = new GetCloneFromInternetDialog(cloneFromInternetModel))
                {
                    switch (cloneFromInternetDialog.ShowDialog(parent))
                    {
                    default:
                        cloneStatus = CloneStatus.NotCreated;
                        break;

                    case DialogResult.Cancel:
                        cloneStatus = CloneStatus.Cancelled;
                        break;

                    case DialogResult.OK:
                        actualCloneLocation = cloneFromInternetDialog.PathToNewlyClonedFolder;
                        cloneStatus         = CloneStatus.Created;
                        break;
                    }
                }
                break;

            case ExtantRepoSource.ChorusHub:
                var getCloneFromChorusHubModel = new GetCloneFromChorusHubModel(baseProjectDirForNewClone)
                {
                    ProjectFilter    = hubQuery,
                    ExistingProjects = existingProjectNames,
                    ExistingRepositoryIdentifiers = existingRepositories
                };

                using (var getCloneFromChorusHubDialog = new GetCloneFromChorusHubDialog(getCloneFromChorusHubModel))
                {
                    switch (getCloneFromChorusHubDialog.ShowDialog(parent))
                    {
                    default:
                        cloneStatus = CloneStatus.NotCreated;
                        break;

                    case DialogResult.Cancel:
                        cloneStatus = CloneStatus.Cancelled;
                        break;

                    case DialogResult.OK:
                        if (getCloneFromChorusHubModel.CloneSucceeded)
                        {
                            actualCloneLocation = getCloneFromChorusHubDialog.PathToNewlyClonedFolder;
                            cloneStatus         = CloneStatus.Created;
                        }
                        else
                        {
                            cloneStatus = CloneStatus.NotCreated;
                        }
                        break;
                    }
                }
                break;

            case ExtantRepoSource.Usb:
                using (var cloneFromUsbDialog = new GetCloneFromUsbDialog(baseProjectDirForNewClone))
                {
                    cloneFromUsbDialog.Model.ProjectFilter    = projectFilter ?? DefaultProjectFilter;
                    cloneFromUsbDialog.Model.ReposInUse       = existingRepositories;
                    cloneFromUsbDialog.Model.ExistingProjects = existingProjectNames;
                    switch (cloneFromUsbDialog.ShowDialog(parent))
                    {
                    default:
                        cloneStatus = CloneStatus.NotCreated;
                        break;

                    case DialogResult.Cancel:
                        cloneStatus = CloneStatus.Cancelled;
                        break;

                    case DialogResult.OK:
                        actualCloneLocation = cloneFromUsbDialog.PathToNewlyClonedFolder;
                        cloneStatus         = CloneStatus.Created;
                        break;
                    }
                }
                break;
            }
            // Warn the user if they already have this by another name.
            // Not currently needed for USB, since those have already been checked.
            if (RepositorySource != ExtantRepoSource.Usb && cloneStatus == CloneStatus.Created)
            {
                var    repo = new HgRepository(actualCloneLocation, new NullProgress());
                string projectWithExistingRepo;
                if (repo.Identifier != null && existingRepositories.TryGetValue(repo.Identifier, out projectWithExistingRepo))
                {
                    using (var warningDlg = new DuplicateProjectWarningDialog())
                        warningDlg.Run(projectWithExistingRepo, howToSendReceiveMessageText);
                    Directory.Delete(actualCloneLocation, true);
                    actualCloneLocation = null;
                    cloneStatus         = CloneStatus.Cancelled;
                }
            }
            return(new CloneResult(actualCloneLocation, cloneStatus));
        }
Exemple #22
0
        protected override bool DisplayError(Exception exception)
        {
            UsageReporter.ReportException(false, null, exception, null);
            try
            {
                // To disable displaying a message box, put
                // <add key="ShowUI" value="False"/>
                // in the <appSettings> section of the .config file (see MSDN for details).
                bool showUI = ShowUI;

                if (exception.InnerException != null)
                {
                    Debug.WriteLine(string.Format("Exception: {0} {1}", exception.Message, exception.InnerException.Message));
                    Logger.WriteEvent("Exception: {0} {1}", exception.Message, exception.InnerException.Message);
                }
                else
                {
                    Debug.WriteLine(String.Format("Exception: {0}", exception.Message));
                    Logger.WriteEvent("Exception: {0}", exception.Message);
                }

                if (exception is ExternalException &&
                    (uint)(((ExternalException)exception).ErrorCode) == 0x8007000E)                        // E_OUTOFMEMORY
                {
                    if (showUI)
                    {
                        ExceptionReportingDialog.ReportException(exception);                        //, parent);
                    }
                    else
                    {
                        Trace.Fail("Out of memory");
                        //                        Trace.Assert(false, FwApp.GetResourceString("kstidMiscError"),
                        //                            FwApp.GetResourceString("kstidOutOfMemory"));
                    }
                }
                else
                {
                    Debug.Assert(exception.Message != string.Empty || exception is COMException,
                                 "Oops - we got an empty exception description. Change the code to handle that!");

                    if (showUI)
                    {
                        // bool fIsLethal = !(exception is Reporting.ConfigurationException);
                        //ErrorReporter.ReportException(exception, parent, fIsLethal);
                        ExceptionReportingDialog.ReportException(exception);
                        return(false);
                    }
                    else
                    {
                        //todo: the reporting component should do all this, too

                        /*                       Exception innerE = ExceptionHelper.GetInnerMostException(exception);
                         *                                              string strMessage = "Error: "; // FwApp.GetResourceString("kstidProgError") + FwApp.GetResourceString("kstidFatalError");
                         *                                              string strVersion;
                         *                                              Assembly assembly = Assembly.GetEntryAssembly();
                         *                                              object[] attributes = null;
                         *                                              if (assembly != null)
                         *                                                      attributes = assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false);
                         *                                              if (attributes != null && attributes.Length > 0)
                         *                                                      strVersion = ((AssemblyFileVersionAttribute)attributes[0]).Version;
                         *                                              else
                         *                                                      strVersion = Application.ProductVersion;
                         *                                              string strReport = string.Format(
                         *                                                      "Got Exception", //"FwApp.GetResourceString("kstidGotException"),
                         *                                                      "*****@*****.**", //"FwApp.GetResourceString("kstidSupportEmail"),
                         *
                         *                                                      exception.Source, strVersion,
                         *                                                      ExceptionHelper.GetAllExceptionMessages(exception), innerE.Source,
                         *                                                      innerE.TargetSite.Name, ExceptionHelper.GetAllStackTraces(exception));
                         *                                              Trace.Assert(false, strMessage, strReport);
                         */

                        Debug.Fail(exception.Message);
                    }
                }
            }
            catch (Exception)
            {
                Debug.Fail("This error could not be reported normally: ", exception.Message);
            }
            return(true);
        }
        public ImageFile Acquire()
        {
            ImageFile image;

            try
            {
                CommonDialog dialog = new CommonDialog();

                var type = WiaDeviceType.ScannerDeviceType;
                if (_deviceKind == DeviceKind.Camera)
                {
                    type = WiaDeviceType.CameraDeviceType;
                }

                var device = dialog.ShowSelectDevice(type, false, false);

                foreach (var item in device.Items)
                {
                }
                foreach (Property propertyItem in device.Properties)
                {
                    //if (!propertyItem.IsReadOnly)
                    {
                        Debug.WriteLine(String.Format("{0}\t{1}\t{2}", propertyItem.Name, propertyItem.PropertyID, propertyItem.get_Value()));
                    }
                }

                //this gives the UI we want (can select profiles), but there's no way for an application to get the
                //results of the scan!!!! It just asks the user where to save the image. GRRRRRRR.
                //object x = dialog.ShowAcquisitionWizard(device);


                //With the low-end canoscan I'm using, it just ignores these settings, so we just get a bitmap of whatever
                //b&w / color the user requested

                image = dialog.ShowAcquireImage(
                    type,
                    WiaImageIntent.GrayscaleIntent,
                    WiaImageBias.MaximizeQuality,
                    WIA.FormatID.wiaFormatBMP,                             //We'll automatically choose the format later depending on what we see
                    false,
                    true,
                    false);
                UsageReporter.SendNavigationNotice("AcquiredImage/" + (_deviceKind == DeviceKind.Camera?"Camera": "Scanner"));

                return(image);
            }
            catch (COMException ex)
            {
                if (ex.ErrorCode == -2145320939)
                {
                    throw new ImageDeviceNotFoundException();
                }
                else
                {
                    //NB: I spend some hours working on adding this wiaaut.dll via the installer, using wix heat, but it was one problem after another.
                    //Decided eventually that it wasn't worth it at this point; it's easy enough to install by hand.
                    if (ErrorReport.GetOperatingSystemLabel().Contains("XP"))
                    {
                        var comErrorCode = new Win32Exception(((COMException)ex).ErrorCode).ErrorCode;

                        if (comErrorCode == 80040154)
                        {
                            throw new WIA_Version2_MissingException();
                        }
                    }

                    throw new ImageDeviceException("COM Exception", ex);
                }
            }
        }
 private void ImageToolboxDialog_Load(object sender, EventArgs e)
 {
     UsageReporter.SendNavigationNotice("ImageToolbox");
 }
        public void Run()
        {
            _cancelRequested     = false;
            _alreadyAccountedFor = new HashSet <string>();

            try
            {
                foreach (var group in _groups)
                {
                    if (_cancelRequested)
                    {
                        break;
                    }
                    _currentGroup = group; //used by callbacks
                    try
                    {
                        if (group.Disposition == FileGroup.DispositionChoice.Hide)
                        {
                            _progress.WriteMessage("Skipping group {0}", group.Name);
                            continue;
                        }
                        if (_gotIOExceptionProbablyDiskFull)
                        {
                            group.Disposition = FileGroup.DispositionChoice.NotEnoughRoom;
                            continue;
                        }

                        _progress.WriteMessage("Beginning group {0}", group.Name);
                        if (group.Disposition == FileGroup.DispositionChoice.NotEnoughRoom)
                        {
                            continue;
                        }

                        group.ClearStatistics();
                        group.Disposition = FileGroup.DispositionChoice.Synchronizing;
                        InvokeGroupProgress();
                        MirrorGroup(group);
                        InvokeGroupProgress();
                    }
                    catch (Exception error)
                    {
                        var message = "Exception processing group: " + group.Name;
                        _progress.WriteError(message);
                        _progress.WriteException(error);
                        UsageReporter.ReportException(false, "backup", error, message);
                    }
                    _engine = null;
                    _progress.WriteMessage("Controller finished normally.");

                    //we don't want to send, say, 100 errors just because the drive is full. Let's just send one.
                    if (_firstErrorMessage != null)
                    {
                        UsageReporter.SendEvent("Backup", "file error(just the 1st one)", "file error(just the 1st one)", _firstErrorMessage, 0);
                    }
                }
//                Program.ReportToGoogleAnalytics("FinishedBackup", "filesBackedUp", _totalFilesThatWillBeBackedUp);

                /*                    Program.ReportToGoogleAnalytics("finishedUpdated","updated", _engine.UpdatedCount);
                 *  Program.ReportToGoogleAnalytics("finishedCreated", "created", _engine.CreatedCount);
                 *  Program.ReportToGoogleAnalytics("finishedDeleted", "deleted", _engine.DeletedCount);
                 */
            }
            finally
            {
                CleanupTempFiles();
            }
        }
Exemple #26
0
        /// <summary>
        /// Perform the configuration import that the controller has prepared to do.
        /// </summary>
        internal void DoImport()
        {
            Debug.Assert(NewConfigToImport != null);

            ImportCustomFields(_importLiftLocation);

            // If the configuration to import has the same label as an existing configuration in the project folder
            // then overwrite the existing configuration.
            var existingConfigurationInTheWay = _configurations.FirstOrDefault(config => config.Label == NewConfigToImport.Label &&
                                                                               Path.GetDirectoryName(config.FilePath) == _projectConfigDir);

            NewConfigToImport.Publications.ForEach(
                publication =>
            {
                AddPublicationTypeIfNotPresent(publication, _cache);
            });
            try
            {
                ImportStyles(_importStylesLocation);
                ImportHappened = true;
            }
            catch (InstallationException e)             // This is the exception thrown if the dtd guid in the style file doesn't match our program
            {
#if DEBUG
                if (_view == null)                 // _view is sometimes null in unit tests, and it's helpful to know what exactly went wrong.
                {
                    throw new Exception(xWorksStrings.kstidCannotImport, e);
                }
#endif
                _view.explanationLabel.Text = xWorksStrings.kstidCannotImport;
            }

            // We have re-loaded the model from disk to preserve custom field state so the Label must be set here
            NewConfigToImport.FilePath = _temporaryImportConfigLocation;
            NewConfigToImport.Load(_cache);
            if (existingConfigurationInTheWay != null)
            {
                _configurations.Remove(existingConfigurationInTheWay);
                if (existingConfigurationInTheWay.FilePath != null)
                {
                    FileUtils.Delete(existingConfigurationInTheWay.FilePath);
                }
            }
            else
            {
                NewConfigToImport.Label = _proposedNewConfigLabel;
            }

            // Set a filename for the new configuration. Use a unique filename that isn't either registered with another configuration, or existing on disk. Note that in this way, we ignore what the original filename was of the configuration file in the .zip file.
            DictionaryConfigurationManagerController.GenerateFilePath(_projectConfigDir, _configurations, NewConfigToImport);

            var outputConfigPath = existingConfigurationInTheWay != null ? existingConfigurationInTheWay.FilePath : NewConfigToImport.FilePath;

            File.Move(_temporaryImportConfigLocation, outputConfigPath);

            NewConfigToImport.FilePath = outputConfigPath;
            _configurations.Add(NewConfigToImport);

            // phone home (analytics)
            var configType = NewConfigToImport.Type;
            var configDir  = DictionaryConfigurationListener.GetDefaultConfigurationDirectory(
                configType == DictionaryConfigurationModel.ConfigType.Reversal
                                        ? DictionaryConfigurationListener.ReversalIndexConfigurationDirectoryName
                                        : DictionaryConfigurationListener.DictionaryConfigurationDirectoryName);
            var isCustomizedOriginal = DictionaryConfigurationManagerController.IsConfigurationACustomizedOriginal(NewConfigToImport, configDir, _cache);
            UsageReporter.SendEvent("DictionaryConfigurationImport", "Import", "Import Config",
                                    string.Format("Import of [{0}{1}]:{2}",
                                                  configType, isCustomizedOriginal ? string.Empty : "-Custom", ImportHappened ? "succeeded" : "failed"), 0);
        }
        public void Report(string message, string messageBeforeStack, Exception error, Form owningForm)
        {
            try
            {
                if (!string.IsNullOrEmpty(message))
                {
                    UsageReporter.ReportExceptionString(message);
                }
                else if (error != null)
                {
                    UsageReporter.ReportException(error);
                }
            }
            catch
            {
                //swallow
            }

            PrepareDialog();
            if (!string.IsNullOrEmpty(message))
            {
                _notificationText.Text = message;
            }

            if (!string.IsNullOrEmpty(message))
            {
                _details.Text += "Message (not an exception): " + message + Environment.NewLine;
                _details.Text += Environment.NewLine;
            }
            if (!string.IsNullOrEmpty(messageBeforeStack))
            {
                _details.Text += messageBeforeStack;
                _details.Text += Environment.NewLine;
            }

            Exception innerMostException = null;

            _details.Text += ErrorReport.GetHiearchicalExceptionInfo(error, ref innerMostException);

            //if the exception had inner exceptions, show the inner-most exception first, since that is usually the one
            //we want the developer to read.
            if (innerMostException != null)
            {
                _details.Text = string.Format("Inner-most exception:{2}{0}{2}{2}Full, hierarchical exception contents:{2}{1}",
                                              ErrorReport.GetExceptionText(innerMostException), _details.Text, Environment.NewLine);
            }

            AddErrorReportingPropertiesToDetails();


            Debug.WriteLine(_details.Text);
            if (innerMostException != null)
            {
                error = innerMostException;
            }


            try
            {
                Logger.WriteEvent("Got exception " + error.GetType().Name);
            }
            catch (Exception err)
            {
                //We have more than one report of dieing while logging an exception.
                _details.Text += "****Could not write to log (" + err.Message + ")" + Environment.NewLine;
                _details.Text += "Was trying to log the exception: " + error.Message + Environment.NewLine;
                _details.Text += "Recent events:" + Environment.NewLine;
                _details.Text += Logger.MinorEventsLog;
            }

            ShowReportDialogIfAppropriate(owningForm);
        }