分类 .NET 下的文章

CEO Friday: Why we don’t hire .NET programmers

Written by David Barrett
March 25, 2011 at 7:00 am
Posted in CEO Friday, Job
Original Post URL: http://blog.expensify.com/2011/03/25/ceo-friday-why-we-dont-hire-net-programmers/






As you might know, we’re hiring the best programmers in the world. Sure, everyone says that. But my coders will beat up your coders, any day of the week. For example, Mich is barely 5 foot tall, but is a competitive fencer. Witold is a 6’3″ former professional hockey player. Nate practices knife fighting for fun. And they’re pretty decent programmers, too.

But finding such people is more than a full time job. Indeed, I spend about half my time on it, while Lisa spends about all hers. And on top of that we have an army of recruiters out scouring the globe, leaving no resume unturned. Taken all together, this creates a lot of resumes. So many that we don’t look at them, because resumes — let’s be honest — are totally worthless. Rather, we pay all our attention to a few key questions we ask every candidate, each aiming at uncovering a single key point: is this someone we really want to work with?

See, experience is cheap. All it takes is time. Skill is harder, but really only requires hard work — a lot of people can get that. But attitude. You either have it, or you don’t. The right sort of person is so passionate about coding, they can’t be stopped from doing it. They typically started before high school — sometimes before middle school — and never looked back. They write everything from assembly to jQuery, on PCs to mobile phones, doing hard core computer graphics to high level social networking. They’ve tried everything.

Everything, that is, but .NET.

Now let me clarify — .NET is a dandy language. It’s modern, it’s fancy, it’s got all the bells and whistles. And if you’re doing Windows Mobile 7 apps (which the stats suggest you aren’t), it’s your only choice. But choosing .NET is a choice, and whenever anybody does it, I can’t help but ask “why?”

Don’t get me wrong: .NET on your resume isn’t an instant showstopper. But it will definitely raise questions during the phone screen, for reasons that are best explained by simile:

Programming with .NET is like cooking in a McDonalds kitchen. It is full of amazing tools that automate absolutely everything. Just press the right button and follow the beeping lights, and you can churn out flawless 1.6 oz burgers faster than anybody else on the planet.

However, if you need to make a 1.7 oz burger, you simply can’t. There’s no button for it. The patties are pre-formed in the wrong size. They start out frozen so they can’t be smushed up and reformed, and the thawing machine is so tightly integrated with the cooking machine that there’s no way to intercept it between the two. A McDonalds kitchen makes exactly what’s on the McDonalds menu — and does so in an absolutely foolproof fashion. But it can’t go off the menu, and any attempt to bend the machine to your will just breaks it such that it needs to be sent back to the factory for repairs.

Instead, we look for a very different sort of person. The sort of person who grew up cooking squirrels over a campfire with sharpened sticks — squirrels they caught and skinned while scavenging in the deep forests for survival. We don’t want a short order chef, we want a Lord of the Flies, carried by wolves into civilization and raised in a French kitchen full of copper-bottomed pots and fresh-picked herbs. We need people who can not only cook burgers, but cook anything, from scratch.

See, Microsoft very intentionally (and very successfully) created .NET to be as different as possible from everything else out there, keeping the programmer far away from the details such that they’re wholly and utterly dependent on Microsoft’s truly amazing suite of programming tools to do all the thinking for them. Microsoft started down this path when they were the only game in town, explicitly to maintain their monopoly by making it as hard as possible to either port Windows apps to non-Windows platforms, or to even conceive of how to do it in the first place.

This decision — or this mandate for incompatibility, perhaps — has produced countless ramifications. Small things, like using backslashes in file paths rather than forward slashes like any dignified OS., or using a left-handed coordinate system with DirectX instead of right-handed as was used since the dawn of computer graphics. Big things, like obscuring the networking stack under so many countless layers of abstraction that it’s virtually impossible to even imagine what bytes are actually going over the wire. And a thousand other things in between: programming tools that generate a dozen complex files before you even write your first line of code, expensive servers that force a remote GUI terminal on you to do essentially anything despite a few keystrokes being perfectly adequate for everybody else, a programming culture almost allergic to open source licensing. The list goes on and on.

None of this makes you a “bad programmer”. All these differences are perfectly irrelevant if you just want to make 1.6 oz burgers as fast as possible, and commit the rest of your career to an endless series of McDonalds menus. But every day spent in that kitchen is a day NOT spent in a real kitchen, learning how to cook real food, and write real code.

Even worse, every day spent learning a Microsoft kitchen takes TWO days to unlearn, meaning once you get a reasonable way down the .NET career path, there is almost no going back. You become so steeped in tools and techniques that have absolutely no relevance outside of .NET that you are actually less valuable to a startup than had you just taken a long nap.

So what’s the moral of this whole story? Two things:

If you ever want to work in a startup, avoid .NET. It does you no favors.
If you are a startup looking to hire really excellent people, take notice of .NET on a resume, and ask why it’s there.

It might sound harsh, and it is. But sometimes we only have squirrels to eat, and we need them to taste good.

