public override void Executar(Wax.IExecutionContext contexto)
        {
            Esperar(3000);

            DialogHelper dialogHelper = new DialogHelper(contexto);

            dialogHelper.ExecutarConfirmJavaScript<Button>(contexto.Browser.Button("btnExcluir"), 60);
        }
Пример #2
0
        private void Initialize() {
            dialog = new DialogHelper();
            actionQueue = new Queue<QueueEntry>();
            selectedController = new ControllerSelection();
            ReInput.ControllerConnectedEvent += JoystickConnected;
            ReInput.ControllerPreDisconnectEvent += JoystickPreDisconnect; // runs before joystick is completely disconnected so we can save maps
            ReInput.ControllerDisconnectedEvent += JoystickDisconnected; // final disconnect that runs after joystick has been fully removed
            Reset();
            initialized = true;
            LoadAllMaps(); // load saved user maps on start if there are any to load

            if(ReInput.unityJoystickIdentificationRequired) {
                IdentifyAllJoysticks();
            }
        }
Пример #3
0
        private void buttonOpenDialog_Click(object sender, EventArgs e)
        {
            IDialogHelper helper = new DialogHelper();

            helper.MultiSelect = true;

            if (helper.OpenDialog())
            {
                StringBuilder strB = new StringBuilder();

                foreach (string fileName in helper.FileNames)
                {
                    if (strB.Length > 0)
                        strB.Append("\n");

                    strB.Append(fileName);
                }

                MessageBox.Show(this, strB.ToString());
            }
        }
        public void clicar_no_botao_de_ok_com_sucesso()
        {
            Castle.DynamicProxy.Generators.AttributesToAvoidReplicating.Add(typeof(TypeIdentifierAttribute));

            var browser = MockRepository.GenerateMock<IEBrowser>(MockRepository.GenerateMock<IWebBrowser2>());

            var executionContext = MockRepository.GenerateMock<IExecutionContext>();

            executionContext.Expect(x => x.Browser).Return(MockRepository.GenerateMock<IE>(browser));

            //executionContext.Browser = MockRepository.GenerateMock<IE>(browser);

            var dialogWatcher = MockRepository.GenerateMock<DialogWatcher>(MockRepository.GenerateMock<Window>(IntPtr.Zero));

            executionContext.Browser.Expect(x => x.DialogWatcher).Return(dialogWatcher);

            var confirmJavaScript = MockRepository.GenerateMock<IDialog>();

            var dialogHelper = new DialogHelper(executionContext, confirmJavaScript);

            //IList<ElementTag> elementTags, Constraint findBy
            var elementFinder = MockRepository.GenerateMock<ElementFinder>(new List<ElementTag>(),
                                                                           MockRepository.GenerateMock<Constraint>());

            var botaoExcluir = MockRepository.GenerateMock<Link>(MockRepository.GenerateMock<DomContainer>(), elementFinder);

            var confirmDialogHandler = MockRepository.GenerateStub<ConfirmDialogHandler>();

            confirmDialogHandler.Expect(x => x.OKButton).Return(new WinButton(IntPtr.Zero));

            var dialogHelperImpl = new DialogImpl(confirmJavaScript);

            dialogHelperImpl.RegisterOn(executionContext.Browser);

            dialogHelperImpl.ClickOkButton();

            dialogHelperImpl.WaitUntilExists(1);

            dialogHelperImpl.Unregister(executionContext.Browser);
        }
        public void executar_confirm_do_javascript_certificando_se_que_o_contexto_ficou_limpo_sem_nenhum_confirm()
        {
            Castle.DynamicProxy.Generators.AttributesToAvoidReplicating.Add(typeof(TypeIdentifierAttribute));

            var browser = MockRepository.GenerateMock<IEBrowser>(MockRepository.GenerateMock<IWebBrowser2>());

            var executionContext = MockRepository.GenerateMock<IExecutionContext>();

            executionContext.Expect(x => x.Browser).Return(MockRepository.GenerateMock<IE>(browser));

            //executionContext.Browser = MockRepository.GenerateMock<IE>(browser);

            var dialogWatcher = MockRepository.GenerateMock<DialogWatcher>(MockRepository.GenerateMock<Window>(IntPtr.Zero));

            executionContext.Browser.Expect(x => x.DialogWatcher).Return(dialogWatcher);

            var confirmJavaScript = MockRepository.GenerateMock<IDialog>();

            var dialogHelper = new DialogHelper(executionContext, confirmJavaScript);

            //IList<ElementTag> elementTags, Constraint findBy
            var elementFinder = MockRepository.GenerateMock<ElementFinder>(new List<ElementTag>(),
                                                                           MockRepository.GenerateMock<Constraint>());

            var botaoExcluir = MockRepository.GenerateMock<Link>(MockRepository.GenerateMock<DomContainer>(), elementFinder);

            dialogHelper.ExecutarConfirmJavaScript<Link>(botaoExcluir, 5);

            Assert.AreEqual(dialogHelper.HandlerCount, 0);

            //Wax.Runner.TestRunner testRunner = new Wax.Runner.TestRunner();

            //testRunner.FileName = @"E:\Projetos\Mongeral\proj-esimteste\proj-esimteste\trunk\Regressao\Mongeral.Regressao.Framework.Exemplos\bin\Debug\Mongeral.Regressao.Framework.Exemplos.dll";

            //testRunner.Load();

            //testRunner.Execute();
        }
 private void AnonymousEditDialogHelpButtonClicked(object sender, CancelEventArgs e)
 {
     DialogHelper.ProcessStart("http://go.microsoft.com/fwlink/?LinkId=210461#Impersonation");
 }
Пример #7
0
 protected override bool ShowHelp()
 {
     DialogHelper.ProcessStart("http://go.microsoft.com/fwlink/?LinkID=130425&amp;clcid=0x409");
     return(true);
 }
