by Andreas

Define a #Region in javascript files (Visual Studio 2010 / 2012)

In these times of super responsive client side processing mega javascript extravaganza web applications  you’re more than likely to end up with fairly large .js files in your projects. The standard code file in Visual Studio allows you to define collapsible sections by wrapping them with the #region / #endregion blocks. In javascript files however, you are restricted to collapsible functions only (“#region” is not recognized as anything valid):

image

Well, I just found out that that’s not entirely true. By marking a section of code (regardless of any logical blocks) and hitting CTRL + M + H you’ll define the selection as a region which is collapsible and expandable

image

by Njål

Quick row count from Microsoft SQL Database

 

Recently, I’ve been involved in a cloud provider project where I had to do a row count on a Microsoft SQL Database table with more than 50.000.000 rows in it.

Doing

SELECT COUNT(*) FROM myTable

took about 10 seconds – since it performs a full table scan.

 

Here’s an alternative way (still accurate) of doing it that takes under 1 sec:

SELECT SUM (row_count)
FROM sys.dm_db_partition_stats
WHERE object_id=OBJECT_ID('myTable')   
AND (index_id=0 or index_id=1);

 

You can run this from Microsoft Entity Framework as well:

long total = dbContext.Database.SqlQuery<long>("SELECT SUM (row_count) FROM sys.dm_db_partition_stats WHERE object_id=OBJECT_ID('myTable') AND (index_id=0 or index_id=1);").First();

by Njål

The directory specified for caching compressed content is invalid. Static compression is being disabled.

image

 

After adding this in my web.config (Azure Project)…

<staticContent>
    <mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
</staticContent>

…IIS refused to serve any static content – such as js and png files. Log entries in Event Viewer said:

The directory specified for caching compressed content
C:\Users\xxx\AppData\Local\dftmp\Resources\b503ce54-3fba-4772-beaa-415d94ffc214\temp\temp\RoleTemp\iisexpress\IIS Temporary Compressed Files\9ef2ab2d-28fc-4554-a09c-5ba867eb1d19 is invalid.
Static compression is being disabled.

The problem was that .svg files were already added to the staticContent list in my applicationHost.config – but still – the error message shown in the Event Viewer is pretty useless. There is nothing wrong with the directory specified to store compressed content.

So if you suddenly get this error – undo any changes in Web.config (remove all config under staticContent) and restart IIS (Express).

by Stian

Decimal validation with comma in MVC

20130228DecimalSeparator.svgIn MVC 3, when using jQuery validation plugin with unobtrusive validation, you will see that comma in a textbox that is bound to a decimal value will not be allowed by client side validation.

Instead of going in and changing the jquery.validate.js, you should override the default behavior by adding these lines to your own javascript file (make sure it is loaded after the valiate javascript!)

$.validator.methods.range = function(value, element, param) {
    var globalizedValue = value.replace(",", ".");
    return this.optional(element) || (globalizedValue >= param[0] && globalizedValue <= param[1]);
};

$.validator.methods.number = function(value, element) {
    return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:[\s\.,]\d{3})+)(?:[\.,]\d+)?$/.test(value);
};



This will fix your problem for the number validation and the range validation!

by Andreas

VMWare Player (free) – how to run virtual machine in headless mode

Virtual machine performance can be improved by running your virtual machine in headless mode (e.g. as a background process, without the GUI). Instead of using the console view in the VMWare Player you’ll connect via standard RDP, and in some cases achieve significant performance improvements.

There’s a small requirement to the VMWare Player preference file. You’ll find it under the following directory (at least in Windows 8):

C:\Users\[Username]\AppData\Roaming\VMware\preferences.ini

Add the following line at the bottom:

pref.vmplayer.exit.vmAction = "disconnect"

This will ensure that you only disconnect from the virtual machine when closing VMWare Player, not send it into Suspended mode.

Fire the virtual machine up as normal (throught the player), and then kill the VMWare Player process through Task Manager (closing it by clicking the X icon will not work – this will also send the virtual machine into Suspended mode):

