Scriptlet to run Firebug Lite for Safari Mobile

Instructions

  • Copy the code block below
  • Create a bookmark in safari and paste the code into the URL
  • Open the page you wish to debug and click on the bookmark you created, the Firebug Lite window will open at the bottom of the page

Code


javascript:(function(F,i,r,e,b,u,g,L,I,T,E){if(F.getElementById(b))return;E=F[i+'NS']&&F.documentElement.namespaceURI;E=E?F[i+'NS'](E,'script'):F[i]('script');E[r]('id',b);E[r]('src',I+g+T);E[r](b,u);(F[e]('head')[0]||F[e]('body')[0]).appendChild(E);E=new%20Image;E[r]('src',I+L);})(document,'createElement','setAttribute','getElementsByTagName','FirebugLite','4','firebug-lite.js','releases/lite/latest/skin/xp/sprite.png','https://getfirebug.com/','#startOpened');

Basic DataAnnotations Validation Example

In this example, I am using System.ComponentModel.DataAnnotations to validate my object.

I wrap two attributes around the property, one that requires a string, and one that marks the property as invalid if the String is greater than 20 chars.

[Required]
[StringLength(20)]
public string Name { get; set; }

Validating System.ComponentModel objects

We can validate the object using TryValidate on the System.ComponentModel.Validator class.

For now, we can just pass the Validator a new empty ValidationContext which is this code:

Validator.TryValidateObject(d1, new ValidationContext(d1, null, null), null, true);

Full test class below:

namespace ExampleLibrary.Tests
{

    public class SimpleCustomer
    {
        [Required]
        [StringLength(20)]
        public string Name { get; set; }
    }

    [TestClass]
    public class DirtyTests
    {
                
        [TestMethod]
        public void Customer_Name_InvalidWhenOverTwentyChars()
        {
            // assemble
            SimpleCustomer d1 = new SimpleCustomer() { Name = "01234567890123456789" };
            bool validWithTwentyChars, validOverTwentyChars;

            // act
            validWithTwentyChars = Validator.TryValidateObject(d1, new ValidationContext(d1, null, null), null, true);
            d1.Name = "012345678901234567890";
            validOverTwentyChars = Validator.TryValidateObject(d1, new ValidationContext(d1, null, null), null, true);

            // assert
            Assert.IsTrue(validWithTwentyChars);
            Assert.IsFalse(validOverTwentyChars);
        }

        [TestMethod]
        public void Customer_Name_InvalidWhenEmpty()
        {
            // assemblt
            SimpleCustomer d1 = new SimpleCustomer();
            bool validNull, validEmptyString, validFilledString;

            // act
            d1.Name = null;
            validNull = Validator.TryValidateObject(d1, new ValidationContext(d1, null, null), null, true);
            d1.Name = string.Empty;
            validEmptyString = Validator.TryValidateObject(d1, new ValidationContext(d1, null, null), null, true);
            d1.Name = "Some value";
            validFilledString = Validator.TryValidateObject(d1, new ValidationContext(d1, null, null), null, true);

            // assert
            Assert.IsFalse(validNull);
            Assert.IsFalse(validEmptyString);
            Assert.IsTrue(validFilledString);
        }
    }
}

Dependency Injection with NInject

Here’s a demo I wrote to show how basic NInject code works.

I setup an abstraction of the IExample interface as the class Example. I’ll use this later to get my HelloWorld text.

I then use it in a Print object (which implements IPrint) and then call the HelloWorld function on the IExample object, whatever that is. Because I’ve already bound any requests for IExample to Example, I will get an Example object.

I initialise the NInject kernel here:

IKernel ninjectKernel = new StandardKernel();

I then add the NInject binding (mapping) here:

ninjectKernel.Bind<IExample>().To<Example>();

If I didn’t setup any binding, I’d get the following NInject.ActivationException:

Error activating IExample
No matching bindings are available, and the type is not self-bindable.
Activation path:
  1) Request for IExample

I’ve posted a full Console Application example below:

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

namespace ConsoleApplication1
{
    // Example interface
    public interface IExample
    {
        string HelloWorld { get; }
    }

    // Example implementation
    public class Example : IExample
    {
        public string HelloWorld
        {
            get
            {
                return "Hello world";
            }
        }
    }

    // print interface for abstraction
    public interface IPrint
    {
        string PrintFunction();
    }

    // print implementation
    public class Print : IPrint {

        private IExample _example;

        public Print(IExample exampleParam) {
            _example = exampleParam;
        }

