Amazon Simple Notification Service AWSSDK C# - S.O.S - c#

I am trying to publish with Amazon's AWSSDK for C# and the Simple Notification Service.
There are no samples that come with the SDK and there are no samples anywhere on the web I could find after 2 hours of Googling. I came up with this but it is throwing an exception that yields no more information than the single string, "TopicARN" - no inner exception - nuffin!
If anyone has successfully sent a message with SNS via C# using the AWSSDK I would love to see even the most rudimentary working example. I am using the latest SDK 1.5x
Here's the code:
string resourceName = "arn:aws:sns:us-east-1:xxxxxxxxxxxx:StackOverFlowStub";
AmazonSimpleNotificationServiceClient snsclient = new AmazonSimpleNotificationServiceClient(accesskey,secretkey);
AddPermissionRequest permissionRequest = new AddPermissionRequest()
.WithActionNames("Publish")
.WithActionNames(accesskey)
.WithActionNames("PrincipleAllowControl")
.WithActionNames(resourceName);
snsclient.AddPermission(permissionRequest);
PublishRequest pr = new PublishRequest();
pr.WithMessage("Test Msg");
pr.WithTopicArn(resourceName);
pr.WithSubject("Test Subject");
snsclient.Publish(pr);

Here is a sample that creates a topic, sets a topic display name, subscribes an email address to the topic, sends a message and deletes the topic. Note that there are two spots where you should wait/check your email before continuing. Client is the client instance, topicName is an arbitrary topic name.
// Create topic
string topicArn = client.CreateTopic(new CreateTopicRequest
{
Name = topicName
}).CreateTopicResult.TopicArn;
// Set display name to a friendly value
client.SetTopicAttributes(new SetTopicAttributesRequest
{
TopicArn = topicArn,
AttributeName = "DisplayName",
AttributeValue = "StackOverflow Sample Notifications"
});
// Subscribe an endpoint - in this case, an email address
client.Subscribe(new SubscribeRequest
{
TopicArn = topicArn,
Protocol = "email",
Endpoint = "sample#example.com"
});
// When using email, recipient must confirm subscription
Console.WriteLine("Please check your email and press enter when you are subscribed...");
Console.ReadLine();
// Publish message
client.Publish(new PublishRequest
{
Subject = "Test",
Message = "Testing testing 1 2 3",
TopicArn = topicArn
});
// Verify email receieved
Console.WriteLine("Please check your email and press enter when you receive the message...");
Console.ReadLine();
// Delete topic
client.DeleteTopic(new DeleteTopicRequest
{
TopicArn = topicArn
});

Related

GMB API - Unable to Get/Updated Google Business Account Pub/Sub Notification Settings

I am trying to use Google My Business API C# Client Library: https://developers.google.com/my-business/samples/ in order to get real-time notifications for Location and Reviews. I have followed the steps provided at: https://developers.google.com/my-business/content/notification-setup#get_started . But I am stuck at point 5) Account.updateNotifications.
I am receiving this error: "{Parameter validation failed for \"name\"}"
I am able to use the same "name" parameter to fetch the Account, Locations, Review etc. successfully, but it's not working with Notifications. I am attaching the code below.
GMBServiceInit();
string name = "accounts/1234567890132456"
var notification = new Notifications
{
TopicName = "projects/gmbproject/topics/notification_topic",
NotificationTypes = new List<string>
{
"NEW_REVIEW",
}
};
//Get Notifications Settings
var response = await GMBService.Accounts.GetNotifications(name).ExecuteAsync();
//Update Notifications Settings
var updateNotificationRequest = GMBService.Accounts.UpdateNotifications(notification, name);
var updateNotificationReponse = await updateNotificationRequest.ExecuteAsync();
If someone had this issue, please help me to figure out this issue. Thanks!
Found the solution.
I am using the name as:
string name = "accounts/1234567890132456"
I should be using:
string name = "accounts/1234567890132456/notifications"

Sendgrid API: The provided authorization grant is invalid, expired, or revoked