-david (Follow us at https://twitter.com/expensify)

Saturday edit: Wow, this post has hit quite a nerve. Had I known it was going to take the internet by storm I probably would have been a bit more careful with my word choice (especially referring to .NET as a language, doh!). But just to clarify a couple points, 24-hours into the storm:

Yes, .NET developers are great at what they do. It’s the most modern platform for application development on the planet. Microsoft has always produced the best tools for building internal business applications, and .NET is their masterpiece. There’s a reason why they own that space; they earned it. That space employs millions of people, and those people are unquestionably the masters at what they do.
But what they do is very, very rarely startups. I’m sorry if that sounds offensive, but that’s a simple fact. You can measure this yourself: go to any list of startups, maybe look at YCombinator’s recent graduate class, or Scoble’s list of picks for 2010, or Sequoia’s list of seed companies — or go find a list you like better. Do a curl (or your .NET equivalent) on each domain, and see how many are running a Windows server: I think you’ll find the fraction very small. Don’t get me wrong: there are a lot of people who aren’t interested in working at a startup, for a lot of very valid reasons. But if you are the odd person who is interested, it’s worth asking: why do so few use .NET?
Because .NET is designed to extend, not disrupt. The same could largely be said about J2EE, but in general anybody who “grows up” with these self-contained, highly-automated platforms can’t help but view computers in a different way than those who start from a lower, less automated, more difficult level. (As one of the coherent commentators says below, Joel Spolsky himself laments schools teaching Java with the same basic reasoning of my article above, albeit more diplomatically stated.) .NET is designed to tightly integrate with and seamlessly extend the Microsoft stack in extremely powerful but ultimately incremental ways. Again, there’s nothing wrong about that if that’s what you want to do. But if that’s not what you want to do, then .NET probably isn’t the right choice, as evidenced by how few people in the startup world choose it.

Again, this isn’t a rant against .NET — it’s fine. It’s not even a rant against .NET developers being incapable of learning — they can learn as well as anyone. It’s a rant against .NET teaching the wrong things for startups. And about how people who use it for too long, can’t help but learn those things. This is a rant about how startups, by definition, need to think of things from new angles, and those angles typically don’t involve .NET.

Anyway, I was going to leave all this to blow over before making any comments in a follow-up post next Friday. Indeed, for all the outrage and fury, this is actually common knowledge amongst startups, and I was going to support that with a bit more data to win over the skeptics (at least, those who were open to listening).

But I’ve seen some recent comments that this post might have upset and offended the SMB community that we serve, and that I cannot abide. For that, I’m truly sorry. As someone who grew up using and ultimately becoming frustrated with the limitations of Microsoft tools, and grew up submitting and hating small-business expense reports, I hope I can convince you that we’re fighting for the same goals. Even if our tools and techniques might differ wildly.

Sunday edit: Incredible that this post is still going strong, on a weekend no less. But what’s most interesting is how the comments have gradually shifted over time. Granted, me even pointing this out will probably have an effect on comments going forward, but the general trend has been:

First wave: Raw, incoherent hate, constructed from near-pure profanity. I took the liberty of deleting most of this, as this is a PG-13 site. Perhaps 1% of the first wave agreed with me.
Second wave: “Reasoned” hate, though most of that reasoning was done by extrapolating my misuse of one word (“language” instead of “platform”) into every conceivable sin. I’d say maybe 15% of the second wave agreed with me (if weighted by actual coherent text).
Third wave: A very heated discussion. It would appear that every possible insult had already been slung so there was nothing left to do but actually discuss the merits of the post. I’d say maybe 25% of the third wave agreed with me.

It’s harder to get a sense of agreement/disagreement from Twitter as most people just retweet without comment. But I’d say those who do make comments have fit the rough curve above.

Serialization in .NET Programming

If you want to Binary or XML Serialization in .NET Programming and you are using C#, you can use following code.

using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.Web.Mail;

namespace npuInfoCS.Utilities
{
public class Serialization
{
public enum SerializationFormat {Xml, Binary}

public static System.Boolean SerializeToDisk(string path, object request, SerializationFormat format)
{
try
{
System.IO.MemoryStream oStream = Serialize(request, format);
if(System.IO.File.Exists(path)) System.IO.File.Delete(path);
System.IO.FileStream output = System.IO.File.Open(path, System.IO.FileMode.CreateNew);
output.Write(oStream.ToArray(),0,Convert.ToInt32(oStream.Length));
output.Close();
oStream.Close();
return true;
}
catch(Exception e)
{
return false;
}
}

public static object DeSerializeFromDisk(string path, SerializationFormat format)
{
try
{
if(System.IO.File.Exists(path))
{
System.IO.FileStream input = System.IO.File.Open(path, System.IO.FileMode.Open);
byte[] filecontents=new byte[Convert.ToInt32(input.Length)];
input.Read(filecontents, 0, Convert.ToInt32(input.Length));
input.Close();
//System.IO.File.Delete(path);
System.IO.MemoryStream inStream = new System.IO.MemoryStream(filecontents);
object newObj = DeSerialize(inStream, format);
inStream.Close();
return newObj;
}
else
{
return null;
}
}
catch(Exception e)
{
return null;
}
}

#region wrappers for binary and xml serialization
public static System.IO.MemoryStream Serialize(object request, SerializationFormat format)
{
if(format==SerializationFormat.Binary)
return SerializeBinary(request);
else
return SerializeSOAP(request);
}
public static object DeSerialize(System.IO.MemoryStream memStream, SerializationFormat format)
{
if(format==SerializationFormat.Binary)
return DeSerializeBinary(memStream);
else
return DeSerializeSOAP(memStream);
}
#endregion

#region Binary Serializers
public static System.IO.MemoryStream SerializeBinary(object request)
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
System.IO.MemoryStream memStream = new System.IO.MemoryStream();
serializer.Serialize(memStream, request);
return memStream;
}

public static object DeSerializeBinary(System.IO.MemoryStream memStream)
{
memStream.Position=0;
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter deserializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
object newobj = deserializer.Deserialize(memStream);
memStream.Close();
return newobj;
}
#endregion

#region XML Serializers
public static System.IO.MemoryStream SerializeSOAP(object request)
{
System.Runtime.Serialization.Formatters.Soap.SoapFormatter serializer = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
System.IO.MemoryStream memStream = new System.IO.MemoryStream();
serializer.Serialize(memStream, request);
return memStream;
}

public static object DeSerializeSOAP(System.IO.MemoryStream memStream)
{
object sr;
System.Runtime.Serialization.Formatters.Soap.SoapFormatter deserializer = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
memStream.Position=0;
sr = deserializer.Deserialize(memStream);
memStream.Close();
return sr;
}
#endregion

#region miscel
public static string ConvertStreamToString(System.IO.Stream theStream)
{
string theString="";
theStream.Position=0;
using (System.IO.StreamReader sr = new System.IO.StreamReader(theStream) )
{
theString = sr.ReadToEnd();
// Close and clean up the StreamReader
sr.Close();
}
return theString;
}
#endregion
}
}

