Example #1
0
        public IndexesViewModel(ISonicCache cache)
        {
            LoadIndexesOperation = new LongRunningOperation();

            LoadIndexesAsync(cache);

            RefreshCommand = new RelayCommand(async () =>
                {
                    ArbitraryContainer.Default.Resolve<INavigationService>().ClearPageCache();

                    var x = new MusicFolders(cache);
                    await x.GetAsync(SourcePolicy.Refresh);

                    Indexes.StableMergeUpdate(x.Folders.First().Indexes);
                });

            DirectoryClickedCommand = new RelayCommand<MusicDirectory>(
                x => ArbitraryContainer.Default.Resolve<INavigationService>().Navigate(typeof(MusicDirectoryView), x));
        }
        public ConnectionViewModel(ConnectionModelProxy connection)
        {
            model = connection;

            if (connection != null && String.IsNullOrEmpty(connection.Name))
            {
                UnsavedChanges = true;
            }

            Owner           = connection.Context.Service;
            ConnectionTypes = new ObservableCollection <ConnectionTypeModelProxy>();
            Parameters      = new ObservableCollection <ConnectionViewParameter>();

            Task.Run(() =>
            {
                // We need to read the info from our backend again since we don't
                // get any property values when enumerating all connections
                try
                {
                    if (connection.ConnectionType != null)
                    {
                        connection = connection.Context.Service.GetConnectionDetails(connection);
                    }

                    var result = Owner.GetConnectionTypes();

                    var connectionTypeNameProp = default(PropertyInfo);
                    if (connection.ConnectionType != null)
                    {
                        connectionTypeNameProp = connection.ConnectionType.GetType().GetProperty("Name");
                    }
                    var connectionTypeName = string.Empty;
                    if (connectionTypeNameProp != null)
                    {
                        connectionTypeName = connectionTypeNameProp.GetValue(connection.ConnectionType).ToString();
                    }

                    Execute.OnUIThread(() =>
                    {
                        foreach (var type in result)
                        {
                            ConnectionTypes.Add(type);

                            if (type.Name.Equals(connectionTypeName, StringComparison.InvariantCultureIgnoreCase))
                            {
                                ConnectionType = type;
                            }
                        }

                        if (Owner is AzureService && connection.ConnectionType != null)
                        {
                            var fields = (connection.ConnectionFieldValues as List <Vendor.Azure.ConnectionFieldValue>);
                            if (fields.Count > 0)
                            {
                                Parameters.Clear();

                                foreach (var field in fields)
                                {
                                    var paramName = field.ConnectionFieldName;

                                    if (field.IsEncrypted)
                                    {
                                        paramName = field.ConnectionFieldName + " (encrypted)";
                                    }

                                    if (!field.IsOptional)
                                    {
                                        paramName += "*";
                                    }

                                    Parameters.Add(new ConnectionViewParameter
                                    {
                                        DisplayName = paramName,
                                        Name        = field.ConnectionFieldName,
                                        Value       = field.Value
                                    });
                                }
                            }
                        }
                        else if (Owner is SmaService && connection.ConnectionType != null)
                        {
                            var fields = (connection.ConnectionFieldValues as List <SMA.ConnectionFieldValue>);
                            if (fields.Count > 0)
                            {
                                Parameters.Clear();

                                foreach (var field in fields)
                                {
                                    var paramName = field.ConnectionFieldName;

                                    if (field.IsEncrypted)
                                    {
                                        paramName = field.ConnectionFieldName + " (encrypted)";
                                    }

                                    if (field.IsOptional != null && field.IsOptional.HasValue && !field.IsOptional.Value)
                                    {
                                        paramName += "*";
                                    }

                                    Parameters.Add(new ConnectionViewParameter
                                    {
                                        DisplayName = paramName,
                                        Name        = field.ConnectionFieldName,
                                        Value       = field.Value
                                    });
                                }
                            }
                        }

                        LongRunningOperation.Stop();
                    });
                }
                catch (ApplicationException ex)
                {
                    LongRunningOperation.Stop();
                    GlobalExceptionHandler.Show(ex);
                }
            });
        }
