How to publish a message to pubsub emulator using C# - c#

I have managed to create a c# tool to push messages to google cloud pubsub. I can't seem to find anywhere how to pubslish the message to the emulator. From what I've read the following should work by passing in the endpoint to the ClientCreationSettings. But I get a bad request response back from the emulator...
public static async Task PublishMessage()
{
var endpoint = new ServiceEndpoint("localhost", 8085);
ClientCreationSettings clientSettings = new ClientCreationSettings(1, null, null, endpoint);
string message = "hello world";
publisherClient = await PublisherClient.CreateAsync(new TopicName("project1", "topic1"), clientSettings);
await publisherClient.PublishAsync(message);
await publisherClient.ShutdownAsync(TimeSpan.FromSeconds(15));
}
Any insight appreciated

For C#, after starting the emulator with gcloud beta emulators pubsub start --project=PUBSUB_PROJECT_ID [options] and setting the environment variable for PUBSUB_EMULATOR_HOST with a handy CLI as shown here, you need to update your application code as shown in this sample:
string emulatorHostAndPort = Environment.GetEnvironmentVariable("PUBSUB_EMULATOR_HOST");
PublisherServiceApiClient client = new PublisherServiceApiClientBuilder
{
Endpoint = emulatorHostAndPort,
ChannelCredentials = ChannelCredentials.Insecure
}.Build();
// do things using client..

You need to send the PubSubMessage object instead of the string.
var message = new PubsubMessage(){ Data = "hello world" };
Your code should be like:
public static async Task PublishMessage()
{
var clientSettings = new PublisherClient.ClientCreationSettings(
null,
PublisherServiceApiSettings.GetDefault(),
ChannelCredentials.Insecure,
"localhost:8085");
var message = new PubsubMessage(){ Data = "hello world" };
publisherClient = await PublisherClient.CreateAsync(new TopicName("project1", "topic1"), clientSettings);
await publisherClient.PublishAsync(message};
await publisherClient.ShutdownAsync(TimeSpan.FromSeconds(15));
}
Source: https://googleapis.github.io/google-cloud-dotnet/docs/Google.Cloud.PubSub.V1/

Related

Trying to transfer ERC20 token using C# .NET Nethereum package

Can someone help me successfully send ERC20 tokens using the Nethereum package in C# .NET?
I am able to successfully get account balances, but when I try to send, it just sits there....
I am using the Infura.io project api also with the below security:
eth_accounts
eth_call
eth_getBalance
eth_getTransactionReceipt
eth_sendRawTransaction
var client = new EthClient(new RpcUrl("https://mainnet.infura.io/v3/-MyProjectID-"));
Here is the code I am using:
--The call to the transfer method
/* transfer 100 tokens */
var transactionHashTask = client.transferTokens(coinOwnerAddress, coinOwnerPrivateKey, toAddress, contractAddress, 0);
var transactionHash = transactionHashTask.Result.ToString();
lblTransHash.Text = "Transaction hash: " + transactionHash;
--Code that contains the actual method
public async Task<string> transferTokens(string senderAddress, string privateKey, string receiverAddress, string contractAddress, UInt64 tokens)
{
var transactionMessage = new TransferFunction()
{
FromAddress = senderAddress,
To = receiverAddress,
AmountToSend = tokens
};
var transferHandler = web3.Eth.GetContractTransactionHandler<TransferFunction>();
Task<string> transactionHashTask = transferHandler.SendRequestAsync(contractAddress,transactionMessage);
return await transactionHashTask;
}
You are transferring something right? So maybe you have to send extra to account for the gas fees. But i'm no expert. Let me know if you solve this please.
The transfer function doesn't have AmountToSend parameter. It has TokenAmount. So change like below
var transactionMessage = new TransferFunction()
{
To = receiverAddress,
TokenAmount= tokens
};

.net Okta and AWS authentication

