how to get AWS SMS publish results in code - c#

I've scoured the AWS documentation to see if there is a a way to get the SMS delivery log via code, but i'm at a miss, I can get the logs via cloud watch but I want to get them in code so if there is a failure ( like delivery.providerResponse
Unknown error attempting to reach phone) I can dequeue the number
this is my code for sending texts, it gets a response code OK all the time even if i've hit my credit limit, the number isnt valid. Viewing failures in the console is great and all, but i want to update my queue programmatically based on success/failure
Regex rgx = new Regex(#"^(07\d{8,12}|447\d{7,11})$");
foreach (var item in accountTextDatas)
{
if (rgx.IsMatch(item.Phone1))
{
item.Phone1 = ReplaceFirst(item.Phone1, "0", "+44");
}
await Task.Delay(2000);
var request = new PublishRequest()
{
Message = $"words go here"
PhoneNumber = item.Phone1,
};
var response = await client.PublishAsync(request);
context.Logger.LogInformation("Response Code to " + item.Phone1 + " " + response.HttpStatusCode);
}

You can fetch the delivery status logs in your code through the CloudWatch API
The CLI equivalent would be something like:
aws logs describe-log-streams --log-group-name sns/$REGION/$ACCOUNT_ID/DirectPublishToPhoneNumber/Failure
{
"logStreams": [
{
"logStreamName": "SOME_LOG_STREAM_NAME", ...
aws logs get-log-events --log-group-name sns/$REGION/$ACCOUNT_ID/DirectPublishToPhoneNumber/Failure --log-stream-name SOME_LOG_STREAM_NAME
{
"events": [
{
"timestamp": 1650659779468,
"message": "{\"notification\":{\"messageId\": ...

Related

Notification on change of data in Xamarin/C#

Hi so I've implemented a method based on this answer:
How to get notification in xamarin forms on firebase data change?
But I'm having trouble getting it working.
Here's my code:
void DoFirebaseObserve()
{
var firebase = new FirebaseClient(Constants.FirebaseProjectUrl);
firebase.Child("RegisterUserTable").AsObservable<RegisterUser>().Subscribe(obs =>
{
switch (obs.EventType)
{
case Firebase.Database.Streaming.FirebaseEventType.InsertOrUpdate:
Console.WriteLine("InsertOrUpdate");
break;
case Firebase.Database.Streaming.FirebaseEventType.Delete:
Console.WriteLine("Delete");
break;
default:
break;
}
});
}
I call this code in the OnAppearing method of my app's home page. I've tried with and without the while (true) {} condition.
When I add, update or delete a record in firebase, nothing happens in my application. The writelines are never called.
Any help would be appreciated. Thanks.
So I worked out how to do it through using Google Cloud Functions in the Firebase console.
Step 1. Set up FCM in your .Net code
Follow this tutorial:
https://learn.microsoft.com/en-us/xamarin/android/data-cloud/google-messaging/remote-notifications-with-fcm?tabs=macos
Once you have got your FCM token from that device, you can add it to your realtime database (I did this myself in the firebase console manually for testing).
Step 2. Set up Cloud Functions
Follow this tutorial:
https://www.youtube.com/watch?v=bpI3Bbhlcas&t=1104s&ab_channel=uNicoDev
Step 3. Create a function to send the message
You can use this node.js code in your cloud functions to send up to 500 devices:
// Create a list containing up to 500 registration tokens.
// These registration tokens come from the client FCM SDKs.
const registrationTokens = [
'YOUR_REGISTRATION_TOKEN_1',
// …
'YOUR_REGISTRATION_TOKEN_N',
];
const message = {
data: {score: '850', time: '2:45'},
tokens: registrationTokens,
};
admin.messaging().sendMulticast(message)
.then((response) => {
console.log(response.successCount + ' messages were sent successfully');
});
Source: https://firebase.google.com/docs/cloud-messaging/send-message#node.js_1
Code Example
Some of my code to help you get an idea of how to go about doing something like this. Can't guarantee this is the optimal method but it works.
const reference = "JourneyTbl/{journeyId}";
// newJourneyAdded | listener method | Send push notif when new journey created:
exports.newJourneyAdded = functions.database.ref(reference)
.onCreate((event, context) => {
// where fcm tokens are stored:
const refNotifications = "NotificationTbl";
// get ref to RegNotTable:
const refFcm = admin.database().ref(refNotifications);
// array to hold all fcms from table:
const allFcms = [];
// get value of "NotificationTbl":
refFcm.on("value", (snapshot) => {
// check if there's any children:
if (snapshot.hasChildren()) {
// loop through children:
snapshot.forEach((element) => {
// stringify the data:
const asString = JSON.stringify(element);
// parse that as a JSON object:
const asJson = JSON.parse(asString);
// add fcm token to array:
allFcms.push(asJson.fcm);
});
}
// if array contains something:
if (allFcms.length > 0) {
// construct message to send:
const msg = {
notification: {
title: "Notification Title goes here",
body: "Notification Body goes here ",
},
tokens: allFcms, // pass the tokens
};
// send that message:
admin.messaging().sendMulticast(msg)
.then((response) => {
console.log(response.successCount + " mgs were sent sfly");
});
} else {
console.log("No devices in FCM tokens list");
}
});
return "ok";
});

Keep getting "Exchange Web Services are not currently available for this request because" error?

We have an application that logs in as an exchange user and does simple tasks like delete / saves / sends emails etc. I'm seeing a lot of two errors in our Splunk report:
"Exchange Web Services are not currently available for this request because none of the Client Access Servers in the destination site could process the request"
and
"Problem deleting email [ item id: (item ID string) ] - The specified object was not found in the store., The process failed to get the correct properties."
I've read that it's important to include:
service.HttpHeaders.Add("X-AnchorMailbox", MailboxToAccess);
when impersonating users and that that may be the issue, but what about when you are just logging in as a user?
Here's the code where we set up the exchange service:
public ExchangeServiceClient(ILog logger, IContentTypeHelper contentTypeHelper)
{
_logger = logger;
_contentTypeHelper = contentTypeHelper;
if (EvidenceSettings.Default.AppEmailUserName.Equals("Windows Credentials", StringComparison.OrdinalIgnoreCase))
{
_exchangeService = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
_exchangeService.Url = new Uri(PartnerEvidenceSettings.Default.ExchangeServiceAddress);
}
else
{
_exchangeService = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
_exchangeService.Url = new Uri(EvidenceSettings.Default.ExchangeServiceAddress);
_exchangeService.Credentials = new WebCredentials(EvidenceSettings.Default.AppEmailUserName, EvidenceSettings.Default.AppEmailPassword);
_exchangeService.TraceEnabled = true;
_exchangeService.UseDefaultCredentials = false;
}
}
And here's an example of when we use the service (just a single example, but all pretty similar functions):
public void DeleteMailMessage(string identifier)
{
// If this email was an attachment in another email, then only delete the container email
if (identifier != null)
{
try
{
var ids = new[] { new ItemId(identifier) };
var responseCollection = _exchangeService.DeleteItems(ids, DeleteMode.MoveToDeletedItems, null, null);
foreach (var response in responseCollection)
{
if (response.Result == ServiceResult.Error)
{
_logger.Error($"Problem deleting email [ item id: {identifier} ] - {response.ErrorMessage}");
}
}
}
catch (Exception ex)
{
_logger.Error($"Error deleting email [ item id: {identifier} ]", ex);
}
}
}
My question is, do we need to be including the HTTPHEADERS, or is something else causing this issue? If it's not that, I'm not quite sure what could be causing this error.
Those two error are different and generally not related
"Exchange Web Services are not currently available for this request because none of the Client Access Servers in the destination site could process the request"
Generally this is a routing error so yes you should always included the X-AnchorMailbox header no matter if its impersonation or not. (Eg if you look at any Microsoft Mail client Outlook,OWA, Outlook Mobile you will always see these headers).
"Problem deleting email [ item id: (item ID string) ] - The specified object was not found in the store., The process failed to get the correct properties."
This is usually an Item error or permissions error eg no access to the Mailbox itself or your trying to access something like the Audit folder in the mailbox etc. It can also mean the Item in question has moved in the Mailbox.

Proper Way To See If Square Checkout Process Completed

I am currently working on a C# Windows Form project that requires the user to pay prior to any processing taking place. I am using the Square .Net SDK for payment processing and have successfully managed to get a payment through to the sandbox environment using the Checkout URL generated by the Checkout API. My question is whether there is a simple way to get whether the payment process has been completed. Right now, I am just polling the API with the same order (with identical idempotency keys) and waiting for it to return an error that the order is no longer valid. Here is the backbone of my current code:
var bodyOrderLineItems = new List<CreateOrderRequestLineItem>();
long totalCost = 100;
var charge0 = new Money.Builder().Amount(totalCost).Currency("USD").Build();
bodyOrderLineItems.Add(new CreateOrderRequestLineItem.Builder("1").Name("Incredibly Valuable Product").BasePriceMoney(charge0).Build());
var order = new CreateOrderRequest.Builder()
.ReferenceId("reference_id")
.LineItems(bodyOrderLineItems)
.Build();
var body = new CreateCheckoutRequest.Builder("Test_iKey4", order)
.AskForShippingAddress(false)
.Build();
var checkoutApi = client.CheckoutApi;
try
{
CreateCheckoutResponse result = checkoutApi.CreateCheckout(locationsString, body);
System.Diagnostics.Process.Start(result.Checkout.CheckoutPageUrl);
while (true)
{
System.Threading.Thread.Sleep(5000);
//while payment hasn't gone through
try
{
result = checkoutApi.CreateCheckout(locationsString, body);
}
catch (ApiException e)
{
MessageBox.Show(e.Errors[0].Detail);
break;
}
}
MessageBox.Show("Payment Must Have Gone Through");
}
catch (ApiException e) { MessageBox.Show(e.Errors[0].Detail); };
Is this a valid approach? While this does seem to work, I feel like I am flooding the api with requests. I am pretty inexperienced with the Square API, so any help would be appreciated.
Typically the Checkout API is used within a website, as it includes a parameter redirect_url so that when the payment is complete, the user is redirected back to your side and it includes url parameters such as the transaction id. If you don't have a website, you can instead sign up for webhooks. The PAYMENT_UPDATED webhook will be sent out when a payment has been processed, so you do not need to do polling; just listen for the webhook.

Gmail Mail Api Working in Api explorer but not in code c#

I am using Gmail Api to get all the unread message in inbox , do some operations on it and then mark the mail as READ.
However when i do any of the below:
var markAsReadRequest = new ModifyThreadRequest { RemoveLabelIds = new[] { "UNREAD" } };
service.Users.Threads.Modify(markAsReadRequest, "xxx#gmail.com", email.ThreadId)
.Execute();
var markemail=new ModifyMessageRequest { RemoveLabelIds = new[] { "UNREAD" } };
service.Users.Messages.Modify(markemail, "xxx#gmail.com", email.Id)
.Execute();
I am getting Error:
Google.Apis.Requests.RequestError
Insufficient Permission [403]
Errors [
Message[Insufficient Permission] Location[ - ] Reason[insufficientPermissions] Domain[global]
]
The thing is i open Api explorer and run the same request and it works fine.
So not sure what am i doing wrong here.
gmail.users.threads.modify:
Modifies the labels applied to the thread. This applies to all messages in the thread.
This works and marks the email as UNREAD.
Found the issue had to add this on top:
static string[] Scopes = { mailService.Scope.GmailReadonly,GmailService.Scope.GmailModify };

Linq-To-Twitter Bad Authentication

So i've been using Linq-To-Twitter to add Twitter Integration to my Windows 8 Store App, Moreso for playing around with it, but i've come accross a problem. My current authentication codeblock is
var auth = new WinRtAuthorizer
{
Credentials = new LocalDataCredentials
{
ConsumerKey = "",
ConsumerSecret = ""
},
UseCompression = true,
Callback = new Uri("http://linqtotwitter.codeplex.com/")
};
if (auth == null || !auth.IsAuthorized)
{
await auth.AuthorizeAsync();
}
Which works great, unless I go into the authentication screen and click the back button on the top left, to exit authentication without supplying details. at which point i get a TwitterQueryException: Bad Authentication data at:
var timelineResponse =
(from tweet in twitterCtx.Status
where tweet.Type == StatusType.Home
select tweet)
.ToList();
Obviously because the Authentication Information was wrong, I'm trying to find a way to stop proceeding to the rest of the code if the authentication fails/is backed out.
I've tried simple boolean checks to no effect. I've been melting my brain over this for hours, so any help would be greatly appreciated. Thanks a bunch!
You can query Account.VerifyCredentials to ensure the user is logged in before performing any other operation. Here's an example:
const int BadAuthenticationData = 215;
var twitterCtx = new TwitterContext(auth);
try
{
var account =
(from acct in twitterCtx.Account
where acct.Type == AccountType.VerifyCredentials
select acct)
.SingleOrDefault();
await new MessageDialog(
"Screen Name: " + account.User.Identifier.ScreenName,
"Verification Passed")
.ShowAsync();
}
catch (TwitterQueryException tqEx)
{
if (tqEx.ErrorCode == BadAuthenticationData)
{
new MessageDialog(
"User not authenticated",
"Error During Verification.")
.ShowAsync();
return;
}
throw;
}
Your error handling strategy will differ from this, which is just a sample, but it shows you how to know that the error occurred and gives you the opportunity to react to the problem before resuming normal operation.
TwitterQueryException will include the Twitter error code in the ErrorCode property. It also sets Message to the error message that Twitter returns. InnerException provides the underlying exception with the original stack trace, which is often a WebException thrown because of the HTTP error code returned from Twitter.

Categories

Resources