Example #3
0
        public TLSRequest TLSServerDecryptRequest(TLSEnvelope tlsEnvelope)
        {
            Guard.NotNull(tlsEnvelope);
            var ar = new TLSRequest();

            byte[] serverPrivateKey;             // static or dynamic
            if (tlsEnvelope.PrivateKeyHint == 0) // The client has used server's static public key to encrypt...
            {
                serverPrivateKey = this._serverPrivateKey;
            }
            // ... so we simple use the servers static private key
            else // tlsEnvelope.PrivateKeyHint is the number the server generated earlier
            {
                serverPrivateKey = GetServerDynamicPrivateKeyForUserByPrivateKeyHint(tlsEnvelope.PrivateKeyHint);
            }
            if (serverPrivateKey == null)
            {
                // we lost our dynamic private key b/c of a disk failure and we don't know who sent us what :-(
                return(null);
            }

            byte[] dynamicSharedSecret = this.ixdsCryptoService.CalculateAndHashSharedSecret(serverPrivateKey, tlsEnvelope.DynamicPublicKey);

            Debug.WriteLine($"{this.ServerId}: TLSDecrypt:  PrivateKeyHint: {tlsEnvelope.PrivateKeyHint}");

            // 'TLSAuthMode.Separate'
            byte[] symmetricKeyMaterial = ByteArrays.Concatenate(dynamicSharedSecret, new byte[32]); // no auth, we dont know who the user is
            // End 'TLSAuthMode.Separate'

            var lro             = new LongRunningOperation(progress => { }, () => { });
            var cipherV2        = XDSSecFormatter.DissectXDSSecBytes(tlsEnvelope.EncipheredPayload, lro.Context);
            var decryptResponse = this.ixdsCryptoService.BinaryDecrypt(cipherV2, new KeyMaterial64(symmetricKeyMaterial), lro.Context);

            if (!decryptResponse.IsSuccess)
            {
                throw new Exception(decryptResponse.Error);
            }

            byte[] tlsDecryptedRequest = decryptResponse.Result.GetBytes();

            // 'TLSAuthMode.Separate'
            var authSecretFromMessage = new byte[32];

            Buffer.BlockCopy(tlsDecryptedRequest, 0, authSecretFromMessage, 0, authSecretFromMessage.Length);

            // must be set even if the user is not authenticated for the case where a new identity is published right now.
            ar.UserId = Encoding.UTF8.GetString(tlsDecryptedRequest, 32, 10);
            // try authenticate
            var authSecret = GetAuthSecret(ar.UserId);

            if (authSecret != null)
            {
                if (ByteArrays.AreAllBytesEqual(authSecretFromMessage, authSecret))
                {
                    ar.IsAuthenticated = true;
                }
            }
            else
            {
                ar.IsAuthenticated = false;
            }

            var requestData = new byte[tlsDecryptedRequest.Length - 32 - 10];

            Buffer.BlockCopy(tlsDecryptedRequest, 32 + 10, requestData, 0, requestData.Length);
            ar.CommandData = requestData;
            // End 'TLSAuthMode.Separate'

            if (ar.IsAuthenticated)
            {
                SaveIncomingDynamicPublicKey(ar.UserId, tlsEnvelope.DynamicPublicKey, tlsEnvelope.DynamicPublicKeyId);
            }

            return(ar);
        }