Trying authenticate via Okta to access AWS resource using c#/.net. Found this sdk for .net https://github.com/okta/okta-auth-dotnet. Following the examples but do not know how to procced to list all AWS resources. Any help will be appreciated it. (credentials are not real and part of the example)
var client = new AuthenticationClient(new OktaClientConfiguration
{
OktaDomain = "https://{{yourOktaDomain}}",
});
var authnOptions = new AuthenticateOptions()
{
Username = $"darth.vader#imperial-senate.gov",
Password = "D1sturB1ng!",
};
var authnResponse = await authClient.AuthenticateAsync(authnOptions);
Step 1: Install the NuGet package. It will install all the dependencies too.
install package 'Okta.Auth.Sdk.2.0.3'
The code you posted should work with one change (name of the variable). Since you copied the code directly from the GitHub site.
using Okta.Auth.Sdk;
using Okta.Sdk.Abstractions.Configuration;
public static class Program
{
static void Main(string[] args)
{
var client = new AuthenticationClient(new OktaClientConfiguration
{
OktaDomain = "https://{{yourOktaDomain}}",
});
var authnOptions = new AuthenticateOptions()
{
Username = $"darth.vader#imperial-senate.gov",
Password = "D1sturB1ng!",
};
//Asynchronous programming with async and await
//var authnResponse = await client.AuthenticateAsync(authnOptions);
//Synchromous Programming - use Result - which would wait until the task had completed.
var authnResponse = client.AuthenticateAsync(authnOptions).Result;
}
}
I did verify the code. and the AuthenticationStatus was SUCCESS

Sending a message to my bot using the Direct Line v3.0 NuGet package

I am trying to use the Direct Line v3.0 NuGet package to send a message to my bot. I am following the sample on Github, but I'm not getting the behavior I expect.
Here is the sample code:
DirectLineClient client = new DirectLineClient(directLineSecret);
var conversation = await client.Conversations.StartConversationAsync();
while (true)
{
string input = Console.ReadLine().Trim();
if (input.ToLower() == "exit")
{
break;
}
else
{
if (input.Length > 0)
{
Activity userMessage = new Activity
{
From = new ChannelAccount(fromUser),
Text = input,
Type = ActivityTypes.Message
};
await client.Conversations.PostActivityAsync(conversation.ConversationId, userMessage);
}
}
}
And here is my code:
var directLineSecret = "MY_SECRET";
var client = new DirectLineClient(directLineSecret);
var conversation = await client.Conversations.StartConversationAsync();
var testActivity = new Activity
{
From = new ChannelAccount(name: "Proactive-Engine"),
Type = ActivityTypes.Message,
Text = "Hello from the PCE!"
};
var response = await client.Conversations.PostActivityAsync(conversation.ConversationId, testActivity);
I'm logging all the messages my bot receives. I can talk to the bot at its endpoint on Azure using the Bot Emulator, so I have confidence that it's working through the web chat API. However when I run the code above, the bot logs only a conversationUpdate message. The message I send does not get logged, and the value of response is null.
I'm hoping someone can help me find out where I'm going wrong here. Thanks!
Look at how the demo instantiates ChannelAccount:
new ChannelAccount(fromUser)
Then look at the ChannelAccount constructor signature:
public ChannelAccount(string id = null, string name = null)
This means that fromUser is passed as id. But look at how you instantiated ChannelAccount:
new ChannelAccount(name: "Proactive-Engine")
That code doesn't pass an id, it passes a name. So, you can change it like this:
new ChannelAccount("Proactive-Engine")
If your chatbot needs the name, then instantiate like this:
new ChannelAccount("MyChatbotID", "MyChatbotName")

Amazon SMS for single number from c# sdk without creating topic