I've just created a sendgrid account. Then I went to settings=>API Keys
and clicked on "Create API Key" and gave any possible permission.
Then I've created a c# project, added nuget packages and put my write the hello world code from here
public async Task HelloEmail()
{
dynamic sg = new SendGrid.SendGridAPIClient("XXX-XXXXXXXXXXXXXXXXXX", "https://api.sendgrid.com");
Email from = new Email("MY#Email.com");
String subject = "Hello World from the SendGrid CSharp Library";
Email to = new Email("test#example.com");
Content content = new Content("text/plain", "Textual content");
Mail mail = new Mail(from, subject, to, content);
Email email = new Email("test2#example.com");
mail.Personalization[0].AddTo(email);
dynamic response = await sg.client.mail.send.post(requestBody: mail.Get());
var x=response.StatusCode;
var y = response.Body.ReadAsStringAsync().Result;
var z = response.Headers.ToString();
}
But I get
Unauthorized =>
"{\"errors\":[{\"message\":\"The provided authorization grant is invalid, expired, or revoked\",\"field\":null,\"help\":null}]}"
In the example, they got the API key from the EnvironmentVariableTarget.User is it related to that?
string apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY", EnvironmentVariableTarget.User);
dynamic sg = new SendGridAPIClient(apiKey);
*The problem is that no one reads messages when creating a key, also Microsoft chooses to show us "API Key ID" which is worst name ever
It is not a duplicate because although the reason was the same, no one would guess it since in c# we use a nuget library, not the api.
Something is wrong with your API key. Check this answer, generate a new key, and double check your permissions.
You also don't need to specify the URL in your SendGrid.SendGridAPIClient. I'd remove that line to reduce hardcoded values.
Put key directly , do not use System.getenv(KEY)
String key = "YOUR KEY";
SendGrid sg = new SendGrid(key);

Sendgrid C# bulk email X-SMTPAPI header not working

I am trying to send email with SendGrid to multiple recipients in an ASP.Net C# web application
According to the SendGrid documentation I need to add X-SMTPAPI header to my message in JSON formatted string. I do so, for first check I just added a hand-typed string before building my json email list progamatically here is my code:
string header = "{\"to\": [\"emailaddress2\",\"emailaddress3\"], \"sub\": { \"%name%\": [\"Ben\",\"Joe\"]},\"filters\": { \"footer\": { \"settings\": { \"enable\": 1,\"text/plain\": \"Thank you for your business\"}}}}";
string header2 = Regex.Replace(header, "(.{72})", "$1" + Environment.NewLine);
var myMessage3 = new SendGridMessage();
myMessage3.From = new MailAddress("emailaddress1", "FromName");
myMessage3.Headers.Add("X-SMTPAPI", header2);
myMessage3.AddTo("emailaddress4");
myMessage3.Subject = "Test subject";
myMessage3.Html = "Test message";
myMessage3.EnableClickTracking(true);
// Create credentials, specifying your user name and password.
var credentials = new NetworkCredential(ConfigurationManager.AppSettings["xxxxx"], ConfigurationManager.AppSettings["xxxxx"]);
// Create an Web transport for sending email.
var transportWeb = new Web(credentials);
// Send the email, which returns an awaitable task.
transportWeb.DeliverAsync(myMessage3);
But it just seems to ignore my header, and sends the email to the one email "emailaddress4" used in "addto".
According the documentation if the header JSON is parsed wrongly, then SendGrid sends an email about the error to the email address set in "FROM" field, but I get no email about any error.
Anyone got any idea?
For me using the latest 9.x c# library the only way I could solve this was by using the MailHelper static functions like this:
var client = new SendGridClient(HttpClient, new SendGridClientOptions { ApiKey = _sendGridApiKey, HttpErrorAsException = true });
SendGridMessage mailMsg;
var recipients = to.Split(',').Select((email) => new EmailAddress(email)).ToList();
if (recipients.Count() > 1)
{
mailMsg = MailHelper.CreateSingleEmailToMultipleRecipients(
new EmailAddress(from),
recipients,
subject,
"",
body);
}
else
{
mailMsg = MailHelper.CreateSingleEmail(
new EmailAddress(from),
recipients.First(),
subject,
"",
body);
}
if (attachment != null)
{
mailMsg.AddAttachment(attachment.Name,
attachment.ContentStream.ToBase64(),
attachment.ContentType.MediaType);
}
var response = await client.SendEmailAsync(mailMsg).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
_log.Trace($"'{subject}' email to '{to}' queued");
return true;
}
else {
throw new HttpRequestException($"'{subject}' email to '{to}' not queued");
}
I'm not sure why you wouldn't recieve any errors at your FROM address, but your JSON contains the following flaws:
, near the end makes the string invalid json
spaces around the first % in %name%, that might make sendgrid think it's an invalid substitution tag
if you use the X-SMTPAPI header to specify multiple recipients, you are not supposed to add a standard SMTP TO using AddTo().
Besides that, you didn't wrap the header at 72 characters (see the example in the documentation).
I figured that however the X-SMTPAPI documentation talks about passing the header as JSON, the API itself expects it as a parameter, containing Ienumerable string. So the working code is:
var myMessage3 = new SendGridMessage();
myMessage3.From = new MailAddress("email4#email.com", "Test Sender");
myMessage3.AddTo("email2#email.com");
myMessage3.Subject = "Új klubkártya regisztrálva";
myMessage3.Html = "Teszt üzenet";
myMessage3.EnableClickTracking(true);
/* SMTP API
* ===================================================*/
// Recipients
var addresses = new[]{
"email2#email.com", "email3#email.com"
};
//string check = string.Join(",", addresses);
myMessage3.Header.SetTo(addresses);
// Create credentials, specifying your user name and password.
var credentials = new NetworkCredential(ConfigurationManager.AppSettings["xxxxxxx"], ConfigurationManager.AppSettings["xxxxxxxxx"]);
// Create an Web transport for sending email.
var transportWeb = new Web(credentials);
// Send the email, which returns an awaitable task.
transportWeb.DeliverAsync(myMessage3);

