Creating a rule with a constant JSON parameter in AWS CDK (C#) - c#

I'm having trouble with my cloud deployment script for AWS, I've been trying to create a rule that triggers my lambda every 15 minutes and invoke it with a json object. If i were to do this from the console i'd do it like this:
After a long time i figured out how to configure this in code:
var functionInput = new { Command = command };
var input = JsonConvert.SerializeObject(functionInput);
var target = new LambdaFunction(lambda, new LambdaFunctionProps
{
Event = RuleTargetInput.FromObject(input)
});
Or like this:
var target = new LambdaFunction(lambda, new LambdaFunctionProps
{
Event = RuleTargetInput.FromText("{\"Command\" = \"" + command + "\"}")
});
But the constant is not correct on aws, i have tried many different ways but it always turns out like this:
This is not correct Json and can't be parsed back to the class, so I want it to turn out like:
{"Command" = "CLEANUP"}

var inputDict = new Dictionary<string, string>();
inputDict.Add("Command", "CleanUp");
myRule.AddTarget(new Amazon.CDK.AWS.Events.Targets.LambdaFunction(myFunction,
new Amazon.CDK.AWS.Events.Targets.LambdaFunctionProps
{
Event = RuleTargetInput.FromObject(inputDict)
}));

I came here looking for the Python equivalent for the same. Figured out finally - Hope someone find this helpful
from aws_cdk import aws_events as events
from aws_cdk import aws_lambda as lambda_
event_input = {"some_key": "some_value"}
some_lambda = lambda_.Function(
# lambda construct
)
some_rule = events.Rule(
# rule construct
)
some_rule.add_target(
targets.LambdaFunction(
some_lambda,
event=events.RuleTargetInput.from_object(event_input)
)
)

Related

Unable to add lambda target in scheduled rule in AWS cloudwatch

I'm Actually Creating a Sheduled Rule in aws cloudwatch in .net as lambda target but im unable to add my lambda as a target.
what is wrong here
`var region = RegionEndpoint.GetBySystemName("us-east-2");`
`AmazonCloudWatchEventsClient client = new AmazonCloudWatchEventsClient(region);`
`AmazonLambdaClient lambda = new AmazonLambdaClient();`
`var putRuleRequest = new PutRuleRequest`
`{`
` Name = "Rule1check",`
`ScheduleExpression = "cron(0 11 24 * ? 2020)",`
`State = RuleState.ENABLED,`
`};`
`//var putTargetRequest = "EC2 RebootInstances API call`
`var putRuleResponse = client.PutRuleAsync(putRuleRequest);`
`AddPermissionRequest lambdaparam = new AddPermissionRequest`
`{`
` Action = "lambda:InvokeFunction",`
`FunctionName = "stop_ec2",`
`Principal = "events.amazonaws.com",`
`SourceArn = putRuleResponse.ToString(),`
`StatementId = "ID-1"`
`};`
`lambda.AddPermissionAsync(lambdaparam);`
`var putTargetRequest = new PutTargetsRequest`
` {`
`Rule = "Rule1check",`
`Targets =`
`{`
`new Target { Arn = "arn:aws:lambda:us-east-2:394451858625:function:stop_ec2",`
`Id = "myCloudWatchEventsTarget",`
`Input = "{\"region\": \"us-east-2\",\"instances\": \"*******\"}"`
` }`
` }`
`};`
`client.PutTargetsAsync(putTargetRequest);`
You have a few problems here.
SourceArn = putRuleResponse.ToString(). The PutRuleResponse object contains a RuleArn property. That's what you should use. SourceArn = putRuleResponse.RuleArn.
client.PutRuleAsync(putRuleRequest) is an async call, but you aren't awaiting it. As a result you are getting a Task<PutRuleResponse> back, not a PutRuleResponse, and you're getting it before the operation is likely completed.
You aren't awaiting anything, which could be an issue when doing things with dependencies.

DBUP - Run scripts in sequence

I'm trying to run some scripts in sequence to create and seed my database. However it seems like the second script never gets run. Furthermore, I think it's running the first script twice.
public DatabaseFixture()
{
var connectionString = "Server=localhost;User Id = sa;Password=yourStrong(!)Password;Initial Catalog = master";
var createSchemaSqlScriptOptions = new SqlScriptOptions { ScriptType = ScriptType.RunAlways, RunGroupOrder = 1 };
var seedDataSqlScriptOptions = new SqlScriptOptions { ScriptType = ScriptType.RunAlways, RunGroupOrder = 2 };
var upgradeEngineBuilder = DeployChanges.To.SqlDatabase(connectionString, null)
.WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly(), script => script.Contains("0001"), createSchemaSqlScriptOptions)
.WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly(), script => script.Contains("0002"), createSchemaSqlScriptOptions)
.LogToConsole();
var upgrader = upgradeEngineBuilder.Build();
var result = upgrader.PerformUpgrade();
}
Also, all my scripts are embedded sources so I don't think it's that.
Hi, your code shows a object createSchemaSqlScriptOptions duplicate in method WithScriptsEmbeddedInAssembly .
Give it a check.