Unable to get the project file from the Web server

My environment:
OS: Windows XP
Web Server: IIS 5
.NET Framework: 1.1
IDE: Visual Studio 2003

After moving or copying my code directory, when I tried to open the solution in the Visual Studio 2003, I got an error: "Unable to get the project file form the Web server" as following screenshot.

Unable to get the project file from the Web server

The reason is the Visual Studio cannot open the project file, which is http://localhost/projectName.csproj. I checked all settings of the IIS and permission of files and found nothing was wrong. After several hours struggling, I finally figured out following solution.

I deleted the all files under VSWebCache folder which is under C:\Documents and Settings\my_user_name\. The screenshot is as below. The possible reason is when I copied or moved the code folder, the previously generated runtime chache conflicts with the new code folder's location.

Clear the VSWebCache

Sending email from ASP.NET MVC through MVC and MSMQ Part 2

Original Post: http://dotnetslackers.com/articles/aspnet/Sending-email-from-ASP-NET-MVC-through-MVC-and-MSMQ-Part2.aspx

By: Andrew Siemer

In this article you will learn how to send emails using ASP.NET MVC and MSMQ.

Contents

  1. Introduction
  2. Setting up a private queue
    1. MSMQ in Windows 7
    2. MSMQ in Windows 2008
  3. Creating an MSMQ Service
  4. Update your web application to use MSMQ instead of SMTP
  5. Draining the queue
    1. A quick refactor of the queue guard code
  6. Sending the emails
    1. Relocating the SerializeMessage method
  7. Creating an installable Windows Service to drain the queue
    1. A quick refactor of our console applciation
  8. Finishing up the Windows Service
    1. Adding a Timer
    2. Making the service installable
  9. Installing your website email queue processing service
  10. Summary

Sending email from ASP.NET MVC through MVC and MSMQ Part Series

Introduction

In the previous article we discussed some of the downfalls of sending email directly from a web page and worker process that served that request. The biggest issue that we discussed was the fact that the user that initiated an email to be sent would be stuck waiting for the code to connect to the mail server and deliver the message. But we also discussed that for important emails we would also need a logging component to keep track of all the customer communications that we send. We then built out an example ASP.NET MVC application that sends email in a direct from the page fashion. We also built out a logging component so that all the messages that we intended to send would be serialized and stored in a logging database using LINQ to SQL.

In this article we will now refactor the previously created code base (make sure you grab a copy of the first articles application if you want to work along with this article) to take advantage of MSMQ. We will modify our EmailService so that rather than speaking directly with System.Net.Mail and SMTP we will instead utilize System.Messaging and MSMQ. Once our web application is converted to send its email communications to MSMQ we will then need to create a queue processing application. We will start by creating this in the form of a console application that clears the queue and sends email via our existing EmailService. Once the console application is working we will convert it into a more reliable Windows Service.

Setting up a private queue

To get started we will first create a new queue. There are many options when creating a queue. Take a look at "Reliable Messaging with MSMQ and .NET" for a good in depth discussion of MSMQ concepts. We are going to create a simple non-transactional private queue for this example. You need to first make sure that you have MSMQ installed on your machine.

I will quickly describe how to install MSMQ in Windows 7 and Windows 2008. You can use MSMQ on any of today's current versions of Windows (just google for some MSMQ installation help if you don't know what to do).

MSMQ in Windows 7

Go to Control Panel\Programs and select "Turn Windows features on or off". In the Windows Features window that pops up, scroll down to Microsoft Message Queue (MSMQ) Server and select that box. Just leave the default selection as that will get us through this demonstration. Then click OK.