Пример #8
0
        public NewNativeDialog(IServiceProvider serviceProvider, GlobalModule existing)
            : base(serviceProvider)
        {
            InitializeComponent();
            if (existing != null)
            {
                txtName.Text = existing.Name;
                txtPath.Text = existing.Image;
                Text         = "Edit Native Module Registration";
                txtName.SelectAll();
                Item = existing;
            }

            var container = new CompositeDisposable();

            FormClosed += (sender, args) => container.Dispose();

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnBrowse, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                DialogHelper.ShowOpenFileDialog(txtPath, "(*.dll)|*.dll|All Files (*.*)|*.*");
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(txtName, "TextChanged")
                .Merge(Observable.FromEventPattern <EventArgs>(txtPath, "TextChanged"))
                .Sample(TimeSpan.FromSeconds(1))
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                btnOK.Enabled = !string.IsNullOrWhiteSpace(txtName.Text) &&
                                !string.IsNullOrWhiteSpace(txtPath.Text);
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnOK, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                if (Item == null)
                {
                    Item = new GlobalModule(null);
                }

                Item.Name  = txtName.Text;
                Item.Image = txtPath.Text;

                try
                {
                    var bit32Condition = "bitness32";
                    var bit64Condition = "bitness64";
                    var bit32          = DialogHelper.GetImageArchitecture(txtPath.Text);
                    if (bit32 && !Item.PreConditions.Contains(bit32Condition))
                    {
                        Item.PreConditions.Add(bit32Condition);
                    }
                    else if (!bit32 && !Item.PreConditions.Contains(bit64Condition))
                    {
                        Item.PreConditions.Add(bit64Condition);
                    }
                }
                catch (Exception)
                {
                    ShowMessage(
                        "The specific module is invalid.",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error,
                        MessageBoxDefaultButton.Button1);
                    return;
                }

                DialogResult = DialogResult.OK;
            }));
        }
        public async Task StartPolling(DiscoveredPrinter printer, List <JobInfo> jobInfoList)
        {
            await Task.Run(() => {
                Connection connection             = null;
                ZebraCardPrinter zebraCardPrinter = null;
                bool showAtmDialog = true;
                bool isFeeding     = false;

                try {
                    connection = printer.GetConnection();
                    connection.Open();

                    zebraCardPrinter = ZebraCardPrinterFactory.GetInstance(connection);

                    Stopwatch stopwatch = Stopwatch.StartNew();

                    foreach (JobInfo jobInfo in jobInfoList)
                    {
                        UpdateLog(jobInfo.JobId, $"Polling job status for job ID {jobInfo.JobId}...");
                    }

                    while (jobInfoList.Count > 0)
                    {
                        foreach (JobInfo jobInfo in jobInfoList.ToList())
                        {
                            JobStatusInfo jobStatusInfo = zebraCardPrinter.GetJobStatus(jobInfo.JobId);

                            if (!isFeeding)
                            {
                                stopwatch = Stopwatch.StartNew();
                            }

                            bool isAlarmInfoPresent = jobStatusInfo.AlarmInfo.Value > 0;
                            bool isErrorInfoPresent = jobStatusInfo.ErrorInfo.Value > 0;
                            isFeeding = jobStatusInfo.CardPosition.Contains("feeding");

                            string alarmInfo = isAlarmInfoPresent ? $"{jobStatusInfo.AlarmInfo.Value} ({jobStatusInfo.AlarmInfo.Description})" : jobStatusInfo.AlarmInfo.Value.ToString();
                            string errorInfo = isErrorInfoPresent ? $"{jobStatusInfo.ErrorInfo.Value} ({jobStatusInfo.ErrorInfo.Description})" : jobStatusInfo.ErrorInfo.Value.ToString();

                            string jobStatusMessage = $"Job ID {jobInfo.JobId}: status:{jobStatusInfo.PrintStatus}, position:{jobStatusInfo.CardPosition}, contact:{jobStatusInfo.ContactSmartCardStatus}, " +
                                                      $"contactless:{jobStatusInfo.ContactlessSmartCardStatus}, alarm:{alarmInfo}, error:{errorInfo}";

                            UpdateLog(jobInfo.JobId, jobStatusMessage, jobInfo.JobNumber, jobStatusInfo);

                            if (jobStatusInfo.PrintStatus.Equals("done_ok"))
                            {
                                UpdateLog(jobInfo.JobId, $"Job ID {jobInfo.JobId} completed.", jobInfo.JobNumber, jobStatusInfo);

                                showAtmDialog = true;
                                stopwatch     = Stopwatch.StartNew();
                                jobInfoList.Remove(jobInfo);
                            }
                            else if (jobStatusInfo.PrintStatus.Equals("done_error"))
                            {
                                UpdateLog(jobInfo.JobId, $"Job ID {jobInfo.JobId} completed with error: {jobStatusInfo.ErrorInfo.Description}", jobInfo.JobNumber, jobStatusInfo);

                                showAtmDialog = true;
                                stopwatch     = Stopwatch.StartNew();
                                jobInfoList.Remove(jobInfo);
                            }
                            else if (jobStatusInfo.PrintStatus.Contains("cancelled"))
                            {
                                if (isErrorInfoPresent)
                                {
                                    UpdateLog(jobInfo.JobId, $"Job ID {jobInfo.JobId} cancelled with error: {jobStatusInfo.ErrorInfo.Description}", jobInfo.JobNumber, jobStatusInfo);
                                }
                                else
                                {
                                    UpdateLog(jobInfo.JobId, $"Job ID {jobInfo.JobId} cancelled.", jobInfo.JobNumber, jobStatusInfo);
                                }

                                showAtmDialog = true;
                                stopwatch     = Stopwatch.StartNew();
                                jobInfoList.Remove(jobInfo);
                            }
                            else if (isAlarmInfoPresent)
                            {
                                MessageBoxResult messageBoxResult = MessageBox.Show($"Job ID {jobInfo.JobId} encountered alarm [{jobStatusInfo.AlarmInfo.Description}].\r\n" +
                                                                                    $"Either fix the alarm and click OK once the job begins again or click Cancel to cancel the job.", "Alarm Encountered", MessageBoxButton.OKCancel, MessageBoxImage.Warning);
                                if (messageBoxResult == MessageBoxResult.Cancel)
                                {
                                    zebraCardPrinter.Cancel(jobInfo.JobId);
                                }
                            }
                            else if (isErrorInfoPresent)
                            {
                                zebraCardPrinter.Cancel(jobInfo.JobId);
                            }
                            else if (jobStatusInfo.ContactSmartCardStatus.Contains("at_station") || jobStatusInfo.ContactlessSmartCardStatus.Contains("at_station"))
                            {
                                MessageBoxResult messageBoxResult = MessageBox.Show("Please click OK to resume the job or Cancel to cancel the job.", "Card at Station", MessageBoxButton.OKCancel, MessageBoxImage.Information);
                                if (messageBoxResult == MessageBoxResult.Cancel)
                                {
                                    zebraCardPrinter.Cancel(jobInfo.JobId);
                                }
                                else
                                {
                                    zebraCardPrinter.Resume();
                                }
                            }
                            else if (isFeeding)
                            {
                                if (showAtmDialog && jobInfo.CardSource == CardSource.ATM)
                                {
                                    DialogHelper.ShowInsertCardDialog();
                                    showAtmDialog = false;
                                }
                                else if (stopwatch.ElapsedMilliseconds > CardFeedTimeoutMilliseconds)
                                {
                                    UpdateLog(jobInfo.JobId, $"Job ID {jobInfo.JobId} timed out waiting for a card and was cancelled.", jobInfo.JobNumber, jobStatusInfo);
                                    zebraCardPrinter.Cancel(jobInfo.JobId);
                                }
                            }

                            Thread.Sleep(500);
                        }
                    }
                } catch (Exception exception) {
                    MessageBoxHelper.ShowError($"Error polling job status: {exception.Message}");
                } finally {
                    ConnectionHelper.CleanUpQuietly(zebraCardPrinter, connection);
                }
            });
        }
Пример #10
0
 public virtual bool ShowHelp()
 {
     DialogHelper.ProcessStart("http://go.microsoft.com/fwlink/?LinkId=210528");
     return(false);
 }
Пример #11
0
 /// <summary>
 /// 显示进度条
 /// </summary>
 public static void ShowProgress()
 {
     DialogHelper.CreateContentDialog(new ProgressDialog(), true);
 }
    protected override async Task RunAsync(CancellationToken token)
    {
        try
        {
            Logger.Info("Connecting to {0} at \"{1}\"", Name, _pipeName);
            using var client = new NamedPipeClientStream(".", _pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);

            try
            {
                await client.ConnectAsync(500, token);
            }
            catch (TimeoutException)
            {
                var executable = Executable?.AsRefreshed() ?? new FileInfo(Path.Join(Path.GetDirectoryName(Environment.ProcessPath), "mpv.exe"));
                if (!executable.Exists)
                {
                    throw new Exception("Could not find mpv executable! Please set path to mpv.exe or download latest release from settings.");
                }
                else
                {
                    var processInfo = new ProcessStartInfo()
                    {
                        FileName  = executable.FullName,
                        Arguments = $"--input-ipc-server={_pipeName} {Arguments}"
                    };

                    Process.Start(processInfo);

                    await client.ConnectAsync(2000, token);
                }
            }

            if (client.IsConnected)
            {
                using var reader = new StreamReader(client);
                using var writer = new StreamWriter(client)
                      {
                          AutoFlush = true
                      };

                await writer.WriteLineAsync("{ \"command\": [\"observe_property_string\", 1, \"pause\"] }");

                await writer.WriteLineAsync("{ \"command\": [\"observe_property_string\", 2, \"duration\"] }");

                await writer.WriteLineAsync("{ \"command\": [\"observe_property_string\", 3, \"time-pos\"] }");

                await writer.WriteLineAsync("{ \"command\": [\"observe_property_string\", 4, \"path\"] }");

                await writer.WriteLineAsync("{ \"command\": [\"observe_property_string\", 5, \"speed\"] }");

                Status = ConnectionStatus.Connected;
                while (_writeMessageChannel.Reader.TryRead(out _))
                {
                    ;
                }

                using var cancellationSource = CancellationTokenSource.CreateLinkedTokenSource(token);
                var task = await Task.WhenAny(ReadAsync(client, reader, cancellationSource.Token), WriteAsync(client, writer, cancellationSource.Token));

                cancellationSource.Cancel();

                task.ThrowIfFaulted();
            }
        }
        catch (OperationCanceledException) { }
        catch (IOException e) { Logger.Debug(e, $"{Name} failed with exception"); }
        catch (Exception e)
        {
            Logger.Error(e, $"{Name} failed with exception");
            _ = DialogHelper.ShowErrorAsync(e, $"{Name} failed with exception", "RootDialog");
        }

        _eventAggregator.Publish(new MediaPathChangedMessage(null));
        _eventAggregator.Publish(new MediaPlayingChangedMessage(isPlaying: false));
    }
