Writing my first TypeScript type definition

14 10 2013

A little delayed, but last week I officially made my first proper contribution to an open source project. As you’ll probably be aware by now if you’re using TypeScript, there is a great resource for type definitions on GitHub called DefinitelyTyped. I was working on some prototyping and wanted to try out some custom scroll bars and found a great library called mCustomScrollbar. Unfortunately there wasn’t already a type definition for this in DefinitelyTyped but after looking at the fantastic documentation provided for it, I decided to write my own.

It was all a bit of a trial really. I hadn’t read anything formally about how to create these but I had been looking at the ones I was getting from the DefinitelyTyped project in order to try and understand what they were doing. One of the benefits of TypeScript is the design time errors so without your type definition between your TypeScript and your library to allow your TypeScript to understand what it is you’re trying to call, all you will see is squiggly red lines and your project won’t build. I found it quite easy to understand what I needed to write in my type definition to make it work and being able to refer to the other definitions in my project was a great help in that sense. The biggest help by far though was the great documentation written by the plugin’s author. I would happily write more type definitions in the future for plugin’s with documentation as good as this one as it made the process a lot easier.

My main piece of advice if you’re thinking of contributing to the project, is to read their contributor guidelines. Making sure you get the small details right mean that you are more likely to get the type definition right (you will have to write tests) and it also means you will save yourself and the person reviewing your pull request from wasting time over formatting / test failure issues. See the contributor guidelines here – https://github.com/borisyankov/DefinitelyTyped/wiki/How-to-contribute

I’m going to attempt to put together an in depth guide on how to write a basic type definition using this as my working example in the very near future. If you want help in the meantime (and let’s be honest, it’s possible this in depth guide will never happen) then get in touch on here and I will get back to you to see if I can be of any help.

I’ll be totally honest, the main reason for this post was because I was so happy to have finally made my first contribution to an open source project as it’s something that I had always wanted to do. I just wanted to share my happiness with whoever may read this!

Advertisements




Using TypeScript with the FullCalendar JQuery Plugin

24 09 2013

I recently needed to do a proof of concept to ensure TypeScript would work with the FullCalendar plugin, as I was planning on using these together in a new app I’m working on. When I searched for any information on this combination, I didn’t find much, which is why I’m writing this.

Now if you’ve found your way here, then I’m sure you’re already familiar with TypeScript so I won’t go into detail on what TypeScript is and how it works. The TypeScript site does that so well itself anyway so if you’re curious, check it out here – http://www.typescriptlang.org/.

The good new is, THEY DO WORK TOGETHER! The even better news is, someone has already written a type definition which has been included in the DefinitelyTyped project. So it’s quite quick and easy to get up and running with this. As I mentioned, this is a proof of concept so I haven’t spent too much time on code structure so please don’t take the structure of my code as the best way, this is just to show you quickly, how I proved this will work.

I’ve got a basic Web Application in Visual Studio. I’ve then used nuget to install the following packages:

  • jQuery (2.0.3 in this case, the latest at the time of writing)
  • jquery.TypeScript.DefinitelyTyped (the jquery.d.ts file)
  • fullCalendar.TypeScript.DefinitelyTyped (the fullCalendar.d.ts file)

I’ve also manually added the FullCalendar files (1.6.4 in this case, the latest at the time of writing). I also created a TypeScript file, which I’ve called App.ts which is where I’m going to put all my TypeScript code (this is what I was referring to earlier when I said please don’t take my code structure as the right way to do it. In a proper application I would have split my classes out etc).

Apologies for the not great formatting of the code. I really need to find a newer theme that deals with code snippets a bit better. I have also uploaded the whole Visual Studio project (it’s a VS2013 project so apologies if you can’t open it, but you will still be able to look at any of the files in Notepad etc). Links are at the end.

Ok, so first up, my reference paths at the top of my TypeScript file are:
/// <reference path="../typings/fullCalendar/fullCalendar.d.ts" />
/// <reference path="../typings/jquery/jquery.d.ts" />

