Ubuntu – Remote Desktop from Windows

It is no joke that Windows and Linux are radically different. Down the to Kernel level, they offer two separate ways of computing. Some would even say the philosophies behind them are at odds as well. All of this aside, in a real situation, or just for fun, you may have a situation where you need to use remote desktop to control your Linux GUI from a Windows machine. Luckily this is actually not that difficult to do.

Today we will be working with one of the most popular distributions of Linux, Ubuntu version 11.04. The version of Windows actually doesn’t matter that much in today’s tutorial, but if you are picky, I have been using Windows 7. The more important part in this tutorial is that you use Ubuntu, as it has a GUI for us to remote desktop into.

Ubuntu

Normally with a Linux distribution, you just SSH into it and go crazy. However, sometimes it is beneficial, especially for those that aren’t used to the command line, to see things visually. As such, all of our steps today will be through the GUI of Ubuntu, and of course Windows.

The first thing we need to do is enable remote desktop connections inside of Ubuntu. Here a are a few screenshots to help you.

So there are few things to keep in mind here. First off, security is always on the top of the list. Thankfully, the Ubuntu GUI makes it pretty obvious what options we have. As you can see, I personally like to add password protection to remote desktop connections. That being said, there are few options that I tweaked for easier access.

There are a few options (“You must confirm each access to this machine” and “Configure network automatically to accept connections”) that are security based that stop unwanted connections, and they both have to do with authorizing incoming RD connections. While tweaking these sounds like a huge security hole, and it sometimes is, if you are using RD on your internal network, the risk is fairly minimal. Disabling confirmation and enabling automatic accepting allows you to RD into Ubuntu without physically allowing each connection. After trying things with these options on their default, I have to say it makes life so much easier to just change them and allow incoming connections.

Windows

So now you have Ubuntu set up and ready for RD connections…the only catch is that the remote desktop protocol is completely different from a Windows machine. Out of the box Ubuntu uses something called VNC. Luckily there are plenty of VNC clients out there for windows. All you have to do is download one and fire it up. Personally, I use TightVNC and it is extremely simple to use. But screenshots help a lot more than my ramblings:

And there you have it, controlling your Ubuntu machine from Windows using remote desktop, and this is just one of the many ways you can do it. There are plenty of other RD protocols out there you can use. This, however, was the simplest ways I found to accomplish it.

This is going to wrap up this tutorial, and I hope it was informative. Just remember, when you need programming help, all you have to do is Switch On The Code.

C# Snippet – Shuffling a Dictionary

Randomizing something can be a daunting task, especially with all the algorithms out there. However, sometimes you just need to shuffle things up, in a simple, yet effective manner. Today we are going to take a quick look at an easy and simple way to randomize a dictionary, which is most likely something that you may be using in a complex application.

The tricky thing about ordering dictionaries is that…well they are not ordered to begin with. Typically they are a chaotic collection of key/value pairs. There is no first element or last element, just elements. This is why it is a little tricky to randomize them.

Before we get started, we need to build a quick dictionary. For this tutorial, we will be doing an extremely simple string/int dictionary, but rest assured the steps we take can be used for any kind of dictionary you can come up with, no matter what object types you use.

Dictionary<String, int> origin = new Dictionary<string, int>();

for (int i = 0; i < 100; i++)
{
  origin.Add("Item " + i.ToString(), i);
}

// "Item 0" -> 0
// "Item 1" -> 1
// "Item 2" -> 2
// …

So now we have a quick and dirty 100-element dictionary that we can use.

Most collections in .Net implement the IEnumerable interface. Among other useful things, this interface allows us to use the OrderBy extension method provided by the System.Linq namespace. As you may have guessed, this takes a collection and orders it. To make things even easier, this function allows some pretty fancy Lamda functions, so we can actually order our Dictionary with just one line of code.

However, we want to shuffle our Dictionary. To do this, we have to order it by a random value. To do this we basically pass in a function that chooses a random number for the index. When we combine the ordering and random index together, our code looks something like so:

using System.Linq;

Random rand = new Random();
origin = origin.OrderBy(x => rand.Next())
  .ToDictionary(item => item.Key, item => item.Value);

It’s actually not that difficult. You just pass in a lamda function that chooses a random number, then convert the reordered collection back into a dictionary. With just two lines we can shuffle our Dictionary. It may seem a little silly that we need to “reconvert” our object back to a Dictionary, but there is a reason why we do this.

The OrderBy function returns an IEnumerable of the original type – in this case KeyValuePair. So once we order our collection, it needs to be converted from a collection of KeyValuePairs to an actual Dictionary object.

So now, in order to make life even easier, I have created a simple extension method that will allow us to just call Shuffle() on our Dictionary. It is a generic function as well, so you will be able to use it on any type of Dictionary you might have:

public static class DictionaryExtensions
{
   public static Dictionary<TKey, TValue> Shuffle<TKey, TValue>(
      this Dictionary<TKey, TValue> source)
   {
      Random r = new Random();
      return source.OrderBy(x => r.Next())
         .ToDictionary(item => item.Key, item => item.Value);
   }
}

Dictionary<string, int> source = new Dictionary<string, int>();
for (int i = 0; i < 5; i++)
{
   source.Add("Item " + i, i);
}

// "Item 0" -> 0
// "Item 1" -> 1
// "Item 2" -> 2
// "Item 3" -> 3
// "Item 4" -> 4

Dictionary<string, int> shuffled = source.Shuffle();

// "Item 4" -> 4
// "Item 2" -> 2
// "Item 0" -> 0
// "Item 1" -> 1
// "Item 3" -> 3

And there we have it, a simple extension method that will allow you to shuffle any Dictionary you may have. It’s not a terrible complicated method, but hey, it is pretty useful.

So this is going to wrap it up for this tutorial, hopefully it helps you get your randomization on. Just remember, when you need programming help, all you have to do is Switch On The Code.

Ubuntu – Setting Up MySQL for Remote Access

Setting up a test server can be quite a daunting task, as we can see from our Drupal Dev Environment Tutorial. There are plenty of things to take into account, and while setting up such an environment can be quick and easy, sometimes there are certain things you would like to have. Today we are going to cover one such feature – setting up MySQL for remote access.

Things to Consider

Setting up MySQL can be extremely easy, and there are plenty of packages out there that make it that way. However, if you have a little bit more advanced setup, such as a local server on your network that you use, you may want something a bit more custom. Today we are going to work with Ubuntu, which will be our server. Keeping that in mind, we will be setting up MySQL so that we can access it from other computers in our local network.

The technique we will be using involves opening up MySQL server for access from other computers. Just remember that like any such access, you should take the proper security steps, such as giving accounts strong passwords, setting up database-specific permissions, and creating accounts with database-specific permissions.

Lastly, I am assuming here that you have already set up your Ubuntu server, and assigned a static IP to it. As this process can have a thousand different permutations based on your network setup, I will not be going over how to do this.

