Thursday, September 29, 2011

A Simple AppSettings Type Provider

With the F# 3.0 Developer Preview now available, I've been spending a decent chunk of my free time playing with Type Providers. With the announcement of the introductory guide and samples for authoring type providers I've had a hard time putting down the computer to sleep (let alone eat).

After a fair amount of experimentation, I've written my first type provider. It is admittedly quite simple and isn't production quality, but it has been a fun exercise. The basic idea is to read the appSettings elements from a config file, parse the values appropriately, and interact with them in a type safe way.

The sample config file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="test2" value="Some Test Value 5"/>
        <add key="TestInt" value="102"/>
        <add key="TestBool" value="True"/>
        <add key="TestDouble" value="10.01"/>
    </appSettings>
</configuration>
Here's the TypeProvider code:

Lastly, here's an example of how to use it.
#r "System"
#r @"bin\debug\AppSettingsTypeProvider.dll"

open System
open AppSettingsTypeProvider

type settings = AppSettings<"App.config">
printfn "Test2 String: %s" settings.test2 
printfn "Test Int: %i" settings.TestInt 
printfn "Test Bool: %b" settings.TestBool  
printfn "Test Double: %f" settings.TestDouble

Wednesday, September 21, 2011

Presentation: Dialing Up with F# and Windows Phone 7

A big thanks to Onorio for having me speak for the MIGang FSharp Special Interest Group tonight.

The slides that accompanied this presentation are shown below (use the mouse or the left and right arrow keys to navigate the slides):



Additionally, these slides and the associated examples can be found on my GitHub at https://github.com/dmohl/DialingUpWithFSharpAndWP7_Presentation.

Friday, September 16, 2011

F# Type Providers - Querying StackOverflow

If you haven't yet heard, the F# 3.0 preview bits were released to the wild a couple of days ago. Congrats to the F# team for this huge accomplishment!

One of the most anticipated features of F# 3.0 is Type Providers. Type Providers make F# the best available option for working in an information-rich world. Even though the preview has only been available for a few days, there is already quite a bit of content covering Type Providers. Here are a few examples:

http://msdn.microsoft.com/en-us/library/hh156509(v=VS.110).aspx
http://blogs.msdn.com/b/fsharpteam/archive/2011/09/14/f-3-0-developer-preview-now-available.aspx
http://fsharp3sample.codeplex.com/

Here's a simple example of querying the StackOverflow OData feed using a Type Provider:


How Do I Get It?

To start playing with F# 3.0, install the VS2011 dev preview and follow any of the step-by-step instructions provided at http://msdn.microsoft.com/en-us/library/hh156509(v=VS.110).aspx.

Tuesday, September 13, 2011

Advantages of CoffeeScript When Working with jQuery Templates

Working with jQuery Templates in CoffeeScript is very similar to working with them in JavaScript. However, there are a couple of CoffeeScript features that can make it even easier.

Here's a simple example (based on an example in the jQuery Template documentation):


As you can see, it's pretty similar to its JavaScript counterpart.

How can CoffeeScript make this better?

Enter Heredoc and String Interpolation...

Heredoc: Heredocs allow you to specify multi-line, formatted text. This can be useful when defining the template markup.

With heredocs, the markup from the previous example changes to this:


String Interpolation: CoffeeScript also provides Ruby style string interpolation. Here's an example of the markup after taking advantage of the string interpolation feature (Note: String interpolation only occurs within double-quoted strings and double-quoted heredocs):


Want to see it in action?

Go to http://tinkerbin.com/w0QoscT9, change the JavaScript Format drop down to CoffeeScript, then click the Run button.

Sunday, September 11, 2011

WP7 AccelerometerProxy in F#

With the release of the Windows Phone 7.1 SDK RC, there is now an easy way to use the emulator to simulate sensor data (such as data from the accelerometer). Unfortunately, I'm doing WP7 development in a VM and haven't yet had any luck getting the new SDK functionality to work in that environment.

I am however able to run the emulator using the WP7 Developer Tools RTW, but of course that version did not include functionality to simulate sensor data. There are a couple of options that people have identified for simulating accelerometer data (see Example using a mouse, Example using a Wiimote, Example using external app). For my needs, I decided to go with the mouse-driven approach.

While I could have easily used the C# library from the previously mentioned example, I decided instead to port that example to F#. The result is show here:


You can find the full example at https://github.com/dmohl/FsWP7Accelerometer.

Tuesday, September 6, 2011

Getting Started with the F# PowerPack - Part 4

In this series, I'm walking you through various features provided by the F# PowerPack.

Here are the links to the previous posts:

- Part 1
- Part 2
- Part 3

In this post, I'll briefly talk about Lexing, Parsing, SI (Metric) Units of Measure, Physical Constants, and Native Array.

Lexing and Parsing:

The FsLex and FsYacc documentation provides a good overview of how to get started with the lexing and parsing functionality offered by the PowerPack. As mentioned in this documentation, Jomo Fisher's Parsed Language Parser Template provides a great place to start from a code point of view. Note: Lexing and Parsing currently require the F# PowerPack to be installed with the MSI rather than with just the NuGet package.

