Convert this sendgrid example to asp.net?
How could I use the following code in an aspx.cs page? I haven’t worked with Task objects before.
using System;
using System.Threading.Tasks;
using SendGrid;
using SendGrid.Helpers.Mail;
class Program
{
static async Task Main()
{
var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
var client = new SendGridClient(apiKey);
var from = new EmailAddress("test@example.com", "Example User");
var subject = "Sending with Twilio SendGrid is Fun";
var to = new EmailAddress("test@example.com", "Example User");
var plainTextContent = "and easy to do anywhere, even with C#";
var htmlContent = "<strong>and easy to do anywhere, even with C#</strong>";
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
var response = await client.SendEmailAsync(msg).ConfigureAwait(false);
}
}
UPDATE 1:
I'm yet to test the solution mentioned in the comments. I'm trusting it doesn't have an ASP.NET blocking issue described in:
https://github.com/sendgrid/sendgrid-csharp/issues/423
https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html
See also questions close to this topic
-
Why am i getting 'A column already belongs to this DataTable.' exception at dt.Columns.Add(header)?
I have the following tsv file: (columns start from
StyleName
and end atCurrent Prod PS
)StyleName Desc Box Count MinPerQ1 MaxPerQ1 SNDContainsPS SNDSpecifiedPSIs CurrentCommonProdID ProductIDs SND Indicates PS? PS Specified In SND Is Currently mapped to Current Prod PS Custom (Sphere Design) Lens 1 357 357 0 NULL 398497 45222275 No NA __Misc GB | Vial 1 PLASMA TREAT PLASMA TREAT 1 11 11 0 NULL -2 38953746 No NA __Unmappable
I am trying to convert the tsv file into a DataTable because after some research, I found that Datatable will make my use case easier to manipulate later on (I want to insert a column into this tsv file later on from another tsv file, which is outside the scope of this question).
I am getting this error at
dt.Columns.Add(header);
:'A column named 'SND Indicates PS?' already belongs to this DataTable.'
Why is that? I searched for the
SND Indicates PS?
keyword and the only one i see is the column name, theres no duplicates whatsover...so how come this exception is being thrown?public static DataTable ConvertCSVtoDataTable(string strFilePath, char delimiter = '\t') { DataTable dt = new DataTable(); using (StreamReader sr = new StreamReader(strFilePath)) { string[] headers = sr.ReadLine().Split(delimiter); foreach (string header in headers) { dt.Columns.Add(header); } while (!sr.EndOfStream) { string[] rows = sr.ReadLine().Split(delimiter); DataRow dr = dt.NewRow(); for (int i = 0; i < headers.Length; i++) { dr[i] = rows[i]; } dt.Rows.Add(dr); } } return dt; }
-
Why Point with random X and Y results always on the same line?
I know that Random isn't totally random and it gives same result repeatedly if use it with a very little span. However, i was just playing around with it and came up with a very interesting result.
Here is my code :
private void Form1_Load(object sender,EventArgs e) { timer1.Enabled = true; timer1.Interval = 1000;//i was hoping that interval will change result but no luck. } private void timer1_Tick(object sender,EventArgs e) { Label label = new Label(); label.Visible =true; label.Text = " "; label.AutoSize = true; Random rndX = new Random(); Random rndY = new Random();//I know i don't actually need this. Point point = new Point(){X=rndX.Next(0,1000),Y=rndY.Next(0,1000)}; label.Location = point; label.BackColor = Color.FromArgb(rnd.Next(1,255),rnd.Next(1,255),rnd.Next(1,255)); this.Controls.Add(label); }
Why is random behaving like this?
Also is there a way to make this truely random?
-
Remove punctation within string
I would like to remove a punctation within a string. The punctuation before a space should be preserved. Double punctuation should also not be removed.
Hel-lo World --> Hello World Hel.lo Wo-rld --> Hello World approx. age --> approx. age approx.-age --> approx.-age
So far i got this. But it replaces all punctations ... and covers only case 1 and 2
Regex.Replace("Hel-lo World!", @"[^\w\s]", "");
-
how to get all controls of aspx page without running in browser
I have aspx page which may controls. I want get all controls of aspx page without running into browser. Means by taking physical path, I want to get list of all controls from aspx.
for example - I have following aspx page and I want to get all controls(textbox and label) and their attributes.
<%@ Page Title="Home Page" Language="VB" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.vb" Inherits="WebApplication1._Default" %> <asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server"> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> </asp:Content>
-
using select options to get value in asp.net razor page
I want to create a select option to input one of a few fixed values and have it return a matching value to a variable similar to how the input text fields, how would I do this? This was my attempt, the
<input type="text">
works fine but the select types return null.<div class="text-center"> <h1 class="display-4">Add new patient</h1> <form method="post"> <input type="text" asp-for="patientModel.PatientID" placeholder="Patient ID" /> <input type="text" asp-for="patientModel.FirstName" placeholder="First Name" /> <input type="text" asp-for="patientModel.SecondName" placeholder="Second Name" /> <input type="text" asp-for="patientModel.Location" placeholder="Location" /> <select id="active" name="active" asp-for="patientModel.Sex"> <option value="ACTIVE">MALE</option> <option value="INACTIVE">FEMALE</option> <option value="OTHER">OTHER</option> </select> <select id="active" name="active" asp-for="patientModel.Active"> <option value="ACTIVE">ACTIVE</option> <option value="INACTIVE">INACTIVE</option> </select> <button type="submit">Submit</button> </form> </div>
public class addnewpatientModel : PageModel { [BindProperty] public PatientModel patientModel { get; set; } public void OnGet() { } public IActionResult OnPost() { return RedirectToPage("/index"); } }
-
Solution for contenteditable="true" property is not working for image tag when resize image in Chrome and Firefox
I want to resize the image inside the img tag in a div. I am using contenteditable="true" property for the div. I am editing the content but I do not select the image and resize the image in chrome and firefox
my code is simple
div contenteditable="true" img src="img.png" div
This code is working in the IE browser and I am selecting an image and also resize the image but in chrome and firefox, it won't work for me.
Please give some solution. Thank you
-
How to send a PDF using sendgrid to an email address?
I'm trying to use the following code to send a pdf
var html_to_pdf = require('html-pdf-node'); var defer = Q.defer(); let options = {format: 'A4', margin: {top: "20", left: "20", right: "20", bottom: "20"}}; let html = "<p>Hi there,</p>"; let file = {content: html}; html_to_pdf.generatePdf(file, options).then(pdfBuffer => { var body = { subject: "Your", personalizations: [{ to: [ { email: recipientEmail } ], "dynamic_template_data": { "senderName": senderName, "name": recipientName, "email": recipientEmail, "body": recipientMessage, "subscriptionCode": subscriptionCode } }], to: [ { email: recipientEmail } ], from: { email: "info@test.com", name: "test Team" }, content: [{type: "text/plain", value: "Hi there"}], attachments: [ { filename: "test.pdf", content: btoa(pdfBuffer), type: 'application/pdf', disposition: 'attachment', } ] }; this._sendEmail(body).then( (result) => { defer.resolve(result); }).catch (error => { defer.reject(error); console.error(error); }); }).catch (error => { defer.reject(error); console.error(error); }); return defer.promise;
Unfortunately, the pdf doesn't get sent? There is no error output. What am I doing wrong?
-
How do we programmatically delete SendGrid account information for GDPR related requests?
We use SendGrid to deliver our emails to our customers. We are implementing a light-weight internal infrastructure to handle GDPR requests from our customers. We would like to know how to forward relevant requests to Sendgrid, as our downstream dependency, to ensure complete deletion of our user information. I noticed from the below link that SendGrid is covered by Twilio's Data Protection Addendum, https://sendgrid.com/resource/general-data-protection-regulation-2/. But I could not find any definitive documentation around API support or actual deletion process with respect to GDPR at Twilio.
If someone could point me to any relevant document or API, it would be helpful.
Thanks, Dheeban
-
Updating SendGrid contact custom fields via SendGrid API. Why isn't this working?
I'm trying to update my SendGrid contacts and can't figure out why my attempts to update my contacts' custom fields are not working. My reserved fields (first_name, last_name, email) update, but my custom fields do not. Any ideas why?
Documentation here: https://sendgrid.api-docs.io/v3.0/contacts/add-or-update-a-contact
try: headers = { 'authorization': f"Bearer {settings.SENDGRID_API_KEY}", } data = { "list_ids": [ # "Users" list "7c2...d20" ], "contacts": [{ "email": user.email, "first_name": user.first_name, "last_name": user.last_name, "custom_fields": { "educator_role": user.educator_role, } }] } response = requests.put("https://api.sendgrid.com/v3/marketing/contacts", headers=headers, data=json.dumps(data)) if(response.status_code != 202): capture_message(f"Could not add user with email {user.email} to Sendgrid.", level="error") except: capture_message(f"Adding/updating SendGrid contact failed for {user.email}.", level="error")```