image

 

The virtual machine is still running in the background, and you’re now able to connect via RDP.

by Aage Andre

Office 2013 – Disable Animations and Effects

While I like the new Office, I honestly loath the “design-guru” who decided to cross-fade, smooth transitions and in general make everything you do slow down, so you can look at the nice little flow of the programs.

The most irritating, for me, the Word typing animations and Excel cell-change. Luckily you can turn them off.

Go into your registry: [HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Common\Graphics]
Create a new dword: “DisableAnimations”=dword:00000001
(I also had to create the Graphic-key)

Reboot and enjoy efficiency once again.

 

by Stian

Long wait-time when taking SQL Server database offline

dbofflineWhen trying to take a SQL Server database offline, you might find yourself waiting, waiting and waiting because some process is hugging the database. This is how you fix it. Run:

ALTER DATABASE <dbname> SET OFFLINE WITH ROLLBACK IMMEDIATE

In some cases you might get an error saying:

ALTER DATABASE failed because a lock could not be placed on database 'dbname' Try again later.

After you get this error, run

EXEC sp_who2

Look for the database in the result and find the SPID for that connection, then run

KILL <SPID>

That should do the trick!

by Aage Andre

Optimizing RAM for Hyper-V

 

I’ve been trying to figure out how to allocate RAM for our guest-servers, and how much is needed for the host. I thought this was a static number, and have been pretty much running it on instinct, usually leaving 2-3GB for my hosts.

As it turns out, it’s a bit more complicated. Memory should be spread out as such:

300 MB for the Hypervisor
plus 32 MB for the first GB of RAM allocated to each virtual machine
plus another 8 MB for every additional GB of RAM allocated to each virtual machine
plus 512 MB for the host operating system running on the root partition

 

Digital Library World has a nice calculator for us here: http://digitallibraryworld.com/?p=55


											
by Andreas

Email validation – finally a .NET regular expression that works!

imageNote: this is only relevant for .NET 3.5 and earlier. In .NET 4 the System.Net.Mail.MailAddress class includes validation and will throw an exception if instantiated with an invalid address. See comments below. 

Validating an email address sounds simple, and it really is! Until your fancy validator is released into the real world and people’s actual email addresses start pouring in, instead of the three email addresses you’ve been testing while developing: your work address, your Gmail address and an old Yahoo address you created in 2001.

chris-@somedomain.com
!habla-hobla%wow@somedomain.com
!def!xyz%abc@example.com
joe_blow_@somedomain.com
love/hate=relationship@example.com
$ilovemoney1234@example.com

They are, believe it or not, all valid according to the RFC spec. That doesn’t mean that you’ll be allowed to actually register them everywhere. Some (most?) email providers have their own rules that are much stricter than the specifications, simply because it makes no sense to allow all sorts of rubbish.

But if you’re writing a system allowing people to register using their email address, and you confirm their ownership of the given address by sending a confirmation email you really can’t be any stricter than the RFC and this is where the problem lies. I was also under the impression that “blah, how often would THAT become an issue?!”, but recently I got feedback from three different users within just a few weeks that they were unable to register. So I thought I’d better find a regular expression that actually works.

I’ve tried them all.. examples from Microsoft, Stack Overflow, random forums, cooked up my own and also converted a couple from other languages. It wasn’t until yesterday I stumbled across an old blog post by Phil Haack called I Knew How To Validate An Email Address Until I Read The RFC. He did all the hard work (i.e. reading the #¤%&”¤ RFC specs), and came up with an expression that so far seems to be working. So I thought I’d better save it here, because I know I will need this one again:

string pattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|"
                + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)"
                + @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";
            
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
return regex.IsMatch(emailAddress);

 

So thanks to Phil for his efforts! Let us know if anyone finds a flaw in this one as well…

by Andreas

Why Programmers Work At Night

