Beispiel #1
0
 private void BtnAgregarCelular_Click(object sender, EventArgs e)
 {
     if (_celular != null)
     {
         using (var seleccionarCelular = _iFormFactory.Create <FrmCrearEditarCelular>(_celular.Id, ActionFormMode.Edit))
         {
             seleccionarCelular.EntityAgregada += (o, celular) =>
             {
                 if (celular.Baja.HasValue)
                 {
                     _celular = null;
                     Celular  = "";
                 }
             };
             seleccionarCelular.ShowDialog();
         }
     }
     else
     {
         using (var seleccionarCelular = _iFormFactory.Create <FrmCrearEditarCelular>(Guid.Empty, ActionFormMode.Create))
         {
             seleccionarCelular.EntityAgregada += (o, celular) =>
             {
                 _celular = celular;
                 Celular  = _celular.TiposCelulares.Tipo;
             };
             seleccionarCelular.ShowDialog();
         }
     }
 }
Beispiel #2
0
        protected override ScanDevice PromptForDeviceInternal()
        {
            var deviceList = GetDeviceList();

            if (!deviceList.Any())
            {
                throw new NoDevicesFoundException();
            }

            var form = formFactory.Create <FSelectDevice>();

            form.DeviceList = deviceList;
            form.ShowDialog();
            return(form.SelectedDevice);
        }
        public bool ExportPDF(string filename, List <ScannedImage> images, bool email)
        {
            var op           = operationFactory.Create <SavePdfOperation>();
            var progressForm = formFactory.Create <FProgress>();

            progressForm.Operation = op;

            var pdfSettings = pdfSettingsContainer.PdfSettings;

            pdfSettings.Metadata.Creator = MiscResources.NAPS2;
            if (op.Start(filename, DateTime.Now, images, pdfSettings, ocrDependencyManager.DefaultLanguageCode, email))
            {
                progressForm.ShowDialog();
            }
            return(op.Status.Success);
        }
