Archive for category Programming

Using HTML 5 data attributes with ASP.NET MVC

HTML 5 data attributes are a way to store data on a DOM element. Check out the spec for more information. For example we have a list of users and want to store the id of the user on the client side for later use. Here is a sample markup.

<ul>
    <li data-id=”4” data-role=”admin”>thorsteinsson</li>
    <li data-id=”23” data-role=”user”>john</li>
</ul>

On the server side we have a class for the user.

public class User
{
    public int Id { get; set; }
    public string Role { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
}

To make it more simple to make these data attributes, I made a extension method for HtmlHelper.

<ul>
    <% foreach (var user in Model.Users) { %>
    <li <%= Html.ToDataAttributes(user) %>><%=user.Username%></li>
    <% } %>
</ul>

If we don’t want to write the username and password to the markup we can choose to skip it.

<%= Html.ToDataAttributes(user, new { “Username”, “Password” }) %>

Here is the complete code for this extension method.

    public static string ToDataAttributes(this HtmlHelper helper, object obj)
    {
        return helper.ToDataAttributes(obj, new string[] {});
    }

    public static string ToDataAttributes(this HtmlHelper helper, object obj, IEnumerable<string> skip)
    {
        StringBuilder builder = new StringBuilder();
        Type t = obj.GetType();
        foreach (var field in t.GetProperties())
        {
            if (skip.Contains(field.Name)) continue; 

            var value = field.GetValue(obj, null);
            if (value != null)
            {
                builder.Append(" data-").Append(field.Name.ToLower()).Append("=\"").Append(helper.AttributeEncode(value)).Append("\"");
            }
        }
        return builder.ToString();
    }

View Comments

Minify JS and CSS in Embedded Resources

At work we have a control library that contains js and css files as embedded resource. This library is consumed by different web projects. By minifying those files we can make our webpage perform faster as the browser does not need to download as large files.

We use YUI Compressor at work for minification, but it can be replaced by any other minification tool such as the Microsoft Ajax Minifier.

We need to add a task in the bottom of out .csproj file that runs before resource generation, that’s why we use task name BeforeResGen.

<UsingTask TaskName="CompressorTask" AssemblyFile="..\..\..\lib\Yahoo\Yahoo.Yui.Compressor.dll" />
<Target Name="BeforeResGen">
  <Copy SourceFiles="@(EmbeddedResource)" DestinationFolder="$(IntermediateOutputPath)" Condition="'%(Extension)'=='.js' or '%(Extension)'=='.css'">
    <Output TaskParameter="DestinationFiles" ItemName="Resources" />
  </Copy>

  <CompressorTask
         Condition="'%(Resources.Identity)' != '' and '%(Extension)'=='.js'"
         JavaScriptFiles="%(Resources.Identity)"
         ObfuscateJavaScript="True"
         PreserveAllSemicolons="True"
         DisableOptimizations="False"
         EncodingType="Default"
         DeleteJavaScriptFiles="False"
         JavaScriptOutputFile="%(Resources.Identity)"
         LoggingType="None" />
  <CompressorTask
         Condition="'%(Resources.Identity)' != '' and '%(Extension)'=='.css'"
         CssFiles="%(Resources.Identity)"
         DeleteCssFiles="False"
         CssOutputFile="%(Resources.Identity)"
         CssCompressionType="YuiStockCompression"
         EncodingType="Default"
         LoggingType="None" />

