Redirect SendGrid Webhook Events with an F5 using Custom Headers - sendgrid

When sending an email through SendGrid I am sending a custom header. Is there a way to configure the webhooks to get the custom header back from SendGrid so that a F5 iRule can be easily written to redirect the traffic based on the value in this custom header. I know I can use .addCustomArgs(...) to return custom data but I would like the custom data in the header.
var client = new SendGridClient("API_KEY");
var from = new EmailAddress("test#example.com", "Example User");
var subject = "Testing with SendGrid API";
var to = new EmailAddress("joe#test.com", "Example User");
var plainTextContent = "Test Content";
var htmlContent = "<strong>Testing with HTML content</strong>";
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
var identifiers = new Dictionary<String, String>();
identifiers["application"] = "APP_NAME_GOES_HERE";
identifiers["resource"] = "RESOURCE_NAME_GOES_HERE";
msg.AddHeaders(identifiers);
var response = await client.SendEmailAsync(msg);

Twilio SendGrid developer evangelist here.
I'm afraid you cannot set headers for the SendGrid event webhook to send back. Custom arguments are sent as part of the JSON body.
I've not used F5 iRules before, but it seems that you may be able to parse and use the JSON body of a request within an iRule. According to this post, you can use iRules LX to deal with the JSON using JavaScript.
Or it seems that you can combine HTTP::collect with an HTTP_REQUEST_DATA block to collect and do things with the request body.

Related

Send email to the new google form submission only

I'm new to the Google apps script. I wrote a script to send emails when there is a new submission from google forms using data and template from a spreadsheet. However, it sends an email to not just the new submission but also to all of the previous submissions. The whole script is quite long, so I only copy a short part of it. Is there any way to fix it?
Here is the link to the spreadsheet https://docs.google.com/spreadsheets/d/1fhuwEndIS3khg3W19jpQnBAaCp_MMrD_bfATrdf2-4I/edit?usp=sharing
Thank you.
function sendEmail() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Calculation");
var lr = ss.getLastRow();
for (var i = 3; i<=lr;i++){
var currentEmail = ss.getRange(i, 1).getValue();
var currentName = ss.getRange(i, 3).getValue();
var currentScore1 = ss.getRange(i, 4).getValue();
MailApp.sendEmail(
currentEmail,
subjectline,
"HTML",
{ htmlBody: messageBody }
);
}
}
Instead of reading the values from the spreadsheet take advantage of the form submit event object. This event object has two properties including the form submission values, one is an Array of form submission values in the same order than the sheet columns, the other is an object having a property for each question each of them having an Array of values. Ref. https://developers.google.com/apps-script/guides/triggers/events
This shows the changes that need to done to your script:
function sendEmail(e) {
var currentEmail = e.values[0];
var currentName = e.values[2];
var currentScore1 = e.values[3];
MailApp.sendEmail(
currentEmail,
subjectline,
"HTML",
{ htmlBody: messageBody }
);
}
Note: In order to make the event object work, the function should be called by a Google Sheets form submit trigger.
Related
Event values and offset in Google spreadsheet
How to send an email only to the last Google form submission?

Proper way to do a PATCH request

Im using ASP.Net Core 2. I need to update a user in a Azure AD with Microsofts Graph API. The API documentation states that i should send the properties of the user in the body and specify the user in the URL like so:
https://graph.windows.net/myorganization/users/{user_id}?api-version
The documentation states that it should be a PATCH request. But HTTPRequestMessage does not accept PATCH as a HttpMethod. What is the proper way to make a PATCH request with asp.net core 2?
When i google i find that all answers suggests using JsonPatch, but that is a format that is not supported by Microsoft Graph API.
This is what i have so far....
var client = new HttpClient();
var requestUri = $"{_azureAdOptions.GraphInstance}/{_azureAdOptions.GraphVersion}/{_azureAdOptions.Domain}/users/me";
var request = new HttpRequestMessage(HttpMethod., requestUri);
var accessToken = await _authenticationHelper.GetAccessTokenAsync();
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var response = await client.SendAsync(request);
var responseString = await response.Content.ReadAsStringAsync();
Given the nature of Http, and the craziness of developers, you can create your own http server with custom methods. The class HttpMethod was created with this in mind allowing you to specify the method as string:
var method = new HttpMethod("PATCH"); // Patch
var request = new HttpRequestMessage(method , requestUri); // Use patch
Note: The new version of HttpClient comes with Patch method by default.

How to call SSRS Rest-Api V1.0 with custom security implemented (NOT SOAP)