Now my first class, my AppGlobal class. A simple class that has a function called InitiateCalendar which does the required setup of FullCalendar:
class AppGlobal {
InitiateCalendar(calEvents: CalendarEvent[]): void {
var calendar: JQuery = $("#calendar");
calendar.fullCalendar({
header: {
left: "month,agendaWeek,agendaDay",
center: "title",
right: "today prev,next"
},
events: calEvents,
firstDay: 1,
weekMode: "fluid",
dayClick: (date: Date, allDay: boolean, jsEvent: Event, view: FullCalendar.View) => {
goToDay(calendar, date, view);
}
});
}
}

You may have noticed that InitiateCalendar is expecting an array of CalendarEvent objects. This is another class I’ve created, inheriting from the FullCalendar EventObject defined in the fullCalendar.d.ts file. Here’s my CalendarEvent class:

class CalendarEvent implements FullCalendar.EventObject {
id: any; // String/number
title: string;
allDay: boolean;
start: Date;
end: Date;
url: string;
className: any; // string/Array
editable: boolean;
source: FullCalendar.EventSource;
color: string;
backgroundColor: string;
borderColor: string;
textColor: string;
// Constructor only requires the first 5 parameters, the rest are optional (this is personal choice)
constructor(id: any, title: string, allDay: boolean, start: Date, end: Date, url?: string, className?: any, editable?: boolean, source?: FullCalendar.EventSource,
color?: string, backgroundColor?: string, borderColor?: string, textColor?: string) {
this.id = id;
this.title = title;
this.allDay = allDay;
this.start = start;
this.end = end;
this.url = url;
this.className = className;
this.editable = editable;
this.source = source;
this.color = color;
this.backgroundColor = backgroundColor;
this.borderColor = borderColor;
this.textColor = textColor;
}
}

One of things that slowed me down a little in getting this up and running, was how best to call the methods such as gotoDate and changeView. You may notice in InitiateCalendar that I am calling a function goToDate on dayClick, so here is that function:

function goToDay(calendar: JQuery, date: Date, currentView: FullCalendar.View) {
if (currentView.name !== "agendaDay") {
calendar.fullCalendar("changeView", "agendaDay");
}
calendar.fullCalendar("gotoDate", date);
}

