Unable to add lambda target in scheduled rule in AWS cloudwatch - c#

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.

Related

Nethereuem SendTransactionAsync from my C# Web API fails with transaction type not supported: eth_sendRawTransaction

I'm working on integrating Nethereum into my .NET 5 C# API and can do read queries against my chosen blockchain (BSC), but cannot get a SendTransactionAsync or SendRequestAsync to successfully execute. I'm consistently getting the following exception:
Nethereum.JsonRpc.Client.RpcResponseException: 'transaction type not supported: eth_sendRawTransaction'.
Here are code snippets of what I have tried:
// Setup
var account = new Account(privateKey, chainId);
var rpcUrl = "https://data-seed-prebsc-2-s2.binance.org:8545/";
var client = new RpcClient(new Uri(rpcUrl));
var web3 = new Web3(account, client);
var mediaTokenAddress = "0x1E4d1BFDa5d55C2176E9E3e8367BAe720525a8e0";
var mtSvc = new MediaTokenService(web3, mediaTokenAddress);
var mintMsg = new MintNftFunction
{
FromAddress = account.Address,
Recipient = "REDACTED",
MetadataHash = "TestMetaDataHash",
MediaHash = "TestMediaHash",
SeasonId = 1
};
// Attempt #1: Using C# classes generated by the Nethereum CodeGen library
var txReceipt = await mtSvc.MintNftRequestAndWaitForReceiptAsync(mintMsg);
// Attempt #2
var txHandler = web3.Eth.GetContractTransactionHandler<MintNftFunction>();
var signedTx = await txHandler.SignTransactionAsync(mediaTokenAddress, mintMsg);
var txReceipt = await web3.Eth.Transactions.SendTransaction.SendRequestAsync(signedTx);
// Attempt #3
var txInput = mintMsg.CreateTransactionInput(mediaTokenAddress);
var txReceipt = await web3.Eth.TransactionManager.SendTransactionAsync(txInput);
Is there a configuration step I'm missing? Any help is appreciated!
EDIT: I want to call a contract method that will change values within the contract, rather than sending currency. So I need help figuring out how to do that.
For those that come across this issue, I resolved it by setting the following flag on my web3 instance:
web3.TransactionManager.UseLegacyAsDefault = true;
If there is a way to do what I need without setting this flag, please feel free to leave a comment.
Here is an example of how I do this with Nethereum
var web3 = new Nethereum.Web3.Web3("YOUR_NODE_ADDRESS");
var privateKey = "someprivatekey";
var senderAddress = "0x..."; // put actual sender address
var receiveAddress = "0x..."; //put actual receiver address
var txCount = await web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(senderAddress);
double sendAmount = 5.09540000; //this is ETH
var amountInWei = Web3.Convert.ToWei(sendAmount);
//600 GWEI = 0.000000600
//60 GWEI = 0.000000060
var gwei = 147; // this is 0.000000147 ETH. You will want to calculate this based on network fees
var gasPrice = Web3.Convert.ToWei(0.000000001 * gwei);
var gasLimit = Web3.Convert.ToWei(0.000000000000021);
var encoded = Web3.OfflineTransactionSigner.SignTransaction(privateKey, receiveAddress, amountInWei, txCount.Value, gasPrice, gasLimit);
//This is what prompts the transactions
Web3.OfflineTransactionSigner.GetSenderAddress(encoded).Dump();
//TX Returns from this action
var txId = await web3.Eth.Transactions.SendRawTransaction.SendRequestAsync("0x" + encoded);
//Dump out the TX if successful
txId.Dump();
I've used this many times and it has worked for me just fine.

Creating a rule with a constant JSON parameter in AWS CDK (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)
)
)

outputLocation is not a valid S3 path. Athena Exception