Then navigate to the Computer Management console. You should be able to expand Services and Applications and see a Message Queuing entry. Expand that entry and right click on Private Queues. Select new private queue. In the New Private Queue window that opens enter WebsiteEmails. This will make the path to your private queue "{ComputerName}\private$\WebsiteEmails".

MSMQ in Windows 2008

In the Server Manager window, navigate to the Features node. Then click on Add Features. In the Add Features Wizard scroll down to Message Queuing. Then click through the wizard buttons to complete the installation.

Back in the Features node of Server Manger you should now have a Message Queue node. Inside of there you will see a Private Queues node. Right click on Private Queues and select new private queue. Give your queue the same name as above WebsiteEmails. This will make the path to your private queue "{ComputerName}\private$\WebsiteEmails".

Creating an MSMQ Service

Now that we have a queue to dump our EmailMessages into, let's write some code that will allow us to do just that. Start by creating a QueueService class in your Services folder. Then we will create a method named QueueMessage that will take in an EmailMessage object.

Listing 1: QueueService.cs

public class QueueService
{
public void QueueMessage(EmailMessage message)
{
}
}


Now let's add a reference to System.Messaging to our BusinessLayer project. Then we will add the code that we need to connect to our private queue and insert a new message.

Listing 2: QueueService.cs

public class QueueService
{
public void QueueMessage(EmailMessage message)
{
Message msg = new Message();
msg.Body = message;
msg.Recoverable = true;
msg.Formatter = new BinaryMessageFormatter();
string queuePath = @".\private$\WebsiteEmails";
MessageQueue msgQ;
//if this queue doesn't exist we will create it
if(!MessageQueue.Exists(queuePath))
MessageQueue.Create(queuePath);
msgQ = new MessageQueue(queuePath);
msgQ.Formatter = new BinaryMessageFormatter();
msgQ.Send(msg);
}
}


Update your web application to use MSMQ instead of SMTP

All that we need to do to get our web site to use MSMQ instead of SMTP is to comment out (or delete) the call to our EmailService and replace it with a call to our QueueService.

Listing 3: HomeController.cs

[HttpPost]
public ActionResult Index(string id)
{
EmailMessage em = new EmailMessage();
em.Subject = "test message";
em.Message = "howdy from asp.net mvc";
em.From = "asiemer@andrewsiemer.com";
em.To = "asiemer@andrewsiemer.com";
//new EmailService().SendMessage(em,
// "{email address}",
// "{password}",
// "smtp.gmail.com",
// 587,
// true,
// new LoggingRepository());
new QueueService().QueueMessage(em);
return View();
}


You should now be able to build and run your application. Clicking the Send Email button should now store messages in your new private queue. More importantly, the time it takes from when you click the button until the page returns should be considerably faster!

After clicking the button a few times you should be able to open up your MSMQ management window and see some messages in the queue.

Also, if you double click one of those messages to open it up, you should be able to see all sorts of data about the message. And you can see the original email that was sent!
Draining the queue

Now that we have our web site converted to send emails to a queue, we need to create an application that can read from the queue, deserialize our messages, and send out the emails as intended. We will start building this application as a console app. Once that is working as expected we can convert it to a Windows Service.

Add a new Console Application to your solution named WebsiteEmailProcessor. Then add two references to that project. The first reference is to the BusinessLayer project. The second reference is to the System.Messaging namespace.

Next we need to add a way for our application to read from the queue. This process is fairly straightforward. We will need the Main method in our console application to get us started. But we are also going to need an event handler to keep processing messages as they come into the queue.

Listing 4: Program.cs

class Program
{
private static MessageQueue msgQ = null;
private static object lockObject = new object();

static void Main(string[] args)
{
string queuePath = @".\private$\WebsiteEmails";
msgQ = new MessageQueue(queuePath);
msgQ.Formatter = new BinaryMessageFormatter();
msgQ.MessageReadPropertyFilter.SetAll();
msgQ.ReceiveCompleted += new ReceiveCompletedEventHandler(msgQ_ReceiveCompleted);
msgQ.BeginReceive();
while (Console.ReadKey().Key != ConsoleKey.Q)
{
// Press q to exit.
}
}
static void msgQ_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
{
lock (lockObject)
{
// The message is plain text.
EmailMessage msg = (EmailMessage)e.Message.Body;
Console.WriteLine("Message received: " + msg.Message);
}
// Listen for the next message.
msgQ.BeginReceive();
}
}


With what we have so far you can now run both the web application and the console application. When you click the Send Email button on the web application you should see a message go through your queue and through the processor. Give it a try!

A quick refactor of the queue guard code

You may have noticed that our console application is currently making an assumption that a queue exists. This is lazy! Let's refactor some code in our QueueService to check that the queue exists and make the queue in the case that it doesn't.

Listing 5: QueueService.cs

public static void InsureQueueExists(string queuePath)
{
//if this queue doesn't exist we will create it
if (!MessageQueue.Exists(queuePath))
MessageQueue.Create(queuePath);
}


And then we can replace this check in our QueueService.QueueMessage method.

Listing 6: QueueService.cs

MessageQueue msgQ;
InsureQueueExists(queuePath);
msgQ = new MessageQueue(queuePath);


