Amazon EventBridge rule cannot trigger a Lambda Function - c#

Using the .Net AWSSDK.EventBridge I created a rule:
var client = new AmazonEventBridgeClient();
string ruleName = "SomeRule";
var putRuleRequest = new Amazon.EventBridge.Model.PutRuleRequest()
{
Name = ruleName,
ScheduleExpression = "rate(10 minutes)",
State = RuleState.ENABLED
}
await client.PutRuleAsync(putRuleRequest);
var target = new Amazon.EventBridge.Model.Target();
target.Arn = "ARN_LAMBDA_FUNCTION";
target.Id = "LAMBDA_FUNCTION_NAME";
target.Input = JsonSerializer.Serialize(new { someId, someDate});
var targetList = new List<Amazon.EventBridge.Model.Target>();
targetList.Add(target);
var putTargetRequest = new Amazon.EventBridge.Model.PutTargetsRequest()
{
Rule = ruleName,
Targets = targetList
};
await client.PutTargetsAsync(putTargetRequest);
The Lambda function is already created so I put the ARN and name on the Target. The idea is that there is one function but multiple rules will call it.
The rule, schedule, and target to the function are created when I run the code but the problem is that the function can't be triggered by the rule. When I edit the rule, update it in the AWS Console without changing anything the trigger works.
What am I missing?

After searching through I found out I was missing the permission for Lambda.
//This line replaces the code above
var putRuleResponse = client.PutRuleAsync(putRuleRequest).Result;
var lp = new Amazon.Lambda.Model.AddPermissionRequest();
lp.FunctionName = FUNCTION_ARN;
lp.Action = "lambda:InvokeFunction";
lp.SourceArn = putRuleResponse.RuleArn;
lp.Principal = "events.amazonaws.com";
lp.StatementId = "SomeStatement";
var lambdaClient = new AmazonLambdaClient();
await lambdaClient.AddPermissionAsync(lp);

Related

