kian ryan - code, photography, bob » Archive of 'May, 2009'

Because Good (Free) Fonts Are So Hard To Find

Those who have to dip their toes into the life of a designer once every so often understand the importance of typography. One of the hard parts of typography is finding the right typeface that isn’t going to break your piggy bank (or your client’s piggy bank).

This morning Tamara pointed me to Font Squirrel . To quote from Font Squirrel’s website:

” We know how hard it is to find quality freeware that is licensed for commercial work. We’ve done the hard work, hand-selecting these typefaces and presenting them in an easy-to-use format.

It’s a simple directory of excellent, high quality, free fonts. Well done guys and keep up the good work.

ASP.NET – Forms Inside Forms.

“It is a truth universally acknowledged, that an ASP.NET page in possession of a component, must be in want of a form.”

I’ve just come across this sticky little scenario in one of my projects:

ASP.NET components need to be wrapped in a form tag for their post-back magic to happen. As such, the form tag is usually as high level as it can possibly go (usually just inside the body tag). Some mailing list (sorry – mail marketing) companies provide you with a HTML form to integrate into your site so users can subscribe to the site’s mailing list. Sometimes these forms also come with a little chunk of Javascript to perform some page validation before performing the post.

So what we’ve got looks like this:

<script src="somethirdpartyvalidator.js"></script></p>

<form id="Form1" method="post" runat="server">
    <form id="MailingForm" method="post" action="somethingremote.pl" onSubmit="validate(this);">
        <!-- Insert some form components here -->
        <input type="submit" value="Submit" />
    </form>
</form>

<p>

And here’s the fun. When you click the submit button, it doesn’t perform the expected behaviour and perform a post to somethingremote.pl. Instead it performs a regular post-back to your site and (most likely) will do diddly squat. The culprit is __doPostBack, injected by ASP.NET at runtime, which hijacks the onSubmit event of the parent form to provide the post-back functionality. Your poor little mailing form doesn’t even get a look in.

The answer is to provide a little roll your own javascript for your own submit functionality. This article demonstrates a version of this technique. My version of the is shown below:

<script language="javascript" src="somethirdpartyvalidator.js"></script></p>

<script language="javascript">
    function submitForm() {
        var theForm = document.getElementById('signupForm');
        if (validateForm(theForm) != false) {
            theForm.encoding = 'application/x-www-form-urlencoded';
            theForm.action = 'somethingremote.pl';
            theForm.submit();
        }
    }
 </script>

<form id="Form1" method="post" runat="server">
    <form id="MailingForm">
        <!-- Insert some form components here -->
        <a href="javascript: submitForm();">Submit;</a>
    </form>
</form>

<p>

The variation from James Byrd’s original article comes from which form we submit. In the original, James posts the global form (in our example Form1) and instructs the reader to simply blank out any values they may not want to communicate to the third party. This seems overly permissive to me, especially in a potentially dynamic environment where you may have hundreds of components and as such my version simply selects the target form from the page before passing it through the validator and performing the submit action. The postback event is avoided, the third party only gets the data they need and the world is a happier place.

A Simple Generic Repository for Linq to SQL

Two code posts in one day, aren’t you lot lucky?

I’m currently working on a small project working with Microsoft ASP.NET MVC. I admit I’m rather enjoying the experience, it’s nice to get back to proper bare metal GETs and POSTs with non of the fluff of normal ASP.NET getting in the way. Since this is a relatively simple project I’m using Linq to SQL rather than the Entity framework. Whilst putting some boilerplate code together (after following the excellent NerdDinner tutorial) I realised there was a lack of a simple generic repository for common object operations. So I present to you my basic, generic repository:

using System.Data.Linq.Mapping;
using System.Linq;
using System.Linq.Expressions;
using BrandingScience.Models;
using System;</p>