I have implemented the custom security on my reporting services 2016 and it displays the login page once the URL for reporting services is typed on browser URL bar (either reports or reportserver)
I am using the following code to pass the Credentials
when i use the code WITHOUT my security extension it works and looks like this
ICredentials _executionCredentials;
CredentialCache myCache = new CredentialCache();
Uri reportServerUri = new Uri(ReportServerUrl);
myCache.Add(new Uri(reportServerUri.GetLeftPart(UriPartial.Authority)),
"NTLM", new NetworkCredential(MyUserName, MyUserPassword));
_executionCredentials = myCache;
when i use the code WITH the security extension it doesnt work and looks like this
ICredentials _executionCredentials;
CredentialCache myCache = new CredentialCache();
Uri reportServerUri = new Uri(ReportServerUrl);
myCache.Add(new Uri(reportServerUri.GetLeftPart(UriPartial.Authority)),
"Basic", new NetworkCredential(MyUserName, MyUserPassword));
_executionCredentials = myCache;
and i get an Exception saying "The response to this POST request did not contain a 'location' header. That is not supported by this client." when i actually use this credentials
Is "basic" the wrong option ?
Have anyone done this ?
Update 1
Well it turns out that my SSRS is expecting an Authorisation cookie
which i am unable to pass (according to fiddler, there is no cookie)
HttpWebRequest request;
request = (HttpWebRequest)HttpWebRequest.Create("http://mylocalcomputerwithRS/Reports_SQL2016/api/v1.0");
CookieContainer cookieJar = new CookieContainer();
request.CookieContainer = cookieJar;
Cookie authCookie = new Cookie("sqlAuthCookie", "username:password");
authCookie.Domain = ".mydomain.mylocalcomputerwithRS";
if (authCookie != null)
request.CookieContainer.Add(authCookie);
request.Timeout = -1;
HttpWebResponse myHttpWebResponse = (HttpWebResponse)request.GetResponse();
That's how I got it (SSRS 2017; api v2.0). I took the value for the "body" from Fiddler:
var handler = new HttpClientHandler();
var httpClient = new HttpClient(handler);
Assert.AreEqual(0, handler.CookieContainer.Count);
// Create a login form
var body = new Dictionary<string, string>()
{
{"__VIEWSTATE", "9cZYKBmLKR3EbLhJvaf1JI7LZ4cc0244Hpcpzt/2MsDy+ccwNaw9hswvzwepb4InPxvrgR0FJ/TpZWbLZGNEIuD/dmmqy0qXNm5/6VMn9eV+SBbdAhSupsEhmbuTTrg7sjtRig==" },
{"__VIEWSTATEGENERATOR", "480DEEB3"},
{ "__EVENTVALIDATION", "IS0IRlkvSTMCa7SfuB/lrh9f5TpFSB2wpqBZGzpoT/aKGsI5zSjooNO9QvxIh+QIvcbPFDOqTD7R0VDOH8CWkX4T4Fs29e6IL92qPik3euu5QpidxJB14t/WSqBywIMEWXy6lfVTsTWAkkMJRX8DX7OwIhSWZAEbWZUyJRSpXZK5k74jl4x85OZJ19hyfE9qwatskQ=="},
{"txtUserName", "User"},
{"txtPassword", "1"},
{"btnLogin","Войти"}
};
var content = new FormUrlEncodedContent(body);
// POST to login form
var response = await httpClient.PostAsync("http://127.0.0.1:777/ReportServer/Logon.aspx", content);
// Check the cookies created by server
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
var cookies = handler.CookieContainer.GetCookies(new Uri("http://127.0.0.1:777/ReportServer"));
Assert.AreEqual("sqlAuthCookie", cookies[0].Name);
// Make new request to secured resource
var myresponse = await httpClient.GetAsync("http://127.0.0.1:777/Reports/api/v2.0/Folders");
var stringContent = await myresponse.Content.ReadAsStringAsync();
Console.Write(stringContent);
As an alternative you can customize SSRS Custom Security Sample quite a bit.
I forked Microsoft's Custom Security Sample to do just what you are describing (needed the functionality at a client long ago and reimplemented as a shareable project on GitHub).
https://github.com/sonrai-LLC/ExtRSAuth
I created a YouTube walkthrough as well to show how one can extend and debug SSRS security with this ExtRSAuth SSRS security assembly https://www.youtube.com/watch?v=tnsWChwW7lA
TL; DR; just bypass the Microsoft example auth check in Login.aspx.cs and put your auth in Page_Load() or Page_Init() event of Login.aspx.cs- wherever you want to perform some custom logging check- and then immediately redirect auth'd user to their requested URI.

Add Email Signature to Email Notification Script

