Ejemplo n.º 1
0
        /// <summary>
        /// Creates or updates a rule. Rules are enabled by default, or based on value of the
        /// State parameter. You can disable a rule using <a>DisableRule</a>.
        ///
        ///
        /// <para>
        ///  <b>Note:</b> When you create or update a rule, incoming events might not immediately
        /// start matching to new or updated rules. Please allow a short period of time for changes
        /// to take effect.
        /// </para>
        ///
        /// <para>
        /// A rule must contain at least an EventPattern or ScheduleExpression. Rules with EventPatterns
        /// are triggered when a matching event is observed. Rules with ScheduleExpressions self-trigger
        /// based on the given schedule. A rule can have both an EventPattern and a ScheduleExpression,
        /// in which case the rule will trigger on matching events as well as on a schedule.
        /// </para>
        ///
        /// <para>
        ///  <b>Note:</b> Most services in AWS treat : or / as the same character in Amazon Resource
        /// Names (ARNs). However, CloudWatch Events uses an exact match in event patterns and
        /// rules. Be sure to use the correct ARN characters when creating event patterns so that
        /// they match the ARN syntax in the event you want to match.
        /// </para>
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the PutRule service method.</param>
        ///
        /// <returns>The response from the PutRule service method, as returned by CloudWatchEvents.</returns>
        /// <exception cref="Amazon.CloudWatchEvents.Model.ConcurrentModificationException">
        /// This exception occurs if there is concurrent modification on rule or target.
        /// </exception>
        /// <exception cref="Amazon.CloudWatchEvents.Model.InternalException">
        /// This exception occurs due to unexpected causes.
        /// </exception>
        /// <exception cref="Amazon.CloudWatchEvents.Model.InvalidEventPatternException">
        /// The event pattern is invalid.
        /// </exception>
        /// <exception cref="Amazon.CloudWatchEvents.Model.LimitExceededException">
        /// This exception occurs if you try to create more rules or add more targets to a rule
        /// than allowed by default.
        /// </exception>
        public PutRuleResponse PutRule(PutRuleRequest request)
        {
            var marshaller   = new PutRuleRequestMarshaller();
            var unmarshaller = PutRuleResponseUnmarshaller.Instance;

            return(Invoke <PutRuleRequest, PutRuleResponse>(request, marshaller, unmarshaller));
        }
Ejemplo n.º 2
0
        internal virtual PutRuleResponse PutRule(PutRuleRequest request)
        {
            var marshaller   = PutRuleRequestMarshaller.Instance;
            var unmarshaller = PutRuleResponseUnmarshaller.Instance;

            return(Invoke <PutRuleRequest, PutRuleResponse>(request, marshaller, unmarshaller));
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Initiates the asynchronous execution of the PutRule operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the PutRule operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task <PutRuleResponse> PutRuleAsync(PutRuleRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = new PutRuleRequestMarshaller();
            var unmarshaller = PutRuleResponseUnmarshaller.Instance;

            return(InvokeAsync <PutRuleRequest, PutRuleResponse>(request, marshaller,
                                                                 unmarshaller, cancellationToken));
        }
        public string Update(Notification input, ILambdaContext context)
        {
            var region = RegionEndpoint.APSoutheast1;

            //Update rule in CloudWatch Events
            var cloudWatchEventClient = new AmazonCloudWatchEventsClient(region);

            var putRuleRequest = new PutRuleRequest();

            putRuleRequest.ScheduleExpression = input.Cron;
            putRuleRequest.Name  = $"testdonkey-rule-{ input.TopicId }";
            putRuleRequest.State = RuleState.ENABLED;

            var putRuleResponse = cloudWatchEventClient.PutRuleAsync(putRuleRequest).Result;

            if (putRuleResponse.HttpStatusCode != HttpStatusCode.OK)
            {
                throw new TestDonkeyException("Can't update rule");
            }

            //Update notification in DynamoDB
            var dynamoDBClient = new AmazonDynamoDBClient(region);

            var key = new Dictionary <string, AttributeValue>();

            key.Add("id", new AttributeValue()
            {
                S = input.TopicId
            });

            var updatedItem = new Dictionary <string, AttributeValueUpdate>();

            updatedItem.Add("cron", new AttributeValueUpdate(new AttributeValue()
            {
                S = input.Cron
            }, AttributeAction.PUT));
            if (input.Messages == null || input.Messages.Count < 1)
            {
                updatedItem.Add("messages", new AttributeValueUpdate(null, AttributeAction.DELETE));
            }
            else
            {
                updatedItem.Add("messages", new AttributeValueUpdate(new AttributeValue()
                {
                    SS = input.Messages
                }, AttributeAction.PUT));
            }


            var putItemResponse = dynamoDBClient.UpdateItemAsync("Topics", key, updatedItem).Result;

            if (putItemResponse.HttpStatusCode != HttpStatusCode.OK)
            {
                throw new TestDonkeyException("Can't update item");
            }

            return("success");
        }
        /// <summary>
        /// Initiates the asynchronous execution of the PutRule operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the PutRule operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/PutRule">REST API Reference for PutRule Operation</seealso>
        public virtual Task <PutRuleResponse> PutRuleAsync(PutRuleRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = PutRuleRequestMarshaller.Instance;
            options.ResponseUnmarshaller = PutRuleResponseUnmarshaller.Instance;

            return(InvokeAsync <PutRuleResponse>(request, options, cancellationToken));
        }
        internal virtual PutRuleResponse PutRule(PutRuleRequest request)
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = PutRuleRequestMarshaller.Instance;
            options.ResponseUnmarshaller = PutRuleResponseUnmarshaller.Instance;

            return(Invoke <PutRuleResponse>(request, options));
        }