My brother-in-law sent me a link to an article by Swizec Teller the other day. This article was so spot on I thought I’d share it here to allow even more programmers to get a bit of insight into their own brain and some understanding of their habits.

So here goes (note that not a single word of the following text is mine):

Why Programmers Work At Night

A popular saying goes that programmers are machines that turn caffeine into code.

And sure enough, ask a random programmer when they do their best work and there’s a high chance they will admit to a lot of late nights. Some earlier, some later. A popular trend is to get up at 4am and get some work done before the day’s craziness begins. Others like going to bed at 4am.

At the gist of all this is avoiding distractions. But you could just lock the door, what’s so special about the night?

I think it boils down to three things: the maker’s schedule, the sleepy brain and bright computer screens.

The maker’s schedule

Paul Graham wrote about the maker’s schedule in 2009 – basically that there are two types of schedules in this world (primarily?). The traditional manager’s schedule where your day is cut up into hours and a ten minute distraction costs you, at most, an hour’s worth of time.

On the other hand you have something PG calls the maker’s schedule – a schedule for those of us who produce stuff. Working on large abstract systems involves fitting the whole thing into your mind – somebody once likened this to constructing a house out of expensive crystal glassand as soon as someone distracts you, it all comes barreling down and shatters into a thousand pieces.

This is why programmers are so annoyed when you distract them.

Because of this huge mental investment, we simply can’t start working until we can expect a couple of hours without being distracted. It’s just not worth constructing the whole model in your head and then having it torn down half an hour later.

In fact, talking to a lot of founders you’ll find out they feel like they simply can’t get any work done during the day. The constant barrage of interruptions, important stuff to tend to and emails to answer simply don’t allow it. So they get most of their “work work” done during the night when everyone else is sleeping.

The sleepy brain

iamge

But even programmers should be sleeping at night. We are not some race of super humans. Even programmers feel more alert during the day.

Why then do we perform our most mentally complex work work when the brain wants to sleep and we do simpler tasks when our brain is at its sharpest and brightest?

Because being tired makes us better coders.

Similar to the ballmer peak, being tired can make us focus better simply because when your brain is tired it has to focus! There isn’t enough left-over brainpower to afford losing concentration.

I seem to get the least work done right after drinking too much tea or having a poorly timed energy drink. Makes me hyperactive and one second I’m checking twitter, the next I’m looking at hacker news and I just seem to be buzzing all over the place..

You’d think I’d work better – so much energy, so much infinite overclocked brainpower. But instead I keep tripping over myself because I can’t focus for more than two seconds at a time.

Conversely, when I’m slightly tired, I just plomp my arse down and code. With a slightly tired brain I can code for hours and hours without even thinking about checking twitter or facebook. It’s like the internet stops existing.

I feel like this holds true for most programmers out there. We have too much brainpower for approximately 80 percent of the tasks we work on – face it, writing that one juicy algorithm, requires ten times as much code to produce an environment in which it can run. Even if you’re doing the most advanced machine learning (or something) imaginable, a lot of the work is simply cleaning up the data and presenting results in a lovely manner.

And when your brain isn’t working at full capacity it looks for something to do. Being tired makes you dumb enough that the task at hand is enough.

Bright computer screens

This one is pretty simple. Keep staring at a bright source of light in the evening and your sleep cycle gets delayed. You forget to be tired until 3am. Then you wake up at 11am and when the evening rolls around you simply aren’t tired because hey, you’ve only been up since 11am!

Given enough iterations this can essentially drag you into a different timezone. What’s more interesting is that it doesn’t seem to keep rolling, once you get into that equilibrium of going to bed between 3am and 4am you tend to stay there.

Or maybe that’s just the alarm clocks doing their thing because society tells us we’re dirty dirty slobs if we have breakfast at 2pm.

Fin

To conclude, programmers work at night because it doesn’t impose a time limit on when you have to stop working, which gives you a more relaxed approach, your brain doesn’t keep looking for distractions and a bright screen keeps you awake.