Sending emails in your app is a normal thing – after some operation, you must send confirmation data to the user, so he can keep the record of it. All the infrastructure for that is available in  .NET, in the System.Net.Mail namespace, there is not much secret in that.

But sometimes things can be more difficult than that – there may be many templates for the email, depending on the kind of email you want to send, they are HTML based and the data in it must come from a different source, like a database.

Sending HTML emails

Sending an HTML email in .NET is fairly easy: you just have to create a MailMessage object, set its From, To, Subject and Body fields, set the IsBodyHtml property to true and send the message using an SmtpClient object:

static void Main(string[] args)
{
    var mail = new MailMessage
    {
        From = new MailAddress("sender@gmail.com"),
        Subject = "Test Mail",
        Body = @" ... ",
        IsBodyHtml = true
    };
    mail.To.Add("email@server.com");
    var client = new SmtpClient("smtp.gmail.com")
    {
        Port = 587,
        Credentials = new System.Net.NetworkCredential(
             username, password),
                EnableSsl = true
    };
 
    client.Send(mail);
 }

Templated emails

The previous code sends a fixed email, but sometimes we have to send a templated email, where we have a template and must fill it with some variables that come from a different source. The variable parts can come embedded in many ways, like between special characters, but I’ll choose the Mustache (http://mustache.github.io/) way: using double braces before and after every variable, like this {{variable}}.

We now need to read the template, find the variables and replace them with the data, creating an HTML string that will be assigned to the Body property of the email:

static void Main(string[] args)
{
    var template = File.ReadAllText("EmailTemplate.html");
    var data = JsonConvert.DeserializeObject<Dictionary>(
        File.ReadAllText("EmailData.json"));
    data.Add("date",DateTime.Now.ToShortDateString());
    var emailBody = ProcessTemplate(template, data);
    var mail = new MailMessage
    {
        From = new MailAddress("sender@gmail.com"),
        Subject = "Test Mail",
        Body = emailBody,
        IsBodyHtml = true
    };
    mail.To.Add("email@server.com");
    var client = new SmtpClient("smtp.gmail.com")
    {
        Port = 587,
        Credentials = new System.Net.NetworkCredential(
           username, password),         
        EnableSsl = true
    };

    client.Send(mail);
}

As we are using a dictionary with the variables, I’ve added a new variable that doesn’t come from the file: the current date. This method is very flexible and you can add data that comes from many sources.

The ProcessTemplate method uses a simple Regex replace to replace the found variables with the data in the dictionary:

private static string ProcessTemplate(string template, 
    Dictionary data)
{
    return Regex.Replace(template, "\\{\\{(.*?)\\}\\}", m =>
        m.Groups.Count > 1 && data.ContainsKey(m.Groups[1].Value) ? 
            data[m.Groups[1].Value] : m.Value);
}

Improving the processing

The processing we’ve chosen is very simple and we can improve it. We can use a library that processes the Mustache variables, like Nustache (https://github.com/jdiamond/Nustache). To use it, we just have to add the Nustache Nuget package. With it installed, the ProcessTemplate method becomes:

private static string ProcessTemplate(string template, 
    Dictionary data)
{
    return Render.StringToString(template, data);
}

This is easier and doesn’t rely in the Regex processing. You can also use some helper functions in the processing. For example, if your data file has the first and last name and you want the full name in the replaced template, you can define a function like this:

private static void FullName(RenderContext context, 
    IList arguments, IDictionary options, 
    RenderBlock fn, RenderBlock inverse)
{
    if (arguments?.Count >= 2) 
        context.Write($"{arguments[0]} {arguments[1]}");
}

And register it like this:

Helpers.Register("FullName", FullName);

Easy, no? Now we have a simple way to create a templated email with data coming from different sources. We’ve used Nustache to process the template, but you could use something else like Handlebars.net (https://github.com/rexm/Handlebars.Net), which would be very similar to what we did here.

The full source code for the project is in https://github.com/bsonnino/HtmlEmail

Introduction

On my developer work, there are some tools that make my job much easier and I use them on a daily basis and miss them when I go to a computer where I don’t have them. To create code, I think that there’s no better tool than Resharper (see my article about it here). For debugging code, the equivalent is OzCode (http://oz-code.com/). I’ve been an OzCode user since its early betas (it was called BugAid, at those days), and it’s been improving from version to version, and its features are really valuable when debugging an app.

Using OzCode

When you are creating a program, you won’t see anything about OzCode, but as soon as you start debugging your program, OzCode appears and start to shine. One of my favorite features there is what they call Reveal (but I call this “Show me what I want”). Here’s the problem: if I have a list of items and I open it, all I see is something like this:

image

This is not what I want. As you can see, I have a list of 91 customers, and what is shown is the ToString evaluation of each one (“OzCodeTest.Customer”). I’d like to see what’s in each one of these customers and search for the ones I want. You may argue that I can create a ToString override and show what I want, but that is not intuitive, and I may change my mind while debugging (at the beginning I want to see the Id and Name, but in the middle of debugging I want to see the Name and City). And what about to find which one is located in London?

With OzCode, this is solved by simply opening one member and clicking on the star near it: the member is “favorited” and is shown in the list:

image

And what about searching? You just have to type in the search box and all items that match the search are shown:

image

If you want to create some special data, without having to create a new member, you can do so: just click on the magic wand besides the object and select “Add custom Expression”. Then, you can type the expression you want, and put the name of the new “member” after a double slash, like a comment:

[sourcecode language='csharp'  gutter='false']
[obj].City == “London” // IsFromLondon
[/sourcecode]

And it will appear on the list of members, where you can even make it as a favorite:

image

And if I only want to see the customers from London? Just click on the magic wand and select “Edit Filter”. Then, type the filter “[obj].City == “London””. The list of customers is filtered to show only the ones whose city is London:

image

One other thing that you can do here is to compare versions of the two lists: how many times do you need to know what changed between two points in the debugging? It’s very easy to find out. Just stop on the first point and click on the magic wand and select “Compare/Save value”. This will open a window to confirm. Confirm and continue running until the second point. Then click on the magic wand again and select “Compare/Compare with saved value”. A window appears and you can compare the two values. If you want to show only the differences, just click “Show differences only”:

image

Instant logging

The inspector window on steroids is very nice, but there is more help for our debugging. For me, it’s very common to need some logging in the code, to see what’s happening. I have to add a logging library, add code to log data and then analyze all logs in a separate tool. Too much work and sometimes I miss what I was expecting. So I must add a little more logging, repeat and rinse. Very cumbersome. With OzCode, all I have to do is to select the variable I’m interested, click on the yellow note icon that appears on the left and select Trace value of {variable}. That will add a new trace point that will log the value I’m interested to see.

 

image

When you run the program, you can see the number of messages traced in the bottom of the window, near the yellow note.

image

When you stop the program, you can see all messages sent in the Tracepoint viewer window:

image

There you can search for something, export the data to Excel, csv or text, so you can have a file to analyze later. Two nice features there are the Thread Id and the Stack trace. Often it’s difficult to debug multi-threading programs, when you go step by step, it’s difficult to follow the code, as the same code can be reached by different threads. If you click in the arrow next the thread Id, you will see from which threads this code was logged, and filter only some of them:

image

When you filter one thread, you can get only the messages that come from that thread:

image

The other thing that is nice is the stack trace. I always have the question: “How did the code reached here?”. The stack trace answers this:

image

Nice, no?

Swami sees all, the past and the future

If you take a look at the figure below, you will see a glimpse of the past and the future:

image

Just above line 16, you will see that we are working with the “ALFKI” customer. In line 18, you can see that the customer’s city is Berlin. OzCode will show you the following line dimmed – that line won’t be executed and the execution will go to line 20, where there is the arrow. You can also see that the second part of the If won’t be executed (it’s crossed out). You also can see the red X near the line, indicating it is false.

If you click on the glasses near the line, you will see more info:

image

You can have a lot of info about your data and how you reached there.

Exception handling

One thing that bothers me regarding exceptions is when I get an exception buried inside a bunch of Inner Exceptions. I must drill down the exception until I find something that is valuable. OzCode makes this a lot easier: when an exception is thrown, something like this one is shown:

image

You can see the exception that occurred above the line (in the code, above line 17), with four icons:

  • The first one will open the exception box – it is showing that there are two nested exceptions
  • The second one will toggle break in this kind of exception
  • The third one will go to the line where the exception occurred
  • The fourth one will search for help on Google, StackOverflow, Yahoo or Bing

If you click on the first icon or in the icon on the left of the line, it will open the exception box:

image

On the top, you will see a breadcrumb of the exception. You can click on any exceptions there and it will show you all the data for that exception and you can go to where the exception was thrown or where the exception was handled. You can also search for help in this window.

Another exception helper is the exception prediction. If you are stepping through code that will generate an exception, you get something like this:

image

You can click on the icon and skip the line, thus not throwing the exception or, if you are using Visual studio 2015, you can even edit the code and continue:

image

That’s really a great way to make your code more solid proof!

Conclusion

As you can see, OzCode gives you a lot of help for your debugging, I received a free copy due to the fact I’m a Microsoft MVP, but I really enjoy using it. If you want to try it by yourself, you can download a free version at http://oz-code.com. Happy debugging!

One of the indirect benefits of being a Microsoft MVP is that many tool or component producers give copies for MVPs for their personal use, so they can use, evaluate and, if they like it, recommend it.

I use many of these tools on a daily basis and like them very much. So nothing more fair than write a post about them and how they help my work.

There is no doubt that the tool I use the most is ReSharper (http://www.jetbrains.com/resharper/), an add-in for Visual Studio to enhance your productivity. When I use Visual Studio, it’s always there, helping me to write code.

Code analysis

When you open a project, ReSharper will analyze your code and start to give you suggestions to enhance it. When you open a console project, you will see something like this on the editor:

image_thumb50

On the right side, a new bar is added with help indicators for your code. The yellow square at the top shows that there are warnings to improve your code. If it’s red, there are compile errors and, if your code is ok, the square turns green. Below the square, there are some bars indicating the points where problems are found. If you hover the mouse over the bars, a tooltip will show the problem.

image_thumb3

Fixing the error is very simple. You just have to click on the bar and the editor will be positioned on the place of the error. A red bulb will indicate the error and we can click on it to show the available actions. This list can be selected with Alt-Enter. If I could only remember one ReSharper shortcut, this would be the one. It will do many fixes for you, with Alt-Enter your code will improve a lot!

 

image_thumb5

We select the desired action and ReSharper corrects the code (by eliminating the using clauses not needed). To fix next error, we can see that the args parameter in the Main function is in gray. That means that it’s not being used there. When we put the mouse over the args parameter, ReSharper shows a pyramid, indicating that there is a refactoring to be made.

 

image_thumb7

It will remove the unused parameter. Besides this change, it will verify all places where the function is called and change its call. That’s great when we add a parameter and later we verify it is not needed and we want to remove it. If we do that, all places where the function is called will not compile. With this refactoring, our code won’t break anymore.

 

image_thumb54

ReSharper is constantly analyzing our code and checking consistency on variables and methods names. You can tell how do you like to name the fields, properties and methods and it will check the consistency for you.

 

image_thumb13

For example, I like to name my private fields using CamelCase, starting with a lowercase character (with no leading underscore). If I put a field using a different naming, ReSharper will tell me and ask to change it. Just press Alt-Enter and it will change the name and all references to this variable.

image_thumb56

Code improvement

ReSharper also verifies the quality of your code. Yes, I know that your code (like mine) is wonderful, but can it be improved? Take a look on the figure below, where I have a WPF application where I’ve added the event handler of the Click event for a button in code, using button1.Click += <tab><tab>.

image_thumb59

ReSharper shows two warnings and a reminder. The first warning is about MainWindow. It shows that the parent type (Window) has been already declared and is not necessary. We should remember that when we create a WPF window we are creating a partial class, declared in two places: on the XAML and on the code behind. The XAML already tells that MainWindow inherits from Window and we can remove this redundant declaration from the code behind. The second warning is due to the fact that we can eliminate the delegate creation when adding the handler. The reminder is to tell us that we have a “Not Implemented” exception, a clear indication that we must add code there. Pressing Alt-Enter twice, and our code will be changed to:

image_thumb61

ReSharper analyses your code, checking for improvements and possible errors. When you enter this code

image_thumb63

you can see on the bar on the right a warning and a possible improvement. The warning tells us that ToString is redundant and that we must specify a culture for the conversion. The fact that it’s redundant makes it a candidate for elimination. Alt-Enter and there it goes. The next improvement is in the for, that can be converted to a LINQ expression. Pressing Alt-Enter again we end up with this code:

image_thumb66

Other common code improvements are if and return optimizations: when we put something like this

 

if (x == 3) y = 2; else y = 5;

ReSharper optimizes to:

y = x == 3 ? 2 : 5;

Or this code:

if (x == 3) return 2; else return 5;

Here, we have two optimizations: eliminate the else

if (x == 3) return 2; return 5;

or use the ternary operator:

return x == 3 ? 2 : 5;

Refactoring

That’s not all that ReSharper can do for you. Its refactoring tools and code creation are fantastic. If we want to extract the code from the event handler to a new method, we can press Ctrl-Shift-R (Refactor this) and ReSharper will show all available refactorings.

image_thumb72

We select the extract method refactoring and this screen is shown:

image_thumb31

We can indicate the parameters, the function name and its return type. By clicking on Next, we get something like

image_thumb68

Code creation

We can also insert code using templates. ReSharper allows to create templates with code for new files or code snippets.

image_thumb39

 

We have three kinds of templates:

  • Live templates – code snippets templates, inserted like Visual Studio snippets. To insert them, we must add the snippet name and press <tab> to insert. One other way to insert these snippets is by using Ctrl-E-L. On the figure above, I’ve created the propnp snippet, that creates a property with a backing field and calls the PropertyChanged handler.
  • Surround templates, that surround the code with a template, like to surround the code with a try…catch. They can be invoked with Ctrl-E-U.
  • File templates – they create new files on our project, like new classes or interfaces. They are invoked with Ctrl-Alt-Ins.

We will create a new class in our project. We press Ctrl-Alt-Ins and create a new class, calling it NewClass. We then press Alt-Ins and insert the constructor for the class. On the constructor parameters, we insert a dependency:

image_thumb41

Note that IDependency is in red, because we have not defined this interface. We press Alt-Enter and these options are shown:

image_thumb43

ReSharper has noted that we’ve set the type name starting with ’I’ and suggests to create a new interface. We can create our interface from here. After creating the interface, we press Alt-Enter again in IDependency in the constructor and we can declare a field to store the dependency:

image_thumb45

Our interface was created on the same file as the class file. We can go to its declaration and press Alt-Enter. ReSharper offers to move it to a different file. A new IDependency.cs file is created with the interface. Easy, no? It also eases the variables declaration. For example, when we enter code like

total = 1;

on the constructor, we see that total is in red. Pressing Alt-Enter we have these options:

image_thumb47

We can create a total field on our code. As we can see, we have many ways to change and improve our code.

XAML help

But that is not alll that we get. We can use ReSharper also while editing XAML code. For example, if we create a Converter in code:

public class DebugConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value; } }

When we want to use it in XAML, we must follow some steps: namespace, resource declaration, etc. ReSharper can help us for that.

image_thumb74

We press Alt-Enter in DebugConverter and select Create resource in type element <Window>. ReSharepr creates the Resources section and creates the resource. We add the name DebugConverter with no namespace. A tooltip is shown indicating the needed namespace

image_thumb76

We then press Alt-Enter and the namespace is added to the window declaration and the prefix added to the element. If we don’t like its name, we can rename it with Ctrl-R-R. Everything needed is ready, now. If we have a DataContext associated to the element and it doesn’t have a property named Valor, we can use ReSharper to create this property on the DataContext class, like a ViewModel.

image_thumb80

Code navigation

ReSharper has many shortcuts for code navigation. For example, Ctrl-T navigates to a defined type. A screen like this open is opened

image_thumb70

We enter part of the name and it shows all types that match with the search. On the same way, we can use Shift-Alt-T to go to a symbol or Ctrl-Shift-T to go to a file. The search is done in all solution’s files. The navigation between members of a class can be done with Alt-`. You can go to the previous or next member with Alt-Up or Alt-Down. If you want, you can even go to a decompiled .net code. ReSharper has a decompiler that decompiles the code and allows navigating to it.

image_thumb85

Misc utilities

You have many othere goodies in ReSharper. You have a unit test runner, where you can run your unit tests. You may be thinking that Visual Studio already has a test runner, but the one VS has runs only MSTest tests. ReSharper runner works with MSTests, NUnit, QUnit or xUnit. One other interesting functionality is the Explore Stack Trace. You have an exception stack trace that comes from any source. You can copy the stack trace to the clipboard and, in Visual Studio, use Ctrl-E-T. The stack trace is shown with links to your code, so you can go to the place where the exception occurred.

image_thumb83

Conclusion

This is just part of the functionality offered by ReSharper, there is much more to explore, but I leave that for you. This is a paid tool, but you can download a 30 days trial version in http://www.jetbrains.com/resharper/download/index.html.

I really think this is an indispensable tool for everyone who develops with Visual Studio, I just have a point against it: it is really addictive and once you get used to using ReSharper, it’s very difficult to develop without it. wlemoticon-smile