        public string PrintFunction() {
            return _example.HelloWorld;
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            // declare the kernel for ninject
            IKernel ninjectKernel = new StandardKernel();

            // setup the example binding
            ninjectKernel.Bind<IExample>().To<Example>();

            // get an implementation (loosely coupled)
            IExample exampleInstance = ninjectKernel.Get<IExample>();

            // return the value and print to the console
            IPrint example = new Print(exampleInstance);
            Console.WriteLine("result: " + example.PrintFunction());
            Console.ReadLine();

        }
    }
}

Using C# Yield

I just found something cool I haven’t been using in Linq so I thought I would share here.

When enumerating through a collection of IEnumerable<Object>, you can use the yeild statement to quickly filter items.

For example if I had a set of ShoppingCartItems held in an IEnumerable<ShoppingCartItem>, and ShoppingCartItem has a Category, I could filter with an extension method like this:

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

namespace ShoppingCartExample
{
    public interface IShoppingCartItem
    {
        string Description { get; set; }
        double Cost { get; set; }
        string Category { get; set; }
    }

    public class ShoppingCartItem : IShoppingCartItem
    {
        public string Description { get; set; }
        public double Cost { get; set; }
        public string Category { get; set; }
    }

    public static class Extensions
    {

public static IEnumerable<IShoppingCartItem> Filter(this IEnumerable<IShoppingCartItem> instance, string Category)
        {
            foreach (IShoppingCartItem item in instance)
            {
                if (item.Category == Category)
                {
                    yield return item;
                }
            }
        }

    }

}

So to use this, we ensure we’ve got the Extensions class in scope / included then call Filter on it like this:

// declare a cart
List cart = new List();

// add items
cart.Add(new ShoppingCartItem() { Category = "Toys", Cost = 1.23D, Description = "Monopoly" });
cart.Add(new ShoppingCartItem() { Category = "Fruit", Cost = 0.50D, Description = "Apple" });

// filter the items
IEnumerable results = cart.Filter("Fruit");

int count = results.Count; // will return 1

Related Content

Unable to serialize the session state

Unable to serialize the session state. In ‘StateServer’ and ‘SQLServer’ mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in ‘Custom’ mode.

Answer:

Make everything serialisable!

Simply declare the objects / types <Serialisable()> or [Serialisable()] if you’re C#

.NET Transactional Test Base

TransactionalTestBase

A Visual Basic .NET (VB.NET) Unit Test base class which automatically rolls back any ADO.NET or LINQ transactions.

Uses ServicedComponent with System.Transactions and provides event hooks for ease of use.

You can find all of this on my GitHub page – Transactional Test Base on GitHub

Minimum-Code Example

This example is the least amount of code required to setup a working Unit Test. There are more examples further down this README.

Imports Microsoft.VisualStudio.TestTools.UnitTesting

<TestClass()> _
Public Class Example_Tests
Inherits TransactionalTestBase

' Example barebones UnitTest with automatic transactioning and roll-back
' Author: Alexander Williamson
' Website: http://www.alexw.co.uk

#Region "Unit Tests"

<TestMethod()> _
Public Sub ExampleUnitTest
Assert.IsTrue(True) ' This test will pass
End Sub

#End Region

End Class

Usage

Create a new Unit Test class. Include any (required) Microsoft Unit Testing references:

Imports Microsoft.VisualStudio.TestTools.UnitTesting
Add the TransactionalTestBase file wherever your test are. Subclass child tests off this class.

<TestClass()> _
Public Class ExampleUnitTest
Inherits TransactionalTestBase

End Class

Each Sub that is decorated with the TestMethod() Attribute will automatically be wrapped in a transaction and rolled back when finished (or when an exception is encountered).

<TestMethod()> _
Public Sub ExampleUnitTest()
Assert.Pass("Hello world!")
End Sub

Hooks

Set-up Sequence

  1. Init Unit Test
  2. PreTransactionBegin
  3. (Transactions are created)
  4. PostTransactionBegin (we are now in transactions)
  5. Unit Test Runs
  6. (Unit Test passes or fails)
  7. PreRollback
  8. (Transactions are rolled back)
  9. PostRollback (we’re out of the transaction, everything has been rolled back)

Tear-down Sequence
Unit Test Ends -> PreRollback -> (Transactions rolled back) -> PostRollback -> End

Overridable functions

You can optionally override the following functions in your Unit tests.

PreTransactionBegin
Called before the transaction is created.

Public Overridable Sub PreTransactionBegin()

PostTransactionBegin
Called after the transaction is created, just before the Unit test is executed.

Public Overridable Sub PostTransactionBegin()

PreRollback
Called after the unit test has run, failed or caused an exception; before the transaction is rolled back.

Public Overridable Sub PreRollback()

PostRollback
Called after the transaction has been rolled back:

Public Overridable Sub PostRollback()

Recommended Example

Normally only overriding PostTransactionBegin to add Set-Up code is required. All transactions will roll back when each Unit Test finishes.