How to IndexKeysDefinitionBuilder change to IndexKeysDefinition (MongoDB in C#)

I have the following code where I am stuck a little bit:
var indexBuilder = Builders<T>.IndexKeys;
if (setting.IsDescending)
indexBuilder.Descending(setting.Column);
else
indexBuilder.Ascending(setting.Column);
var indexOptions = new CreateIndexOptions();
if (setting.IsUnique)
indexOptions.Unique = true;
var model = new CreateIndexModel<T>(indexBuilder, indexOptions);
I got the following error:
Argument 1: cannot convert from 'MongoDB.Driver.IndexKeysDefinitionBuilder' to 'MongoDB.Driver.IndexKeysDefinition'
I am not sure why as I have done the same as it is in official documentation.
You need to create a variable with IndexKeysDefinition<T> and pass it to the CreateIndexModel as below:
IndexKeysDefinition<T> index;
var indexBuilder = Builders<T>.IndexKeys;
if (setting.IsDescending)
index = indexBuilder.Descending(setting.Column);
else
index = indexBuilder.Ascending(setting.Column);
var indexOptions = new CreateIndexOptions();
if (setting.IsUnique)
indexOptions.Unique = true;
var model = new CreateIndexModel<T>(index, indexOptions);
Demo

CreatePushAsync not working: VssServiceException: The parameters supplied are not valid. Parameter name: newPush

I am trying to replicate the post request as given in the doc: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pushes/create?view=azure-devops-rest-5.0#update_a_file
using the .Net libraries for making an extension.
I have checked that the refUpdate and OldObjectId are correct through trial and error.
changes, item, repo are all defined and not null.
GitPush push = new GitPush();
GitCommit gitCommit = new GitCommit();
GitChange change = new GitChange();
ItemContent content = new ItemContent();
content.Content = changeString;
content.ContentType = ItemContentType.RawText;
change.NewContent = new ItemContent();
change.ChangeType = VersionControlChangeType.Edit;
change.Item = item;
List<GitChange> changes = new List<GitChange>();
changes.Add(change);
gitCommit.Changes = changes;
gitCommit.Comment = "updated app.cpp";
GitRefUpdate refUpdate = new GitRefUpdate();
refUpdate.Name = "refs/heads/dev";
refUpdate.OldObjectId = oldObjectId;
List<GitCommit> commits = new List<GitCommit>();
commits.Add(gitCommit);
List<GitRefUpdate> refUpdates = new List<GitRefUpdate>();
refUpdates.Add(refUpdate);
push.Commits = commits;
push.RefUpdates = refUpdates;
GitPush pushed = gitClient.CreatePushAsync(push, repo.Id).Result;
On the last line the debugger gives the exception that parameter "newPush" is not defined.

How do you preview a proration using Stripe.NET?

I'm following the example provided in the Stripe documentation on Previewing Proration using the Stripe.NET library to try to find the amount that will be charged when a customer upgrades from Plan A to Plan B.
However, when I use the code sample in the documentation, I get an error:
UpcomingInvoiceOptions options = new UpcomingInvoiceOptions()
{
CustomerId = "cus_XXXXXXXXXXXXX",
SubscriptionProrationDate = DateTime.UtcNow,
SubscriptionItems = new List<InvoiceSubscriptionItemOptions>()
{
new InvoiceSubscriptionItemOptions()
{
Id = "si_XXXXXXXXXXXXXX", // Current Sub Item
PlanId = "plan_XXXXXXXXXXXX" // New plan
}
}
};
InvoiceService service = new InvoiceService();
var result = service.Upcoming(options);
The last line throws a Stripe.StripeException: You cannot update a subscription item without a subscription.
Turns out options.SubscriptionId is a required field for this action if you don't call service.Get first.
The following code produces the correct results:
UpcomingInvoiceOptions options = new UpcomingInvoiceOptions()
{
CustomerId = "cus_XXXXXXXXXXXXX",
SubscriptionId = "sub_XXXXXXXXXXXX",
SubscriptionProrationDate = DateTime.UtcNow,
SubscriptionItems = new List<InvoiceSubscriptionItemOptions>()
{
new InvoiceSubscriptionItemOptions()
{
Id = "si_XXXXXXXXXXXXXX", // Current Sub Item
PlanId = "plan_XXXXXXXXXXXX" // New plan
}
}
};
InvoiceService service = new InvoiceService();
var result = service.Upcoming(options);

How do I use AWS SDK for .Net to create an image to an instance I have? (AMI)

I have an Amazon EC2 instance and I need to be able to create an AMI (image) from it programmatically. I'm trying the following:
CreateImageRequest rq = new CreateImageRequest();
rq.InstanceId = myInstanceID;
rq.Name = instance.KeyName;
rq.Description = "stam";
rq.NoReboot = true;
IAmazonEC2 ec2;
AmazonEC2Config ec2conf = new AmazonEC2Config();
ec2 = AWSClientFactory.CreateAmazonEC2Client(ec2conf);
// CreateImageResponse imageResp;
Amazon.EC2.Model.CreateImageResponse imageResp = null;
try
{
imageResp = ec2.CreateImage(rq);
}
catch (AmazonServiceException ase)
{
MessageBox.Show(ase.Message);
}
The result is always an AmazonServiceException saying that there is a NameResolutionFailure.
How do I overcome this? I tried different possible "name" possibilities but cannot find the right one.
string amiID = ConfigurationManager.AppSettings[AmazonConstants.AwsImageId];
string keyPairName = ConfigurationManager.AppSettings[AmazonConstants.AwsKeyPair];
List<string> groups = new List<string>() { ConfigurationManager.AppSettings[AmazonConstants.AwsSecurityGroupId] };
var launchRequest = new RunInstancesRequest()
{
ImageId = amiID,
InstanceType = ConfigurationManager.AppSettings[AmazonConstants.AwsInstanceType],
MinCount = 1,
MaxCount = 1,
KeyName = keyPairName,
SecurityGroupIds = groups,
SubnetId = ConfigurationManager.AppSettings[AmazonConstants.AwsSubnetId]
};
RunInstancesResponse runInstancesResponse = amazonEc2client.RunInstances(launchRequest);
RunInstancesResult runInstancesResult = runInstancesResponse.RunInstancesResult;
Reservation reservation = runInstancesResult.Reservation;
Problem eventually solved!
it turned out thyat some codelines were doing things which were already done already and removing this part:
IAmazonEC2 ec2;
AmazonEC2Config ec2conf = new AmazonEC2Config();
ec2 = AWSClientFactory.CreateAmazonEC2Client(ec2conf);
// CreateImageResponse imageResp;
Amazon.EC2.Model.CreateImageResponse imageResp = null;
Made things clearer and no wrong repetitions happened! Now it works!

Amazon Product Advertising API - searching for multiple UPCs

Using the Amazon Product Advertising API I am searching for 2 different UPCs:
// prepare the first ItemSearchRequest
// prepare a second ItemSearchRequest
ItemSearchRequest request1 = new ItemSearchRequest();
request1.SearchIndex = "All";
//request1.Keywords = table.Rows[i].ItemArray[0].ToString();
request1.Keywords="9120031340270";
request1.ItemPage = "1";
request1.ResponseGroup = new string[] { "OfferSummary" };
ItemSearchRequest request2 = new ItemSearchRequest();
request2.SearchIndex = "All";
//request2.Keywords = table.Rows[i+1].ItemArray[0].ToString();
request2.Keywords = "9120031340300";
request2.ItemPage = "1";
request2.ResponseGroup = new string[] { "OfferSummary" };
// batch the two requests together
ItemSearch itemSearch = new ItemSearch();
itemSearch.Request = new ItemSearchRequest[] { request1,request2 };
itemSearch.AWSAccessKeyId = accessKeyId;
// issue the ItemSearch request
ItemSearchResponse response = client.ItemSearch(itemSearch);
foreach (var item in response.Items[0].Item)
{
}
foreach (var item in response.Items[1].Item)
{
}
Is it possible to combine these two separate requests into one request and just have the first request return 2 items by setting keywords = "9120031340256 and 9120031340270"
Does anyone know how to do this?
Do I need to specifically search the UPC?
From looking at the API docs I think you may want to use an ItemLookup if you want to get results for multiple UPCs.
ItemLookup itemLookup = new ItemLookup(){
AssociateTag = "myaffiliatetag-20"
};
itemLookup.AWSAccessKeyId = MY_AWS_ID;
ItemLookupRequest itemLookupRequest = new ItemLookupRequest();
itemLookupRequest.IdTypeSpecified = true;
itemLookupRequest.IdType = ItemLookupRequestIdType.UPC;
itemLookupRequest.ItemId = new String[] { "9120031340300", "9120031340270" };
itemLookupRequest.ResponseGroup = new String[] { "OfferSummary" };
itemLookup.Request = new ItemLookupRequest[] { itemLookupRequest };
ItemLookupResponse response = client.ItemLookup(itemLookup);
foreach(var item in response.Items[0])
{
//Do something...
Console.WriteLine(item.ItemAttributes.Title);
}
That being said, if you are not working with lookups by some ID (UPC, ASIN, etc) your original code of doing batched keyword searches appears to be only way to make multiple keyword searches in a single request (that I could find..). If doing keyword searches you could always make a ItemSearchRequest generator method to cut down on duplicate code when creating multiples.
You can use the following nuget
package.
PM> Install-Package Nager.AmazonProductAdvertising
Example
var authentication = new AmazonAuthentication("accesskey", "secretkey");
var client = new AmazonProductAdvertisingClient(authentication, AmazonEndpoint.US);
var result = await client.GetItemsAsync(new string[] { "B00BYPW00I", "B004MKNBJG" });

Categories