Installing MySQL

Installing things on a Linux system is quite easy. To install MySQL, the Ubuntu documentation actually recommends that you use the following command:

# sudo apt-get install mysql-server

However, I have seen another install command that offers a few extra tools which come in handy from time to time, so I prefer to use:

# sudo apt-get install mysql-server mysql-common mysql-client

Either one of these commands will work for what we need to do, and installing these will also start the server so we can dig right into the setup. One thing to remember, though, is the root password you provided during the setup procedure.

Setting Up the User

Before we go digging into our configuration file, which we will have to do, we need to setup a user for remote access. To start we need to log into our MySQL server through the terminal:

# mysql -u root -p

This will log into your MySQL server and allow you to run commands against it. First we need create a new user, which we are going to call remote, as it will be our remote admin. We do this with a simple command:

> CREATE USER ‘remote’@’%’ IDENTIFIED BY ‘somepass’;

There is one very important thing about this statement, the ‘%’ used to identify the host that this user can connect from. The % represents a wildcard, or any host, which means that this user can connect from anywhere. But this really means nothing without privileges.

Privileges in MySQL can be extremely complex, and this is something to consider when we grant permissions to our new user. For simplicity, we are going to grant our new user enough privileges to be dangerous, but not too dangerous.

> GRANT SELECT, INSERT, UPDATE ON *.* TO ‘remote’@’%’;

Now our user has access to all the data they could ever want, but they can’t create new databases or tables, and they cannot remove any objects from the server. To me, this is a good set of permissions to start with.

So there is our user, all setup and ready to go. There is still one last thing to do however, and that involves our configuration file.

The Bind Address

MySQL is a very complex creature. Thankfully, most of these complexities are abstracted so they work and work well, but sometimes we need to tweak a few things. In today’s case we need to modify the “bind address” of our MySQL server.

The bind address refers to the IP address that MySQL listens to for connections. For security reasons, the default is always 127.0.0.0, or localhost for those host name addicts out there. We need to change this address so it accepts connections from the IP it has been assigned by the router on our network. For simplicity sake, lets say this is 192.168.1.2.

To change this value, we need to open our MySQL configuration file, which in Ubuntu using MySQL 5.1, can be found in /etc/mysql/my.conf. Using the text editor of your choice, open that baby up.

What we are looking for here is something like the following;

bind-address = 127.0.0.0

All you have to do is change the address to your server’s IP address, in this case 192.168.1.2. Once you save the file, all you need to do is save the configuration and restart your MySQL server:

# sudo service mysql restart

And there you have it! Now you can access MySQL from any machine on your network, using your new remote user.

Well, that is going to wrap it up for this tutorial. I hope you learned a lot and just remember, when you need programming help, all you have to do is Switch On The Code.

WPF Tutorial – Increasing a Window’s Border

Extending the window’s frame is a design trend that is becoming popular in modern applications – especially browsers. Every major browser today (Chrome, Firefox, Internet Explorer, and Opera) uses this technique to increase the visual quality of their applications.

Today we’re going to see how to duplicate this look in WPF. The approach we’re going to take relies on the OS supporting Aero, which means only Vista and Windows 7 are supported. For Windows XP, you’re going to have to find another solution.

Perhaps in future versions of WPF Microsoft will simply add a property that can be used to set the window’s frame, but unfortunately that doesn’t exist today. We’re going to have to get our hands dirty inside the Windows API to get this done.

The example I’m going to build today gets its inspiration from modern browsers. I’m going to build an application that puts a search box up in the window’s frame.

Let’s start with a basic window definition in XAML. There’s very little we have to do in XAML to support extending the frame, so this is very basic markup for creating the application pictured above.

<!– Normal window.  The only required addition is setting
    the Background to transparent. –>
<Window x:Class="WindowBorder.MainWindow"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       Title="MainWindow"
       Height="300"
       Width="400"
       Background="Transparent">
  <Grid>
    <Grid.RowDefinitions>
      <!– 30 is how much margin was added to the window frame. –>
      <RowDefinition Height="30" />
      <RowDefinition Height="*" />
    </Grid.RowDefinitions>
   
    <!– Stack panel to layout the search box and the Go button. –>
    <StackPanel Orientation="Horizontal"
               HorizontalAlignment="Right"
               VerticalAlignment="Center">
     
      <!– Search box. –>
      <TextBox Width="150"
              VerticalAlignment="Center"
              Text="Search" />
     
      <!– Go button. –>
      <Button Content="Go"
             VerticalAlignment="Center"
             Margin="5,0,0,0" />
    </StackPanel>
   
    <!– This is where the rest of the content would go. –>
    <Grid Background="White"
         Grid.Row="1">

    </Grid>
  </Grid>
</Window>

The only important pieces in this code are the Window’s background, which must be set to transparent, and the magic row height of 30. I’ve extended the frame of this window by 30, so this row will hold items that are on top of the window’s frame – like the search box and Go button.

All right, now on to some meat. The first thing we need to do is provide access to the DwmExtendFrameIntoClientArea API function. This function requires a MARGINS structure, which we will also have to define.

using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
/// <summary>
/// Structure to hold the new window frame.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct MARGINS
{
  public int cxLeftWidth;
  public int cxRightWidth;
  public int cxTopHeight;
  public int cxBottomHeight;
}

/// <summary>
/// Extends the window’s frame into the client area.
/// </summary>
/// <param name="hWnd">Handle of the window to extend.</param>
/// <param name="pMarInset">Amount to extend.</param>
/// <returns>0 on success or error code.</returns>
[DllImport("dwmapi.dll")]
public static extern int DwmExtendFrameIntoClientArea(
  IntPtr hWnd, ref MARGINS pMarInset);

The structure and the function definition come straight from MSDN’s documentation. Nothing fancy here.

Everything required to adjust the frame happens in the window’s Loaded event. We have to wait until the window is loaded because the handle isn’t valid until that happens.

void OnLoaded(object sender, RoutedEventArgs e)
{
  // Get the handle for this window.
  IntPtr windowHandle = new WindowInteropHelper(this).Handle;

  // Get the Win32 window that hosts the WPF content.
  HwndSource window = HwndSource.FromHwnd(windowHandle);

  // Get the visual manager and set its background to transparent.
  window.CompositionTarget.BackgroundColor = Colors.Transparent;

  // Set the desired margins.
  MARGINS margins = new MARGINS();
  margins.cxTopHeight = 30;

  // WPF is DPI independent.  Simply passing 30 into the
  // Windows API does not take into account differences in the
  // user’s DPI settings.  We must adjust the margins to
  // reflect different settings.
  margins = AdjustForDPISettings(margins, windowHandle);

  // Call into the windows API to extend the frame.
  // Only supported on OS versions with Aero (Vista, 7).
  // Throws an exception on non-supported operating systems.
  int result = DwmExtendFrameIntoClientArea(windowHandle, ref margins);
}