Again, I’m not saying this IS the best. It’s just the best way I’ve thought of myself so far. If you have a suggestion, please leave a comment! 🙂 My reasons for doing it this way at this point were:

  • By saving $(“#calendar”) to a variable, I am only asking jQuery to select it once which means I am gaining a small performance increase each time I use it after that
  • Every time I want to use the variable, it’s shorter and easier to write, especially as intellisense completes it for me
  • Separating it out into a named function instead of leaving it in the anonymous function makes it accessible for unit testing if required

So the final part, at the end of my TypeScript file, I have the following:

$(document).ready(() => {
var app = new AppGlobal();
var events: CalendarEvent[] = [
new CalendarEvent(1, "Test Event 1", false, new Date(2013, 8, 1, 12, 0, 0, 0), new Date(2013, 8, 1, 13, 0, 0, 0)),
new CalendarEvent(2, "Test All Day Event 1", true, new Date(2013, 8, 2, 0, 0, 0, 0), new Date(2013, 8, 2, 0, 0, 0))
];
app.InitiateCalendar(events);
});

I hope this makes sense! As promised anyway, you can download a zip file with the Visual Studio 2013 solution here – https://dl.dropboxusercontent.com/u/88673025/FullCalendarWithTypescript.zip. Alternatively, if you’d prefer to just look at the TypeScript, you can get that here – https://dl.dropboxusercontent.com/u/88673025/App.ts

Hopefully this helps someone even if it just saves someone else doing a proof of concept 🙂 Any questions, leave a comment and I’ll try and help!





Using Bootstrap typeahead in an accordion panel

20 06 2013

I was recently creating a quick prototype when I came across this issue. If you place an input of type text inside a Bootstrap accordion, the typeahead popup is likely to get cut off by the hidden overflow on the accordion panel containing it.

Hidden overflow

The popup is being cut off by the hidden overflow value

In the image above, you should be able to see 8 test clients. As you can see, the overflow value being set on the “Advanced Options” accordion panel means you only see the first 5. The z-index being set on the ul element that typeahead pops up is of no use due to the setting of the overflow value on the parent div.

I had a look around online to see how people were getting around this issue and it was the following issue on Github that pointed me in the right direction. HOWEVER, this did not solve it for me. The following link requires you include the Twitter typeahead.js file which is different to the Bootstrap typeahead plugin included in the bootstrap.js file and you will experience some weird behaviour! https://github.com/twitter/typeahead.js/issues/273

As I said, that solution helped point me in the right direction. The events being used in the jsFiddle example linked to on the github issue page above, do not exist in the Bootstrap typeahead. So I came up with the following code to fix this issue for me, without me needing to include the Twitter typeahead.js file.

$("input.typeahead").on("keydown", function () {
   $(this).closest(".accordion-body").css("overflow", "visible");
}).on("blur", function () {
   var input = this;
   setTimeout(function () {
      $(input).closest(".accordion-body").css("overflow", "hidden");
   }, 200);
});

My code picks up all input elements with the class “typeahead” which if you’re using Bootstrap, your input elements will have. On the keydown event, it sets the overflow value of the parent div with a class of “accordion-body” (again which you will have if you’re using Bootstrap) to “visible”. On blur, it saves the firing input (this) to a variable (this is just so that it can be used in the setTimeout function). I’ve then had to set a short timeout. This is because if you don’t, the overflow is set back to “hidden” before the click on your option registers. Therefore if you click on an option outside of the accordion panel, it isn’t registered and your text box remains blank. This short timeout just allows that click to fire before setting the overflow value for the accordion panel back to hidden. The accordion will now continue to function as expected.  So now we get this…

Visible overflow

The popup now overflows over the containing div

I realise this is a little bit hacky, but until Bootstrap includes the same events in their version of typeahead as the twitter-typeahead file, it is a solution. There are rumours that in version 3 of Bootstrap, they will be using the full version so we’ll have to wait and see if that’s true.

I don’t want to make this post huge by putting in all of the HTML. My accordion is the same as the template given in the Bootstrap documentation here – http://twitter.github.io/bootstrap/javascript.html#collapse

My typeahead controls are the same as the templates given in the Bootstrap documentation here – http://twitter.github.io/bootstrap/javascript.html#typeahead

Here is my solution in JSFiddle – http://jsfiddle.net/flurg/FX66C/3/

Hope this helps someone! If you need any more help with this, leave a comment and I’ll see if I can help.





Setting MaxValue for Migrations

12 03 2013

I’ve just been using the MigratorDotNet framework for the first time. I was creating a migration that would create a new table with various new fields. One of the fields I wanted to create was to store files so therefore I wanted a varbinary(max) field. If you leave the size undeclared, it will create a varbinary(8000). The way I got around this was to create my column as follows:

Column file = new Column("BinaryFile", System.Data.DbType.Binary, int.MaxValue, ColumnProperty.NotNull);

Using the int.MaxValue gives the same result as varbinary(max). However, this doesn’t create a varbinary(max) field (at least not in SQL Server 2008 R2 which is what I am using). It creates an image field instead. This isn’t necessarily a problem, it still gives me the space I require. Importantly though, Microsoft are now advising you do not use this type in new development as it will be removed in a future version of SQL Server (see MSDN article here). We’ve weighed this up and have decided that this is not a problem for us at this time because we are developing improvements to a current system with no plans for any SQL upgrade in the future. There are also uses of the image type in other parts of the database. We have instead logged it in our technical backlog to go through and change all uses of this type at a later date. Personally, in a new project, I would not use it, just in case!

I did some searching in the hope I would find a more elegant solution (something akin to the EF Code First data annotations would have been nice) but I didn’t find anything. If anybody comes across this post, and you’ve found a nicer way to do this, please comment on here to let me know!





Sorting UK Postcodes with C#

19 11 2012

Ok, before you say anything, yes I know. It has been a long time since I posted anything remotely useful here. Well in my last job I ended up doing less development and more team management so the useful bits I came across were few and far between. In my new job I am back to development, so I should have more to post here in the future.

One of the requirements I had recently was to sort UK postcodes in ascending order. The postcodes were being stored in a list of type IEnumerable and were all strings. As you are probably aware if you are searching for this, UK postcodes are alphanumeric (NP10, NP11 etc). This means that if you try and sort the following list of postcodes: NP1, NP23, NP35, NP3, NP2, NP45, NP11

You would get the outcome: NP1, NP11, NP2, NP23, NP3, NP35, NP45

However the outcome required is: NP1, NP2, NP3, NP11, NP23, NP35, NP45

I found this brilliant blog post which provides some code under the MIT license which does the job perfectly – Natural Sorting in C#

I included his EnumerableComparer class as a Utility class in my Framework and then used the code in a similar way to this:

IEnumerable<PostcodeAllocation> allocations = GetAllAllocations();
// Declare convert string as per IanG's blog post
Func<string, object> convert = str =>
{
try
{
return int.Parse(str);
}
catch
{
return str;
}
};
allocations.OrderBy(str => Regex.Split(str.Postcode.Replace(" ", ""), "([0-9]+)").Select(convert), new EnumerableComparer<object>());

This then sorts my data as follows: NP1, NP2, NP3, NP11, NP23, NP35, NP45.

Perfect! I hope this helps someone else and a huge thanks to IanG on his blog for this great snippet of code.





My new HP Touchpad

15 04 2012

So I’ve been very quiet on here for quite a while. I’ve gotten so busy at work that I haven’t found much time to do anything here outside of work hours as I’ve been spending a lot of time doing reading on unit testing and design patterns and other things like that.

Yesterday my new purchase arrived. An HP Touchpad. I’ve got it dual booted using Cyanogen Mod 9 to run Android Ice Cream Sandwich. As you may have already guessed this is what I’m using here to test the keyboard and how responsive it is and how accurate I am on it. Other than the space key not always firing, I’m finding it pretty good. The corrections are pretty good too. Seems a lot better than my phone which is also Android, running 2.3.5. In fact using this is making me want to root my phone and get ICS on there too!

The battery life is pretty good. I used it a lot yesterday (obviously, it’s my new toy) and the battery lasted until early afternoon today. Having this is also making me want to start doing some Android development. I’ve been thinking about it for a while and now I have the perfect excuse 🙂

I am hoping I get some time to do something useful enough to warrant a post on here. I will definitely try! I hope all of you that are finding your way here through Google find some of my older posts useful. Please feel free to leave a comment saying hi and how any post has helped you!





Belated statistics for 2010

19 02 2011

This is a little late but I still wanted to post my 2010 stats up (even if just for my benefit 🙂 )

In 2009 I had 4,229 unique visitors to my blog. I am happy to announce that in 2010, that number rose to 6,403 unique visitors! As I said last year, to some people this number isn’t exactly staggering. To me however it really is. I started this blog to keep a note of all the little code snippets I thought may be useful instead of relying on my memory and reams of post it notes! It’s brilliant that it helps other people and in 2010 (end of the year excluded) I really started trying to make sure my posts could be found via search engines by trying to use tags properly and trying to write the posts so that other people could understand them!

So thank you for visiting, I really hope my blog can help you. I generally do check my comments regularly (again end of 2010 excluded!) so if you want to ask any questions about my code, need some help getting it to work or give some feedback on the site, leave me a comment and I will try and get back to you as soon as possible.

Stats for 2011 are looking good so far so lets hope we can top 2010′s stats! Bring on 2011…I should probably get writing some new posts!