Example #4
0
        public void Execute(object parameter)
        {
            var shell = IoC.Get <IShell>();

            if (parameter is ResourceContainer)
            {
                // This command has been called from the Environment Explorer tool
                var viewItem = (ResourceContainer)parameter;

                if (viewItem.Tag is IBackendContext)
                {
                    LongRunningOperation.Start();

                    shell.StatusBar.Items[0].Message = "Loading data from " + (viewItem.Tag as IBackendContext).Name + "...";
                    Task.Run(() => {
                        try
                        {
                            (viewItem.Tag as IBackendContext).Start();
                        }
                        catch (AggregateException ex)
                        {
                            Caliburn.Micro.Execute.OnUIThread(() =>
                            {
                                if (ex.InnerException != null)
                                {
                                    MessageBox.Show(ex.InnerException.Message, "Error");
                                }
                                else
                                {
                                    MessageBox.Show(ex.Message, "Error");
                                }

                                LongRunningOperation.Stop();
                            });
                        }
                    });

                    return;
                }

                if (!(viewItem.Tag is ModelProxyBase))
                {
                    return;
                }

                LongRunningOperation.Start();
                shell.StatusBar.Items[0].Message = "Loading " + viewItem.Title + "...";

                Task.Run(delegate()
                {
                    var viewModel = (ModelProxyBase)viewItem.Tag;

                    if (viewItem.Tag is RunbookModelProxy)
                    {
                        shell.OpenDocument(viewModel.GetViewModel <RunbookViewModel>());
                    }
                    else if (viewItem.Tag is VariableModelProxy)
                    {
                        shell.OpenDocument(viewModel.GetViewModel <VariableViewModel>());
                    }
                    else if (viewItem.Tag is CredentialModelProxy)
                    {
                        shell.OpenDocument(viewModel.GetViewModel <CredentialViewModel>());
                    }
                    else if (viewItem.Tag is ScheduleModelProxy)
                    {
                        shell.OpenDocument(viewModel.GetViewModel <ScheduleViewModel>());
                    }
                    else if (viewItem.Tag is ConnectionModelProxy)
                    {
                        shell.OpenDocument(viewModel.GetViewModel <ConnectionViewModel>());
                    }

                    shell.StatusBar.Items[0].Message = "";

                    CommandManager.InvalidateRequerySuggested();
                });
            }
            else if (parameter is JobModelProxy)
            {
                // This command has been called from our Job History view
                var jobProxy = (JobModelProxy)parameter;

                shell.OpenDocument(new ExecutionResultViewModel(jobProxy.BoundRunbookViewModel, jobProxy.JobID, false));
            }
        }
Example #5
0
        CipherV2 EncryptCommon(KeyMaterial64 keyMaterial64, RoundsExponent roundsExponent, LongRunningOperationContext context,
                               Compressed compressed)
        {
            if (context == null)
            {
                context = new LongRunningOperation(progress => { }, () => { }).Context;
            }

            if (this._log)
            {
                Debug.WriteLine("KeyMaterial64:");
                Debug.WriteLine(keyMaterial64.GetBytes().ToHexView(false));
            }

            if (this._log)
            {
                Debug.WriteLine("Compressed:");
                Debug.WriteLine(compressed.GetBytes().ToHexView(false));
            }

            PaddedData paddedData = this._internal.ApplyRandomPadding(compressed);

            if (this._log)
            {
                Debug.WriteLine("PaddedData:");
                Debug.WriteLine(paddedData.GetBytes().ToHexView(false));

                Debug.WriteLine("PlainTextPadding:");
                Debug.WriteLine(paddedData.PlaintextPadding);
            }

            IV16 iv = new IV16(this._platform.GenerateRandomBytes(16));

            if (this._log)
            {
                Debug.WriteLine("IV16:");
                Debug.WriteLine(iv.GetBytes().ToHexView(false));
            }

            InputDerivedKey32 inputDerivedKey = roundsExponent.Value == RoundsExponent.DontMakeRounds
                ? CreateDerivedKeyWithSHA256(iv, keyMaterial64)
                : CreatePasswordDerivedKeyWithBCrypt(iv, keyMaterial64, roundsExponent, context);

            if (this._log)
            {
                Debug.WriteLine("InputDerivedKey32:");
                Debug.WriteLine(inputDerivedKey.GetBytes().ToHexView(false));
            }

            RandomKey32 randomKey = new RandomKey32(this._platform.GenerateRandomBytes(32));

            if (this._log)
            {
                Debug.WriteLine("RandomKey32:");
                Debug.WriteLine(randomKey.GetBytes().ToHexView(false));
            }

            XDSSecAPIInternal.IVCache ivCache = roundsExponent.Value == RoundsExponent.DontMakeRounds
                ? null
                : this._internal.CreateIVTable(iv, roundsExponent.Value);

            var cipherV2 = new CipherV2 {
                RoundsExponent = roundsExponent, IV16 = iv
            };

            this._internal.AESEncryptRandomKeyWithInputDerivedKey(inputDerivedKey, randomKey, cipherV2, ivCache, context);
            if (this._log)
            {
                Debug.WriteLine("RandomKeyCipher32:");
                Debug.WriteLine(cipherV2.RandomKeyCipher32.GetBytes().ToHexView(false));
            }

            this._internal.AESEncryptMessageWithRandomKey(paddedData, randomKey, cipherV2, ivCache, context);
            if (this._log)
            {
                Debug.WriteLine("MessageCipher:");
                Debug.WriteLine(cipherV2.MessageCipher.GetBytes().ToHexView(false));
            }

            MAC16 mac = CreateMAC(cipherV2, context);

            if (this._log)
            {
                Debug.WriteLine("MAC16:");
                Debug.WriteLine(mac.GetBytes().ToHexView(false));
            }

            this._internal.AESEncryptMACWithRandomKey(cipherV2, mac, randomKey, ivCache, context);
            if (this._log)
            {
                Debug.WriteLine("MACCipher16:");
                Debug.WriteLine(cipherV2.MACCipher16.GetBytes().ToHexView(false));
            }
            return(cipherV2);
        }
