,

Extension methods were added in C# 3.0 and are a great way to add commonly used functionality to your projects in an object oriented way that cuts down on repetitive code. While extension methods are an underlying feature of C#, I am going to focus on their use in a view in an ASP.NET MVC project. The same principles apply to using them in any C# code..

I write a lot of ecommerce-related web applications, so I am constantly having to output prices formatted as currency. While I could just use the String.format method directly in a view, I prefer something a little more elegant and less repetitive. By adding a ToCurrency method to the decimal type, I can easily output a formatted string.

Start by adding a new class to your project with its own namespace, for example myproject.Extensions:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace myProject.Extensions
{

 

Add a static class – this class will have methods added to it that will become your extension methods:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace myProject.Extensions
{
    public static class Extensions
    {
    
    }
}

Each static method you add to the class will become an extension method. You tie it to a particular type by using the this keyword and a parameter of the type you want to extend:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace myProject.Extensions
{
    public static class Extensions
    {
        public static string ToCurrency(this decimal amount)
        {

            return String.Format("{0:C}", amount);

        }
    }
}

The ToCurrency method will be added to the decimal type because it is specified as the parameter type and includes the keyword this. I am simply passing the parameter to the String.Format method and returning a formatted string.

Calling the extension method either in other code such as a controller or within a view is simple. You just need to be certain to include the namespace in your class or view with a using statement. This is an example of it in a Razor view:

 

@model myProject.Models.Product
@using myProject.Extensions;

<span>@Model.Price.ToCurrency()</span>

The price property of the Product class is a decimal, so the method is available as if it were part of the underlying type.

You can add extension methods to any class the same way. Another example is providing a formatted address for an address object:

public static string GetFormatted(this Address address)
{
 string a=address.Name+"<br>";

if(address.Company!=null)
{
a+=address.Company+"<br>";
}
a+=address.Address1+"<br>";
if(address.Address2!=null)
{
a+=address.Address2+"<br>";
}
a+=address.City+", "+address.State+" "+address.Zip
return a;

}

Then, within a view, you can easily output a formatted address without having to put all the logic into the view:

@Model myProject.Models.Order
@using myProject.Extensions

<div>
@Model.BillingAddress.GetFormatted()
</div>

Since the BillingAddress property of the Order object is of type Address, the extension method is available as if it were a native part of the class. While you could add the method directly to the underlying class, if you are working with Entity Framework or a class you may not have the source code to, you can extend it without having to modify the original class.

While you could just as easily create a library of functions to call, extension methods provide a more elegant solution to code reuse and providing utility functions. The can even be put into a separate class library project to reuse them between projects.

For more information about Extension methods, see:

http://weblogs.asp.net/dwahlin/archive/2008/01/25/c-3-0-features-extension-methods.aspx
http://csharp.net-tutorials.com/csharp-3.0/extension-methods/

Windows 8 introduces a much improved notification system that allows your applications to notify users in a variety of ways, from local application notifications to push notifications and badges on live tiles.

The simplest type of notification is a toast notification, which is a message that appears temporarily in the corner of the users screen and then fades away. Various applications have used them for notification of events like users signing on or off, messages received, etc. Windows 8 supports them at the OS level, so you can provide consistent notifications in your applications.

The notification system is in the Windows.UI.Notifications namespace, so the first step is to include the namespace in your code:

using Windows.UI.Notifications;

The notification templates are XML documents, so you also need to include the Windows.Data.Xml.Dom namespace:

using Windows.Data.Xml.Dom;

Creating the notification is simple. First, you use the ToastNotificationManager to get a template to work with for your notification. The GetTemplateContent method returns an XML document containing the template of the type you pass to the method as a ToastTemplateType value. In this case, we just need a simple text template, so we will pass it ToastText01:

XmlDocument x = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);

The Xml document that is returned looks like this:

<toast>
    <visual>
        <binding template="ToastText01">
            <text id="1"></text>
        </binding>  
    </visual>
</toast>

Pulling out the <text> element and appending a text node to it will set the text for the notification:

XmlNodeList toastTextElements = x.GetElementsByTagName("text");
toastTextElements[0].AppendChild(x.CreateTextNode("Copied to clipboard."));

Once the text is set, you create a ToastNotification object and pass the XML template to the constructor:

 ToastNotification toast = new ToastNotification(x);

Finally, you call the CreateToastNotifier method of the ToastNotificationManager and pass the ToastNotification object to the Show method to display it:

  ToastNotificationManager.CreateToastNotifier().Show(toast);

That’s all it takes. There are additional templates you can use that include spaces for images and formatted text. For more information on available templates, see http://msdn.microsoft.com/en-us/library/windows/apps/hh761494.aspx 

I often find that sometimes the smallest things that were simple in regular HTML are frustratingly complex in CSS. Take, for example, centering a div. You can float it right, float it left, but there is no center. Using text-align: center does not center it either, it just makes any text inside of it centered.

It turns out it is very simple to do. The key is that you must specify a width for your div, either using an exact pixel width, a percentage, or some other measure like em units. Once you set the width, you just have to add left and right margins set to auto, and the div will be centered inside of the container it is in.

Continue reading

I am in the process of learning iOS development, and the tutorial I am using on the using tab bars was written for Xcode 3. In the tutorial, you add a third tab to the two that are created by default. It instructs you to use the attributes page for the tab bar controller to add another item:

 