Microsoft.Bot.Connector - The To Address refers to {} which is not a known

I'm developing a bot to be used with the email channel (Office 365).
I'm struggling to implement a "Starting a new conversation with the user", i.e. the bot should initiate conversation with the user(s) after receiving certain triggers.
I'm referencing the example available on http://docs.botframework.com/.
var connector = new ConnectorClient();
Message newMessage = new Message();
newMessage.From = new ChannelAccount() { Address = "[email the bot is registered with]", Name = "Awesome Bot", ChannelId = "email", IsBot = true };
newMessage.To = new ChannelAccount() { Address = user.Email, Name = $"{ user.FirstName } {user.LastName}", ChannelId = "email", IsBot = false };
newMessage.Text = message;
newMessage.Language = "en";
connector.Messages.SendMessage(newMessage);
The bot is live in Azure and registered with the framework.
When I invoke the above code, looks like the connector is sending a request to api.botframework.com, but receives a status code 404 back. I'm also seeing the following error message:
The To Address refers to [user email] which is not a known
It sounds like the error is cut off. I'm not sure what I'm doing wrong here.
We were worried about spammers abusing the ability to send email through our servers, so we limited the ability to send a message to people who are not already in the conversation or users of the system. Our thoughts are that we will enable this functionality as part of being approved in our directory or as for paid clients.

Set up a subscription for messages with no matching filter in Azure Service Bus (on-premise)

I'm using Azure Service Bus 1.1 (the on premise version)
I'm trying to set up a subscription that will receive messages that have not been filtered into any other existing subscription.
I have 3 console apps, one that creates topics and subscriptions, one that sends messages to the topic, and one that receives messages from a subscription.
I'm also using the Service Bus Explorer (V2.1) to see what is happening with my console apps.
I have tried setting up the topic as described on this page and this page which uses a MatchNoneFilterExpression but the example code does not compile(?) ie the FilterAction and FilterExpression properties are not in the RuleDescription class
RuleDescription matchNoneRule = new RuleDescription()
{
FilterAction = new SqlFilterAction("set defer = 'yes';"),
FilterExpression = new MatchNoneFilterExpression()
};
The RuleDescription class I'm using is in v2.1.0.0 of the Microsoft.ServiceBus.dll
It has the following properties available,
How do I send a message that matches no other filters to a particular subscription?
From this page which suggests setting the EnableFilteringMessagesBeforePublishing property on the topic.
It then suggests that on sending a message to this topic a message will trigger the NoMatchingSubscriptionException
I'm creating my topic with this code
var myTopic = new TopicDescription(topicName)
{
EnableFilteringMessagesBeforePublishing = true
};
namespaceManager.CreateTopic(myTopic);
I'm sending a message to the topic that doesn't match any filters and I can catch the exception and potentially resend the message with a property that does match a filter, e.g.:
try
{
topicClient.Send(message);
Console.WriteLine(string.Format("Message sent: Id = {0}, Body = {1}", message.MessageId, message.GetBody<string>()));
}
catch (NoMatchingSubscriptionException ex)
{
string messageBody = message.GetBody<string>();
BrokeredMessage msg = new BrokeredMessage(messageBody);
msg.Properties.Add("Filter", "NoMatch");
foreach (var prop in message.Properties)
{
msg.Properties.Add(prop.Key, prop.Value);
}
topicClient.Send(msg);
Console.WriteLine("\n NoMatchingSubscriptionException - message resent to NoMatchingSubscription");
Console.WriteLine(string.Format("Message sent: Id = {0}, Body = {1}", msg.MessageId, msg.GetBody<string>()));
}

Categories