SyntaxHighlighter

Wednesday, 14 December 2011

PHP header 200 Status Not Being Sent

I'm having a real mare with this PHP site I am working at the moment. Having constant configuration problems - grrr!

I am using a .htaccess file to handle the a 404 (ErrorDocument 404 /404.php). It's used to handle friendly URLs mainly. One of the other things I use it for is allowing JavaScript files to be PHP processed before they are served to the browser. This is dead useful as I can modify and customise the scripts where required.

Anyway...
In the code I use header("HTTP/1.1 200 OK") and in nearly all instances that works fine. Except for when it is processing the the JavaScript files. After massive annoyance and trying loads of different things, it turns out there is a bug in PHP 5. As they suggest at the bottom, the workaround is:

header("Status: 200 OK");

Fixed!

Tuesday, 8 November 2011

Add a Border to a Panel Using .NET Compact Framework

After spending quite some time working out how to add a border round a panel control in the .NET compact framework, I finally got it working. It's pretty easy to be honest.

VB.NET
Using g As Graphics = e.Graphics
    Using p As New Pen(Color.Black, 1)
        g.DrawRectangle(p, 0, 0, MyPanel.Width - 1, MyPanel.Height)
    End Using
End Using

C#
Using (Graphics g = e.Graphics) {
    Using (Pen p = New Pen(Color.Black, 1)) {
        g.DrawRectangle(p, 0, 0, MyPanel.Width - 1, MyPanel.Height);
    }
}

You need to make sure that this code is put in the Paint event of your panel.

Monday, 31 October 2011

HSBC API: PayerTxnId is not in a valid base64 encoding

That pesky HSBC API caused me a lot of grief when I first had to set it up on a client site. For various reasons I ended up using the XML method of performing the transaction.

Anyway...
Having recently implemented the 3D secure (Payer Authentication Specification (PAS)) I was getting a PayerTxnId 'LOADS_OF CHARS' is not in a valid  base64 encoding. The PayerTxnId is pulled from the posted data from HSBC. It comes from the XID field.

It took me a while to spot it and, to be honest, I thought I would have to contact HSBC technical support yet again (who , by the by, are very good). But I did spot it! There was a space in the string. I swapped that out for a + and hey presto, the HSBC API processed it just fine.

Wednesday, 19 October 2011

Block IP Addresses on Windows Server 2003

A big thank you goes out to CodeHill today for allowing me to find out how to easily block IP addresses with built-in Windows server functionality.

The idea is that you create an IP Security Policy on the server and add each IP, range or subnet to it. Perfect :)


Tuesday, 18 October 2011

Unicode Characters in an Email Subject using PHP and PEAR

I've been working on a PHP site recently where I have had to cater for all languages and more importantly Unicode languages.

So after quite a lot of messing about and hunting around I found that I needed to do the following with the subject:

if (function_exists("mb_internal_encoding"))
 mb_internal_encoding("UTF-8");
if (function_exists("mb_encode_mimeheader"))
 $subject = mb_encode_mimeheader($subject, "UTF-8", "B", "\n");

Obviously if you know if the mb_* functions are available, then you can do away with the if statements.

This works using the PEAR Mail_Mime library. I haven't tested it with the built-in PHP mail function. I would assume it does not work.

Tuesday, 4 October 2011

How To Reset an Identity Column in MSSQL / SQL Server

Something I often find myself needing to do is reset the identity column on auto incrementing field in MS SQL / SQL Server.

There are a couple of ways of doing it:
  1. If you are emptying the table, instead of using a DELETE, use a TRUNCATE. That will automatically reset the identity.
  2. The ID can be set to a specific number by using DBCC CHECKIDENT([TABLE_NAME], RESEED, n). Where n is the number that is to be set.
If you already have data in the table and you want to make sure that the sequence is followed, then use this:
DBCC CHECKIDENT([TABLE_NAME], RESEED, 0)
DBCC CHECKIDENT([TABLE_NAME], RESEED)

Monday, 19 September 2011

Android: Starts in Car Mode

When I turn on my HTC Desire android phone, the device is automatically in car mode. I get a notification item allowing me turn it off, so that does the job. But I couldn't find any way of stopping it starting automatically.

