August 23 2010

Parse JSON Date into a javascript Date object

I’m recording this here so I don’t ever have to look for this solution again.  It works perfectly with .net date json serialization and +400  timezones as well!

var date = new Date(parseInt(jsonDate.substr(6)));

The substr strips out the leading “Date” meta text.

Comments (View)
August 20 2010

Linq : Converting a List<> to a List<SelectListItem>

Just like when I was learning regular expression, I find that I’m using Linq to do more and more with my data objects the more I use it.  

Also with regular expression I’m wary of using it because it’s still not in the “everyday developer’s” skill set and if said developer ever has to debug my work, they might find it a steep learning curve.

This example however I think this code for converting a List<> to a List<SelectListItem> is pretty neat and self explanatory:

List<SelectListItem> SelectListItemList =
    (        
        from rec in myReadList  
        select new SelectListItem
            {
                Text = rec.Value,
                Value = rec.Key
            }
     ).ToList();

However, for those who DO want an explanation, this is what is happening:

  1. each item of a List<> named myReadList is read one-at-a-time into a variable called “rec”
  2. for each “rec” item a new “SelectListItem” object is made and the values rec.Value and rec.Key are read into the SelectListItem’s .Text and .Value properties
  3. Inside the brackets this will be returned as IEnumerable<SelectListItem> however I want it as a List<SelectListItem> so I call .ToList() afterwards.

For those who find the example above too long, here is the short-hand version. (It’s just one line, but broken so it wraps well)

List<SelectListItem> SelectListItemList =  
    myReadList.Select(
    rec => new SelectListItem 
    { Text = rec.Value, Value = rec.Key }).ToList();

UPDATE: For those wishing to set a default or selected item can find a solution (as chosen) at StackOverflow.

Comments (View)
August 03 2010

Detecting nested exceptions (because of CSLA)

CSLA is a pretty good middle-tier framework (though not without it’s complexity or problems).  A colleague and I were discussing that for small organisations, it’s just not worth implementing it if you’re not going to be running the factory methods on one server and the executions method on another server…. but that is not what I’m here to talk about!

So my problem with CSLA today is that when I want to invoke an exception from the bowels of an internal method, it is wrapped up nicely in a CSLA defined exception.  This means I can’t catch my exception like this:

try
{
    user = UserCsla.GetById(userId);
}
catch (DataNotFoundException dNFExc) // !!! THIS WON'T WORK !!!
{
    //user not found
    user = new User();
}

I know my exception is in there somewhere, but I don’t want to catch ALL exceptions in case something unexpected happens.  In that case I want the exception to keep bubbling.

My solution is to write an extension method for class Exception, that will recursively plumb the depths of .InnerException and see if it contains a certain type.

Extension Method:

public static class ExceptionExtender
{
    /// 
    /// Recurses Inner Exceptions and returns true if 
    /// the exception type is found in the stack
    /// 
    public static bool Contains(this Exception exception, 
                                Type exceptionType)
    {
        if (exception.GetType().Equals(exceptionType))
        {
            return true;
        }
        if (exception.InnerException != null)
        {
            return exception.InnerException
                               .Contains(exceptionType);
        }
        return false;
    }
}

Using it:

try
{
    user = UserCsla.GetById(userId);
}
catch (Exception exc)
{
    if (exc.Contains(typeof(DataNotFoundException)))
    {
        //user not found
        user = new User();
    }
    else
    {
        throw;
    }
}

Extra Note: I am aware that a better way to consume this data would be to have .GetById(userId) return a null value if the user isn’t found.  The method was created by another developer with that behaviour intentionally, and to consume it, I had to live by its rules.

Comments (View)
July 20 2010

Lightweight javascript graphics using SVN Vectors

Over at my favourite design website, they are discussing how to make a table of data gracefully upgrade itself from a table to a graph.. but to still be available as a table to non-supported browsers and spider-bots.

http://www.alistapart.com/articles/svg-with-a-little-help-from-raphael/

NOTE: Be aware, that at the time of writing, there is a bug that orders pie chart items by the highest to lowest value.  You can track the bug (and the fix) at the repository at GitHub.

