Peter's Software House

Things I learned last week #2

Last week I started a session at work during our Monday morning development meeting called Things I learned last week.  Here is episode #2.

It was a bit of a dry week in terms of what I learned, but there was a few things worth mentioning.

I learned:

  • to love Code Contracts.  I knew that James from Intergen had done a mentoring session at Intergen and had done the same presentation at Code Camp 2009 as I looked at his presentation he put up on his blog.  I have read up on Code Contract before then but then quickly forgot about it.  Having a second look and actually RTFM I have to admit that I like it.  So much actually that we have started using it in out new codebase that will only see the light after .NET 4.0 and VS2010 is released and as such this will provide us with some future proving as we don’t then have to pull out all our custom old school pre-condition checking.  Code Contracts also add so much more, for example you can create Code Contracts for Interfaces, post-conditions and Invariants, fantastic stuff.  But as always, use wisely, don’t go and implement everything the static analysis tells you to implement. ;)
  • how to use SyntaxHighlighter and love PreCode the Windows Live Writer add-in.
  • about Web.Config Transformation coming in VS2010.  Finally I can get rid of all the complex homebrew .config handling between all the environments.
Posted by Pieter | with no comments
Filed under:

Code Snippet With Syntaxhighlighter Support for Windows Live Writer

I found the PreCode AddIn for Windows Live Writer from Scott’s Blog.

So to celebrate ;) here is another WTF:

  try
  {
    // Some Code
  }
  catch (WebException we)
  {
      throw (we);
  }
  catch (Exception e)
  {
      throw (e);
  }
  finally
  {
  }

What is the point of catching these Exceptions?  Nothing!  You also loose all the StackTrace when an error does exist.   O yea and the finally block is totally superficial.

There are rules when dealing with Exceptions:

  1. Only catch exceptions if you can deal with them (Log it, gracefully exit, etc…).
  2. If you want to add additional value to the exception, create your own with the new information and use the caught exception as an inner exception.
  3. If for what ever reason you need to re-throw, then use “throw;” not “throw e;”.

I’m sure there is more, but for me these are probably the most important.

Posted by Pieter | with no comments
Filed under: ,

Testing SyntaxHighlighter

Trying to see if I can get SyntaxHighlighter to work from Windows Live Writer.


    if (aAttachments != null)
    {
        Array.ForEach(aAttachments, sAttachment => msg.Attachments.Add(new Attachment(sAttachment)));
    }

Posted by Pieter | with no comments

How not to use string.Format

   1: sMsgLine = String.Format("The {{0}} is Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean adipiscing mollis turpis, et facilisis nisi porta at. Maecenas sollicitudin neque et sapien pharetra non tempor sem laoreet. Sed varius porta.");
   2: sMsgLine = String.Format(sMsgLine, someObject.Name);
   3: sWebSite = String.Format("The web site to go to is www.crapcode.com. {{2}}{{2}}Should you have any queries Lorem ipsum dolor sit amet, consectetur adipiscing elit, please contact the Administrator of the {{0}} on {{1}}");
   4: sWebSite = String.Format(sWebSite, someObject.Name, somePersonObject.Phone, Environment.NewLine);

Line 1 and 3: Redundant call to String.Format

Line 1 and 3: Have a look at the ‘{{0}}’, ‘{{1}}’ and ‘{{2}}’!  Needs to escape the placeholders so they will work in line 2 and 4! WTF!!!

 

This is Better:

   1: sMsgLine = String.Format("The {0} is Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean adipiscing mollis turpis, et facilisis nisi porta at. Maecenas sollicitudin neque et sapien pharetra non tempor sem laoreet. Sed varius porta.", someObject.Name);   
   2: sWebSite = String.Format("The web site to go to is www.crapcode.com. {2}{2}Should you have any queries Lorem ipsum dolor sit amet, consectetur adipiscing elit, please contact the Administrator of the {0} on {1}", someObject.Name, somePersonObject.Phone, Environment.NewLine);
Posted by Pieter | with no comments
Filed under:

WTF : if and foreach on the same line?

I’m sorry but I couldn’t resist.  Why the hell would you write your code like this?

WTF

Isn’t this a lot more readable?

Better

I don’t like the naming conventions, but at least its consistent.

Posted by Pieter | 3 comment(s)
Filed under:

Things I learned last week.

Just had our weekly development meeting and I talked about the things I’ve learned last week.  Here is a short summary:

I learned:

Posted by Pieter | 1 comment(s)

Another WTF – How not to get a Unique Login ID

In this code (from a large production system), they have seen it fit to use generate a random number to create a LoginId.  And how do they get past the possibility of duplicate logins?  O they just check the DB if it exists and if it does then go and generate a new random LoginId.  Never heard of IDENTITY?
 
   1: '========================================================================================================================
   2: Function GetUniqueLogin()
   3: '========================================================================================================================
   4:     GetUniqueLogin = ""
   5:     strLogin = GetHash( GetARandomLogin )
   6:     While ZWN(GetDataWhere("Login", "LoginID", "Login='" & strLogin & "'"))<>0
   7:         strLogin = GetHash( GetARandomLogin )
   8:     Wend
   9:     GetUniqueLogin = strLogin
  10: End Function

 

And what the F is PutDashesIn?  Well they take a number and split it into groups of three with… yea dashes in between.

   1: '========================================================================================================================
   2: Function GetARandomLogin
   3: '========================================================================================================================
   4:     Randomize
   5:     GetARandomLogin = Int( 999999999.9999 * Rnd() )
   6:     GetARandomLogin = PutDashesIn(GetARandomLogin)
   7: End Function

 

Did you see the GetHash in GetUniqueLogin?  what does it do?  O, nothing it turns out…

   1: '========================================================================================================================
   2: Function GetHash( inValue )
   3: '========================================================================================================================
   4:     GetHash = inValue
   5: End Function
Posted by Pieter | with no comments
Filed under:

Enabling HTTP Compression on your Windows 2003 Server and IIS 6 for static and dynamic .NET pages

This is a document I created to remind me how to setup HTTP Compression on Win2003 that works. Most of the images and text is my own, but some I got from the Web and if I in breach of any Copyrights please contact me and I will add the appropriate references.

Right Click on the ‘Web Sites’ folder in IIS Manager.

clip_image002

Go to the Service tab. Check the ‘Compress application files’ and ‘Compress static files’ checkboxes.

clip_image004

You can also enable content expiry to improve your YSLOW score, although this is not strictly related to compression. By removing the default Custom Http Header and adding the ‘Etag:’ header YSLOW will remove the requirement for ETags. I have not found this to cause any problems although be warned, I have no idea what the true side effects are or could be.

clip_image006

You also need to add a Web service extension. So select the ‘Web Service Extensions’ folder in IIS Manager and right click in the Right hand panel. Select ‘Add a new Web service extension…”.

clip_image008

Enter a name for the Extension. I used the very creative HTTP Compression. Add the c:\windows\system32\inetsrv\gzip.dll and select the ‘Set extension status to Allowed’ checkbox.

clip_image010

Now it is time to do some MetaBase configuration changes. NOTE: You cannot by default edit the MetaBase.xml file while IIS is running. So either stop IIS or enable direct MetaBase editing.

clip_image012

IIS 6.0 Metabase Configuration - MetaBase.xml

Goto C:\Windows\System32\inetsrv.

Find MetaBase.xml.

Make a Copy.

Open MetaBase.xml in a text editor (like Notepad2, etc…).

Find <IIsCompressionScheme/>

Be careful, there are two sections here: one for deflate and one for gzip. We want gzip so the Location attribute of the element will have the following value:

Location ="/LM/W3SVC/Filters/Compression/gzip"

Look for the HcScriptFileExtensions section. Your default should have: asp, dll, and exe. This is where you add any extensions you want to compress for dynamic files.