Example #6
0
        public async Task <TLSRequest> DecryptRequest(TLSEnvelope tlsEnvelope)
        {
            Guard.NotNull(tlsEnvelope);
            await this._publicMemberLock.WaitAsync();

            try
            {
                var ar = new TLSRequest();

                byte[] clientDynamicPrivateKey;
                this._server.DynamicPrivateDecryptionKeys.TryGetValue(tlsEnvelope.PrivateKeyHint, out clientDynamicPrivateKey);
                if (clientDynamicPrivateKey == null)
                {
                    throw new Exception(
                              "This should rarely happen. It means, the server has hinted me to private Key I no longer have.");
                }

                RemovePreviousKeys(tlsEnvelope.PrivateKeyHint);

                var dynamicSharedSecret = this._visualCrypt2Service.CalculateAndHashSharedSecret(clientDynamicPrivateKey,
                                                                                                 tlsEnvelope.DynamicPublicKey);
                Debug.WriteLine($"{this.MyId}: TLSDecrypt:  PrivateKeyHint: {tlsEnvelope.PrivateKeyHint}");

                // TLSAuthMode Combined
                byte[] authSecretBytes      = this._server.AuthSecret;
                var    symmetricKeyMaterial = ByteArrays.Concatenate(dynamicSharedSecret, authSecretBytes);
                // End TLSAuthMode Combined

                // TODO: make LRO optional!
                var lro             = new LongRunningOperation(progress => { }, () => { });
                var cipherV2        = VisualCrypt2Formatter.DissectVisualCryptBytes(tlsEnvelope.EncipheredPayload, lro.Context);
                var decryptResponse = this._visualCrypt2Service.BinaryDecrypt(cipherV2,
                                                                              new KeyMaterial64(symmetricKeyMaterial), lro.Context);
                var isIncomingKeyUnusable = false;
                if (!decryptResponse.IsSuccess)
                {
                    // has the server just lost the dynamic keys?
                    this._server.DynamicPrivateDecryptionKeys.TryGetValue(tlsEnvelope.PrivateKeyHint,
                                                                          out clientDynamicPrivateKey);
                    if (clientDynamicPrivateKey == null)
                    {
                        throw new Exception(
                                  "This should rarely happen. It means, the server has hinted me to private Key I no longer have.");
                    }
                    dynamicSharedSecret = this._visualCrypt2Service.CalculateAndHashSharedSecret(clientDynamicPrivateKey,
                                                                                                 this._server.StaticPublicKey);
                    authSecretBytes      = new byte[32];
                    symmetricKeyMaterial = ByteArrays.Concatenate(dynamicSharedSecret, authSecretBytes);
                    var decryptResponse2 = this._visualCrypt2Service.BinaryDecrypt(cipherV2,
                                                                                   new KeyMaterial64(symmetricKeyMaterial), lro.Context);
                    if (!decryptResponse2.IsSuccess)
                    {
                        throw new Exception("Decryption failed in all ways!");
                    }
                    decryptResponse = decryptResponse2;
                    Debug.WriteLine("Decryption succeded in Anonymous mode.");
                    DoReset();
                    isIncomingKeyUnusable = true;
                }

                byte[] tlsDecryptedRequest = decryptResponse.Result.GetBytes();

                ar.IsAuthenticated = true;
                ar.UserId          = this._server.UserId;
                ar.CommandData     = tlsDecryptedRequest;

                if (!isIncomingKeyUnusable)
                {
                    Guard.NotNull(tlsEnvelope.DynamicPublicKey);
                    if (tlsEnvelope.DynamicPublicKeyId == 0)
                    {
                        throw new ArgumentException("A dynamic public key must never have an ID of 0.");
                    }
                    this._server.LatestDynamicPublicKey   = tlsEnvelope.DynamicPublicKey;
                    this._server.LatestDynamicPublicKeyId = tlsEnvelope.DynamicPublicKeyId;
                }
                return(ar);
            }
            finally
            {
                this._publicMemberLock.Release();
            }
        }