Пример #13
0
 public CheckedMessageBoxResult BlockingCheckedMessageBox(string message, bool?isChecked, string checkboxMessage, MessageBoxButton button = MessageBoxButton.OK, MessageBoxImage image = MessageBoxImage.None, WindowOwner owner = WindowOwner.LastModal)
 {
     return(DialogHelper.BlockingCheckedMessageBox(Dispatcher, message, ApplicationName, isChecked, checkboxMessage, button, image, owner));
 }
Пример #14
0
        private async Task GeneratePrecompiledFont()
        {
            var font          = (SpriteFontAsset)AssetItem.Asset;
            var dialogService = ServiceProvider.Get <IDialogService>();

            // Dynamic font cannot be precompiled
            if (font.FontType is RuntimeRasterizedSpriteFontType)
            {
                // Note: Markdown (**, _) are used to format the text.
                await dialogService.MessageBox(Tr._p("Message", "**Only static fonts can be precompiled.**\r\n\r\nClear the _Is Dynamic_ property on this font and try again."), MessageBoxButton.OK, MessageBoxImage.Error);

                return;
            }
            // Compute unique name
            var precompiledName = NamingHelper.ComputeNewName($"{AssetItem.Location.GetFileNameWithoutExtension()} (Precompiled)", Directory.Assets, x => x.Name);

            // Ask location for generated texture
            var folderDialog = dialogService.CreateFolderOpenModalDialog();

            folderDialog.InitialDirectory = (Session.CurrentProject?.Package?.RootDirectory ?? Session.SolutionPath.GetFullDirectory()).ToWindowsPath() + "\\Resources";
            var dialogResult = await folderDialog.ShowModal();

            if (dialogResult != DialogResult.Ok)
            {
                return;
            }

            bool srgb;
            var  gameSettings = Session.CurrentProject?.Package.GetGameSettingsAsset();

            if (gameSettings == null)
            {
                var buttons = DialogHelper.CreateButtons(new[] { ColorSpace.Linear.ToString(), ColorSpace.Gamma.ToString(), Tr._p("Button", "Cancel") }, 1, 3);
                var result  = await dialogService.MessageBox(Tr._p("Message", "Which color space do you want to use?"), buttons, MessageBoxImage.Question);

                // Close without clicking a button or Cancel
                if (result == 0 || result == 3)
                {
                    return;
                }
                srgb = result == 2;
            }
            else
            {
                srgb = gameSettings.GetOrCreate <RenderingSettings>().ColorSpace == ColorSpace.Linear;
            }

            var precompiledFontAsset = (font.FontType is SignedDistanceFieldSpriteFontType) ?
                                       font.GeneratePrecompiledSDFSpriteFont(AssetItem, UFile.Combine(folderDialog.Directory, precompiledName)) :
                                       font.GeneratePrecompiledSpriteFont(AssetItem, UFile.Combine(folderDialog.Directory, precompiledName), srgb);

            // NOTE: following code could be factorized with AssetFactoryViewModel
            var            defaultLocation = UFile.Combine(Directory.Path, precompiledName);
            var            assetItem       = new AssetItem(defaultLocation, precompiledFontAsset);
            AssetViewModel assetViewModel;

            using (var transaction = UndoRedoService.CreateTransaction())
            {
                // FIXME: do we need to delete the generated file upon undo?
                assetViewModel = Directory.Package.CreateAsset(Directory, assetItem, true, null);
                UndoRedoService.SetName(transaction, $"Create Asset '{precompiledName}'");
            }

            Session.CheckConsistency();
            if (assetViewModel != null)
            {
                Session.ActiveAssetView.SelectAssetCommand.Execute(assetViewModel);
            }
        }
    public async void OnDownloadExecutable()
    {
        IsDownloading = true;
        Executable    = null;

        try
        {
            var downloadRoot = new DirectoryInfo(Path.Combine(Path.GetDirectoryName(Environment.ProcessPath), "bin", "mpv"));
            if (downloadRoot.Exists)
            {
                downloadRoot.Delete(true);
            }

            downloadRoot = Directory.CreateDirectory(downloadRoot.FullName);
            var bootstrapperUri = new Uri("https://sourceforge.net/projects/mpv-player-windows/files/bootstrapper.zip/download");
            var bootstrapperZip = new FileInfo(Path.Combine(downloadRoot.FullName, "bootstrapper.zip"));

            {
                using var client = WebUtils.CreateClient();
                await client.DownloadFileAsync(bootstrapperUri, bootstrapperZip.FullName);
            }

            ZipFile.ExtractToDirectory(bootstrapperZip.FullName, downloadRoot.FullName, true);
            bootstrapperZip.Delete();

            var updater = new FileInfo(Path.Combine(downloadRoot.FullName, "updater.bat"));
            using var process = new Process
                  {
                      StartInfo =
                      {
                          FileName        = updater.FullName,
                          UseShellExecute = true
                      },
                      EnableRaisingEvents = true
                  };

            var completionSource = new TaskCompletionSource <int>();
            process.Exited += (s, e) => completionSource.SetResult(process.ExitCode);
            process.Start();

            var result = await completionSource.Task;
            if (result == 0)
            {
                Executable = new FileInfo(Path.Combine(downloadRoot.FullName, "mpv.exe"));
            }

            foreach (var file in downloadRoot.EnumerateFiles("mpv*.7z"))
            {
                file.Delete();
            }

            if (Executable?.Exists == false)
            {
                Executable = null;
            }
        }
        catch (Exception e)
        {
            Logger.Error(e, $"{Name} executable download failed with exception");
            _ = DialogHelper.ShowErrorAsync(e, $"{Name} executable download failed with exception", "RootDialog");
        }

        IsDownloading = false;
    }
        protected override void CompleteWizard()
        {
            // Generate the CSR
            X509Name subjectName =
                new X509Name(string.Format("C={0},ST={1},L={2},O={3},OU={4},CN={5}",
                                           _wizardData.Country,
                                           _wizardData.State,
                                           _wizardData.City,
                                           _wizardData.Organization,
                                           _wizardData.Unit,
                                           _wizardData.CommonName));

            // Generate the private/public keypair
            RsaKeyPairGenerator      kpgen           = new RsaKeyPairGenerator();
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();

            kpgen.Init(new KeyGenerationParameters(new SecureRandom(randomGenerator), _wizardData.Length));
            AsymmetricCipherKeyPair keyPair = kpgen.GenerateKeyPair();
            // Generate the CSR

            Asn1Set attributes = new DerSet(
                new DerSequence(
                    new DerObjectIdentifier("1.3.6.1.4.1.311.13.2.3"),
                    new DerSet(new DerIA5String(Environment.OSVersion.Version.ToString()))),
                new DerSequence(
                    new DerObjectIdentifier("1.3.6.1.4.1.311.21.20"),
                    new DerSet(
                        new DerSequence(
                            new DerInteger(5),
                            new DerUtf8String(Environment.MachineName),
                            new DerUtf8String(Environment.UserName),
                            new DerUtf8String("JexusManager.exe")))),
                new DerSequence(
                    new DerObjectIdentifier("1.3.6.1.4.1.311.13.2.2"),
                    new DerSet(
                        new DerSequence(
                            new DerInteger(1),
                            new DerBmpString("Microsoft RSA SChannel Cryptographic Provider"),
                            new DerBitString(new byte[0])))),
                new DerSequence(
                    new DerObjectIdentifier("1.2.840.113549.1.9.14"),
                    new DerSet(
                        new DerSequence(
                            new DerSequence(
                                new DerObjectIdentifier("2.5.29.15"),
                                new DerBoolean(new byte[] { 0x01 }),
                                new DerOctetString(new byte[] { 0x03, 0x02, 0x04, 0xF0 })),
                            new DerSequence(
                                new DerObjectIdentifier("2.5.29.37"),
                                new DerOctetString(new byte[]
            {
                0x30, 0x0a, 0x06, 0x08,
                0x2b, 0x06, 0x01, 0x05,
                0x05, 0x07, 0x03, 0x01
            })),
                            new DerSequence(
                                new DerObjectIdentifier("1.2.840.113549.1.9.15"),
                                new DerOctetString(new byte[]
            {
                0x30, 0x69, 0x30, 0x0e,
                0x06, 0x08, 0x2a, 0x86,
                0x48, 0x86, 0xf7, 0x0d,
                0x03, 0x02, 0x02, 0x02,
                0x00, 0x80, 0x30, 0x0e,
                0x06, 0x08, 0x2a, 0x86,
                0x48, 0x86, 0xf7, 0x0d,
                0x03, 0x04, 0x02, 0x02,
                0x00, 0x80, 0x30, 0x0b,
                0x06, 0x09, 0x60, 0x86,
                0x48, 0x01, 0x65, 0x03,
                0x04, 0x01, 0x2a, 0x30,
                0x0b, 0x06, 0x09, 0x60,
                0x86, 0x48, 0x01, 0x65,
                0x03, 0x04, 0x01, 0x2d,
                0x30, 0x0b, 0x06, 0x09,
                0x60, 0x86, 0x48, 0x01,
                0x65, 0x03, 0x04, 0x01,
                0x02, 0x30, 0x0b, 0x06,
                0x09, 0x60, 0x86, 0x48,
                0x01, 0x65, 0x03, 0x04,
                0x01, 0x05, 0x30, 0x07,
                0x06, 0x05, 0x2b, 0x0e,
                0x03, 0x02, 0x07, 0x30,
                0x0a, 0x06, 0x08, 0x2a,
                0x86, 0x48, 0x86, 0xf7,
                0x0d, 0x03, 0x07
            })),
                            new DerSequence(
                                new DerObjectIdentifier("2.5.29.14"),
                                new DerOctetString(new byte[]
            {
                0x04, 0x14, 0xaa, 0x25,
                0xd9, 0xa2, 0x39, 0x7e,
                0x49, 0xd2, 0x94, 0x85,
                0x7e, 0x82, 0xa8, 0x8f,
                0x3b, 0x20, 0xf1, 0x4e, 0x65, 0xe5
            }))))));

            var signing = new Asn1SignatureFactory("SHA256withRSA", keyPair.Private);
            Pkcs10CertificationRequest kpGen = new Pkcs10CertificationRequest(signing, subjectName, keyPair.Public, attributes, keyPair.Private);

            using (var stream = new StreamWriter(_wizardData.FileName))
            {
                stream.WriteLine(_wizardData.UseIisStyle ? "-----BEGIN NEW CERTIFICATE REQUEST-----" : "-----BEGIN CERTIFICATE REQUEST-----");
                stream.WriteLine(Convert.ToBase64String(kpGen.GetDerEncoded(), Base64FormattingOptions.InsertLineBreaks));
                stream.WriteLine(_wizardData.UseIisStyle ? "-----END NEW CERTIFICATE REQUEST-----" : "-----END CERTIFICATE REQUEST-----");
            }

            var        key = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)keyPair.Private);
            PrivateKey pvk = new PrivateKey();

            pvk.RSA = new RSACryptoServiceProvider();
            pvk.RSA.ImportParameters(key);
            pvk.Save(DialogHelper.GetPrivateKeyFile(subjectName.ToString()));
        }
