public async Task <Response <ActionGroupResource> > CreateOrUpdateAsync(string resourceGroupName, string actionGroupName, ActionGroupResource actionGroup, CancellationToken cancellationToken = default)
        {
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (actionGroupName == null)
            {
                throw new ArgumentNullException(nameof(actionGroupName));
            }
            if (actionGroup == null)
            {
                throw new ArgumentNullException(nameof(actionGroup));
            }

            using var message = CreateCreateOrUpdateRequest(resourceGroupName, actionGroupName, actionGroup);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);

            switch (message.Response.Status)
            {
            case 200:
            case 201:
            {
                ActionGroupResource value = default;
                using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);

                value = ActionGroupResource.DeserializeActionGroupResource(document.RootElement);
                return(Response.FromValue(value, message.Response));
            }
        public void UpdateActionGroupTest()
        {
            ActionGroupResource expectedParameters = GetCreateOrUpdateActionGroupParameter();

            var handler          = new RecordedDelegatingHandler();
            var insightsClient   = GetMonitorManagementClient(handler);
            var serializedObject = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(expectedParameters, insightsClient.SerializationSettings);

            serializedObject = serializedObject.Replace("{", "{\"name\":\"" + expectedParameters.Name + "\",\"id\":\"" + expectedParameters.Id + "\",");
            var expectedResponse = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(serializedObject)
            };

            handler        = new RecordedDelegatingHandler(expectedResponse);
            insightsClient = GetMonitorManagementClient(handler);

            ActionGroupPatchBody bodyParameter = new ActionGroupPatchBody
            {
                Enabled = true,
                Tags    = null
            };

            var result = insightsClient.ActionGroups.Update(
                resourceGroupName: "rg1",
                actionGroupName: expectedParameters.Name,
                actionGroupPatch: bodyParameter);

            AreEqual(expectedParameters, result);
        }
 /// <summary>
 /// Initializes a new instance of the PSActionGroupProperty class.
 /// </summary>
 /// <param name="actionGroup">The action group to wrap.</param>
 public PSActionGroupProperty(ActionGroupResource actionGroup)
 {
     this.Status           = actionGroup.Enabled ? "Enabled" : "Disabled";
     this.GroupShortName   = actionGroup.GroupShortName;
     this.EmailReceivers   = actionGroup.EmailReceivers.Select(e => new PSEmailReceiver(e)).ToList();
     this.SmsReceivers     = actionGroup.SmsReceivers.Select(s => new PSSmsReceiver(s)).ToList();
     this.WebhookReceivers = actionGroup.WebhookReceivers.Select(w => new PSWebhookReceiver(w)).ToList();
 }