Google AdWords library doesn't create an access token

I'm trying to make a targetingIdeaService API call to Google AdWords. This is my code so far:
[HttpGet]
public IEnumerable<string> Get()
{
var user = new AdWordsUser();
using (TargetingIdeaService targetingIdeaService = (TargetingIdeaService)user.GetService(AdWordsService.v201802.TargetingIdeaService))
{
// Create selector.
TargetingIdeaSelector selector = new TargetingIdeaSelector();
selector.requestType = RequestType.IDEAS;
selector.ideaType = IdeaType.KEYWORD;
selector.requestedAttributeTypes = new AttributeType[] {
AttributeType.KEYWORD_TEXT,
AttributeType.SEARCH_VOLUME,
AttributeType.AVERAGE_CPC,
AttributeType.COMPETITION,
AttributeType.CATEGORY_PRODUCTS_AND_SERVICES
};
// Set selector paging (required for targeting idea service).
var paging = Paging.Default;
// Create related to query search parameter.
var relatedToQuerySearchParameter =
new RelatedToQuerySearchParameter
{ queries = new String[] { "bakery", "pastries", "birthday cake" } };
var searchParameters = new List<SearchParameter> { relatedToQuerySearchParameter };
var page = new TargetingIdeaPage();
page = targetingIdeaService.get(selector);
return new string[] { "value1", "value2" };
}
}
it looks ok, compiles at last, and so on. But then I went into debug mode. And I saw this:
So as you can see, the variable doesn't have the access token. The other data comes from app.config file.
I am quite certain the keys passed in are correct.
Then the code throws the famous invalid_grand error. In my case, I believe that's because the access token is not being generated. I'm new to AdWords and ASP.NET, so I probably missed something, but I have no idea what.
I used the
docs,
Code Structure instructions, and
code examples to put it all together.
I had my configuration wrong. I had to recreate all the credentials using incognito window. If you have any issues just open a thread here: https://groups.google.com/forum/#!forum/adwords-api

How to create a TensorProto in c#?