The Windows API controls windows using their handles, so the first thing we need to do is get this window’s handle. .NET provides a nice helper class for that called WindowInteropHelper. Next we have to get an HwndSource from that handle. These objects represent a low-level Win32 window that will host WPF content. The only thing we need that object for is to set the background to transparent. If you don’t, you’ll see a nasty black rectangle where the new frame is supposed to be. Next we create a MARGINS structure that holds how much we’d like to adjust our window frame – in this case I’m adding 30 to the top. Because WPF is resolution independent, we have to adjust our margin based on the current DPI setting of the computer. The very last thing is to simply call the API function to adjust the frame.

Let’s take a look at the AdjustForDPISettings function.

/// <summary>
/// Adjusts the margins based on the users DPI settings.
/// </summary>
/// <param name="input">The unadjusted margin.</param>
/// <param name="hWnd">The window handle.</param>
/// <returns>Adjusted margins.</returns>
private MARGINS AdjustForDPISettings(MARGINS input, IntPtr hWnd)
{
  MARGINS adjusted = new MARGINS();

  // Gets the graphic object from the window handle
  // so we can get the current DPI settings.
  var graphics = System.Drawing.Graphics.FromHwnd(hWnd);

  // The default DPI is 96.  This creates a ratio that
  // will be applied to the incoming values to adjust them
  // based on whatever the current DPI setting is.
  float dpiRatioX = graphics.DpiX / 96;
  float dpiRatioY = graphics.DpiY / 96;

  // Adjust settings.
  adjusted.cxLeftWidth = (int)(input.cxLeftWidth * dpiRatioX);
  adjusted.cxRightWidth = (int)(input.cxRightWidth * dpiRatioX);
  adjusted.cxTopHeight = (int)(input.cxTopHeight * dpiRatioY);
  adjusted.cxBottomHeight = (int)(input.cxBottomHeight * dpiRatioY);

  return adjusted;
}

All this is doing is multiplying the original margin by an adjustment factor. The adjustment factor is simply the current setting divided by the default value (96).

That’s actually all there is to it. If you run the application now, you’d see a nice large top application frame with a search box and button overlaying it. The code isn’t all that long, so here it is again in one big chunk.

using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;

namespace WindowBorder
{
  /// <summary>
  /// Interaction logic for MainWindow.xaml
  /// </summary>
  public partial class MainWindow : Window
  {
    public MainWindow()
    {
      InitializeComponent();

      // Has to be done in the Loaded event because the window
      // handle is not valid until the window has loaded.
      this.Loaded += OnLoaded;
    }

    void OnLoaded(object sender, RoutedEventArgs e)
    {
      // Get the handle for this window.
      IntPtr windowHandle = new WindowInteropHelper(this).Handle;

      // Get the Win32 window that hosts the WPF content.
      HwndSource window = HwndSource.FromHwnd(windowHandle);

      // Get the visual manager and set its background to transparent.
      window.CompositionTarget.BackgroundColor = Colors.Transparent;

      // Set the desired margins.
      MARGINS margins = new MARGINS();
      margins.cxTopHeight = 30;

      // WPF is DPI independent.  Simply passing 30 into the
      // Windows API does not take into account differences in the
      // user’s DPI settings.  We must adjust the margins to
      // reflect different settings.
      margins = AdjustForDPISettings(margins, windowHandle);

      // Call into the windows API to extend the frame.
      // Only supported on OS versions with Aero (Vista, 7).
      // Throws an exception on non-supported operating systems.
      int result = DwmExtendFrameIntoClientArea(windowHandle, ref margins);
    }

    /// <summary>
    /// Adjusts the margins based on the users DPI settings.
    /// </summary>
    /// <param name="input">The unadjusted margin.</param>
    /// <param name="hWnd">The window handle.</param>
    /// <returns>Adjusted margins.</returns>
    private MARGINS AdjustForDPISettings(MARGINS input, IntPtr hWnd)
    {
      MARGINS adjusted = new MARGINS();

      // Gets the graphic object from the window handle
      // so we can get the current DPI settings.
      var graphics = System.Drawing.Graphics.FromHwnd(hWnd);

      // The default DPI is 96.  This creates a ratio that
      // will be applied to the incoming values to adjust them
      // based on whatever the current DPI setting is.
      float dpiRatioX = graphics.DpiX / 96;
      float dpiRatioY = graphics.DpiY / 96;

      // Adjust settings.
      adjusted.cxLeftWidth = (int)(input.cxLeftWidth * dpiRatioX);
      adjusted.cxRightWidth = (int)(input.cxRightWidth * dpiRatioX);
      adjusted.cxTopHeight = (int)(input.cxTopHeight * dpiRatioY);
      adjusted.cxBottomHeight = (int)(input.cxBottomHeight * dpiRatioY);

      return adjusted;
    }

    /// <summary>
    /// Structure to hold the new window frame.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    public struct MARGINS
    {
      public int cxLeftWidth;
      public int cxRightWidth;
      public int cxTopHeight;
      public int cxBottomHeight;
    }

    /// <summary>
    /// Extends the window’s frame into the client area.
    /// </summary>
    /// <param name="hWnd">Handle of the window to extend.</param>
    /// <param name="pMarInset">Amount to extend.</param>
    /// <returns>0 on success or error code.</returns>
    [DllImport("dwmapi.dll")]
    public static extern int DwmExtendFrameIntoClientArea(
      IntPtr hWnd, ref MARGINS pMarInset);
  }
}

Hopefully Microsoft will make doing this a little easier in future versions of WPF – especially since the design has become so popular. For now, however, we get to use the long way. If you’ve got any questions or comments, feel free to leave them below.

jQuery Really Simple Tabs

Once again, we find ourselves opening up our favorite IDE and looking jQuery straight in the eye. However, instead of a complex script that controls an alien mothership, we are going to build some really simple, yet useful, tabs. Even though jQuery UI offers some pretty cool tab objects, it is still a very large library and sometimes you just need some simple tabs. Today, we are going to tackle this.

Now, when I say simple tabs, I mean something like so:

This is tab one!
This is tab two!
This is tab three!

As you can see they are nothing complicated, and they work. Best of all, the code behind this is literally a few lines of jQuery and a little CSS. Let’s start with our HTML:

<div id="tab-anchors">
  <a id="tab-anchor-1" class="tab-anchor selected-tab" href="javascript:ShowTab(1);">
    Tab 1
  </a>
  <a id="tab-anchor-2" class="tab-anchor" href="javascript:ShowTab(2);">Tab 2</a>
  <a id="tab-anchor-3" class="tab-anchor" href="javascript:ShowTab(3);">Tab 3</a>
</div>
<div id="tab-1" class="tab">This is tab one!</div>
<div id="tab-2" class="tab">This is tab two!</div>
<div id="tab-3" class="tab">This is tab three!</div>