Now we are ready to update our console app so that it makes this check as well.

Listing 7: Program.cs

class Program
{
private static MessageQueue msgQ = null;
private static object lockObject = new object();
static void Main(string[] args)
{
string queuePath = @".\private$\WebsiteEmails";
QueueService.InsureQueueExists(queuePath);
msgQ = new MessageQueue(queuePath);
}
}


Sending the emails

Now that the core guts of this thing are working we can now integrate our EmailService back into the picture. We will add this to our msgQ_RecieveCompleted event handler.

Listing 8: Program.cs

static void msgQ_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
{
lock (lockObject)
{
// The message is plain text.
EmailMessage msg = (EmailMessage)e.Message.Body;
new EmailService().SendMessage(msg,
"{username}",
"{password}",
"{host}",
587,
true,
new LoggingRepository());
Console.WriteLine("Message received: " + msg.Message);
}
// Listen for the next message.
msgQ.BeginReceive();
}


Now when we run the web application and the console application we can click the SendEmail button, see the messages get queued up in the MSMQ manager, see the console application process the queue, see in the database that our log is being added too, and see in our email client that the emails are getting sent too!
Relocating the SerializeMessage method

This looks pretty good so far. But it no longer makes sense to keep our SerializeMessage method in the EmailService. Let's move it to its own class now and then we can come back to update the QueueService. We need to create a new Serializer class. Then if you are using ReShaper you can simply put your mouse over the SerializeMessage method name and press [ctrl][shift][r] to refactor the method. Then you can choose Move to another Type from the list that pops up. If you don't have ReShaper then you can copy/paste! Don't forget to update your EmailService to use the relocated Serializer.SerializeMessage method (ReSharper does this for you!).

Listing 9: Serializer.cs

namespace AndrewSiemer.BusinessLayer.Services
{
public class Serializer
{
public static string SerializeMessage(EmailMessage message)
{
StringWriter outStream = new StringWriter();
XmlSerializer s = new XmlSerializer(typeof(EmailMessage));
s.Serialize(outStream, message);
return outStream.ToString();
}
}
}


Creating an installable Windows Service to drain the queue

To complete our distributed application we need to take the console application and beef it up a bit. While we could technically leave our queue processor in the console application and just leave the console application running all day, this is not a very "enterprise" way of doing things! For that reason we will create one last project. This time we will create a Windows Service project that can be installed on a server and left to run forever after.

Let's start by adding a new Windows Service project called WebsiteEmailService to our solution. Then set the ServiceName (in the properties window) to something you will recognize in your Services MMC. I am calling my service WebsiteEmailQueueProcessor.
A quick refactor of our console applciation

Then we need to do a quick refactor of our console application. We need to pull the code that we wrote there up into our BusinessLayer project. We will do this by adding a QueueProcessor class to our Services folder. Inside that class we will add all the code from our Project.cs file so that it can be referenced by both the console application and the service.

Listing 10: QueueProcessor.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using System.Text;
using AndrewSiemer.BusinessLayer.DataAccess;
using AndrewSiemer.BusinessLayer.Domain;
namespace AndrewSiemer.BusinessLayer.Services
{
public class QueueProcessor
{
private static MessageQueue msgQ = null;
private static object lockObject = new object();
public static void StartProcessing()
{
string queuePath = @".\private$\WebsiteEmails";
QueueService.InsureQueueExists(queuePath);
msgQ = new MessageQueue(queuePath);
msgQ.Formatter = new BinaryMessageFormatter();
msgQ.MessageReadPropertyFilter.SetAll();
msgQ.ReceiveCompleted += new ReceiveCompletedEventHandler(msgQ_ReceiveCompleted);
msgQ.BeginReceive();
while (Console.ReadKey().Key != ConsoleKey.Q)
{
// Press q to exit.
Thread.Sleep(0);
}
}
static void msgQ_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
{
lock (lockObject)
{
// The message is plain text.
EmailMessage msg = (EmailMessage)e.Message.Body;
new EmailService().SendMessage(msg,
"{username}",
"{password}",
"{host}",
587,
true,
new LoggingRepository());
Console.WriteLine("Message received: " + msg.Message);
}
// Listen for the next message.
msgQ.BeginReceive();
}
public static void StopProcessing()
{
msgQ.Close();
}
}
}


From there we can update our Program class in the console application to use this code which will make it much smaller and easier to read!

Listing 11: Program.cs

class Program
{
static void Main(string[] args)
{
QueueProcessor.StartProcessing();
}
}


We also need to move the while loop out of the QueueProcessor as that implementation will only work when ran from the Console Application. It will give us errors if ran from the Windows Service. For that reason we will relocate that looping logic to our console app like this.

Listing 12: Program.cs

class Program
{
static void Main(string[] args)
{
QueueProcessor.StartProcessing();
while (Console.ReadKey().Key != ConsoleKey.Q)
{
// Press q to exit.
Thread.Sleep(0);
}
}
}


Finishing up the Windows Service

Now that our code is accessible for both the Windows Service and the Console Application we can complete the service. In the design surface for your service click the "click here to switch to code view" link.

Adding a Timer

One of the first things that we need to do when building up our service is to add a Timer to keep track of how often our service does its job. Every time the Timer's interval completes it will fire an event that we will capture to perform our queue processing. To do this we first need to declare a private Timer instance.