As per the docs, to send an SMS for single number, we need not create SNS topic.
Clearly, they have given a sample code which shows we can set phone number for publish request method
http://docs.aws.amazon.com/sns/latest/dg/sms_publish-to-phone.html
As per the java docs, I can clearly see that method.
http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/sns/model/PublishRequest.html#setPhoneNumber-java.lang.String-
But, how do we implement same in c#? I couldn't find any method to send an sms without creating an SNS topic.
Can someone guide me how do I send an SMS without creating an SNS topic from C# SDK?
I hope this helps:
var smsAttributes = new Dictionary<string, MessageAttributeValue>();
MessageAttributeValue senderID = new MessageAttributeValue();
senderID.DataType = "String";
senderID.StringValue = "mySenderId";
MessageAttributeValue sMSType = new MessageAttributeValue();
sMSType.DataType = "String";
sMSType.StringValue = "Promotional";
////MessageAttributeValue maxPrice = new MessageAttributeValue();
////maxPrice.DataType = "Number";
////maxPrice.StringValue = "0.1";
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;
smsAttributes.Add("AWS.SNS.SMS.SenderID", senderID);
smsAttributes.Add("AWS.SNS.SMS.SMSType", sMSType);
////smsAttributes.Add("AWS.SNS.SMS.MaxPrice", maxPrice);
PublishRequest publishRequest = new PublishRequest();
publishRequest.Message = vm.Message;
publishRequest.MessageAttributes = smsAttributes;
publishRequest.PhoneNumber = vm.PhoneNumber;
AmazonSimpleNotificationServiceClient client = new AmazonSimpleNotificationServiceClient(vm.AccessKey, vm.SecretKey, config);
AmazonSNSResponse resp = new AmazonSNSResponse();
await client.PublishAsync(publishRequest);
AmazonSNSResponse response = new AmazonSNSResponse();
response.Status = HttpStatusCode.OK.ToString();
response.Message = "Success";
return response;
I believe you'll find the answer here: https://forums.aws.amazon.com/thread.jspa?threadID=250183&tstart=0
Basically what is saying and quote: "...PhoneNumber property was added in version 3.1.1.0 of AWSSDK.SimpleNotificationService..."
I haven't put example code since the PhoneNumber property is what is missing in the request, the rest should work as similar to Java Example :D.
See Publish(PublishRequest).
Amazon.SimpleNotificationService.Model.PublishRequest has a PhoneNumber property, used for setting the number when sending a direct SMS message.

Can't receive any notification from AmazonSNS

I am not sure why I can't receive any notification from AmazonSNS. Am I missing something in my code? I am using the latest version of AWSSDK for Windows Store App by the way.
Here's my code so far.
d("init AmazonSimpleNotificationServiceClient");
AmazonSimpleNotificationServiceClient sns = new AmazonSimpleNotificationServiceClient("secret", "secret", RegionEndpoint.EUWest1);
d("get notification channel uri");
string channel = string.Empty;
var channelOperation = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
channelOperation.PushNotificationReceived += ChannelOperation_PushNotificationReceived;
d("creating platform endpoint request");
CreatePlatformEndpointRequest epReq = new CreatePlatformEndpointRequest();
epReq.PlatformApplicationArn = "arn:aws:sns:eu-west-1:X413XXXX310X:app/WNS/Device";
d("token: " + channelOperation.Uri.ToString());
epReq.Token = channelOperation.Uri.ToString();
d("creat plateform endpoint");
CreatePlatformEndpointResponse epRes = await sns.CreatePlatformEndpointAsync(epReq);
d("endpoint arn: " + epRes.EndpointArn);
d("subscribe to topic");
SubscribeResponse subsResp = await sns.SubscribeAsync(new SubscribeRequest()
{
TopicArn = "arn:aws:sns:eu-west-1:X413XXXX310X:Topic",
Protocol = "application",
Endpoint = epRes.EndpointArn
});
private void ChannelOperation_PushNotificationReceived(Windows.Networking.PushNotifications.PushNotificationChannel sender, Windows.Networking.PushNotifications.PushNotificationReceivedEventArgs args)
{
Debug.WriteLine("receiving something");
}
this is actually working after enabling Toast on .appxmanifest
I get notified everytime I publish a RAW message from Amazon SNS console. I am not receiving a JSON though which I actually need.

Categories

Resources