Ejemplo n.º 7
0
        static async Task Main(string[] args)
        {
            // Create Eventbridge & Lambda Client
            var EBclient     = new AmazonEventBridgeClient(awsAccessKeyId: "Your-Access-Key", awsSecretAccessKey: "Your-Secret-Access-Key", region: Amazon.RegionEndpoint.APSoutheast1);
            var lambdaClient = new AmazonLambdaClient(awsAccessKeyId: "Your-Access-Key", awsSecretAccessKey: "Your-Secret-Access-Key", region: Amazon.RegionEndpoint.APSoutheast1);

            // Create a Scheduled Rule on EventBridge
            var putRuleRequest = new PutRuleRequest();

            putRuleRequest.Name = "Rule2";
            putRuleRequest.ScheduleExpression = "cron(*/1 * * * ? *)"; // Cron Expression (UTC Time): Minute Hour (DayofMonth) Month (DayofWeek) Year
            putRuleRequest.EventBusName       = "default";
            putRuleRequest.State = RuleState.ENABLED;

            var putRuleResponse = await EBclient.PutRuleAsync(putRuleRequest);

            Console.WriteLine(putRuleResponse.HttpStatusCode);
            Console.WriteLine(putRuleResponse.RuleArn);

            // Add Permission of the ScheduledRule to invoke function in Lambda
            var addPermissionRequest = new Amazon.Lambda.Model.AddPermissionRequest();

            addPermissionRequest.Action       = "lambda:InvokeFunction";
            addPermissionRequest.Principal    = "events.amazonaws.com";
            addPermissionRequest.StatementId  = "lambda-rule-2";
            addPermissionRequest.SourceArn    = putRuleResponse.RuleArn;
            addPermissionRequest.FunctionName = "TestEBSNS";

            var addPermissionResponse = await lambdaClient.AddPermissionAsync(addPermissionRequest);

            Console.WriteLine(addPermissionResponse.HttpStatusCode);

            // Set Target of the Schedule Rule to Lambda Function
            var putTargetRequest = new PutTargetsRequest();

            putTargetRequest.Rule         = "Rule2";
            putTargetRequest.EventBusName = "default";

            var eventTarget = new Target();

            eventTarget.Arn   = "arn:aws:lambda:your-region:your-account:function:TestEBSNS";
            eventTarget.Input = "{ \"Key1\":\"Rule1\", \"Key2\":\"Rule2\" }";
            eventTarget.Id    = "1";

            List <Target> eventTargets = new List <Target>();

            eventTargets.Add(eventTarget);
            putTargetRequest.Targets = eventTargets;

            var putTargetResponse = await EBclient.PutTargetsAsync(putTargetRequest);

            Console.WriteLine(putTargetResponse.HttpStatusCode);
        }
Ejemplo n.º 8
0
        public static void PutRuleExample()
        {
            AmazonCloudWatchEventsClient client = new AmazonCloudWatchEventsClient();

            var putRuleRequest = new PutRuleRequest
            {
                Name               = "DEMO_EVENT",
                RoleArn            = "IAM_ROLE_ARN",
                ScheduleExpression = "rate(5 minutes)",
                State              = RuleState.ENABLED
            };

            var putRuleResponse = client.PutRule(putRuleRequest);

            Console.WriteLine("Successfully set the rule {0}", putRuleResponse.RuleArn);
        }