Unfortunately, this option is gone in Xcode 4, and the method of adding a new tab is completely different. Here is a step by step demonstration of how to add a Tab Bar Item in Xcode 4.

Hopefully this will help someone who is confused by the change.

While the HTML5 specification apparently won’t be finalized until 2014, you can use one of its more useful new additions, the data attribute, right now with jQuery for easy access to extra data.

When you are creating a dynamic page, you often need to store some additional data on an html element that will be used later when interacting with the page. Right now, developers often use non-existent class names or the rel attribute as a solution, or they add their own attributes, which is not valid HTML.

For example:

<img src="picture.jpg" largeimage="picturelarge.jpg">


<li rel="menu1">Menu item</li>

Browsers just ignore attributes they don’t support, so it has no negative effect. While this works, it is not the most elegant solution and is not valid HTML.


HTML5 introduces the data attribute to html elements. You can add multiple data attributes to an element. It works differently than other html attributes. The attribute begins with data, then has a dash and the name of the data item.

Example:

<img id="pic" src="picture.jpg" data-large="picturelarge.jpg"

data-productid="52" data-license="creative commons">

The img tag has three data attributes – large, productid and license. These can be accessed by getting the attribute, or by using the element’s dataset object. Each data attribute becomes a named property of the dataset object:

 
el.dataset.productid

Unfortunately, that method is not useable right now because of lack of browser support for the dataset object.
 
The solution is to use jQuery 1.43 or later, which has full support for the data attributes through the data() method. It does not rely on the dataset object, so it is compatible with non-HTML5 browsers.
 
Using the img example above, you can access the values of the data attributes like this:

$('#pic').data('productid') // 52


$('#pic').data('large') // picturelarge.jpg

While you could have just used the attr() to retrieve the value using the full attribute name ("data-productid"), the data() method is more elegant and readable, and has enhanced functionality. It can handle json encoded attributes, for example:

<li id='line1' data-options='{"color":"black","interior":"gray"}'>


Aston Martin</li>

The options attribute is automatically parsed by the data() method into named properties:

$('#line1').data("options").color //black


$('#line1').data("options").interior //gray

Data can also be added through code to an element with the data() method. It also has an event model that can be attached to for processing when data is read or set. For more info on data(), see the jQuery documentation on it.

jQuery provides an excellent way to start using HTML5 now without having to wait until browsers catch up.

 

 
 

When working with a table of data, it is helpful to add some type of highlight to the row to indicate the current row. This is extremely easy to do with a few lines of code in jQuery.

I have a table that has rows with two editable text boxes in them. When one of the text boxes receives focus, the row it is in becomes highlighted. When exiting, the row is no longer highlighted.

I have created a CSS class called highlight that adds a light yellow background:

.highlight { background:#FFFFCC;}

The table is just standard <tr>, <td> and <input> tags. The <input> tags do not have event handlers specified as attributes, they will be added in code.

The code is very simple. Two event handlers are added to all input textboxes, one for focus and one for blur. In the focus, the highlight class is added to the parent <tr> tag of selected texbox. On blur, the class is removed. I used the closest() function, which finds the closest element. It’s a shortcut to using .parent().parent() to get to the <tr> tag of the current row:

$('input').focus(function() {
 $(this).closest('tr').addClass('highlight');
});
 
$('input').blur(function() {
 $(this).closest('tr').removeClass('highlight');
});

 

The event handlers are added to all <input> tags. You will want to get more specific with the selector if you need to narrow down which elements cause highlighting. In the context of the event handler function, $(this) refers to the element that fired the event (the textbox).

That’s it. With a little CSS and jQuery, the table becomes more usable.

Working example

I am currently working on a project for a client that involves updating an existing legacy ASP application to make it easier to use, but I am not yet able to completely replace the entire application. Wherever possible, I have been getting around limitations by adding in AJAX code to pages to make them more interactive using jQuery.

As example is an order list in the back end administration section. It has a column with a checkbox next to the order id, and a column with a dropdown list of status codes (with the current status for each order selected), along with the rest of the basic order information.

In order to update the status of an order, you have to check the box next to the order #, select the new status, and the click on an Update Status button at the bottom of the page to post the page back and save the changes. It works, but it is clunky and annoying when you have a lot of orders to update. Also, you could easily forget to check an order or to click on update to save your changes.

Ideally, the order status should update immediately after selecting the new status, without any other steps. Using the onchange handler on the dropdown list, along with jQuery’s post() function, I can do just that with an ajax request to a separate page to handle to status update.

Continue reading

One common design problem is how to display a large amount of content on a page and still make it easily accessible. Often times, a table of contents is used at the top with links within the same page to sections below. This gets pretty unwieldy if you have a lot of content, and splitting it up into multiple pages can be annoying and hard to navigate.

An easy and elegant alternative is to use a dropdown list with content panels made of individual divs. The dropdown acts as the table of contents, and each time a selection is made, only that panel is displayed.

Example:

contentpanel

With a little bit of jQuery and CSS, it’s very simple to create this kind of ui.

Continue reading

A common need in a web application is to open a separate window to display some information or get input. As most modern browsers have popup blockers, it is difficult to use window.open reliably, and it also detracts from the user experience.

A better solution is to have a modal dialog that pops up within the same page over the current content. You see this very commonly on sites, and it is extremely easy to achieve with jQuery UI,  a library that adds rich UI elements to jQuery, such as dialog boxes, date and color pickers, buttons, sliders, and tabs.

Continue reading