<p>public abstract class Repository<T, C> where T : class where C : System.Data.Linq.DataContext, new()
{
    private C db = new C();</p>

<pre><code>// Query Methods
public IQueryable&lt;T&gt; FindAll()
{
    return db.GetTable&lt;T&gt;();
}


public T Get(int id)
{
    MetaTable mapping = db.Mapping.GetTable(typeof(T));
    MetaDataMember pkfield = mapping.RowType.DataMembers.SingleOrDefault(d =&gt; d.IsPrimaryKey);

    ParameterExpression param = Expression.Parameter(typeof(T), "e");
    var p = Expression.Lambda&lt;Func&lt;T, bool&gt;&gt;(
          Expression.Equal(Expression.Property(param, pkfield.Name),
          Expression.Constant(id)),
          new ParameterExpression[] { param });

    return db.GetTable&lt;T&gt;().SingleOrDefault(p);

}

// Insert/Delete
public void Add(T t)
{
    db.GetTable&lt;T&gt;().InsertOnSubmit(t);
}

public void Delete(T t)
{
    db.GetTable&lt;T&gt;().DeleteOnSubmit(t);
}

// Persistence
public void Save()
{
    db.SubmitChanges();
}
</code></pre>

<p>}

T is the table class you want to create the repository for, C is the DataContext created by Linq to SQL. Pretty straightforward. A typical implementation looks like this:

public class JobRepository : Repository<Job, MyDataContext>
{
}</p>

<p>public static void Main(string[] args)
{
    JobRepository jobRepository = new JobRepository();
    List<Job> allJobs = jobRepository.FindAll();</p>

<pre><code>// Return a single item and change the title.
Job job = jobRepository.Get(1);
job.Title = "Mutated Gerkhin Production";

// Create a new item.
Job newJob = new Job();
newJob.Title = "Mutated Gerkhin Anti-Coagulant Production";
jobRepository.Add(newJob);

// Delete an old item.
Job removeJob = jobRepository.Get(2);
Console.WriteLine(removeJob.Title); // Output: Survival of human race.
jobRepository.Delete(removeJob);

// Save all changes to the repository.
jobRepository.Save();
</code></pre>

<p>}

This version currently does not support dependancy injection, which is something I’ll be looking into shortly. But for now, it saves a heck of a lot of time to just get the simple stuff done. I’m surprised MS didn’t actually ship Linq to SQL with something similar.

Javascript Intellisense & jQuery.noConflict();

I’ll make no bones about it, VS08 SP1’s Javascript Intellisense saves me from having to dive into the docs every five seconds. Not having that fingertip intelligence to my hand would probably cost me quite a bit of time each day. However, since I often end up using multiple frameworks in one project, I tend to use the jQuery.noConflict(); to avoid it conflicting with the other frameworks. Unfortunately, the moment you stick var $j = jQuery.noConflict(); into the top of your javascript file, your intellisense will break for the rest of your script. I’ve currently got two methods for handling this:

1 – Create a “preload” file

This is a small script that sits in between loading jQuery and loading your page scripts. All it contains is the following statement:

    var $j = jQuery.noConflict();

Save it as preload.js and you can then sandwich this in between loading the jQuery framework and loading the page scripts as so:

<head>
    <script type="text/javascript" src="scripts/jquery-1.3.2.js"></script>
    <script type="text/javascript" src="scripts/preload.js"></script>
    <script type="text/javascript" src="scripts/whatever-you-want.js"></script> 
</head>

In your actual work scripts, you can then reference jQuery and the preload using the standard VS reference notation:

/// <reference path="jquery-1.3.2.js" />
/// <reference path="preload.js" />

Visual studio will have sorted out it’s type resolution for $j meaning that so long as you also have the jQuery .vsdoc file in the same folder as jQuery you get this glorious view:

Noconflict

The pros of this technique are that you can drop in new versions of jQuery at a whim and not have to worry too much about having to update preload.js. Of course the downside is that preload.js then needs to be sent to the client, with all the associated overhead of a get request.

2 – Append noConflict onto jQuery

There are those that will believe that the jQuery file is sanctimonious and should never be tainted by a developer’s touch. As it is I’m already using ASP.NET and cursed for all eternity, so how much worse could it be? So path two is pretty straightforward, open up the jQuery and jQuery.vsdoc files and add var $j = jQuery.noConflict(); to the bottom of the file. Again, this will sort out all the resolution gubbins while you’re working away in your own scripts.

Just remember that if/when you update your original jQuery files to also replace the noConflict statement at the bottom.

© 2008 kian ryan – code, photography, bob is powered by WordPress

Bad Behavior has blocked 34 access attempts in the last 7 days.