Ejemplo n.º 9
0
Archivo: Rule.cs Proyecto: Ragu777/Code
        public async Task <String> SetRule(AmazonCloudWatchEventsClient client, String rulename, String cron)
        {
            try
            {
                var putRuleRequest = new PutRuleRequest
                {
                    Name = rulename,
                    ScheduleExpression = cron,
                    State = RuleState.ENABLED
                };

                var putRuleResponse = await client.PutRuleAsync(putRuleRequest);

                String result = putRuleResponse.RuleArn;
                return(result);
            }
            catch (Exception e)
            {
                throw new Exception("unable to set rule");
            }
        }
        public string Add(Notification input, ILambdaContext context)
        {
            if (input == null)
            {
                throw new ArgumentNullException("Input required");
            }

            //var topicId = Guid.NewGuid().ToString();
            var region = RegionEndpoint.APSoutheast1;

            //Create topic in SNS
            var snsClient = new AmazonSimpleNotificationServiceClient(region);

            var createTopicRequest = new CreateTopicRequest();

            createTopicRequest.Name = input.TopicName;
            var createTopicResponse = snsClient.CreateTopicAsync(createTopicRequest).Result;

            if (createTopicResponse.HttpStatusCode != HttpStatusCode.OK)
            {
                throw new TestDonkeyException("Can't add topic");
            }

            //Create rule in CloudWatch Events
            var cloudWatchEventClient = new AmazonCloudWatchEventsClient(region);

            var putRuleRequest = new PutRuleRequest();

            putRuleRequest.ScheduleExpression = input.Cron;
            putRuleRequest.Name  = $"testdonkey-rule-{ input.TopicId }";
            putRuleRequest.State = RuleState.ENABLED;

            var putRuleResponse = cloudWatchEventClient.PutRuleAsync(putRuleRequest).Result;

            if (putRuleResponse.HttpStatusCode != HttpStatusCode.OK)
            {
                throw new TestDonkeyException("Can't add rule");
            }

            //Set target for CloudWatch Events
            var putTargetsRequest = new PutTargetsRequest();

            putTargetsRequest.Rule    = putRuleRequest.Name;
            putTargetsRequest.Targets = new List <Target> {
                new Target()
                {
                    Arn   = "arn:aws:lambda:ap-southeast-1:404276529491:function:TestDonkeyLambda",
                    Id    = $"testdonkey-target-{ input.TopicId }",
                    Input = $"{{\"TopicId\":\"{ input.TopicId }\"}}"
                }
            };

            var putTargetsResponse = cloudWatchEventClient.PutTargetsAsync(putTargetsRequest).Result;

            if (putTargetsResponse.HttpStatusCode != HttpStatusCode.OK)
            {
                var deleteRuleRequest = new DeleteRuleRequest();
                deleteRuleRequest.Name = putRuleRequest.Name;
                cloudWatchEventClient.DeleteRuleAsync(deleteRuleRequest);
                throw new TestDonkeyException("Can't add target");
            }

            //Add permission to accept CloudWatch Events trigger for Lambda
            var lambdaClient = new AmazonLambdaClient(region);

            var addPermissionRequest = new Amazon.Lambda.Model.AddPermissionRequest();

            addPermissionRequest.FunctionName = "TestDonkeyLambda";
            addPermissionRequest.Action       = "lambda:InvokeFunction";
            addPermissionRequest.StatementId  = $"testdonkey-lambda-{ input.TopicId }";
            addPermissionRequest.Principal    = "events.amazonaws.com";
            addPermissionRequest.SourceArn    = putRuleResponse.RuleArn;

            var addPermissionResponse = lambdaClient.AddPermissionAsync(addPermissionRequest).Result;

            if (addPermissionResponse.HttpStatusCode != HttpStatusCode.Created)
            {
                throw new TestDonkeyException("Can't add permission");
            }

            //Save notification to DynamoDB
            var dynamoDBClient = new AmazonDynamoDBClient(region);

            var item = new Dictionary <string, AttributeValue>();

            item.Add("id", new AttributeValue()
            {
                S = input.TopicId
            });
            item.Add("name", new AttributeValue()
            {
                S = input.TopicName
            });
            item.Add("arn", new AttributeValue()
            {
                S = createTopicResponse.TopicArn
            });
            item.Add("cron", new AttributeValue()
            {
                S = input.Cron
            });

            var putItemResponse = dynamoDBClient.PutItemAsync("Topics", item).Result;

            if (putItemResponse.HttpStatusCode != HttpStatusCode.OK)
            {
                throw new TestDonkeyException("Can't add item");
            }

            return("success");
        }