Пример #17
0
        private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string   name         = ValidateProduct.Name(tbName.Text);
                int      quantity     = ValidateProduct.Quantity(tbQuantity.Text);
                string   unitName     = cbUnit.Text;
                decimal  unitQuantity = ValidateProduct.UnitQuantity(tbUnitQuantity.Text);
                DateTime?date         = ValidateProduct.Date(dpExpirationDate.SelectedDate);
                int      code         = ValidateProduct.Code(tbCode.Text);
                decimal  price        = ValidateProduct.Price(tbPrice.Text);
                price = Convert.ToDecimal(Math.Round(Convert.ToDouble(price), 1, MidpointRounding.AwayFromZero)); // cena se zaokrouhlí na jedno desetinné místo
                bool priceForUnit = cbPriceForUnit.Text == "Ano" ? true : false;
                char VAT          = cbVAT.SelectedItem.ToString()[0];

                LinqToSqlDataContext db = DatabaseSetup.Database;
                int i = (from u in db.Units
                         where u.name == unitName
                         select u.id).Single();
                int unitId = i;

                if (StorageSetup.AddProduct(name, quantity, unitId, unitQuantity, date, code, price, priceForUnit, VAT))
                {
                    // ještě je potřeba uložit do databáze obrázky a asociovat je s produktem
                    Product lastAddedProduct = StorageSetup.GetLastAddedProduct();
                    if (gallery.lbContainer.HasItems)
                    {
                        foreach (ImageStruct istr in gallery.Images)
                        {
                            Images.AddImage(istr);
                            ImagesTable lastAddedImage = Images.FindLastAddedImage();
                            Images.AssignImageToProduct(lastAddedProduct, lastAddedImage);
                        }
                    }

                    DialogHelper.ShowInfo("Produkt přidán.");
                    this.Close();
                }
                else
                {
                    throw new NotImplementedException();
                }
            }
            catch (InvalidNameException ex)
            {
                DialogHelper.ShowWarning(ex.Message);
            }
            catch (InvalidQuantityException ex)
            {
                DialogHelper.ShowWarning(ex.Message);
            }
            catch (InvalidUnitQuantityException ex)
            {
                DialogHelper.ShowWarning(ex.Message);
            }
            catch (ExistingCodeException ex)
            {
                DialogHelper.ShowWarning(ex.Message);
            }
            catch (InvalidCodeException ex)
            {
                DialogHelper.ShowWarning(ex.Message);
            }

            catch (InvalidPriceException ex)
            {
                DialogHelper.ShowWarning(ex.Message);
            }
            catch (NullDateTimeException ex)
            {
                DialogHelper.ShowWarning(ex.Message);
            }
            catch
            {
                DialogHelper.ShowError("Produkt nebylo možné přidat.");
            }
        }
Пример #18
0
 private void AddConditionDialogHelpButtonClicked(object sender, CancelEventArgs e)
 {
     DialogHelper.ProcessStart("http://go.microsoft.com/fwlink/?LinkID=130403&amp;clcid=0x409");
 }