Example #7
0
        private void SubscribeToJob()
        {
            var job = default(JobModelProxy);

            Task.Run(() =>
            {
                try
                {
                    //AsyncExecution.Run(ThreadPriority.Normal, () =>
                    // Wait for the job ID to be set by our backend service
                    while (_jobId == Guid.Empty)
                    {
                        if (_runbookViewModel.Runbook.JobID != null)
                        {
                            _jobId = _runbookViewModel.Runbook.JobID;
                        }

                        Thread.Sleep(1 * 1000);
                    }

                    if (_runbookViewModel.Runbook.JobID != null && _runbookViewModel.Runbook.JobID != Guid.Empty)
                    {
                        job = _backendService.GetJobDetails(_runbookViewModel.Runbook);
                    }
                    else if (_jobId != Guid.Empty)
                    {
                        job = _backendService.GetJobDetails(_jobId);
                    }

                    if (job != null)
                    {
                        Execute.OnUIThread(() =>
                        {
                            foreach (var entry in job.Result)
                            {
                                Result.Add(entry);
                            }

                            JobStatus = job.JobStatus;
                            NotifyOfPropertyChange(() => DisplayName);

                            _propertyInfo                  = new ExecutionResultPropertyInfo();
                            _propertyInfo.JobID            = (_jobId == null) ? Guid.Empty : (Guid)_jobId;
                            _propertyInfo.RunbookID        = (_runbookViewModel != null) ? ((RunbookModelProxy)_runbookViewModel.Model).RunbookID : Guid.Empty;
                            _propertyInfo.RunbookName      = (_runbookViewModel != null) ? ((RunbookModelProxy)_runbookViewModel.Model).RunbookName : "Unknown";
                            _propertyInfo.JobStatus        = job.JobStatus;
                            _propertyInfo.StartTime        = job.StartTime;
                            _propertyInfo.EndTime          = job.EndTime;
                            _propertyInfo.CreationTime     = job.CreationTime;
                            _propertyInfo.LastModifiedTime = job.LastModifiedTime;
                            _propertyInfo.ErrorCount       = job.ErrorCount;
                            _propertyInfo.WarningCount     = job.WarningCount;
                            _propertyInfo.Exception        = job.JobException;

                            if (!string.IsNullOrEmpty(job.JobException))
                            {
                                _output.AppendLine("Error when executing runbook:");
                                _output.AppendLine(job.JobException);
                                _output.AppendLine(" ");
                            }

                            _inspectorTool.SelectedObject = _propertyInfo;
                        });
                    }

                    bool hasDisplayedException = false;
                    while (!_completedExecutionStatus.Contains(job.JobStatus))
                    {
                        job = _backendService.GetJobDetails(_runbookViewModel.Runbook);

                        if (job != null)
                        {
                            Execute.OnUIThread(() =>
                            {
                                JobStatus = job.JobStatus;
                                NotifyOfPropertyChange(() => DisplayName);

                                _propertyInfo.StartTime    = job.StartTime;
                                _propertyInfo.EndTime      = job.EndTime;
                                _propertyInfo.ErrorCount   = job.ErrorCount;
                                _propertyInfo.WarningCount = job.WarningCount;
                                _propertyInfo.JobStatus    = job.JobStatus;
                                _propertyInfo.Exception    = job.JobException;

                                if (!String.IsNullOrEmpty(job.JobException) && !hasDisplayedException)
                                {
                                    _output.AppendLine("Error when executing runbook:");
                                    _output.AppendLine(job.JobException);
                                    _output.AppendLine(" ");

                                    hasDisplayedException = true;
                                }

                                _inspectorTool.SelectedObject = null;
                                _inspectorTool.SelectedObject = _propertyInfo;

                                foreach (var entry in job.Result)
                                {
                                    Result.Add(entry);
                                }
                            });
                        }

                        Thread.Sleep(5 * 1000);
                    }

                    // The job is completed
                    _runbookViewModel.Runbook.JobID = Guid.Empty;
                    LongRunningOperation.Stop();
                }
                catch (Exception ex)
                {
                    GlobalExceptionHandler.Show(ex);
                    _runbookViewModel.Runbook.JobID = Guid.Empty;

                    job.JobStatus = "Failed";
                }
            });

            if (job != null)
            {
                var output = IoC.Get <IOutput>();
                output.AppendLine("Job executed with status: " + job.JobStatus);
            }
        }
        public override void Create()
        {
            this.mainWindow.RemoveAll();

            var frameViewInfo = new FrameView("Info")
            {
                X      = 0,
                Y      = 0,
                Height = Dim.Percent(100),
                Width  = Dim.Percent(25)
            };
            var labelInfoText = new Label(1, 1, "Now, please choose your device vault passphrase - it will be used to encrypt all your locally stored data.");

            labelInfoText.LayoutStyle = LayoutStyle.Computed;
            frameViewInfo.Add(labelInfoText);
            this.mainWindow.Add(frameViewInfo);

            var labelPassphrase = new Label("Passphrase:")
            {
                X = Pos.Right(frameViewInfo) + 1,
                Y = 1,
            };

            this.mainWindow.Add(labelPassphrase);
            var textViewPassphrase = new TextField("")
            {
                Secret = true,
                X      = Pos.Right(frameViewInfo) + 1,
                Y      = Pos.Bottom(labelPassphrase),
                Width  = Dim.Fill()
            };

            this.mainWindow.Add(textViewPassphrase);

            var buttonAcceptPassphrase = new Button("Set passphrase", true)
            {
                X = Pos.Right(frameViewInfo) + 1,
                Y = Pos.Bottom(textViewPassphrase) + 1,
            };

            buttonAcceptPassphrase.Clicked = async() =>
            {
                if (string.IsNullOrWhiteSpace(textViewPassphrase.Text.ToString()))
                {
                    ErrorBox.Show("The passphrase must not be empty");
                }
                else
                {
                    this.onboardingViewModel.ValidatedMasterPassphrase = textViewPassphrase.Text.ToString();
                    var quality = this.deviceVaultService.GetPassphraseQuality(this.onboardingViewModel
                                                                               .ValidatedMasterPassphrase);
                    var labelPassphraseAccepted =
                        new Label(
                            $"Your passphrase was set! Passphrase Quality: {this.deviceVaultService.GetPassphraseQualityText(quality)}.")
                    {
                        X = Pos.Right(frameViewInfo) + 1,
                        Y = Pos.Bottom(textViewPassphrase) + 1,
                    };
                    this.mainWindow.Remove(buttonAcceptPassphrase);
                    this.mainWindow.Add(labelPassphraseAccepted);
                    var progressBar = new ProgressBar
                    {
                        X           = Pos.Right(frameViewInfo) + 1,
                        Y           = Pos.Bottom(labelPassphraseAccepted) + 1,
                        Width       = Dim.Fill(),
                        Height      = 1,
                        Fraction    = 0.0f,
                        ColorScheme = Colors.Error
                    };
                    this.mainWindow.Add(progressBar);
                    var labelProgressText =
                        new Label("                                                                            ")
                    {
                        X     = Pos.Right(frameViewInfo) + 1,
                        Y     = Pos.Bottom(progressBar) + 1,
                        Width = Dim.Fill()
                    };
                    this.mainWindow.Add(labelProgressText);
                    var op = new LongRunningOperation(encryptionProgress =>
                    {
                        progressBar.Fraction   = encryptionProgress.Percent / 100f;
                        labelProgressText.Text =
                            $"{encryptionProgress.Percent} % {MockLocalization.ReplaceKey(encryptionProgress.Message)}";
                    }, () => { });

                    try
                    {
                        await this.onboardingViewModel.CommitAllAsync(op.Context);

                        labelProgressText.Text = "Cryptographic operations complete!";

                        this.mainWindow.Add(
                            new Label("That's it! You can now start chatting with your new encrypted identity!")
                        {
                            X     = Pos.Right(frameViewInfo) + 1,
                            Y     = Pos.Bottom(labelProgressText) + 1,
                            Width = Dim.Fill()
                        });



                        var buttonStartChat = new Button("Start chat")
                        {
                            X       = Pos.Right(frameViewInfo) + 1,
                            Y       = Pos.Bottom(labelProgressText) + 3,
                            Clicked = () =>
                            {
                                App.IsOnboardingRequired = false;
                                NavigationService.ShowLockScreen();
                            }
                        };

                        this.mainWindow.Add(buttonStartChat);
                        buttonStartChat.SetFocus();
                    }
                    catch (Exception e)
                    {
                        ErrorBox.Show($"Could not commit profile: {e}");
                    }
                }
            };

            this.mainWindow.Add(buttonAcceptPassphrase);


            textViewPassphrase.SetFocus();
        }
