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;
        }
 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;
        }
 /// <summary>
 /// Updates the runbook draft with runbookStream as its content.  (see
 /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more
 /// information)
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Automation.IRunbookDraftOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group
 /// </param>
 /// <param name='automationAccount'>
 /// Required. The automation account name.
 /// </param>
 /// <param name='parameters'>
 /// Required. The runbook draft update parameters.
 /// </param>
 /// <returns>
 /// A standard service response for long running operations.
 /// </returns>
 public static Task<LongRunningOperationResultResponse> UpdateGraphAsync(this IRunbookDraftOperations operations, string resourceGroupName, string automationAccount, RunbookDraftUpdateParameters parameters)
 {
     return operations.UpdateGraphAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None);
 }
 /// <summary>
 /// Updates the runbook draft with runbookStream as its content.  (see
 /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more
 /// information)
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Automation.IRunbookDraftOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group
 /// </param>
 /// <param name='automationAccount'>
 /// Required. The automation account name.
 /// </param>
 /// <param name='parameters'>
 /// Required. The runbook draft update parameters.
 /// </param>
 /// <returns>
 /// A standard service response for long running operations.
 /// </returns>
 public static LongRunningOperationResultResponse UpdateGraph(this IRunbookDraftOperations operations, string resourceGroupName, string automationAccount, RunbookDraftUpdateParameters parameters)
 {
     return Task.Factory.StartNew((object s) => 
     {
         return ((IRunbookDraftOperations)s).UpdateGraphAsync(resourceGroupName, automationAccount, parameters);
     }
     , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
        /* 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 Runbook ImportRunbook(string resourceGroupName, string automationAccountName, string runbookPath, string description, IDictionary tags, string type, bool? logProgress, bool? logVerbose, bool published, bool overwrite)
        {

            var fileExtension = Path.GetExtension(runbookPath);

            if (0 !=
                string.Compare(fileExtension, Constants.SupportedFileExtensions.PowerShellScript,
                    StringComparison.OrdinalIgnoreCase) &&
                0 !=
                string.Compare(fileExtension, Constants.SupportedFileExtensions.Graph,
                    StringComparison.OrdinalIgnoreCase))
            {
                throw new ResourceCommonException(typeof(Runbook),
                        string.Format(CultureInfo.CurrentCulture, Resources.InvalidImportFile, runbookPath));
            }

            // if graph runbook make sure type is not null and has right value
            if (0 == string.Compare(fileExtension, Constants.SupportedFileExtensions.Graph, StringComparison.OrdinalIgnoreCase) 
                && string.IsNullOrWhiteSpace(type) 
                && (0 != string.Compare(type, Constants.RunbookType.Graph,StringComparison.OrdinalIgnoreCase)))
            {
                throw new ResourceCommonException(typeof(Runbook),
                        string.Format(CultureInfo.CurrentCulture, Resources.InvalidRunbookTypeForExtension, fileExtension));
            }


            var runbookName = Path.GetFileNameWithoutExtension(runbookPath);

            using (var request = new RequestSettings(this.automationManagementClient))
            {
                var runbook = this.CreateRunbookByName(resourceGroupName, automationAccountName, runbookName, description, tags, type, logProgress, logVerbose, overwrite);

                var rduprop = new RunbookDraftUpdateParameters()
                {
                    Name = runbookName,
                    Stream = File.ReadAllText(runbookPath)
                };

                this.automationManagementClient.RunbookDraft.Update(resourceGroupName, automationAccountName, rduprop);

                if (published)
                {
                    runbook = this.PublishRunbook(resourceGroupName, automationAccountName, runbookName);
                }

                return runbook;
            }
        }
        public async Task<OperationStatus> SaveRunbookContentAsync(RunbookModelProxy runbook, string runbookContent, RunbookType runbookType)
        {
            var longRunningOp = default(LongRunningOperationResultResponse);

            var runbookUpdate = new RunbookDraftUpdateParameters();
            runbookUpdate.Stream = runbookContent;
            runbookUpdate.Name = runbook.RunbookName;

            longRunningOp = await _client.RunbookDraft.UpdateAsync(_connectionData.AzureRMGroupName, _connectionData.AzureAutomationAccount, runbookUpdate);

            if (runbookType == RunbookType.Published)
            {
                await CheckIn(runbook);
            }

            if (longRunningOp.Status == Microsoft.Azure.OperationStatus.Failed)
                return OperationStatus.Failed;
            else if (longRunningOp.Status == Microsoft.Azure.OperationStatus.InProgress)
                return OperationStatus.InProgress;
            else if (longRunningOp.Status == Microsoft.Azure.OperationStatus.Succeeded)
                return OperationStatus.Succeeded;

            return OperationStatus.Failed;
        }
        public async Task<bool> CheckOut(RunbookViewModel runbook)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            cts.CancelAfter(TIMEOUT_MS);

            RunbookGetResponse response = await _client.Runbooks.GetAsync(_connectionData.AzureRMGroupName, _connectionData.AzureAutomationAccount, runbook.Runbook.RunbookName, cts.Token);

            if (response.Runbook.Properties.State != "Published")
                return false;

            cts = new CancellationTokenSource();
            cts.CancelAfter(TIMEOUT_MS);

            RunbookContentResponse runbookContentResponse = await _client.Runbooks.ContentAsync(_connectionData.AzureRMGroupName, _connectionData.AzureAutomationAccount, runbook.Runbook.RunbookName, 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.Runbook.RunbookName;
            draftParams.Location = _connectionData.AzureRMLocation;

            cts = new CancellationTokenSource();
            cts.CancelAfter(TIMEOUT_MS);

            await _client.Runbooks.CreateOrUpdateWithDraftAsync(_connectionData.AzureRMGroupName, _connectionData.AzureAutomationAccount, draftParams, cts.Token);
            RunbookDraftUpdateParameters draftUpdateParams = new RunbookDraftUpdateParameters()
            {
                Name = runbook.Runbook.RunbookName,
                Stream = runbookContentResponse.Stream.ToString()
            };
            cts = new CancellationTokenSource();
            cts.CancelAfter(TIMEOUT_MS);

            await _client.RunbookDraft.UpdateAsync(_connectionData.AzureRMGroupName, _connectionData.AzureAutomationAccount, draftUpdateParams, cts.Token);

            return true;
        }