Example #1
0
        public static async Task DownloadRunbook(AutomationRunbook runbook, AutomationManagementClient automationManagementClient, string workspace, string resourceGroupName, AutomationAccount account)
        {
            CancellationTokenSource cts = new CancellationTokenSource();

            cts.CancelAfter(TIMEOUT_MS);
            RunbookGetResponse response = await automationManagementClient.Runbooks.GetAsync(resourceGroupName, account.Name, runbook.Name, cts.Token);

            RunbookDraftGetResponse draftResponse          = null;
            RunbookContentResponse  runbookContentResponse = null;

            cts = new CancellationTokenSource();
            cts.CancelAfter(TIMEOUT_MS);
            if (response.Runbook.Properties.State == "Published")
            {
                runbookContentResponse = await automationManagementClient.Runbooks.ContentAsync(resourceGroupName, account.Name, runbook.Name, cts.Token);
            }
            else
            {
                runbookContentResponse = await automationManagementClient.RunbookDraft.ContentAsync(resourceGroupName, account.Name, runbook.Name, cts.Token);

                cts = new CancellationTokenSource();
                cts.CancelAfter(TIMEOUT_MS);
                draftResponse = await automationManagementClient.RunbookDraft.GetAsync(resourceGroupName, account.Name, runbook.Name, cts.Token);
            }
            String runbookFilePath = System.IO.Path.Combine(workspace, runbook.Name + ".ps1");

            try
            {
                File.WriteAllText(runbookFilePath, runbookContentResponse.Stream.ToString(), Encoding.UTF8);
            }
            catch (Exception Ex)
            {
                // Atempting to write the file while it is being read. Wait a second and retry.
                if (Ex.HResult == -2147024864)
                {
                    Thread.Sleep(1000);
                    File.WriteAllText(runbookFilePath, runbookContentResponse.Stream.ToString(), Encoding.UTF8);
                }
            }
            runbook.AuthoringState = AutomationRunbook.AuthoringStates.InEdit;
            runbook.localFileInfo  = new FileInfo(runbookFilePath);

            /* This is the only way I can see to "check out" the runbook using the SDK.
             * Hopefully there's a better way but for now this works */
            if (response.Runbook.Properties.State == "Published")
            {
                await UploadRunbookAsDraft(runbook, automationManagementClient, resourceGroupName, account);

                cts = new CancellationTokenSource();
                cts.CancelAfter(TIMEOUT_MS);
                draftResponse = await automationManagementClient.RunbookDraft.GetAsync(resourceGroupName, account.Name, runbook.Name, cts.Token);
            }
            /* Ensures the correct sync status is detected */
            if (draftResponse != null)
            {
                runbook.localFileInfo.LastWriteTime = draftResponse.RunbookDraft.LastModifiedTime.LocalDateTime;
                runbook.LastModifiedLocal           = draftResponse.RunbookDraft.LastModifiedTime.LocalDateTime;
                runbook.LastModifiedCloud           = draftResponse.RunbookDraft.LastModifiedTime.LocalDateTime;
            }
        }
        public static async Task UploadToCloud(ICollection<AutomationAsset> assetsToUpload, AutomationManagementClient automationApi, string resourceGroupName, string automationAccountName)
        {
            var jss = new JavaScriptSerializer();
            
            foreach (var assetToUpload in assetsToUpload)
            {
                if (assetToUpload is AutomationVariable)
                {
                    var asset = (AutomationVariable)assetToUpload;

                    var properties = new VariableCreateOrUpdateProperties();
                    properties.IsEncrypted = asset.Encrypted;

                    var stringBuilder = new StringBuilder();
                    jss.Serialize(asset.getValue(), stringBuilder);
                    properties.Value = stringBuilder.ToString();
                    
                    await automationApi.Variables.CreateOrUpdateAsync(resourceGroupName, automationAccountName, new VariableCreateOrUpdateParameters(asset.Name, properties));
                }
                else if(assetToUpload is AutomationCredential)
                {
                    var asset = (AutomationCredential)assetToUpload;

                    var properties = new CredentialCreateOrUpdateProperties();
                    properties.UserName = asset.getUsername();
                    properties.Password = asset.getPassword();

                    await automationApi.PsCredentials.CreateOrUpdateAsync(resourceGroupName, automationAccountName, new CredentialCreateOrUpdateParameters(asset.Name, properties));
                }
                else if (assetToUpload is AutomationConnection)
                {
                    // TODO: implement this and certificates
                }
            }
        }
        public static async Task DeleteCloudRunbook(AutomationRunbook runbook, AutomationManagementClient automationManagementClient, string resourceGroupName, string accountName)
        {
            CancellationTokenSource cts = new CancellationTokenSource();

            cts.CancelAfter(TIMEOUT_MS);
            await automationManagementClient.Runbooks.DeleteAsync(resourceGroupName, accountName, runbook.Name, cts.Token);
        }
        public static async void DownloadFromCloud(ICollection<AutomationAsset> assetsToDownload, String localWorkspacePath, AutomationManagementClient automationApi, string resourceGroupName, string automationAccountName, String encryptionCertThumbprint, ICollection<ConnectionType> connectionTypes)
        {
            try
            {
                var cloudAssets = await AutomationAssetManager.GetAll(null, automationApi, resourceGroupName, automationAccountName, encryptionCertThumbprint, connectionTypes);
                var assetsToSaveLocally = new SortedSet<AutomationAsset>();

                foreach (var cloudAsset in cloudAssets)
                {
                    foreach (var assetToDownload in assetsToDownload)
                    {
                        if (cloudAsset.Equals(assetToDownload))
                        {
                            assetsToSaveLocally.Add(cloudAsset);
                            break;
                        }
                    }
                }

                AutomationAssetManager.SaveLocally(localWorkspacePath, assetsToSaveLocally, encryptionCertThumbprint, connectionTypes);
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private static async Task <IList <Module> > DownloadModuleMetadata(AutomationManagementClient automationManagementClient, string resourceGroupName, string accountName)
        {
            IList <Module>          modules = new List <Module>();
            CancellationTokenSource cts     = new CancellationTokenSource();

            cts.CancelAfter(TIMEOUT_MS);
            ModuleListResponse cloudModules = await automationManagementClient.Modules.ListAsync(resourceGroupName, accountName, cts.Token);

            foreach (var module in cloudModules.Modules)
            {
                // Skip automation internal modules
                if (!(Constants.excludeModules.Contains(module.Name)))
                {
                    modules.Add(module);
                }
            }

            while (cloudModules.NextLink != null)
            {
                cts = new CancellationTokenSource();
                cts.CancelAfter(TIMEOUT_MS);
                cloudModules = await automationManagementClient.Modules.ListNextAsync(cloudModules.NextLink, cts.Token);

                foreach (var module in cloudModules.Modules)
                {
                    // Skip automation internal modules
                    if (!(Constants.excludeModules.Contains(module.Name)))
                    {
                        modules.Add(module);
                    }
                }
            }
            return(modules);
        }
Example #6
0
        private async Task <IEnumerable <RunbookParameter> > ListAutomationRunbookParameters(
            string accessToken,
            string subscriptionId,
            string resourceGroupName,
            string automationAccountName,
            string runbookName)
        {
            var credentials = new TokenCredentials(subscriptionId, accessToken);

            using (var automationClient = new AutomationManagementClient(credentials))
            {
                var automationRunbookResult = await automationClient.Runbooks.GetAsync(resourceGroupName, automationAccountName, runbookName);

                var automationRunbookPrameters = automationRunbookResult.Runbook.Properties.Parameters.Select(
                    parameter => new RunbookParameter
                {
                    ParameterName = parameter.Key,
                    DefaultValue  = parameter.Value.DefaultValue,
                    IsMandatory   = parameter.Value.IsMandatory,
                    Position      = parameter.Value.Position,
                    Type          = parameter.Value.Type
                }).ToList();

                return(automationRunbookPrameters);
            }
        }
        public static async Task DeleteCloudModule(AutomationModule module, AutomationManagementClient automationManagementClient, string resourceGroupName, string accountName)
        {
            CancellationTokenSource cts = new CancellationTokenSource();

            cts.CancelAfter(TIMEOUT_MS);
            await automationManagementClient.Modules.DeleteAsync(resourceGroupName, accountName, module.Name, cts.Token);
        }
 public static async Task DownloadRunbook(AutomationRunbook runbook, AutomationManagementClient automationManagementClient, string workspace, string resourceGroupName, AutomationAccount account)
 {
     RunbookGetResponse response = await automationManagementClient.Runbooks.GetAsync(resourceGroupName, account.Name, runbook.Name);
     RunbookDraftGetResponse draftResponse = null;
     RunbookContentResponse runbookContentResponse = null;
     if (response.Runbook.Properties.State == "Published")
     {
         runbookContentResponse = await automationManagementClient.Runbooks.ContentAsync(resourceGroupName, account.Name, runbook.Name);
     }
     else
     {
         runbookContentResponse = await automationManagementClient.RunbookDraft.ContentAsync(resourceGroupName, account.Name, runbook.Name);
         draftResponse = await automationManagementClient.RunbookDraft.GetAsync(resourceGroupName, account.Name, runbook.Name);
     }
     String runbookFilePath = System.IO.Path.Combine(workspace, runbook.Name + ".ps1");
     File.WriteAllText(runbookFilePath, runbookContentResponse.Stream.ToString());
     runbook.localFileInfo = new FileInfo(runbookFilePath);
     /* This is the only way I can see to "check out" the runbook using the SDK.
      * Hopefully there's a better way but for now this works */
     if (response.Runbook.Properties.State == "Published")
     {
         await UploadRunbookAsDraft(runbook, automationManagementClient, resourceGroupName, account);
         draftResponse = await automationManagementClient.RunbookDraft.GetAsync(resourceGroupName, account.Name, runbook.Name);
     }
     /* Ensures the correct sync status is detected */
     if (draftResponse != null)
     {
         runbook.localFileInfo.LastWriteTime = draftResponse.RunbookDraft.LastModifiedTime.LocalDateTime;
         runbook.LastModifiedLocal = draftResponse.RunbookDraft.LastModifiedTime.LocalDateTime;
         runbook.LastModifiedCloud = draftResponse.RunbookDraft.LastModifiedTime.LocalDateTime;
     }
 }
Example #9
0
        public IEnumerable <Variable> ListVariables(string automationAccountName)
        {
            IList <AutomationManagement.Models.Variable> variables = AutomationManagementClient.ContinuationTokenHandler(
                skipToken =>
            {
                var response = this.automationManagementClient.Variables.List(
                    automationAccountName, skipToken);
                return(new ResponseWithSkipToken <AutomationManagement.Models.Variable>(
                           response, response.Variables));
            });

            var result =
                variables.Select(
                    (variable, autoamtionAccountName) =>
                    this.CreateVariableFromVariableModel(variable, automationAccountName)).ToList();

            IList <AutomationManagement.Models.EncryptedVariable> encryptedVariables = AutomationManagementClient
                                                                                       .ContinuationTokenHandler(
                skipToken =>
            {
                var response = this.automationManagementClient.EncryptedVariables.List(
                    automationAccountName, skipToken);
                return(new ResponseWithSkipToken <AutomationManagement.Models.EncryptedVariable>(
                           response, response.EncryptedVariables));
            });

            result.AddRange(
                encryptedVariables.Select(
                    (variable, autoamtionAccountName) =>
                    this.CreateVariableFromVariableModel(variable, automationAccountName)).ToList());

            return(result);
        }
        public static async Task <Boolean> CheckModuleExists(string moduleName, AutomationManagementClient automationManagementClient, string resourceGroupName, string accountName, string version)
        {
            try
            {
                CancellationTokenSource cts = new CancellationTokenSource();
                cts.CancelAfter(TIMEOUT_MS);
                ModuleGetResponse response = await automationManagementClient.Modules.GetAsync(resourceGroupName, accountName, moduleName, cts.Token);

                // If the cloud module is greater or equal to local module then return false so that it gets imported.
                if ((response.Module.Properties.Version != null && response.Module.Properties.Version.CompareTo(version) < 0) || !(String.IsNullOrEmpty(response.Module.Properties.Error.Message)))
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                // Module not found.
                if (ex.HResult == -2146233088)
                {
                    return(false);
                }
                else
                {
                    throw ex;
                }
            }
            // Module exists and is the same or newer version
            return(true);
        }
        public static async Task UploadRunbookAsDraft(AutomationRunbook runbook, AutomationManagementClient automationManagementClient, string resourceGroupName, AutomationAccount account)
        {
            RunbookCreateOrUpdateDraftProperties draftProperties = new RunbookCreateOrUpdateDraftProperties("Script", new RunbookDraft());

            draftProperties.Description = runbook.Description;
            RunbookCreateOrUpdateDraftParameters draftParams = new RunbookCreateOrUpdateDraftParameters(draftProperties);

            draftParams.Name     = runbook.Name;
            draftParams.Location = account.Location;
            await automationManagementClient.Runbooks.CreateOrUpdateWithDraftAsync(resourceGroupName, account.Name, draftParams);

            /* Update the runbook content from .ps1 file */
            RunbookDraftUpdateParameters draftUpdateParams = new RunbookDraftUpdateParameters()
            {
                Name   = runbook.Name,
                Stream = File.ReadAllText(runbook.localFileInfo.FullName)
            };
            await automationManagementClient.RunbookDraft.UpdateAsync(resourceGroupName, account.Name, draftUpdateParams);

            /* Ensure the correct sync status is detected */
            RunbookDraft draft = await GetRunbookDraft(runbook.Name, automationManagementClient, resourceGroupName, account.Name);

            runbook.localFileInfo.LastWriteTime = draft.LastModifiedTime.LocalDateTime;
            runbook.LastModifiedLocal           = draft.LastModifiedTime.LocalDateTime;
            runbook.LastModifiedCloud           = draft.LastModifiedTime.LocalDateTime;
        }
        private static async Task <IList <Runbook> > DownloadRunbookMetadata(AutomationManagementClient automationManagementClient, string resourceGroupName, string accountName)
        {
            IList <Runbook>         runbooks = new List <Runbook>();
            CancellationTokenSource cts      = new CancellationTokenSource();

            cts.CancelAfter(TIMEOUT_MS);
            RunbookListResponse cloudRunbooks = await automationManagementClient.Runbooks.ListAsync(resourceGroupName, accountName, cts.Token);

            foreach (var runbook in cloudRunbooks.Runbooks)
            {
                runbooks.Add(runbook);
            }

            while (cloudRunbooks.NextLink != null)
            {
                cts = new CancellationTokenSource();
                cts.CancelAfter(TIMEOUT_MS);
                cloudRunbooks = await automationManagementClient.Runbooks.ListNextAsync(cloudRunbooks.NextLink, cts.Token);

                foreach (var runbook in cloudRunbooks.Runbooks)
                {
                    runbooks.Add(runbook);
                }
            }
            return(runbooks);
        }
        public static async Task UploadRunbookAsDraft(AutomationRunbook runbook, AutomationManagementClient automationManagementClient, string resourceGroupName, AutomationAccount account)
        {
            RunbookCreateOrUpdateDraftProperties draftProperties;

            // Parse the script to determine if it is a PS workflow or native script
            String PSScriptText = File.ReadAllText(runbook.localFileInfo.FullName);
            System.Management.Automation.Language.Token[] AST;
            System.Management.Automation.Language.ParseError[] ASTError = null;
            var ASTScript = System.Management.Automation.Language.Parser.ParseInput(PSScriptText, out AST, out ASTError);

            // If the script starts with workflow, then create a PS Workflow script runbook or else create a native PS script runbook
            if (ASTScript.EndBlock.Extent.Text.ToLower().StartsWith("workflow"))
            {
                draftProperties = new RunbookCreateOrUpdateDraftProperties(Constants.RunbookType.Workflow, new RunbookDraft());
            }
            else
                draftProperties = new RunbookCreateOrUpdateDraftProperties(Constants.RunbookType.PowerShellScript, new RunbookDraft());

            // Get current properties if is not a new runbook and set these on the draft also so they are preserved.
            RunbookGetResponse response = null;
            CancellationTokenSource cts = new CancellationTokenSource();
            cts.CancelAfter(TIMEOUT_MS);
            if (runbook.SyncStatus != AutomationAuthoringItem.Constants.SyncStatus.LocalOnly)
            {
                response = await automationManagementClient.Runbooks.GetAsync(resourceGroupName, account.Name, runbook.Name, cts.Token);
                draftProperties.Description = response.Runbook.Properties.Description;
            }

            // Create draft properties
            RunbookCreateOrUpdateDraftParameters draftParams = new RunbookCreateOrUpdateDraftParameters(draftProperties);
            draftParams.Name = runbook.Name;
            draftParams.Location = account.Location;

            // If this is not a new runbook, set the existing properties of the runbook
            if (response != null)
            {
                draftParams.Tags = response.Runbook.Tags;
                draftParams.Properties.LogProgress = response.Runbook.Properties.LogProgress;
                draftParams.Properties.LogVerbose = response.Runbook.Properties.LogVerbose;
            }
            cts = new CancellationTokenSource();
            cts.CancelAfter(TIMEOUT_MS);
            await automationManagementClient.Runbooks.CreateOrUpdateWithDraftAsync(resourceGroupName, account.Name, draftParams, cts.Token);
            /* Update the runbook content from .ps1 file */

            RunbookDraftUpdateParameters draftUpdateParams = new RunbookDraftUpdateParameters()
            {
                Name = runbook.Name,
                Stream = PSScriptText
            };
            cts = new CancellationTokenSource();
            cts.CancelAfter(TIMEOUT_MS);
            await automationManagementClient.RunbookDraft.UpdateAsync(resourceGroupName, account.Name, draftUpdateParams, cts.Token);
            /* Ensure the correct sync status is detected */
            RunbookDraft draft = await GetRunbookDraft(runbook.Name, automationManagementClient, resourceGroupName, account.Name);
            runbook.localFileInfo.LastWriteTime = draft.LastModifiedTime.LocalDateTime;
            runbook.LastModifiedLocal = draft.LastModifiedTime.LocalDateTime;
            runbook.LastModifiedCloud = draft.LastModifiedTime.LocalDateTime;
        }
Example #14
0
 protected AzureAutomationClient(Guid tenantId, Guid subscriptionId, string resourceGroupName, string automationAccountName)
 {
     _authCtx               = new AuthenticationContext(Parameters.AZURE_LOGIN_AUTHORITY + tenantId);
     _subscriptionId        = subscriptionId;
     _resourceGroupName     = resourceGroupName;
     _automationAccountName = automationAccountName;
     _client = new AutomationManagementClient();
 }
        public static async Task <Module> GetModule(string moduleName, AutomationManagementClient automationManagementClient, string resourceGroupName, string accountName)
        {
            CancellationTokenSource cts = new CancellationTokenSource();

            cts.CancelAfter(TIMEOUT_MS);
            ModuleGetResponse response = await automationManagementClient.Modules.GetAsync(resourceGroupName, accountName, moduleName, cts.Token);

            return(response.Module);
        }
        public static async Task <ISet <AutomationRunbook> > GetAllRunbookMetadata(AutomationManagementClient automationManagementClient, string workspace, string resourceGroupName, string accountName, Dictionary <string, string> localScriptsParsed)
        {
            ISet <AutomationRunbook> result        = new SortedSet <AutomationRunbook>();
            IList <Runbook>          cloudRunbooks = await DownloadRunbookMetadata(automationManagementClient, resourceGroupName, accountName);

            /* Create a Dictionary of (filename, filepath) tuples found on disk. This will come in handy */
            Dictionary <string, string> filePathForRunbook = new Dictionary <string, string>();

            if (localScriptsParsed != null)
            {
                foreach (string path in localScriptsParsed.Keys)
                {
                    if (localScriptsParsed[path] == ("script"))
                    {
                        filePathForRunbook.Add(System.IO.Path.GetFileNameWithoutExtension(path), path);
                    }
                }
            }
            /* Start by checking the downloaded runbooks */
            foreach (Runbook cloudRunbook in cloudRunbooks)
            {
                /* Don't bother with graphical runbooks, since the ISE can't do anything with them */
                if (cloudRunbook.Properties.RunbookType != Constants.RunbookType.Graphical && cloudRunbook.Properties.RunbookType != Constants.RunbookType.GraphPowerShell)
                {
                    RunbookDraftGetResponse draftResponse;
                    try
                    {
                        CancellationTokenSource cts = new CancellationTokenSource();
                        cts.CancelAfter(TIMEOUT_MS);
                        draftResponse = await automationManagementClient.RunbookDraft.GetAsync(resourceGroupName, accountName, cloudRunbook.Name, cts.Token);
                    }
                    catch
                    {
                        draftResponse = null;
                        continue;
                    }
                    if (filePathForRunbook.ContainsKey(cloudRunbook.Name))
                    {
                        result.Add(new AutomationRunbook(new FileInfo(filePathForRunbook[cloudRunbook.Name]), cloudRunbook, draftResponse.RunbookDraft));
                    }
                    else
                    {
                        result.Add(new AutomationRunbook(cloudRunbook, draftResponse.RunbookDraft));
                    }
                }
            }
            /* Now find runbooks on disk that aren't yet accounted for */
            foreach (string localRunbookName in filePathForRunbook.Keys)
            {
                //Not great, but works for now
                if (result.FirstOrDefault(x => x.Name == localRunbookName) == null)
                {
                    result.Add(new AutomationRunbook(new FileInfo(filePathForRunbook[localRunbookName])));
                }
            }
            return(result);
        }
        public static async Task <RunbookDraft> GetRunbookDraft(string runbookName, AutomationManagementClient automationManagementClient, string resourceGroupName, string accountName)
        {
            CancellationTokenSource cts = new CancellationTokenSource();

            cts.CancelAfter(TIMEOUT_MS);
            RunbookDraftGetResponse response = await automationManagementClient.RunbookDraft.GetAsync(resourceGroupName, accountName, runbookName, cts.Token);

            return(response.RunbookDraft);
        }
Example #18
0
        private async Task AssureLogin()
        {
            var token = await((ClientType == ClientType.Workflow) ? GetAppToken() : GetUserToken());

            if (token != _token)
            {
                _token  = token;
                _client = new AutomationManagementClient(new TokenCloudCredentials(_subscriptionId.ToString(), _token));
            }
        }
        public static async Task<bool> isSourceControlEnabled(AutomationManagementClient automationClient, String resourceGroup, String automationAccount)
        {
            JobListParameters listParams = new JobListParameters();
            listParams.RunbookName = Constants.sourceControlRunbook;

            var response = await automationClient.Jobs.ListAsync(resourceGroup,
                    automationAccount, listParams, new System.Threading.CancellationToken());
            if (response.Jobs.Count > 0) return true;
            else return false;
        }
Example #20
0
        private async Task InitializeAsync()
        {
            await RefreshTokenAsync();

            _client = new AutomationManagementClient(_accessToken);

            // We need the location of the azure automation account for later use
            var account = _client.AutomationAccounts.Get(_connectionData.AzureRMGroupName, _connectionData.AzureAutomationAccount);
            _connectionData.AzureRMLocation = account.AutomationAccount.Location;
        }
 public static async Task<LongRunningOperationResultResponse> PublishRunbook(AutomationRunbook runbook, AutomationManagementClient automationManagementClient, string resourceGroupName, string accountName)
 {
     RunbookDraftPublishParameters publishParams = new RunbookDraftPublishParameters
     {
         Name = runbook.Name,
         PublishedBy = "ISE User: " + System.Security.Principal.WindowsIdentity.GetCurrent().Name
     };
     LongRunningOperationResultResponse resultResponse = await automationManagementClient.RunbookDraft.PublishAsync(resourceGroupName, accountName, publishParams);
     return resultResponse;
 }
Example #22
0
        public async Task <string> GetAutomationJobOutputAsync(string accessToken, string subscriptionId, string resourceGroupName, string automationAccountName, string jobId)
        {
            var credentials = new TokenCredentials(subscriptionId, accessToken);

            using (var automationClient = new AutomationManagementClient(credentials))
            {
                var jobOutputResponse = await automationClient.Jobs.GetOutputAsync(resourceGroupName, automationAccountName, new Guid(jobId));

                return(jobOutputResponse.Output);
            }
        }
        public RequestSettings(IAutomationManagementClient automationClient)
        {
            client = ((AutomationManagementClient)automationClient);
            client.HttpClient.DefaultRequestHeaders.Remove(Constants.ClientRequestIdHeaderName);
            client.HttpClient.DefaultRequestHeaders.Add(Constants.ClientRequestIdHeaderName, Guid.NewGuid().ToString());

            client.HttpClient.DefaultRequestHeaders.Remove(Constants.ActivityIdHeaderName);
            var activityId = Guid.NewGuid();
            EventProvider.SetActivityId(ref activityId);
            client.HttpClient.DefaultRequestHeaders.Add(Constants.ActivityIdHeaderName, activityId.ToString());
        }
        public static async Task DownloadConfiguration(AutomationDSC configuration, AutomationManagementClient automationManagementClient, string workspace, string resourceGroupName, AutomationAccount account)
        {
            CancellationTokenSource cts = new CancellationTokenSource();

            cts.CancelAfter(TIMEOUT_MS);
            DscConfigurationGetResponse response = await automationManagementClient.Configurations.GetAsync(resourceGroupName, account.Name, configuration.Name, cts.Token);

            DscConfigurationGetResponse        draftResponse = null;
            DscConfigurationGetContentResponse configurationContentResponse = null;

            cts = new CancellationTokenSource();
            cts.CancelAfter(TIMEOUT_MS);
            if (response.Configuration.Properties.State == "Published")
            {
                configurationContentResponse = await automationManagementClient.Configurations.GetContentAsync(resourceGroupName, account.Name, configuration.Name, cts.Token);
            }
            else
            {
                // Draft not supported yet
            }
            String configFilePath = System.IO.Path.Combine(workspace, configuration.Name + ".ps1");

            try
            {
                File.WriteAllText(configFilePath, configurationContentResponse.Content.ToString(), Encoding.UTF8);
            }
            catch (Exception Ex)
            {
                // Atempting to write the file while it is being read. Wait a second and retry.
                if (Ex.HResult == -2147024864)
                {
                    Thread.Sleep(1000);
                    File.WriteAllText(configFilePath, configurationContentResponse.Content.ToString(), Encoding.UTF8);
                }
            }
            configuration.localFileInfo = new FileInfo(configFilePath);

            if (response.Configuration.Properties.State == "Published")
            {
                await UploadConfigurationAsDraft(configuration, automationManagementClient, resourceGroupName, account);

                cts = new CancellationTokenSource();
                cts.CancelAfter(TIMEOUT_MS);
                draftResponse = await automationManagementClient.Configurations.GetAsync(resourceGroupName, account.Name, configuration.Name, cts.Token);
            }
            /* Ensures the correct sync status is detected */
            if (draftResponse != null)
            {
                configuration.localFileInfo.LastWriteTime = draftResponse.Configuration.Properties.LastModifiedTime.LocalDateTime;
                configuration.LastModifiedLocal           = draftResponse.Configuration.Properties.LastModifiedTime.LocalDateTime;
                configuration.LastModifiedCloud           = draftResponse.Configuration.Properties.LastModifiedTime.LocalDateTime;
            }
        }
Example #25
0
 public IEnumerable <Runbook> ListRunbooks(string automationAccountName)
 {
     return(AutomationManagementClient
            .ContinuationTokenHandler(
                skipToken =>
     {
         var response = this.automationManagementClient.Runbooks.List(
             automationAccountName, skipToken);
         return new ResponseWithSkipToken <AutomationManagement.Models.Runbook>(
             response, response.Runbooks);
     }).Select(c => new Runbook(automationAccountName, c)));
 }
Example #26
0
        public RequestSettings(IAutomationManagementClient automationClient)
        {
            client = ((AutomationManagementClient)automationClient);
            client.HttpClient.DefaultRequestHeaders.Remove(Constants.ClientRequestIdHeaderName);
            client.HttpClient.DefaultRequestHeaders.Add(Constants.ClientRequestIdHeaderName, Guid.NewGuid().ToString());

            client.HttpClient.DefaultRequestHeaders.Remove(Constants.ActivityIdHeaderName);
            var activityId = Guid.NewGuid();

            EventProvider.SetActivityId(ref activityId);
            client.HttpClient.DefaultRequestHeaders.Add(Constants.ActivityIdHeaderName, activityId.ToString());
        }
Example #27
0
        public async Task <IList <AutomationAccount> > GetAutomationAccounts()
        {
            if (currSubscription.Name == null)
            {
                throw new Exception(Properties.Resources.SubscriptionNotSet);
            }

            // Get the token for the tenant on this subscription.
            azureARMAuthResult = AuthenticateHelper.RefreshTokenByAuthority(currSubscription.Authority, Properties.Settings.Default.appIdURI);
            subscriptionCreds  = new TokenCloudCredentials(currSubscription.SubscriptionId, azureARMAuthResult.AccessToken);

            automationManagementClient = new AutomationManagementClient(subscriptionCreds, new Uri(Properties.Settings.Default.appIdURI));

            // Add user agent string to indicate this is coming from the ISE automation client.
            ProductInfoHeaderValue ISEClientAgent = new ProductInfoHeaderValue(Constants.ISEUserAgent, Constants.ISEVersion);

            automationManagementClient.UserAgent.Add(ISEClientAgent);

            //TODO: does this belong here?
            if (accountResourceGroups == null)
            {
                accountResourceGroups = new Dictionary <AutomationAccount, ResourceGroupExtended>();
            }
            else
            {
                accountResourceGroups.Clear();
            }

            IList <AutomationAccount> result = new List <AutomationAccount>();

            // Get ARM automation account resources
            var automationResources = await GetAutomationResources();

            // Retrieve all of the automation accounts found
            foreach (var resource in automationResources.Resources)
            {
                CancellationTokenSource cts = new CancellationTokenSource();
                cts.CancelAfter(TIMEOUT_MS);

                // Find the resource group name from the resource id.
                var startPosition = resource.Id.IndexOf("/resourceGroups/");
                var endPosition   = resource.Id.IndexOf("/", startPosition + 16);
                var resourceGroup = resource.Id.Substring(startPosition + 16, endPosition - startPosition - 16);

                AutomationAccountGetResponse account = await automationManagementClient.AutomationAccounts.GetAsync(resourceGroup, resource.Name, cts.Token);

                result.Add(account.AutomationAccount);
                var accountResourceGroup = new ResourceGroupExtended();
                accountResourceGroup.Name = resourceGroup;
                accountResourceGroups.Add(account.AutomationAccount, accountResourceGroup);
            }
            return(result);
        }
        public static async Task UploadToCloud(ICollection<AutomationAsset> assetsToUpload, AutomationManagementClient automationApi, string resourceGroupName, string automationAccountName)
        {
            var jss = new JavaScriptSerializer();

            foreach (var assetToUpload in assetsToUpload)
            {
                CancellationTokenSource cts = new CancellationTokenSource();
                cts.CancelAfter(TIMEOUT_MS);
                if (assetToUpload is AutomationVariable)
                {
                    var asset = (AutomationVariable)assetToUpload;

                    var properties = new VariableCreateOrUpdateProperties();
                    properties.IsEncrypted = asset.Encrypted;

                    var stringBuilder = new StringBuilder();
                    jss.Serialize(asset.getValue(), stringBuilder);
                    properties.Value = stringBuilder.ToString();

                    await automationApi.Variables.CreateOrUpdateAsync(resourceGroupName, automationAccountName, new VariableCreateOrUpdateParameters(asset.Name, properties), cts.Token);
                }
                else if(assetToUpload is AutomationCredential)
                {
                    var asset = (AutomationCredential)assetToUpload;

                    var properties = new CredentialCreateOrUpdateProperties();
                    properties.UserName = asset.getUsername();
                    properties.Password = asset.getPassword();

                    await automationApi.PsCredentials.CreateOrUpdateAsync(resourceGroupName, automationAccountName, new CredentialCreateOrUpdateParameters(asset.Name, properties), cts.Token);
                }
                else if (assetToUpload is AutomationConnection)
                {
                    var asset = (AutomationConnection)assetToUpload;

                    var properties = new ConnectionCreateOrUpdateProperties();
                    var connectionFieldsAsJson = new Dictionary<string, string>();

                    foreach(KeyValuePair<string, object> field in asset.getFields())
                    {
                        connectionFieldsAsJson.Add(field.Key, field.Value.ToString());
                    }

                    properties.FieldDefinitionValues = connectionFieldsAsJson;
                    properties.ConnectionType = new ConnectionTypeAssociationProperty();
                    properties.ConnectionType.Name = asset.ConnectionType;

                    await automationApi.Connections.CreateOrUpdateAsync(resourceGroupName, automationAccountName, new ConnectionCreateOrUpdateParameters(asset.Name, properties), cts.Token);
                }
                // TODO: implement certificates
            }
        }
        /* This is the only way I can see to "check out" a runbook (get it from Published to Edit state) using the SDK. */
        public static async Task CheckOutRunbook(AutomationRunbook runbook, AutomationManagementClient automationManagementClient, string resourceGroupName, AutomationAccount account)
        {
            CancellationTokenSource cts = new CancellationTokenSource();

            cts.CancelAfter(TIMEOUT_MS);
            RunbookGetResponse response = await automationManagementClient.Runbooks.GetAsync(resourceGroupName, account.Name, runbook.Name, cts.Token);

            if (response.Runbook.Properties.State != "Published")
            {
                return;
            }
            cts = new CancellationTokenSource();
            cts.CancelAfter(TIMEOUT_MS);
            RunbookContentResponse runbookContentResponse = await automationManagementClient.Runbooks.ContentAsync(resourceGroupName, account.Name, runbook.Name, cts.Token);

            // Create draft properties
            RunbookCreateOrUpdateDraftParameters draftParams = new RunbookCreateOrUpdateDraftParameters();

            draftParams.Properties             = new RunbookCreateOrUpdateDraftProperties();
            draftParams.Properties.Description = response.Runbook.Properties.Description;
            draftParams.Properties.LogProgress = response.Runbook.Properties.LogProgress;
            draftParams.Properties.LogVerbose  = response.Runbook.Properties.LogVerbose;
            draftParams.Properties.RunbookType = response.Runbook.Properties.RunbookType;
            draftParams.Properties.Draft       = new RunbookDraft();
            draftParams.Tags     = response.Runbook.Tags;
            draftParams.Name     = runbook.Name;
            draftParams.Location = account.Location;

            cts = new CancellationTokenSource();
            cts.CancelAfter(TIMEOUT_MS);
            await automationManagementClient.Runbooks.CreateOrUpdateWithDraftAsync(resourceGroupName, account.Name, draftParams, cts.Token);

            RunbookDraftUpdateParameters draftUpdateParams = new RunbookDraftUpdateParameters()
            {
                Name   = runbook.Name,
                Stream = runbookContentResponse.Stream.ToString()
            };

            cts = new CancellationTokenSource();
            cts.CancelAfter(TIMEOUT_MS);
            await automationManagementClient.RunbookDraft.UpdateAsync(resourceGroupName, account.Name, draftUpdateParams, cts.Token);

            /* Ensure the correct sync status is detected */
            if (runbook.localFileInfo != null)
            {
                RunbookDraft draft = await GetRunbookDraft(runbook.Name, automationManagementClient, resourceGroupName, account.Name);

                runbook.localFileInfo.LastWriteTime = draft.LastModifiedTime.LocalDateTime;
                runbook.LastModifiedLocal           = draft.LastModifiedTime.LocalDateTime;
                runbook.LastModifiedCloud           = draft.LastModifiedTime.LocalDateTime;
            }
        }
Example #30
0
        public IEnumerable <Module> ListModules(string resourceGroupName, string automationAccountName)
        {
            IList <AutomationManagement.Models.Module> modulesModels = AutomationManagementClient
                                                                       .ContinuationTokenHandler(
                skipToken =>
            {
                var response = this.automationManagementClient.Modules.List(resourceGroupName, automationAccountName);
                return(new ResponseWithSkipToken <AutomationManagement.Models.Module>(
                           response, response.Modules));
            });

            return(modulesModels.Select(c => new Module(resourceGroupName, automationAccountName, c)));
        }
        public IEnumerable <Schedule> ListSchedules(string automationAccountName)
        {
            IList <AutomationManagement.Models.Schedule> scheduleModels = AutomationManagementClient.ContinuationTokenHandler(
                skipToken =>
            {
                var response = this.automationManagementClient.Schedules.List(
                    automationAccountName, skipToken);
                return(new ResponseWithSkipToken <AutomationManagement.Models.Schedule>(
                           response, response.Schedules));
            });

            return(scheduleModels.Select(this.CreateScheduleFromScheduleModel));
        }
 /// <summary>
 /// This function checks is source control is enabled on the automation account
 /// </summary>
 /// <param name="automationClient"></param>
 /// <param name="resourceGroup"></param>
 /// <param name="automationAccount"></param>
 /// <returns>boolean value indicating if source control is enabled. True means it is and false means it is not</returns>
 public static async Task<bool> isSourceControlEnabled(AutomationManagementClient automationClient, String resourceGroup, String automationAccount)
 {
     // TODO This is a current way to determine if source control is enabled.
     // Will update this once the API becomes available.
     try {
         var response = await automationClient.Variables.GetAsync(resourceGroup, automationAccount, Constants.sourceControlConnectionVariable);
         return true;
     }
     catch
     {
         return false;
     }
 }
 public static async Task<ISet<AutomationRunbook>> GetAllRunbookMetadata(AutomationManagementClient automationManagementClient, string workspace, string resourceGroupName, string accountName)
 {
     ISet<AutomationRunbook> result = new SortedSet<AutomationRunbook>();
     IList<Runbook> cloudRunbooks = await DownloadRunbookMetadata(automationManagementClient, resourceGroupName, accountName);
     
     /* Create a Dictionary of (filename, filepath) tuples found on disk. This will come in handy */
     Dictionary<string, string> filePathForRunbook = new Dictionary<string, string>();
     if (Directory.Exists(workspace))
     {
         string[] localRunbookFilePaths = Directory.GetFiles(workspace, "*.ps1");
         foreach (string path in localRunbookFilePaths)
         {
             filePathForRunbook.Add(System.IO.Path.GetFileNameWithoutExtension(path), path);
         }
     }
     /* Start by checking the downloaded runbooks */
     foreach (Runbook cloudRunbook in cloudRunbooks)
     {
         /* Don't bother with graphical runbooks, since the ISE can't do anything with them */
         if (cloudRunbook.Properties.RunbookType != Constants.RunbookType.Graphical)
         {
             RunbookDraftGetResponse draftResponse;
             try
             {
                 draftResponse = await automationManagementClient.RunbookDraft.GetAsync(resourceGroupName, accountName, cloudRunbook.Name);
             }
             catch
             {
                 draftResponse = null;
             }
             if (filePathForRunbook.ContainsKey(cloudRunbook.Name))
             {
                 result.Add(new AutomationRunbook(new FileInfo(filePathForRunbook[cloudRunbook.Name]), cloudRunbook, draftResponse.RunbookDraft));
             }
             else
             {
                 result.Add(new AutomationRunbook(cloudRunbook, draftResponse.RunbookDraft));
             }
         }
     }
     /* Now find runbooks on disk that aren't yet accounted for */
     foreach (string localRunbookName in filePathForRunbook.Keys)
     {
         //Not great, but works for now
         if (result.FirstOrDefault(x => x.Name == localRunbookName) == null)
         {
             result.Add(new AutomationRunbook(new FileInfo(filePathForRunbook[localRunbookName])));
         }
     }
     return result;
 }
        public IEnumerable <Runbook> ListRunbooks(string automationAccountName)
        {
            IList <AutomationManagement.Models.Runbook> runbookModels = AutomationManagementClient.ContinuationTokenHandler(
                skipToken =>
            {
                var listRunbookResponse =
                    this.automationManagementClient.Runbooks.ListWithSchedules(
                        automationAccountName, skipToken);
                return(new ResponseWithSkipToken <AutomationManagement.Models.Runbook>(
                           listRunbookResponse, listRunbookResponse.Runbooks));
            });

            return(runbookModels.Select(runbookModel => new Runbook(runbookModel)));
        }
        /// <summary>
        /// This function checks is source control is enabled on the automation account
        /// </summary>
        /// <param name="automationClient"></param>
        /// <param name="resourceGroup"></param>
        /// <param name="automationAccount"></param>
        /// <returns>boolean value indicating if source control is enabled. True means it is and false means it is not</returns>
        public static async Task <bool> isSourceControlEnabled(AutomationManagementClient automationClient, String resourceGroup, String automationAccount)
        {
            // TODO This is a current way to determine if source control is enabled.
            // Will update this once the API becomes available.
            try {
                var response = await automationClient.Variables.GetAsync(resourceGroup, automationAccount, Constants.sourceControlConnectionVariable);

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Example #36
0
        public IEnumerable <Model.AutomationAccount> ListAutomationAccounts(string resourceGroupName)
        {
            Requires.Argument("ResourceGroupName", resourceGroupName).NotNull();

            return(AutomationManagementClient
                   .ContinuationTokenHandler(
                       skipToken =>
            {
                var response = this.automationManagementClient.AutomationAccounts.List(
                    resourceGroupName);
                return new ResponseWithSkipToken <AutomationManagement.Models.AutomationAccount>(
                    response, response.AutomationAccounts);
            }).Select(c => new Model.AutomationAccount(resourceGroupName, c)));
        }
Example #37
0
        public IEnumerable <Credential> ListCredentials(string automationAccountName)
        {
            IList <AutomationManagement.Models.Credential> credentialModels = AutomationManagementClient
                                                                              .ContinuationTokenHandler(
                skipToken =>
            {
                var response = this.automationManagementClient.PsCredentials.List(automationAccountName,
                                                                                  skipToken);
                return(new ResponseWithSkipToken <AutomationManagement.Models.Credential>(
                           response, response.Credentials));
            });

            return(credentialModels.Select(c => new Credential(automationAccountName, c)));
        }
        public static async Task <ISet <ConnectionType> > GetConnectionTypes(AutomationManagementClient automationApi, string resourceGroupName, string automationAccountName)
        {
            CancellationTokenSource cts = new CancellationTokenSource();

            cts.CancelAfter(TIMEOUT_MS);
            var connectionTypeListResponse = await automationApi.ConnectionTypes.ListAsync(resourceGroupName, automationAccountName, cts.Token);

            var connectionTypes = new HashSet <ConnectionType>();

            foreach (var connectionType in connectionTypeListResponse.ConnectionTypes)
            {
                connectionTypes.Add(connectionType);
            }

            return(connectionTypes);
        }
Example #39
0
        public async Task <string> GetAutomationRunbookDescriptionAsync(
            string accessToken,
            string subscriptionId,
            string resourceGroupName,
            string automationAccountName,
            string runbookName)
        {
            var credentials = new TokenCredentials(subscriptionId, accessToken);

            using (var automationClient = new AutomationManagementClient(credentials))
            {
                var automationRunbookResult = await automationClient.Runbooks.GetAsync(resourceGroupName, automationAccountName, runbookName);

                return(automationRunbookResult.Runbook.Properties.Description);
            }
        }
        public static async Task <ISet <AutomationModule> > GetAllModuleMetadata(AutomationManagementClient automationManagementClient, string workspace, string resourceGroupName, string accountName, Dictionary <string, PSObject> localModulesParsed)
        {
            ISet <AutomationModule> result       = new SortedSet <AutomationModule>();
            IList <Module>          cloudModules = await DownloadModuleMetadata(automationManagementClient, resourceGroupName, accountName);

            /* Start by checking the downloaded modules */
            foreach (Module cloudModule in cloudModules)
            {
                ModuleGetResponse draftResponse;

                try
                {
                    CancellationTokenSource cts = new CancellationTokenSource();
                    cts.CancelAfter(TIMEOUT_MS);
                    draftResponse = await automationManagementClient.Modules.GetAsync(resourceGroupName, accountName, cloudModule.Name, cts.Token);
                }
                catch
                {
                    draftResponse = null;
                    continue;
                }
                if (localModulesParsed != null && localModulesParsed.ContainsKey(cloudModule.Name))
                {
                    var moduleFileInfo = new FileInfo(localModulesParsed[cloudModule.Name].Properties["Path"].Value.ToString());
                    result.Add(new AutomationModule(localModulesParsed[cloudModule.Name], cloudModule, draftResponse.Module, moduleFileInfo.LastWriteTime));
                    moduleFileInfo = null;
                }
                else
                {
                    result.Add(new AutomationModule(cloudModule, draftResponse.Module));
                }
            }
            /* Now find module on disk that aren't yet accounted for */
            if (localModulesParsed != null)
            {
                foreach (string localModuleName in localModulesParsed.Keys)
                {
                    if (result.FirstOrDefault(x => x.Name == localModuleName) == null)
                    {
                        var moduleFileInfo = new FileInfo(localModulesParsed[localModuleName].Properties["Path"].Value.ToString());
                        result.Add(new AutomationModule(localModulesParsed[localModuleName], moduleFileInfo.LastWriteTime));
                        moduleFileInfo = null;
                    }
                }
            }
            return(result);
        }
Example #41
0
        public async Task <IEnumerable <AutomationAccount> > ListAutomationAccountsAsync(string accessToken, string subscriptionId)
        {
            var credentials = new TokenCredentials(subscriptionId, accessToken);

            using (var automationClient = new AutomationManagementClient(credentials))
            {
                var automationAccountsResult = await automationClient.AutomationAccounts.ListAsync(null).ConfigureAwait(false);

                return(automationAccountsResult.AutomationAccounts.Select(account => new AutomationAccount
                {
                    SubscriptionId = subscriptionId,
                    ResourceGroup = GetResourceGroup(account.Id),
                    AutomationAccountId = account.Id,
                    AutomationAccountName = account.Name,
                }).ToList());
            }
        }
        public static async Task<JobCreateResponse> startSouceControlJob(AutomationManagementClient automationClient, String resourceGroup, String automationAccount)
        {
            var jobParams = new JobCreateParameters
            {
                Properties = new JobCreateProperties
                {
                    Runbook = new RunbookAssociationProperty
                    {
                        Name = Constants.sourceControlRunbook
                    },
                    Parameters = null
                }
            };

            var jobResponse = await automationClient.Jobs.CreateAsync(resourceGroup,
                                automationAccount, jobParams, new CancellationToken());
            return jobResponse;
        }
        public static async void DownloadFromCloud(ICollection<AutomationAsset> assetsToDownload, String localWorkspacePath, AutomationManagementClient automationApi, string resourceGroupName, string automationAccountName, String encryptionCertThumbprint)
        {
            var cloudAssets = await AutomationAssetManager.GetAll(null, automationApi, resourceGroupName, automationAccountName, encryptionCertThumbprint);
            var assetsToSaveLocally = new SortedSet<AutomationAsset>();

            foreach (var cloudAsset in cloudAssets)
            {
                foreach (var assetToDownload in assetsToDownload)
                {
                    if (cloudAsset.Equals(assetToDownload))
                    {
                        assetsToSaveLocally.Add(cloudAsset);
                        break;
                    }
                }
            }

            AutomationAssetManager.SaveLocally(localWorkspacePath, assetsToSaveLocally, encryptionCertThumbprint);
        }
        /* This is the only way I can see to "check out" a runbook (get it from Published to Edit state) using the SDK. */
        public static async Task CheckOutRunbook(AutomationRunbook runbook, AutomationManagementClient automationManagementClient, string resourceGroupName, AutomationAccount account)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            cts.CancelAfter(TIMEOUT_MS);
            RunbookGetResponse response = await automationManagementClient.Runbooks.GetAsync(resourceGroupName, account.Name, runbook.Name, cts.Token);
            if (response.Runbook.Properties.State != "Published")
                return;
            cts = new CancellationTokenSource();
            cts.CancelAfter(TIMEOUT_MS);
            RunbookContentResponse runbookContentResponse = await automationManagementClient.Runbooks.ContentAsync(resourceGroupName, account.Name, runbook.Name, cts.Token);
            // Create draft properties
            RunbookCreateOrUpdateDraftParameters draftParams = new RunbookCreateOrUpdateDraftParameters();
            draftParams.Properties = new RunbookCreateOrUpdateDraftProperties();
            draftParams.Properties.Description = response.Runbook.Properties.Description;
            draftParams.Properties.LogProgress = response.Runbook.Properties.LogProgress;
            draftParams.Properties.LogVerbose = response.Runbook.Properties.LogVerbose;
            draftParams.Properties.RunbookType = response.Runbook.Properties.RunbookType;
            draftParams.Properties.Draft = new RunbookDraft();
            draftParams.Tags = response.Runbook.Tags;
            draftParams.Name = runbook.Name;
            draftParams.Location = account.Location;

            cts = new CancellationTokenSource();
            cts.CancelAfter(TIMEOUT_MS);
            await automationManagementClient.Runbooks.CreateOrUpdateWithDraftAsync(resourceGroupName, account.Name, draftParams, cts.Token);
            RunbookDraftUpdateParameters draftUpdateParams = new RunbookDraftUpdateParameters()
            {
                Name = runbook.Name,
                Stream = runbookContentResponse.Stream.ToString()
            };
            cts = new CancellationTokenSource();
            cts.CancelAfter(TIMEOUT_MS);
            await automationManagementClient.RunbookDraft.UpdateAsync(resourceGroupName, account.Name, draftUpdateParams, cts.Token);
            /* Ensure the correct sync status is detected */
            if (runbook.localFileInfo != null)
            {
                RunbookDraft draft = await GetRunbookDraft(runbook.Name, automationManagementClient, resourceGroupName, account.Name);
                runbook.localFileInfo.LastWriteTime = draft.LastModifiedTime.LocalDateTime;
                runbook.LastModifiedLocal = draft.LastModifiedTime.LocalDateTime;
                runbook.LastModifiedCloud = draft.LastModifiedTime.LocalDateTime;
            }
        }
        public async Task<IEnumerable<AutomationAccount>> ListRunbooksAsync(string accessToken, string subscriptionId)
        {
            var credentials = new TokenCredentials(subscriptionId, accessToken);

            using (var automationClient = new AutomationManagementClient(credentials))
            {
                var automationAccountsResult = await automationClient.AutomationAccounts.ListAsync(null).ConfigureAwait(false);
                var automationAccounts = await Task.WhenAll(
                    automationAccountsResult.AutomationAccounts.Select(
                        async account => new AutomationAccount
                        {
                            SubscriptionId = subscriptionId,
                            ResourceGroup = GetResourceGroup(account.Id),
                            AutomationAccountId = account.Id,
                            AutomationAccountName = account.Name,
                            Runbooks = await this.ListAutomationRunbooks(accessToken, subscriptionId, GetResourceGroup(account.Id), account.Name)
                        }).ToList());
                return automationAccounts;
            }
        }
 public static async Task UploadRunbookAsDraft(AutomationRunbook runbook, AutomationManagementClient automationManagementClient, string resourceGroupName, AutomationAccount account)
 {
     RunbookCreateOrUpdateDraftProperties draftProperties = new RunbookCreateOrUpdateDraftProperties("Script", new RunbookDraft());
     draftProperties.Description = runbook.Description;
     RunbookCreateOrUpdateDraftParameters draftParams = new RunbookCreateOrUpdateDraftParameters(draftProperties);
     draftParams.Name = runbook.Name;
     draftParams.Location = account.Location;
     await automationManagementClient.Runbooks.CreateOrUpdateWithDraftAsync(resourceGroupName, account.Name, draftParams);
     /* Update the runbook content from .ps1 file */
     RunbookDraftUpdateParameters draftUpdateParams = new RunbookDraftUpdateParameters()
     {
         Name = runbook.Name,
         Stream = File.ReadAllText(runbook.localFileInfo.FullName)
     };
     await automationManagementClient.RunbookDraft.UpdateAsync(resourceGroupName, account.Name, draftUpdateParams);
     /* Ensure the correct sync status is detected */
     RunbookDraft draft = await GetRunbookDraft(runbook.Name, automationManagementClient, resourceGroupName, account.Name);
     runbook.localFileInfo.LastWriteTime = draft.LastModifiedTime.LocalDateTime;
     runbook.LastModifiedLocal = draft.LastModifiedTime.LocalDateTime;
     runbook.LastModifiedCloud = draft.LastModifiedTime.LocalDateTime;
 }
        public static async Task UploadRunbookAsDraft(AutomationRunbook runbook, AutomationManagementClient automationManagementClient, string resourceGroupName, AutomationAccount account)
        {
            RunbookCreateOrUpdateDraftProperties draftProperties;

            // Parse the script to determine if it is a PS workflow or native script
            String PSScriptText = File.ReadAllText(runbook.localFileInfo.FullName);
            System.Management.Automation.Language.Token[] AST;
            System.Management.Automation.Language.ParseError[] ASTError = null;
            var ASTScript = System.Management.Automation.Language.Parser.ParseInput(PSScriptText, out AST, out ASTError);

            // If the script starts with workflow, then create a PS Workflow script runbook or else create a native PS script runbook
            if (ASTScript.EndBlock.Extent.Text.ToLower().StartsWith("workflow"))
            {
                draftProperties = new RunbookCreateOrUpdateDraftProperties(Constants.RunbookType.Workflow, new RunbookDraft());
            }
            else
                draftProperties = new RunbookCreateOrUpdateDraftProperties(Constants.RunbookType.PowerShellScript, new RunbookDraft());

            draftProperties.Description = runbook.Description;
            RunbookCreateOrUpdateDraftParameters draftParams = new RunbookCreateOrUpdateDraftParameters(draftProperties);
            draftParams.Name = runbook.Name;
            draftParams.Location = account.Location;
            await automationManagementClient.Runbooks.CreateOrUpdateWithDraftAsync(resourceGroupName, account.Name, draftParams);
            /* Update the runbook content from .ps1 file */

            RunbookDraftUpdateParameters draftUpdateParams = new RunbookDraftUpdateParameters()
            {
                Name = runbook.Name,
                Stream = PSScriptText
            };
            await automationManagementClient.RunbookDraft.UpdateAsync(resourceGroupName, account.Name, draftUpdateParams);
            /* Ensure the correct sync status is detected */
            RunbookDraft draft = await GetRunbookDraft(runbook.Name, automationManagementClient, resourceGroupName, account.Name);
            runbook.localFileInfo.LastWriteTime = draft.LastModifiedTime.LocalDateTime;
            runbook.LastModifiedLocal = draft.LastModifiedTime.LocalDateTime;
            runbook.LastModifiedCloud = draft.LastModifiedTime.LocalDateTime;
        }
 private static async Task<IList<Runbook>> DownloadRunbookMetadata(AutomationManagementClient automationManagementClient, string resourceGroupName, string accountName)
 {
     RunbookListResponse cloudRunbooks = await automationManagementClient.Runbooks.ListAsync(resourceGroupName, accountName);
     return cloudRunbooks.Runbooks;
 }
 public static async Task<RunbookDraft> GetRunbookDraft(string runbookName, AutomationManagementClient automationManagementClient, string resourceGroupName, string accountName)
 {
     RunbookDraftGetResponse response = await automationManagementClient.RunbookDraft.GetAsync(resourceGroupName, accountName, runbookName);
     return response.RunbookDraft;
 }
        private async Task<IEnumerable<RunbookParameter>> ListAutomationRunbookParameters(
            string accessToken,
            string subscriptionId,
            string resourceGroupName,
            string automationAccountName,
            string runbookName)
        {
            var credentials = new TokenCredentials(subscriptionId, accessToken);

            using (var automationClient = new AutomationManagementClient(credentials))
            {
                var automationRunbookResult = await automationClient.Runbooks.GetAsync(resourceGroupName, automationAccountName, runbookName);

                var automationRunbookPrameters = automationRunbookResult.Runbook.Properties.Parameters.Select(
                    parameter => new RunbookParameter
                    {
                        ParameterName = parameter.Key,
                        DefaultValue = parameter.Value.DefaultValue,
                        IsMandatory = parameter.Value.IsMandatory,
                        Position = parameter.Value.Position,
                        Type = parameter.Value.Type
                    }).ToList();

                return automationRunbookPrameters;
            }
        }
        /// <summary>
        /// Refreshes the token used to access azure automation.
        /// This is currently called from a timer that runs on the Constants.tokenRefreshInterval
        /// If it is about to expire (2 minutes from the next refresh, it will renew)
        /// </summary>
        public void RefreshAutomationClientwithNewToken()
        {
            // Get the token for the tenant on this subscription and check if it is about to expire.
            // If it is, refresh it if possible.
            if (currSubscription == null) return;
            if (azureARMAuthResult.ExpiresOn.ToLocalTime() < DateTime.Now.AddMinutes(Constants.tokenRefreshInterval + 2))
            {
                azureARMAuthResult = AuthenticateHelper.RefreshTokenByAuthority(currSubscription.ActiveDirectoryTenantId);
                subscriptionCreds = new TokenCloudCredentials(currSubscription.SubscriptionId, azureARMAuthResult.AccessToken);

                automationManagementClient = new AutomationManagementClient(subscriptionCreds);

                // Add user agent string to indicate this is coming from the ISE automation client.
                ProductInfoHeaderValue ISEClientAgent = new ProductInfoHeaderValue(Constants.ISEUserAgent, Constants.ISEVersion);
                automationManagementClient.UserAgent.Add(ISEClientAgent);
            }
        }
 public RequestSettings(IAutomationManagementClient automationClient)
 {
     client = ((AutomationManagementClient)automationClient);
     client.HttpClient.DefaultRequestHeaders.Remove(Constants.ClientRequestIdHeaderName);
     client.HttpClient.DefaultRequestHeaders.Add(Constants.ClientRequestIdHeaderName, Guid.NewGuid().ToString());
 }
        private async Task<IEnumerable<Runbook>> ListAutomationRunbooks(string accessToken, string subscriptionId, string resourceGroupName, string automationAccountName)
        {
            var credentials = new TokenCredentials(subscriptionId, accessToken);

            using (var automationClient = new AutomationManagementClient(credentials))
            {
                var automationRunbooksResult = await automationClient.Runbooks.ListAsync(resourceGroupName, automationAccountName);

                var automationRunbooks = await Task.WhenAll(automationRunbooksResult.Runbooks.Select(
                    async runbook => new Runbook
                    {
                        RunbookId = runbook.Id,
                        RunbookName = runbook.Name,
                        RunbookParameters = await this.ListAutomationRunbookParameters(accessToken, subscriptionId, resourceGroupName, automationAccountName, runbook.Name)
                    }).ToList());

                return automationRunbooks;
            }
        }
 public static async Task DeleteCloudRunbook(AutomationRunbook runbook, AutomationManagementClient automationManagementClient, string resourceGroupName, string accountName)
 {
     CancellationTokenSource cts = new CancellationTokenSource();
     cts.CancelAfter(TIMEOUT_MS);
     await automationManagementClient.Runbooks.DeleteAsync(resourceGroupName, accountName, runbook.Name, cts.Token);
 }
        private static async Task<IList<Runbook>> DownloadRunbookMetadata(AutomationManagementClient automationManagementClient, string resourceGroupName, string accountName)
        {
            IList<Runbook> runbooks = new List<Runbook>();
            CancellationTokenSource cts = new CancellationTokenSource();
            cts.CancelAfter(TIMEOUT_MS);
            RunbookListResponse cloudRunbooks = await automationManagementClient.Runbooks.ListAsync(resourceGroupName, accountName, cts.Token);
            foreach (var runbook in cloudRunbooks.Runbooks)
            {
                runbooks.Add(runbook);
            }

            while (cloudRunbooks.NextLink != null)
            {
                cts = new CancellationTokenSource();
                cts.CancelAfter(TIMEOUT_MS);
                cloudRunbooks = await automationManagementClient.Runbooks.ListNextAsync(cloudRunbooks.NextLink, cts.Token);
                foreach (var runbook in cloudRunbooks.Runbooks)
                {
                    runbooks.Add(runbook);
                }
            }
            return runbooks;
        }
 public static async Task<RunbookDraft> GetRunbookDraft(string runbookName, AutomationManagementClient automationManagementClient, string resourceGroupName, string accountName)
 {
     CancellationTokenSource cts = new CancellationTokenSource();
     cts.CancelAfter(TIMEOUT_MS);
     RunbookDraftGetResponse response = await automationManagementClient.RunbookDraft.GetAsync(resourceGroupName, accountName, runbookName, cts.Token);
     return response.RunbookDraft;
 }
        private async Task<IEnumerable<RunbookJob>> ListAutomationJobs(string accessToken, string subscriptionId, string resourceGroupName, string automationAccountName)
        {
            var credentials = new TokenCredentials(subscriptionId, accessToken);

            using (var automationClient = new AutomationManagementClient(credentials))
            {
                var automationJobsResult = await automationClient.Jobs.ListAsync(resourceGroupName, automationAccountName, parameters: null);

                var automationJobs = automationJobsResult.Jobs.Select(
                     job => new RunbookJob
                     {
                         JobId = job.Properties.JobId.ToString(),
                         Status = job.Properties.Status,
                         RunbookName = job.Properties.Runbook?.Name ?? "_(Unknown)_"
                     }).ToList();

                return automationJobs;
            }
        }
        public async Task<RunbookJob> GetAutomationJobAsync(string accessToken, string subscriptionId, string resourceGroupName, string automationAccountName, string jobId, bool configureAwait = false)
        {
            var credentials = new TokenCredentials(subscriptionId, accessToken);

            using (var automationClient = new AutomationManagementClient(credentials))
            {
                var automationJobResult = configureAwait ? await automationClient.Jobs.GetAsync(resourceGroupName, automationAccountName, new Guid(jobId)).ConfigureAwait(false) :
                    await automationClient.Jobs.GetAsync(resourceGroupName, automationAccountName, new Guid(jobId));

                var automationJob = new RunbookJob
                {
                    JobId = automationJobResult.Job.Properties.JobId.ToString(),
                    Status = automationJobResult.Job.Properties.Status,
                    RunbookName = automationJobResult.Job.Properties.Runbook?.Name ?? "_(Unknown)_",
                    ResourceGroupName = resourceGroupName,
                    AutomationAccountName = automationAccountName,
                    StartDateTime = automationJobResult.Job.Properties.StartTime,
                    EndDateTime = automationJobResult.Job.Properties.EndTime
                };

                return automationJob;
            }
        }
 public static async Task<LongRunningOperationResultResponse> PublishRunbook(AutomationRunbook runbook, AutomationManagementClient automationManagementClient, string resourceGroupName, string accountName)
 {
     RunbookDraftPublishParameters publishParams = new RunbookDraftPublishParameters
     {
         Name = runbook.Name,
         PublishedBy = "ISE User: " + System.Security.Principal.WindowsIdentity.GetCurrent().Name
     };
     CancellationTokenSource cts = new CancellationTokenSource();
     cts.CancelAfter(TIMEOUT_MS);
     LongRunningOperationResultResponse resultResponse = await automationManagementClient.RunbookDraft.PublishAsync(resourceGroupName, accountName, publishParams, cts.Token);
     /* Ensure the correct sync status is detected */
     if (runbook.localFileInfo != null)
     {
         cts = new CancellationTokenSource();
         cts.CancelAfter(TIMEOUT_MS);
         RunbookGetResponse response = await automationManagementClient.Runbooks.GetAsync(resourceGroupName, accountName, runbook.Name, cts.Token);
         runbook.localFileInfo.LastWriteTime = response.Runbook.Properties.LastModifiedTime.LocalDateTime;
         runbook.LastModifiedLocal = response.Runbook.Properties.LastModifiedTime.LocalDateTime;
         runbook.LastModifiedCloud = response.Runbook.Properties.LastModifiedTime.LocalDateTime;
     }
     /* Return the publish response */
     return resultResponse;
 }
        public async Task<IList<AutomationAccount>> GetAutomationAccounts()
        {
            if(currSubscription == null)
                throw new Exception(Properties.Resources.SubscriptionNotSet);

            // Get the token for the tenant on this subscription.
            azureARMAuthResult = AuthenticateHelper.RefreshTokenByAuthority(currSubscription.ActiveDirectoryTenantId);
            subscriptionCreds = new TokenCloudCredentials(currSubscription.SubscriptionId, azureARMAuthResult.AccessToken);

            automationManagementClient = new AutomationManagementClient(subscriptionCreds);
            
            // Add user agent string to indicate this is coming from the ISE automation client.
            ProductInfoHeaderValue ISEClientAgent = new ProductInfoHeaderValue(Constants.ISEUserAgent, Constants.ISEVersion);
            automationManagementClient.UserAgent.Add(ISEClientAgent);

            //TODO: does this belong here?
            if (accountResourceGroups == null)
                accountResourceGroups = new Dictionary<AutomationAccount, ResourceGroupExtended>();
            else
                accountResourceGroups.Clear();
            IList<AutomationAccount> result = new List<AutomationAccount>();
            IList<ResourceGroupExtended> resourceGroups = await this.GetResourceGroups();
            foreach (ResourceGroupExtended resourceGroup in resourceGroups)
            {
                AutomationAccountListResponse accountListResponse = await automationManagementClient.AutomationAccounts.ListAsync(resourceGroup.Name);
                foreach (AutomationAccount account in accountListResponse.AutomationAccounts)
                {
                    result.Add(account);
                    accountResourceGroups.Add(account, resourceGroup);
                }
            }
            return result;
        }