Listing 13: Service1.cs

public partial class WebsiteEmailQueueProcessor : ServiceBase
{
Timer timer = new Timer();
}


Then we need to initialize our timer in the OnStart method.

Listing 14: Service1.cs

protected override void OnStart(string[] args)
{
timer.Interval = 1000;
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.AutoReset = true;
timer.Enabled = true;
timer.Start();
}


Next, we need to create our even handler which will actually kick off the processor.

Listing 15: Service1.cs

void timer_Elapsed(object sender, ElapsedEventArgs e)
{
QueueProcessor.StartProcessing();
}


Lastly, we need to add some code to the OnStop method of our service that will stop the timer and free the resources in our QueueProcessor.

Listing 16: Service1.cs

protected override void OnStop()
{
QueueProcessor.StopProcessing();
timer.AutoReset = false;
timer.Enabled = false;
}


Logging makes building a service much easier!

I didn't want to bog down our code examples with logging code. But in the code download for this article you will find that I have added some error handling and logging code. This will allow you to look into what is going on with the service when you attempt to install it, run it, etc. which will ultimately help you track down problems in your service. My logging implementation just appends text to a text file in the root of your C drive. You may want to update this to run from somewhere else!

Making the service installable

Now that we have everything ready for testing we have a few more steps to perform to get our service installed and running. To make an installer for our service you need to go the design surface of your service. Then right click in the grey area and select add installer. This will add two components to your design surface, a service process installer, and a service installer. You might want to rename these to something more descriptive to your project. I prefixed both of them with WebsiteEmailQueueProcessor.

In the service installer you will want to give your service a description and name that means something to you when looking at the service in the Services MMC. I named my service "Website Email Queue Processor" and gave it a description of "Website email queue processing service".

Then in the process installer you will want to change the Account that your service will run under by default to "LocalSystem". This should give your service enough rights to run after the basic install process (described shortly).

The last and most important step of all this is to navigate to the properties window for your windows service project. In the application tab make sure that you set the Startup Object to the Program class in your service project.

Now you can build the entire solution (cross your fingers). Once everything builds ok we can get this puppy installed and running.

Installing your website email queue processing service

To get your service installed you need to open the Visual Studio command prompt in administrator mode. Then navigate to the directory that contains your service executable. This is most likely in the bin/debug folder of your service project. Then you can run installutil and the executable name to install your service.

Run these commands in the Visual Studio command prompt.

Listing 17: Visual Studio Command Prompt in Administrator Mode

cd /d {drive letter where your code is}:
cd "{full path to project}\bin\debug\"
installutil {name of executable}.exe

Microsoft (R) .NET Framework Installation utility Version 4.0.30319.1
Copyright (c) Microsoft Corporation. All rights reserved.

Running a transacted installation.

.........

The Commit phase completed successfully.
The transacted install has completed.


If you want to remove a service, you can type following command in the Visual Studio command prompt:

installutil /u {name of executable}.exe

If you find that you are having issues getting your service installed, you can always check the folder that contains your executable. After running the installutil you will have a couple of log files that will give you the details of your installation. Check there for more clues and google for the answer!

With any luck everything should be installed and at this point. You will then need to go to the Services MMC and start your service. You should now be able to run your web application and click the magical Send Email button. And after a few seconds that email should arrive in your inbox!

Summary

In our previous article we discussed why sending email directly from a website upon a user's request might be a bad idea. We then discussed some of the options for getting around these various forms of evil. We then created a demo application that sent email directly from the website. In this article we refactored our initial code base so that it would use a distributed method of sending email using an MSMQ private queue and a Windows Service to drain that queue and do the heavy lifting of sending email.

Sending email from ASP.NET MVC through MVC and MSMQ Part 1

Original Post: http://dotnetslackers.com/articles/aspnet/Sending-email-from-ASP-NET-MVC-through-MVC-and-MSMQ-Part1.aspx

Published: 22 Mar 2010
By: Andrew Siemer

In this article you will learn how to send emails using ASP.NET MVC and MSMQ.

Contents

  1. Introduction
  2. An example of sending mail directly to SMTP
    1. Creating the ASP.NET MVC web application
    2. Creating the email logging database
    3. Creating a quick business layer
    4. Adding LINQ to SQL support for data access
    5. Creating an email wrapper
    6. Logging to the database
    7. Hooking up our web page
    8. Ready to send an email?
  3. Summary

Sending email from ASP.NET MVC through MVC and MSMQ Part Series

Introduction

I have worked in a lot of different web environments ranging from high traffic social networking sites to high transaction ecommerce sites. One thing every site has in common regardless of the industry that it serves is that at some point in time it will need to send an email communication to someone. In the case of a community site you might send an email to a user when they comment on a friend's profile. For ecommerce sites you might send a confirmation email when someone purchases a product from your site.

Regardless of the reason that the email is being sent, sending it directly from your web sites worker process is generally a bad idea. Connecting to an SMTP server, especially one on a separate server, can be a long blocking process. Adding insult to injury, the poor guy that performed the initial button click of some kind is now stuck waiting for the next web page to return. And if you work in an environment that needs to log every communication with its customers (a common requirements these days), the customer may have to endure the wait for the sending of the email as well as a dip to an email logging database. Luckily for your customer there is a better method!