Пример #19
0
 private void BtnBrowseClick(object sender, EventArgs e)
 {
     DialogHelper.ShowOpenFileDialog(txtName, "Common Files|*.config;*.sln|Config Files|*.config|Solution Files|*.sln|All Files|*.*");
 }
Пример #20
0
        private async Task ReadMagEncodeData()
        {
            MessageDialog insertCardDialog = null;

            viewModel.Track1Data = "";
            viewModel.Track2Data = "";
            viewModel.Track3Data = "";
            JobStatusControl.ClearLog();

            Console.SetOut(new TextBoxTextWriter(JobStatusControl.JobStatusLog));

            await printerManager.PerformAction("Reading mag encode data...", (zebraCardPrinter, connection) => {
                if (printerManager.IsPrinterReady(zebraCardPrinter, JobStatusControl))
                {
                    Console.WriteLine(); // Start logging on new line after printer ready check

                    CardSource cardSource = (CardSource)Enum.Parse(typeof(CardSource), viewModel.SelectedSource);

                    Dictionary <string, string> jobSettings = new Dictionary <string, string> {
                        { ZebraCardJobSettingNames.CARD_SOURCE, cardSource.ToString() },
                        { ZebraCardJobSettingNames.CARD_DESTINATION, viewModel.SelectedDestination.ToString() }
                    };

                    zebraCardPrinter.SetJobSettings(jobSettings);

                    if (cardSource == CardSource.ATM)
                    {
                        insertCardDialog = DialogHelper.ShowInsertCardDialog();
                    }

                    MagTrackData magTrackData = zebraCardPrinter.ReadMagData(DataSource.Track1 | DataSource.Track2 | DataSource.Track3, true);

                    if (string.IsNullOrEmpty(magTrackData.Track1) && string.IsNullOrEmpty(magTrackData.Track2) && string.IsNullOrEmpty(magTrackData.Track3))
                    {
                        Console.WriteLine("No data read from card.");
                    }

                    Application.Current.Dispatcher.Invoke(() => {
                        viewModel.Track1Data = magTrackData.Track1;
                        viewModel.Track2Data = magTrackData.Track2;
                        viewModel.Track3Data = magTrackData.Track3;
                    });
                }
            }, (exception) => {
                string errorMessage = $"Error reading mag encode data: {exception.Message}";
                MessageBoxHelper.ShowError(errorMessage);
                Console.WriteLine(errorMessage);
            });

            if (insertCardDialog != null)
            {
                insertCardDialog.Close();
            }

            StreamWriter streamWriter = new StreamWriter(Console.OpenStandardOutput())
            {
                AutoFlush = true
            };

            Console.SetOut(streamWriter);
        }
Пример #21
0
 public MessageBoxResult BlockingMessageBox(string message, IEnumerable <DialogButtonInfo> buttons, MessageBoxImage image = MessageBoxImage.None, WindowOwner owner = WindowOwner.LastModal)
 {
     return(DialogHelper.BlockingMessageBox(Dispatcher, message, ApplicationName, buttons, image, owner));
 }
        public StreamingPlatformAccountControlViewModel(StreamingPlatformTypeEnum platform)
        {
            this.Platform = platform;

            if (this.IsUserAccountConnected)
            {
                if (this.Platform == StreamingPlatformTypeEnum.Twitch && ChannelSession.TwitchUserNewAPI != null)
                {
                    this.UserAccountAvatar   = ChannelSession.TwitchUserNewAPI.profile_image_url;
                    this.UserAccountUsername = ChannelSession.TwitchUserNewAPI.display_name;
                }
            }
            if (this.IsBotAccountConnected)
            {
                if (this.Platform == StreamingPlatformTypeEnum.Twitch && ChannelSession.TwitchBotNewAPI != null)
                {
                    this.BotAccountAvatar   = ChannelSession.TwitchBotNewAPI.profile_image_url;
                    this.BotAccountUsername = ChannelSession.TwitchBotNewAPI.display_name;
                }
            }

            this.UserAccountCommand = this.CreateCommand(async() =>
            {
                if (this.IsUserAccountConnected)
                {
                    //if (this.Platform == StreamingPlatformTypeEnum.Mixer)
                    //{
                    //    ChannelSession.DisconnectMixerUser();
                    //}
                    //this.UserAccountAvatar = null;
                    //this.UserAccountUsername = null;
                }
                else
                {
                    Result result = new Result(false);
                    if (this.Platform == StreamingPlatformTypeEnum.Twitch)
                    {
                        result = await ChannelSession.ConnectTwitchUser();
                        if (result.Success && ChannelSession.TwitchUserNewAPI != null)
                        {
                            this.UserAccountAvatar   = ChannelSession.TwitchUserNewAPI.profile_image_url;
                            this.UserAccountUsername = ChannelSession.TwitchUserNewAPI.display_name;
                        }
                    }

                    if (!result.Success)
                    {
                        this.UserAccountAvatar   = null;
                        this.UserAccountUsername = null;

                        await DialogHelper.ShowMessage(result.Message);
                    }
                }
                this.NotifyAllProperties();
            });

            this.BotAccountCommand = this.CreateCommand(async() =>
            {
                if (this.IsBotAccountConnected)
                {
                    if (this.Platform == StreamingPlatformTypeEnum.Twitch)
                    {
                        await ChannelSession.DisconnectTwitchBot();
                        ChannelSession.Settings.StreamingPlatformAuthentications[StreamingPlatformTypeEnum.Twitch].BotOAuthToken = null;
                    }
                    this.BotAccountAvatar   = null;
                    this.BotAccountUsername = null;
                }
                else
                {
                    Result result = new Result(false);
                    if (this.Platform == StreamingPlatformTypeEnum.Twitch)
                    {
                        result = await ChannelSession.ConnectTwitchBot();
                        if (result.Success)
                        {
                            if (ChannelSession.TwitchBotNewAPI.id.Equals(ChannelSession.TwitchUserNewAPI?.id))
                            {
                                await ChannelSession.DisconnectTwitchBot();
                                result = new Result(MixItUp.Base.Resources.BotAccountMustBeDifferent);
                            }
                            else if (ChannelSession.TwitchBotNewAPI != null)
                            {
                                this.BotAccountAvatar   = ChannelSession.TwitchBotNewAPI.profile_image_url;
                                this.BotAccountUsername = ChannelSession.TwitchBotNewAPI.display_name;
                            }
                        }
                    }

                    if (!result.Success)
                    {
                        this.BotAccountAvatar   = null;
                        this.BotAccountUsername = null;

                        await DialogHelper.ShowMessage(result.Message);
                    }
                }
                this.NotifyAllProperties();
            });
        }
Пример #23
0
 public virtual bool ShowHelp()
 {
     DialogHelper.ProcessStart("http://go.microsoft.com/fwlink/?LinkID=130403&amp;clcid=0x409");
     return(false);
 }