NOTE: Be also aware that if you have values with a large difference (one is 1,000,000 and the other is 10), that it currently has a rendering issue that prevent the whole graph from loading. You can track the bug (and the fix) at the repository at GitHub.

Comments (View)
July 12 2010

Getting Started with NHibernate

A 6+ part series of “How-To’s” on getting started and mastering NHibernate.

Link to Article 1

Comments (View)

Versioning CSS and Javascript Files

I was reading a hints article regarding MVC and I came across a novel way of ensuring that you never have to ask a client to “Try clearing your cache”.

All you have to do is:

  1. Implement auto version numbering on your application
  2. Append the version number to the url for the .css or .js resource

So your resources will be cached until your version rebuilds, when the resource url will change!

This is actually getting into my next blog post, but figure out a way to version your JavaScript and CSS.  This really isn’t MVC specific, you should do this in almost any project.  The key reason is to help you with a browser’s cache.  You know you have a problem when the first thing someone tells you, when asking for help, is that they cleared their cache already.   My thought on this is your web app’s dll should have a version number, set the project to auto version, and then pop that onto the end of the css/javascript file call.  So it might look like this:  ”http://myapp/…/file.css?version=1.0.0.256″.   In my sample code, when in development I stick a timestamp on the file in the same way.

Comments (View)
October 29 2009

Using jQuery with Greasemonkey (and including javascript files from javascript)

Since my recent, torrid love affair with all things jQuery, I decided to go back to Greasemonkey and see if I could integrate it with jQuery to make selection and manipulation jsut THAT much easier.. and guess what? …it is!

If you use the following script.. jQuery will be registered from Google’s CDN and then the code will loop until the script is included in the DOM and then execute the doReady() function.

Use this template for all your jQuery / Greasemonkey scripting pleasures:

// ==UserScript==
// @name           jQuery include template
// @namespace      evildonald.net
// @include        http://the.pagedomain.com/
// ==/UserScript==

// include an external javascript file
function include(filename)
{
var head = document.getElementsByTagName('head')[0];

script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';

head.appendChild(script);

checkJQueryLoaded();
}

// Check if jQuery is loaded
function checkJQueryLoaded()
{
if (typeof unsafeWindow.jQuery == 'undefined')
{
window.setTimeout(checkJQueryLoaded, 100);
}
else
{
$ = unsafeWindow.jQuery;
$(document).ready(doReady);
}
}

// initialize the page
function doReady()
{
alert($); // this proves jQuery is loaded
}


include('http://ajax.googleapis.com/ajax/libs/jquery' +
'/1.3.2/jquery.min.js');


Many thanks go to Joan Peidra for their invaluable method for testing if jQuery is loaded

Comments (View)
October 06 2009

Online Unix Banner Generator

Sometimes you really want something to stand out.  Unix banners are a great universal way of marking up text with an important message, but not having access to a Unix system, I couldn’t generate one!

Fortunately, this site has come up with the goods and will let you generate banners in a myriad of “fonts”.  The example below was generated in “Letters” font.

 OOOOO  BBBBB    SSSSS   OOOOO  LL      EEEEEEE TTTTTTT EEEEEEE 
OO   OO BB   B  SS      OO   OO LL      EE        TTT   EE      
OO   OO BBBBBB   SSSSS  OO   OO LL      EEEEE     TTT   EEEEE   
OO   OO BB   BB      SS OO   OO LL      EE        TTT   EE      
 OOOO0  BBBBBB   SSSSS   OOOO0  LLLLLLL EEEEEEE   TTT   EEEEEEE 

UPDATE: My co-worker BH was auditing/refactoring all stored procedures and seemed to really like the OBSOLETE headers. It made his job easier being able to see straight away that he didn’t need to process that proc.

Comments (View)
September 11 2009

Handling multiple submit buttons in MVC v1

A lot of forms have input fields with multiple action buttons that act on that data.  MVC doesn’t immediately offer an ability to detect which submit button was clicked.

One solution is to use different forms that are tagged with action labels that will invoke a method in a controller. The following works:

<% using (Html.BeginForm("Action1", "ControllerName")) { %>
<%= Html.TextBox("Id") %>
<input type="submit" value="Save" />
<% } // end form %>

