public NewOrEditConnectionDialog(AutomationConnection connection, ISet<ConnectionType> connectionTypes)
        {
            InitializeComponent();

            _connectionTypes = connectionTypes;

            // populate connection types drop down
            foreach (var connectionType in connectionTypes)
            {
                connectionTypeComboBox.Items.Add(connectionType.Name);
            }

            if (connection != null)
            {
                //UsernameTextbox.Text = cred.getUsername();

                this.Title = "Edit Connection Asset";
                connectionTypeComboBox.SelectedValue = connection.ConnectionType;
                AddConnectionFieldInputs(connection.ConnectionType, connection);
            }
            else
            {
                this.Title = "New Connection Asset";
                connectionTypeComboBox.SelectedIndex = 0;
            }
        }
 public ConnectionJson(AutomationConnection connection)
     : base(connection)
 {
     this.ValueFields = connection.getFields();
 }
        private async Task createOrUpdateConnectionAsset(string connectionAssetName, AutomationConnection connectionToEdit, bool newAsset = false)
        {
            if (newAsset)
            {
                // Check if connection already exists before creating one.
                var asset = await AutomationAssetManager.GetAsset(connectionAssetName, Constants.AssetType.Connection, iseClient.currWorkspace, iseClient.automationManagementClient, iseClient.accountResourceGroups[iseClient.currAccount].Name, iseClient.currAccount.Name, getEncryptionCertificateThumbprint(), connectionTypes);
                if (asset != null) throw new Exception("Connection with that name already exists");
            }

            var dialog = new NewOrEditConnectionDialog(connectionToEdit, connectionTypes);

            if (dialog.ShowDialog() == true)
            {
                var assetsToSave = new List<AutomationAsset>();

                var newConnection = new AutomationConnection(connectionAssetName, dialog.connectionFields, dialog.connectionType);
                assetsToSave.Add(newConnection);

                try
                {
                    AutomationAssetManager.SaveLocally(iseClient.currWorkspace, assetsToSave, getEncryptionCertificateThumbprint(), connectionTypes);
                    await refreshAssets();
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
 public ConnectionJson(AutomationConnection connection)
     : base(connection)
 {
     this.ValueFields    = connection.getFields();
     this.ConnectionType = connection.ConnectionType;
 }
        private void AddConnectionFieldInputs(string connectionTypeName, AutomationConnection startingConnection)
        {
            IDictionary<string, FieldDefinition> connectionFieldDefinitions = new Dictionary<string, FieldDefinition>();
            foreach (var connectionType in _connectionTypes)
            {
                if (connectionType.Name.Equals(connectionTypeName))
                {
                    connectionFieldDefinitions = connectionType.Properties.FieldDefinitions;
                }
            }
            
            /* Remove old added fields */
            if (ParametersGrid.RowDefinitions.Count > 2)
            {
                ParametersGrid.RowDefinitions.RemoveRange(1, ParametersGrid.RowDefinitions.Count - 2);


                var i = 0;
                var toRemove = new HashSet<UIElement>();
                foreach (UIElement element in ParametersGrid.Children)
                {
                    if(i > 1 && (!element.GetType().Name.Equals("WrapPanel")))
                    {
                        // removes everything that is not the connection type selector at the top or the ok / cancel button in the WrapPanel at the bottom
                        toRemove.Add(element);
                    }   
 
                    i++;
                }

                foreach (UIElement removeElement in toRemove)
                {
                    ParametersGrid.Children.Remove(removeElement);
                }
            }

            /* Update the UI Grid to fit everything */
            for (int i = 0; i < connectionFieldDefinitions.Count * 2; i++)
            {
                RowDefinition rowDef = new RowDefinition();
                rowDef.Height = System.Windows.GridLength.Auto;
                ParametersGrid.RowDefinitions.Add(rowDef);
            }
            Grid.SetRow(ButtonsPanel, ParametersGrid.RowDefinitions.Count - 1);

            /* Fill the UI with parameter data */
            int count = 0;
            foreach (string paramName in connectionFieldDefinitions.Keys)
            {
                /* Parameter Name and Type */
                Label parameterNameLabel = new Label();
                parameterNameLabel.Content = paramName;

                Label parameterTypeLabel = new Label();
                parameterTypeLabel.Content = "(" + connectionFieldDefinitions[paramName].Type + ")\t";
                if (!connectionFieldDefinitions[paramName].IsOptional)
                {
                    parameterTypeLabel.Content += "[REQUIRED]";
                }
                else
                {
                    parameterTypeLabel.Content += "[OPTIONAL]";
                }

                Grid.SetRow(parameterNameLabel, 1 + count * 2);
                Grid.SetRow(parameterTypeLabel, 1 + count * 2);
                Grid.SetColumn(parameterNameLabel, 0);
                Grid.SetColumn(parameterTypeLabel, 1);

                /* Input field */
                Control parameterValueBox = null;
                Object paramValue = null;

                // Set previous value for this parameter if available
                if (startingConnection != null && startingConnection.ConnectionType.Equals(connectionTypeComboBox.SelectedValue))
                {
                    paramValue = startingConnection.getFields()[paramName];
                }
               
                if (
                    connectionFieldDefinitions[paramName].Type.Equals(Constants.ConnectionTypeFieldType.String) || 
                    connectionFieldDefinitions[paramName].Type.Equals(Constants.ConnectionTypeFieldType.Int)
                )
                {
                    if (connectionFieldDefinitions[paramName].IsEncrypted)
                    {
                        parameterValueBox = new PasswordBox();
                        if(paramValue != null)
                        {
                            ((PasswordBox)parameterValueBox).Password = paramValue.ToString();
                        }
                    }
                    else
                    {
                        parameterValueBox = new TextBox();
                        if (paramValue != null)
                        {
                            ((TextBox)parameterValueBox).Text = paramValue.ToString();
                        }
                    }
                }
                else if (connectionFieldDefinitions[paramName].Type.Equals(Constants.ConnectionTypeFieldType.Boolean))
                {
                    parameterValueBox = new ComboBox();
                    ((ComboBox)parameterValueBox).Items.Add("True");
                    ((ComboBox)parameterValueBox).Items.Add("False");

                    if (paramValue != null)
                    {
                        try
                        {
                            if ((bool)paramValue == true)
                            {
                                ((ComboBox)parameterValueBox).SelectedValue = "True";
                            }
                            else
                            {
                                ((ComboBox)parameterValueBox).SelectedValue = "False";
                            }
                        }
                        catch
                        {
                            // value is not a bool, even though connection type schema says it should be
                        }
                    }
                }

                parameterValueBox.Name = paramName;

                parameterValueBox.MinWidth = 200;
                parameterValueBox.Margin = new System.Windows.Thickness(0, 5, 5, 5);
                Grid.SetColumn(parameterValueBox, 0);
                Grid.SetRow(parameterValueBox, 1 + count * 2 + 1);
                Grid.SetColumnSpan(parameterValueBox, 2);
                
                /* Add to Grid */
                ParametersGrid.Children.Add(parameterNameLabel);
                ParametersGrid.Children.Add(parameterTypeLabel);
                ParametersGrid.Children.Add(parameterValueBox);
                count ++;
            }

            // Set focus to first parameter textbox
            if (count > 0) ParametersGrid.Children[3].Focus();
        }
        /// <summary>
        /// Returns if the asset exists locally or in the cloud
        /// </summary>
        /// <param name="assetName"></param>
        /// <param name="assetType"></param>
        /// <param name="localWorkspacePath"></param>
        /// <param name="automationApi"></param>
        /// <param name="resourceGroupName"></param>
        /// <param name="automationAccountName"></param>
        /// <param name="encryptionCertThumbprint"></param>
        /// <returns>null if the asset does not exist or else returns the asset</returns>
        public static async Task <AutomationAsset> GetAsset(String assetName, String assetType, String localWorkspacePath, AutomationManagementClient automationApi, string resourceGroupName, string automationAccountName, string encryptionCertThumbprint, ICollection <ConnectionType> connectionTypes)
        {
            AutomationAsset automationAsset = null;

            // Get local assets
            LocalAssets localAssets = LocalAssetsStore.Get(localWorkspacePath, encryptionCertThumbprint, connectionTypes);

            // Search for variables
            CancellationTokenSource cts = new CancellationTokenSource();

            cts.CancelAfter(TIMEOUT_MS);
            if (assetType == Constants.AssetType.Variable)
            {
                // Check local asset store first
                var localVariable = localAssets.Variables.Find(asset => asset.Name == assetName);
                if (localVariable != null)
                {
                    automationAsset = new AutomationVariable(localVariable);
                }
                else
                {
                    try
                    {
                        // Check cloud. Catch exception if it doesn't exist
                        VariableGetResponse cloudVariable = await automationApi.Variables.GetAsync(resourceGroupName, automationAccountName, assetName, cts.Token);

                        automationAsset = new AutomationVariable(cloudVariable.Variable);
                    }
                    catch (Exception e)
                    {
                        // If the exception is not found, don't throw new exception as this is expected
                        if (e.HResult != -2146233088)
                        {
                            throw e;
                        }
                    }
                }
            }
            // Search for credentials
            else if (assetType == Constants.AssetType.Credential)
            {
                // Check local asset store first
                var localCredential = localAssets.PSCredentials.Find(asset => asset.Name == assetName);
                if (localCredential != null)
                {
                    automationAsset = new AutomationCredential(localCredential);
                }
                else
                {
                    try
                    {
                        // Check cloud. Catch execption if it doesn't exist
                        CredentialGetResponse cloudVariable = await automationApi.PsCredentials.GetAsync(resourceGroupName, automationAccountName, assetName, cts.Token);

                        automationAsset = new AutomationCredential(cloudVariable.Credential);
                    }
                    catch (Exception e)
                    {
                        // If the exception is not found, don't throw new exception as this is expected
                        if (e.HResult != -2146233088)
                        {
                            throw e;
                        }
                    }
                }
            }
            // Search for connections
            else if (assetType == Constants.AssetType.Connection)
            {
                // Check local asset store first
                var localConnection = localAssets.Connections.Find(asset => asset.Name == assetName);
                if (localConnection != null)
                {
                    automationAsset = new AutomationConnection(localConnection);
                }
                else
                {
                    try
                    {
                        // Check cloud. Catch exception if it doesn't exist
                        ConnectionGetResponse cloudConnection = await automationApi.Connections.GetAsync(resourceGroupName, automationAccountName, assetName, cts.Token);

                        cts = new CancellationTokenSource();
                        cts.CancelAfter(TIMEOUT_MS);
                        ConnectionTypeGetResponse connectionType = await automationApi.ConnectionTypes.GetAsync(resourceGroupName, automationAccountName,
                                                                                                                cloudConnection.Connection.Properties.ConnectionType.Name, cts.Token);

                        automationAsset = new AutomationConnection(cloudConnection.Connection, connectionType.ConnectionType);
                    }
                    catch (Exception e)
                    {
                        // If the exception is not found, don't throw new exception as this is expected
                        if (e.HResult != -2146233088)
                        {
                            throw e;
                        }
                    }
                }
            }
            // Search for certificates
            else if (assetType == Constants.AssetType.Certificate)
            {
                // Check local asset store first
                var localCertificate = localAssets.Certificate.Find(asset => asset.Name == assetName);
                if (localCertificate != null)
                {
                    automationAsset = new AutomationCertificate(localCertificate);
                }
                else
                {
                    try
                    {
                        // Check cloud. Catch execption if it doesn't exist
                        CertificateGetResponse cloudCertificate = await automationApi.Certificates.GetAsync(resourceGroupName, automationAccountName, assetName, cts.Token);

                        automationAsset = new AutomationCertificate(cloudCertificate.Certificate);
                    }
                    catch (Exception e)
                    {
                        // If the exception is not found, don't throw new exception as this is expected
                        if (e.HResult != -2146233088)
                        {
                            throw e;
                        }
                    }
                }
            }
            return(automationAsset);
        }
        public static async Task <ISet <AutomationAsset> > GetAll(String localWorkspacePath, AutomationManagementClient automationApi, string resourceGroupName, string automationAccountName, string encryptionCertThumbprint, ICollection <ConnectionType> connectionTypes)
        {
            CancellationTokenSource cts = new CancellationTokenSource();

            cts.CancelAfter(TIMEOUT_MS);
            VariableListResponse cloudVariables = await automationApi.Variables.ListAsync(resourceGroupName, automationAccountName, cts.Token);

            cts = new CancellationTokenSource();
            cts.CancelAfter(TIMEOUT_MS);
            CredentialListResponse cloudCredentials = await automationApi.PsCredentials.ListAsync(resourceGroupName, automationAccountName, cts.Token);

            cts = new CancellationTokenSource();
            cts.CancelAfter(TIMEOUT_MS);
            ConnectionListResponse cloudConnections = await automationApi.Connections.ListAsync(resourceGroupName, automationAccountName, cts.Token);

            CertificateListResponse cloudCertificates = await automationApi.Certificates.ListAsync(resourceGroupName, automationAccountName, cts.Token);

            // need to get connections one at a time to get each connection's values. Values currently come back as empty in list call
            var connectionAssetsWithValues = new HashSet <Connection>();

            foreach (var connection in cloudConnections.Connection)
            {
                cts = new CancellationTokenSource();
                cts.CancelAfter(TIMEOUT_MS);
                var connectionResponse = await automationApi.Connections.GetAsync(resourceGroupName, automationAccountName, connection.Name, cts.Token);

                connectionAssetsWithValues.Add(connectionResponse.Connection);
            }

            LocalAssets localAssets = LocalAssetsStore.Get(localWorkspacePath, encryptionCertThumbprint, connectionTypes);

            var automationAssets = new SortedSet <AutomationAsset>();

            // Compare cloud variables to local
            foreach (var cloudAsset in cloudVariables.Variables)
            {
                var localAsset = localAssets.Variables.Find(asset => asset.Name == cloudAsset.Name);

                var automationAsset = (localAsset != null) ?
                                      new AutomationVariable(localAsset, cloudAsset) :
                                      new AutomationVariable(cloudAsset);

                automationAssets.Add(automationAsset);
            }

            // Add remaining locally created variables
            foreach (var localAsset in localAssets.Variables)
            {
                var automationAsset = new AutomationVariable(localAsset);
                automationAssets.Add(automationAsset);
            }

            // Compare cloud credentials to local
            foreach (var cloudAsset in cloudCredentials.Credentials)
            {
                var localAsset = localAssets.PSCredentials.Find(asset => asset.Name == cloudAsset.Name);

                var automationAsset = (localAsset != null) ?
                                      new AutomationCredential(localAsset, cloudAsset) :
                                      new AutomationCredential(cloudAsset);

                automationAssets.Add(automationAsset);
            }

            // Add remaining locally created credentials
            foreach (var localAsset in localAssets.PSCredentials)
            {
                var automationAsset = new AutomationCredential(localAsset);
                automationAssets.Add(automationAsset);
            }

            // Compare cloud connections to local
            foreach (var cloudAsset in connectionAssetsWithValues)
            {
                ConnectionTypeGetResponse connectionType = await automationApi.ConnectionTypes.GetAsync(resourceGroupName, automationAccountName, cloudAsset.Properties.ConnectionType.Name);

                var localAsset = localAssets.Connections.Find(asset => asset.Name == cloudAsset.Name);

                var automationAsset = (localAsset != null) ?
                                      new AutomationConnection(localAsset, cloudAsset) :
                                      new AutomationConnection(cloudAsset, connectionType.ConnectionType);

                automationAssets.Add(automationAsset);
            }

            // Add remaining locally created connections
            foreach (var localAsset in localAssets.Connections)
            {
                var automationAsset = new AutomationConnection(localAsset);
                automationAssets.Add(automationAsset);
            }

            // Compare cloud certificates to local
            foreach (var cloudAsset in cloudCertificates.Certificates)
            {
                var localAsset = localAssets.Certificate.Find(asset => asset.Name == cloudAsset.Name);

                var automationAsset = (localAsset != null) ?
                                      new AutomationCertificate(localAsset, cloudAsset) :
                                      new AutomationCertificate(cloudAsset);

                automationAssets.Add(automationAsset);
            }

            // Add remaining locally created certificates
            foreach (var localAsset in localAssets.Certificate)
            {
                var automationAsset = new AutomationCertificate(localAsset);
                automationAssets.Add(automationAsset);
            }

            return(automationAssets);
        }
        /// <summary>
        /// Returns if the asset exists locally or in the cloud
        /// </summary>
        /// <param name="assetName"></param>
        /// <param name="assetType"></param>
        /// <param name="localWorkspacePath"></param>
        /// <param name="automationApi"></param>
        /// <param name="resourceGroupName"></param>
        /// <param name="automationAccountName"></param>
        /// <param name="encryptionCertThumbprint"></param>
        /// <returns>null if the asset does not exist or else returns the asset</returns>
        public static async Task<AutomationAsset> GetAsset(String assetName, String assetType, String localWorkspacePath, AutomationManagementClient automationApi, string resourceGroupName, string automationAccountName, string encryptionCertThumbprint, ICollection<ConnectionType> connectionTypes)
        {
            AutomationAsset automationAsset = null;

            // Get local assets
            LocalAssets localAssets = LocalAssetsStore.Get(localWorkspacePath, encryptionCertThumbprint, connectionTypes);

            // Search for variables
            CancellationTokenSource cts = new CancellationTokenSource();
            cts.CancelAfter(TIMEOUT_MS);
            if (assetType == Constants.AssetType.Variable)
            {
                // Check local asset store first
                var localVariable = localAssets.Variables.Find(asset => asset.Name == assetName);
                if (localVariable != null)
                {
                    automationAsset = new AutomationVariable(localVariable);
                }
                else
                {
                    try
                    {
                        // Check cloud. Catch exception if it doesn't exist
                        VariableGetResponse cloudVariable = await automationApi.Variables.GetAsync(resourceGroupName, automationAccountName, assetName, cts.Token);
                        automationAsset = new AutomationVariable(cloudVariable.Variable);
                    }
                    catch (Exception e)
                    {
                        // If the exception is not found, don't throw new exception as this is expected
                        if (e.HResult != -2146233088) throw e;
                    }
                }
            }
            // Search for credentials
            else if (assetType == Constants.AssetType.Credential)
            {
                // Check local asset store first
                var localCredential = localAssets.PSCredentials.Find(asset => asset.Name == assetName);
                if (localCredential != null)
                {
                    automationAsset = new AutomationCredential(localCredential);
                }
                else
                {
                    try
                    {
                        // Check cloud. Catch execption if it doesn't exist
                        CredentialGetResponse cloudVariable = await automationApi.PsCredentials.GetAsync(resourceGroupName, automationAccountName, assetName, cts.Token);
                        automationAsset = new AutomationCredential(cloudVariable.Credential);
                    }
                    catch (Exception e)
                    {
                        // If the exception is not found, don't throw new exception as this is expected
                        if (e.HResult != -2146233088) throw e;
                    }
                }
            }
            // Search for connections
            else if (assetType == Constants.AssetType.Connection)
            {
                // Check local asset store first
                var localConnection = localAssets.Connections.Find(asset => asset.Name == assetName);
                if (localConnection != null)
                {
                    automationAsset = new AutomationConnection(localConnection);
                }
                else
                {
                    try
                    {
                        // Check cloud. Catch exception if it doesn't exist
                        ConnectionGetResponse cloudConnection = await automationApi.Connections.GetAsync(resourceGroupName, automationAccountName, assetName, cts.Token);
                        cts = new CancellationTokenSource();
                        cts.CancelAfter(TIMEOUT_MS);
                        ConnectionTypeGetResponse connectionType =  await automationApi.ConnectionTypes.GetAsync(resourceGroupName, automationAccountName, 
                            cloudConnection.Connection.Properties.ConnectionType.Name, cts.Token);
                        automationAsset = new AutomationConnection(cloudConnection.Connection, connectionType.ConnectionType);
                    }
                    catch (Exception e)
                    {
                        // If the exception is not found, don't throw new exception as this is expected
                        if (e.HResult != -2146233088) throw e;
                    }
                }
            }
            return automationAsset;
        }
        public static async Task<ISet<AutomationAsset>> GetAll(String localWorkspacePath, AutomationManagementClient automationApi, string resourceGroupName, string automationAccountName, string encryptionCertThumbprint, ICollection<ConnectionType> connectionTypes)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            cts.CancelAfter(TIMEOUT_MS);
            VariableListResponse cloudVariables = await automationApi.Variables.ListAsync(resourceGroupName, automationAccountName, cts.Token);
            cts = new CancellationTokenSource();
            cts.CancelAfter(TIMEOUT_MS);
            CredentialListResponse cloudCredentials = await automationApi.PsCredentials.ListAsync(resourceGroupName, automationAccountName, cts.Token);
            cts = new CancellationTokenSource();
            cts.CancelAfter(TIMEOUT_MS);
            ConnectionListResponse cloudConnections = await automationApi.Connections.ListAsync(resourceGroupName, automationAccountName, cts.Token);

            // need to get connections one at a time to get each connection's values. Values currently come back as empty in list call
            var connectionAssetsWithValues = new HashSet<Connection>();
            foreach (var connection in cloudConnections.Connection)
            {
                cts = new CancellationTokenSource();
                cts.CancelAfter(TIMEOUT_MS);
                var connectionResponse = await automationApi.Connections.GetAsync(resourceGroupName, automationAccountName, connection.Name, cts.Token);
                connectionAssetsWithValues.Add(connectionResponse.Connection);
            }

            LocalAssets localAssets = LocalAssetsStore.Get(localWorkspacePath, encryptionCertThumbprint, connectionTypes);

            var automationAssets = new SortedSet<AutomationAsset>();

            // Compare cloud variables to local
            foreach (var cloudAsset in cloudVariables.Variables)
            {
                var localAsset = localAssets.Variables.Find(asset => asset.Name == cloudAsset.Name);

                var automationAsset = (localAsset != null) ?
                        new AutomationVariable(localAsset, cloudAsset) :
                        new AutomationVariable(cloudAsset);

                automationAssets.Add(automationAsset);
            }

            // Add remaining locally created variables
            foreach (var localAsset in localAssets.Variables)
            {
                var automationAsset = new AutomationVariable(localAsset);
                automationAssets.Add(automationAsset);
            }

            // Compare cloud credentials to local
            foreach (var cloudAsset in cloudCredentials.Credentials)
            {
                var localAsset = localAssets.PSCredentials.Find(asset => asset.Name == cloudAsset.Name);

                var automationAsset = (localAsset != null) ?
                        new AutomationCredential(localAsset, cloudAsset) :
                        new AutomationCredential(cloudAsset);

                automationAssets.Add(automationAsset);
            }

            // Add remaining locally created credentials
            foreach (var localAsset in localAssets.PSCredentials)
            {
                var automationAsset = new AutomationCredential(localAsset);
                automationAssets.Add(automationAsset);
            }

            // Compare cloud connections to local
            foreach (var cloudAsset in connectionAssetsWithValues)
            {
                ConnectionTypeGetResponse connectionType = await automationApi.ConnectionTypes.GetAsync(resourceGroupName, automationAccountName, cloudAsset.Properties.ConnectionType.Name); 
                var localAsset = localAssets.Connections.Find(asset => asset.Name == cloudAsset.Name);

                var automationAsset = (localAsset != null) ?
                        new AutomationConnection(localAsset, cloudAsset) :
                        new AutomationConnection(cloudAsset, connectionType.ConnectionType);

                automationAssets.Add(automationAsset);
            }

            // Add remaining locally created connections
            foreach (var localAsset in localAssets.Connections)
            {
                var automationAsset = new AutomationConnection(localAsset);
                automationAssets.Add(automationAsset);
            }

            return automationAssets;
        }