Пример #24
0
        public void RunStarted(object automationObject, Dictionary <string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
        {
            bool iscancel = false;

            try
            {
                var dte            = (DTE)automationObject;
                var currentProject = dte.ActiveSolutionProjects[0] as Project;
                var kind           = currentProject.Kind;

                var    framework = GetFrameworkName(currentProject);
                string language  = string.Empty;
                var    isnetcore = false;
                var    val       = currentProject.Kind.ToUpper().Trim('{', '}');
                switch (currentProject.Kind.ToUpper().Trim('{', '}'))
                {
                case "FAE04EC0-301F-11D3-BF4B-00C04F79EFBC":    //.net framework
                    language = "CSharp";
                    break;

                case "F184B08F-C81C-45F6-A57F-5ABD9991F28F":    //.net framework
                    language = "VisualBasic";
                    break;

                case "9A19103F-16F7-4668-BE54-9A1E7A4F7556":    //.net core
                    language  = "CSharp";
                    isnetcore = true;
                    break;

                case "778DAE3C-4631-46EA-AA77-85C1314464D9":    //.net core
                    language  = "VisualBasic";
                    isnetcore = true;
                    break;

                default:
                    throw new NotSupportedException(currentProject.Kind);
                }
                var iswebproject = false;
                if (!isnetcore)
                {
                    var extenderNames = (string[])currentProject.ExtenderNames;
                    iswebproject = extenderNames.Contains("WebApplication");
                }
                else
                {
                    replacementsDictionary.Add("$netcore$", "true");
                }
                var configFileName = iswebproject ? "Web.config" : "App.config";
                var templateName   = iswebproject ? "WebConfig.zip" :
                                     (language == "VisualBasic" ? "AppConfiguration.zip" : "AppConfig.zip");

                NewItemWizardViewModel vm = new NewItemWizardViewModel()
                {
                    ConfigName = replacementsDictionary["$safeitemname$"],
                    Language   = language
                };
                if (DialogHelper.ShowDialog(ref vm) == true)
                {
                    if (vm.IsSaveConfig && !isnetcore)
                    {
                        var configureItem = FindProjectItemConfigure(currentProject, configFileName);
                        if (configureItem == null)
                        {
                            var templatePath = ((Solution2)dte.Solution).GetProjectItemTemplate(templateName, language);
                            currentProject.ProjectItems.AddFromTemplate(templatePath, configFileName);
                            configureItem = FindProjectItemConfigure(currentProject, configFileName);
                        }
                        replacementsDictionary.Add("$megoargu$", $"\"{vm.ConfigName}\"");
                        WriteConnectionString(vm, configureItem);
                    }
                    else
                    {
                        var info = vm.Information;
                        replacementsDictionary.Add("$megoargu$", $"\"{info.ConnectionString}\", \"{info.ProviderName}\"");
                    }
                    var generator = vm.Generator;
                    replacementsDictionary.Add("$megodbset$", generator.GenerateDbSet());
                    replacementsDictionary.Add("$megoclassdef$", generator.GenerateSetClass());
                    _AllowAddProjectItem = true;
                    InstallNugetPackage(currentProject);
                }
                else
                {
                    iscancel = true;
                }
            }
            catch (Exception ex)
            {
                DialogHelper.MessageBox(ex.Message);
            }
            if (iscancel)
            {
                throw new WizardCancelledException("The wizard has been cancelled by the user.");
            }
        }
Пример #25
0
        private void View()
        {
            var cert = SelectedItem.Certificate;

            DialogHelper.DisplayCertificate(cert, IntPtr.Zero);
        }
        private void SaveBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            _view.Dispatcher.Invoke(DispatcherPriority.Render, (Action)(() =>
            {
                var dataResponse = new DataResponse(true, 1);
                if (IsAdding)
                {
                    Checksum = FileUtils.GetChecksum(_filePath);
                    dataResponse = ServiceManager.Upload(new FileUploadRequest
                    {
                        Name = Name,
                        SecurityKey = RequestResponseUtils.EncryptString(
                            AppSettings.GetConfig <string>(CommonConstants.MESSAGE_KEY)),
                        VirtualPath = _filePath
                    }, Checksum);
                }
                else
                {
                    if (_oriFileName != Executable)
                    {
                        Checksum = FileUtils.GetChecksum(_filePath);
                        //upload another file
                        ServiceManager.DeleteSoftwareFile(new List <string> {
                            Name
                        });
                        dataResponse = ServiceManager.Upload(new FileUploadRequest
                        {
                            Name = Name,
                            SecurityKey = RequestResponseUtils.EncryptString(
                                AppSettings.GetConfig <string>(CommonConstants.MESSAGE_KEY)),
                            VirtualPath = _filePath
                        }, Checksum);
                    }
                }

                if (!dataResponse.Status)
                {
                    DialogHelper.Error(dataResponse.Message, "Error on Upload file");
                    e.Result = false;
                    return;
                }

                var scontent = new SoftwareContent
                {
                    Id = Id,
                    Comment = Comment,
                    FileName = Executable,
                    LastUpdated = DateTime.Now,
                    Name = Name,
                    Parameters = Parameters,
                    Size = Size,
                    Version = Version,
                    Checksum = Checksum
                };
                var resultDeserialize = ServiceManager.Invoke(sc => RequestResponseUtils.GetData <DataResponse>(
                                                                  sc.SoftwareInsertOrUpdate,
                                                                  scontent));
                Id = resultDeserialize.Result;
                e.Result = resultDeserialize.Status;
            }));
        }
Пример #27
0
        public void AddDelayedNotification(SettingsKey <bool> confirmationSettingsKey, string message, string yesCaption, string noCaption, Action yesAction, Action noAction, SettingsKey <bool> yesNoSettingsKey)
        {
            if (confirmationSettingsKey == null)
            {
                throw new ArgumentNullException(nameof(confirmationSettingsKey));
            }
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }
            if (yesCaption == null)
            {
                throw new ArgumentNullException(nameof(yesCaption));
            }
            if (noCaption == null)
            {
                throw new ArgumentNullException(nameof(noCaption));
            }

            // Prevent duplicate
            if (delayedNotifications.Any(t => ReferenceEquals(t.Item1, confirmationSettingsKey)))
            {
                return;
            }

            Action action = async() =>
            {
                var yesNo = yesNoSettingsKey?.GetValue() ?? true;
                var ask   = confirmationSettingsKey.GetValue();
                if (ask)
                {
                    var buttons = DialogHelper.CreateButtons(new[] { yesCaption, noCaption }, 1, 2);
                    var result  = await CheckedMessageBox(message, false, DialogHelper.DontAskAgain, buttons, MessageBoxImage.Question);

                    // Close without clicking on a button
                    if (result.Result == 0)
                    {
                        return;
                    }

                    yesNo = result.Result == 1;
                    if (result.IsChecked == true && (yesNo || yesNoSettingsKey != null))
                    {
                        confirmationSettingsKey.SetValue(false);
                        yesNoSettingsKey?.SetValue(yesNo);
                        Settings.EditorSettings.Save();
                    }
                }
                if (yesNo)
                {
                    yesAction?.Invoke();
                }
                else
                {
                    noAction?.Invoke();
                }
            };

            var windows = Application.Current.Windows;

            if (windows.Count == 0 || windows.OfType <Window>().Any(w => w.IsActive))
            {
                // Execute immediately
                Dispatcher.Invoke(action);
                return;
            }

            // Add a new question
            delayedNotifications.Enqueue(Tuple.Create((SettingsKey)confirmationSettingsKey, action));
        }