SI (Metric) Units of Measurement:

Units of Measure are available in F# out-of-the-box (see http://cvslab.di.unipi.it/vslab/blog/post/2011/09/05/Ammeter-interface.aspx for a recent example of this feature in use); however, the PowerPack contains several useful predefined units of measure. Chris Smith speaks of the F# PowerPack in his Programming F# book and SI units of measure is one of the highlighted features. Additionally, Andrew Kennedy has a great post on this topic: http://blogs.msdn.com/b/andrewkennedy/archive/2008/09/02/units-of-measure-in-f-part-two-unit-conversions.aspx.

Here's a list of the SI Units that are provided:

Meter (m), Kilogram (kg), Second (s), Ampere (A), Kelvin (K), Mole (mol), Candela (cd), Hertz (Hz), Newton (N), Pascal (Pa), Joule (J), Watt (W), Coulomb (C), Volt (V), Farad (F), Ohm (ohm), Siemens (S), Weber (Wb), Tesla (T), Henry (H), Lumen (lm), Lux (lx), Becquerel (Bq), Gray (Gy), Sievert (Sv), Katal (kat)

PhysicalConstants:

The PowerPack also comes with a few useful predefined physical constants.

Here's the full list (note: these are basically straight from the code comments):

- Speed of light in vacuum
- Magnetic constant
- Electric constant
- Newtonian constant of gravitation
- Planck constant
- Dirac constant (a.k.a. the reduced Planck constant)
- Elementary charge
- Magnetic flux quantum h/2e
- Conductance quantum
- Electron mass
- Proton mass
- Fine-structure constant
- Rydberg constant
- Avogadro constant
- Faraday constant
- Molar gas constant
- Boltzmann constant R/N_A
- Stefan-Boltzmann constant
- Electron volt
- Unified atomic mass unit

NativeArray:

NativeArray.fs provides several modules and types that can be useful when doing native interop.

The NativeOps and Ref modules provide functions for pinning an object.

The types that are defined include PinnedArray, PinnedArray2, NativeArray, and FortranMatrix. There are a few examples of these types in use in the NativeArrayTests.fs file in the FSharp.PowerPack.Unittests project.

Thursday, September 1, 2011

Unit Testing a jQuery Plugin with CoffeeScript and Pavlov

If you search the web, you'll find a handful of good examples of jQuery plugins written in CoffeeScript, but there seems to be few examples of writing unit tests/specs in CoffeeScript. In this post, I'll show a very simple jQuery plugin with Pavlov specs.

Simple Plugin

This plugin simply wraps the jQuery UI dialog (http://jqueryui.com/demos/dialog/).
do ($ = jQuery) ->
  methods = 
    init: (options) ->
      dialogElement = $(options.dialogSelector)
      dialog = dialogElement.dialog autoOpen: false, modal: true, resizable: false 
      $(options.inputSelector).click -> dialog.dialog 'open'
  
  $.fn.simple = (options) -> 
    settings = dialogSelector:'.dialog', inputSelector:'.input'
    if options 
      $.extend settings, options
    methods.init settings
Pavlov Specs

QUnit is a JavaScript testing framework (learn more about it at http://docs.jquery.com/Qunit) and Pavlov (https://github.com/mmonteleone/pavlov) extends QUnit with several features that promote Behavior-Driven Development (BDD). Here's the example:
pavlov.specify "Simple Plugin", ->
  describe "Given default options", -> 
    before -> $(this).simple()
    describe "when executing a click event", ->
      before -> $('.input').click()
      it "it should open the dialog", ->
        assert($('.dialog').parents('.ui-dialog:visible').length).isTrue()
      after ->
        $('.dialog').dialog('close')
    describe "When the click event has not been executed", ->
      it "it should not have an open dialog", ->
        assert($('.dialog').parents('.ui-dialog:visible').length).isFalse()
      after -> 
        $('.dialog').dialog('close')

  describe "Given all custom options", -> 
    before -> 
      $(this).simple dialogSelector:'.customDialog', inputSelector:'.customInput' 
    describe "when executing a click event", ->
      before -> $('.customInput').click()
      it "it should open the custom dialog", ->
        assert($('.customDialog').parents('.ui-dialog:visible').length).isTrue()
      after ->
        $('.customDialog').dialog('close')

  describe "Given only a custom dialogSelector", -> 
    before -> $(this).simple dialogSelector:'.customDialog'
    describe "when executing a click event", ->
      before -> $('.input').click()
      it "it should open the custom dialog", ->
        assert($('.customDialog').parents('.ui-dialog:visible').length).isTrue()
      after ->
        $('.customDialog').dialog('close')

  describe "Given only a custom inputSelector", -> 
    before -> $(this).simple inputSelector:'.customInput' 
    describe "when executing a click event", ->
      before -> $('.customInput').click()
      it "it should open the dialog", ->
        assert($('.dialog').parents('.ui-dialog:visible').length).isTrue()
      after ->
        $('.dialog').dialog('close')
The Output

Once we have this in place and create a simple test runner page, we end up with the standard QUnit output that looks like the following: