Monday, February 23, 2009

ASP.NET Membership Configuration

IIS 7 logo I’m using ASP.NET membership provider to manage ASP.NET users and roles. I’m using IIS 7. I can say just one thing: use IIS 7!!! You can manage the whole ASP.NET membership task from IIS7 MMC.

The best part: it gives much more information about errors compared to ASP.NET Configuration web-based configuration editor. I’ve extended the schema with own tables and I made a wrong constraint so I couldn’t create new users. I got a generic error message in web-based configuration editor tool. I got a specific error message in IIS 7. I couldn’t have traced back the error to the database without IIS 7 (or just with huge effort).

Thursday, February 19, 2009

Grading in Excel

Let’s say you have the following grades:

Score Grade Grade
[0,6] 1 E
(6,8] 2 D
(8,10] 3 C
(10,12] 4 B
(12,infinity) 5 A

You have the final score for a student, and you want to automate the grade calculation in Excel.

You have to use a function. The function you need is VLOOKUP.

You can use the VLOOKUP function to search the first column of a range (range: Two or more cells on a sheet. The cells in a range can be adjacent or nonadjacent.) of cells, and then return a value from any cell on the same row of the range.

The V in VLOOKUP stands for vertical. Use VLOOKUP instead of HLOOKUP when your comparison values are located in a column to the left of the data that you want to find.