Add “aspx”, “asmx”, “css”, “js” and “axd”, but don’t try to save. It won’t work because the file is locked by default if IIS is running.

  • HcDoDynamicCompression. Specifies whether dynamic content should be compressed. This is important because dynamic content is by definition always changing, and IIS does not cache compressed versions of dynamic output. Thus, if dynamic compression is enabled, each request for dynamic content causes the content to be compressed. Dynamic compression consumes considerable CPU time and memory resources, and should only be used on servers that have slow network connections, but CPU time to spare.
  • HcDoStaticCompression. Specifies whether static content should be compressed.
  • HcDoOnDemandCompression: Specifies whether static files, such as .htm and .txt files, are compressed if a compressed version of the file does not exist. If set to True and a file doesn't exist, the user will be sent an uncompressed file while a background thread creates a compressed version for the next request.
  • HcDynamicCompressionLevel. VAL(1-10) specifies the compression level for the compression scheme, when the scheme is compressing dynamic content. Low compression levels produce slightly larger compressed files, but with lower overall impact on CPU and memory resources. Higher compression levels generally result in smaller compressed files, but with higher CPU and memory usage.
  • HcFileExtensions. Indicates which file name extensions are supported by the compression scheme. Only static files with the specified file extensions are compressed by IIS. If this setting is empty, no static files are compressed.
  • HcScriptFileExtensions. Indicates which file name extensions are supported by the compression scheme. The output from dynamic files with the file extensions specified in this property is compressed by IIS.

clip_image014

Shutdown IIS, save the file and restart IIS.

You can test at http://www.pipeboost.com, or using a tool like YSlow.

Posted by Pieter | with no comments
Filed under: ,

Why does excel not support the taskbar right-click menu?

A silly rant, but it is a bit frustrating if you want to quickly close all those instances of an application and it doesn’t allow it.

image

I’m hoping someone will tell me there is an easy hack to fix this, or that I am blind and should look at some option somewhere. ;)

Posted by Pieter | with no comments
Filed under:

Code Reviews

It is clear to me that based on some of the online and offline comments I have been getting on my WTF blog posts that there is a bit of a misunderstanding about them.  This post will hopefully clear any misunderstanding there might be.

At work I work on several applications (mostly web based, but a couple of ‘smart client’ apps as well).  The oldest application is over 10 years old and originally started as an Access 2.0 application and over time evolved, using SQL Server, VB6, Classic ASP and finally .NET.  The .NET conversion started back in 2003 and we have just recently converted the last VB6, Classic ASP pages to C#.  All our other applications started out as .NET applications, except for one exception. 

This is the code base I have mostly been blogging about.  The original codebase was not developed by my current employer, it was purchased about 9 months ago (a couple of months before I started there) as my employer believed that the company that developed and maintained it was not financially viable and as the software formed a critical part of our operations in Australia it was decided to purchase the code and move future development in-house.

This code is a mess, apparently there was more than 40 contractors working on it at one time, you all have seen some of the shit they have produced.  Clearly there wasn’t any decent code reviews done on the code and based on some of the stuff I’ve seen most of the dev’s were either a) lazy as hell, b) had no idea what they were doing or c) just plain bad developers.  Now it has been my job to try and figure out how this software works and how we can leverage or extend the code for our own use.  It has been nothing short of a nightmare, really I have woken up at night screaming… ;)  The code base includes, BASH shell scripts, VB6 COM and Windows code, classic ASP, VB.NET and C# code.  A crazy mix of technologies and no clear path on were they are going next.  The code is such a mess that we are writing a new application to replace this in about 2-3 years and will only update this codebase for legal and compliancy reasons.

So finally the reason for my WTF’s is to show what crap is out there in the commercial world.  And hopefully by showing this in blog posts a few people will read this and notice similar crappy patterns in their code bases and highlight them to their co-workers and peers, hopefully through more rigorous code reviews.

Happy Coding!

Posted by Pieter | 1 comment(s)
Filed under:

Telkom stock increases by +599900.0% ?

image

Wish I had some Telkom stock. ;)

[FYI: This is a system error.]

Posted by Pieter | with no comments

Can’t has…

A nice DevExpress Control Error: ;)

image

Posted by Pieter | with no comments
Filed under:

WTF – Assign variables to themselves

Clearly this dev thought: I have nothing else to-do, let me assign variables to themselves:

image

And not only in one place, o no, he had loads of time.  I found thirty of these in one method!!

Posted by Pieter | with no comments
Filed under:

How not to do Generics!

The wrong way:

image

The right way:

image

Posted by Pieter | with no comments

How not to use LINQ (to DataSets)

Don’t fill your DataSet with all the records from your database and then use LINQ to filter out the data you need!!!

Let your database do what it is good at, let it select the data you want, it can make use of its indexes etc… to optimize your queries.  Trying to replicate this with LINQ will make your users cry elephant tears!

Use the appropriate tools and techniques for the job at hand.

Posted by Pieter | 1 comment(s)
More Posts Next page »