Alright, so here we have some anchors and some divs, pretty straightforward. However, without styles, nothing looks pretty, so here is what I came up with for styles:

.tab {
  width: 200px;
  height: 200px;
  display: none;
}

#tab-anchors {
  margin-bottom: 4px;
}

.tab-anchor {
  background-color: #ccc;
  padding: 5px;
  border: 1px solid #aaa;
  border-bottom: none;
}

.selected-tab {
  background-color: #eee;
}

#tab-1 {
  background-color: #D480FF;
  display: block;
}

#tab-2 {
  background-color: #809FFF;
}

#tab-3 {
  background-color: #FF7C5C;
}

Again, very simple, nothing too crazy. Now all we need is a few lines of javascript. As you can see in the HTML, we need to define a ShowTab function, and luckily I have one right here:

function ShowTab(num)
{
  $(‘#tab-anchors a’).removeClass(‘selected-tab’);
  $(‘#tab-anchor-‘ + num).addClass(‘selected-tab’);

  $(‘.tab’).hide();
  $(‘#tab-‘ + num).show();
}

So there it is. What? Too Easy? Well you better believe it. Basically we have a stack of divs that we show/hide when the anchors are clicked. It really is that simple. Just add some content in the divs and you are ready to go.

Well that wraps it up for this tutorial. Don’t forget to style and fill your tabs, and remember, when you need programming help all you have to do is Switch On The Code.

Snippet Tutorial – Short Circuiting

Typically here at Switch On The Code, we cover something that is language specific, focusing on syntax solutions that help you with your projects. Today we are going to step back a bit and talk about a feature of programming that I think is neat and worthy of talking about. This feature is known as Short-Circuiting, and it may elude some of you beginners out there.

Perhaps we should begin with an explanation. Short-Circuiting is a term used to describe logical operators that only evaluate if the first does not. For example, lets take the following PHP snippet:

$one = true;
$two = false;

if($one == null && !$two)
  echo "GO IF!";

In the context of short-circuiting, the second logical test would never get evaluated because the first one in the line already failed. Variable $two doesn’t even have to exist in this example, because it is technically never used.

You may be asking yourself “Why would I need this?” and in some languages don’t even offer this feature. Trust me though, it is extremely useful when you are dealing with large systems, with highly dynamic data. In the example above, it is clear that if you have short-circuiting available, it can be used when one variable relies on another. My favorite example of this is when you are using a Dataset, because it is very clear why you would use something like this:

DataSet data = GetSomeData();

if(data.tables.count > 0 && data.tables(0).rows.count > 0)
{
  //Do Something with data…
}

Normally you would never see something like this, mainly because if there are no tables, then there is certainly no rows in table 0. However, since we used short-circuiting operators, we can make both tests in one if statement. If there are no tables in the dataset, then it will “short-circuit” and break from the if statement. This way we can order our logical tests so that one can depend on the other evaluating.

It is an extremely useful feature that comes in handy more than it seems like at first. Now the only thing we need to know is what languages support short-circuiting. This is quickly remedied from a quick look at the wikipedia page provided in the references below.

One language that makes is quite obvious that is supports short-circuiting is the classic vb. The normal logical operators are And and Or, while the short-circuiting operators are AndAlso and OrElse. Most other languages use && and || as their short-circuiting operators. In the end you may just have to do some research to find out if your preferred language supports it.

So this is going to wrap it up for this tutorial. I hope you have been enlightened, and are learning about it before you need it. Just remember, when you need coding help, all you have to do is Switch On The Code.

jQuery Snippet – Interesting Selectors

As usual, here at Switch On The Code we are diving into jQuery once again. However, unlike a typical foray in the Javascript world, we are going to look at some simple jQuery selectors. Not just any selectors though. Today I have some interesting selectors that you may not know about, but can be extremely useful. So let’s get started.

:even and :odd

Quite possibly the most practical of the non-standard selectors, these do exactly what you are thinking. Being able to select every even or every odd object in an array can be very useful when you need to make your tables spiffy.

//Give my even rows some color
$(‘#myTable td:even’).css("background-color", "#ff5544");

:header

Before you go crazy trying to figure why you would need to select all header elements (h1, h2, h3), think about it a bit more. You could want to restructure the page, or scrap it for titles or important notes. You could also want to apply something to all the headers, who knows what crazy jQuery things you might need to do. This selector just saves you a few extra lines.

//Why not?
$(‘body’).find(‘:header’).remove();

:lt() and :gt()

Two letters can mean a lot of things, but in this case we have the Less-than and Greater-than selectors. This allows you to directly effect the result set that is returned, but specifying what indexes you want. Lesser-than (:lt) will return anything in the result set that appears before the specified index. As you may have guessed, greater than returns any object that appears after. Personally I am not sure why you would use this, but it is an interesting concept, none-the-less.

//Lets shorten things up a bit
$(‘div span:gt(4)’).remove();

:hidden

This one I personally find extremely useful. This selects elements that are not currently displayed, but not just with inputs of type hidden. This also selects anything of display none, objects with a width and height of 0, or any element with a hidden parent. So if you ever wanted to find out what might be hidden on a page, this selector is how you do it.

//Lets reveal a few things
$(‘body’).find(‘:hidden’).show();

:contains()

This is by far the most powerful selector that jQuery has to offer. It’s pretty obvious what this selector does, and I know I love the prospect of using a selector to determine what elements have the information I am looking for. This selector really shows that jQuery goes beyond normal CSS selectors and gives us ways to get exactly what we need, no matter how we want to find it.

//This is how you find him
$(‘body’).find(":contains(‘waldo’)");

:animated

We both know you use jQuery animations, and this seletor will help you halt all those animations if you need to. If you use one animation, chances are you use multiple ones, and sometimes you just need to hit the panic button and stop everything. So don’t underestimate such a specialized selector.

$(‘body:animated’).stop();

So these are some of the more interesting selectors I have come across. Some are more specialized than others, but they all have their uses. One thing to keep in mind though is that most of these have a sister function. For example, there are selectors for :first and :last, but there are also functions that do the same thing, .first() and .last(). That being said, personally I think selectors offer a more efficient way of doing things.

This wraps it up for this tutorial, I hope you have a place for your new selectors. Just remember, when you need coding help all you have to do is Switch On The Code.

Redirect Mobile Devices Using Htaccess

When working with clients you always get some odd requests, well I recently was requested to redirect a particular url on a site to a third party url when someone visits from a mobile device. Now, in theory this doesn’t sound all that difficult and really there isn’t much code either. The problem is getting the exact htaccess code you need, which can be a pain especially with trying to debug mod_rewrite and Apache.

I figured I would help everyone out and plop down some code here for everyone. So, in all it’s glory I give you some rules for mod_rewrite to redirect a url on a mobile device to another url.

########## Begin – Redirect Mobile Browser Accessing /siteurltoredirect
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
RewriteRule ^siteurltoredirect$ http://theendpointurl.com [R,L]
########## End – Redirect Mobile Browser Accessing /siteurltoredirect

The above code should cover all modern mobile browsers. Basically, it checks the user agent to see if the incoming is a mobile browser and then if the url requested is /siteurltoredirect it redirects it to http://theendpointurl.com. It’s as simple as that, now I hope this helps you from wasting an hour tracking down the exact syntax like I did.

Drupal 7 Snippet – info File Expanded

Over the last few weeks, we have explored Drupal themes and what is possible with them. While theming can be quite simple once you understand the basics, there are more advanced concepts to Drupal themes, and today we will be taking a short look at one of them. More specifically, today we are going to be taking a quick look at some of the optional sections of the info file.

In our first tutorial, we touched on some of the basic concepts in Drupal themes, including the heart of the theme, the info file. In that tutorial, only the most necessary parts were revealed, but today we are going to touch on some of the parts that are not required, but are still good to have. Before we get started, let’s review the file as it is right now:

name        = SOTC Theme
description = The Theme used for Switch On The Code
;screenshot = zen-internals/screenshot.png

core        = 7.x
engine      = phptemplate

regions[top_nav]    = Top Navigation
regions[content]    = Content Area
regions[sidebar]    = Sidebar
regions[bottom_nav] = Bottom Navigation

stylesheets[all][] = styles.css

;Theme Information
version = "0.1a"
core = "7.x"
project = "Switch On The Code"

Nothing too special, just a few regions, a stylesheet, and of course a name and description. All of this was explained in greater detail in part 1, so if you want to catch up, take a look at it.

Javascript Includes

The first addition we will be making is some script files, i.e. javascript files. The info file actually allows us to include javascript files. In Drupal 7, this is actually the only way to include javascript in the theme, so this is actually a fairly crucial aspect for more advanced themes. So with this addition, you info file might look something like this:

name        = SOTC Theme
description = The Theme used for Switch On The Code
;screenshot = zen-internals/screenshot.png

core        = 7.x
engine      = phptemplate

regions[top_nav]    = Top Navigation
regions[content]    = Content Area
regions[sidebar]    = Sidebar
regions[bottom_nav] = Bottom Navigation

stylesheets[all][] = styles.css

scripts[] = jquery-1.6.2.min.js
scripts[] = sotc.js

;Theme Information
version = "0.1a"
core = "7.x"
project = "Switch On The Code"

As you can see, it is fairly simple, in a way just like you add stylesheets. One important thing to note, however, is that you can always include your javascript files on the template pages themselves, or directly in your html template, which would be a global javascript include for every page. Using the info file is just one way to accomplish this.

Theme Features

In Drupal, there are certain featured that are offered to themes. These features in Drupal 7 include things such as a logo or a favicon. In the info file, you can turn these features on or off for your theme by listing them. If the feature is listed in the info file, then it will be available for Drupal users to take advantage of. Just remember, any feature you list, you must include it your theme in some way or another.

If we were to include every feature Drupal 7 has to offer themes, our new info would look like this:

name        = SOTC Theme
description = The Theme used for Switch On The Code
;screenshot = zen-internals/screenshot.png

core        = 7.x
engine      = phptemplate

regions[top_nav]    = Top Navigation
regions[content]    = Content Area
regions[sidebar]    = Sidebar
regions[bottom_nav] = Bottom Navigation

stylesheets[all][] = styles.css

scripts[] = jquery-1.6.2.min.js
scripts[] = sotc.js

features[] = logo
features[] = name
features[] = slogan
features[] = node_user_picture
features[] = comment_user_picture
features[] = favicon
features[] = main_menu
features[] = secondary_menu

;Theme Information
version = "0.1a"
core = "7.x"
project = "Switch On The Code"

Screenshot and PHP Version

Lastly, we have a few loose ends. First off, keen-eyed observers should have noticed that throughout the talk about our info file, there is a commented block that looks like ;screenshot = zen-internals/screenshot.png, which you have probably figured out that it is a remnant from the theme I started this project with. However, the screenshot, while not vital, is important in depicting what the theme will look like when enabled. The reference in our info file is literally a path to the screenshot file, in relation to our theme’s root folder. So if we were to use a screenshot, we might use screenshot = sotc-theme.png.

One last note on the info file would be the PHP version. While Drupal already has requirements for what PHP versions it supports, your theme could use features of newer versions of PHP. If this is the case, it is likely you will want to let Drupal know that your theme requires a newer version of PHP to work. To do this, you will use php = 5.3.0, which tells Drupal your theme needs that version or higher of PHP to work correctly.

So if we add these last two snippets, we get:

name        = SOTC Theme
description = The Theme used for Switch On The Code
screenshot = sotc-theme.png

core        = 7.x
engine      = phptemplate

regions[top_nav]    = Top Navigation
regions[content]    = Content Area
regions[sidebar]    = Sidebar
regions[bottom_nav] = Bottom Navigation

stylesheets[all][] = styles.css

scripts[] = jquery-1.6.2.min.js
scripts[] = sotc.js

features[] = logo
features[] = name
features[] = slogan
features[] = node_user_picture
features[] = comment_user_picture
features[] = favicon
features[] = main_menu
features[] = secondary_menu

;Theme Information
version = "0.1a"
core = "7.x"
php = 5.3.0
project = "Switch On The Code"

So this is the info file in all its glory. There is little more to it. With that in mind, its time to wrap up this tutorial. I hope you learned a lot, and that this helps in your Drupal theme development. Just remember, when you need coding help, all you have to do is Switch On The Code.

WPF’s Most Important Property – UseLayoutRounding

Ever since the introduction of WPF, applications developed using the technology have all had a similar look – fuzzy. In .NET 4, the developers at Microsoft made great strides in the clarity and readability of WPF applications.

Up until .NET 4, developers have used many tricks to get icons and line edges clearer than they are by default. Whereas some tricks may still be needed, one new property puts an end to much of the fuzziness frustration – UseLayoutRounding.

Below is an example of how UseLayoutRounding can help us. The left image is how WPF acts by default. The right is with UseLayoutRounding set to true.

UseLayoutRounding Example

Left: UseLayoutRounding Disabled Right: UseLayoutRounding Enabled

The above examples are made using a very basic WPF application. The only difference between the applications is whether or not UseLayoutRounding is enabled.

<Window x:Class="UseLayoutRoundingTutorial.MainWindow"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       Title="MainWindow"
       Height="350"
       Width="525"
       UseLayoutRounding="True">
  <Grid>
    <Image Source="image.png" Width="100" Height="100" />
  </Grid>
</Window>

UseLayoutRounding should be set on a root element, like the main window in this example. MSDN explains it best:

You should set UseLayoutRounding to true on the root element. The layout system adds child coordinates to the parent coordinates; therefore, if the parent coordinates are not on a pixel boundary, the child coordinates are also not on a pixel boundary.

That does it for the UseLayoutRounding property. I can’t imagine any WPF application where this should not be added, as it can only improve the visual quality of your applications.

jQuery Snippit – .each()

Here at Switch On The Code we love us some jQuery. We not only have tutorials, but we use jQuery ourselves for the very site you are visiting right now. It makes the life of a web developer so much easier. Sometimes, however, there just isn’t a magical jQuery function that does what you need. On occasion you need to select a bunch of stuff and do some custom logic on each element. You don’t necessarily need to move all the objects or change some css, sometimes you just need to do something more your own style. This is where the each() function comes in.

The each() works just like it sounds. It takes a collection of jQuery objects and iterates over each DOM object for the jQuery objects. This is an important fact to remember, that each() iterates the DOM objects associated with the jQuery objects, not the jQuery objects themselves. Now, that being said, it is not difficult to use each. First, we have to start with some HTML to manipulate.

<div id="numbers">
  <span>45</span>
  <span>10</span>
  <span>35</span>
  <span>89</span>
  <span>17</span>
</div>

So here we have a few numbers inside a div. Let’s say we want to add 10 to every number. jQuery doesn’t have a function to do that, which is not too much of a surprise. However, using jQuery’s each(), it becomes much easier.

$(‘#numbers span’).each(function(index)
{
  var num = parseInt($(this).text());
  num = num + 10;
  $(this).text(num);
});

With this simple example we just select all the spans inside the div, convert the text to an int, then finally add ten and set the span text to the new number. With jQuery’s each() it is extremely quick and quite simple to do. We just have to remember that the function iterates DOM objects so this refers to a DOM object, not a jQuery Object. This is why you see $(this) which converts the DOM object into a jQuery object.

This is it for this snippit, and now you know how the each() works. If you have any questions concerning jQuery or javascript, just head over to the forums. And don’t forget, when you need coding help, all you have to do is Switch On The Code.

Drupal 7 – Building Themes Part 2

In part one, we covered the basics of how Drupal themes work and the base files that are used. We left off on template files, which are the heart of Drupal themes. Today we are going to continue with template files and give some examples of ones every theme will most likely use.

We covered html.tpl.php in part 1, but it was also mentioned that you will most likely not override this file, and it was used more for example purposes. The files we will be going over today are going to be used by any theme you come across and include a lot more bulk than html.tpl.php. The first one we will be covering is page.tpl.php.

page.tpl.php

page.tpl.php is the heart of a Drupal theme. While html.tpl.php provides the basic HTML template for a theme, it is really just a simple wrapper and is so generic that it will never change. The real juicy template you want is the page template. It provide the structure for every page in Drupal, no matter what it is. For an example, we will be looking at the file from the garland theme, which is included with any fresh Drupal install.

<?php print render($page[‘header’]); ?>

<div id="wrapper">
  <div id="container" class="clearfix">

    <div id="header">
      <div id="logo-floater">
      <?php if ($logo || $site_title): ?>
        <?php if ($title): ?>
          <div id="branding"><strong><a href="<?php print $front_page ?>">
          <?php if ($logo): ?>
            <img
              src="<?php print $logo ?>"
              alt="<?php print $site_name_and_slogan ?>"
              title="<?php print $site_name_and_slogan ?>"
              id="logo" />
          <?php endif; ?>
          <?php print $site_html ?>
          </a></strong></div>
        <?php else: ?>
          <h1 id="branding"><a href="<?php print $front_page ?>">
          <?php if ($logo): ?>
            <img
              src="<?php print $logo ?>"
              alt="<?php print $site_name_and_slogan ?>"
              title="<?php print $site_name_and_slogan ?>"
              id="logo" />
          <?php endif; ?>
          <?php print $site_html ?>
          </a></h1>
      <?php endif; ?>
      <?php endif; ?>
      </div>

      <?php if ($primary_nav): print $primary_nav; endif; ?>
      <?php if ($secondary_nav): print $secondary_nav; endif; ?>
    </div>

    <?php if ($page[‘sidebar_first’]): ?>
      <div id="sidebar-first" class="sidebar">
        <?php print render($page[‘sidebar_first’]); ?>
      </div>
    <?php endif; ?>

    <div id="center"><div id="squeeze">
      <div class="right-corner">
        <div class="left-corner">
          <?php print $breadcrumb; ?>
          <?php if ($page[‘highlighted’]): ?>
           <div id="highlighted">
              <?php print render($page[‘highlighted’]); ?>
            </div>
          <?php endif; ?>
          <a id="main-content"></a>
          <?php if ($tabs): ?><div id="tabs-wrapper" class="clearfix"><?php endif; ?>
          <?php print render($title_prefix); ?>
          <?php if ($title): ?>
            <h1<?php print $tabs ? ‘ class="with-tabs"’ : ?>>
            <?php print $title ?></h1>
          <?php endif; ?>
          <?php print render($title_suffix); ?>
          <?php if ($tabs): ?><?php print render($tabs); ?></div><?php endif; ?>
          <?php print render($tabs2); ?>
          <?php print $messages; ?>
          <?php print render($page[‘help’]); ?>
          <?php if ($action_links): ?>
          <ul class="action-links">
            <?php print render($action_links); ?>
          </ul>
          <?php endif; ?>
          <div class="clearfix">
            <?php print render($page[‘content’]); ?>
          </div>
          <?php print $feed_icons ?>
          <?php print render($page[‘footer’]); ?>
          </div>
        </div>
      </div>
    </div>

    <?php if ($page[‘sidebar_second’]): ?>
      <div id="sidebar-second" class="sidebar">
        <?php print render($page[‘sidebar_second’]); ?>
      </div>
    <?php endif; ?>

  </div>
</div>

At first glance this can be a bit intimidating, but overall this file is a very simple shell of a website. As we examine the file from top to bottom, we see all the basic parts of a site. We have a header, a few sidebars, a content area, and a footer. The difference between a normal page layout and this one is, again, the use of php variables to include the content.

Your page.tpl.php file can be laid out in any way you want. However, the sections you setup in your info file should be included here. You print your sections using the $page variable and the render() function, which is used in combination throughout the example.

Another thing we see quite often are checks for variables. Like html.tpl.php, there are variables that are only available in this template file. Things such as the blog title, logo, and navigation are included so you can lay them out as you see fit. Check the references section for a link to a list of all the available variables for this page.

node.tpl.php

Quite possibly the most important template in a theme, node.tpl.php is used for a single node page. This is used for any content type that uses the node structure, and typically this is just about any piece of content you have. So let’s take a look at an example file:

<div
  id="node-<?php print $node->nid; ?>"
  class="<?php print $classes; ?>"
  <?php print $attributes; ?>>

  <?php print $user_picture; ?>

  <?php print render($title_prefix); ?>
  <?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>>
      <a href="<?php print $node_url; ?>">
      <?php print $title; ?></a>
    </h2>
  <?php endif; ?>
  <?php print render($title_suffix); ?>

  <?php if ($display_submitted): ?>
    <span class="submitted"><?php print $submitted ?></span>
  <?php endif; ?>

  <div class="content clearfix"<?php print $content_attributes; ?>>
    <?php
      hide($content[‘comments’]);
      hide($content[‘links’]);
      print render($content);
    ?>
  </div>

  <div class="clearfix">
    <?php if (!empty($content[‘links’])): ?>
      <div class="links">
        <?php print render($content[‘links’]); ?>
      </div>
    <?php endif; ?>

    <?php print render($content[‘comments’]); ?>
  </div>

</div>

Like our previous examples, we have a lot of php code referencing variables that are passed through. In this template we have access to all the information about the node, such as the author and comments. While this is a little simpler than the page template, it is equally as important.

One thing to keep in mind, however, is that the node template is being included inside the page template when you are viewing a node. This is one of the most important concepts behind themes, that your template files will create a hierarchy. The HTML template will include the page template, which will include the node template. This is the way the templating engine works.

Between these two files, combined with the others from part one, you have a simple theme. In fact, some of the themes included with Drupal are little more than what we have here. If you add some CSS and the few missing images, you will be good to go.

So this wraps up part two. Keep an eye out for part three, where we will be going over some of the more advanced features of theme building, and some of the other important template files. Just remember, that if you need coding help, all you have to do is Switch On The Code.

Drupal 7 – Building Themes Part 1

Drupal is a very powerful, and extensible, CMS and with release of Drupal 7 we saw even more power added to it. However, Drupal has always been known to have a fairly steep learning curve, with a whole lot of new concepts to learn. Today we hope to break some of that curve by showing you how to start your Drupal theme, and bring your Drupal site an exciting new look.

Introduction

The easiest part of the theme process in drupal is finding them. They can be found in the themes folder, which is in the root folder of your Drupal installation. Inside Drupal itself, you change the theme by going to the Appearance section on the Admin side. So putting your theme in the right place and changing it is pretty easy.

The difficulties start when it is time to begin building the theme. The folder structure itself can seem a bit alien, especially if you are looking at some of the more complex themes. That being said, there is basically only one folder inside our theme directory, templates. Every theme needs at least templates to change the design of a page, and it is best to create a folder for this, as organization is key. The real trick here is figuring out what templates to override.

Think of themes in Drupal as sub-classes of the main theme. Unlike WordPress or other CMS theming systems, Drupal uses its built-in basic theme for anything that is not defined in the theme itself. In essence, you are overriding this basic theme with each template you make, and if Drupal doesn’t find a template it is looking for, it uses its basic one.

Getting Started

Before we get into our first template file, we need a theme folder, and setup our theme configuration. As long as this folder is inside the themes directory, you can call it whatever you want. Another thing that needs to present is the templates directory inside our themes folder.

The first file we will need is our configuration file. This will tell Drupal a load of information about our theme, including the name, version, and even a few files that needs to be loaded in. This magical file is called the info file and has be be named the same at the theme folder with the .info file extension. So if we named our folder “sotc”, then our info file will be “sotc.info”. The whole folder structure for our theme will look something like so:

The Folder Structure for our Drupal Theme

Info File

The info file itself has quite a structure to it. It can be quite large or deceptively small. The most basic file will look something like so:

name        = SOTC Theme
description = The Theme used for Switch On The Code
;screenshot = zen-internals/screenshot.png

core        = 7.x
engine      = phptemplate

regions[top_nav]    = Top Navigation
regions[content]    = Content Area
regions[sidebar]    = Sidebar
regions[bottom_nav] = Bottom Navigation

stylesheets[all][] = styles.css

;Theme Information
version = "0.1a"
core = "7.x"
project = "Switch On The Code"

Most of the items here are self explanatory. You have a name, description, screenshot, etc. However, the regions section is not as obvious. The regions separate different parts of a Drupal page, and define the area’s content. Regions are defined by the theme, but can be utilized by the Drupal admin to place widgets and other content pieces. Things such as navigation and the login form can be placed based on what region they need to be in. So it is important that you layout your regions wisely.

In this example we have a basic website layout, with a header/footer, content area, and a sidebar. You can change, add, or remove regions as you see fit. There is literally no limit to the regions you can have. However, you will almost always need at least content region defined.

Lastly, we have the stylesheet. You can have a lot of different stylesheets defined in the info file, based on what pages you need them to appear in. In this basic example, we just have one stylesheet that is included on every page.

Before we move on, remember that this info file can be a lot more complex. I left out theme “features” because they are not required and for this basic tutorial they are not needed. If you would like to know the true potential of this file, check out the references.

html.tpl.php

Our last step in this tutorial is to create our first template file, with is the basis of our theme. html.tpl.php is the wrapper for all pages in Drupal. Most themes don’t actually override this file, as it is typically very basic. We will be defining our own in order to introduce the basic concepts behind templates.

To start, each template is named with a “.tpl.php” extension, and is typically named in relation to what role it plays in the theme. For example, html.tpl.php refers to the fact that this file is the html template for the theme. Other templates include page.tpl.php and node.tpl.php. Overall there are templates for just about any type of page you can think of, so in theory your theme could control how every page looks.

So after the file itself is created, it has to be filled. Our file will look something like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html
 xmlns="http://www.w3.org/1999/xhtml"
 xml:lang="<?php print $language->language; ?>"
  version="XHTML+RDFa 1.0"
  dir="<?php print $language->dir; ?>"
  <?php print $rdf_namespaces; ?>>

  <head profile="<?php print $grddl_profile; ?>">
    <?php print $head; ?>
    <title><?php print $head_title; ?></title>
    <?php print $styles; ?>
    <?php print $scripts; ?>
  </head>
  <body class="<?php print $classes; ?>" <?php print $attributes; ?>>
    <?php print $page_top; ?>
    <?php print $page; ?>
    <?php print $page_bottom; ?>
  </body>
</html>

As I mentioned above, most themes used the default html.tpl.php, but this one has a few things stripped out. However, overall this file is the same as the default template. With this in mind, this does show us how a basic template file is structured.

Templates are, at their core, an HTML file with some php mixed in. As the view layer of Drupal, templates are very simple and do very little work beyond formatting output. The output itself is provided by a series of variables, which are passed to the template. Each template file has its own collection of output variables, so keep in mind that other templates may not have access to the variables in this one.

So this is our first template file. In provides the base for our Drupal theme. In the next tutorial we will be building our other templates, and providing some CSS to make things pretty. So keep an eye out for Part 2, and just remember that if you need coding help, all you have to do is Switch On The Code.

C# Tutorial – Optional and Named Arguments

When C# 4.0 was released, developers got their hands on some syntactic sugar that helps in the readability and maintainability of code – optional arguments and named arguments.

Optional Arguments

The first concept we’ll be looking at today is optional arguments. Let’s use optional arguments to help a common maintainability issue – adding another argument to a function. Here’s a really basic method that we’ll be extending.

public void MyFunction(int a)
{
  Console.WriteLine("Parameter a is: {0}", a);
}

MyFunction(3);
// Output: Parameter a is: 3

At some point in the future, as often happens, a developer decides MyFunction needs to do a little more and needs another argument.

public void MyFunction(int a, int b)
{
  Console.WriteLine(a);
  Console.WriteLine(b);
}

This introduces a maintainability problem – everywhere that MyFunction is called now needs to supply another argument. What the developer can do instead is assign argument “b” a default value.

public void MyFunction(int a, int b = 4)
{
  Console.WriteLine("Parameter a is: {0}", a);
  Console.WriteLine("Parameter b is: {0}", b);
}

MyFunction(3);
// Output: Parameter a is: 3
// Output: Parameter b is: 4

With the use of optional parameters none of the calling code needs to change, and the developer can be at least a little more confident that she didn’t break existing code.

There’s no limit to the types that can be used in optional parameters. Let’s extend our method again by adding an optional string parameter.

public void MyFunction(int a, int b = 4, string c = "foo")
{
  Console.WriteLine("Parameter a is: {0}", a);
  Console.WriteLine("Parameter b is: {0}", b);
  Console.WriteLine("Parameter c is: {0}", c);
}

This function can now be called three different ways.

MyFunction(3);
// Output: Parameter a is: 3
// Output: Parameter b is: 4
// Output: Parameter c is: foo

MyFunction(3, 5);
// Output: Parameter a is: 3
// Output: Parameter b is: 5
// Output: Parameter c is: foo

MyFunction(3, 5, "bar");
// Output: Parameter a is: 3
// Output: Parameter b is: 5
// Output: Parameter c is: bar

So now what happens if a caller wants to use MyFunction and only supply values for “a” and “c”. This is now possible with the use of named arguments.

Named Arguments

Using named parameters, let’s call the previous function and supply values for “a” and “c”.

MyFunction(3, c: "bar");
// Output: Parameter a is: 3
// Output: Parameter b is: 4
// Output: Parameter c is: bar

As you can see, named arguments are used by supplying the name of the argument, a colon, and then the value you’d like to supply for that argument. If you don’t supply a name, like I did in this case, they will be assigned in the order they appear in the method signature.

We could also reorder the arguments, if we wanted.

MyFunction(c: "bar", a: 3);
// Output: Parameter a is: 3
// Output: Parameter b is: 4
// Output: Parameter c is: bar

One of the best uses I’ve seen so far for named arguments is to improve readability. Here’s an example of code that has poor readability.

Update(
  0.1,
  2.4,
  1.7,
  0.0,
  10.3,
  2.3,
  1.0,
  0.0,
  0.0);

I’m sure we’ve all seen something similar to this. What the heck are those values supposed to mean. Using comments for every value would help, but another solution is to name each argument.

Update(
  positionX: 0.1,
  positionY: 2.4,
  positionZ: 1.7,
  velocityX: 0.0,
  velocityY: 10.3,
  velocityZ: 2.3,
  accelerationX: 1.0,
  accelerationY: 0.0,
  accelerationZ: 0.0);

This is much more readable. We can see clearly that this Update function is used for some physical properties of an object and we can clearly see where each value is being applied.

That does it for this tutorial on optional and named arguments. Hopefully you can see where this syntax would be useful in your own systems and you begin using them to create higher quality code. If you’ve got any questions or comments, please leave them below.

WPF DataGrid Tutorial – Row Headers

When using Data Grids to present data, row headers can be valuable additions – especially if the grid contains more columns than can fit on the screen at one time. Row headers don’t scroll horizontally with the rest of the content, which means users can use them to see the context of the data they’re viewing. This tutorial will demonstrate how to create row headers using WPF’s DataGrid control.

The first thing we need is some data to put in our DataGrid. I’m going to use a very basic Movie class that contains some basic information about movies for this.

/// <summary>
/// Class that holds basic details for a movie.
/// </summary>
public class Movie
{
  public string Title { get; set; }
  public int Year { get; set; }
  public string Director { get; set; }
}

Now let’s create some of these and assign them to the DataGrid’s ItemsSource.

// Create a collection of movies.
var movies = new List<Movie>
{
  new Movie()
  {
    Title = "The Fifth Element",
    Year = 1997,
    Director = "Luc Besson"
  },

  new Movie()
  {
    Title = "Dark City",
    Year = 1998,
    Director = "Alex Proyas"
  },

  new Movie()
  {
    Title = "The Lawnmower Man",
    Year = 1992,
    Director = "Brett Leonard"
  }
};

// Fill the datagrid with the collection of movies.
// This datagrid is defined in XAML.
_myDataGrid.ItemsSource = movies;

In this snippet of code, I’ve created three Movie objects and put them into a List. I then assigned the list to the ItemsSource of a DataGrid. The DataGrid was created in XAML, so let’s look at that now.

<Window x:Class="DataGridRowHeader.MainWindow"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       Title="MainWindow"
       Height="350"
       Width="525">
  <Grid>
    <DataGrid x:Name="_myDataGrid"
             AutoGenerateColumns="False"
             IsReadOnly="True">
      <DataGrid.Columns>
        <DataGridTextColumn Header="Title"
                           Binding="{Binding Title}" />
        <DataGridTextColumn Header="Year"
                           Binding="{Binding Year}" />
        <DataGridTextColumn Header="Director"
                           Binding="{Binding Director}" />
      </DataGrid.Columns>
    </DataGrid>
  </Grid>
</Window>

If we run this code now, we’d get something that looks like this:

No row headers

Obviously we have no row headers yet. Let’s take a look at the XAML change required to make those happen.

<DataGrid x:Name="_myDataGrid"
         AutoGenerateColumns="False"
         IsReadOnly="True">
  <DataGrid.RowHeaderStyle>
    <Style TargetType="DataGridRowHeader">
      <Setter Property="Content"
             Value="{Binding Title}" />
    </Style>
  </DataGrid.RowHeaderStyle>
  <DataGrid.Columns>
    <DataGridTextColumn Header="Year"
                       Binding="{Binding Year}" />
    <DataGridTextColumn Header="Director"
                       Binding="{Binding Director}" />
  </DataGrid.Columns>
</DataGrid>

Unfortunately, row headers aren’t as simple as they should be to set up, but they’re not too bad once you’ve figured it out. What we have to do is use a style to set the Content property of the DataGridRowHeader objects. The DataGrid directly exposes a property that can be used to set this style – which is nice. What we’re doing is setting the content to a property in our Movie class, the Title. Since the title is now in the row header, I also removed the column for this property. Now if we run the app, we get something that looks like this:

Row headers

And there you have it. We’ve created nice looking row headers for our WPF DataGrid. Hopefully this helped you out in your own projects, and if you have any questions or comments, feel free to leave them below.