Wednesday, August 14, 2013

Lambda Expressions

A function can be sent as a parameter to another sub procedure or function.

For example:

    <Extension>
    Public Iterator Function Filter(aBookEnum As IEnumerable(Of Book), selector As Func(Of Book, Boolean)) As IEnumerable(Of Book)
        For Each thisBook As Book In aBookEnum
            If selector(thisBook) Then
                Yield thisBook
            End If
        Next
    End Function

The selector parameter is defined with the Func type.  This means that a function must be passed in with a return type of boolean and takes a parameter of type Book.

So when we call the Filter extension method, can do the following:

Let's say you have a function that meets the criteria for the parameter:

    Function GetBookOne(myBook As Book) As Boolean
        Return myBook.Title = "Book One"
    End Function

You could send this function as a parameter like this:

Dim MySelector As Func(Of Book, Boolean) = AddressOf GetBookOne
MyBookShelf.Filter(MySelector)

Or you could use a lambda expression and seriously streamline your code like this:

MyBookShelf.Filter(Function(x) x.Title = "Book One")

So, "x" represents the Book input parameter.

Tuesday, August 13, 2013

What is IEnumerable(Of T)?

IEnumerable is the base interface for all generic collections that can be enumerated (iterated through).  Examples of classes that implement IEnumerable include Lists, Arrays, Stacks, and Queues.  You can also write your own classes that implement it.  Any class that implements this interface can have LINQ queries performed on its enumerator.  You can also iterate through the collection using the For Each operator.  T is the type of item that the collection stores.  When you perform LINQ queries, you often get anonymous classes that implement the IEnumerable interface in return.

The System.Linq namespace contains all kinds of extension methods that operate on classes that implement the IEnumerable interface.  This is what allows you to write LINQ queries against these objects.

Use Syntax Highlighter to display code in your Blogger posts

Edit the HTML of your blogger template.  From your blog dashboard, click Template on the left side, and then click the Edit HTML button.  Add the following to the head section.

    <link href='http://alexgorbatchev.com/pub/sh/current/styles/shCore.css' rel='stylesheet' type='text/css'/>
    <link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeEclipse.css' rel='stylesheet' type='text/css'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJScript.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushVb.js' type='text/javascript'/>
    <script language='javascript' type='text/javascript'>
    SyntaxHighlighter.config.bloggerMode = true;
    SyntaxHighlighter.all();
    </script>

This example is set up for JavaScript, XML, and VB, but you can find other "brushes" here:

http://alexgorbatchev.com/SyntaxHighlighter/manual/brushes/

Switching to HTML when writing your post, if you wanted to demonstrate a bit of HTML, you do this:

<pre class="brush:xml;">
    &lt;script src="StevesJScript.js" type="text/javascript"&gt;&lt;/script&gt;
</pre>

Note that I had to escape the angle brackets with the &lt; and &gt;.

Symmetric and Asymmetric Encryption (and SSL)

Symmetric encryption requires one shared private key.  This same key is used by Person A to encrypt the message and by Person B to decrypt the message.  They can go back and forth all day long using the same key.  It's great and it's private.  However, the problem is getting the key to the other person.  Physically giving the key to the other person is great, but obviously not practical for an internet situation.

Asymmetric encryption is another technique.  Asymmetric means one-way.  It is another means of encrypting a message, but it can only occur in one direction.  Person A can encrypt a message that only Person B can decrypt.  How?  Mathematics.  You don't really need to understand the cryptography details to understand this.  Person B has a private key.  Mathematically, Person B can derive a public key from this private key.  Due to the miracle of modern math, this "public" key can be used to encrypt a message, but not decrypt the message.  Person B can give this public key out to anyone that he wants to receive a secure message from and only Person B will be able to decrypt the message.  So Person B sends Person A the public key.  Person A encrypts his message using the public key, and sends it to Person B who decrypts the message using the private key.  The big breakthrough here is that a private key never has to be given out.

How are these two methods used?  SSL.  A combination of these two methods is used to establish a secure browsing session.  The web server has a certificate installed that contains the private key.  When average Joe points his browser to the web site, the server will generate a certificate that contains the public key derived from this private key and send it to the browser.  The browser generates something called a "session key" (AKA shared private key ), and sends this to the web server using the public key in the certificate.  Now, the web server and the browser both know the session key (AKA shared private key) and can begin communicating both ways using symmetric encryption.

To summarize, the shared private key is securely given to the web server by using asymmetric encryption.  Once the shared private key is in both party's hands, symmetric encryption can commence.

Tuesday, July 23, 2013

Call a WCF web service using jQuery

