kian ryan - code, photography, bob » Posts in 'Code' category

Fiddler 2 and MVC Forms

I’ve been using ASP.NET MVC for a couple of projects now, and so far my assessment is lukewarm. I like it in that it lets me play with raw data and is increadibly powerful, extensible and testable. It does take quite a while to spin things up though, and you can end up in a headache of chase the forms. It’s quite likely I’ve not quite got the hang of it yet, but that’s fine.

One tool that has proved invaluable to my understanding of forms, FormCollections and the noise going backwards and forwards between my app and the browser is Fiddler 2. It’s a proxy server with a UI over the top that lets you see the requests and responses that are sent between your web browser and server. It’s great to understand the shape of the data your sending to the formCollection, whether various fields are sending the right name, checking that JSON data as it’s coming back etc. In no respect should it replace testing, but it makes understanding the flow significantly easier.

Masque Mobile: The fencing ref’s Android friend.

Promotional

Orange Tentacle have just released their latest Android application: Masque Mobile. Masque Mobile is a fencing referee’s friend designed to take the pain out of juggling scores, times and cards.

Screenshot 1

The UI has been built, and rebuilt around the ideal of a clean interface designed to minimise potential mistakes. The referee is presented with a clean UI, with only the score counters, cards and time on screen. A large button with haptic feedback means the timer can be started and stopped with the eyes away from the device.

Screenshot 3

If a penalty occurs during a bout, the referee can action a card by selecting the appropriate card outline. Optionally a full screen card can be presented to the offending party. The interface will keep track of the number of cards awarded and can also award hits to opponents.

Screenshot 4

Other features are cleverly hidden away. Priority resets, and breaks are all actioned from the menu, and preferences to define period length, and the amount and kinds of feedback the application provide can all be set from the preferences dialog.

This is the first “paid for” app released by Orange Tentacle (at a very modest 99p), and while we’re not expecting it to be proving Porsches for Christmas, we hope the fencing community will appreciate the amount of time that has gone into developing this little application.

Resources For Android Development

Just a short post today, outlining some cool stuff I’ve found for Android development.

IntelliJ IDEA

Google have very kindly put together the ADT for Eclipse, which consists of plugins and layout managers to make development a bit smoother. Which would be great for me, if using Eclipse didn’t make me want to pull my nails out with forceps (I’m a Visual Studio person by day). I dislike Eclipse so much, that I spent most of the last project building in TextMate and looking up API references by hand. The very nice people who make my most favourite Visual Studio plugin in the whole WORLD – Resharper, also make a very nice Java IDE called IntelliJ IDEA. Version 8 came with some basic plugins you could download for Android development, but the very nice people at Jetbrains have put some serious time into the Android tools for Version 9 of IntelliJ. Inbuilt Logcat support, and a run/deploy model which beats the socks off the Eclipse one. I believe there’s debugging support as well – I’ve not been able to test that yet though. All in all, a very nice environment. Oh, and most of the refactoring & code navigation tools that make Resharper so awesome in the first place. Check out version 9 BETA.

DroidDraw Beta

DroidDraw is a cross-browser UI designer and editor for Android applications. I’ve not had a proper play around with it yet, I’ve just been using it for a few days, but so far it is officially awesome. Much more reliable than the in built Eclipse editor, and nowhere near as frustrating. I’ll be honest, now I’ve got the very, very good XML support which IntelliJ provides, I’m not needing it so much, but it makes a great prototyping tool.

Linky Linky Linky

Some articles which have been useful over the past few days:
How to use AlertDialog.Builder in Android applications Great quick reference to AlertDialog.Builder.
What’s Your Preference: Part One Writing preferences should be easy. _Don’t do my trick and write a load of custom layouts, only to realise the API does 90% of the work for you
What’s Your Preference: Part Two more of the above
Android 1.5 android.R.drawable Icon Resources The API contains a load of built in graphics you can just reference.

Internet Explorer User-Agent Strings

Internet Explorer can be a right PITA when it wants to be. I’m using Thickbox to render on page dialogues in one of my projects. Thickbox relies on testing $jquery.browser.version for determining the version number of Internet Explorer.

!(jQuery.browser.msie && jQuery.browser.version < 7

Apart from the fact that it doesn’t always work. Below is what you would expect to be presented as a user agent string for IE8:

Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; GTB6; SLCC2; 
.NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; 
.NET CLR 4.0.20506; InfoPath.2)