Now if like me, you couldn't find the "dock" app (that seems to be mentioned all over the Internet) anywhere you need to do following:

  1. From the home screen: Menu > Settings > Search > Searchable Items
  2. Make sure the Settings options is checked
  3. Press the physical search key (usually a magnifying glass)
  4. Click the Google logo and choose Settings
  5. Type car
  6. Choose Dock
  7. Make sure the Auto-launch option is un-checked
Hey presto!
Android version: 2.2

Thursday, 1 September 2011

Compressing JPG/JPEG Images

If you need to compress and reduce the disk footprint and reduce bandwidth use, then check out JPEGmini. They are managing a 5 times reduction in the size of images!

Monday, 22 August 2011

Asus EEE Pad Transformer Quick Review 2

Following on from my original Asus EEE Pad Transformer quick review, I thought I would write another quick one. I hadn't long had the tablet when I did the first one and I have now had it for a sensible amount of time and have used it for what I had planned.

I had planned to use it not only as a browser for home use (for which it is superb), but also as a tool for when I need to work remotely.

My biggest gripe when I first got it was the lag when typing with the keyboard docked and using the browser. Typing with the keyboard in all other applications is fine. It's fine with Polaris Office and it has an excellent response time. I installed Dolphin Browser which is far superior and the gesture action is pretty useful too. The lag wasn't anywhere near as bad and the general usability of the browser (when using the blogger blogging interface for example) was much better. There is still lag, but I put that down to the speed at which the device/browser can process JavaScript. As typing into in non-JS based box is fine and there is no lag.

I also installed a different movie player. The pre-installed one will only play certain types of files - which for the most part is nether use nor ornament! I am currently using MoboPlayer.

The battery lasts really well. With it's current use it lasts around a week. It is left on stand-by all the time. It gets used one day a week for a working day - not constantly, but a reasonable amount and is used adhoc in the evenings for email checking, twitter, etc.

The reality is, that I still really can't pick fault with it. I will be away on Holiday for two weeks soon, so that will be a real good test of it's usability and battery life. Especially as we are likely to get through a 13 episode season of something or other...

Monday, 15 August 2011

How to Export Scheduled Tasks on Windows Server 2003

If you need to export your scheduled tasks from Windows, like I have just needed to, use this from the command prompt:

schtasks /query /FO CSV /V >sched_tasks.csv

This will output to a comma-delimited file with all the tasks in it to the current folder called sched_tasks.csv.

The "SendUsing" Configuration Value is Invalid

I recently moved a VBScript script from one server to another. The new server did not have an SMTP server on it. When I ran the script (which emailed) I got a The "SendUsing" Configuration Value is Invalid error. Having already spent sometime recently using VBScript to email via Gmail, it was an easy fix for me. I specified the server and port and off it went!

Dim objMessage

Set objMessage = CreateObject("CDO.Message")
objMessage.Subject = "MY_SUBJECT"
objMessage.From = "FROM_ADDRESS_SAME_AS_USER_NAME"
objMessage.To = "TO_ADDRESS"
objMessage.TextBody = "MY_MESSAGE"