VLOOKUP(lookup_value, table_array, col_index_num, [range_lookup])

  • lookup_value  Required. The value to search in the first column of the table or range. The lookup_value argument can be a value or a reference. If the value you supply for the lookup_value argument is smaller than the smallest value in the first column of the table_array argument, VLOOKUP returns the #N/A error value.

  • table_array  Required. The range of cells that contains the data. You can use a reference to a range (for example, A2:D8), or a range name. The values in the first column of table_array are the values searched by lookup_value. These values can be text, numbers, or logical values. Uppercase and lowercase text are equivalent.
  • col_index_num  Required. The column number in the table_array argument from which the matching value must be returned. A col_index_num argument of 1 returns the value in the first column in table_array; a col_index_num of 2 returns the value in the second column in table_array, and so on.

    If the col_index_num argument is:

    • Less than 1, VLOOKUP returns the #VALUE! error value.
    • Greater than the number of columns in table_array, VLOOKUP returns the #REF! error value.
  • range_lookup  Optional. A logical value that specifies whether you want VLOOKUP to find an exact match or an approximate match:
    • If range_lookup is either TRUE or is omitted, an exact or approximate match is returned. If an exact match is not found, the next largest value that is less than lookup_value is returned.

      Important   If range_lookup is either TRUE or is omitted, the values in the first column of table_array must be placed in ascending sort order; otherwise, VLOOKUP might not return the correct value.

      For more information, see Sort data.

      If range_lookup is FALSE, the values in the first column of table_array do not need to be sorted.

    • If the range_lookup argument is FALSE, VLOOKUP will find only an exact match. If there are two or more values in the first column of table_array that match the lookup_value, the first value found is used. If an exact match is not found, the error value #N/A is returned.

    So in my case the function is


    It means I want to lookup the value of cell T3 in the range, and pick the result from the second column. The range contains the score and grade cells without the column headers.

    The lookup table should be

    Score Grade Grade
    0 1 E
    6,1 2 D
    8,1 3 C
    10,1 4 B
    12,1 5 A
    The score column values should be in increasing order. The score value column should contain the smallest numbers in the range.

    Thursday, February 12, 2009

    Moonlight 1.0

    I’ve just seen that Novell published Moonlight 1.0, the open source implementation of Silverlight for Linux. It’s very good for everyone, I can see just one problem: it’s Silverlight 1.0 implementation. Microsoft Silverlight is now in version 2.0.

    Can Novell follow (or catch) Microsoft? They can, but it seems to me that they are unable to follow them fast enough. They are late with almost a whole version. And that’s too much for me.

    Link: Moonlight 1.0 brings Silverlight to Linux

    Sunday, February 8, 2009

    F# - Exceptions

    /// Standard exception and rethrow
        | :? System.DivideByZeroException as exc ->
                printfn "1/0: %s" exc.Message
        | _ -> rethrow()
    /// Raise exception            
        raise (new System.Exception("Generic error"))
        | _ as exc -> printfn "Error: %s" exc.Message
    /// F# exception
        failwith "F# error"
        | _ as exc -> 
            printfn "Error: %s" exc.Message
            printfn "Exception type: %O" (exc.GetType())
    /// Finally
        failwith "Finally test"
        printfn ">>Finally"
    1/0: Attempted to divide by zero.
    Error: Generic error
    Error: F# error
    Exception type: Microsoft.FSharp.Core.FailureException
    Unhandled Exception: Microsoft.FSharp.Core.FailureException: Finally test
       at Microsoft.FSharp.Core.Operators.failwith[T](String message)
       at <StartupCode$Tupples>.$Program._main() in C:\Users\XXXXX\Documents\Visual
    Studio 2008\Projects\XXXXX\Program.fs:line 29

    Standard .NET exceptions can be handled by try … with expression. | is a pattern matching. :? is a type test, here against System.DivideByZeroException .NET exception.  as exc means exc is a variable that stores the exception (just like in C#). rethrow() rethrows the exception, like throw() in C#.

    raise can raise an exception. | _ means pattern matching for any kind of exception.

    F# exception can also be thrown. F# uses Microsoft.FSharp.Core.FailureException as its base exception type.

    There is a finally block as well, just like in C#, to execute code after try block independently from try block results. Unfortunately with and finally can’t be combined.

    F# – Control Flow

    There are 3 main loop types in F# for imperative programming style:

    • Iteration
      for id = … to … do
    • Sequence loop
      for … in expression do
    • Pre-test loop
      while … do

    This is an example code for each loops:

    /// Iteration
    printfn "for to do"
    printf "["
    for i=1 to 5 do
        printf "%d " i
    printf "]"
    /// Sequence loop
    printfn ""
    printfn ""
    printfn "for in do"
    let items = seq{1..5}
    printf "["
    for i in items do
        printf "%d " i
    printf "]"
    /// Pre-test loop
    printfn ""
    printfn ""
    printfn "while do"
    printf "["
    let mutable i = 1
    while i<=5 do 
        printf "%d " i
        i <- i+1
    printf "]"
    for to do
    [1 2 3 4 5 ]
    for in do
    [1 2 3 4 5 ]
    while do
    [1 2 3 4 5 ]

    All the loop types can be found in C#.

    seq{1..5} is a sequence data type that means:

    val it : seq<int> = seq [1; 2; 3; 4; ...]

    So we can say it contains 1,2,3,4,5.


    let mutable i = 1

    line means variable i can change its value. So i <- i+1 means assignment and can be evaluated.

    F# – Functional Composition

    I have created an example code in a previous blog entry to demonstrate the piping capabilities of F#:

    let replace from tos list = (fun item -> 
                    if item = from then tos
                    else item )
    let count list =
        List.length list
    let printList list =
        List.iter (fun item -> printfn "[%s]" item) list
    let abc = ["a";"b";"c"]
    abc |> printList
    abc |> replace "a" "k" |> count |> printfn "Number of items: %d"
    abc |> replace "a" "k" |> printList
    Number of items: 3

    This is a form of code we got used to in C-like languages: we have a function and we have arguments. What can we do if we don’t want to specify the arguments for a function? We can use functional composition.

    let count =
    let replace from tos = (fun item ->
                    if item = from then tos
                    else item)
    let printList =
           List.iter (fun item -> printfn "[%s]" item)
    let abc = ["a";"b";"c"]
    abc |> printList
    let nrOfItems =
        replace "a" "k"
        >> count
        >> printfn "Number of items: %d"
    let printReplace =
        replace "a" "k"
        >> printList
    abc |> nrOfItems
    abc |> printReplace
    Number of items: 3

    You can omit the parameter of the function and you can specify that at calling time. Code is more readable, maintainable.

    The operator specification for functional composition (>>) is:

    let (>>) f g x = g(f(x))

    The operator specification for pipeline (|>) is:

    let (|>) x f = f x

    Wednesday, February 4, 2009

    F# – Pipeline

    One of the unique functional elements of F# is piping. Piping means

    let (|>) x f = f x

    So a |> b means b a. It’s a reverse application function. Let’s see an example:

    let replace from tos list = (fun item -> 
                    if item = from then tos
                    else item )
    let count list =
        List.length list
    let printList list =
        List.iter (fun item -> printfn "[%s]" item) list
    let abc = ["a";"b";"c"]
    abc |> printList
    abc |> replace "a" "k" |> count |> printfn "Number of items: %d"
    abc |> replace "a" "k" |> printList
    Number of items: 3

    replace function changes list elements from to tos(tring). count function counts the number of list elements. printList prints the elements of the list.

    Piping can be used to chain the results of the functions after each other. It’s very similar to the piping pattern employed on Unix/Linux systems.

    F# – Visual Studio Integration

    The newer versions of F# support Visual Studio better and better, but don’t wait such feature rich designer support as C# and other mainstream languages have. In fact F# doesn’t have any designer support (yet?).

    F# integrates with Visual Studio, so first of all you can create an F# project from File/New/Project… Select Visual F# node. There are three project types:

    Project Description
    F# Application It creates a project that compiles to .NET .exe. It can be run from command prompt.
    F# Library It creates a project that compiles to .NET .dll. It can be referenced from other .NET applications.
    F# Tutorial It creates a project containing examples of F# language constructs.

    So application template compiles to a standalone application, library templates compiles to a .NET DLL, and tutorial template contains several examples. Library template contains a Script.sfx file. This file can be directly accessed from F# Interactive and loads the DLL so it can be tested in an interactive manner.

    F# Interactive is the interactive environment of F#. It’s reminds me to qBasic: expressions are evaluated as you type and close them. It’s basically an interpreter. F# Interactive can be accessed either from command prompt (called fsi.exe) or from Visual Studio. You can display it clicking on View/Other Windows/F# Interactive (CTRL+ALT+F). I prefer it full (editor) screen, so I usually drag it up to the editor area (e.g. over the editor window).
    Expressions must be closed with ;; operator in F# Interactive.

    Tuesday, February 3, 2009

    F# - Immutability

    Many F# data structures are immutable. Immutable means data can't be modified. It is one of the main ideas of functional programming. Let’s look at the following code:

    let text = "Hello F#"
    printf "4th character: %c" text.[3]
    4th character: l

    Dynamic data modification can be done by using the <- operator. Let’s try to modify the 4th character of the string.

    > a.[3] <- 'r';;
      a.[3] <- 'r';;
    stdin(8,1): error FS0191: invalid indexer expression.

    It means that a character of a string cannot be modified because a string is an immutable type. There are no background mechanism, to cover string immutability, similar to C#.

    Array is also an immutable type. Here is an example:

    let enumFruits fruitList =
        List.iter (fun element -> printf "[%s] " element) fruitList
        printfn ""
    let fruits = ["Apple"; "Banana"; "Cherry"]
    printf "Fruits: "
    enumFruits fruits
    printf "Fruits: "
    enumFruits fruits
    let extFruits = "Nut"::fruits
    printf "extFruits: "
    enumFruits extFruits
    Fruits: [Apple] [Banana] [Cherry]
    Fruits: [Apple] [Banana] [Cherry]
    extFruits: [Nut] [Apple] [Banana] [Cherry]

    enumFruits is a function to enumerate the items of the fruit list.

    The fruits array initially contains 3 elements: Apple, Banana, Cherry. The :: operator attaches an element called Nut to the head of the array. Inspecting the elements of fruits reveals that nothing has changed, fruits contains the same 3 elements. Array is immutable. extFruits is just for showing that :: operator really works.

    Monday, February 2, 2009

    F# – User Interface

    F# can access .NET assemblies, so Windows Forms is the UI library for F#. The following code reads and displays the HTML code in a TextBox.

    open System.Windows.Forms
    open System.IO
    open System.Net
    let form = new Form(Visible=false,Text="Hello F#")
    let result = new TextBox(Multiline=true,Dock=DockStyle.Fill, Text="")
    let getHtml (url: string) =
        let req = System.Net.WebRequest.Create(url)
        let resp = req.GetResponse()
        printfn "Connected"
        let stream = resp.GetResponseStream()
        let reader = new StreamReader(stream)
        let html = reader.ReadToEnd()
        printfn "Response read"
    printfn "Connecting..."
    let microsoft = getHtml("")
    result.Text <- microsoft
    form.Visible <- true
    Response read

    As you can see, Windows Forms knowledge is a requirement for F# UI development. Personally I don’t think UI elements should be developed in F#, C# has much better IDE designer support so far (F# don’t have designers).

    F# – Sequential code

    F# can handle sequential code. Expressions evaluated sequentially. Just the last result will be kept, other results will be dismissed to prevent side effects.

    let a = (2+3;5+7;4+4)
    printfn "a= %d" a
    let b = (a+2;a+5)
    printfn "b= %d" b
    a= 8
    b= 13

    It can be useful when we are doing complicated computations or initializations and we want to indicate the progress:

    printf "Processing"
    let c = (printf ".."; 2; printfn ".."; 3)
    printfn "c= %d" c
    c= 3

    F# – Typed tuples

    F# is a typed language. I create 2 tuples containing site URLs and relevancies. I create a tuple from the tuples above. I execute a pattern matching on site1 tuple, splitting it up to a string and an integer variables. Finally I print the content of the url and relevance variable to the console.

    let site1 = ("",10)
    let site2 = ("",9)
    let sites = (site1, site2)
    let url,relevance = site1
    printfn "site: %s" url
    printfn "relevance: %d" relevance
    relevance: 10

    Let’s test type safety:

    let url = url +2

    > let url = url + 2;;
      let url = url + 2;;
    stdin(34,17): error FS0001: The type 'int' does not match the type 'string'.

    This error message means that integer cannot be converted to string.

    Tuples can be used effectively in functions:

    let increase (a,b) =
    let printIncreased (a,b) =
        let (a,b) = increase (a,b)
        printfn "a: %d" a
        printfn "b: %d" b
    printIncreased (5,6)
    a: 6
    b: 7

    Finally a tuple with 4 elements:

    let quad = ("Doe", "John", 23, "New York")
    let last,first,age,location = quad
    System.Console.WriteLine("Last name: {0}\nFirst name: {1}\nAge: {2}\nLocation: {3}", last, first, age, location)
    Last name: Doe
    First name: John
    Age: 23
    Location: New York

    Sunday, February 1, 2009

    F# - Hello World

    A simple Hello World code in F#:

    let HelloWorld =
        printfn "Hello World"

    It is the IL code for the F# code above:

    Code to execute in IL:

      1: .class private abstract auto ansi sealed beforefieldinit $Program
      2:     extends [mscorlib]System.Object
      3: {
      4:     .method public static void _main() cil managed
      5:     {
      6:         .entrypoint
      7:         .maxstack 3
      8:         L_0000: nop 
      9:         L_0001: ldstr "Hello World"
     10:         L_0006: newobj instance void [FSharp.Core]Microsoft.FSharp.Text.Format`5<class [FSharp.Core]Microsoft.FSharp.Core.Unit, class [mscorlib]System.IO.TextWriter, class [FSharp.Core]Microsoft.FSharp.Core.Unit, class [FSharp.Core]Microsoft.FSharp.Core.Unit, class [FSharp.Core]Microsoft.FSharp.Core.Unit>::.ctor(string)
     11:         L_000b: call !!0 [FSharp.Core]Microsoft.FSharp.Core.Pervasives::printfn<class [FSharp.Core]Microsoft.FSharp.Core.Unit>(class [FSharp.Core]Microsoft.FSharp.Text.Format`4<!!0, class [mscorlib]System.IO.TextWriter, class [FSharp.Core]Microsoft.FSharp.Core.Unit, class [FSharp.Core]Microsoft.FSharp.Core.Unit>)
     12:         L_0010: stsfld class [FSharp.Core]Microsoft.FSharp.Core.Unit <StartupCode$ConsoleApplication1>.$Program::HelloWorld@19
     13:         L_0015: call class [FSharp.Core]Microsoft.FSharp.Core.Unit Program::get_HelloWorld()
     14:         L_001a: pop 
     15:         L_001b: ret 
     16:     }
     19:     .field assembly static class [FSharp.Core]Microsoft.FSharp.Core.Unit HelloWorld@19
     21: }

    The same code in C#:

      1: internal static class $Program
      2: {
      3:     // Fields
      4:     internal static Unit HelloWorld@19;
      6:     // Methods
      7:     public static void _main()
      8:     {
      9:         HelloWorld@19 = Pervasives.printfn<Unit>(new Format<Unit, TextWriter, Unit, Unit, Unit>("Hello World"));
     10:         Program.get_HelloWorld();
     11:     }
     12: }

    Something similar in C#:

      1: class Program
      2: {
      3:     static void Main(string[] args)
      4:     {
      5:         Console.WriteLine("Hello World");
      6:     }
      7: }

    It is the IL code for the C# code above:

      1: .class private auto ansi beforefieldinit Program
      2:     extends [mscorlib]System.Object
      3: {
      4:     .method public hidebysig specialname rtspecialname instance void .ctor() cil managed
      5:     {
      6:         .maxstack 8
      7:         L_0000: ldarg.0 
      8:         L_0001: call instance void [mscorlib]System.Object::.ctor()
      9:         L_0006: ret 
     10:     }
     12:     .method private hidebysig static void Main(string[] args) cil managed
     13:     {
     14:         .entrypoint
     15:         .maxstack 8
     16:         L_0000: nop 
     17:         L_0001: ldstr "Hello World"
     18:         L_0006: call void [mscorlib]System.Console::WriteLine(string)
     19:         L_000b: nop 
     20:         L_000c: ret 
     21:     }
     23: }

    Early and Late Binding

    There are numerous definitions for early and late binding. Some are technical, some are theoretical. I will try to define it from both viewpoints.

    Variables and expressions can be assigned at compile time or at runtime. Compile time (declaration time) assignment is called:

    • early binding
    • static binding
    • static typing

    An example for early binding:

      1: '  Create a variable to hold a new object.
      2: Dim FS As System.IO.FileStream
      3: ' Assign a new object to the variable.
      4: FS = New System.IO.FileStream("C:\tmp.txt", _
      5:     System.IO.FileMode.Open)

    Runtime assignment is called dynamic binding or late binding, when the type of the variable or expression is determined by the current (application) conditions. An example for late binding:

      1: ' To use this example, you must have Microsoft Excel installed on your computer.
      2: ' Compile with Option Strict Off to allow late binding.
      3: Sub TestLateBinding()
      4:     Dim xlApp As Object
      5:     Dim xlBook As Object
      6:     Dim xlSheet As Object
      7:     xlApp = CreateObject("Excel.Application")
      8:     ' Late bind an instance of an Excel workbook.
      9:     xlBook = xlApp.Workbooks.Add
     10:     ' Late bind an instance of an Excel worksheet.
     11:     xlSheet = xlBook.Worksheets(1)
     12:     xlSheet.Activate()
     13:     ' Show the application.
     14:     xlSheet.Application.Visible = True
     15:     ' Place some text in the second row of the sheet.
     16:     xlSheet.Cells(2, 2) = "This is column B row 2"
     17: End Sub

    Another example for late binding:

      1: Dim MyVariable As Object
      2: MyVariable = "About Visual Basic"
      3: Debug.WriteLine("The variable data type is: " & MyVariable.GetType.ToString)
      4: MyVariable = #6/30/2006#
      5: Debug.WriteLine("The variable data type is: " & MyVariable.GetType.ToString)

    The result for the code above:

    The variable data type is: System.String
    The variable data type is: System.DateTime

    As you can see, the variable named MyVariable can represent a System.String and a System.Date in the code above.

    Despite of the advantages of late binding, early binding is recommended:

    • Early binding code can be optimized better by the compiler, so it runs (much) faster
    • It is usually easier to read early binding code (known types, etc.)
    • Automatic code completion, Dynamic Help and other advanced IDE features are available only for early binding codes
    • Compiler can type 'compatibility' for early binding variables and expressions
    • Application constants are accessible (e.g. in MS Word)

    Some advantages of late binding:

    • Version independence. E.g. in case of MS Word, programming against Word 97 and changing code libraries to Word 2000 can be smooth and automatic.
    • More references can mean more linking and bigger file size (in case of unmanaged code)

    There are numerous methods in C# to use late binding. Most of them employs reflection and dynamic compilation. There will be late binding as a language feature from C# 4.0 specification. Late binding will be as simple as the following:

      1: dynamic d = GetDynamicObject();
      2: d.Foo();
    Late binding will be achieved by the dynamic keyword.