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.


Enable the Usage Summary page in SharePoint

The Usage Summary page is an administrative page that is useful for monitoring the size of the content database.  Normally,it is available from Site Settings on the parent site of a site collection.  However, if it does not show up, you probably need to enable usage logging by performing the following:


  1. Central Admin
  2. Operations
  3. Under Logging and Reporting, click "Usage analysis processing"
  4. Check "Enable logging" and "Enable usage analysis processing"
  5. OK

LinkButton redirect to a page in a new browser window

Let's say you have a LinkButton control.  If you do a Response.Redirect in the code behind, the page will be opened in the same browser window.  But what if you want the page to open in a new browser window?  Unfortunately, Response.Redirect can't do this.  Javascript on the client or a plain html hyperlink (with target="_blank") is the only way to do this.  The simplest way to do this is to set the OnClientClick code to execute some javascript to make this happen.  Like this:

LinkButton1.OnClientClick = "window.open('http://www.blogger.com', '_blank')"

Then, when the user clicks the button, the javascript will open the link in the new window.  (The server side click event will also fire)

Javascript and ASP.NET

Many ASP.NET server controls provide a property or two for specifying javascript to execute.  For example, a Button control will expose a OnClientClick property where you can specify javascript.  A CustomValidator control exposes a ClientValidationFunction where you can specify a javascript function.

The first thing you need to do is write the javascript function.  The javascript must be enclosed in <script> tags, and can be placed anywhere in the markup.  For example:

<script type="text/javascript">
     function SayHello() {
          alert('Hello');
     }
</script>

Now, you can refer to this function in those properties.  You can set these properties in either the markup or the code-behind.  For example in code-behind, you could write:

Button1.OnClientClick = "SayHello()"

Or, if your javascript is just a one or two liner, you could put the lines of code directly into the property like this:

Button1.OnClientClick = "alert('Hello')"

Sometimes, a server control will not expose a property to execute the script when you want it to.  For example, let's say you want javascript to execute when you change the value of a TextBox control.  A TextBox control will actually render as an html input tag.  The input tag has an attribute of "onchange" which is part of a group of attributes called "intrinsic events".  We can actually stick some javascript in these events with the following code:

TextBox1.Attributes.Add("onchange", "SayHello()")

Now when the TextBox's contents are changed and user tabs off, your script will execute.

One final note.  There is no way to directly call a javascript function from your code behind.  However, by using the above methods, and "injecting" the javascript at run-time, you can effectively accomplish this.