Archive Page 2

jQuery Tab View using AJAX and WCF REST Service

In response to a question on StackOverflow Master Details using jQuery Tabs I wrote little sample app to demonstrate using jQuery Tabs and a WCF REST Service to create a Master Details view of Orders. I decided I’d also reference the solution here and give a little bit of an overview of how the Sample works.

Download

Sample Project: jQuery-AjaxTabView-Sample.zip (194KB)

Default.aspx

The Default page is basically a UI Tab setup with a ListView on the first tab.  The ListView contains a table of Orders with a simple Select link.  Notice that the select button is not an asp hyperlink control.  If you don’t need the extra code-behind or rendering of the user control I avoid them.  But, back to the Default Page.  On the second tab I have to layers one for loading and one for results.  The results tab is preloaded with the default message of Select an order.

The other major function of the page is in the jQuery Scripting, but I’ll get into that later.  First let me explain the service.

WCF Orders Service

With the release of the WCF REST Starter Kit its become very simple to create a service that returns some simple JSON results.   In this sample I have a single service called Service.svc (OrderService might have been a better name, next time…).  The service has a standard WebServiceHost2 Factory definition (which you can view by opening the actual Service.svc file) and a single Service.svc.cs code-behind.  The Service contains two methods one to return all Orders and one to return a single Order’s Details