First, add an AJAX-enabled WCF Service to your project.  There is a Visual Studio template for this.  Add a web method like the following:

    <OperationContract(), WebGet()>
    Public Function GetFood(inputId As String) As Food()
        Dim ReturnFood As New List(Of Food)
        If inputId = 1 Then
            ReturnFood.Add(New Food With {.Id = "1", .Name = "Bananas", .Color = "Yellow"})
        ElseIf inputId = 2 Then
            ReturnFood.Add(New Food With {.Id = "2", .Name = "Apples", .Color = "Red"})
        Else
            ReturnFood.Add(New Food With {.Id = "1", .Name = "Bananas", .Color = "Yellow"})
            ReturnFood.Add(New Food With {.Id = "2", .Name = "Apples", .Color = "Red"})
        End If
        Return ReturnFood.ToArray
    End Function

Notice the WebGet attribute.  This allows your web method to be called using a GET operation.  Very important.  Won't work without this.  What this means is if you browse to http://yourserver/AjaxGetResultsService.svc/GetFood, you will get Json back in return.

Also notice that I'm returning an array of Food which is a class I made up.  The .net framework will automatically turn this into Json for you.

So, if you had a button with an id of buttonPopulateFood, the following jQuery code would call this method and display the results.

    $("#buttonPopulateFood").click(function () {
        $.ajax({
            url: "AjaxGetResultsService.svc/GetFood",
            type: "GET",
            dataType: "json",
            data: {
                inputId: "1"
            },
            success: function (json) {
                displayJson(json);
            },
            error: function () { alert("You have failed.") }
        });
    });

Here is the displayJson function I'm calling.  I'm using the each function to iterate through the json array.

function displayJson(jsonData) {
    $.each(jsonData.d, function (index, value) {
        $("#food").append(index + ": " + value.Name + ", ");
    });
};

jQuery Basics

JavaScript

JavaScript is a programming language that runs inside a browser.  Because it runs inside a browser, it runs on the user's machine instead of on the web server.  JavaScript code will respond much quicker to events like button clicks than code that runs on the server.  JavaScript also uses a technology known as AJAX to call server code without a time consuming post back.  Incorporating more JavaScript into your web site can speed up and improve the user experience.  However, JavaScript is ugly.  You sometimes have to jump through a lot of hoops to do simple things, including AJAX calls.

jQuery

jQuery is simply a JavaScript library.  It is literally just one file that you download at jquery.com.  It's free and open source (you can't compile JavaScript anyway).  The library contains a bunch of functions that you can call.  The functions do pretty much everything you would want to do with JavaScript, so every line of code you write is just a call to a jQuery function.

To use jQuery, you just need to reference the jQuery library with a line like the following in the head tag of your html page:

    <script type="text/javascript" src="jquery-1.10.2.js"></script>  

You should definitely keep your own JavaScript in a separate file as well:

    <script src="StevesJScript.js" type="text/javascript"></script>

Let's dive into an example to demonstrate how this all works.

Clicking buttons

First, add a text box, a few buttons, and a paragraph to display some results to your page:

   <input type="text" id="textBoxNumber" />  
   <button id="buttonPressMe">Press Me</button>  
   <button id="buttonClear">Clear</button>  
   <p id="results">results</p>

Instead of setting the event attribute on the actual tag, you can associate a click event in your JavaScript file by calling a jQuery function.  This almost feels like a "code-behind" page like you see with ASP WebForms.

$(document).ready(function () {

    $("#buttonPressMe").click(function () {
        $("#results").text($("#textBoxNumber").val())
    });

    $("#buttonClear").click(function () {
        $("#textBoxNumber").val("");
    });

});

The $ function selects an element.  In this case, we select the whole document.  Then we call the ready function for that element.  So this means, after the document loads, whatever is sent to the ready function will execute.  You can see we have selected both buttons by id (using the # symbol) and have called the click function which specifies what to execute when the selected button is clicked.  Here I am simply displaying the contents of the text box and clearing out the text box.

Tuesday, July 9, 2013

"Unable to Start Debugging on the Web Server" error when hosting your web application on your local IIS

It works fine when you host your project using the Visual Studio Development Server, but when you choose IIS, you get this error.  Try the following from a command prompt:

%SystemRoot%\Microsoft.NET\Framework64\{version number goes here}\aspnet_regiis -i

I think this happens when IIS doesn't recognize the version of the .net framework that you are running.  So this might happen when you install a Service Pack for instance.  Anyway, this line of code makes the version known to IIS.  Keep in mind that if you are running version 3.5 that you find this aspnet_regiis executable in the folder for version 2.0.  3.5 shares a common CLR with 2.0.