  <ItemGroup>
    <EmbeddedResource Remove="@(EmbeddedResource)" Condition="'%(Extension)'=='.js' or '%(Extension)'=='.css'" />
    <EmbeddedResource Include="@(Resources)" />
    <FileWrites Include="@(Resources)" />
  </ItemGroup>
</Target>

We start off by copying all js and css files from the embedded resource to the obj folder (IntermediateOutputPath) and then we minify all the files and add them back as embedded resources.

This task needs to be in the csproj file and can not be in tfsbuild.proj file because it does not have the BeforeResGen task.

View Comments

Presentations

I had two presentations last Friday. The first one was at work and I talked about my trip to Mix10 in Las Vegas. It was my first time using the Prezi presentation tool. The title of the presentation was “Client-side web development”, that was my focus at Mix10. I talked about the keynotes, HTML 5, SVG, IE 9, jQuery and Reactive Extensions for JavaScript.

My second presentation on Friday was about jQuery. I went to an insurance company here in Iceland and introduced their web department to jQuery. I used slides from John Resig, the creator of jQuery. I decided to post link to the slides here:

I loved to see the big interest in jQuery and hope that the presentations where useful for the attendees.

View Comments

Should you use HTML 5 today?

This is a difficult question and depends on your circumstances. You can definitely use the features that have a backwards compatibility in older browsers. For example the input type for email and url fall back to a normal textbox. However if you want to use the native date picker you have to detect that feature with javascript and fall back to a javascript based date picker for older browsers.

I have been using the canvas element for a year now using the google excanvas for IE support. In my environment I can not use flash, silverlight or any other browser plugin and that’s why I used canvas for creating interactive graphs.

I created a pie with canvas in javascript and that requires a lot of work related to mouse movements, x and y coordinates and math calculations. That is why SVG (Scalable Vector Graphics) is a great alternative. Instead of working with rasterized images (pixel by pixel), everything is a vector. That means it is scalable and easier to work with.

After seeing Doug Schepers talk at Mix 10, I knew I should be using SVG instead. Before Mix I thought that SVG had no decent browser support, but Doug told me otherwise. SVG has a long history in browsers and I recommend watching his talk here. He recommended using Raphael js library for creating SVG, because it has fallback to VML for IE browsers.

If you want to know the answer to my question, then go to www.ishtml5ready.com.

Check out html5doctor.com for more information about HTML 5, html5gallery.com for real world demos of HTML 5 and modernizr.com for javascript feature detection.

View Comments

“HTML 5 is intentionally sloppy”

That is an interesting quote from Molly E. Molzschlag from her workshop at Mix10. When I thought of HTML 5, I thought of something new, with lot of features and no sloppy markup.

The only way to make a new better version of HTML is to support older versions (backwards compatibility). Old html markup is usually sloppy and that is why html is intentionally sloppy. Many companies have spent a lot of money making websites and they need to be able to switch to HTML 5 without a high cost.

Although HTML 5 support sloppy markup, that does not mean that we should write sloppy markup. XHTML has thought us to write well-formed markup and we should continue doing that.

View Comments

C# string format in JS

The string format function in C# can be handy in JavaScript.

String.prototype.format = function() {
    var regex = /\{(\d)}/g;
    var text = this;
    while (match = regex.exec(text)) {
        text = text.replace(match[0], arguments[match[1]]);
    }
    return text;
};

I use regular expressions to match numbers with curly braces and then loop through the matches and call string replace.

Usage:

var color = 'blue';
'{0} is {1}'.format('the sky', color);

View Comments

Using EF with MySql and Visual Studio 2010 RC

So you just downloaded Visual Studio 2010 RC and want to connect to your MySql database and have the powers of the Entity Framework (EF)?

Your problem is probably that you can’t find the MySql connector when you add data source in Visual Studio 2010 RC. MySql just got VS 2010 support 15th feb 2010, but the connector is not stable yet. Go to the Development releases tab to download the latest connector. You must get MySql Connector /NET 6.3.0 alpha or later.

After installing the MySql Connector /NET 6.3.0 alpha you can open the Server Explorer, press Connect to Database and there you should see MySql in the list of data sources.

Note: Entity Framework does not support ODBC drivers and that is why you need the ADO.NET connector from MySql.

View Comments

Titler – javascript game in the titlebar

Play the game nowSee the source on Github

I had an idea the other day about creating a game using only the window title bar. Afterwards I just needed to try it out and see if I could do it, so here is my game. It is really simple but can be extended.

The controls are up and down arrow and you have to watch out for flying objects. On the left side you see what level you are on and how many lives are left.

The “magic” behind the game is setInterval to call a function every x milliseconds and window.title to change the text in the title bar. For more detail, look at the source on Github.

View Comments

Having fun with Powershell

It is awesome that you can use the .NET framework in Powershell. I am working on a website that contains a gallery. I got a lot of pictures sent in different sizes. At the moment I am only interested in pictures in a certain size. I used Powershell to find pictures in a folder with a specified height. Take a look.

[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
foreach ($file in get-childitem c:\web\photos -Filter "*.jpg" | where {[System.Drawing.Image]::FromFile($_.fullname).Height -eq 425 })
{
    cp c:\web\photos\$file c:\web\photos\chosen\$file
}

View Comments

Fork me on GitHub