In this article we will take a look at all the normal steps required to send an email directly from an ASP.NET MVC web page. We will also discuss how to log all of our communications by serializing our email communications to a logging database with LINQ to SQL. Once we complete this article we will have a working codebase that we can then refactor to send email in a more efficient and disconnected manner through MSMQ.
An example of sending mail directly to SMTP

In the majority of consulting gigs I have been a part of I almost always come across a web page that connects directly to an SMTP server. It creates an instance of MailMessage, populates various properties of that message, spins up an instance of SmtpClient, and attempts to send the message. If the message was sent successfully then we can log it to a database. If the message doesn't send then we can log the failed attempt too.
Creating the ASP.NET MVC web application

Let's create a quick web application

that works in this fashion. To start we will create an ASP.NET MVC 2 application (in Visual Studio 2010). I am going to place mine in a source folder and call the application "Web Application" (clever eh?).

Creating the email logging database

Then we need to create the database for the logging side of our application. Right click on the App_Data folder in your MVC application and choose to add a new item. Then select a SQL Server Database (you need SQL Express installed for this to work). Name the database EmailLogging.mdf and click Add. The new database should then show up in the App_Data folder as well as under your Data Connections section of the Server Explorer.

Expand the database in the Data Connections window. Right click on the Tables folder and select add new table. Add a column named EmailLogID with an int data type and don't allow nulls. Then mark that column as a primary key (click the key above). Then scroll down in the Column Properties and set the (Is Identity) filed under the Identity Specification to Yes.

Then add a SentSuccessfully field with a data type of bit and don't allow nulls.

Next we will add a SentDate field with a data type
of date (about time we got this data type!).

And lastly we will add a Message field with a data type of varchar(500).

Now you can save your table. Name the table EmailLogs in the window that pops up.

Creating a quick business layer

Now we can add a new class library to manage our data access and business logic. Do this by right clicking on your solution and selecting to add a new project. Choose to add a new Class Library project. Name this project BusinessLayer. Then add a reference from your WebApplication project to your BusinessLayer project. This can be done by right clicking on the WebApplication project and selecting add reference. In the project tab, select the BusinessLayer project.

Adding LINQ to SQL support for data access

The quickest way to achieve data access these days is through the uses of LINQ to SQL! Add a folder to the BusinessLayer project called Domain. Then right click on that folder and choose to add a new item. Then add a LINQ to SQL Classes item and call it Logging.dbml.

NOTE

The name you choose here will be used to generate a {nameYouPick}DataContext class. If you choose AndrewsEmailLoggingContext.dbml you will end up with an AndrewsEmailLoggingContextDataContext class that you have to do all your data access through. Buyer beware!

Now you can drag the EmailLogs table we create out of the Data Connections->EmailLogging.mdf->Tables section of the Server Explorer on to the design surface of your Logging.dbml. This will generate an EmailLogging class for you. Now save your Logging.dbml file. Then build your project so that your LoggingDataContext will be created for you as we will need it in upcoming steps.

Why did you put the LINQ to SQL classes in the Domain folder?

Good question. The LINQ to SQL classes item sort of leaks it's concerns throughout your application so you have to know how to pick the lesser of two evils when deciding where to put this thing. LINQ to SQL performs (at least) two functions for you. 1) It creates the classes that represent your database objects. 2) It provides you with the tools you need to query the database with.

What this means to you from a code organization perspective is that you either have Domain objects that live in a DataAccess folder (ugly) or code that you never directly reference in your application that lives in your Domain folder. What I mean to say is that you will use a Repository class that you create and that Repository class will have a reference to Domain.LoggingDataContext. Equally ugly but you only have to touch it when building the repositories.

If this discussion is boring you then it doesn't apply to you. If this discussion has you thinking then you should probably use the Entity Framework or NHibernate! :P

Creating an email wrapper

Next we need to create a quick wrapper class that will handle sending email for us. We will do this by creating a new folder in our BusinessLayer project called Services. Inside that we can create an EmailService class. We will use this class as the entry point into sending our email directly through SMTP. Make this class public and add a method called SendMessage.

Listing 1: EmailService.cs

public void SendMessage(EmailMessage message, string username, string password, string host, int port)
{
}


Use ReShaper to save you some time!

If you are a big ReSharper fan you might just implement the usage of the EmailMessage directly in the SendMessage method and then use ReSharper to create the EmailMessage class for you (must faster).

Now go to the Domain folder and create a new class called EmailMessage.
Listing 2: EmailMessage.cs

namespace AndrewSiemer.BusinessLayer.Domain
{
public class EmailMessage
{
public string To { get; set; }
public string From { get; set; }
public string Subject { get; set; }
public string Message { get; set; }
}
}


Back in your EmailService we can now map our EmailMessage properties into the constructor of a MailMessage instance.

Listing 3: EmailService.cs

MailMessage mm = new MailMessage(message.From, message.To, message.Subject, message.Message);

After that we can create an instance of NetworkCredential with the passed in username and password. And then we can create an instance of SmtpClient with the host and port. And then we can bring those two together by passing in the credentials to the SmtpClient.

Listing 4: EmailService.cs