So far today, I’ve seen three customers with the following string

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; 
Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 1.1.4322; 
.NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648; .NET CLR 
3.0.4506.2152; .NET CLR 3.5.30729)

Somewhere, somehow, the user agent string has become corrupted (and hence the MSIE 6.0). There’s some information on this available on Microsoft communities.

The way around this is to do some explicit regular expression checking on the useragent string. For those that didn’t know about this previously, it’s demonstrated by Jamie Thompson. He introduces a new property called $.browser.msie6 which is used to check for the presence of the IE6 string without the IE7 string.

$.browser.msie6 =
    $.browser.msie
    && /MSIE 6.0/i.test(window.navigator.userAgent)
    && !/MSIE 7.0/i.test(window.navigator.userAgent);

You then adapt thickbox.js to test for this new property.

if ( !(jQuery.browser.msie6)) { // take away IE6
    $("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
}

Which works great for IE6, great for IE7, fine for vanilla IE8 (which doesn’t suffer from the above bug), but falls down on corrupted IE8. Not to panic, simply adjust $.browser.msie6 to look for this additional string.

$.browser.msie6 =
    $.browser.msie
    && /MSIE 6.0/i.test(window.navigator.userAgent)
    && !/MSIE 7.0/i.test(window.navigator.userAgent)
    && !/MSIE 8.0/i.test(window.navigator.userAgent);

The downside to this fix is that if and when Microsoft comes out with Internet Explorer 9, then you’ll need to adjust this script again to take this into account. I therefore propose a slight departure, using regular expressions to test for values above 6:

$.browser.versionOver6 = function() {
    var re = /MSIE (\d+)/ig;
    var match;
    while (match = re.exec(window.navigator.userAgent)) {
        if (match[1] > 6) {
            return true;
        }
    }
    return false;
}</p>

<p>$.browser.msie6 =
    $.browser.msie &amp;&amp;
    $.browser.versionOver6();

This modified version should work on all future versions of IE. Browsers which report a MSIE 6.0 as well as a MSIE 7.0, MSIE 8.0, MSIE 9.0, etc will now also report as not IE6, which should make filtering off IE6 fixes a little easier.

Enjoy.

Guathon – After Tea

Here we go Visual Studio 2010 & ASP.NET 4.0

  • Lots of content not being covered. At least he’s clear about this.
  • Now built on WPF – woof. Multi monitor support.
  • Demos being done on the MVC codebase :-)
  • Code navigation – select param, highlights all instance usages.
  • Intellisense – Mid term search, no longer need to type start of term. Filters based on camelcasing woot. Someone has been using Quicksilver.
  • Oh dear – resharper is in trouble. Navigate to – “goto Type”. Although now quite as neat – needs keyboard interaction.
  • View call heirarchy – more Resharper features :-) (althought being able to keep searches around is a nice feature.
  • Col based code selection as well as line selection.
  • TDD support – “Consume First”, stops intellisense from attemting to autocomplete when writing not-yet-existing classes. Then becomes aware of class and allows you to define/work with properties. Nice.
  • TDD support – generate class (wait – this wasn’t in 08? More resharper?)
  • MY GODS – 2010 really is 2008 + Resharper (so far). Remind me to reiterate my love for Resharper.
  • CodeSnippets in VS2010 feel like completion in TextMate. Nice mechanism. Extended for ASP.NET, download extra snippets.
  • #scottgufact – Scott Gu works at Redmond, you don’t.
  • Debug history – useful landmarks in lifecycle.
  • Historic debugging – allows step forward/step back through source code.
  • Test tool – run on client, captures information on state of crash. Sends state back to developer. Developer can debug from the state of the crash. That’s pretty damn neat. Can also capture screenshots/video.
  • .NET 4.0, new version of CLR (guessing because of dynamics, etc).
  • Visual Studio 2010 filters intellisense and properties for target framework. Uses reference libraries.
  • ASP.NET 4 – emphasis on clean HTML and SEO (routing, user configurable ClientIDMode), etc.
  • Are we back on web apps vs web sites? (Scott jumped straight to web app rather than web site).
  • New web app template looks good. Jquery, logins, etc included out of the box. Very nice.
  • ClientIdMode – Predictable is the new black (and will save front end developers having migraines when given ASP.NET apps).
  • CSS rendering for controls – YES! THE TABLES ARE BANISHED! RenderTable=false
  • Finer grained control over the viewstate.
  • Improvements coming to the WYSIWIG designer – who uses the designer for ASP.NET? Really?
  • Routing support for ASP.NET 4 – quite elegant :-) Page.RouteData.Values. Doesn’t to URL rewriting, more subtle mechanism.
  • IIS SEO Toolkit. Analysis tool for SEO optimisation of sites. Target site does not need to be running on IIS. Can perform some optimisations to IIS sites – hence linked to IIS manager.
  • It looks like VS 2010 javascript support no longer sucks. A seriously robust engine. Involves intellisense which can keep track of quite impressive object definition at design time. Woot!
  • ASP.NET Ajax – new things for those people that use it (I’ve never got on with it).
    • ADO.NET Entity Framework – more T4 support good. Model first and POCO to boot.
  • Apparently LINQ 2 SQL is not dead – improvements coming. I remain sceptical.
  • Design surface no longer has a “dump and replace” attitude. This may rendel DBML Tools redundant.
  • Inbuilt fake support, reliance on T4 – looks like MS is buying hard into T4 for code gen. I see this as a positive thing.
  • I admit – the chart control is cute :-)
  • WAIT? Multiple config file support – build config dependant. I do this already! I will no longer be special! Don’t like deployment support from within VS, prefer to do it clean from a build server.
  • Release specific configs only contain overwrites – this is useful.
  • If you can tie the Deployment Projects up with build servers (I’m looking at you CCNet), you’ve got a rather powerful test & deployment environment.
  • Seriously folks – this is one of the really nice things…