objMessage.Configuration.Fields.Item( _
"http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objMessage.Configuration.Fields.Item( _
"http://schemas.microsoft.com/cdo/configuration/smtpserver") = "IP_OR_NAME_OF_SERVER"
objMessage.Configuration.Fields.Item( _
"http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objMessage.Configuration.Fields.Update

out = objMessage.Send
Set objMessage = Nothing

Thursday, 11 August 2011

CSS Colour Chart


Not being a designer type chappy I often find it hard to work out what colours to use and then what their colour code is. While I was on my Internet travels the other day I found this little gem with a whole load of colour codes on it: http://www.somacon.com/p142.php


While you're at it ColorPic is another sweet little tool, to grab colour that yuu can see on screen.


Tuesday, 9 August 2011

woff 404 Font Not Found

I noticed recently that a site I work on that uses a woff font was getting a 404 not found error in Chrome. It was also giving a Resource interpreted as Font but transferred with MIME type application/octet-stream. I spent ages hunting around the forums and found no solution to it.


The fact that I was getting a 404 was the oddest thing and made me think that IIS wasn't serving the font correctly (it was being used by the browser none the less). So I went about checking to see what .woff MIME type was set in IIS. The local computer had no MIME Type handling for .woff so I added it (Right-click > Properties > MIME Types... Extension: .woff and Type: application/x-font-woff). That didn't fix it :(

I right-clicked the Default Web Site > Properties > HTTP Headers > MIME Types... and added the new extension there also (Extension: .woff and Type: application/x-font-woff). Reloaded the page and the warning and error had gone - happy days!

Update...
Thanks to the comment below added by RyanonRails, here is an example web.config (http://pastie.org/4081017):
<system.webServer>
    <httpErrors errorMode="Detailed" />
    <staticContent>
      <mimeMap fileExtension=".coffee" mimeType="coffeescript" />
      <mimeMap fileExtension=".woff" mimeType="application/x-font-woff" />
    </staticContent>
  </system.webServer>
</configuration>

Monday, 1 August 2011

How to Share Files on Blogspot / Blogger

I keep needing to find a way of sharing files through Blogspot / Blogger that isn't costly and is dead easy - well I think I've found it - boxify.me. This is a great service, that requires no registration, is free and there is no quota - superb!

All you literally need to do is is click the "Start sharing for free" button and hey presto you're off! By default you get given a crazy link to use, but you can click the "rename" link at the top and choose something more suitable (http://boxify.me/box/techygypo).

So here's a link to my first file: http://uploads.boxify.me/7831/techygypo.png

And here's the file in question


Thank you boxify.me - stunning work!

Friday, 22 July 2011

Quick Review of Asus EEE Pad Transformer

Well, I've not long opened my new Asus EEE Pad Transformer and so far everything is really sweet with it! My major gripe at the moment is the lag between the docked keyboard and the browser - it's shockingly slow!

That aside, the tablet iteself is really nice and the on-sreen keyboard works with no lag :) The docked keyboard randomly makes you go somewhere else on the screen (especially in the browser) and I keep end up typing something in the address bar - well annoying!

I can pretty much second what everybody else has said on their reviews of this device - and honestly - it is really nice. I purchased it to use it as a work tool as well an internet browser. So TeamViewer is on and working a treat on the nice 10.1" screen.

I'll no doubt put more details with how I get on with this as time goes by...but for now, it's play time!

Friday, 15 July 2011

Sending Email using VBScript via Google Apps Mail / GMail

Following on from my previous post Sending Email using ASP.NET via Google Apps Mail / GMail, I have needed to send an email via GMail / Google Apps using VBScript. So here it is...

Dim objMessage

Set objMessage = CreateObject("CDO.Message")
objMessage.Subject = "MY_SUBJECT"
objMessage.From = "FROM_ADDRESS_SAME_AS_USER_NAME"
objMessage.To = "TO_ADDRESS"
objMessage.TextBody = "MY_MESSAGE"

objMessage.Configuration.Fields.Item( _
"http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objMessage.Configuration.Fields.Item( _
"http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
objMessage.Configuration.Fields.Item( _
"http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
objMessage.Configuration.Fields.Item( _
"http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
objMessage.Configuration.Fields.Item( _
"http://schemas.microsoft.com/cdo/configuration/smtpusessl") = true
objMessage.Configuration.Fields.Item( _
"http://schemas.microsoft.com/cdo/configuration/sendusername") = "MY_USER_NAME"
objMessage.Configuration.Fields.Item( _
"http://schemas.microsoft.com/cdo/configuration/sendpassword") = "MY_PASSWORD"
objMessage.Configuration.Fields.Update

out = objMessage.Send
Set objMessage = Nothing

Thursday, 14 July 2011

Linux / Unix Commands

Found myself the last few days having to use a lot of Unix commands and have been using this site to help me with commands and syntax: http://www.computerhope.com/unix.htm#04

Friday, 24 June 2011

How To Enumerate / Iterate an Enum

I often find myself needing to iterate/enumerate an enum. It's dead easy, but seem to always forget! What a fool ;)

Anyway, here ya go...

Public Enum MyEnum
    Jim = 0
    Bob = 1
End Enum

For Each e As MyEnum in [Enum].GetValues(GetType(MyEnum))
    Console.Write(String.Concat(e.ToString(), "=", Int32.Parse(e)))
Next

The GetValues method is quite useful as you can also get stuff like the length from it:
[Enum].GetValues(GetType(MyEnum)).Length.

The C# is pretty much the same just that [Enum] has no square brackets around it.

Wednesday, 22 June 2011

Auto Trimming - Whitespace Removal in SQL Server/MSSQL

I got really angry about this one yesterday as I can't see one possible reason why this "feature" would be required.

If you run this script, the whitespace padded string is also returned along with the unpadded string.

CREATE TABLE #t ([col1] varchar(100))

INSERT INTO #t ([col1]) VALUES ('hello')
INSERT INTO #t ([col1]) VALUES ('hello     ')

SELECT '''' + [col1] + '''', LEN([col1]), DATALENGTH([col1])
FROM #t

SELECT * FROM #t WHERE [col1] = 'hello'
SELECT * FROM #t WHERE [col1] = 'hello     '

DROP TABLE #t


How can this possibly be right? If I want 'hello     ' to be returned, then return 'hello     ' not 'hello'. These are two very different strings!

Peoples arguments are why would want to save that and other such silly statements. My philosophy is, if I can think of it, it will happen! I can think of many cases where it would be beneficial to have the padding - dealing with old systems or external systems over which control is not possible.

Now I know that SQL Server does this stupid thing, I can account for it - but seriously - why?? It's stupid!

Oh and ANSI_PADDING - makes no odds!

Thursday, 16 June 2011

Clear / Remove Recent Projects in Visual Studio

For those of you still unlucky enough to be using Visual Studio 6 out there this is how to clear the recent Visual Basic projects from the recent projects list:

  1. Run regedit from Start > Run
  2. Go to KEY_CURRENT_USER\Software\Microsoft\VisualBasic\6.0\RecentFiles
  3. Delete or change the paths as necessary

For more recent versions of Visual Studio, clear the recent project list by doing this.

Tuesday, 14 June 2011

MSSQL Saving Change is not Permitted (Prevent)

This was a cheeky one I came across today. Where I was getting the following message from SQL Server 2008 in the table designer:
Saving change is not permitted. the changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that cant be re-created or enabled the option Prevent Saving changes that require the table to be re-created.
The solution is to change the setting by using the menu: Tools > Options > Designers, then unchecking the "Prevent saving changes that require table re-creation" box.


 Guessing it's not a problem and more like a feature. Little bit odd, but I can understand why...

Thursday, 9 June 2011

Website Availability Monitoring

I was looking for a tool that would easily monitor the availability of a website that I work on. This particular site has a tendency to become unavailable. Usually some kind of network related issue.

Anyway...
After some hunting around I came across www.siteuptime.com. They have a range of packages, but I used the free one as that gave me enough for this site. It's checking every 30 minutes and the reporting seems pretty much spot on. The service will email me if the site becomes unavailable, so hopefully I'll spot it much sooner now!


Tuesday, 7 June 2011

System.Web.Services.Protocols.SoapException: The permissions granted to user 'IIS APPPOOL\MyUser' are insufficient for performing this operation

I had this error (System.Web.Services.Protocols.SoapException: The permissions granted to user 'IIS APPPOOL\MyUser' are insufficient for performing this operation) and took me a while to work out what to do to fix it. All the references I found  to it were relating to SharePoint.

In my instance I had added a web reference to my application to make use the reporting services (SSRS) web service (http://localhost/ReportServer/ReportExecution2005.asmx). Although it was working locally, it was not working when I deployed it to the dev or live server.

Turns out the account that is used by the reporting services service account needed to be the same as the account that the application pool was using.

So check the service account in the reporting services configuration tool:


Then from within the IIS, change the identity that the application pool is using (right click the pool and choose Advanced Settings...):


FYI, here's the full error message:
System.Web.Services.Protocols.SoapException: The permissions granted to user 'IIS APPPOOL\MyUser' are insufficient for performing this operation. ---> Microsoft.ReportingServices.Diagnostics.Utilities.AccessDeniedException: The permissions granted to user 'IIS APPPOOL\MyUser' are insufficient for performing this operation. at Microsoft.ReportingServices.WebServer.ReportExecution2005Impl.LoadReport(String Report, String HistoryID, ExecutionInfo2& executionInfo) at Microsoft.ReportingServices.WebServer.ReportExecutionService.LoadReport(String Report, String HistoryID, ExecutionInfo& executionInfo)


Monday, 6 June 2011

Remove Importance Markers from GMail

GMail recently introduced the importance marker as part of their priority inbox feature. I accepted the setting to see how it worked. It wasn't for me so I wanted to turn it off. So this is how to do it...

Go to Mail Settings and choose the Priority Inbox tab. Then set the Importance markers option to No markers and click Save - Happy days :)


Thursday, 19 May 2011

Compacting a Microsoft Virtual PC (VPC) Hard Disk

Depending on how busy your VPC installation is, it can grow massively beyond the size it really needs to be, so periodically it is very useful to compact it.

So here is an MSDN blog on how to compact a virtual PC image.

Wednesday, 20 April 2011

Format of the initialization string does not conform to specification starting at index

When I recently moved a site from the dev location to the live location, I got presented with Format of the initialization string does not conform to specification starting at index when trying to make a database connection.


This obviously wasn't happening on the live and the connection string, which was in the Web.Config file, was correct. I was using SQL authentication and the password had both semi-colons (;) and ampersands (&) in it. I wasn't sure which character was causing the problem. As I was able to, I changed the password for the user (removing the ;&). All worked a treat then :)

Tuesday, 19 April 2011

Test a POP3 Connection (Telnet)

I often find myself needing to be able to check a username and password combination for somebodies email connection (normally because they have forgotten their password - again!). A really quick and easy way to do this is using telnet. Here's the easiest way to do it, from the DOS/command prompt:

> telnet mail.mydomain.com
> user my_user_name
> pass my_password


At this point, if all is good, you will have made a successful connection. Show all messages as a list using:

> list

If you want to see the contents of a specific mail then use:

> retr mail_item_number

If you leave the connection with no activity then it close the connection itself, but preferably use:

> quit

There are some more telnet commands here. Also, if you using an IP address, you may well have to use a port number (usually 110). e.g. 123.123.123.123 110

Thursday, 7 April 2011

Could not establish trust relationship for the SSL/TLS secure channel with authority

I recently had this error (Could not establish trust relationship for the SSL/TLS secure channel with authority) when trying to make a remote call from a C# web app. I hunted around and came across this article on thejoyofcode.com.

ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(
    delegate
    {
        return true;
    }
);

So I used the suggested code to bypass the certificate verification, but got a trust level permission error. In order to get round that I modified the Web.Config file to have the trust level set to Full.

Just for the record, this is a quick and dirty hack while I sort out what the actual problem is ;)

Wednesday, 6 April 2011

Free File Recovery

We've all been there - deleted a file we shouldn't have - oops! Well, thanks to this article on LifeHacker we can take a big sigh of relief and use MiniTool Power Data Recovery.


It's free for personal use and chargeable otherwise.

Thursday, 31 March 2011

Microsoft Image Composite Editor

I came across the Microsoft Image Composite Editor courtesy of @bbcclick. It allows you to very easily put together large landscape images. It was quite happy to take these 3 images:


And turn them into this:



It does all the alignment and colour standardising itself - happy days :) It can do other stuff too and I would argue that the join lines are impossible to see.

Here's another:


Friday, 18 March 2011

Changing the RAM/Memory Setting in Microsoft VPC

I recently added a shed load more memory to my lappy (thanks Orca), so I finally got round to increasing the memory on the various VPCs I use. So I did the usual of going to the settings, but the memory slider (to choose how much you want to assign) was not there. Not disabled. Not there at all!

In the end I removed the VPC (I didn't physically delete it, just removed it) and added it again, using the wizard. Hey presto, just like magic, I could change it again.

It's a bit like the old "have you turned it off and on again?"...

Monday, 28 February 2011

I Forgot What Access Was Like...

I haven't used MS Access for a fair while now. There was a time when I used to have use it loads. Thankfully not so much now. The more the years have gone on the more the glorified filing system has got annoying. I remember the good old days of 97 when it did what it said on the tin and didn't try to be too clever for it's own good.

I have had the unfortunate opportunity of using it again today in anger. What a ball-ache! That much of a ball-ache that I decided to blog while I, once again, wait for this update query to run (which would take a matter of seconds in SQL Server). 20 minutes in and I'm slightly bored!

That coupled with my previously stated hatred of IIf, that got right on my tits! So another annoyance to add to that is that you can only have up to 6 nested IIf statements - great! I needed 36. Switch was no good either - that only goes up to 15 (at least in the query editor anyway).

So regular crashes and constant "not an updateable query" messages later - I'm still waiting... Roll on tomorrow so I can get back to a real database and a proper programming language!

Friday, 4 February 2011

Blogger App on Android

Finally here! An android app for Blogger >> http://market.android.com/details?id=com.google.android.apps.blogger

So in honour of it here is a post using it.

Biggest issue far is that there is no formatting - not even basic stuff. But I'm sure that will come...and existing posts aren't available to view.

Thursday, 3 February 2011

If You Can Think Of It, It Will Happen!

Just had a really good one :)

If there's a faint possibility that a parameter for a routine might change, I whack it in the config. Now doing what I do means I work with a lot of different types of coders some good (not many) and some bad (surprising how many!). Anyway, one particular guy is one of those why would they ever want to do that or what's the point, that'll never happen types of guys. Fine - if he wants to do as little possible then that's fine. But. And it's a big but.

Today, the remote mail server they use for emailing from within their web applications has been changed and no longer allows remote mails to sent. Oops!
So all smug I say "just swap the mail server address that you'll have used in your config to use localhost - everybody's happy"
Him - guess what it was...drum roll..."like that's gonna happen, they're all hard coded, gonna take ages to swap all them!"
Me (raising my eyebrows with a small lips twist): "oh well..."

So I feel really good about that :) A classic example of if you can think of it, it will happen syndrome.

Monday, 31 January 2011

PHP: String StartsWith / EndsWith

In case you need the PHP equivalent to the .NET String.StartsWith and String.EndsWith, here they are:


public static function StringStartsWith($string, $search) {
 $ret = false;
 if (strlen($string) >= strlen($search)) {
  $ret = (substr($string, 0, strlen($search)) == $search);
 }
 return $ret;
}

public static function StringEndsWith($string, $search) {
 $string = strrev($string);
 $search = strrev($search);
 return Utils::StringStartsWith($string,$search);
}

Hope it helps :)

