Tuesday, 21 December 2010
Favourite Geek Jokes
Because Oct 31 = Dec 25
There are 10 types of people in the world: those who understand binary, and those who don't
Infinite mathematicians walk into a bar. The first one orders a pint. The second orders half a pint. The third orders a quarter pint. The fourth orders an eighth of a pint. the fifth orders a sixteenth of a pint. The barman sighs, and pours two pints.
Two hydrogen atoms walk into a bar.
One says, “I think I’ve lost an electron.”
The other says, “Are you sure?”
The first replies, “Yes, I’m positive…”
A cloud of Argon drifts into a bar. The barman says "Sorry, we don't serve noble gasses in here". The Argon doesn't react.
Two chemists are working in a lab. One turns to the other and asks "Know any good jokes about Sodium?". The other shakes his head and says "Na".
Werner Heisenberg is speeding down a highway, when he's pulled over by the police. The cop walks up to him and says, "Excuse me, sir, do you know how fast you were driving?" Heisenberg looks up to the officer and says, "Nope, but I know exactly where I was!"
A physicist, an engineer and a statistician go hunting. 50m away from them they spot a deer. The physicist calculates the trajectory of the bullet in a vacuum, raises his rifle and shoots. The bullet lands 5m short. The engineer adds a term to account for air resistance, lifts his rifle a little higher and shoots. The bullet lands 5m long. The statistician yells “we got him!”.
.titanic { float: none; }
Friday, 15 October 2010
JQuery and the update panel
$(function() {
$( "#datepicker" ).datepicker();
});
What they don't tell you is that this doesn't work properly if the page element on which the JQuery is acting is in an Update Panel control.
Fortunately there's a simple solution. Get a pagerequestmanager first, and use that to call the function. Again, the example is using the datepicker:
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(LoadMe);
function LoadMe() {
$( "#datepicker" ).datepicker();
});
Wednesday, 12 May 2010
Bit Field Enumerations
The programming construct behind the idea is called a Bit Field. It's simple, really. An enumeration is basically just a list of numeric values linked to text labels, and the usual form is to increase the numeric values incrementally, so ...
Public Enum ColoursEnum
Clear = 0
Red = 1
Blue = 2
Green = 3
Yellow = 4
Purple = 5
End Enum
But what if, instead of assigning your numeric values incrementally you decide to double them up each time, creating a number series which can be represeted by a bit:
Public Enum ColoursEnum
Clear = 0
Red = 1
Blue = 2
Green = 4
Yellow = 8
Purple = 16
End Enum
Looks a bit odd, no? Well whilst it does *look* odd you can do something clever with this series of values: the gap between each one means that if you wanted to, say, have an Enum with more than one value each potential value has a unique numeric identifier created by adding the values together. A numeric value of 12, in the above example, can only be made up by adding Green and Yellow. A numeric value of 19 can only be reached by adding Red, Blue and Purple. A numeric value of 2 can only be reached if the Enum is Blue and Blue alone.
So if you create a single database field to hold a single int, by making it a bitwise field you can make it hold more than one value. This has a multitude of uses: I came across it whilst trying to create a "status" column for a database object that could in fact have more than one status at once. Rather than the ugly approach of creating a boolean column for each potential status, I can have a single status column, link it to an Enum and have a bit field join to make it hold multiple values. Neat!
Be aware that in such an enumeration the "zero" value has to be unique - it can't be a part of any other combination of numbers. So you need to assign zero a value and it needs to be some sort of "resting" value indicating the enumeration is effectively empty - even if that means linking it to a text flag like "empty" or "not set".
However you may think you've spotted a flaw here: am I not going to have to introduce some slightly annoying and convoluted logic somewhere to take the value from the database, look at the enumeration and decide what set of values my field is actually holding? Thankfully the .net framework automates all of this for us.
All you have to do is add a Flags attribute to the enum:
_
Public Enum ColoursEnum
Clear = 0
Red = 1
Blue = 2
Green = 4
Yellow = 8
Purple = 16
End Enum
And .Net does all the work for you. It's slightly different in C# by the look of things: you need to use [FlagsAttribute] instead of
.Net will now treat each potential set of values from this enumeration differently. That is to say that if you loop through all the potential values of Colours above you'll get separate entries for Red, RedBlue, RedBlueGreen, RedGreen and so on.
You can also set your Enum to hold multiple values by using a bitwise "OR" operator (a pipe |):
Dim myRed as ColoursEnum = ColoursEnum.Red
Dim myBrown As ColoursEnum = ColoursEnum.Red | ColoursEnum.Purple
And in the same manner you can use a bitwise "AND" operator (an ampersand &) to isolate a single value and check it. Colours are a bad way of demonstrating this but hopefully the logic will read through.
Dim myBrown As ColoursEnum = ColoursEnum.Red | ColoursEnum.Purple
Dim myRed As ColoursEnum = myBrown & ColoursEnum.Red
'This will set MyRed equal to Red, since it matches something in the enum
Dim noColour As ColoursEnum = myBrown & ColoursEnum.Green
'This will set noColour equal to Clear since green doesn't match anything in the enum
Friday, 19 February 2010
URL Routing Niggles
The basics of how to do this are well documented, so I won't bore you with them. If you don't know how it's done, I'll let 4-Guys bore you instead.
Trying to implement it I ran into a couple of small hurdles though, which I thought I'd document for reference. It's a little embarrassing really because both of these things are quite clear if you read the documentation properly instead of skimming and getting down to trying it out.
Optional & Extensible Parameters
The first is how to make parameters optional. Let's say for example that I have a search function with two parameters: firstname and surname. I might want the url for that search function to look like this:
/people/search/(searched text for firstname)/(searched text for surname)/
Let's further assume that I have various other pages I want to map inside the people folder, so things like:
/people/summary/
/people/management/
So I define my virtual URL like this:
Dim urlPattern As String = "people/{action}/{firstname}/{surname}"
And as soon as I do that, /people/summary/ fails. It's expecting a firstname and a surname as part of the URL and doesn't recognise the address.
To solve thisWe add a dictionary to the route value, like so:
reportRoute = New Route(urlPattern, New ReportRouteHandler)
reportRoute.Defaults = New RouteValueDictionary(New With {.firstname = "", .surname = ""})
This instructs the route that the firstname and surname parameters can be replaced with a default - in this case an empty string - if they're missing. And of course this being a dictionary you can add as many key/value pairs as you need.
But there's still one more thing. What if we might want to include some additional information in that URL, or even just make sure that longer URLs fail gracefully? At the moment /people/search/matt/j/thrower/ will fail. To solve this, add an asterisk to the final part of your virtual URL:
Dim urlPattern As String = "people/{action}/{firstname}/{*surname}"
And voilĂ ! The * indicates that the final parameter is extensible and can be of any length.
Getting Values from Parameters in Target Pages
The other thing that you'll probably want to do with this is to have a target page read the items in the url parameter collection. Right now you can access the values in {action}, {firstname}, {lastname} and so on inside route handling functions, but the target web form won't know about them.
My first approach to this was to change the parameters into querystrings and include them in the redirect part of the route handler:
Dim handlerUrl As String
Dim hand As Web.IHttpHandler
Select Case CStr(routeData.Values("action")).ToLower()
Case "search"
handlerUrl = String.Format("/people/search.aspx?firstname={0}&surname={1}", routeData.Values("firstname"), routeData.Values("surname"))
End Case
hand = DirectCast(System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(handlerUrl, GetType(Web.UI.Page)), Web.IHttpHandler)
Which blows up in your face because the querystring isn't a valid virtual path.
The way round this is to utilise a handy collection in HttpContext called Items, which allows you to store key/value pairs of data:
Dim handlerUrl As String
Dim hand As Web.IHttpHandler
Select Case CStr(routeData.Values("action")).ToLower()
Case "search"
handlerUrl = "/people/search.aspx"
For Each urlParm In requestContext.RouteData.Values
requestContext.HttpContext.Items(urlParm.Key) = urlParm.Value
Next
End Case
hand = DirectCast(System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(handlerUrl, GetType(Web.UI.Page)), Web.IHttpHandler)
And you can pick these up in your target page like so:
Dim firstname As String = HttpContext.Current.Items("firstname").ToString
Dim surname As String = HttpContext.Current.Items("surname").ToString
Friday, 12 February 2010
Quey across a join in nHibernate
Stupid nHibernate.
So, after spending ages trying to get something as simple as a rowcount, today I have spent an equally frustrating period trying to get a results set which does a logic OR operation across a joined table. Something as petty as this, in SQL terms:
SELECT * from product p
inner join sku s on s.id = p.id
WHERE p.Name like '%widget%'
OR s.SkuCode like '%wd_%'
The issue arises because even though my mappings are correct, nHibernate throws a wobbler at you if you start with Product and try and get it to recognise that it should be able to filter on a field in the joined sku table. This, for example, compiles but fails horribly even though to my mind it's the intuitive way of presenting the above query in nHibernate:
Dim results As ArrayList = session.CreateCriteria(Of DataTransferObjects.Product) _
.Add(Expression.Or( _
Expression.Like("Name", "widget"), _
Expression.Like("SkuCode", "wd_"))) _
.List()
No, what you have to do is set up a CreateAlias to the table and use that:
Dim results As ArrayList = session.CreateCriteria(Of DataTransferObjects.Product) _
.CreateAlias("Skus", "sku") _
.Add(Expression.Or( _
Expression.Like("Name", "widget"), _
Expression.Like("sku.SkuCode", "wd_"))) _
.List()
Certainly not the way I'd expect a "highly intuitive", productivity-enhancing framework to function. Not by a long shot.
I could have done the required work by creating a couple of custom data handling objects and accompanying T-SQL stored procedures in about ten minutes. To do the same thing in nHibernate has taken two days. What's that about enhancing productivity?
nHibernate Projections in VB.net
Anyway, just in case some poor soul has the same problem and gets stuck, this is how you do it:
Dim pResults As IList = session.CreateCriteria(GetType(dto.Product)) _
.SetProjection(Projections.RowCount()).List()
Of course "dto.Product" is a custom class I'm using that's specific to what I'm trying to do, so stick your own in there and you should be good to go.
Tuesday, 31 March 2009
Date Conversions in SQL
Stupid Excel.
Anyway, on with the show.
CONVERT(CHAR(19),GETDATE()) -- gives 31 March 2003 11:19
CONVERT(CHAR(11),GETDATE(),106) -- gives 31 March 2003
Thursday, 12 March 2009
A SQL Split function
CREATE FUNCTION fnSplit(@Data nvarchar(4000),
@Delimiter varchar(10) = ',')
RETURNS @tblSplit TABLE
(ItemId int IDENTITY(1, 1) NOT NULL PRIMARY KEY,
Item nvarchar(4000) NULL)
AS
BEGIN
DECLARE @Delimiter2 varchar(12),
@item nvarchar(4000),
@iPos int,
@DelimWidth int
--had to do this cuz if they send in a > 9 char delimiter I could not pre and post append the % wildcards
SET @Delimiter2 = @Delimiter
SET @Delimiter2 = ISNULL(@Delimiter2, ',')
SET @DelimWidth = LEN(@Delimiter2)
IF RIGHT(RTRIM(@Data), 1) <> @Delimiter2
SELECT @Data = RTRIM(@Data) + @Delimiter2
IF LEFT(@Delimiter2, 1) <> '%'
SET @Delimiter2 = '%' + @Delimiter2
IF RIGHT(@Delimiter2, 1) <> '%'
SET @Delimiter2 = @Delimiter2 + '%'
SELECT @iPos = PATINDEX(@Delimiter2, @Data)
WHILE @iPos > 0
BEGIN
SELECT @item = LTRIM(RTRIM(LEFT(@Data, @iPos - 1)))
IF @@ERROR <> 0 BREAK
SELECT @Data = RIGHT(@Data, LEN(@Data) - (LEN(@item) + @DelimWidth))
IF @@ERROR <> 0 BREAK
INSERT INTO @tblSplit VALUES(@item)
IF @@ERROR <> 0 BREAK
SELECT @iPos = PATINDEX(@Delimiter2, @Data)
IF @@ERROR <> 0 BREAK
END
RETURN
END
You call it like this:
select item from [reference]..fnSplit( @variable, ',' )
Where @variable is a varchar containing your comma-delineated string. Useful for sticking directly into IN clauses.
Tuesday, 10 March 2009
Reading XML with XPath
using System.Xml.XPath;
XPathDocument xDoc = new XPathDocument(“filepath”);
XPathNavigator xNav = xDoc.CreateNavigator();
Xnav.MoveToRoot();
Xnav.MoveToFirstChild();
do
{
//do stuff .. like xNav.GetAttribute(""AttributeName", "");
}
while (Xnav.MoveToNext());
So, load your xml file by replacing "filepath" with the path of the - ahem - file you want to load. MoveToRoot and MoveToFirstChild do exactly what you'd expect them to, and you can obviously vary these commands depending on where you want to start reading. Then the do-while loop should pass through each node in turn, allowing you to access its attributes and such.
Monday, 9 March 2009
SQL Cursors
Beware though that SQL cursors are resource-intensive. If efficiency at the database end is important to you, it might be better to return the data and loop through it in the handling code. However, there are times when you need to get data, loop through it and then do something else at the DB end with the results of the loop. In those cases using a cursor is likely to be less intensive than the round trips involved in two separate back-and-forth trips to the database server.
Declare c1 cursor read_only
For
Select from
-- select statement picks up
--rows to sort through
Declare @trackingID int
-- declare a variable to hold the primary key
-- of the rows you’re returning
Open c1
Fetch next from c1 into @trackingID
While @@fetch_status = 0
Begin
--do something with the tracking variable,
--such as using it to select some
--data or do an update or somesuch
Fetch next from c1 into @trackingID
End
Close c1
Deallocate c1
Tuesday, 3 March 2009
Writing files to disc
using System.IO;
FileStream myStream = new FileStream("insert File path here", FileMode.Create);
StreamWriter myWriter = new StreamWriter(myStream);
myWriter.Write("Some Text");
myWriter.Write(Environment.NewLine);
//this creates a new line. Duh!
myWriter.Close();
myStream.Close();
So put the target path into "insert File path here" and put your text into where it says "some text". Obviously you can keep adding as much text or new lines as you need.
Friday, 27 February 2009
Finding start of week in T-SQL
Wah! So, the first two posts turn out to be HTML posts! Well, probably because I'm not doing much actual dot net programming right now :). Besides, this was too neat not to document. It's a line of SQL commands which will determine the first day of the current week. Could be extended to find the first day of any given week.
declare @weekStart datetime
select @weekStart = dateadd(dd, (datepart(dw, GetDate()) * -1) + 2, GetDate())
select @weekstart
You can also put some more jiggery-pokery round it in order to get midnight on the first day of the week:
declare @weekStart datetime, @now datetime
select @weekStart = dateadd(dd, 0, datediff(dd, 0, dateadd(dd, (datepart(dw, GetDate()) * -1) + 2, GetDate())))
select @weekstart
Thursday, 26 February 2009
Search Stored Procedures in T-SQL
So, I started a blog called "dot net notes" and my first post is about SQL. Doesn't look good but in honesty this is one of the most useful things I ever learned in SQL - how to do a blanket search of the text in all the stored procedures in a given database.
SELECT Distinct SO.Name
FROM sysobjects SO (NOLOCK)
INNER JOIN syscomments SC (NOLOCK) on SO.Id = SC.ID
AND SO.Type = 'P'
AND SC.Text LIKE '%text_to_search_for%'
ORDER BY SO.NameJust replace "text_to_search_for" with, well, whatever you want to search for and you're good to go. Immensely helpful for tracking down chains of stored procedures which call each other, or examples of something you've done before in SQL but can't quite remember, or finding all the SP's in a database which reference a particular table or field. With enough tweaking it'd probably make you tea in the morning and wipe your arse for you.
Wednesday, 25 February 2009
Introduction
And I figured I'd move it into a blog.
Why? Well, partly because it's easier for me to index and find things in a blog format. Partly because it's stuff other people might use. So if you find something useful on here, just enjoy. No need to comment unless I've made a fundamental error :)