Beispiel #4
0
        public void PerformUpdate(IAutoUpdaterClient client, VersionInfo versionInfo)
        {
            switch (formFactory.Create <FUpdate>().ShowDialog())
            {
            case DialogResult.Yes:     // Install
                // TODO: The app process might need to be killed/restarted before/after installing
                autoUpdater.DownloadAndInstallUpdate(versionInfo).ContinueWith(result =>
                {
                    if (result.Result)
                    {
                        client.InstallComplete();
                    }
                    else
                    {
                        MessageBox.Show(MiscResources.InstallFailed, MiscResources.InstallFailedTitle,
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                });
                break;

            case DialogResult.OK:     // Download
                var saveDialog = new SaveFileDialog
                {
                    FileName = versionInfo.FileName
                };
                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    // TODO: Display progress while downloading
                    autoUpdater.DownloadUpdate(versionInfo, saveDialog.FileName);
                }
                break;
            }
        }
        public Stream Transfer(int pageNumber, WiaBackgroundEventLoop eventLoop, string format)
        {
            if (pageNumber == 1)
            {
                // The only downside of the common dialog is that it steals focus.
                // If this is the first page, then the user has just pressed the scan button, so that's not
                // an issue and we can use it and get the benefits of progress display and immediate cancellation.
                ImageFile imageFile = eventLoop.GetSync(wia =>
                                                        (ImageFile) new CommonDialogClass().ShowTransfer(wia.Item, format));
                if (imageFile == null)
                {
                    return(null);
                }
                return(new MemoryStream((byte[])imageFile.FileData.get_BinaryData()));
            }
            // For subsequent pages, we don't want to take focus in case the user has switched applications,
            // so we use the custom form.
            var form = formFactory.Create <FScanProgress>();

            form.PageNumber = pageNumber;
            form.EventLoop  = eventLoop;
            form.Format     = format;
            form.ShowDialog();
            if (form.Exception != null)
            {
                throw form.Exception;
            }
            if (form.DialogResult == DialogResult.Cancel)
            {
                return(null);
            }
            return(form.ImageStream);
        }
        public void SendSelectionToApplication(ISelection selection)
        {
            if (string.IsNullOrEmpty(_path) || !File.Exists(_path) || selection == null || selection.IsEmpty)
            {
                return;
            }
            IInputFile inputFile;

            if (selection.Results != null && selection.Results.Length == 1 && (inputFile = selection.Results[0] as IInputFile) != null)
            {
                Process.Start(_path, string.Format("\"{0}\"", inputFile.Name));
                return;
            }

            string tmpfile = TempFile.GetTempFileName();

            // Use the detector info of the first result to determine the file extension
            if (selection.OutputFileExtension != null)
            {
                tmpfile = System.IO.Path.ChangeExtension(tmpfile, selection.OutputFileExtension);
            }

            var sendToProgressReporter = _formFactory.Create <SendToProgressReporter>();

            sendToProgressReporter.SendToAsync(selection, _path, _parameters, tmpfile);
        }
Beispiel #7
0
        private bool SaveOneFile(AutoSaveSettings settings, DateTime now, int i, List <ScannedImage> images, ISaveNotify notify, ref string firstFileSaved)
        {
            if (images.Count == 0)
            {
                return(true);
            }
            var    form    = formFactory.Create <FProgress>();
            string subPath = fileNamePlaceholders.SubstitutePlaceholders(settings.FilePath, now, true, i);

            if (settings.PromptForFilePath)
            {
                if (dialogHelper.PromptToSavePdfOrImage(subPath, out string newPath))
                {
                    subPath = fileNamePlaceholders.SubstitutePlaceholders(newPath, now, true, i);
                }
            }
            var extension = Path.GetExtension(subPath);

            if (extension != null && extension.Equals(".pdf", StringComparison.InvariantCultureIgnoreCase))
            {
                if (File.Exists(subPath))
                {
                    subPath = fileNamePlaceholders.SubstitutePlaceholders(subPath, now, true, 0, 1);
                }
                var op = operationFactory.Create <SavePdfOperation>();
                form.Operation = op;
                var ocrLanguageCode = userConfigManager.Config.EnableOcr ? userConfigManager.Config.OcrLanguageCode : null;
                if (op.Start(subPath, now, images, pdfSettingsContainer.PdfSettings, ocrLanguageCode, false))
                {
                    form.ShowDialog();
                }
                if (op.Status.Success && firstFileSaved == null)
                {
                    firstFileSaved = subPath;
                }
                if (op.Status.Success)
                {
                    notify?.PdfSaved(subPath);
                }
                return(op.Status.Success);
            }
            else
            {
                var op = operationFactory.Create <SaveImagesOperation>();
                form.Operation = op;
                if (op.Start(subPath, now, images))
                {
                    form.ShowDialog();
                }
                if (op.Status.Success && firstFileSaved == null)
                {
                    firstFileSaved = op.FirstFileSaved;
                }
                if (op.Status.Success)
                {
                    notify?.ImagesSaved(images.Count, op.FirstFileSaved);
                }
                return(op.Status.Success);
            }
        }
Beispiel #8
0
            private bool PromptForNextScan()
            {
                var promptForm = formFactory.Create <FBatchPrompt>();

                promptForm.ScanNumber = scans.Count + 1;
                return(promptForm.ShowDialog() == DialogResult.OK);
            }
        public void ShowProgress(IOperation op)
        {
            var form = formFactory.Create <FProgress>();

            form.Operation = op;
            form.ShowDialog();
        }
Beispiel #10
0
            private DialogResult PromptToRecover()
            {
                var recoveryPromptForm = formFactory.Create <FRecover>();

                recoveryPromptForm.SetData(imageCount, scannedDateTime);
                return(recoveryPromptForm.ShowDialog());
            }
Beispiel #11
0
        public void ShowErrorWithDetails(string errorMesage, string details)
        {
            var form = formFactory.Create <FError>();

            form.ErrorMessage = errorMesage;
            form.Details      = details;
            form.ShowDialog();
        }
Beispiel #12
0
        private void OnCreate(object sender, EventArgs e)
        {
            var customerForm = _formFactory.Create <CustomerForm>();

            if (customerForm.ShowDialog(this) == DialogResult.OK)
            {
                LoadCustomers();
            }
        }
Beispiel #13
0
        protected override ScanDevice PromptForDeviceInternal()
        {
            var twainImpl = ScanProfile != null ? ScanProfile.TwainImpl : TwainImpl.Default;

            // Exclude WIA proxy devices since NAPS2 already supports WIA
            var deviceList = GetDeviceList(twainImpl).Where(x => !x.ID.StartsWith("WIA-")).ToList();

            if (!deviceList.Any())
            {
                throw new NoDevicesFoundException();
            }

            var form = formFactory.Create <FSelectDevice>();

            form.DeviceList = deviceList;
            form.ShowDialog();
            return(form.SelectedDevice);
        }
 public bool PromptToInstall(ExternalComponent component, string promptText)
 {
     if (MessageBox.Show(promptText, MiscResources.DownloadNeeded, MessageBoxButtons.YesNo) == DialogResult.Yes)
     {
         var progressForm = formFactory.Create <FDownloadProgress>();
         progressForm.QueueFile(component);
         progressForm.ShowDialog();
     }
     return(component.IsInstalled);
 }
        private void UseFileAsSource(IInputFile inputFile, IDetector detector)
        {
            // Use the owner of the current window, this Form will be closed soon.
            SearchHeader searchHeader = _formFactory.Create <SearchHeader>();

            if (searchHeader.RunSearchHeader(inputFile, detector))
            {
                searchHeader.ShowDialog(Owner);
            }
        }
        public bool ProvidePassword(string fileName, int attemptCount, out string password)
        {
            var passwordForm = formFactory.Create <FPdfPassword>();

            passwordForm.FileName = fileName;
            var dialogResult = passwordForm.ShowDialog();

            password = passwordForm.Password;
            return(dialogResult == DialogResult.OK);
        }
Beispiel #17
0
 public void ShowModalProgress(IOperation op)
 {
     if (!op.IsFinished)
     {
         var form = formFactory.Create <FProgress>();
         form.Operation = op;
         form.ShowDialog();
     }
     op.Wait();
 }
Beispiel #18
0
        private async Task <(ScannedImage, bool)> Transfer(Lazy <KeyValueScanOptions> options, int pageNumber)
        {
            return(await Task.Factory.StartNew(() =>
            {
                Stream stream;
                if (ScanParams.NoUi)
                {
                    stream = saneWrapper.ScanOne(ScanDevice.Id, options.Value, null, CancelToken);
                }
                else
                {
                    var form = formFactory.Create <FScanProgress>();
                    var unifiedCancelToken = CancellationTokenSource.CreateLinkedTokenSource(form.CancelToken, CancelToken).Token;
                    form.Transfer = () => saneWrapper.ScanOne(ScanDevice.Id, options.Value, form.OnProgress, unifiedCancelToken);
                    form.PageNumber = pageNumber;
                    ((FormBase)Application.OpenForms[0]).SafeInvoke(() => form.ShowDialog());

                    if (form.Exception != null)
                    {
                        form.Exception.PreserveStackTrace();
                        throw form.Exception;
                    }
                    if (form.DialogResult == DialogResult.Cancel)
                    {
                        return (null, true);
                    }

                    stream = form.ImageStream;
                }
                if (stream == null)
                {
                    return (null, true);
                }
                using (stream)
                    using (var output = Image.FromStream(stream))
                        using (var result = scannedImageHelper.PostProcessStep1(output, ScanProfile, false))
                        {
                            if (blankDetector.ExcludePage(result, ScanProfile))
                            {
                                return (null, false);
                            }

                            // By converting to 1bpp here we avoid the Win32 call in the BitmapHelper conversion
                            // This converter also has the side effect of working even if the scanner doesn't support Lineart
                            using (var encoded = ScanProfile.BitDepth == ScanBitDepth.BlackWhite ? UnsafeImageOps.ConvertTo1Bpp(result, -ScanProfile.Brightness) : result)
                            {
                                var image = new ScannedImage(encoded, ScanProfile.BitDepth, ScanProfile.MaxQuality, ScanProfile.Quality);
                                scannedImageHelper.PostProcessStep2(image, result, ScanProfile, ScanParams, 1, false);
                                var tempPath = scannedImageHelper.SaveForBackgroundOcr(result, ScanParams);
                                scannedImageHelper.RunBackgroundOcr(image, ScanParams, tempPath);
                                return (image, false);
                            }
                        }
            }, TaskCreationOptions.LongRunning));
        }
Beispiel #19
0
 private void BtnAgregarTitular_Click(object sender, EventArgs e)
 {
     using (var seleccionar = _iFormFactory.Create <FrmCrearEditarTitular>(Guid.Empty, ActionFormMode.Create))
     {
         seleccionar.EntityAgregada += (o, titular) =>
         {
             CargarCombos();
             ddlTitulares.SelectedValue = seleccionar.Titular.Id;
         };
         seleccionar.ShowDialog();
     }
 }
        public IForm GetForm(string formName)
        {
            BizFormInfo formObject = BizFormInfoProvider.GetBizFormInfo(formName, SiteContext.CurrentSiteID);

            if (formObject != null)
            {
                var formInfo = _formFactory.Create(formObject);
                return(formInfo);
            }

            return(null);
        }
Beispiel #21
0
        static void Main(string[] args)
        {
            IKernel kernel = new StandardKernel();

            kernel.Load <Module>();

            IFormFactory formFactory = kernel.Get <IFormFactory>();

            var stringReader = new StringReader(Resources._in);

            var form = formFactory.Create(stringReader);
        }
Beispiel #22
0
 private void BtnAgregarProveedor_Click(object sender, EventArgs e)
 {
     using (var seleccionarMovil = _iFormFactory.Create <FrmCrearEditarMovil>(Guid.Empty, ActionFormMode.Create))
     {
         seleccionarMovil.EntityAgregada += (o, movil) =>
         {
             CargarCombos();
             DdlProveedores.SelectedValue = seleccionarMovil.Movil.Id;
         };
         seleccionarMovil.ShowDialog();
     }
 }
        private void InstallComponents()
        {
            var availableComponents = new List <IExternalComponent>();
            var ocrEngine           = ocrManager.EngineToInstall;

            if (ocrEngine != null)
            {
                availableComponents.Add(ocrEngine.Component);
                availableComponents.AddRange(ocrEngine.LanguageComponents);
            }

            if (ghostScriptManager.IsSupported)
            {
                availableComponents.Add(ghostScriptManager.GhostScriptComponent);
            }

            var componentDict = availableComponents.ToDictionary(x => x.Id.ToLowerInvariant());
            var installId     = options.Install.ToLowerInvariant();

            if (!componentDict.TryGetValue(installId, out var toInstall))
            {
                Console.WriteLine(ConsoleResources.ComponentNotAvailable);
                return;
            }

            if (toInstall.IsInstalled)
            {
                Console.WriteLine(ConsoleResources.ComponentAlreadyInstalled);
                return;
            }

            // Using a form here is not ideal (since this is supposed to be a console app), but good enough for now
            // Especially considering wia/twain often show forms anyway
            var progressForm = formFactory.Create <FDownloadProgress>();

            if (toInstall.Id.StartsWith("ocr-", StringComparison.InvariantCulture) &&
                componentDict.TryGetValue("ocr", out var ocrExe) && !ocrExe.IsInstalled)
            {
                progressForm.QueueFile(ocrExe);
                if (options.Verbose)
                {
                    Console.WriteLine(ConsoleResources.Installing, ocrExe.Id);
                }
            }

            progressForm.QueueFile(toInstall);
            if (options.Verbose)
            {
                Console.WriteLine(ConsoleResources.Installing, toInstall.Id);
            }

            progressForm.ShowDialog();
        }
Beispiel #24
0
        public async Task <bool> EmailPDF(List <ScannedImage> images)
        {
            if (!images.Any())
            {
                return(false);
            }

            if (userConfigManager.Config.EmailSetup == null)
            {
                // First run; prompt for a
                var form = formFactory.Create <FEmailProvider>();
                if (form.ShowDialog() != DialogResult.OK)
                {
                    return(false);
                }
            }

            var emailSettings  = emailSettingsContainer.EmailSettings;
            var invalidChars   = new HashSet <char>(Path.GetInvalidFileNameChars());
            var attachmentName = new string(emailSettings.AttachmentName.Where(x => !invalidChars.Contains(x)).ToArray());

            if (string.IsNullOrEmpty(attachmentName))
            {
                attachmentName = "Scan.pdf";
            }
            if (!attachmentName.EndsWith(".pdf", StringComparison.InvariantCultureIgnoreCase))
            {
                attachmentName += ".pdf";
            }
            attachmentName = fileNamePlaceholders.SubstitutePlaceholders(attachmentName, DateTime.Now, false);

            var tempFolder = new DirectoryInfo(Path.Combine(Paths.Temp, Path.GetRandomFileName()));

            tempFolder.Create();
            try
            {
                string targetPath  = Path.Combine(tempFolder.FullName, attachmentName);
                var    changeToken = changeTracker.State;

                var message = new EmailMessage();
                if (await ExportPDF(targetPath, images, true, message) != null)
                {
                    changeTracker.Saved(changeToken);
                    return(true);
                }
            }
            finally
            {
                tempFolder.Delete(true);
            }
            return(false);
        }
Beispiel #25
0
        private void CreateForm(FormViewModel formModel, Service service)
        {
            var form = formFactory.Create
                       (
                formModel.Body.Title,
                formModel.Body.Description
                       );

            entityRepository.InsertOnSave(form);

            service.FormId = form.Id;

            CreateFormField(formModel.Body.FormFields, form);
        }
Beispiel #26
0
        private void buttonChange_Click(object sender, EventArgs e)
        {
            if (table.SelectedRows.Count != 1)
            {
                MessageBox.Show("Please, select (only) one item", "item not correctly selected", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            string name     = table.SelectedRows[0].Cells[0].Value.ToString();
            var    editForm = _formFactory.Create <EditSendToItemForm>();         // TODO: we used to be able to edit the name too!!

            editForm.Item = _sendToList.GetItem(name);
            editForm.ShowDialog(this);
        }
Beispiel #27
0
        private void InstallComponents()
        {
            var availableComponents = new List <(DownloadInfo download, ExternalComponent component)>();

            if (ocrDependencyManager.Components.Tesseract304.IsSupported)
            {
                availableComponents.Add((ocrDependencyManager.Downloads.Tesseract304, ocrDependencyManager.Components.Tesseract304));
            }
            else if (ocrDependencyManager.Components.Tesseract304Xp.IsSupported)
            {
                availableComponents.Add((ocrDependencyManager.Downloads.Tesseract304Xp, ocrDependencyManager.Components.Tesseract304Xp));
            }
            foreach (var lang in ocrDependencyManager.Languages.Keys)
            {
                availableComponents.Add((ocrDependencyManager.Downloads.Tesseract304Languages[lang], ocrDependencyManager.Components.Tesseract304Languages[lang]));
            }
            availableComponents.Add((GhostscriptPdfRenderer.Dependencies.GhostscriptDownload, GhostscriptPdfRenderer.Dependencies.GhostscriptComponent));

            var componentDict = availableComponents.ToDictionary(x => x.component.Id.ToLowerInvariant());
            var installId     = options.Install.ToLowerInvariant();

            if (!componentDict.TryGetValue(installId, out var toInstall))
            {
                Console.WriteLine(ConsoleResources.ComponentNotAvailable);
                return;
            }
            if (toInstall.component.IsInstalled)
            {
                Console.WriteLine(ConsoleResources.ComponentAlreadyInstalled);
                return;
            }
            // Using a form here is not ideal (since this is supposed to be a console app), but good enough for now
            // Especially considering wia/twain often show forms anyway
            var progressForm = formFactory.Create <FDownloadProgress>();

            if (toInstall.component.Id.StartsWith("ocr-") && componentDict.TryGetValue("ocr", out var ocrExe) && !ocrExe.component.IsInstalled)
            {
                progressForm.QueueFile(ocrExe.download, ocrExe.component.Install);
                if (options.Verbose)
                {
                    Console.WriteLine(ConsoleResources.Installing, ocrExe.component.Id);
                }
            }
            progressForm.QueueFile(toInstall.download, toInstall.component.Install);
            if (options.Verbose)
            {
                Console.WriteLine(ConsoleResources.Installing, toInstall.component.Id);
            }
            progressForm.ShowDialog();
        }
 private void BtnAgregarCelular_Click(object sender, EventArgs e)
 {
     if (_celularAnterior != null)
     {
         using (var seleccionarCelular = _iFormFactory.Create <FrmCrearEditarCelular>(Guid.Empty, ActionFormMode.Create))
         {
             seleccionarCelular.EntityAgregada += (o, celular) =>
             {
                 _celularNuevo = celular;
                 CambioCelular(celular);
             };
             seleccionarCelular.ShowDialog();
         }
     }
 }
Beispiel #29
0
        private Stream DoTransfer(int pageNumber, WiaBackgroundEventLoop eventLoop, string format)
        {
            var invoker = (FormBase)DialogParent;

            if (eventLoop.GetSync(wia => wia.Item) == null)
            {
                return(null);
            }
            if (ScanParams.NoUI)
            {
                return(eventLoop.GetSync(wia => WiaApi.Transfer(wia, format, false)));
            }
            if (pageNumber == 1)
            {
                // The only downside of the common dialog is that it steals focus.
                // If this is the first page, then the user has just pressed the scan button, so that's not
                // an issue and we can use it and get the benefits of progress display and immediate cancellation.
                return(ScanParams.Modal
                    ? eventLoop.GetSync(wia => invoker.InvokeGet(() => WiaApi.Transfer(wia, format, true)))
                    : eventLoop.GetSync(wia => WiaApi.Transfer(wia, format, true)));
            }
            // For subsequent pages, we don't want to take focus in case the user has switched applications,
            // so we use the custom form.
            var form       = formFactory.Create <FScanProgress>();
            var waitHandle = new AutoResetEvent(false);

            form.PageNumber = pageNumber;
            form.Transfer   = () => eventLoop.GetSync(wia => WiaApi.Transfer(wia, format, false));
            form.Closed    += (sender, args) => waitHandle.Set();
            if (ScanParams.Modal)
            {
                invoker.Invoke(() => form.ShowDialog(DialogParent));
            }
            else
            {
                invoker.Invoke(() => form.Show(DialogParent));
            }
            waitHandle.WaitOne();
            if (form.Exception != null)
            {
                WiaApi.ThrowDeviceError(form.Exception);
            }
            if (form.DialogResult == DialogResult.Cancel)
            {
                return(null);
            }
            return(form.ImageStream);
        }
Beispiel #30
0
 public static List<ScannedImage> Scan(ScanProfile settings, ScanDevice device, IWin32Window pForm, IFormFactory formFactory)
 {
     var tw = new Twain();
     if (!tw.Init(pForm.Handle))
     {
         throw new DeviceNotFoundException();
     }
     if (!tw.SelectByName(device.ID))
     {
         throw new DeviceNotFoundException();
     }
     var form = formFactory.Create<FTwainGui>();
     var mf = new TwainMessageFilter(settings, tw, form);
     form.ShowDialog(pForm);
     return mf.Bitmaps;
 }
Beispiel #31
0
        public static List <ScannedImage> Scan(ScanProfile settings, ScanDevice device, IWin32Window pForm, IFormFactory formFactory)
        {
            var tw = new Twain();

            if (!tw.Init(pForm.Handle))
            {
                throw new DeviceNotFoundException();
            }
            if (!tw.SelectByName(device.ID))
            {
                throw new DeviceNotFoundException();
            }
            var form = formFactory.Create <FTwainGui>();
            var mf   = new TwainMessageFilter(settings, tw, form);

            form.ShowDialog(pForm);
            return(mf.Bitmaps);
        }