I am trying to execute athena query using c# athena driver.
Amazon.Athena.Model.ResultConfiguration resultConfig = new Amazon.Athena.Model.ResultConfiguration();
resultConfig.OutputLocation = "https://s3.us-east-2.amazonaws.com/testbucket/one/2018-02-06/";
//other inputs i have tried
//"s3://testbucket/one/2018-02-06/"
//testbucket
//Populate the request object
Amazon.Athena.Model.StartQueryExecutionRequest queryExec = new Amazon.Athena.Model.StartQueryExecutionRequest();
queryExec.QueryString = query.QueryString;
queryExec.QueryExecutionContext = queryExecutionContext;
queryExec.ResultConfiguration = resultConfig;
StartQueryExecutionResponse athenaResponse = athenaClient.StartQueryExecution(queryExec);//throws exception
Exception for different cases:
outputLocation is not a valid S3 path. Provided https://s3.us-east-2.amazonaws.com/testbucket/one/2018-02-06/
Unable to verify/create output bucket testbucket. Provided s3://testbucket/one/2018-02-06/
Unable to verify/create output bucket testbucket. Provided testbucket
Can someone help me out with the right s3 format?
Thanks in advance.
The output location needs to be in the following format:
s3://{bucketname}/{path}
In your case this would lead to the following location:
resultConfig.OutputLocation = "s3://testbucket/one/2018-02-06/";
Amazon.Athena.AmazonAthenaClient _client = new Amazon.Athena.AmazonAthenaClient(AwsAccessKeyId, AwsSecretAccessKey, EndPoint);
Amazon.Athena.Model.ResultConfiguration resultConfig = new Amazon.Athena.Model.ResultConfiguration();
resultConfig.OutputLocation = "s3://"+BucketName+"/key1/";
string query = "SELECT * FROM copalanadev.logs";
//Populate the request object
Amazon.Athena.Model.StartQueryExecutionRequest queryExec = new Amazon.Athena.Model.StartQueryExecutionRequest();
queryExec.QueryString = query;
//queryExec.QueryExecutionContext = queryExecutionContext;
queryExec.ResultConfiguration = resultConfig;
StartQueryExecutionResponse athenaResponse = _client.StartQueryExecution(queryExec);//throws exception

How to create New EPT by using CSOM

I try to create a new EPT (project server 2013) using C# CSOM library.
But It has following error occurred.
"PJClientCallableException: EnterpriseProjectTypeInvalidCreatePDPUid"
Couple of article tell to change the "IsCreate=true". But it does not success for me. Here is the code what I have done.
public void CreateEnterpriseProjectType(Guid eptGuid, string eptName, string eptDescription)
{
ProjectContext pwaContext = new ProjectContext(this.PWA_URL);
EnterpriseProjectTypeCreationInformation eptData = new EnterpriseProjectTypeCreationInformation();
eptData.Id = eptGuid;
eptData.Name = eptName;
eptData.Description = eptDescription;
eptData.IsDefault = false;
eptData.IsManaged = true;
eptData.WorkspaceTemplateName = "PROJECTSITE#0";
eptData.ProjectPlanTemplateId = Guid.Empty;
eptData.WorkflowAssociationId = Guid.Empty;
eptData.Order = 4;
List<ProjectDetailPageCreationInformation> projectDetailPages = new
List<ProjectDetailPageCreationInformation>() {
new ProjectDetailPageCreationInformation() {
Id = pwaContext.ProjectDetailPages[1].Id, IsCreate = true }
};
eptData.ProjectDetailPages = projectDetailPages;
pwaContext.Load(pwaContext.EnterpriseProjectTypes);
pwaContext.ExecuteQuery();
EnterpriseProjectType newEpt = pwaContext.EnterpriseProjectTypes.Add(eptData);
pwaContext.EnterpriseProjectTypes.Update();
pwaContext.ExecuteQuery();
}
Can anyone explain the issue or provide the working code part.
I would like to suggest the following:
Define an enterprise project type:
string basicEpt = "Enterprise Project"; // Basic enterprise project type.
int timeoutSeconds = 10; // The maximum wait time for a queue job, in seconds.
And then, when you create the new project, work like this:
ProjectCreationInformation newProj = new ProjectCreationInformation();
newProj.Id = Guid.NewGuid();
newProj.Name = "Project Name";
newProj.Description = "Test creating a project with CSOM";
newProj.Start = DateTime.Today.Date;
// Setting the EPT GUID is optional. If no EPT is specified, Project Server
// uses the default EPT.
newProj.EnterpriseProjectTypeId = GetEptUid(basicEpt);
PublishedProject newPublishedProj = projContext.Projects.Add(newProj);
QueueJob qJob = projContext.Projects.Update();
// Calling Load and ExecuteQuery for the queue job is optional.
// projContext.Load(qJob);
// projContext.ExecuteQuery();
JobState jobState = projContext.WaitForQueue(qJob, timeoutSeconds);
When the last line of that piece of code ends, the project must be created and published in order to define tasks or whatever.
I don't know what is happening to your code, seems great.
Hope it helps to you,