Imports Microsoft.VisualStudio.TestTools.UnitTesting

<TestClass()> _
Public Class Example_Tests
Inherits TransactionalTestBase

' Example barebones UnitTest with automatic transactioning and roll-back
' Author: Alexander Williamson
' Website: http://www.alexw.co.uk

#Region "Set-Up and Tear-Down"

Public Overrides Sub PostTransactionBegin()
' Called after the TransactionalTestBase transactions are created.
' We are in a transaction at this point.
' This is an optional override
' Put your Set-Up Code in here. This is normally the only section you will need.
End Sub

#End Region

#Region "Unit Tests"

<TestMethod()> _
Public Sub ExampleUnitTest
Assert.IsTrue(True) ' This test will pass
End Sub

#End Region

End Class
Full Unit Test Example
Imports Microsoft.VisualStudio.TestTools.UnitTesting

<TestClass()> _
Public Class Example_Tests
Inherits TransactionalTestBase

' Example UnitTest with automatic transactioning and roll-back
' Author: Alexander Williamson
' Website: http://www.alexw.co.uk

#Region "Set-Up and Tear-Down"

Public Overrides Sub PreTransactionBegin()
' Called before the TransactionalTestBase transactions are created.
' We are not in a transaction at this point.
' This is an optional override.
End Sub

Public Overrides Sub PostTransactionBegin()
' Called after the TransactionalTestBase transactions are created.
' We are in a transaction at this point.
' This is an optional override
' Put your Set-Up Code in here. This is normally the only section you will need.
End Sub

Public Overrides Sub PreRollback()
' Called just before a transactional roll-back.
' Put your Tear-Down code here (although you probably don't need anything in here).
' We are still in a transaction at this point.
' This is an optional override.
End Sub

Public Overrides Sub PostRollback()
' Called after the TransactionalTestBase transactions are created.
' We are not in a transaction at this point.
' This is an optional override.
End Sub

#End Region

#Region "Unit Tests"

<TestMethod()> _
Public Sub ExampleUnitTest
Assert.IsTrue(True) ' This test will pass
End Sub

#End Region

End Class

Generate QR Codes using the Google Chart API

When I’m testing or deploying websites built for mobiles and desktops, it’s often a bit of a challenge to get a URL over to a mobile. This isn’t really a problem the first couple of times; you can copy and paste, use Chrome to Phone or Google Chrome, email it over, etc., however I always like to find ways to speed up repetitive tasks.

To address this, at the bottom of our apps, I generate a link to the page and append it to the following URL. This link will generate a 400 w x 400 h pixel QR code to the chl argument.

https://chart.googleapis.com/chart?cht=qr&chs=400x400&chl=[url here]

Example Generated QR Code

Blow on the pie!

Example script

<p><img src="" alt="Example QR Code" id="generateMe" /></p>
<script type="text/javascript">
var ele = document.getElementById("generateMe");
ele.src = "https://chart.googleapis.com/chart?cht=qr&chs=400x400&chl=" + document.location.href;
</script>

Useful links

Writing Windows Services

I’m currently writing a Synchronisation Service for RedZebra Software. It synchronises information between Call2Field and k3 SysPro.

I was having a bit of trouble getting the MSI installer to register the service, so I thought I’d throw this post together in case it would help me if I forget again!

Microsoft have produced a tutorial for creating an Windows Service app and installer, it’s pretty foolproof, right up to the part where it says you might not need Custom Components (but you do, otherwise the program files get copied but the service isn’t registered), so don’t skip that bit!

Install, Start, Stop and Uninstall Windows Services using SC

SC is a very useful command for total manipulation of Windows Services, especially when you get past it’s quirky arguments.

  • Install a Windows Service with SC
    sc create "Service Name" binPath= "C:\Program Files\Whatever\Service.exe"

    Note: There’s a space between binPath= and the actual path – this catches a lot of people out!

  • Uninstall a Windows Service with SC
    sc delete "Service Name"
  • Start and Stop a Windows Service with SC
    sc start "Service Name"
    sc stop "Service Name"

Planning ahead with BugTracker.NET

Planned Dates Screenshot
Planned Dates columns highlighted

When I joined RedZebra, we were good at supporting customers because there were few requests and few problems. We’ve grown a lot and managing support requests is not easy when there are all the different configurations etc.

I introduced BugTracker.NET several months ago and got buy-in from the rest of the team to use this tool to log and record everything that comes through from support. We also use it to plan support if we’re waiting on someone. Ideally we’d integrate this with Outlook Calendars and resource scheduling so we can plan ahead, but this hits the budget for now.