<% using (Html.BeginForm("Action2", "ControllerName")) { %>
<%= Html.TextBox("Id") %>
<input type="submit" value="Save" />
<% } // end form %>

But what if you want to use the same input fields for both submit buttons? A submit will only POST back the named fields that are in the same form as it.  You might consider the following solution, but it will not work:

<% using (Html.BeginForm() { %>
<%= Html.TextBox("Id") %>
<% } // end form %>

<% using (Html.BeginForm("Action1", "ControllerName")) { %>
<input type="submit" value="Save" />
<% } // end form %>

<% using (Html.BeginForm("Action2", "ControllerName")) { %>
<input type="submit" value="Save" />
<% } // end form %>

As a better solution, I like to name all the submit buttons with the same name, and have each button have it’s own value.

<% using (Html.BeginForm()) {%>

<%= Html.TextBox("Id") %>

<input type="submit" value="Action1" name="SubmitButton" />
<input type="submit" value="Action2" name="SubmitButton" />

<% } // end form %>

Then all I need to do is capture the value of the POST item “SubmitButton” and I can perform business logic on what value is returned!

Here is a sample Model:

[Serializable]
public class MyModel
{
public int Id { get; set; }
public string SubmitButton { get; set; }
}

Here is a sample Controller:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DoSomething(MyModel model)
{
if (model.SubmitButton.Equals("Action1",
StringComparison.OrdinalIgnoreCase))
{
return RedirectToAction("Action1", new { id = model.Id });
}
else if (model.SubmitButton.Equals("Action2",
StringComparison.OrdinalIgnoreCase))
{
return RedirectToAction("Action2", new { id = model.Id });
}
return View();
}
Comments (View)

Thoughts on Oracle (FAIL)

So we’re starting new development on a web project. We’re also using Oracle with packages.

  • Oracle only supports object names of up to 30 characters. FAIL.
  • Oracle’s If..Else statement uses ELSIF.  What? You didn’t want to waste space on an E?  You can’t overload the loop to make it correct for future version? FAIL.
  • Want to quickly debug a stored procedure in TOAD? Fuggedaboutit!  You have to declare variables in a DECLARE block.. and if you’ve done that, you can’t just see the results of your query.. you’ve gotta add it to a cursor and then loop through the cursor.  FAIL.
  • Oracle decided that a package needs a header file.  This is to avoid re-compilation if you change the package body. It’s also a redundant pain-in-the-ass. FAIL.
  • Oracle packages are all one SQL script. Do you think it’s unlikely that two developers want to code two different procedures in the same package? That is what Oracle must have been thinking when they wrote their package code.  Unless you are coordinated or use some locking mechanism, the potential for overwriting another developers work is Huge! FAIL.
Comments (View)
June 18 2009

How to Clone a DBParameter in .Net

DBParameter doesn’t support ICloneable.  I wanted to clone my DBParameter collection because when I cached them, and then tried to reuse them, i was re-using a reference to the parameter which was already used in a different command object.  This would throw a runtime error of “The OracleParameter is already contained by another OracleParameterCollection.”

The trick to getting around this is realising that even though DBParameter doesn’t support ICloneable, OracleParameter which inherits from DBParameter does!  In my application I’m only dealing with Oracle databases, but I think this applies to SqlParameter and OLEDBParameter as well.

Just for kicks, I also made it an extension method because I like ‘em!

using System;
using System.Data.Common;

namespace MyProject
{
public static class DBParameterExtension
{
public static DbParameter Clone(this DbParameter param)
{
ICloneable cloneableParameter = param as ICloneable;

if (cloneableParameter != null)
{
return cloneableParameter.Clone() as DbParameter;
}
else
{
throw new ApplicationException(
string.Format("Unable to clone parameter {0}",
param.ParameterName));
}
}
}
}
Comments (View)

A list of free Windows utilities that do exactly what they promise

There are a lot of dodgy freeware products out there. These do exactly what the name says:

  • AusLogics Disk Defrag - Fast, Efficient Defragger
  • Mouse Imp - Scroll vertically and horizontally by holding down your right-mouse button
  • TrueCrypt - The big daddy in reliable open-source encryption
  • Secure Delete OnClick - Removes any file without a trace.
  • Process Explorer - This is a task manager replacement tool. Looks ugly. Is INVALUABLE if you get a virus that is scanning your hard drive and it has disabled Task Manager.
  • DoPDF PDFCreator - Creates PDFs for you as a printer with very little fuss
  • Notepad 2 or TextPad - Great replacements for the venerable (doddering?) Notepad.exe
  • Volumouse - Hold your mouse over the task bar and scroll up or down to control volume.  Works perfectly!
  • 7-Zip - Easy file compression, handles many formats
  • Desk Pins - Will pin any window to “Stay on top always”
  • Drop Box - AMAZING folder sync tools. Syncs shared folders across the internet and keeps versioned master backups as well
  • Launchy - Windows XP - A quick launcher so you never need to open your Start menu again
  • Taskix - Lets you reorganise the order of your task bar placeholders (Doesn’t play nicely with UltraMon)
  • Beyond Compare - Awesome for comparing files to each other, or synchronising folders with each other
  • WinGrep - Because Windows search is rubbish and it ignores code files in searches… and because Regular Expression is so cool.  TextPad can also do this with its “Find in Files” functionality.
  • TeraCopy - Vista Only - file copying is slow and unresponsive. Copying over a network is unbearable with clicking “Cancel” taking minutes to register and it spending seemingly forever to calculate how long it’s going to take instead of just doing it.  Teracopy fixes all this and more.  The best part: You can set it as the default copying engine. It’s lovely.
  • PureText - Use Windows-V to paste from clipboard with all HTML formatting removed
  • Expresso (version 1) - Regular Expression sandbox.  The first version was the best, but version 3 is mostly OK.
  • Task Switch Xp - A light and crash-free Alt+Tab replacement GUI
  • Paint.Net - A light-weight image editor.  Loads faster than GIMP which i also like.

For anything else, someone with more patience than me has created a pretty comprehensive list of freeware.

Comments (View)

Essential (and not so essential) Firefox plug-ins

  1. Firebug - Amazing javascript/css/html debug tool
  2. Download Statusbar - For the best downloading experience
  3. Adblock Plus - No more annoying flash ads that yell out. Until the ads play nicely, I’m blocking them!
  4. Tab Mix Plus - Lets you Control + Tab in last opened order
  5. SearchPreview - Adds a preview thumbnail in standard Google searches.
  6. Web Developer - The big daddy of dynamic browser tweaking
  7. YSlow - Profiles your site using Yahoo! rules for high traffic
  8. GreaseMonkey + GreaseFire - Lets you run post-javascript on web pages to make them work the way you want
  9. XMarks (a.k.a. FoxMarks) - Synchronise your bookmarks (as well as passwords and cookies if you want)
  10. Google Advertising Opt-Out - Google were kind enough to let you opt-out of their ad tracking
  11. FireFTP - The best free FTP client I’ve ever used

Comments (View)
May 26 2009

Oracle: Date manipulation

I’m just listing this because I ALWAYS forget the syntax for this small stuff.

Converting Varchar2 to Date:

SELECT to_date('01-JUL-2009','dd-mon-yyyy') 
FROM Dual;

Using todays date to build a relative date:

SELECT trunc(sysdate + 36) 
FROM Dual;
Comments (View)

Oracle: Searching for a keyword in the database objects

It can be vitally important to know if an object is being referenced in a stored procedure or function, and although TOAD very helpfully will tell you all dependencies of an object, it is possible (if you are working on a horrible legacy project like me), to have SQL created on the fly and executed as a string.  Yech!

SQL for searching your oracle procedures and functions:

SELECT * 
FROM USER_SOURCE
WHERE LOWER(TEXT) LIKE LOWER('%to_date%')

UPDATE:I’ve also decided to include some code to search tables that contain a keyword. This can be very useful if you have a column name but don’t know table it’s contained in

SELECT *
FROM all_tab_columns
WHERE LOWER(column_name) LIKE LOWER('%SearchTerm%');
Comments (View)

Please...

Leave a comment if this has helped or offended you.

StackOverflow Id