Пример #28
0
        public BindingDialog(IServiceProvider serviceProvider, Binding binding1, Site site)
            : base(serviceProvider)
        {
            InitializeComponent();
            Binding = binding1;
            Text    = Binding == null ? "Create Site Binding" : "Edit Site Binding";
            DialogHelper.LoadAddresses(cbAddress);
            txtPort.Text         = "80";
            cbType.SelectedIndex = 0;
            if (!site.Server.SupportsSni)
            {
                cbSniRequired.Enabled = false;
            }

            if (Binding == null)
            {
                txtHost.Text = site.Server.Mode == WorkingMode.IisExpress ? "localhost" : string.Empty;
            }
            else
            {
                cbType.Text    = Binding.Protocol;
                cbType.Enabled = Binding == null;
                cbAddress.Text = Binding.EndPoint.Address.AddressToCombo();
                txtPort.Text   = Binding.EndPoint.Port.ToString();
                txtHost.Text   = Binding.Host.HostToDisplay();
                if (site.Server.SupportsSni)
                {
                    cbSniRequired.Checked = Binding.GetIsSni();
                }
            }

            var container = new CompositeDisposable();

            FormClosed += (sender, args) => container.Dispose();

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnOK, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                IPAddress address;
                try
                {
                    address = cbAddress.Text.ComboToAddress();
                }
                catch (Exception)
                {
                    MessageBox.Show("The specified IP address is invalid. Specify a valid IP address.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                int port;
                try
                {
                    port = int.Parse(txtPort.Text);
                }
                catch (Exception)
                {
                    MessageBox.Show("The server port number must be a positive integer between 1 and 65535", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                if (port < 1 || port > 65535)
                {
                    MessageBox.Show("The server port number must be a positive integer between 1 and 65535", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                var invalid = "\"/\\[]:|<>+=;,?*$%#@{}^`".ToCharArray();
                foreach (var ch in invalid)
                {
                    if (txtHost.Text.Contains(ch))
                    {
                        MessageBox.Show("The specified host name is incorrect. The host name must use a valid host name format and cannot contain the following characters: \"/\\[]:|<>+=;,?*$%#@{}^`. Example: www.contoso.com.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                }

                if (site.Server.Mode == WorkingMode.IisExpress)
                {
                    if (txtHost.Text != "localhost")
                    {
                        MessageBox.Show(
                            "The specific host name is not recommended for IIS Express. The host name should be localhost.",
                            Text,
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Warning);
                    }
                }

                var certificate = cbCertificates.SelectedItem as CertificateInfo;
                var host        = txtHost.Text.DisplayToHost();
                var binding     = new Binding(
                    cbType.Text,
                    $"{address.AddressToDisplay()}:{port}:{host.HostToDisplay()}",
                    cbType.Text == "https" ? certificate?.Certificate.GetCertHash() : new byte[0],
                    cbType.Text == "https" ? certificate?.Store : null,
                    cbSniRequired.Checked ? SslFlags.Sni : SslFlags.None,
                    site.Bindings);
                var matched = site.Parent.FindDuplicate(binding, site, Binding);
                if (matched == true)
                {
                    var result = ShowMessage(
                        $"The binding '{binding}' is assigned to another site. If you assign the same binding to this site, you will only be able to start one of the sites. Are you sure that you want to add this duplicate binding?",
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question,
                        MessageBoxDefaultButton.Button1);
                    if (result != DialogResult.Yes)
                    {
                        return;
                    }
                }

                if (matched == null)
                {
                    ShowMessage(
                        "The specific port is being used by a different binding.",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Warning,
                        MessageBoxDefaultButton.Button1);
                    return;
                }

                var conflicts = binding.DetectConflicts();
                if (conflicts)
                {
                    var result = ShowMessage(
                        $"This binding is already being used. If you continue you might overwrite the existing certificate for this IP Address:Port or Host Name:Port combination. Do you want to use this binding anyway?",
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question,
                        MessageBoxDefaultButton.Button1);
                    if (result != DialogResult.Yes)
                    {
                        return;
                    }
                }

                if (Binding == null)
                {
                    Binding = binding;
                }
                else
                {
                    Binding.Reinitialize(binding);
                }

                if (site.Server.Mode == WorkingMode.IisExpress)
                {
                    var result = Binding.FixCertificateMapping(certificate?.Certificate);
                    if (!string.IsNullOrEmpty(result))
                    {
                        MessageBox.Show($"The binding '{Binding}' is invalid: {result}", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }

                DialogResult = DialogResult.OK;
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(cbType, "SelectedIndexChanged")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                txtPort.Text            = cbType.Text == "http" ? "80" : "443";
                txtCertificates.Visible = cbType.SelectedIndex == 1;
                cbSniRequired.Visible   = cbType.SelectedIndex == 1;
                cbCertificates.Visible  = cbType.SelectedIndex == 1;
                btnSelect.Visible       = cbType.SelectedIndex == 1;
                btnView.Visible         = cbType.SelectedIndex == 1;
            }));

            var certificatesSelected = Observable.FromEventPattern <EventArgs>(cbCertificates, "SelectedIndexChanged");

            container.Add(
                certificatesSelected
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                btnView.Enabled = cbCertificates.SelectedIndex > 0;
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(cbAddress, "TextChanged")
                .Merge(Observable.FromEventPattern <EventArgs>(txtPort, "TextChanged"))
                .Merge(certificatesSelected)
                .Sample(TimeSpan.FromSeconds(1))
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                if (Helper.IsRunningOnMono())
                {
                    return;
                }

                var toElevate = BindingUtility.Verify(cbType.Text, cbAddress.Text, txtPort.Text, cbCertificates.SelectedItem as CertificateInfo);
                btnOK.Enabled = toElevate != null;
                if (!toElevate.HasValue || !toElevate.Value)
                {
                    JexusManager.NativeMethods.RemoveShieldFromButton(btnOK);
                }
                else
                {
                    JexusManager.NativeMethods.TryAddShieldToButton(btnOK);
                }
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnView, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                DialogHelper.DisplayCertificate(((CertificateInfo)cbCertificates.SelectedItem).Certificate, Handle);
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnSelect, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                // TODO:
            }));
        }
Пример #29
0
        internal Platform()
        {
            _renderer = new PlatformRenderer(this);
            _modals   = new List <Page>();
            Application.Current.NavigationProxy.Inner = this;

            MessagingCenter.Subscribe(this, Page.AlertSignalName, (Page sender, AlertArguments arguments) => DialogHelper.ShowAlert(PlatformRenderer, arguments));
            MessagingCenter.Subscribe(this, Page.ActionSheetSignalName, (Page sender, ActionSheetArguments arguments) => DialogHelper.ShowActionSheet(PlatformRenderer, arguments));
        }
 public void teste_do_construtor()
 {
     var dialogHelper = new DialogHelper(null);
 }
        public CompleteRequestDialog(IServiceProvider serviceProvider, CertificatesFeature feature)
            : base(serviceProvider)
        {
            InitializeComponent();
            cbStore.SelectedIndex = 0;
            if (Environment.OSVersion.Version < Version.Parse("6.2"))
            {
                // IMPORTANT: WebHosting store is available since Windows 8.
                cbStore.Enabled = false;
            }

            if (!Helper.IsRunningOnMono())
            {
                NativeMethods.TryAddShieldToButton(btnOK);
            }

            var container = new CompositeDisposable();

            FormClosed += (sender, args) => container.Dispose();

            container.Add(
                Observable.FromEventPattern <EventArgs>(txtName, "TextChanged")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                btnOK.Enabled = !string.IsNullOrWhiteSpace(txtName.Text) &&
                                !string.IsNullOrWhiteSpace(txtPath.Text);
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnOK, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                if (!File.Exists(txtPath.Text))
                {
                    ShowMessage(
                        string.Format(
                            "There was an error while performing this operation.{0}{0}Details:{0}{0}Could not find file '{1}'.",
                            Environment.NewLine,
                            txtPath.Text),
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error,
                        MessageBoxDefaultButton.Button1);
                    return;
                }

                var p12File = DialogHelper.GetTempFileName();
                var p12pwd  = "test";
                try
                {
                    // TODO: check administrator permission.
                    var x509     = new X509Certificate2(txtPath.Text);
                    var filename = DialogHelper.GetPrivateKeyFile(x509.Subject);
                    if (!File.Exists(filename))
                    {
                        ShowMessage(
                            string.Format(
                                "There was an error while performing this operation.{0}{0}Details:{0}{0}Could not find private key for '{1}'.",
                                Environment.NewLine,
                                txtPath.Text),
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error,
                            MessageBoxDefaultButton.Button1);
                        return;
                    }

                    x509.PrivateKey   = PrivateKey.CreateFromFile(filename).RSA;
                    x509.FriendlyName = txtName.Text;
                    var raw           = x509.Export(X509ContentType.Pfx, p12pwd);
                    File.WriteAllBytes(p12File, raw);
                    Item = x509;
                }
                catch (Exception ex)
                {
                    ShowError(ex, string.Empty, false);
                    return;
                }

                Store = cbStore.SelectedIndex == 0 ? "Personal" : "WebHosting";

                try
                {
                    // add certificate
                    using (var process = new Process())
                    {
                        var start       = process.StartInfo;
                        start.Verb      = "runas";
                        start.FileName  = "cmd";
                        start.Arguments = string.Format("/c \"\"{4}\" /f:\"{0}\" /p:{1} /n:\"{2}\" /s:{3}\"",
                                                        p12File,
                                                        p12pwd,
                                                        txtName.Text,
                                                        cbStore.SelectedIndex == 0 ? "MY" : "WebHosting",
                                                        Path.Combine(Environment.CurrentDirectory, "certificateinstaller.exe"));
                        start.CreateNoWindow = true;
                        start.WindowStyle    = ProcessWindowStyle.Hidden;
                        process.Start();
                        process.WaitForExit();
                        File.Delete(p12File);
                        if (process.ExitCode == 0)
                        {
                            DialogResult = DialogResult.OK;
                        }
                        else
                        {
                            MessageBox.Show(process.ExitCode.ToString());
                        }
                    }
                }
                catch (Win32Exception ex)
                {
                    // elevation is cancelled.
                    if (ex.NativeErrorCode != Microsoft.Web.Administration.NativeMethods.ErrorCancelled)
                    {
                        Rollbar.Report(ex, ErrorLevel.Error, new Dictionary <string, object> {
                            { "native", ex.NativeErrorCode }
                        });
                        // throw;
                    }
                }
                catch (Exception ex)
                {
                    Rollbar.Report(ex, ErrorLevel.Error);
                }
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnBrowse, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                DialogHelper.ShowOpenFileDialog(txtPath, "*.cer|*.cer|*.*|*.*");
            }));

            container.Add(
                Observable.FromEventPattern <CancelEventArgs>(this, "HelpButtonClicked")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(EnvironmentVariableTarget =>
            {
                feature.ShowHelp();
            }));
        }
Пример #32
0
        private void MainWindow_Closing(object sender, CancelEventArgs e)
        {
            MessageBoxResult messageBoxResult = DialogHelper.ShowChangeMessageBox();

            e.Cancel = (messageBoxResult == MessageBoxResult.Cancel);
        }
Пример #33
0
        public ImportCertificateDialog(IServiceProvider serviceProvider, CertificatesFeature feature)
            : base(serviceProvider)
        {
            InitializeComponent();
            cbStore.SelectedIndex = 0;
            if (Environment.OSVersion.Version < Version.Parse("6.2"))
            {
                // IMPORTANT: WebHosting store is available since Windows 8.
                cbStore.Enabled = false;
            }

            if (!Helper.IsRunningOnMono())
            {
                JexusManager.NativeMethods.TryAddShieldToButton(btnOK);
            }

            var container = new CompositeDisposable();

            FormClosed += (sender, args) => container.Dispose();

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnBrowse, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                DialogHelper.ShowOpenFileDialog(txtFile, ".pfx|*.pfx|*.*|*.*", null);
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(txtFile, "TextChanged")
                .Sample(TimeSpan.FromSeconds(1))
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                btnOK.Enabled = !string.IsNullOrWhiteSpace(txtFile.Text);
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnOK, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                try
                {
                    // Load your certificate from file
                    Item        = new X509Certificate2(txtFile.Text, txtPassword.Text, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
                    Store       = cbStore.SelectedIndex == 0 ? "Personal" : "WebHosting";
                    var service = (IConfigurationService)GetService(typeof(IConfigurationService));
                    if (service.ServerManager.Mode == WorkingMode.Jexus)
                    {
                        var server = (JexusServerManager)service.Server;
                        // Public Key;
                        StringBuilder publicBuilder = new StringBuilder();
                        publicBuilder.AppendLine("-----BEGIN CERTIFICATE-----");
                        publicBuilder.AppendLine(Convert.ToBase64String(Item.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks));
                        publicBuilder.AppendLine("-----END CERTIFICATE-----");
                        var file = AsyncHelper.RunSync(() => server.SaveCertificateAsync(publicBuilder.ToString()));
                        server.SetCertificate(file);
                        // Private Key
                        RSACryptoServiceProvider rsa    = (RSACryptoServiceProvider)Item.PrivateKey;
                        MemoryStream memoryStream       = new MemoryStream();
                        TextWriter streamWriter         = new StreamWriter(memoryStream);
                        PemWriter pemWriter             = new PemWriter(streamWriter);
                        AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetRsaKeyPair(rsa);
                        pemWriter.WriteObject(keyPair.Private);
                        streamWriter.Flush();
                        string output     = Encoding.ASCII.GetString(memoryStream.GetBuffer()).Trim();
                        int indexOfFooter = output.IndexOf("-----END RSA PRIVATE KEY-----", StringComparison.Ordinal);
                        memoryStream.Close();
                        streamWriter.Close();
                        string key  = output.Substring(0, indexOfFooter + 29);
                        var keyFile = AsyncHelper.RunSync(() => server.SaveKeyAsync(key));
                        server.SetKeyFile(keyFile);
                        service.ServerManager.CommitChanges();
                    }
                    else
                    {
                        try
                        {
                            using (var process = new Process())
                            {
                                // add certificate
                                var start             = process.StartInfo;
                                start.Verb            = "runas";
                                start.UseShellExecute = true;
                                start.FileName        = "cmd";
                                start.Arguments       = $"/c \"\"{CertificateInstallerLocator.FileName}\" /f:\"{txtFile.Text}\" /p:{txtPassword.Text} /n:\"{Item.FriendlyName}\" /s:{(cbStore.SelectedIndex == 0 ? "MY" : "WebHosting")}\"";
                                start.CreateNoWindow  = true;
                                start.WindowStyle     = ProcessWindowStyle.Hidden;
                                process.Start();
                                process.WaitForExit();
                                if (process.ExitCode == 0)
                                {
                                    DialogResult = DialogResult.OK;
                                }
                                else
                                {
                                    MessageBox.Show(process.ExitCode.ToString());
                                }
                            }
                        }
                        catch (Win32Exception ex)
                        {
                            // elevation is cancelled.
                            if (ex.NativeErrorCode != NativeMethods.ErrorCancelled)
                            {
                                RollbarLocator.RollbarInstance.Error(ex, new Dictionary <string, object> {
                                    { "native", ex.NativeErrorCode }
                                });
                                // throw;
                            }
                        }
                        catch (Exception ex)
                        {
                            RollbarLocator.RollbarInstance.Error(ex);
                        }
                    }
                }
                catch (Exception ex)
                {
                    ShowError(ex, string.Empty, false);
                }
            }));

            container.Add(
                Observable.FromEventPattern <CancelEventArgs>(this, "HelpButtonClicked")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(EnvironmentVariableTarget =>
            {
                feature.ShowHelp();
            }));
        }
Пример #34
0
 public Task <MessageBoxResult> MessageBox(string message, MessageBoxButton buttons = MessageBoxButton.OK, MessageBoxImage image = MessageBoxImage.None, WindowOwner owner = WindowOwner.LastModal)
 {
     return(DialogHelper.MessageBox(Dispatcher, message, ApplicationName, buttons, image, owner));
 }
Пример #35
0
 private void BindingDialogHelpButtonClicked(object sender, CancelEventArgs e)
 {
     DialogHelper.ProcessStart("http://go.microsoft.com/fwlink/?LinkId=210531#Site_Bingings");
 }
Пример #36
0
 private void IdentityDialogHelpButtonClicked(object sender, System.ComponentModel.CancelEventArgs e)
 {
     DialogHelper.ProcessStart("http://go.microsoft.com/fwlink/?LinkId=210456#ApplicationPoolIdentity");
 }