Author Archives: Brad Kingsley

Sending Email Code Sample (Razor, C#)

A *really* common and popular thing to do with web pages it to send email. That email might be a feedback form, or an order confirmation, or a variety of other functions. Below is the complete contents of a page I named SendEmail.cshtml. I’ll throw it out there right at the start in case you want to copy/paste it and start playing around. After the code I’ll break things down a bit to explain.

**NOTE: You need a working SMTP Server to send the email. In my code sample I used GMail’s SMTP service, which requires SMTP-AUTH of an existing username/password. If you have a GMail account and want to use this same SMTP server, just be sure to put your username (email address) and password in the appropriate places. If you want to use a different SMTP server, then you’ll need the name of that server and security requirements (SMTP-AUTH, IP-AUTH, etc.) and adjust your code as needed.

Oh, let me also say up-front here – DO NOT just use this code sample and put it out on a public web page. It won’t take a spammer very long to find the page (I don’t know how they do – but they do!) and start abusing it. As soon as that happens you are going to be on the hook for a lot of trouble since your specific identity is known via the authentication.

Okay, here’s the code:

@{
    var errorMessage = "";

    if (IsPost)
    {
        var toEmail = Request["toEmail"];
        var fromEmail = Request["fromEmail"];
        var subject = Request["subject"];
        var body = Request["body"];

        try {
            WebMail.SmtpServer = "smtp.gmail.com";
            WebMail.SmtpPort = 25;
            WebMail.EnableSsl = true;
            WebMail.UserName = "*YOU*@gmail.com";
            WebMail.Password = "*YourGMailPassword*";
            WebMail.From = fromEmail;
            WebMail.Send(to: toEmail,
                subject: subject,
                body: body
            );
        }
        catch (Exception ex ) {
            errorMessage = ex.Message;
        }
    }
}
@if (errorMessage !="") {
<div>Error: @errorMessage

}
<form method="post">
 From Address: <input type="text" name="fromEmail" />
 To Address: <input type="text" name="toEmail" />
 Subject: <input type="text" name="subject" />
 Body: <textarea id="body" cols="40" rows="10"></textarea>
 <input id="Submit1" type="submit" value="submit" />
</form>

Okay, let’s break this down a bit. In line two I’m defining a variable that can be used to capture any error message that’s returned. I actually added that after I started working on this sample because I was throwing a number of different errors every time I fixed one. :)

Starting at line 4 I check to see if this is a postback to the page or a first load. If it’s a first load then I ignore the code and show the form. If it’s a postback then I define some variables and load them with values posted from the form.

Then on line 11 we start the try block that wraps the email-sending code. I find that it’s pretty easy to have errors working with email code (a previous post I wrote years ago had over 100 comments from people with various challenges) so wrapping the code in a Try-Catch block and showing the error in a user-friendly format is helpful.

Starting with line 12 we define everything we need to send the email. First I define the SMTP server. This can be “localhost” if you have an SMTP service running on your machine (like Smtp4dev or even the Microsoft SMTP service (if you are running Windows Server 2008 R2 or earlier – Windows 8.1 and Server 2012 no longer support the Microsoft SMTP service). In my sample code I’m using my GMail account so using GMail’s SMTP server. Then I clarify the port number (some ISPs use a non-standard port). GMail’s SMTP server requires an encrypted connection so I specifically set EnableSsl to true (this is ISP dependent – check with whoever manages your SMTP server). The new two lines set the username and password if SMTP-AUTH is requires by your SMTP server (GMail does require it to track spammers). Lastly I set the From address and then execute the Send method.

If there is an error it will be noticed by the Catch statement on line 23 and assigned to the errorMessage variable for display on line 29.

That’s about it. The rest is a really basic HTML form so I won’t go through that specifically.

Brad on Google+

Loop Through Database Records (C#, Razor)

Here’s a code sample showing a quick and easy way to loop through the results of a SQL query and display them on a web page in a list.

@{
    var db = Database.Open("YourDatabase");
    var ListDataItems = db.Query("SELECT SomeField FROM SomeTable");
}
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8" />
    <head>
        <meta charset="utf-8" />
        <title>ForEach Query Test Page</title>
    </head>
    <body>
        <ul>
        @foreach(var ListItem in ListDataItems){
	<li>@ListItem.SomeField</li>
        }
        </ul>
    </body>
</html>

This is pretty basic but let’s break it down.

In this example I have an existing database in my project’s /App_Data/ folder named “YourDatabase.sdf” (it’s a SQL CE database). I reference that database in line 2 and then run my query in line 3. The results of that query are placed into a recordset stored in the ListDataItems variable also defined on line 3.

Most of the rest is basic HTML but on line 14 I start a look that iterates through each item in ListDataItems and puts the rows – one at a time – into the ListItem variable.

On line 15 I reference the row (using ListItem) and also the specific field I want to display – SomeField in this case. I could have easily had multiple items returned per row in my query (line 3) and in that case I would have been able to reference whichever, or multiples, using their specific field name.

Line 16 just closes out the code block for the loop.

Brad on Google+

Crucial SSD Drives – Old vs. New

I have a few of the Crucial M4 drives in various personal machines. One of my devices (Dell e6400 laptop) is running low on space so I spent a little time this morning looking at drive upgrades. I noticed that Crucial has a new M550 SSD drive and I was curious how benchmarks compared to the older M4 that I already use.

After a little Google-fu I came across this post that compares the M4 and the M500 drives. I expected an increase in performance just because it is a new drive, but WOW, those benchmarks show HUGE performance with the new model. Based on this – and the fact that they’re quite reasonably priced – I think I might actually upgrade a number of my devices to take advantage of the increased performance of these faster drives.

The Lastest Version of WordPress

I got behind again on my WordPress updates – I can be pretty lazy about that with the theory of “if it ain’t broke…” but I was doing a post or two today and the available updates were screaming at me (well, that little icon kept catching my eye). I had 6 plugin updates and one full WordPress update available.

So, I took the plunge. Being a Windows guy, and a long time server guy, I’m ALWAYS nervous about updates. But once again WordPress held strong and true. Every one of the updates processes flawlessly without any issues at all.

Good for you WordPress.

BTW – I like the new administration console interface. Very nice. :)

Happy hosting!

EC2 Error: The request must contain the parameter instance id

I was trying to associate an elastic IP to a running EC2 VM today and kept hitting this error. There is surprisingly little available via Google when typing in the error message – nothing actually with an exact match. So I figured I’d drop a quick post to help out other people like myself who might run into this issue.

I added an elastic IP and saw it in the list. The next day I noticed I got billed ($.03) for having an elastic IP that wasn’t assigned to an instance. OK. Strange but whatever. I went into theĀ management console to assign the elastic IP to my running instance. I right-clicked and chose “associate” but no matter what options I tried to link it to my VM, it kept giving me this error.

Well, after some playing around – for way longer than I wanted to spend – I deleted the elastic IP and recreated it. When first creating (“allocating”) an elastic IP it gives you two choices – EC2 or VPC. The default selected in the list is EC2 and that’s what I originally left as my selected choice. I changed this to VPC and voila! – now I could associate the IP to my running VM nice and easily.

So, what’s the deal? Well, I guess new EC2 instances are created as VPC instances now by default. I don’t remember being asked or prompted when I created my instance.

VPC at Amazon stands for “Virtual Private Cloud”. If you are curious, here is a post that lists the differences between a classic EC2 instance and a newer VPC instance.

Hopefully this little tip saves someone else some time. I sure wish I’d stumbled across it earlier and saved the hassle and headache of tinkering to figure it out on my own.

Happy hosting!