Example #4
0
        public async Task Get()
        {
            var actionGroupName = Recording.GenerateAssetName("testActionGroup-");
            var actionGroup     = await CreateActionGroupAsync(actionGroupName);

            ActionGroupResource actionGroup2 = await actionGroup.GetAsync();

            ResourceDataHelper.AssertActionGroup(actionGroup.Data, actionGroup2.Data);
        }
 private void AreEqual(ActionGroupResource exp, ActionGroupResource act)
 {
     if (exp != null)
     {
         Assert.AreEqual(exp.Location, act.Location);
         Assert.AreEqual(exp.Name, act.Name);
         Assert.AreEqual(exp.Enabled, act.Enabled);
         AreEqual(exp.EmailReceivers, act.EmailReceivers);
         AreEqual(exp.SmsReceivers, act.SmsReceivers);
     }
 }
        public async Task Get()
        {
            var collection = await GetActionGroupCollectionAsync();

            var actionGroupName = Recording.GenerateAssetName("testActionGroup-");
            var input           = ResourceDataHelper.GetBasicActionGroupData("global");
            var lro             = await collection.CreateOrUpdateAsync(WaitUntil.Completed, actionGroupName, input);

            ActionGroupResource actionGroup1 = lro.Value;
            ActionGroupResource actionGroup2 = await collection.GetAsync(actionGroupName);

            ResourceDataHelper.AssertActionGroup(actionGroup1.Data, actionGroup2.Data);
        }
        public GetAzureRmActionGroupTests(Xunit.Abstractions.ITestOutputHelper output)
        {
            TestExecutionHelpers.SetUpSessionAndProfile();
            insightsOperationsMock       = new Mock <IActionGroupsOperations>();
            insightsManagementClientMock = new Mock <MonitorManagementClient>()
            {
                CallBase = true
            };
            commandRuntimeMock = new Mock <ICommandRuntime>();
            cmdlet             = new GetAzureRmActionGroupCommand()
            {
                CommandRuntime          = commandRuntimeMock.Object,
                MonitorManagementClient = insightsManagementClientMock.Object
            };

            ActionGroupResource responseObject = ActionGroupsUtilities.CreateActionGroupResource(name: "actiongroup1", shortName: "ag1");

            responseSimple = new AzureOperationResponse <ActionGroupResource>()
            {
                Body = responseObject
            };

            responsePage = new AzureOperationResponse <IEnumerable <ActionGroupResource> >()
            {
                Body = new List <ActionGroupResource> {
                    responseObject
                }
            };

            insightsOperationsMock.Setup(f => f.GetWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <AzureOperationResponse <ActionGroupResource> >(responseSimple))
            .Callback((string resourceGrp, string name, Dictionary <string, List <string> > headers, CancellationToken t) =>
            {
                this.resourceGroup = resourceGrp;
                this.name          = name;
            });

            insightsOperationsMock.Setup(f => f.ListByResourceGroupWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <AzureOperationResponse <IEnumerable <ActionGroupResource> > >(responsePage))
            .Callback((string resourceGrp, Dictionary <string, List <string> > headers, CancellationToken t) =>
            {
                this.resourceGroup = resourceGrp;
            });

            insightsOperationsMock.Setup(f => f.ListBySubscriptionIdWithHttpMessagesAsync(It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <AzureOperationResponse <IEnumerable <ActionGroupResource> > >(responsePage))
            .Callback((Dictionary <string, List <string> > headers, CancellationToken t) =>
                      { });

            insightsManagementClientMock.SetupGet(f => f.ActionGroups).Returns(this.insightsOperationsMock.Object);
        }
 public static void AreEqual(ActionGroupResource exp, ActionGroupResource act)
 {
     if (exp != null)
     {
         Assert.Equal(exp.Id, act.Id);
         Assert.Equal(exp.Name, act.Name);
         Assert.Equal(exp.Location, act.Location);
         Assert.Equal(exp.GroupShortName, act.GroupShortName);
         Assert.Equal(exp.Enabled, act.Enabled);
         AreEqual(exp.Tags, act.Tags);
         AreEqual(exp.EmailReceivers, act.EmailReceivers);
         AreEqual(exp.SmsReceivers, act.SmsReceivers);
         AreEqual(exp.WebhookReceivers, act.WebhookReceivers);
     }
 }
 /// <summary>Initializes a new instance of the PSActionGroup class.</summary>
 /// <param name="actionGroupResource">the action group resource</param>
 public PSActionGroupResource(ActionGroupResource actionGroupResource)
     : base(
         location: actionGroupResource.Location,
         id: actionGroupResource.Id,
         name: actionGroupResource.Name,
         type: actionGroupResource.Type,
         tags: actionGroupResource.Tags)
 {
     this.ResourceGroupName = new ResourceIdentifier(actionGroupResource.Id).ResourceGroupName;
     GroupShortName         = actionGroupResource.GroupShortName;
     Enabled          = actionGroupResource.Enabled;
     EmailReceivers   = actionGroupResource.EmailReceivers?.Select(o => new PSEmailReceiver(o)).ToList();
     SmsReceivers     = actionGroupResource.SmsReceivers?.Select(o => new PSSmsReceiver(o)).ToList();
     WebhookReceivers = actionGroupResource.WebhookReceivers?.Select(o => new PSWebhookReceiver(o)).ToList();
 }
 /// <summary>
 /// Initializes a new instance of the PSActionGroupProperty class.
 /// </summary>
 /// <param name="actionGroup">The action group to wrap.</param>
 public PSActionGroupProperty(ActionGroupResource actionGroup)
 {
     this.Status                     = actionGroup.Enabled ? "Enabled" : "Disabled";
     this.GroupShortName             = actionGroup.GroupShortName;
     this.EmailReceivers             = actionGroup.EmailReceivers.Select(e => new PSEmailReceiver(e)).ToList();
     this.SmsReceivers               = actionGroup.SmsReceivers.Select(s => new PSSmsReceiver(s)).ToList();
     this.WebhookReceivers           = actionGroup.WebhookReceivers.Select(w => new PSWebhookReceiver(w)).ToList();
     this.ItsmReceivers              = actionGroup.ItsmReceivers.Select(w => new PSItsmReceiver(w)).ToList();
     this.VoiceReceivers             = actionGroup.VoiceReceivers.Select(w => new PSVoiceReceiver(w)).ToList();
     this.ArmRoleReceivers           = actionGroup.ArmRoleReceivers.Select(w => new PSArmRoleReceiver(w)).ToList();
     this.AzureFunctionReceivers     = actionGroup.AzureFunctionReceivers.Select(w => new PSAzureFunctionReceiver(w)).ToList();
     this.LogicAppReceivers          = actionGroup.LogicAppReceivers.Select(w => new PSLogicAppReceiver(w)).ToList();
     this.AutomationRunbookReceivers = actionGroup.AutomationRunbookReceivers.Select(w => new PSAutomationRunbookReceiver(w)).ToList();
     this.AzureAppPushReceivers      = actionGroup.AzureAppPushReceivers.Select(w => new PSAzureAppPushReceiver(w)).ToList();
 }
 private static void AreEqual(ActionGroupResource exp, ActionGroupResource act)
 {
     if (exp != null)
     {
         Assert.Equal(exp.Id, act.Id);
         Assert.Equal(exp.Name, act.Name);
         Assert.Equal(exp.Location, act.Location);
         Assert.Equal(exp.GroupShortName, act.GroupShortName);
         Assert.Equal(exp.Enabled, act.Enabled);
         Utilities.AreEqual(exp.Tags, act.Tags);
         AreEqual(exp.EmailReceivers, act.EmailReceivers);
         AreEqual(exp.SmsReceivers, act.SmsReceivers);
         AreEqual(exp.WebhookReceivers, act.WebhookReceivers);
         AreEqual(exp.ItsmReceivers, act.ItsmReceivers);
         AreEqual(exp.AzureAppPushReceivers, act.AzureAppPushReceivers);
         AreEqual(exp.AutomationRunbookReceivers, act.AutomationRunbookReceivers);
     }
 }
        public AddAzureRmActionGroupTests(Xunit.Abstractions.ITestOutputHelper output)
        {
            TestExecutionHelpers.SetUpSessionAndProfile();
            insightsOperationsMock       = new Mock <IActionGroupsOperations>();
            insightsManagementClientMock = new Mock <MonitorManagementClient>()
            {
                CallBase = true
            };
            commandRuntimeMock = new Mock <ICommandRuntime>();
            cmdlet             = new SetAzureRmActionGroupCommand
            {
                CommandRuntime          = commandRuntimeMock.Object,
                MonitorManagementClient = insightsManagementClientMock.Object
            };

            response = new AzureOperationResponse <ActionGroupResource>()
            {
                Body =
                    ActionGroupsUtilities.CreateActionGroupResource(
                        name: "ActionGroupName",
                        shortName: "AgShortName")
            };

            insightsOperationsMock.Setup(f => f.CreateOrUpdateWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <ActionGroupResource>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(response))
            .Callback((string resourceGrp, string name, ActionGroupResource createOrUpdateParams, Dictionary <string, List <string> > headers, CancellationToken t) =>
            {
                this.resourceGroup      = resourceGrp;
                this.name               = name;
                this.createOrUpdatePrms = createOrUpdateParams;
            });

            insightsManagementClientMock.SetupGet(f => f.ActionGroups).Returns(this.insightsOperationsMock.Object);

            // Setup Confirmation
            commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny <string>())).Returns(true);
            commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny <string>(), It.IsAny <string>())).Returns(true);
            commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).Returns(true);
            commandRuntimeMock.Setup(f => f.ShouldContinue(It.IsAny <string>(), It.IsAny <string>())).Returns(true);
        }