This is a snipped of the c# client I created to query the tensorflow server I set up using this tutorial: https://tensorflow.github.io/serving/serving_inception.html
var channel = new Channel("TFServer:9000", ChannelCredentials.Insecure);
var request = new PredictRequest();
request.ModelSpec = new ModelSpec();
request.ModelSpec.Name = "inception";
var imgBuffer = File.ReadAllBytes(#"sample.jpg");
ByteString jpeg = ByteString.CopyFrom(imgBuffer, 0, imgBuffer.Length);
var jpgeproto = new TensorProto();
jpgeproto.StringVal.Add(jpeg);
jpgeproto.Dtype = DataType.DtStringRef;
request.Inputs.Add("images", jpgeproto); // new TensorProto{TensorContent = jpeg});
PredictionClient client = new PredictionClient(channel);
I found out that most classes needed to be generated from proto files using protoc
The only thing which I cant find is how to construct the TensorProto. The error I keep getting is : Additional information: Status(StatusCode=InvalidArgument, Detail="tensor parsing error: images")
There is a sample client (https://github.com/tensorflow/serving/blob/master/tensorflow_serving/example/inception_client.py) byt my Python skills are not sufficient to understand the last bit.
I also implemented that client in another language (Java).
Try to change
jpgeproto.Dtype = DataType.DtStringRef;
to
jpgeproto.Dtype = DataType.DtString;
You may also need to add a tensor shape with a dimension to your tensor proto. Here's my working solution in Java, should be similar in C#:
TensorShapeProto.Dim dim = TensorShapeProto.Dim.newBuilder().setSize(1).build();
TensorShapeProto shape = TensorShapeProto.newBuilder().addDim(dim).build();
TensorProto proto = TensorProto.newBuilder()
.addStringVal(ByteString.copyFrom(imageBytes))
.setTensorShape(shape)
.setDtype(DataType.DT_STRING)
.build();
ModelSpec spec = ModelSpec.newBuilder().setName("inception").build();
PredictRequest r = PredictRequest.newBuilder()
.setModelSpec(spec)
.putInputs("images", proto).build();
PredictResponse response = blockingStub.predict(r);

Amazon Product Advertising API for Asp.net & C#

I want to fetch books using Amazon Product Advertising API with asp.net and C#. All the guides and codes are so confusing as to they don't give you a single method to search the books.
Is there any single stub that can be used to call the service and fetch the books based on the ISBN.
thanks
There's a good sample solution you can download.
http://aws.amazon.com/code/2480?_encoding=UTF8&queryArg=searchQuery&x=0&fromSearch=1&y=0&searchPath=code&searchQuery=Advertising
They give you a class called SignedRequestHelper, then you make a call like this:
public static void Main()
{
SignedRequestHelper helper = new SignedRequestHelper(MY_AWS_ACCESS_KEY_ID, MY_AWS_SECRET_KEY, DESTINATION);
/*
* The helper supports two forms of requests - dictionary form and query string form.
*/
String requestUrl;
String title;
/*
* Here is an ItemLookup example where the request is stored as a dictionary.
*/
IDictionary<string, string> r1 = new Dictionary<string, String>();
r1["Service"] = "AWSECommerceService";
r1["Version"] = "2009-03-31";
r1["Operation"] = "ItemLookup";
r1["ItemId"] = ITEM_ID;
r1["ResponseGroup"] = "Small";
/* Random params for testing */
r1["AnUrl"] = "http://www.amazon.com/books";
r1["AnEmailAddress"] = "foobar#nowhere.com";
r1["AUnicodeString"] = "αβγδεٵٶٷٸٹٺチャーハン叉焼";
r1["Latin1Chars"] = "ĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıIJij";
requestUrl = helper.Sign(r1);
title = FetchTitle(requestUrl);
System.Console.WriteLine("Method 1: ItemLookup Dictionary form.");
System.Console.WriteLine("Title is \"" + title + "\"");
System.Console.WriteLine();
}
You need to use the ItemLookup (like the example) but set the IdType to ISBN. Then set the ItemId to the actual ISBN. Here are the details on ItemLookup:
docs.amazonwebservices.com/AWSECommerceService/latest/DG/index.html?ItemLookup.html
I get this when I use that sample. looks like there has been a change in the API recently.
System.InvalidOperationException: There is an error in the XML document. ---> Sy
stem.InvalidOperationException: <ItemLookupResponse xmlns='http://webservices.am
azon.com/AWSECommerceService/2011-08-01'> was not expected.
To fetch books install this library (Install-Package Nager.AmazonProductAdvertising)
https://www.nuget.org/packages/Nager.AmazonProductAdvertising/
Example:
var authentication = new AmazonAuthentication("accesskey", "secretkey");
var client = new AmazonProductAdvertisingClient(authentication, AmazonEndpoint.UK);
var result = await client.GetItemsAsync("978-0261102385");

Categories