[ServiceContract]
[ServiceBehavior(IncludeExceptionDetailInFaults = true, InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class OrderDetailsService
{
    [OperationContract]
    [WebGet(UriTemplate = "", ResponseFormat = WebMessageFormat.Json)]
    public IEnumerable GetOrders()
    {
        // todo: replace with real implementation
        return Order.GetStubData();
    }

    [OperationContract]
    [WebGet(UriTemplate = "{orderId}", ResponseFormat = WebMessageFormat.Json)]
    public List GetOrderDetails(string orderId)
    {
        // todo: replace with real implementation
        var orders = Order.GetStubData();

        // todo: handle bad orderIds
        var order = orders.FirstOrDefault(o => o.OrderId == int.Parse(orderId));

        if (order == null)
            return null;

        return order.Details;
    }
}

You can access http://localhost:{port}/Service.svc to get the Orders as a JSON list, or you can access http://localhost:{port}/Service.svc/1 to get the OrderDetails as a JSON list for Order #1.

jQuery Scripts

Now that you have the WCF Service setup you need to have jquery connect to the service and render the data out when it receives the results.  The basic steps are that occur when the Select button is clicked are:

  1. Call preventDefault to stop the link
  2. Update the Tab2 UI to Loading
  3. Select Tab 2
  4. Parse the OrderId from the Hash of the link
  5. call jQuery $.getJSON(‘Service.svc/{orderId}’, null, function(json) {  } );

When the you return from the getJSON call you need to:

  1. Check to determine that you got valid results
  2. Set error message if necessary
  3. Generate table of results
  4. Loop results creating a row for each result
  5. Reset UI to hide loading and show results

Now on to the actual script that handles this.  Keep in mind that all this code is inside a $(document).ready(), for the full implementation download the sample project.

$('.selectOrder').click(function(e) {
    e.preventDefault();

    //setup loading ui
    $('#tabs').tabs('select', 1);
    $('#tabs-2 .loading').show();
    $('#tabs-2 .results').hide().empty();

    var id = this.hash.replace("#Select_", "")

    $.getJSON("Service.svc/" + id, null, function(details) {
        details.length = details.length ? details.length : 0;
        if (details.length == 0) {
            $('#tabs-2 .results').append('<h3>No Order Details</h3>').show();
        }
        else {
            var table = $('<table />').attr('cellspacing', 0).attr('cellpadding', 4);

            var header = $(<tr />')
                .appendCell("Product")
                .appendCell("Quantity")
                .appendCell("Price")
                .appendCell("Cost")
                .addClass('header');
            table.append(header);

            $.each(details, function() {
                var row = $('<tr />')
                    .appendCell(this.Product)
                    .appendCell(this.Quantity)
                    .appendCell(this.Price)
                    .appendCell(this.Quantity*this.Price);
                table.append(row);
            });

            $('#tabs-2 .results').append(table).show();
        }

        $('#tabs-2 .loading').hide();
    });
});

Conculsion

I hope that you like this sample.  As with any full AJAX solution the real complication comes into play when we start trying to customize the design.  That being said I would recommend putting as much of the design into the css as possible and avoid putting to many styles in the javascript. 

Other things to note, this doesn’t work cross domain, in order to do cross-domain json you need to use jsonp (JSON with Padding).   JSONP can be accomplished through the use of WCF Extensions which is not covered in this article, for more information see this msdn article and this msdn forum post.  jQuery supports jsonp; you would change the getJSON call to $.getJSON(‘Service.svc/1?callback=?’), where callback is the name of the querystring parameter expected by the service, and jquery would recongnize the callback=? and handle all the dirty work for you.  Finally, there is no exception handling in this code.  I just set the length to 0 if I don’t find one.  WCF will actually return the Exception message in the json response.  The next iteration of this project would be to include exception handling in the results callback. 

Happy coding.

Very Simple Javascript State Matching

I created this simple little javascript state matching library and I was amazed at how simple it turned out being, so I had to post it.

I’m leveraging a javascript object as a Key/Value Pair lookup.

stateMatcher.js


var stateMatcher = {
    Names: { "":"", "ALASKA": "AK", "ALABAMA": "AL", "ARKANSAS": "AR", "ARIZONA": "AZ", "CALIFORNIA": "CA", "COLORADO": "CO", "CONNECTICUT": "CT", "DISTRICT OF COLUMBIA": "DC", "DELAWARE": "DE", "FLORIDA": "FL", "GEORGIA": "GA", "GUAM": "GU", "HAWAII": "HI", "IOWA": "IA", "IDAHO": "ID", "ILLINOIS": "IL", "INDIANA": "IN", "KANSAS": "KS", "KENTUCKY": "KY", "LOUISIANA": "LA", "MASSACHUSETTS": "MA", "MARYLAND": "MD", "MAINE": "ME", "MICHIGAN": "MI", "MINNESOTA": "MN", "MISSOURI": "MO", "MISSISSIPPI": "MS", "MONTANA": "MT", "NORTH CAROLINA": "NC", "NORTH DAKOTA": "ND", "NEBRASKA": "NE", "NEW HAMPSHIRE": "NH", "NEW JERSEY": "NJ", "NEW MEXICO": "NM", "NEVADA": "NV", "NEW YORK": "NY", "OHIO": "OH", "OKLAHOMA": "OK", "OREGON": "OR", "PENNSYLVANIA": "PA", "PUERTO RICO": "PR", "RHODE ISLAND": "RI", "SOUTH CAROLINA": "SC", "SOUTH DAKOTA": "SD", "TENNESSEE": "TN", "TEXAS": "TX", "UTAH": "UT", "VIRGINIA": "VA", "VERMONT": "VT", "WASHINGTON": "WA", "WISCONSIN": "WI", "WEST VIRGINIA": "WV", "WYOMING": "WY" },
    Abbreviations: { "": "", "AK": "Alaska", "AL": "Alabama", "AR": "Arkansas", "AZ": "Arizona", "CA": "California", "CO": "Colorado", "CT": "Connecticut", "DC": "DistrictofColumbia", "DE": "Delaware", "FL": "Florida", "GA": "Georgia", "GU": "Guam", "HI": "Hawaii", "IA": "Iowa", "ID": "Idaho", "IL": "Illinois", "IN": "Indiana", "KS": "Kansas", "KY": "Kentucky", "LA": "Louisiana", "MA": "Massachusetts", "MD": "Maryland", "ME": "Maine", "MI": "Michigan", "MN": "Minnesota", "MO": "Missouri", "MS": "Mississippi", "MT": "Montana", "NC": "NorthCarolina", "ND": "NorthDakota", "NE": "Nebraska", "NH": "NewHampshire", "NJ": "NewJersey", "NM": "NewMexico", "NV": "Nevada", "NY": "NewYork", "OH": "Ohio", "OK": "Oklahoma", "OR": "Oregon", "PA": "Pennsylvania", "PR": "PuertoRico", "RI": "RhodeIsland", "SC": "SouthCarolina", "SD": "SouthDakota", "TN": "Tennessee", "TX": "Texas", "UT": "Utah", "VA": "Virginia", "VT": "Vermont", "WA": "Washington", "WI": "Wisconsin", "WV": "WestVirginia", "WY": "Wyoming" }
};

Usage


var longName = stateMatcher.Abbreviations["NY"];
// or
var abbr = stateMatcher.Names["New York".toUpperCase()];

I just love how simple it is. I feel like I’m calling a function, but I’m not.

jQuery FormatCurrency Plugin

This plugin has been made obselete.
Please use the latest release available on google code at http://jquery-formatcurrency.googlecode.com

Hey all, its been a while since my last post.  This just a simple little format currency plugin that I built a while back.  Hope everyone enjoys it.

About the Plugin

The plugin, called the FormatCurrency Plugin, requires the jQuery core file and a single javascript file, jquery.formatCurrency.js. A demo is available on my prorfolio website. The plugin was designed with the following features.

  • Formats the selector’s value to a formatted version of the currency.

Options

useHtml – if true this value uses the html() attribute to get and set the value for the currency, otherwise the plugin will use the val() attribute.  The default is false.

symbol – The dollar sign to be used when formatting the currency. The default is $.

Downloads

This plugin has been made obselete.
Please use the latest release available on google code at http://jquery-formatcurrency.googlecode.com

jQuery Core (plugin built on jquery-1.2.6.js)

jquery.formatCurrency.js

jQueryFormatCurrencySample.zip

Using the Plugin

In order to use this plugin create an html page and attached the jQuery core javascript file and the jquery.formatCurrency.js file.  In this example I will be formatting the currency on a button click.  Although another popular formatting technique would be to set the currency on lost focus (the sample download and demo contain both options).

Html

<div class="sample">
<h3>Formatting Using Button Click</h3>
<input type="textbox" id="currencyField" value="$1,220.00" />
     <input type="button" id="currencyButton" value="Convert" /></div>

Javascript

    $(document).ready(function()
    {
        $('#currencyButton').click(function()
        {
            $('#currencyField').formatCurrency();
        });
    });

Known Issues

At the moment their are no known issues.  The plugin has been tested successfully in Windows IE 8 Beta, Mozilla, and Google Chrome.

Welcome, Mia Claire Dewey (10/5/2008)

We were blessed with a beautiful baby girl this past weekend.  Life will be changing drastically in the next few weeks.  I’d like to thank my wife Kelly, who is a terrific woman and will make a great mom.

WPF Shadowed TextBox (aka. WPF Watermark TextBox)

This article demonstrates a Shadowed TextBox in WPF.  The initial concept seemed like it would be easy.  I went through about 3 different iterations in order to tackle this situation.  The first two had potential, but both had odd issues that forced me to try different techniques.  The winning solution uses an adorner to decorate the Textbox with a label.

Failed Techniques

Change the Text and Style on Got/Lost Focus

In this technique I would just  change the Text of the Textbox and and the Style whenever the TextBox Got or Lost Focus.  I had used this technique previously in WinForms, but this App that I was building used Drag-and-Drop in the textboxes and the users had expressed the need for this feature.  The issues with Drag-and-Drop using this technique were a nightmare.  This on top of other issues such as Binding caused be to abandon this technique.

Changing the Textboxes Background to a VisualBrush with with a Label

In this technique I would change the background of the TextBox to a VisualBrush that contained a Label on Got/Lost Focus.  This method had some initial pitfalls and work arounds with sizing.  I finally got past that by setting the VisualBrush Stretch=None.  This technique worked great until I went to my DataBound Form.  If a textbox has a value with one record, when you changed records that textboxes background wouldn’t update.  I searched a long time for a method to override to force that update, but no luck.

Winning Technique

Textbox adorned by a Label

View Code Preview:  ShadowedTextBox.cs
Download Source Code: ShadowedTextBoxExample.zip (70.3 KB)

Shadowed TextBox Preview
Shadowed TextBox Preview

This final technique worked great and involves creating and attaching an AdornerLabel to the TextBox.  This version worked with styling, drag-drop, and Binding, right out of the box.  All you need to do to get the Shadowed TextBox working is add the required files and set the Label and LabelStyle of the ShadowedTextBox.

jQuery RollOver Image Link Plugin

After listening to the .NET Rocks segment with Rick Strahl, I instantly found areas of my current project that could utilize jQuery. At the time I was building a forms control that utilized a LayoutTemplate and a DataPager similar to the new ListView Control. I decided to rewrite my rollover images using jQuery and found 3 main advantages in this project alone.

  • Almost half the code in JavaScript and C#
  • Allowed me to fade the images on rollover without having to write custom fading javascript.
  • I could use css style selectors instead of capturing and registering the controls ClientID on PreRender.

About the Plugin

The plugin, called the RollOverImageLink Plugin, requires the jQuery core file and a single javascript file, jquery.rollOverImageLink.js. A demo is available on my prorfolio website. The plugin was designed with the following features.

  • Images are all preloaded.
  • Fading in/out of the OverImage on rollover
  • Disabled Image when image is in disabled state

Downloads

jQuery Core (plugin built on jquery-1.2.6.js)

jquery.rollOverImageLink.js

jQueryRolloverImageSample.zip

Using the Plugin

In order to use this plugin create an html page and attached the jQuery core javascript file and the jquery.rollOverImageLink.js file. The rollover image link is constructed with one hyperlink and 3 images.

<a href="#" title="Back" class="rollOverImageLink" disabled="disabled"><img
  src="images/back_over.png" class="overImage" /><img
  src="images/back.png" class="baseImage" /><img
  src="images/back_disabled.png" class="disabledImage" /></a>

<a href="#" title="Next" class="rollOverImageLink"><img
  src="images/next_over.png" class="overImage" /><img
  src="images/next.png" class="baseImage" /><img
  src="images/next_disabled.png" class="disabledImage" /></a>

You will also need the following CSS code to set the initial state of the images

.rollOverImageLink img {
  border:0px; }

.rollOverImageLink .overImage, .rollOverImageLink .disabledImage {
  display:none; }

.rollOverImageLink .overImage {
  position:absolute; }

Known Issues

Below is a list of known issues with this plugin. Please post any thoughts or solutions to these issues in the comments section

  • Requires the overloaded disabled and enabled selectors to work with Firefox
  • Queues a fade loop when a user repeatedly hovers over and off of the link. I tried using the stop method on the animation, but it was stopping the fade feature for the remaining lifecycle of the page.
  • Disabled Images are set in the document ready state. Dynamically changing the disabled state of the link won’t change the image. In theory if its only loading the disabled image from load you would really need to preload the remaining images, but I plan to add this feature in future versions.
  • Disabled Images are set in the document ready state. Dynamically changing the disabled state of the link won’t change the image. In theory if its only loading the disabled image from load you would really need to preload the remaining images, but I plan to add this feature in future versions.

NativeFileTypeViewer : FileIconImageConverter – Convert a filename to the file system icon.

I’ve recently been creating more desktop applications and I often needed to print out the system icons for standard files.  In the past I had used Photoshop to crop out the icons and I ended up only supportting a limited number of file icons.  And as I was writing this post I also found a shell32 tatic  used to create ImageLists in WinForms.

In order to load the system file icons and descriptions for my WPF applications, I built this Binding Converter.  The FileIconImageConverter.cs file is an IValueConverter that accepts  a filename or full file path.  The Converter supports caching and both 32-pixel and 16-pixel icons.  With the exception of the cache checking functionality, this converter has 4 main parts. First it creates a blank 0kb text file the the same extension as the source filename.  Second it loads a SHFILEINFO Struct using Win32.SHGetFileInfo and creates an Icon from the handle. Third it creates Bitmap from the Icon and saves it to a MemoryStream as a PNG.  Finally it loads the ImageSource using a PngBitmapDecoder from the previous Memory Stream.

I would love to give credit to Atul Gupta’s Blog, which help me out a lot with this.  I haven’t tried it in Silverlight, please let me know if you try it.  Please see my website for the full code.

http://www.bendewey.com/code/FilenameIconImageConverter.html

This little application, called the NativeFileTypeViewer (source code), loads a directory and converts the filenames into the filename descriptions and the file icon, to demonstrate the use of the binding converters.

Native FileType Viewer

Swoosh Button

I created this little swoosh button, as I call it, as my main button design for most of my apps. There are three colors for now but it can easily be adapted to support multiple more. There is a standard blue color, a red color (i used for the cancel buttons), and a green color (I used for the OK and Next Buttons) . I also think the button looks really good with all caps text.

I keep trying to come up with a good way to pass the color in without creating a custom control. If anyone has any thought please feel free to share.

Enjoy

SwooshButtonBlueSwoosh

Usage

<Button Width=”60″ x:Name=”browse” Style=”{StaticResource SwooshButton}”>Browse</Button>

Code

http://www.bendewey.name/code/swooshButton.html

My First Blog Post

I’m Ben Dewey, this is my first blog post.  I am hoping to post code samples and discussions on cool .NET controls.  I will be posting code in my free time which is fairly limited. 

My brother is a big open source guy and this blog is going to be my contribution to the open source world.  WPF has some great features that allow programmers to reuse control templates.  If I can save some other programmers time and effort than I’ll be happy.

Comments are always welcome.  I’ll try to respond as quickly as possible, but please be patient.

« Previous Page


What else am I doing?

StackOverflow Facebook Twitter LinkedIn Live

Twitter

Pages

 

November 2009
M T W T F S S
« Aug    
 1
2345678
9101112131415
16171819202122
23242526272829
30