• Beth Massi - Sharing the goodness

    How To Send HTML Email from a LightSwitch Application

    • 14 Comments

    A while back Paul Patterson wrote an awesome step-by-step blog post based on a forum question on how to send an automated email using System.Net.Mail from LightSwitch. If you missed it here it is:

    Microsoft LightSwitch – Send an Email from LightSwitch

    This is a great solution if you want to send email in response to some event happening in the data update pipeline on the server side. In his example he shows how to send a simple text-based email using an SMTP server in response to a new appointment being inserted into the database. In this post I want to show you how you can create richer HTML mails from data and send them via SMTP. I also want to present a client-side solution that creates an email using the Outlook client which allows the user to see and modify the email before it is sent.

    Sending Email via SMTP

    As Paul explained, all you need to do to send an SMTP email from the LightSwitch middle-tier (server side) is switch to File View on the Solution Explorer and add a class to the Server project. Ideally you’ll want to put the class in the UserCode folder to keep things organized.

    image

    TIP: If you don’t see a UserCode folder that means you haven’t written any server rules yet. To generate this folder just go back and select any entity in the designer, drop down the “Write Code” button on the top right, and select one of the server methods like entity_Inserted.

    The basic code to send an email is simple. You just need to specify the SMTP server, user id, password and port. TIP: If you only know the user ID and password then you can try using Outlook 2010 to get the rest of the info for you automatically.

    Notice in my SMTPMailHelper class I’m doing a quick check to see whether the body parameter contains HTML and if so, I set the appropriate mail property.

    Imports System.Net
    Imports System.Net.Mail
    
    Public Class SMTPMailHelper
        Const SMTPServer As String = "smtp.mydomain.com"
        Const SMTPUserId As String = "myemail@mydomain.com"
        Const SMTPPassword As String = "mypassword"
        Const SMTPPort As Integer = 25
        Public Shared Sub SendMail(ByVal sendFrom As String,
                                   ByVal sendTo As String,
                                   ByVal subject As String,
                                   ByVal body As String)
            Dim fromAddress = New MailAddress(sendFrom)
            Dim toAddress = New MailAddress(sendTo)
            Dim mail As New MailMessage
    
            With mail
                .From = fromAddress
                .To.Add(toAddress)
                .Subject = subject
    
                If body.ToLower.Contains("<html>") Then
                    .IsBodyHtml = True
                End If
    
                .Body = body
            End With
    
            Dim smtp As New SmtpClient(SMTPServer, SMTPPort)
            smtp.Credentials = New NetworkCredential(SMTPUserId, SMTPPassword)
            smtp.Send(mail)
        End Sub
    End Class

    Creating HTML from Entity Data

    Now that we have the code to send an email I want to show you how we can quickly generate HTML from entity data using Visual Basic’s XML literals. (I love XML literals and have written about them many times before.) If you are new to XML literals I suggest starting with this article and this video. To use XML literals you need to make sure you have an assembly reference to System.Core, System.Xml, and System.Xml.Linq.

    What I want to do is create an HTML email invoice for an Order entity that has children Order_Details. First I’ve made my life simpler by adding computed properties onto the Order_Details and Order entities that calculate line item and order totals respectively. The code for these computed properties is as follows:

    Public Class Order_Detail
        Private Sub LineTotal_Compute(ByRef result As Decimal)
            ' Calculate the line item total for each Order_Detail
            result = (Me.Quantity * Me.UnitPrice) * (1 - Me.Discount)
        End Sub
    End Class

    Public Class Order
        Private Sub OrderTotal_Compute(ByRef result As Decimal)
            ' Add up all the LineTotals on the Order_Details collection for this Order
            result = Aggregate d In Me.Order_Details Into Sum(d.LineTotal)
        End Sub
    End Class

    Next I want to send an automated email when the Order is inserted into the database. Open the Order entity in the designer and then drop down the “Write Code” button on the top right and select Order_Inserted to generate the method stub. To generate HTML all you need to do is type well formed XHTML into the editor and use embedded expressions to pull the data out of the entities.

    Public Class NorthwindDataService
        Private Sub Orders_Inserted(ByVal entity As Order)
            Dim toEmail = entity.Customer.Email
    
            If toEmail <> "" Then
                Dim fromEmail = entity.Employee.Email
                Dim subject = "Thank you for your order!"
    
                Dim body = <html>
                               <body style="font-family: Arial, Helvetica, sans-serif;">
                                   <p><%= entity.Customer.ContactName %>, thank you for your order!<br></br>
                                   Order date: <%= FormatDateTime(entity.OrderDate, DateFormat.LongDate) %></p>
                                   <table border="1" cellpadding="3"
                                       style="font-family: Arial, Helvetica, sans-serif;">
                                       <tr>
                                           <td><b>Product</b></td>
                                           <td><b>Quantity</b></td>
                                           <td><b>Price</b></td>
                                           <td><b>Discount</b></td>
                                           <td><b>Line Total</b></td>
                                       </tr>
                                       <%= From d In entity.Order_Details
                                           Select <tr>
                                              <td><%= d.Product.ProductName %></td>
                                              <td align="right"><%= d.Quantity %></td>
                                              <td align="right"><%= FormatCurrency(d.UnitPrice, 2) %></td>
                                              <td align="right"><%= FormatPercent(d.Discount, 0) %></td>
                                              <td align="right"><%= FormatCurrency(d.LineTotal, 2) %></td>
                                          </tr>
                                       %>
                                       <tr>
                                           <td></td>
                                           <td></td>
                                           <td></td>
                                           <td align="right"><b>Total:</b></td>
                                           <td align="right"><b><%= FormatCurrency(entity.OrderTotal, 2) %></b></td>
                                       </tr>
                                   </table>
                               </body>
                           </html>
    
                SMTPMailHelper.SendMail(fromEmail, toEmail, subject, body.ToString)
            End If
        End Sub
    End Class

    The trick is to make sure your HTML looks like XML (i.e. well formed begin/end tags) and then you can use embedded expressions (the <%= syntax) to embed Visual Basic code into the HTML. I’m using LINQ to query the order details to populate the rows of the HTML table. (BTW, you can also query HTML with a couple tricks as I show here).

    So now when a new order is entered into the system an auto-generated HTML email is sent to the customer with the order details.

    image

    Sending Email via an Outlook Client

     The above solution works well for sending automated emails but what if you want to allow the user to modify the email before it is sent? In this case we need a solution that can be called from the LightSwitch UI. One option is to automate Microsoft Outlook -- most people seem to use that popular email client, especially my company ;-). Out of the box, LightSwitch has a really nice feature on data grids that lets you to export them to Excel if running in full trust. We can add a similar Office productivity feature to our screen that auto generates an email for the user using Outlook. This will allow them to modify it before it is sent.

    We need a helper class on the client this time. Just like in the SMTP example above, add a new class via the Solution Explorer file view but this time select the Client project. This class uses COM automation, a feature of Silverlight 4 and higher. First we need to check if we’re running out-of-browser on a Windows machine by checking the AutomationFactory.IsAvailable property. Next we need to get a reference to Outlook, opening the application if it’s not already open. The rest of the code just creates the email and displays it to the user.

    Imports System.Runtime.InteropServices.Automation
    
    Public Class OutlookMailHelper
        Const olMailItem As Integer = 0
        Const olFormatPlain As Integer = 1
        Const olFormatHTML As Integer = 2
    
        Public Shared Sub CreateOutlookEmail(ByVal toAddress As String,
                                             ByVal subject As String,
                                             ByVal body As String)
            Try
                Dim outlook As Object = Nothing
    
                If AutomationFactory.IsAvailable Then
                    Try
                        'Get the reference to the open Outlook App
                        outlook = AutomationFactory.GetObject("Outlook.Application")
    
                    Catch ex As Exception 'If Outlook isn't open, then an error will be thrown.
                        ' Try to open the application
                        outlook = AutomationFactory.CreateObject("Outlook.Application")
                    End Try
    
                    If outlook IsNot Nothing Then
                        'Create the email
    
                        ' Outlook object model (OM) reference: 
                        ' http://msdn.microsoft.com/en-us/library/ff870566.aspx
    
                        Dim mail = outlook.CreateItem(olMailItem)
                        With mail
                            If body.ToLower.Contains("<html>") Then
                                .BodyFormat = olFormatHTML
                                .HTMLBody = body
                            Else
                                .BodyFormat = olFormatPlain
                                .Body = body
                            End If
    
                            .Recipients.Add(toAddress)
                            .Subject = subject
    
                            .Save()
                            .Display()
                            '.Send()
                        End With
                    End If
                End If
    
            Catch ex As Exception
                Throw New InvalidOperationException("Failed to create email.", ex)
            End Try
        End Sub
    End Class

    The code to call this is almost identical to the previous example. We use XML literals to create the HTML the same way. The only difference is we want to call this from a command button on our OrderDetail screen. (Here’s how you add a command button to a screen.) In the Execute method for the command button is where we add the code to generate the HTML email. I also want to have the button disabled if AutomationFactory.IsAvailable is False and you check that in the CanExecute method.

    Here’s the code we need in the screen:

    Private Sub CreateEmail_CanExecute(ByRef result As Boolean)
        result = System.Runtime.InteropServices.Automation.AutomationFactory.IsAvailable
    End Sub
    
    Private Sub CreateEmail_Execute()
        'Create the html email from the Order data on this screen
        Dim toAddress = Me.Order.Customer.Email
        If toAddress <> "" Then
    
            Dim entity = Me.Order
            Dim subject = "Thank you for your order!"
    
            Dim body = <html>
                           <body style="font-family: Arial, Helvetica, sans-serif;">
                               <p><%= entity.Customer.ContactName %>, thank you for your order!<br></br>
                              Order date: <%= FormatDateTime(entity.OrderDate, DateFormat.LongDate) %></p>
                               <table border="1" cellpadding="3"
                                   style="font-family: Arial, Helvetica, sans-serif;">
                                   <tr>
                                       <td><b>Product</b></td>
                                       <td><b>Quantity</b></td>
                                       <td><b>Price</b></td>
                                       <td><b>Discount</b></td>
                                       <td><b>Line Total</b></td>
                                   </tr>
                                   <%= From d In entity.Order_Details
                                       Select <tr>
                                          <td><%= d.Product.ProductName %></td>
                                          <td align="right"><%= d.Quantity %></td>
                                          <td align="right"><%= FormatCurrency(d.UnitPrice, 2) %></td>
                                          <td align="right"><%= FormatPercent(d.Discount, 0) %></td>
                                          <td align="right"><%= FormatCurrency(d.LineTotal, 2) %></td>
                                      </tr>
                                   %>
                                   <tr>
                                       <td></td>
                                       <td></td>
                                       <td></td>
                                       <td align="right"><b>Total:</b></td>
                                       <td align="right"><b><%= FormatCurrency(entity.OrderTotal, 2) %></b></td>
                                   </tr>
                               </table>
                           </body>
                        </html>
    
            OutlookMailHelper.CreateOutlookEmail(toAddress, subject, body.ToString)
        Else
            Me.ShowMessageBox("This customer does not have an email address",
                              "Missing Email Address",
                              MessageBoxOption.Ok)
        End If
    End Sub
    

    Now when the user clicks the Create Email button on the ribbon, the HTML email is created and the Outlook mail message window opens allowing the user to make changes before they hit send.

    image

    I hope I’ve provided a couple options for sending HTML emails in your LightSwitch applications. Select the first option to use SMTP when you want automated emails sent from the server side. Select the second option to use the Outlook client when you want to interact with users that have Outlook installed and LightSwitch is running out-of-browser.

    Enjoy!

  • Beth Massi - Sharing the goodness

    Tips and Tricks on Controlling Screen Layouts in Visual Studio LightSwitch

    • 2 Comments

    NOTE: This information applies to LightSwitch Beta 1 ONLY.
    Please see updated information: Tips and Tricks for Using the Screen Designer

    Visual Studio LightSwitch has a bunch of screen templates that you can use to quickly generate screens. They give you good starting points that you can customize further. When you add a new screen to your project you see a set of screen templates that you can choose from. These templates lay out all the related data you choose to put on a screen automatically for you. And don’t under estimate them; they do a great job of laying out controls in a smart way. For instance, a tab control will be used when you select more than one related set of data to display on a screen. However, you’re not limited to taking the layout as is. In fact, the screen designer is pretty flexible and allows you to create stacks of controls in a variety of configurations. You just need to visualize your screen as a series of containers that you can lay out in rows and columns. You then place controls or stacks of controls into these areas to align the screen exactly how you want.

    Let’s start with a simple example. I have already designed my data entities for a simple order tracking system similar to the Northwind database. I also have added a Search Data  Screen to search my Products already. Now I will add a new Details Screen for my Products and make it the default screen via the “Add New Screen” dialog:

    image

    The screen designer picks a simple layout for me based on the single entity I chose, in this case Product. Hit F5 to run the application, select a Product on the search screen to open the Product Details Screen. Notice that it’s pretty simple because my entity is simple. Click the “Customize” button in the top right of the screen so we can start tweaking it.

    image

    The left side of the screen shows the containership of controls and data bindings (called the content tree) and the right side shows the live preview with data. Notice that we have a simple layout of two rows but only one row is populated (with a vertical stack of controls in this case). The bottom row is empty. You can envision the screen like this:

    image

    Each container will display a group of data that you select. For instance in the above screen, the top row is set to a vertical stack control and the group of data to display is coming from Product. So when laying out screens you need to think in terms of containers of controls bound to groups of data. To change the data to which a container is bound, select the data item next to the container:

    image

    You can select the “New Group” item in order to create more containers (or controls) within the current container. For instance to totally control the layout, select the Product in the top row and hit the delete key. This will delete the vertical stack and therefore all the controls on the screen. The content tree will still have two rows, but the rows are now both empty.

    image

    If you want a layout of four containers (two rows and two columns) then select “New Group” for the data item and then change the vertical stack control to “Two Columns” for both of the rows as shown here:

    image

    You can keep going on and on by selecting new groups and choosing between rows or columns. Here’s a layout with 8 containers, 4 rows and 2 columns:

    image

    And here is a layout with 7 content areas; one row across the top of the screen and three rows with two columns below that:

    image

    When you select Choose Content and select a data item like Product it will populate all the controls within the container (row or column in a vertical stack) however you have complete control on what to display within each group. You can delete fields you don’t want to display and/or change their controls. You can also change the size of controls and how they display by changing the settings in the properties window. If you are in the Screen Designer (and not the customization mode like we are here) you can also drag-drop data items from the left-hand side of the screen to the content tree. Note, however, that not all areas of the tree will allow you to drop a data item if there is a binding already set to a different set of data. For instance you can’t drop a Customer ID into the same group as a Product if they originate from different entities. To get around this, all you need to do is create a new group and content area as shown above.

    Let’s take a more complex example that deals with more than just product. I want to design a complex screen that displays Products and their Category, as well as all the OrderDetails for which that product is selected. This time I will create a new screen and select List and Details, select the Products screen data, and include the related OrderDetails. However I’m going to totally change the layout so that a Product grid is at the top left and below that is the selected Product detail. Below that will be the Category text fields and image in two columns below. On the right side I want the OrderDetails grid to take up the whole right side of the screen. All this can be done in customization mode while you’re debugging the application.

    To do this, I first deleted all the content items in the tree and then re-created the content tree as shown in the image below. I also set the image to be larger and the description textbox to be 5 rows using the property window below the live preview. I added the green lines to indicate the containers and show how it maps to the content tree (click to enlarge):

    image

    I hope this demystifies the screen designer a little bit. Remember that screen templates are excellent starting points – you can take them as-is or customize them further. It takes a little fooling around with customizing screens to get them to do exactly what you want but there are a ton of possibilities once you get the hang of it. Stay tuned for more information on how to create your own screen templates that show up in the “Add New Screen” dialog.

    Enjoy!

  • Beth Massi - Sharing the goodness

    Visual Basic Samples, Resources and More!

    • 9 Comments

    Yesterday the VB Team posted links to a TON of Visual Basic code samples and resources (see below) that have been made available by teams across Microsoft. It’s really nice to see the internal culture shift on a lot of teams to embrace the C# /VB Co-Evolution strategy. The VB Team still has work to do but the mentality on a lot of teams has come a long way since I joined Microsoft as a VB community champion almost 4 years ago.

    The VB Team has also made strides in supporting other platforms like the phone and XNA. In SP1 they’ve made it a lot easier for product teams building other platforms to incorporate Visual Basic by using the new compilation mode in Visual Studio 2010 SP1. 

    Here’s the list of samples and resources pulled from the VB team blog that they wanted to call out. Check them out and let us know what else is missing that you’d like to see:

    Category

    Links to Resources

    clip_image001

    o    Visual Basic for Windows Phone Developer Tools - RTW

    o    Visual Basic Code Samples for Windows Phone

    o    Free ebook: “Programming Windows Phone 7, by Charles Petzold” - VB Code Samples (direct)

    o    Windows Phone 7 Development For Absolute Beginners on Channel 9

    o Visual Basic Windows Phone 7 Tutorials (Part 1, Part 2, Part 3) 

    clip_image002

    o    Silverlight 4 Training Kit

    o    Silverlight 4 MSDN Help Documentation

    o    Silverlight 4 Application Themes Including Visual Basic Templates

    o    See Also: Silverlight QuickStarts, Silverlight Video Code Downloads, Silverlight 4 Tutorials, Silverlight Toolkit Samples, Blog Tutorials (SL HyperVideo | Silverlight/MEF/HVP | Project Turing RIA Services | Project Turing Multiple Tables | Silverlight TDD | MVVM)*

    clip_image003

    o    Office 2010 Training Course Hands-On-Labs (Channel9, Download)

    o    Open XML SDK 2.0 Samples for Microsoft Office

    o    Open XML SDK 2.0 Documentation

    clip_image004

    o    SharePoint 2010 Help Topics

    o    SharePoint 2010 Developer Training Kit*

    clip_image005

    o    Visual Studio Extensibility Samples

    o    Visual Studio Start Page Customization Template

    o    Static Code Analysis MSDN Help Documentation

    o    101 Async CTP Samples & Walkthrough

    o    See Also: Visual Studio 2010 and .NET 4 Training Kit and VB Samples -> Language directory*

    clip_image006

    o    Managed Extensibility Framework (MEF) Samples

    o    MEF Programming Guide Documentation

    o    See Also: Hello MEF in Silverlight 4 and VB! Blog*

    clip_image007

    o    Windows 7 Training Kit For Developers & Windows 7 Online Training*

    o    Windows 7 API Code Pack Samples*

    clip_image008

    o    Microsoft Expression Encoder 4 SDK Samples

    o    See Also: Expression Encoder 3 Samples

    clip_image009

    o    “Using EF in Silverlight with VB” Article

    o    Entity Framework Samples (VBTeam Blog, Code Gallery)*

    o    VS 2010 Data How-Do-I Videos & Visual Basic Videos*

    clip_image010

    o    WCF Azure Samples

    o    See Also: Windows Azure Platform Training Kit & Windows Azure SDK Samples

    (more recent VB samples underway, as well as documentation)

    clip_image011

    o    WCF/WF Samples, WCF/WF Help topics *

    o    WPF Help topics, WPF Video Code Downloads*

    o    ASP.NET MVC Tutorials *

    o    Samples for Parallel Programming with the .NET 4, .NET 4 Paper: Parallel Programming Patterns*

    clip_image012

    o    Patterns & Practices: “Parallel Programming with Microsoft .NET” - Book Companion Samples  

    o    Prism 4 Reference Implementations, QuickStarts, and Hands-on Labs for WPF & Silverlight

    o    Hands-On Labs for Microsoft Enterprise Library 5.0

    clip_image013

    o    Book: "Programming Microsoft ASP.NET MVC" - VB Code Samples

    o    Book: "ASP.Net 4 Step by Step" - VB Code Samples 

    o    Visual Basic 2010 Books (Various)

    o    MSDN Magazine Code Downloads

    clip_image014

    o    “Pex for Fun” Code Samples

    clip_image015

    o    VB Team Blog

    o    WPF & Silverlight Blog by Karl Shifflett

    o    Beth Massi Blog

    o    VB MVP Articles & Blogs

    Enjoy!

  • Beth Massi - Sharing the goodness

    National GiveCamp coming to San Francisco, February 4-6, 2011

    • 0 Comments

    image_thumb

    GiveCamp is a weekend-long event where software developers, designers, and database administrators donate their time to create custom software for non-profit organizations. Our local developer evangelists Bruno Terkaly and Doris Chen are organizing the event. This is a great way to give back by using your developer skills to build custom software for charities.

    They are currently looking for developers, coordinators, analysts and leaders. Check out Bruno’s blog for more details.

    Contact bterkaly@microsoft.com if you are interested.

  • Beth Massi - Sharing the goodness

    Build Business Applications Quickly with Visual Studio LightSwitch

    • 6 Comments

    Check it out, the Jan/Feb 2011 issue of CoDe Magazine is out and I’ve got an article in there on Visual Studio LightSwitch. In this article I give a good overview of what LightSwitch is and what it can do. I also take you on a tour of the development and deployment experience and well as the capabilities of this newest member of the Visual Studio family.


    Read it: Build Business Applications Quickly with Visual Studio LightSwitch

    BTW, if you tried to access page 2 of this article before it was locked out. The editors just unlocked the entire article so you don’t need a subscription to read the whole thing. Thanks CoDe!

    Enjoy!

  • Beth Massi - Sharing the goodness

    Happy New Year! (Now get to work)

    • 3 Comments

    Happy New Year everyone! I’ve enjoyed a nice long vacation with good friends and family but now it’s time to come out of my holiday coma and get back to work. :-)

    While I was away a couple things have happened in the LightSwitch community. First, I’d like to introduce our newest LightSwitch Technical Evangelist, Robert Green. I am very excited to have him back at Microsoft and especially working on LightSwitch. Keep an eye on his blog for more awesome content. Robert has a good “How To” style of writing that makes learning easy.

    Also another LightSwitch community blogger has come back out from hiding with a new website, a good line-up of content, and a passion for making things easy to learn. Check out Paul Patterson’s new blog.

    I’ll also be back at it with the team with more content so stay tuned here and the LightSwitch Team blog. And don’t forget to pop into the LightSwitch Forums to say hello and visit the Developer Center for more community interaction and training content.

    It’s good to be back and ready to tackle 2011!

    Enjoy!

     image image image

Page 1 of 1 (6 items)