Unable to create Azure WebSpace

I'm trying to create a new Website using the nuget package Microsoft.WindowsAzure.Management.WebSites (Version 3.0.0)
This tutorial has been helpful (even though its Java):
http://azure.microsoft.com/fi-fi/documentation/articles/java-create-azure-website-using-java-sdk/
except it suggests to use the WebSpaceNames.WestUSWebSpace constant.
var hostingPlanParams = new WebHostingPlanCreateParameters
{
Name = this.webhostingPlanName,
NumberOfWorkers = 1,
SKU = SkuOptions.Free,
WorkerSize = WorkerSizeOptions.Small
};
var result = new WebSiteManagementClient(this.Credentials)
.WebHostingPlans
.CreateAsync(WebSpaceNames.WestUSWebSpace, hostingPlanParams, CancellationToken.None)
.Result
This will result in an exception: NotFound: Cannot find WebSpace with name westuswebspace.
I actually want to create a custom WebSpace.
Except I can't find any method for it. See MSDN
So the only way I can make this work is using an existing WebSpace, that had created through the manage.windowsazure.com site. Which defeats the whole purpose of automating this.
The only Create[...] Method on IWebSpaceOperations is CreatePublishingUserAsync which I have tried running this as well but it results in an exception This operation is not supported for subscriptions that have co-admins. Which is pretty annoying in itself, doesn't make much sense to me, but is not really the core of my question.
I resolved this by using the prerelease package: PM> Install-Package Microsoft.Azure.Management.WebSites -Pre
Which works perfectly well. Except that it's only a pre-release of cause
// Create Web Hosting Plan
var hostingPlanParams = new WebHostingPlanCreateOrUpdateParameters
{
WebHostingPlan = new WebHostingPlan()
{
Name = "WebHostingPlanName",
Location = "Australia Southeast",
Properties = new WebHostingPlanProperties
{
NumberOfWorkers = 1,
Sku = SkuOptions.Standard,
WorkerSize = WorkerSizeOptions.Small
}
},
};
var result = this.ManagementContext.WebSiteManagementClient.WebHostingPlans.CreateOrUpdateAsync(
"ResourceGroupName",
"WebHostingPlanName",
CancellationToken.None).Result;
// Create Website
var websiteParams = new WebSiteCreateOrUpdateParameters
{
WebSite = new WebSiteBase
{
Location = "Australia Southeast",
Name = "WebSiteName",
Properties = new WebSiteBaseProperties
{
ServerFarm = "WebHostingPlanName"
}
}
};
var siteResult = this.ManagementContext.WebSiteManagementClient.WebSites.CreateOrUpdateAsync(
"ResourceGroupName",
"WebSiteName",
null,
websiteParams,
CancellationToken.None).Result;
If you want to use deployment slots you have to take this under consideration:
https://github.com/Azure/azure-sdk-for-net/issues/1088

Categories