Visual Studio 2008 default keyboard shortcuts and customisation

There is an old “saying” in the world of software development that you should learn to “use a single text editor well” in order to obtain maximum efficiency [see The Pragmatic Programmer]. In the case of Microsoft development the only real choice is Visual Studio and that’s what I’ve focused my energy on the last couple of months.

I have forced myself to find, use and hopefully remember keyboard shortcuts for Visual Studio 2008. On my project I’m in the process of getting familiar with some legacy code so my focus has been on things that help me understand and view code. There are a lot of shortcuts in Visual Studio 2008, but here are a few I find myself using a bit:

Comments:

  • Comment code: ‘Ctrl’+’K’, ‘Ctrl’+’C’
  • Uncomment code: ‘Ctrl’+’K’, ‘Ctrl’+’U’

Bookmarks:

  • Set/unset bookmark on line: ‘Ctrl’+’K’, ‘Ctrl’+’K’
  • Go to next bookmark: ‘Ctrl’+’K’, ‘Ctrl’+’N’
  • Go to previous bookmark: ‘Ctrl’+’K’, ‘Ctrl’+’P’

Navigation:

  • Navigate backward: ‘Ctrl’+’-‘
  • Navigate forward: ‘Ctrl’+’Shift’+’-‘
  • Go to line: ‘Ctrl’+’G’
  • Go to definition: ‘F12’
  • Go to declaration: ‘Ctrl’+’F12’
  • Find all references: ‘Shift’+’F12’
  • Find symbol: ‘Alt’+’F12’

Collapsing/Expanding code regions:

  • Expand all regions: ‘Ctrl’+’M’, ‘Ctrl’+’L’
  • Collapse all regions: ‘Ctrl’+’M’, ‘Ctrl’+’O’
  • Collapse / Expand current region: ‘Ctrl’+’M’, ‘Ctrl’+’M’

Breakpoints:

  • Set/unset breakpoint: ‘F9’
  • Enable/disable breakpoint: ‘Ctrl’+’F9’
  • Show breakpoints window: ‘Ctrl’+’Alt’+’B’

stepping through code:

  • Step over: ‘F10’
  • Step into: ‘F11’
  • Step out: ‘Shift’+’F11’
  • Run to cursor: ‘Ctrl’+’F10’

I’m not sure if these are global shortcuts for Visual Studio 2008 IDE irrespective of development language, but they work for me when coding ASP.NET using C#.

You can also download a nice pdf for the Microsoft Visual C# default keybindings here. However, I didn’t get all of them to work “out of the box”.

Customising the editors keybindings

If the default keybindings aren’t covering your needs then you can customise the editor to your own. The “Tools | customize” menu will open the customize dialog box which in turn let’s you customise the default keybindings.

I found myself building my project often, but found no default keybinding for it apart from the one which applied to the full solution which was too much in my case. According to the pdf mentioned above the ‘Shift’+’F6’ keybinding should have done this, but in my case it wasn’t assigned. The screenshot below illustrates what I did to set it to adhere to my needs.

The cusomize keyboard options

Advertisements

Using WinMerge in Microsoft Visual Studio 2008

As a newcomer to Visual Studio 2008 I am not impressed by the file comparison tools used by default in the IDE (a part of Team Foundation Server, I think). I have always reverted to WinMerge as my tool of choice for comparing text files. Today I came across a great little utility named Visual Studio Comparison Tools that lets me use WinMerge directly from Visual Studio. Well… not directly – but it starts WinMerge as an external tool and supplies the selected IDE files as arguments. The screenshot shows the tool in action from the IDE’s solution explorer.

A screenshot illustrating how text files can be compared using WinMerge from within the Visual Studio 2008 IDE

You need to have WinMerge installed in the default location (C:\Program Files\WinMerge) for it to work.

Missing build configuration dropdown in Visual Studio 2008

My project is using Microsoft Visual Studio 2008 for development. For some strange reason the build configuration dropdown does not show up by default in the IDE.

A screenshot of the build configuration dropdown present in the IDE

I found the following procedure online and very helpful. It describes how to get this useful dropdown visible:

  1. In Visual Studio 2008, click “Tools” -> “Options”
  2. Under “Projects and Solutions” -> “General”, check “Show advanced build options”, and click “OK”
  3. Right click anywhere in the blank space of the toolbar and click “Customize…”
  4. In “Commands” tab, select “Build” in “Categories”.
  5. Scroll the right listbox to the bottom and drag “Solution Configurations” to the toolbar

I really can’t take credit for creating this procedure since I found it somewhere else on the web, but I had a lot of trouble re-finding the original posting in my browser history when the dropdown suddenly disappeared from my IDE today. The original posting is located found here.

Javascript mouseover effects on table rows using jQuery

Introduction
Lately I’ve been getting into jQuery. On first sight the syntax can look a bit strange, but I get it now – for the most part, that is. On a related note, for a while now I’ve been “wondering” about how you do the mouseover effects you sometimes see on table rows. I’m talking about the effects where you move your mouse over a cell in table row and then the full row’s background colour changes to give the effect of highlighting the full row for selection. I really haven’t given it much thought, but I recently came across some code in a company application that got me thinking about it again so I decided time was right for to take a closer look.