[Please note these posts are done from my G1. Typos and errors may/will/are included].

Guathon – Before Tea

Covered so far:

  • Websitespark (we know about this already
  • Web Platforms Installer (Apt for windows – this looks good – can developers submit apps to it?)
  • MVC (we’re here for two hours on this – basic intro and new stuff on 2.0)
    • Support for jQuery.validate in MVC2
    • (Usual MVC basics – saw this at Mix 07)
    • Humm, routes supports reg-ex. Is this new to 2.0?
    • Ahh – scaffolding, etc is T4. That’s been an itching question. I severely like the layout of the default generated views.
    • MVC2 – new “filter” attributes. [HttpPost] replaces [AcceptVerbs(Http.Post)]. Small but nice detail.
    • Ohh, you can mark which attributes are bindable in the class – you don’t have to do it in UpdateModel.
    • “buddy class” – way to get around partial method limitation. Haven’t seen this before… Link the buddy class to the type class using [Metadatatype(typeof(buddy))]
    • Er, okay. This is new stuff in the validation. Direct validation attributes using the buddy class. COOL! System.ComponentModel.DataAnnotations.
    • The binding has changed quite a bit. I like the new architecture, much less messy, much stronger.
    • MicrosoftMvcJQueryValidation.js <– nice one.
    • Complex validation – base off a webservice.
    • New helpers: Html.EditorFor, Html.DisplayFor. Strongly typed lambda syntax – compile time checking.
    • Templates allow override of HTML generated for EditorFor and DisplayFor. Uses partial views. Name partial view to type (e.g. Decimal). Drop in “EditorTemplates” folder. Can be applied to shared folder and/or view specific. Nice.
    • Can also generate templates not related to type, pass to “EditorFor” as a parameter. Also nice.
    • Can use the buddy class with [UIHint] attribute to specify type to field. Big emphasis on DRY. Ohhh nice.
    • Whole model can be CRUD rendered on the fly. [ScaffoldColumn] can be used to inclue/exclude properties.
    • Unit testing time… First up the unit testing sales pitch.
    • “Vs 08 adds all this value added … crap” as the Gu goes mad with the delete key.
    • Unit testing models, unit testing controllers (nothing new here so far).
    • Simple testing on controllers to ensure they render views, etc.
    • Here we go – the hiccups with tight binding to the DB for tests. Ohh, dependancy injection.
    • IService, Db imp of service. Pass into constructor.
    • Use 3rd party dependancy injection or “poor mans – pass through the controller”.
    • Pass collection of objects to “FakeService”. How should you happen multiple services?
    • No shame in writing tests to test the database and tests against the fake services.

Log Parser Is My New Best Friend

SEO may be something of a dark art, but even if we don’t practice it, as web developers we’re usually responsible for putting into place the mechanisms that allow the Mouldy-morts to practice their forbidden forms. Recently, that usually consists of dropping analytics code onto a page to track your users every move, but what do you do when someone’s “forgotten” the analytics code, or it fails for some unknown reason?

Step up to the plate server logs! Both IIS and Apache quite happily dump their site logs for you to parse through them. But this is where the fun bit comes in, since they can get quite large. How large? This morning I’ve had to wade through 102GB of logs. Most unix monkeys will probably laugh at their windows using counterparts, and with their long hair and sandals decry, “102GB! Hah, I eat 102GB of server logs for breakfast with my organically grown shredded wheat!”. And yes, with Perl, awk and sed, 102GB is pretty much nothing. But you don’t tend to have these tools easily accessible on a window box, and if you’re messing around on someone else’s Windows box, you want to create the smallest footprint possible.

And here’s where Microsoft has been quite clever with a little known, but very powerful tool called LogParser. Log Parser provides you with SQL-style syntax access to the data contained in those log files and can output it in a range of formats from CSVs through to charts. I’ve been playing with it most of the morning. It’s nice.

Install it, add it’s location to your path variable and the log world is your oyster. Open a command prompt and traverse to your IIS log directory (mine is at c:\iislogs) and execute the command using the following:

logparser -i:iisw3c -o:csv "{insert-sql-query-here}"
or
logparser -i:iisw3c -o:csv file:query.sql

-i:iisw3c tells log parser its looking at w3c formatted log files, -o:csv to output as CSV and you can either present your sql inline or reference an external file. I’ve listed a few examples below to get you started:

-- Return page hits for all aspx pages handled from the beginning of the year to today in a given directory.
SELECT COUNT(*), cs-uri-stem 
INTO hits.csv 
FROM *.log WHERE EXTRACT_EXTENSION(cs-uri-stem) = 'aspx'
AND cs-uri-stem LIKE '/subdirectory/%'
AND date between timestamp('2009-01-01 00:00:00','yyyy-MM-dd hh:mm:ss') 
    AND timestamp('2009-09-11 00:00:00','yyyy-MM-dd hh:mm:ss')
GROUP BY cs-uri-stem</p>

<p>-- Return number of hits for different query string tokens
SELECT COUNT(*), EXTRACT_TOKEN(cs-uri-query, 0, '&amp;'), EXTRACT_TOKEN(cs-uri-query, 1, '&amp;')
INTO search.csv 
FROM *.log WHERE cs-uri-stem LIKE 'Query.aspx'
AND date between timestamp('2009-01-01 00:00:00','yyyy-MM-dd hh:mm:ss') 
AND timestamp('2009-09-10 00:00:00','yyyy-MM-dd hh:mm:ss')
GROUP BY cs-uri-stem, EXTRACT_TOKEN(cs-uri-query, 0, '&amp;'), EXTRACT_TOKEN(cs-uri-query, 1, '&amp;')

And here’s a few links to other people who’ve done more with it than I:

Livejournal iGoogle Gadget

Livejournal Gadget

For the past few weeks I’ve been using Google’s “iGoogle” service, a customisable home page with widget support. Gadgets are HTML/Javascript and fit in nicely with Google’s philosophy of everything on the cloud. If you’re running other chunks of Google Apps, such as Google Calendar or Google Reader, you’ll find iGoogle a nice unified dashboard to work from.

I’m an avid LiveJournal user, and have been since January 2004, but the lack of portability of the friends page – arguably the most vital resource for a LiveJournal account has griped me. You can’t access entries as an RSS feed, and until a few days ago there was no decent mobile solution.

This morning I received a nice e-mail from LiveJournal notifying users they’ve updated their mobile site to be more inline with the current crop of mobiles. It’s nice, displays full entries and has a straightforward UI. I like it. I liked it so much I wanted it on my iGoogle page.

So after a bit of griping with the Google Gadgets documentation I finally came out with the following code which works quite nicely. I present it to you in all its majesty:

<?xml version="1.0" encoding="UTF-8" ?>
 <Module>
   <ModulePrefs title="LiveJournal Friends"
        height="400"
        scrolling="true">
        </ModulePrefs>
   <Content type="url" href="http://m.livejournal.com/read/friends/"><br />
   </Content>
 </Module>

Impressive, innit?

Strangely, although Google provide wizards and templates for generating boiler-plate gadgets they don’t provide a way for embedding remote HTML content. There’s probably a very good reason for that, but I’ll be damned if I know what it is at this time of night.

If you want to add the gadget to your own iGoogle page, click on the button below. If you know anyone who does use LiveJournal, pass it on.

Add to Google

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.

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

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