I am writing a code on Google Apps Script to send an email every time there is a new announcement made in my site. Here is the code for reference:
var url_of_announcements_page = "https://sites.google.com/announcements";
var who_to_email = "emailaccount";
function emailAnnouncements(){
var page = SitesApp.getPageByUrl(url_of_announcements_page);
if(page.getPageType() == SitesApp.PageType.ANNOUNCEMENTS_PAGE){
var announcements = page.getAnnouncements({ start: 0,
max: 10,
includeDrafts: false,
includeDeleted: false});
announcements.reverse();
for(var i in announcements) {
var ann = announcements[i];
var updated = ann.getLastUpdated().getTime();
if (updated > PropertiesService.getScriptProperties().getProperty("last-update")){
var options = {};
options.htmlBody = Utilities.formatString("<h1><a href='%s'>%s</a></h1>%s", ann.getUrl(), ann.getTitle(), ann.getHtmlContent());
MailApp.sendEmail(who_to_email, "Announcement - '"+ann.getTitle()+"'", ann.getTextContent()+"\n\n"+ann.getUrl(), options);
PropertiesService.getScriptProperties().setProperty('last-update',updated);
}
}
}
}
function setup(){
PropertiesService.getScriptProperties().setProperty('last-update',new Date().getTime());
}
I would like to know if it is possible to add my gmail signature to the code. As when I send it with the script my signature is removed. Do I have to make my signature in the code or am i able to get my signature from gmail and automatically insert it at the end? Here is the line for the formatting of the email:
MailApp.sendEmail(who_to_email, "Announcement - '"+ann.getTitle()+"'", ann.getTextContent()+"\n\n"+ann.getUrl(), options);
Apps Script cannot access user's signature: there is no method for that in MailApp, or GmailApp, or even in Gmail API accessible via Advanced Google Services.
In principle, you could use GmailApp to get a recent outgoing message and search its text for the signature contained after the last -- found in message body. But this requires giving the script a lot more access (GmailApp can access, forward and delete existing email, unlike MailApp) and is error-prone (when text parsing fails, you might end up with an embarrassing fragment of text in your message).
Just append it directly:
var signature = "\n\n--\nFirstName LastName";
// ...
MailApp.sendEmail(... +signature, options);
(By the way, Gmail web interface and Gmail mobile app have different user signatures in general, so having another one for script-generated messages doesn't seem unusual.)

Payflow Gateway w/ Secure Token & Transparent Redirect - return URL issue

I've built a client (in .NET, but it could be in any framework) to consume the Payflow Gateway NVP API using the Transparent Redirect and Secure Token features. I am able to receive the token, send the credit card data, and receive an Approved response from PayPal. The problem is that PayPal is not redirecting properly back to my site. I passed a RETURNURL (http://localhost:49881/transaction/details?processor=PayflowGateway) parameter when requesting the Secure Token, but instead of returning me to that URL after the transaction, it navigates my browser to the following URL:
https://pilot-payflowlink.paypal.com/http%3A%2F%2Flocalhost%3A49881%2Ftransaction%2Fdetails%3Fprocessor%3DPayflowGateway?POSTFPSMSG=No%20Rules%20Triggered&RESPMSG=Approved&ACCT=1111&COUNTRY=US&PROCCVV2=M&VISACARDLEVEL=12&CVV2MATCH=Y&CARDTYPE=0&PNREF=A70A8EB8B6A1&AVSDATA=XXN&SECURETOKEN=9eGKZsSldEU6mIdSEV5DB4wWd&PREFPSMSG=No%20Rules%20Triggered&SHIPTOCOUNTRY=US&AMT=14.75&SECURETOKENID=1850a8f2-f180-4474-aa31-35d736fd7921&TRANSTIME=2016-03-24%2007:58:48&HOSTCODE=A&COUNTRYTOSHIP=US&RESULT=0&BILLTOCOUNTRY=US&AUTHCODE=872PNI&EXPDATE=1218
I have tried removing the "?processor=PayflowGateway" to fix the multiple question mark issue in the URL, but that doesn't seem to help. I've also tried tagging the RETURNURL[xx] with xx being the length of the URL value, but that seems to be the same as not passing a RETURNURL at all as it just shows a confirmation page on paypal.com instead of redirecting back to my site.
In PayPal Manager, I set the "Show confirmation page" setting to "On my website", Return URL to blank, and Return URL Method to GET. Are there any other settings or API request changes I need to make to get this to return properly to my test site?
This problem is caused because you're URL-Encoding the RETURNURL parameter passed when requesting the secure token from payflowpro gateway.
See the Do Not URL Encode Name-Value Parameter Data section on the Integration Guide.
Also, here you can get some C# code working you can use.
And some guidelines about PayPal HTTP here.
Do not use System.Net.Http.HttpClient nor System.Net.WebClient to make the HTTP POST to request the secure token. Instead use the low level System.Net.WebRequest to be able to write the POST data unencoded.
For example:
private string RequestSecureToken(double amount)
{
var secureTokenId = Guid.NewGuid().ToString();
var requestId = Guid.NewGuid().ToString();
var pairs = new Dictionary<string, string>()
{
{"PARTNER", "PayPal"},
{"VENDOR", "VENDOR NAME"},
{"USER", "USER NAME"},
{"PWD", "PASSWORD"},
{"TRXTYPE", "S"},
{"AMT", amount.ToString()},
{"CREATESECURETOKEN", "Y"},
{"SECURETOKENID", secureTokenId},
{"SILENTTRAN", "TRUE"},
{"RETURNURL", "http://mycompany.com/success"},
{"ERRORURL", "http://mycompany.com/error"}
};
string postData = string.Join("&", pairs.Select(p => string.Format("{0}[{2}]={1}", p.Key, p.Value, p.Value.Length)));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://pilot-payflowpro.paypal.com");
request.Method = "POST";
request.ContentType = "text/namevalue";
request.Headers.Add("X-VPS-CLIENT-TIMEOUT", "45");
request.Headers.Add("X-VPS-REQUEST-ID", requestId);
request.ContentLength = postData.Length;
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(postData);
}
//Get the response
var response = request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}