Code
Originally, before the use of jQuery, your markup would look something like this:



   <table>
      <tbody>
         <tr>
            <td>some table cell content here</td>
         </tr>
         <tr style="cursor:pointer;">
            <td>some table cell content here</td>
         </tr>
         <tr>
            ...
            more rows and cells containing more of the same here
            ...
         </tr>
      </tbody>
   </table>


You’ll notice the obtrusive JavaScript event handling code on lines 5 to 8 and 11 to 14. This code repeats itself on every row of the table which is just annoying. The only difference between the code attached to the individual table rows is the obvious onclick event handler (here a simple alert message) which should simulate some functionality specific to a click on that unique row. As a whole this use of Javascript makes the markup somewhat more difficult to read and generally untidy. Of course it is usually the backend server code creating this kind of code in a for-loop or similar – nobody writes this stuff by hand, but that’s not the point.
So how can you use jQuery to replace this mess? The following shows a first attempt of a replacement using jQuery.



   
   
      $(function() {
         $('table tbody tr').mouseover(function() {
            $(this).addClass('selectedRow');
         }).mouseout(function() {
            $(this).removeClass('selectedRow');
         }).click(function() {
            alert($('td:first', this).text());
         });
      });
   
   
      .selectedRow {
         background-color: blue;
         cursor: pointer;
      }
   


   <table border="1">
      <thead>
         <tr>
            <th>First column</th>
            <th>Second column</th>
            <th>Third column</th>
         </tr>
      </thead>
      <tbody>
         <tr>
            <td>This</td>
            <td>That</td>
            <td>The other</td>
         </tr>
         <tr>
            <td>Second</td>
            <td>line</td>
            <td>here</td>
         </tr>
      </tbody>
   </table>


So – I guess a brief explanation is in order. You’ll of course need the jQuery JavaScript library available in the correct location as referred to in the script tag (line 3). Apart from that, all the custom JavaScript jQuery code is happening in the script tag at the top of the page (lines 4 to 14). We are first creating a jQuery selector to select all tr tags inside a tbody tag which itself must reside within a table tag (line 6). When these tag elements are found we bind the ‘mouseover’, ‘mouseout’ and ‘click’ events to the rows (lines 6,8 and 10 respectively). The mouseover and mouseout event just add or remove a CSS class named ‘selectedRow’ dynamically to or from the row which adds the effect. The CSS class itself is defined at the top of the page within the style tags just after the script. The actual mouse click functionality just returns the value of the first cell in the selected row, just as an example. This could be a unique row id or similar.
The jQuery selector makes sure the mouse click event is set to only work on tr tags that are present from within a tbody tag to avoid adding the effect to the thead header row.

So that’s all there is to it really – not too bad. It was a lot simpler than I first imagined and the jQuery code makes things nice and tidy once you get used to the chained decorator pattern syntax.

My meeting with a celebrity

Last week, a colleage and myself were fortunate to participate at a one day GSE Nordic WebSphere User Group conference held at Bouvet’s offices in Oslo. One of the conference speakers was Stefan Hepper from IBM Germany. Stefan works as the WebSphere Portal Programming Model Architect and leads the programming model part of IBM’s flagship portal product, IBM WebSphere Portal Server. However, more importantly (at least to me), he had the honorable task of working as specification lead for the JSR-168 Portlet version 1.0 specification, and is currently working as specification lead on the new JSR-286 Portlet version 2.0 specification. Naturally, Stefan spoke primarily of the new features in the upcoming WebSphere Portal Server version 6.1 product in the context of JSR-286, but the two aforementioned portlet specifications influence every serious Java based portal server like IBM’s WebSphere Portal Server, SAP Enterprise Portal, Oracle Portal Server, Liferay and JBoss Portal Server, just to name but a few.

Stefan Hepper and the site authorHowever, although Stefan answered a lot of question during his talks, oddly enough, for me the highlight was sharing a taxi and a 20 minute train ride from the conference back to Gardermoen airport (main Oslo airport) where we loosely discussed portlets and portals in depth, and Stefan willingly shared his knowledge with us indiscriminately. It goes without saying that this guy really knows his “stuff”, but it was also quite fascinating to hear how a Java Community Process expert group works in practice. I admit that I knew little of how the JCP works behind the scenes before our conversation, but I got the impression that Stefan is responsible for a whole lot of the final specification work and seems to carry a “heavy burden” by leading the group. However, you won’t find a nicer guy willing to help you with anything related to Java portlet/portal development should you need to call upon him for help.

As you may know, the JSR-168 specification is implemented and supported on almost every Java based portal server. The JSR-286 specification is expected to be finished in april 2008 and introduces quite a lot of new features. If memory serves me correctly, Stefan mentioned that the specifcation API has grown by over 100% since version 1.0. IBM WebSphere Portal Server 6.1 is scheduled for release sometime in the second quarter of 2008 and will support portlets complying with either of the portlet standards. It is also possible to communicate between portlets developed on either standard something that was not possible before between the proprietary IBM Portal API and the JSR-168 implementation.