public void SendMessage(EmailMessage message, string username, string password, string host, int port, bool enableSsl)
{
MailMessage mm = new MailMessage(message.From, message.To, message.Subject, message.Message);
NetworkCredential credentials = new NetworkCredential(username, password);
SmtpClient sc = new SmtpClient(host, port);
sc.EnableSsl = enableSsl;
sc.Credentials = credentials;
}


Once this is completed we are ready to try to send our message with a call to SmtpClient.Send().

Listing 5: EmailService.cs

try
{
sc.Send(mm);
//add to logging db
}
catch (Exception)
{
//add to logging db
throw;
}
SmtpClient.SendAsync()


If you really just want to send email from your page "because that is how you have always done it" you should at least upgrade to .NET 4 and use the SendAssync method (http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx)

Now we can create one last method to serialize a mail message for us which we can then pass into our logging database.
Listing 6: EmailService.cs

public static string SerializeMessage(EmailMessage message)
{
string result = "";
StreamWriter tw = new StreamWriter(result);
XmlSerializer x = new XmlSerializer(message.GetType());
x.Serialize(tw, message);
return tw.ToString();
}


And now we can serialize our mail message to be logged by adding this line to our SendMessage method.

Listing 7: EmailService.cs

public void SendMessage(EmailMessage message, string username, string password, string host, int port)
{
string serializedMessage = SerializeMessage(message);
MailMessage mm = new MailMessage(message.From, message.To, message.Subject, message.Message);
}


Logging to the database

Now we are ready to build up a repository for our logging purposes. Add a new folder to the business layer called DataAccess. Then add a class called LoggingRepository. Then add a method called LogMessage. In this method we will connect to our database and insert our serialized message.

Listing 8: LoggingRepository.cs

public class LoggingRepository
{
public void LogMessage(string message, bool sentSuccessfully)
{
string connectionString =
@"Data Source=.\SQLEXPRESS;AttachDbFilename={pathToDatabase}\EmailLogging.mdf;Integrated Security=True;User Instance=True";
using(LoggingDataContext dc = new LoggingDataContext(connectionString))
{
EmailLog el = new EmailLog();
el.Message = message;
el.SentDate = DateTime.Now;
el.SentSuccessfully = sentSuccessfully;
dc.EmailLogs.InsertOnSubmit(el);
dc.SubmitChanges();
}
}
}


Now we can return to the EmailSerivce and wire up our LoggingRepository. Start by adding another parameter to our SendMessage method that takes in an instance of our new LoggingRepository. Then replace the "//add to logging db" comments with a call to the LoggingRepository.LogMessage method.

Listing 9: EmailService.cs

try
{
sc.Send(mm);
repository.LogMessage(serializedMessage, true);
}
catch (Exception)
{
repository.LogMessage(serializedMessage, false);
throw;
}


Hooking up our web page

Now we can return to our web application. Open the Views/Home folder and then open the Index.aspx view page. We are going to add a form with a button that will allow us to catch a post to an action that will attempt to send an email for us.

Listing 10: Index.aspx

<% Html.BeginForm("Index", "Home"); %>

<% Html.EndForm(); %>


With this in place we can then navigate to our HomeController. In the HomeController we need to add a new action to catch the form submission from the Index view. Make sure that you specify the HttpPost attribute! Without it our form post won't find this new action.

Listing 11: HomeController.cs

[HttpPost]
public ActionResult Index(string id)
{
return View();
}


Once we have our new action in place we can then wire up our email sending code! We need to create a new instance of a MailMessage. Then we need to populate the various properties of our MailMessage. From there we can create an instance of EmailService and pass in all the various properties that your SMTP server requires.

Listing 12: HomeController.cs

[HttpPost]
public ActionResult Index(string id)
{
EmailMessage em = new EmailMessage();
em.Subject = "test message";
em.Message = "howdy from asp.net mvc";
em.From = "asiemer@andrewsiemer.com";
em.To = "asiemer@andrewsiemer.com";
new EmailService().SendMessage(em,
"{email account}",
"{password}",
"{smtp server address}",
{smtp port},
{ssl or not},
new LoggingRepository());
return View();
}


Ready to send an email?

With all of these steps completed you should now be able to hit F5 and run your web application. When it pops open you will have a "SendEmail" button on your form just begging to be clicked. When you click it an email should be sent (or not depending on lots of things). And regardless of the status of your email being sent you should get a serialized EmailMessage logged into your database. If the email was sent you will probably notice that it took at least several seconds to perform its operation. If your email server was not available then you would have noticed that the server took around a minute (give or take) to tell you that it wasn't available for sending messages. Add to that the latency of logging the message into the database and you have a slow process no matter how successful it was!

Listing 13: Serialized EmailMessage from the EmailLogs table


asiemer@andrewsiemer.com asiemer@andrewsiemer.com test message howdy from asp.net mvc


Summary

In this article we discussed some of the issues with sending email directly out of a page in your web application. We then jumped into creating an example ASP.NET MVC application that would send email in this manner. Our example also serialized all of our communications and logged them into a logging database using LINQ to SQL.

In the next article we will take a look at the steps required to move away from this thread blocking way of sending email. We will then implement a disconnected method of sending email communications using MSMQ.