Example #13
0
 /// <summary>Initializes a new instance of the PSActionGroup class.</summary>
 /// <param name="actionGroupResource">the action group resource</param>
 public PSActionGroupResource(ActionGroupResource actionGroupResource)
     : base(
         location: actionGroupResource.Location,
         id: actionGroupResource.Id,
         name: actionGroupResource.Name,
         type: actionGroupResource.Type,
         tags: actionGroupResource.Tags)
 {
     this.ResourceGroupName = new ResourceIdentifier(actionGroupResource.Id).ResourceGroupName;
     GroupShortName         = actionGroupResource.GroupShortName;
     Enabled                    = actionGroupResource.Enabled;
     EmailReceivers             = actionGroupResource.EmailReceivers?.Select(o => new PSEmailReceiver(o)).ToList();
     SmsReceivers               = actionGroupResource.SmsReceivers?.Select(o => new PSSmsReceiver(o)).ToList();
     WebhookReceivers           = actionGroupResource.WebhookReceivers?.Select(o => new PSWebhookReceiver(o)).ToList();
     ArmRoleReceivers           = actionGroupResource.ArmRoleReceivers?.Select(o => new PSArmRoleReceiver(o)).ToList();
     ItsmReceivers              = actionGroupResource.ItsmReceivers?.Select(o => new PSItsmReceiver(o)).ToList();
     VoiceReceivers             = actionGroupResource.VoiceReceivers?.Select(o => new PSVoiceReceiver(o)).ToList();
     AzureFunctionReceivers     = actionGroupResource.AzureFunctionReceivers?.Select(o => new PSAzureFunctionReceiver(o)).ToList();
     LogicAppReceivers          = actionGroupResource.LogicAppReceivers?.Select(o => new PSLogicAppReceiver(o)).ToList();
     AutomationRunbookReceivers = actionGroupResource.AutomationRunbookReceivers?.Select(o => new PSAutomationRunbookReceiver(o)).ToList();
     AzureAppPushReceivers      = actionGroupResource.AzureAppPushReceivers?.Select(o => new PSAzureAppPushReceiver(o)).ToList();
 }
        public static MetricAlertData GetBasicMetricAlertData(AzureLocation location, ActionGroupResource actionGroup)
        {
            IEnumerable <string> scopes = new List <string>()
            {
                "/subscriptions/db1ab6f0-4769-4b27-930e-01e2ef9c123c/resourceGroups/deleteme0122/providers/Microsoft.Compute/virtualMachines/MetricAlertActionTestVM01",
                // "/subscriptions/db1ab6f0-4769-4b27-930e-01e2ef9c123c/resourceGroups/deleteme0122/providers/Microsoft.Compute/virtualMachines/MetricAlertActionTestVM02"
            };
            var metricAlertAction = new MetricAlertAction()
            {
                ActionGroupId     = actionGroup.Id.ToString(),
                WebHookProperties = { new KeyValuePair <string, string>("key1", "value1") }
            };
            var metricCriteria = new MetricCriteria("High_CPU_80", "Percentage CPU", AggregationTypeEnum.Average, Operator.GreaterThan, 80.50)
            {
            };

            return(new MetricAlertData(
                       location,
                       3,
                       true,
                       scopes,
                       new TimeSpan(0, 1, 0),
                       new TimeSpan(0, 5, 0),
                       new MetricAlertSingleResourceMultipleMetricCriteria()
            {
                AllOf = { metricCriteria }
            })
            {
                Actions = { metricAlertAction }
            });
        }
 /// <summary>
 /// Create a new action group or update an existing one.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='actionGroupName'>
 /// The name of the action group.
 /// </param>
 /// <param name='actionGroup'>
 /// The action group to create or use for the update.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <ActionGroupResource> CreateOrUpdateAsync(this IActionGroupsOperations operations, string resourceGroupName, string actionGroupName, ActionGroupResource actionGroup, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, actionGroupName, actionGroup, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
 /// <summary>
 /// Create a new action group or update an existing one.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='actionGroupName'>
 /// The name of the action group.
 /// </param>
 /// <param name='actionGroup'>
 /// The action group to create or use for the update.
 /// </param>
 public static ActionGroupResource CreateOrUpdate(this IActionGroupsOperations operations, string resourceGroupName, string actionGroupName, ActionGroupResource actionGroup)
 {
     return(operations.CreateOrUpdateAsync(resourceGroupName, actionGroupName, actionGroup).GetAwaiter().GetResult());
 }
        public void CreateEnableListDeleteActionGroup()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var insightsClient = GetMonitorManagementClient(context, handler);
                this.VerifyExistenceOrCreateResourceGroup(resourceGroupName: ResourceGroupName, location: "Global");

                ActionGroupResource expectedParameters = GetCreateOrUpdateActionGroupParameter();
                ActionGroupResource result             = insightsClient.ActionGroups.CreateOrUpdate(
                    resourceGroupName: ResourceGroupName,
                    actionGroupName: ActionGroupName,
                    actionGroup: expectedParameters);

                if (!this.IsRecording)
                {
                    // TODO: Create a check with these commands
                    Assert.False(string.IsNullOrWhiteSpace(result.Id));
                    Assert.Equal(ActionGroupName, result.Name);
                    Assert.NotNull(result.EmailReceivers);
                    Assert.NotNull(result.SmsReceivers);

                    // AreEqual(expectedParameters, result);
                }

                ActionGroupResource singleActionGroup = insightsClient.ActionGroups.Get(
                    resourceGroupName: ResourceGroupName,
                    actionGroupName: ActionGroupName);

                if (!this.IsRecording)
                {
                    Utilities.AreEqual(result, singleActionGroup);
                }

                IEnumerable <ActionGroupResource> actualGroups = insightsClient.ActionGroups.ListBySubscriptionId();

                if (!this.IsRecording)
                {
                    var listActualGroups = actualGroups.ToList();
                    Assert.NotNull(listActualGroups);
                    Assert.True(listActualGroups.Count > 0);

                    // Utilities.AreEqual(new List<ActionGroupResource> { expectedParameters }, listActualGroups);
                }

                actualGroups = insightsClient.ActionGroups.ListByResourceGroup(resourceGroupName: ResourceGroupName);

                if (!this.IsRecording)
                {
                    var listActualGroups = actualGroups.ToList();
                    Assert.NotNull(listActualGroups);
                    Assert.True(listActualGroups.Count > 0);

                    // Utilities.AreEqual(new List<ActionGroupResource> { expectedParameters }, actualGroups.ToList());
                }

                // TODO: it responds 'already enabled' (Conflict: 409)
                AzureOperationResponse response = insightsClient.ActionGroups.EnableReceiverWithHttpMessagesAsync(
                    resourceGroupName: ResourceGroupName,
                    actionGroupName: ActionGroupName,
                    receiverName: "emailreceiver").Result;

                if (!this.IsRecording)
                {
                    Assert.Equal(HttpStatusCode.Conflict, response.Response.StatusCode);
                }

                response = insightsClient.ActionGroups.DeleteWithHttpMessagesAsync(
                    resourceGroupName: ResourceGroupName,
                    actionGroupName: ActionGroupName).Result;

                if (!this.IsRecording)
                {
                    Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode);
                }
            }
        }
        internal HttpMessage CreateCreateOrUpdateRequest(string resourceGroupName, string actionGroupName, ActionGroupResource actionGroup)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;

            request.Method = RequestMethod.Put;
            var uri = new RawRequestUriBuilder();

            uri.Reset(endpoint);
            uri.AppendPath("/subscriptions/", false);
            uri.AppendPath(subscriptionId, true);
            uri.AppendPath("/resourceGroups/", false);
            uri.AppendPath(resourceGroupName, true);
            uri.AppendPath("/providers/microsoft.insights/actionGroups/", false);
            uri.AppendPath(actionGroupName, true);
            uri.AppendQuery("api-version", "2019-06-01", true);
            request.Uri = uri;
            request.Headers.Add("Content-Type", "application/json");
            request.Headers.Add("Accept", "application/json");
            var content = new Utf8JsonRequestContent();

            content.JsonWriter.WriteObjectValue(actionGroup);
            request.Content = content;
            return(message);
        }
        /// <summary>
        /// Executes the cmdlet.
        /// </summary>
        protected override void ProcessRecordInternal()
        {
            if (
                ShouldProcess(
                    target: string.Format("Add/update action group: {0} from resource group: {1}", this.Name, this.ResourceGroupName),
                    action: "Add/update action group"))
            {
                if (ParameterSetName == ByInputObject)
                {
                    this.ResourceGroupName = this.InputObject.ResourceGroupName;
                    if (this.Name == null)
                    {
                        this.Name = this.InputObject.Name;
                    }
                    if (this.ShortName == null)
                    {
                        this.ShortName = this.InputObject.GroupShortName;
                    }
                    if (!this.DisableGroup.IsPresent)
                    {
                        this.DisableGroup = !this.InputObject.Enabled;
                    }
                    if (this.Tag == null)
                    {
                        this.Tag = this.InputObject.Tags;
                    }
                    this.Receiver = new List <PSActionGroupReceiverBase>();
                    this.Receiver.AddRange(this.InputObject.EmailReceivers);
                    this.Receiver.AddRange(this.InputObject.SmsReceivers);
                    this.Receiver.AddRange(this.InputObject.WebhookReceivers);
                    this.Receiver.AddRange(this.InputObject.ItsmReceivers);
                    this.Receiver.AddRange(this.InputObject.VoiceReceivers);
                    this.Receiver.AddRange(this.InputObject.ArmRoleReceivers);
                    this.Receiver.AddRange(this.InputObject.AzureFunctionReceivers);
                    this.Receiver.AddRange(this.InputObject.LogicAppReceivers);
                    this.Receiver.AddRange(this.InputObject.AutomationRunbookReceivers);
                    this.Receiver.AddRange(this.InputObject.AzureAppPushReceivers);
                }
                else if (ParameterSetName == ByResourceId)
                {
                    ResourceIdentifier resourceId = new ResourceIdentifier(this.ResourceId);
                    this.ResourceGroupName = resourceId.ResourceGroupName;
                    this.Name = resourceId.ResourceName;
                }

                IList <EmailReceiver> emailReceivers =
                    this.Receiver.OfType <PSEmailReceiver>().
                    Select(o => new EmailReceiver(name: o.Name, emailAddress: o.EmailAddress, status: TransitionHelpers.ConvertNamespace(o.Status), useCommonAlertSchema: o.UseCommonAlertSchema)).ToList();

                IList <SmsReceiver> smsReceivers =
                    this.Receiver.OfType <PSSmsReceiver>().
                    Select(o => new SmsReceiver(name: o.Name, countryCode: o.CountryCode, phoneNumber: o.PhoneNumber, status: TransitionHelpers.ConvertNamespace(o.Status))).ToList();

                IList <WebhookReceiver> webhookReceivers =
                    this.Receiver.OfType <PSWebhookReceiver>().
                    Select(o => new WebhookReceiver(
                               name: o.Name,
                               serviceUri: o.ServiceUri,
                               useCommonAlertSchema: o.UseCommonAlertSchema,
                               useAadAuth: o.UseAadAuth,
                               objectId: o.ObjectId,
                               identifierUri: o.IdentifierUri,
                               tenantId: o.TenantId)).ToList();

                IList <ItsmReceiver> itsmReceivers =
                    this.Receiver.OfType <PSItsmReceiver>().
                    Select(o => new ItsmReceiver(name: o.Name, workspaceId: o.WorkspaceId, connectionId: o.ConnectionId, ticketConfiguration: o.TicketConfiguration, region: o.Region)).ToList();

                IList <VoiceReceiver> voiceReceivers =
                    this.Receiver.OfType <PSVoiceReceiver>().
                    Select(o => new VoiceReceiver(name: o.Name, countryCode: o.CountryCode, phoneNumber: o.PhoneNumber)).ToList();

                IList <ArmRoleReceiver> armRoleReceivers =
                    this.Receiver.OfType <PSArmRoleReceiver>().
                    Select(o => new ArmRoleReceiver(name: o.Name, roleId: o.RoleId, useCommonAlertSchema: o.UseCommonAlertSchema)).ToList();

                IList <AzureFunctionReceiver> azureFunctionReceivers =
                    this.Receiver.OfType <PSAzureFunctionReceiver>().
                    Select(o => new AzureFunctionReceiver(
                               name: o.Name,
                               functionName: o.FunctionName,
                               functionAppResourceId: o.FunctionAppResourceId,
                               httpTriggerUrl: o.HttpTriggerUrl,
                               useCommonAlertSchema: o.UseCommonAlertSchema)).ToList();

                IList <LogicAppReceiver> logicAppReceivers =
                    this.Receiver.OfType <PSLogicAppReceiver>().
                    Select(o => new LogicAppReceiver(
                               name: o.Name,
                               resourceId: o.ResourceId,
                               callbackUrl: o.CallbackUrl,
                               useCommonAlertSchema: o.UseCommonAlertSchema
                               )).ToList();

                IList <AutomationRunbookReceiver> automationRunbookReceivers =
                    this.Receiver.OfType <PSAutomationRunbookReceiver>().
                    Select(o => new AutomationRunbookReceiver(
                               name: o.Name,
                               runbookName: o.RunbookName,
                               webhookResourceId: o.WebhookResourceId,
                               isGlobalRunbook: o.IsGlobalRunbook,
                               useCommonAlertSchema: o.UseCommonAlertSchema,
                               serviceUri: o.ServiceUri,
                               automationAccountId: o.AutomationAccountId
                               )).ToList();

                IList <AzureAppPushReceiver> azureAppPushReceivers =
                    this.Receiver.OfType <PSAzureAppPushReceiver>().
                    Select(o => new AzureAppPushReceiver(
                               name: o.Name,
                               emailAddress: o.EmailAddress
                               )).ToList();

                ActionGroupResource actionGroup = new ActionGroupResource
                {
                    Location                   = "Global",
                    GroupShortName             = this.ShortName,
                    Enabled                    = !this.DisableGroup.IsPresent || !this.DisableGroup,
                    Tags                       = this.Tag,
                    EmailReceivers             = emailReceivers,
                    SmsReceivers               = smsReceivers,
                    WebhookReceivers           = webhookReceivers,
                    ItsmReceivers              = itsmReceivers,
                    VoiceReceivers             = voiceReceivers,
                    ArmRoleReceivers           = armRoleReceivers,
                    AzureFunctionReceivers     = azureFunctionReceivers,
                    LogicAppReceivers          = logicAppReceivers,
                    AutomationRunbookReceivers = automationRunbookReceivers,
                    AzureAppPushReceivers      = azureAppPushReceivers
                };

                WriteObject(
                    new PSActionGroupResource(
                        this.MonitorManagementClient.ActionGroups.CreateOrUpdate(
                            resourceGroupName: this.ResourceGroupName,
                            actionGroupName: this.Name,
                            actionGroup: actionGroup)));
            }
        }
        public async Task ActionGroupsCreateOrUpdateTest()
        {
            var actionGroupResource = new ActionGroupResource("ONE", "Name", null, "West Us",
                                                              new Dictionary <string, string>(), null, true,
                                                              new List <EmailReceiver>()
            {
                new EmailReceiver("Email", "Email@AZ", true, ReceiverStatus.Enabled)
            },
                                                              new List <SmsReceiver>()
            {
                new SmsReceiver("SmsName", "countryCode", "phoneNum", ReceiverStatus.Enabled)
            },
                                                              new List <WebhookReceiver>(),
                                                              new List <ItsmReceiver>(),
                                                              new List <AzureAppPushReceiver>(),
                                                              new List <AutomationRunbookReceiver>(),
                                                              new List <VoiceReceiver>(),
                                                              new List <LogicAppReceiver>(),
                                                              new List <AzureFunctionReceiver>(),
                                                              new List <ArmRoleReceiver>());
            var mockResponse = new MockResponse((int)HttpStatusCode.OK);
            var content      = @"{
                            'id': 'ONE',
                            'name': 'Name',
                            'type': null,
                            'location': 'West Us',
                            'tags': { },
                            'properties':
                                {
                                    'groupShortName': null,
                                    'enabled': true,
                                    'emailReceivers': [
                                        {
                                            'name': 'Email',
                                            'emailAddress': 'Email@AZ',
                                            'useCommonAlertSchema': true,
                                            'status': 'Enabled'
                                        }
                                    ],
                                    'smsReceivers': [
                                        {
                                            'name': 'SmsName',
                                            'countryCode': 'countryCode',
                                            'phoneNumber': 'phoneNum',
                                            'status': 'Enabled'
                                        }
                                ],
                                    'webhookReceivers': [],
                                    'itsmReceivers': [],
                                    'azureAppPushReceivers': [],
                                    'automationRunbookReceivers': [],
                                    'voiceReceivers': [],
                                    'logicAppReceivers': [],
                                    'azureFunctionReceivers': [],
                                    'armRoleReceivers': []
                                }
                            
                        }
            ".Replace("'", "\"");

            mockResponse.SetContent(content);
            var mockTransport  = new MockTransport(mockResponse);
            var insightsClient = GetInsightsManagementClient(mockTransport);
            var result         = (await insightsClient.ActionGroups.CreateOrUpdateAsync("rg1", "actGroup1", actionGroupResource)).Value;

            AreEqual(actionGroupResource, result);
        }
 public virtual async Task <Response <ActionGroupResource> > CreateOrUpdateAsync(string resourceGroupName, string actionGroupName, ActionGroupResource actionGroup, CancellationToken cancellationToken = default)
 {
     using var scope = _clientDiagnostics.CreateScope("ActionGroupsOperations.CreateOrUpdate");
     scope.Start();
     try
     {
         return(await RestClient.CreateOrUpdateAsync(resourceGroupName, actionGroupName, actionGroup, cancellationToken).ConfigureAwait(false));
     }
     catch (Exception e)
     {
         scope.Failed(e);
         throw;
     }
 }
 public virtual Response <ActionGroupResource> CreateOrUpdate(string resourceGroupName, string actionGroupName, ActionGroupResource actionGroup, CancellationToken cancellationToken = default)
 {
     using var scope = _clientDiagnostics.CreateScope("ActionGroupsOperations.CreateOrUpdate");
     scope.Start();
     try
     {
         return(RestClient.CreateOrUpdate(resourceGroupName, actionGroupName, actionGroup, cancellationToken));
     }
     catch (Exception e)
     {
         scope.Failed(e);
         throw;
     }
 }