I also mentioned to Stefan that I thought it was odd that there were so few JSR-168 or porlet related books available on the market. It just so happens that he has co-written and almost finalized a Manning book that was never published. It happens to be available for free download from the Manning web site, but requires registration (free). The book is titled “Portlets and Apache Portals” and it looks good. It also seems to cover WSRP (Web Services for Remote Portlets, version 1.0) and also portlet development using JSR-127 (Java Server Faces).

Sending SMTP mail with Java

Introduction

So your Java application needs to send a notification mail? Not an uncommon scenario, but how to do it? Luckily this turns out to be pretty easy in it’s simplest form, but SMTP configuration can be the killer. You are of course dependent on being able to access a SMTP mail server and also possessing a little knowledge of the SMTP protocol.

What you need

Some years ago, Sun released the Java Mail API. It doesn’t ship along with the standard Java distribution (yet!) so you will need to download it manually. It can be found here and at the time of writing is at version 1.4.1. The Mail API depends on code from the JavaBeans Activation Framework (JAF) so you’ll need to download that package also. It can be found at this link and at the time of writing is at version 1.1.1. Make sure you add the activation.jar file from the JAF distribution to your Java classpath and you will also need both the mail.jar and smtp.jar files from the Mail API distribution to enable you to send SMTP mail.

The code

The code itself is straightforward enough, but as I said earlier, it’s the SMTP mail server configuration that can turn out to be the problem. Specially if the server is configured to not let you use it indiscriminately to avoid SPAM etc. This will depend on the company policy configuration settings of the SMTP server you are trying to connect to.

OK, here’s a simple example of how it can be done…

import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Main {
    public static void main(String[] args) {
        Properties props = new Properties();
        props.put("mail.smtp.host", "your SMTP mail server here");
        props.put("mail.debug", "true");

        Session session = Session.getInstance(props);

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress("from@here.com"));
            InternetAddress[] address = {new InternetAddress("to@somewhere.com")};
            msg.setRecipients(Message.RecipientType.TO, address);
            msg.setSubject("Mail subject title");
            msg.setSentDate(new Date());
            msg.setText("Message body string");

            Transport.send(msg);
        }
        catch (MessagingException e) {}
    }
}

So, to summarize, start you of by creating a Java Properties object and populating it with relevant configuration information. You need to specify the SMTP host name or IP address for the key “mail.smtp.host”. The “mail.debug” property is useful for development and will give you a hint what’s going wrong should you get into trouble. Proceed on by creating a javax.mail.Session object and passing it your properties object. To create the actual mail message use a javax.mail.internet.MimeMessage object passing along the session instance you just created. Populate the javax.mail.Message object with a valid sender address and receiver address array (mail has only one sender, but can have multiple receivers). Add a mail subject, the timestamp and of course the mail message body. Then all that remains is to actually post the message to the SMTP server. That where the hard part usually begins.
So, not that difficult all in all, but remember to encapsulate the code in a try/catch block and catch the javax.mail.MessagingException exception type for it to compile. Handle errors appropriately, there is a lot that could possibly go wrong here.

SMTP server authentication

As I mentioned earlier, configuration can be the killer. These days most SMTP servers don’t let any old message pass through the system without some kind of policy checking switched on. It is likely that you will need to authenticate your application to the SMTP server when creating the session object. It is also possible that the server will attempt to validate the sender e-mail address your application is using so you need to choose it wisely since it will need to be valid in the mail domain.

To create an authenticated session object you will need to make a few minor adjustments to the code. Create a javax.mail.Authenticator subclass and override the protected method getPasswordAuthentication. By default this method returns null, so you will have to make it return an initialized javax.mail.PasswordAuthentication object containing your username and password.

You also need to tell the session object to use your new authentication class so add the property “mail.smtp.auth” to your Properties object and set its to “true”. Also change the code that creates the session object by using an overloaded version passing both your Properties object and an instance of your new Authenticator subclass. The new code should look something like this:

import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Main {
    public static void main(String[] args) {
        Properties props = new Properties();
        props.put("mail.smtp.host", "your SMTP mail server here");
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true");

        Session session = Session.getInstance(props, new MyAuth());

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress("from@here.com"));
            InternetAddress[] address = {new InternetAddress("to@somewhere.com")};
            msg.setRecipients(Message.RecipientType.TO, address);
            msg.setSubject("");
            msg.setSentDate(new Date());

            msg.setText("Message body string");

            Transport.send(msg);
        }
        catch (MessagingException e) {}
    }
}

class MyAuth extends Authenticator {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("your username","your password");
    }
}

And that ought to do it! This code worked fine for me when testing with two separately configured Microsoft Exchange servers (ESMTP , version 6.0.3790.1830 and 6.0.3790.3959) in different mail domains as my SMTP server host, but only if clear text authentication (BASIC) was enabled on the Exchange server.

In both cases the Exchange server checked my sender address and also insisted that my application authenticate itself before allowing it to post.