Example #9
0
        public static void Write(CodeWriter writer, LongRunningOperation operation)
        {
            var responseVariable = "response";

            void WriteResultFunction(bool async)
            {
                if (operation.ResultSerialization != null)
                {
                    writer.WriteDeserializationForMethods(
                        operation.ResultSerialization,
                        async: async,
                        (w, v) => w.Line($"return {v};"),
                        responseVariable);
                }
                else
                {
                    if (async)
                    {
                        writer.Line($"return await new {typeof(ValueTask<Response>)}({responseVariable}).ConfigureAwait(false);");
                    }
                    else
                    {
                        writer.Line($"return {responseVariable};");
                    }
                }
            }

            var cs         = operation.Type;
            var @namespace = cs.Namespace;

            using (writer.Namespace(@namespace))
            {
                writer.WriteXmlDocumentationSummary(operation.Description);
                var interfaceType         = new CSharpType(typeof(IOperationSource <>), operation.ResultType);
                var baseType              = new CSharpType(typeof(Operation <>), operation.ResultType);
                var waitForCompletionType = new CSharpType(typeof(ValueTask <>), new CSharpType(typeof(Response <>), operation.ResultType));
                var helperType            = new CSharpType(typeof(ArmOperationHelpers <>), operation.ResultType);

                using (writer.Scope($"{operation.Declaration.Accessibility} partial class {cs.Name}: {baseType}, {interfaceType}"))
                {
                    writer.Line($"private readonly {helperType} _operation;");

                    using (writer.Scope($"internal {cs.Name}({typeof(ClientDiagnostics)} clientDiagnostics, {typeof(HttpPipeline)} pipeline, {typeof(Request)} request, {typeof(Response)} response)"))
                    {
                        writer.Line($"_operation = new {helperType}(this, clientDiagnostics, pipeline, request, response, {typeof(OperationFinalStateVia)}.{operation.FinalStateVia}, {operation.Diagnostics.ScopeName:L});");
                    }

                    writer.WriteXmlDocumentationInheritDoc();
                    writer.Line($"public override string Id => _operation.Id;");
                    writer.Line();

                    writer.WriteXmlDocumentationInheritDoc();
                    writer.Line($"public override {operation.ResultType} Value => _operation.Value;");
                    writer.Line();

                    writer.WriteXmlDocumentationInheritDoc();
                    writer.Line($"public override bool HasCompleted => _operation.HasCompleted;");
                    writer.Line();

                    writer.WriteXmlDocumentationInheritDoc();
                    writer.Line($"public override bool HasValue => _operation.HasValue;");
                    writer.Line();

                    writer.WriteXmlDocumentationInheritDoc();
                    writer.Line($"public override {typeof(Response)} GetRawResponse() => _operation.GetRawResponse();");
                    writer.Line();

                    writer.WriteXmlDocumentationInheritDoc();
                    writer.Line($"public override {typeof(Response)} UpdateStatus({typeof(CancellationToken)} cancellationToken = default) => _operation.UpdateStatus(cancellationToken);");
                    writer.Line();

                    writer.WriteXmlDocumentationInheritDoc();
                    writer.Line($"public override {typeof(ValueTask<Response>)} UpdateStatusAsync({typeof(CancellationToken)} cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken);");
                    writer.Line();

                    writer.WriteXmlDocumentationInheritDoc();
                    writer.Line($"public override {waitForCompletionType} WaitForCompletionAsync({typeof(CancellationToken)} cancellationToken = default) => _operation.WaitForCompletionAsync(cancellationToken);");
                    writer.Line();

                    writer.WriteXmlDocumentationInheritDoc();
                    writer.Line($"public override {waitForCompletionType} WaitForCompletionAsync({typeof(TimeSpan)} pollingInterval, {typeof(CancellationToken)} cancellationToken = default) => _operation.WaitForCompletionAsync(pollingInterval, cancellationToken);");
                    writer.Line();

                    using (writer.Scope($"{operation.ResultType} {interfaceType}.CreateResult({typeof(Response)} {responseVariable:D}, {typeof(CancellationToken)} cancellationToken)"))
                    {
                        WriteResultFunction(false);
                    }
                    writer.Line();

                    using (writer.Scope($"async {new CSharpType(typeof(ValueTask<>), operation.ResultType)} {interfaceType}.CreateResultAsync({typeof(Response)} {responseVariable:D}, {typeof(CancellationToken)} cancellationToken)"))
                    {
                        WriteResultFunction(true);
                    }
                }
            }
        }