Select Multiple Emails in GMail / Google Apps Mail

I found it quite annoying when there were a lot of emails that I needed to delete in GMail. Turns out you can select multiple emails by checking the first item in the list, pressing the shift key and checking the last item in the list - hey presto :)

Friday, 28 January 2011

MSSQL ISDATE - Is It?

Another is it type one from MSSQL, but this time ISDATE. SQLServerCentral.com article by Kameswari Aravindh very kindly makes us aware that ISDATE('1973') returns a true response. So long as the number is between 1753 and 9999, it's a valid year and therefore a valid date.

Bear it in mind!! ;)

Wednesday, 19 January 2011

Kinect Not Exclusive to Microsoft

Quite an interesting article about the makers of Kinect cleverly not giving Microsoft exclusivity to the device! Will be very interesting to see what is going to happen...

Friday, 14 January 2011

Eclipse: Exclude SVN Folders in Project Explorer

If you like me you don't use the SVN tools that are built into Eclipse and you wan to exclude the .svn or _svn folders from the project explorer, do the following:

  1. Right click the project root node > Build Path > Configure Build Path...
  2. Click the Excluded node on the tree in the Properties pop-up and click Edit...
  3. Click to Add... an exclusion pattern
  4. Type in _svn/** and click OK
  5. Do the same and this time add **/_svn/**
  6. Click OK in Properties pop-up
  7. Sorted!

Obviously I have used _ in the example. Swap that for a . if needed ;)

Android: Remove Words From Dictionary

Just a quicky and quite an obvious one really, but in case you need to remove unwanted words from your android custom dictionary, do the following:

Go to Settings > Language & Keyboard > Touch Input > User Dictionary

Press the Menu button and choose Delete. You'll then be shown the same list with a delete button on the right. Select the words to be deleted and click OK when you're done.

Happy days :)

Thursday, 13 January 2011

Rant: VB.NET and IIf

Yes - another rant about VB. I really do dislike it the more I use it and I've been using it for too long! This time it's IIf that's getting on my wick!

Why can't VB have the "normal" inline If like real programming languages
x = (a == b ? 1 : 2) and not this stupid IIf function?

The problem I have (and I'm sure everybody else who VBs has), is that IIf is a function and therefore evaluates it's parameters first. Which then means this:

x = IIf(String.IsNullOrEmpty(textbox.Text), Nothing, Double.Parse(textbox.Text))

fails and has to be changed to this:

x = Nothing
If Not String.IsNullOrEmpty(textbox.Text) Then
    x = Double.Parse(textbox.Text)
End If

OK, I know I can change it round a bit to make fit one line a bit more, but that's not the point. Come on MS, give us a real inline if...

Grrr!!