I wanted a way to add a date to the items, and then be able to see when they’re planned in for, and if something is due for today. We already use BugTracker.NET’s categories, organisation, statuses and priorities, this just helps us organise that little bit better since we don’t have any time to go in and customise it ourselves.

I added a custom field called Planned Date and then modified our Queries (bug lists) to show the planned date, and another column indicating if the job is today. I’d previously joined the two together but mixing datetime and varchar sort wouldn’t be easy in this. I’m sure we could write a custom sort, or just modify the codebehind to do this, but I wanted to try and stay within the confines of the editors if I could.

Adding a Custom Field

  • In BugTracker.NET, navigate to Admin > Custom Fields
  • Click Add New Custom Field
  • Planned Date was the name of the field, and I chose datetime as the type. This hint lets BugTracker.NET display the right component. There’s a few different options here worth exploring, but for now just choose datetime so we get a calendar control.
  • Save

Now when you return to the Add or Edit Bug screens, you’ll be presented with the field.

Adding fields in here actually modifies the bugs table definition in the database (by adding and removing columns), so use with caution.

Selecting dates

When you’ve added your Custom Field, it’s right there when you edit an item.

Custom SQL for Queries

You won’t be able to see Planned Date or Today columns unless you add them to your Queries.

In BugTracker.NET navigate to Queries > Add New Query

Enter “planned” as the Description and copy the code below into the SQL box. Hit Create to add the Query and then navigate to Items > Query dropdown list > planned to see your new list. You can organise by Today or Planned as expected. It should look like the screenshot above.

I used an inline SELECT CASE which is similar to a switch or inline if for dates.


select DISTINCT
isnull(pr_background_color,'#ffffff'),
bg_id [id],
isnull(bu_flag,0) [$FLAG],
CASE WHEN CONVERT(DATETIME, bugs.[Planned Date]) >=
(SELECT DATEADD(dd, DATEDIFF(dd,0,GETDATE()), 0))
AND CONVERT(DATETIME, bugs.[Planned Date]) <
(SELECT DATEADD(dd, DATEDIFF(dd,0,GETDATE()), 1))
THEN 'Today!'
ELSE '' END [Today],
bugs.[Planned Date],
bg_short_desc [desc],
isnull(st_name,'') [status],
isnull(asg.us_username,'') [assigned to],
isnull(ct_name,'') [category],
isnull(pj_name,'') [project],
isnull(og_name,'') [organization],
isnull(pr_name,'') [priority],
rpt.us_username [reported by],
bg_reported_date [reported on],
isnull(lu.us_username,'') [last updated by],
bg_last_updated_date [last updated on]
from bugs
left outer join bug_user on bu_bug = bg_id and bu_user = $ME
left outer join users rpt on rpt.us_id = bg_reported_user
left outer join users lu on lu.us_id = bg_last_updated_user
left outer join users asg on asg.us_id = bg_assigned_to_user
left outer join projects on pj_id = bg_project
left outer join orgs on og_id = bg_org
left outer join categories on ct_id = bg_category
left outer join priorities on pr_id = bg_priority
left outer join statuses on st_id = bg_status
where bg_status not in (5,6)
order by bg_id desc

Service Management Expo 2012

Service Management Expo - Copyright SME
Service Management Expo 2011 – Copyright SME

Today I went to the annual Service Management Expo which was held in the National Exhibition Centre in Birmingham (the NEC). This is the second time I’ve gone, again with my boss, to check out our competition and get a feel for how the market is changing. It’s nice to see what’s out there, what’s new and where we fit into things – it gives me perspectives and ideas that I just cannot get from sitting and researching behind a computer screen.

The industry, like any other, is smart. It adapts, morphs and constantly pushes and innovates by creating more features and options. These features come at a cost; for the developing teams in terms of hours and other resources, and then to the customer as they purchase it; pushing up the initial and ongoing costs of the software.

There are always new entrants into the field and these are now web-based, look really promising and match our thinking. The industry is pushing HTML5 apps and the cloud in a big way. I have my reservations of cloud storage, I always prefer owning my content and I can understand why customers are hesitant about migrating to the cloud. I saw a demonstration today where the presenter could dip into live systems from a sitemap list and view live installations at will. Imagine if he accidentally saved his password using Chrome or similar – disastrous.

Thankfully we are keeping up with the innovation game and know where we want to go with the software in the next couple of years. There was nothing there we’d not considered or hadn’t thought about before, so there was nothing so shocking or interesting for us this time. I still maintain that it’s important keep up with your competitors through innovation, and I pushed for our apprentice to go and visit it and get a feel for the industry he’s in. He came back with some ideas, some of the features he thought our competitors lacked and saw gaps in the software that he never saw before.

One day, when this business grows enough, we hope to present at the SME, but for now we need to continue developing the features we’re going to add and concentrate on that at a later date.