Example #23
0
        /// <summary>
        /// Executes the cmdlet.
        /// </summary>
        protected override void ProcessRecordInternal()
        {
            if (
                ShouldProcess(
                    target: string.Format("Add/update action group: {0} from resource group: {1}", this.Name, this.ResourceGroupName),
                    action: "Add/update action group"))
            {
                if (ParameterSetName == ByInputObject)
                {
                    this.ResourceGroupName = this.InputObject.ResourceGroupName;
                    if (this.ShortName == null)
                    {
                        this.ShortName = this.InputObject.GroupShortName;
                    }
                    if (!this.DisableGroup.IsPresent)
                    {
                        this.DisableGroup = !this.InputObject.Enabled;
                    }
                    if (this.Tag == null)
                    {
                        this.Tag = this.InputObject.Tags;
                    }
                    this.Receiver = new List <PSActionGroupReceiverBase>();
                    this.Receiver.AddRange(this.InputObject.EmailReceivers);
                    this.Receiver.AddRange(this.InputObject.SmsReceivers);
                    this.Receiver.AddRange(this.InputObject.WebhookReceivers);
                }
                else if (ParameterSetName == ByResourceId)
                {
                    ResourceIdentifier resourceId = new ResourceIdentifier(this.ResourceId);
                    this.ResourceGroupName = resourceId.ResourceGroupName;
                    this.Name = resourceId.ResourceName;
                }

                IList <EmailReceiver> emailReceivers =
                    this.Receiver.OfType <PSEmailReceiver>().
                    Select(o => new EmailReceiver(name: o.Name, emailAddress: o.EmailAddress, status: o.Status)).ToList();
                IList <SmsReceiver> smsReceivers =
                    this.Receiver.OfType <PSSmsReceiver>().
                    Select(o => new SmsReceiver(name: o.Name, countryCode: o.CountryCode, phoneNumber: o.PhoneNumber, status: o.Status)).ToList();
                IList <WebhookReceiver> webhookReceivers =
                    this.Receiver.OfType <PSWebhookReceiver>().
                    Select(o => new WebhookReceiver(name: o.Name, serviceUri: o.ServiceUri)).ToList();
                ActionGroupResource actionGroup = new ActionGroupResource
                {
                    Location         = "Global",
                    GroupShortName   = this.ShortName,
                    Enabled          = !this.DisableGroup.IsPresent || !this.DisableGroup,
                    Tags             = this.Tag,
                    EmailReceivers   = emailReceivers,
                    SmsReceivers     = smsReceivers,
                    WebhookReceivers = webhookReceivers
                };

                WriteObject(
                    new PSActionGroupResource(
                        this.MonitorManagementClient.ActionGroups.CreateOrUpdate(
                            resourceGroupName: this.ResourceGroupName,
                            actionGroupName: this.Name,
                            actionGroup: actionGroup)));
            }
        }