Example #10
0
        public void Execute(object parameter)
        {
            if (parameter == null)
            {
                return;
            }

            if (!(parameter is ResourceContainer))
            {
                return;
            }

            if (((ResourceContainer)parameter).Tag == null)
            {
                return;
            }

            var backendService      = ((parameter as ResourceContainer).Tag as ModelProxyBase).Context.Service;
            var environmentExplorer = IoC.Get <EnvironmentExplorerViewModel>();

            if (MessageBox.Show("Are you sure you want to delete the object? This cannot be reverted.", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                LongRunningOperation.Start();
                var item = (ModelProxyBase)(parameter as ResourceContainer).Tag;

                // Make sure that we remove the object from the context as well
                if (item is RunbookModelProxy)
                {
                    backendService.Context.Runbooks.Remove(parameter as ResourceContainer);
                }
                else if (item is ConnectionModelProxy)
                {
                    backendService.Context.Connections.Remove(parameter as ResourceContainer);
                }
                else if (item is ScheduleModelProxy)
                {
                    backendService.Context.Schedules.Remove(parameter as ResourceContainer);
                }
                else if (item is VariableModelProxy)
                {
                    backendService.Context.Variables.Remove(parameter as ResourceContainer);
                }
                else if (item is ModuleModelProxy)
                {
                    backendService.Context.Modules.Remove(parameter as ResourceContainer);
                }
                else if (item is CredentialModelProxy)
                {
                    backendService.Context.Credentials.Remove(parameter as ResourceContainer);
                }

                try {
                    if (backendService.Delete(item))
                    {
                        environmentExplorer.Delete(parameter as ResourceContainer);
                    }
                }
                catch (ApplicationException ex)
                {
                    GlobalExceptionHandler.Show(ex);
                }

                LongRunningOperation.Stop();
            }
        }
Example #11
0
        public async Task <int> SubscribeForNotifications(string operationId)
        {
            await Groups.AddToGroupAsync(Context.ConnectionId, operationId);

            return(LongRunningOperation.GetCurrentProgress(operationId));
        }
Example #12
0
 public Task CancelProcessing(string operationId)
 {
     Clients.Group(operationId).SetMessage("Cancellation requested...");
     LongRunningOperation.CancelProcessing(operationId);
     return(Task.CompletedTask);
 }