Posts Tagged ‘code’

Finding and dropping a constraint using a table and column name

I had a bit of a problem in work. I had to write some SQL to drop a uniqueness constraint on a column but was unsure of the constraint name (since it was auto generated with a GUID on the end). Looking at the MSDN ‘Alter table’ documentation, it seems that you need the constraint name to drop it (please correct me if I’m wrong). I knew the table and the column names, so this is what I needed to work with.

So here’s what I came up with and this did the job:

            DECLARE @constraintName VARCHAR(50)

            select @constraintName = CONSTRAINT_NAME
            from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE
            WHERE TABLE_NAME = '[YOUR_TABLENAME]' AND COLUMN_NAME = '[YOUR_COLUMNNAME]'

            IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[YOUR_TABLENAME]') AND name = @constraintName)
                EXEC('ALTER TABLE [YOUR_TABLENAME] DROP CONSTRAINT ' + @constraintName)

This worked for me since I know that the column will only have one constraint. Presumable the CONSTRAINT_COLUMN_USAGE will return multiple rows if there are multiple constraints. I also did the EXEC to get past the limitation that the DROP CONSTRAINT call doesn’t accept a variable.

If anyone has any comments/improvements on the above, I’d appreciate if you let me know.

How clean is your window (object)?

I recently wanted to see how polluted the global namespace of our web application was. By that, I mean I wanted to see how many unnecessary objects we were assigning to the window object.

To do this, I wanted to compare against a clean window object. A quick look on Google and I found this article: Getting a clean document or window Object in JavaScript. The basic idea is that you create a new iframe element, and you can use the contentWindow property of that to give you a nice clean window object. As the author states, you might want to do this to prevent the remapping of native methods but I just want it for a quick (i.e. hacky) way to see what objects have being put into my own ‘clean’ window.

What I do is create the iframe to get my clean window. Set up an object to copy across the objects from the main window object, then remove any that appear in the clean window.

Here it is in glorious, unminified code:

(function(window){
	var keys = {},
	cleanWindow,
	iframe = document.createElement("iframe");

	iframe.style.display ="none";
	iframe = document.body.appendChild(iframe);

	cleanWindow = iframe.contentWindow;
	document.body.removeChild(iframe);

	for(var keyName in window){
		keys[keyName] = window[keyName];
	}

	for(var keyName in cleanWindow) {
		delete keys[keyName]
	}

	return keys;
}(window))

And here’s a version that I’ve minified down:

(function($){var k={},w,d=document,b=d.body,i=d.createElement("iframe");i.style.display="none";i=b.appendChild(i);w=i.contentWindow;b.removeChild(i);for(var s in $){k[s]=$[s]}for(var s in w){delete k[s]}return k}(window))

This is written as self executing JavaScript and will return an object containing the objects that we worked out were added to the window.

Note: This is a very quick and dirty piece of code. Mostly it was an experiment for myself, to use the ‘clean window’ object. It won’t tell you if a native window property was changed or anything, it only compares the keys. Just remember that.

JavaScript – e.preventDefault() is NOT return false

I’ve seen a lot of people use return false in place of e.preventDefault. This is usually when dealing with setting the click event on a hyperlink. I can only think that this comes from the original JavaScript snippets of running code on a click by setting onclick="alert('hi'); return false".

This is wrong

Well – it might be wrong. It all depends on your application. As long as you know the differences in them, you should be fine:

  • e.preventDefault: this (aptly) prevents the default event from happening. In the case of a hyperlink that you want to assign JavaScript to, this will stop the link from going to the location of the link
  • e.stopPropagation: this stops the event from bubbling up. If you click on something that had a click event then using this will stop the event bubbling up and any click event that the parent containers might have.
  • return false: this is the same as calling both of the methods above.

I’ve done two examples for this:

  1. Showing the difference in e.preventDefault() and return false: This example works on the click event and shows that preventDefault and return false are actually different.
  2. Example of e.stopPropagation: This example shows a practical example of when you’d want to stop an event bubbling up. It uses event handlers on the mouseover event to show this.

Shortcut for JavaScript timestamp

JavaScript’s Date object provides a function for getting the milliseconds from the UNIX epoch – getTime():

var timeStamp = new Date().getTime();

However, there is a handy shortcut that gets the same thing:

var timeStamp = +new Date();

It makes me wonder if the +new shortcut can work for any other JavaScript object but I haven’t had a chance to look yet.

Update: Apparently it’s just the unary operator (http://xkr.us/articles/javascript/unary-add/). From the article:

The unary + operator, when used on types other than string, will internally attempt to call valueOf() or toString() (in that order) and then attempt to convert the result to a number. Thusly, the unary + operator can successfully convert many of the native JS types with certain restrictions.

Indexed IEnumerable extension

The original intention for this was to clean up some code which was calling a Select to get an Index value so that basic zebra striping of rows could be done. It return an IndexedType generic class of type T which has properties for the original object and the index value of it.

public static IEnumerable<IndexedType<T>> Index<T>(this IEnumerable<T> source)
{
	return source.Select((x, i) => new IndexedType<T>() { Item = x, Index = i });
}

And the class returned:

public class IndexedType<T>
{
	public T Item { get; set; }
	public int Index { get; set; }
}

This could be extended to include values like if the index value is even, N-Indexed values, etc but I leave that up to the imagination of the programmer.