Wednesday, August 14, 2013

SQL Updates - One shot

Let's be honest, we've all made that mistake in SQL where we accidentally
forgot to put the right parameters into a where clause, and had to
run down to the dba and beg for a recent backup!

Writing SQL update statements really isn't that difficult,
but sometimes it can be daunting executing them,
depending on how many records you're looking at.

There are a few ways you can make things a little less intimidating.

1 - Work up your where clause in a select statement first, to see how many records would be affected.

For a simple example, let's say Ronald McDonald is in our database as "Ron",
and we want to update to use his full name.

Ex:
select First, Last, Middle
from dbo.tblEmployees
where Last = 'McDonald'
It should came back with 1 row.
update dbo.tblEmployees
set First = 'Ronald',
    Modify_Date = GETDATE()
where Last = 'McDonald'
Now when you run this, it had better come back with only 1 row affected!

2 - Write your where clause so that if you ran it a second time it would affect 0 rows.

Taking the same example, it's good practice to make sure that
if you run your stored procedure twice, it will not do any updates the second time.

Ex:
update dbo.tblEmployees
set First = 'Ronald'
    Modify_Date = GETDATE()
where Last = 'McDonald'
    and First = 'Ron'
Now when you run this the first time you'll see 1 row affected.
If you run it a second time, it will show 0 rows affected.
Note that it won't overwrite the Modify date, so you'll preserve the date of the original update.

I call this method a one-shot. It can be very useful if you need to track the history of updates,
and especially useful if you have things like update triggers on your table.

Wednesday, July 17, 2013

Interviews - Be Ready to Code!


Finding a good programmer can often be like trying to find a needle in a haystack.

Sometimes the best ones have no degrees, no certifications and very little varied job experience,
and some of the worst interview candidates have glowing shining resumes that make them look like the next Bill Gates.

The best and most reliable way to filter out the people who actually know what they're doing
versus the people who know how to craft a pretty resume is to throw down some code in the interview.

It might seem taboo to some people, but it can save you massive headaches in the future!

It doesn't even have to be rocket science, just something like:
"Write the code to query table X in database Y, and display the data in a grid."

And for the interviewees?
Show up with a pen and a brain ready to show what you know.
Study ahead of time if you have to!

Saying "Yeah I really don't remember how to do it, I usually just copy past from old code" probably isn't going to cut it.
Your memory doesn't have to be perfect, but if you're as good as your resume shows you should be able to at least get close to the mark.

Sunday, June 9, 2013

You down with OPC? (Other People's Code)

One of the laws of programmers and programming that I believe to be universal is:
Nobody likes anybody else's code

It could just be the leading or trailing spaces, too few comments, too much whitespace or any number of things.
In the end it simply boils down to the fact that it's not YOUR code, but you have to touch it.

As a programmer, there are virtually only two ways to avoid having to work with other people's code:
1 - Quit programming
2 - Die

Even looking back on code you wrote years ago can be like looking at a foreign language as styles and talents grow through the years.

So the only advice I can give here is to try and code NOW with other coders in mind.
Think of it as making a work of art that someone else will unveil some day.

A nicely wrapped present that they will open and get a wonderful surprise and not a box of poop!

Tuesday, May 7, 2013

DON'T YELL AT ME

When you're coding error messages, emails, notices and every other kind of text interface for a user, try to think about how it's going to look 10 years down the road.

If someone forgets to fill in a field, which one looks the best?

Required field: First name
YOU MUST FILL IN ALL REQUIRED FIELDS!
This form requires that you fill in all fields before submitting. Please check the form and review all required fields to make sure they are completed. Required fields are highlighted in RED with an asterisk next to the field.
Cheerio, jolly good day outside isn't it? By the by I noticed that you may have forgotten to fill in one teensy weensy field. Would you mind lending a hand by filling that field out if it's not too much of a bother? Thanks in advance.
ERROR.

As comical as these may seem, I've seen some code that was pretty close to some of those examples.

When in doubt: Keep it simple, and avoid SHOUTING !! with caps lock or exclamation points.

Tuesday, April 24, 2012

& versus +

I've pretty much switched over to C# programming, and while I do like some aspects of it, there are some that I think are just silly.

Type conversion is SOOOO easy in VB versus C#.

Ex:
Dim x As Integer
Dim s As String

s = "7"

x = s 'Since x is an Integer, it automatically converts s to an Integer

x = 5

s = x 'Since s is a String, it automatically converts x to a String

In C# you have to EXPLICITLY cast everything.Kind of a pain.

Ex:
int x;
string s;

s = "7";

x = Convert.ToInt32(s); //Explicitly converts s to an int

x = 5;

s = Convert.ToString(x); //Explicitly converts x to a string

I understand that VB allows for some "sloppy" programming by making the compiler assume the type conversions, but as programmers shouldn't we be able to depend on the programming language to be smart enough to perform the default type conversion based on the type of the variable on the left?

It just makes things kind of silly sometimes, and I was thinking that maybe the root of it all is that C# doesn't have a separate operator for string concatenation.

In VB you use + for arithmetic, and & for string concatenation.In C#, + is for both. (& is for bitwise operations)

Ex:
Dim x, y, z As Integer
Dim s As String

s = "Results: " & x & ", " & y & ", " & z


Ex:
int x, y, z;string s;

s = "Results: " + Convert.ToString(x) + ", " + Convert.ToString(y) + ", " + Convert.ToString(z);

Wouldn't it be sweet if C# defined a string concatenation operator?

And if your response is "Don't be a lazy VB programmer, C# rules!"I say bite me, and if less typing makes you lazy then why are you all so excited about lambda expressions? :P

I really despise the religious war between VB and C# programmers. I've programmed in so many different languages that I think it's just silly because really VB and C# are more similar to each other than to they are to so many other languages.
*sigh*

Tuesday, March 20, 2012

How to save VB and piss off the rest of the world

Visual Basic is a dying language.

People are mostly switching to C#, either due to their familiarity with Java, C++ or just because every sample on the planet is in C#, including the ones provided by Microsoft.

The way things are going, some day VB will go the way of Pascal and COBOL. Languages that are still around to some extent, but people don't really use unless they're supporting an old system.

How could they save VB?

Here's my idea:

***** Make VB recognize similar syntax from other languages *****

If the VB compiler accepted this:


If ((x = 1) And Not(y < 0)) Then
    sTmp = "Test"
End If


AND this:


if ((x == 1) && !(y < 0))
{
    sTmp = "Test";
}


Then all of the C# syntax in the world could just be copied & pasted into VB apps, PROBLEM SOLVED.

Here are some of the main things that would need to be allowed:
1 - Semicolon to end a line
2 - Curly braces to open & close constructs (if, while, for)
3 - &&, ||, ! % in place of And, Or, Not, Mod
4 - Brackets for arrays, [] instead of ()
5 - Declarations with type first versus last (string sTmp; vs. Dim sTmp As String)
6 - // and /* */ for comments

Some things that would cause problems:
1 - C# ONLY ends a line of code with a semicolon.

So you can have a statement that spans multiple lines and is only ended when the compiler hits the ;
In VB to extend your program to another line you have to use the _ symbol.

Sample C#:

x = y
+ 7;


Sample VB:

x = y _
+ 7


2 - C# string syntax uses \ escape sequences instead of "" for quotes.

Sample C#:

sTmp = "Fail \\, what\" hey";

Sample VB:

sTmp = "Fail \, what"" hey"

Honestly though I think if there was like a compiler setting like "Allow compatible C# syntax" then you would basically be doing it at your own risk and have to take the risky things into account, but the benefits would WAAAY outweigh the drawbacks!
.
.
.

Monday, February 20, 2012

Switch Hitting

Since the middle of last year I've made the switch from VB to C#.

Why?
Mostly because every where I look for samples, training, webcasts, etc. all the code is in C#. Even Microsoft employees doing webcasts or seminars have all been using C#, without exception.

I've done my share of programming in several languages throughout school and work. (BASIC, QuickBasic, pascal, FORTRAN, C, C++, SPARC Assembly, Intel Assembly, java, VB, VB.Net, C#, SQL, HTML, JavaScript, VBScript, batch files, PLC, vhdl, plus a handful of others I dabbled in) So switching languages was no big deal to me, but now that I have switched I've found if I go back to do some things in older projects that are still in VB I code a little differently just in case I decide to convert the code to C# later.

For example, in the old days when you had a string that you wanted to get rid of leading and trailing spaces on, in VB you would go:

sTxt = Trim(sTxt)


But in C# there aren't really a lot of standalone built in functions like Trim, Split, Left, Right, etc. they are all tied directly to the datatypes and accessible as member functions and properties of the variables.
So in C# if I wrote that same line it would be:

sTxt = sTxt.Trim();


Now since C# and VB are both in the .Net world, they share the same data types and member functions, meaning in VB I can do the same code as above (without the semicolon).
So previously in VB I would write something like this:

Dim sSplit() As String
Dim nVal As Integer
Dim sTxt As String

If (InStr(SomeInput, ",", > 0) Then
    sSplit = Split(SomeInput, ",")
    If (IsNumeric(sSplit(0))) Then
        nVal = CLng(sSplit(0))
    Else
        nVal = -1
    End If
    sTxt = Trim(sSplit(1))
End If


Now I write it something like this:

If (SomeInput.indexOf(",") >= 0) Then
    sSplit = SomeInput.Split(New String() {","}, _
        StringSplitOptions.RemoveEmptyEntries)
    If (Not(Integer.TryParse(sSplit(0), nVal))) Then
        nVal = -1
    End If
    sTxt = sSplit(1).Trim()
End If


So that to convert it to C# I really only have to change the built in keywords like If, Then, Not, etc. and add a bunch of semicolons:

if (SomeInput.IndexOf(",") >= 0)
{
    sSplit = SomeInput.Split(new string[] {","},
        StringSplitOptions.RemoveEmptyEntries);
    if (!(int.TryParse(sSplit[0], nVal)))
    {
        nVal = -1;
    }
    sTxt = sSplit[1].Trim();
}


Voila!
A little bit of a change in style for me after several years of coding in VB, but not difficult by any means, and it can save me tons of time later if I decide to convert an old project to C#. Since the middle of last year I've made the switch from VB to C#.

Friday, January 20, 2012

The Computer Science Degree Problem

I was inspired by this post on Slashdot: Are You a Blue-Collar Or White-Collar Developer?

Lots of people sounding off not only about why employers shouldn't necessarily require degrees, but also about the inherent problem with computer science degrees.
It's kind of a sore subject with me, having personally experienced computer science curriculums from two different universities, and having researched programs from several others.

I think there are HUGE problems with every single CS degree program I've looked at, and I've checked out quite a few, even including Berkeley and Stanford.
Some are better than others, but all are still off the mark.

Here are the basics of my main argument:


I - Argument Basics:
    1 - People go to college to get a degree so they can get a good job
    2 - Employers in computing fields prefer a computer science degree
    3 - Employers in computing fields want people who already have the skills to do the job
    4 - Computer Science degrees do not teach people the skills to work in computing fields
    5 - "Vocational schools" suck

II - By computing fields I mean:
    1 - Application development (websites, EXEs, databases, etc)
    2 - Network management (routers, firewalls, switches, etc)
    3 - PC Support (software & hardware installation and troubleshooting)
    4 - Server Support (mail, web, database, etc)
    5 - Hardware programming (ROMs, CE devices, etc)


Supporting arguments:

Computer science is for scientists.
For people who are typically going to spend their careers researching the next best algorithm to solve a non-polynomial problem, or write journal entries to help advance the world of academics, and later the private sector.

Let's look at a sample degree programs, I'll pick on University of Michigan.
I should note that U of M's degree program is almost exactly the same as Oakland University's and Michigan Tech's, so I'm picking on a curriculum that matches classes I've taken (and passed), not teachers or facilities.
Having attended both OU and MTU, I can tell you the big difference:
OU has better teachers, but MTU looks better on for your resume.

And to be clear, I am not focusing on ELECTIVES or the options that a university offers, I am focusing on CORE REQUIREMENTS.
When you are looking at a graduate from this degree program, what guaranteed topics have they been required to pass?

University of Michigan

EECS 203. Discrete Mathematics
Introduction to the mathematical foundations of computer science. Topics covered include: propositional and predicate logic, set theory, function and relations, growth of functions and asymptotic notation, introduction to algorithms, elementary combinatorics and graph theory, and discrete probability theory.

Worthless. Did I say worthless? Let me clarify: WORTHLESS!!!!!


EECS 280. Programming and Introductory Data Structures
Techniques and algorithm development and effective programming, top-down analysis, structured programming, testing, and program correctness. Program language syntax and static and runtime semantics. Scope, procedure instantiation, recursion, abstract data types, and parameter passing methods. Structured data types, pointers, linked data structures, stacks, queues, arrays, records, and trees.

Introductory programming is probably the most relevant class here, although once they get into the structured data types, you start to lose a lot of relevance.
Not saying that there isn't good use for stacks, queues, etc. but that there are many many very successful programs and programmers who never use them and never need to.


EECS 281. Data Structures and Algorithms
Introduction to algorithm analysis and O-notation; Fundamental data structures including lists, stacks, queues, priority queues, hash tables, binary trees, search trees, balanced trees and graphs; searching and sorting algorithms; recursive algorithms; basic graph algorithms; introduction to greedy algorithms and divide and conquer strategy. Several programming assignments.

Almost entirely worthless.
It's nice to get a little insight on how a few search algorithms work, but in about a week you've gone beyond what most people need.
The few lucky people off writing database engines and compilers might need to optimize their code down to the millisecond or rebalance a tree, but for the computing fields in IT, you can be a great programmer and never use any of those things.


EECS 370. Introduction to Computer Organization
Basic concepts of computer organization and hardware. Instructions executed by a processor and how to use these instructions in simple assembly-language programs. Stored-program concept. Datapath and control for multiple implementations of a processor. Performance evaluation, pipelining, caches, virtual memory, input/output.

This is a nice one to round out the education of a computer professional.
Technically worthless as far as application in a job goes, but it's at least a nice token to actually understand the guts of what is running inside the computer.


EECS 376. Foundations of Computer Science
An introduction to computation theory: finite automata, regular languages, pushdown automata, context-free languages, Turing machines, recursive languages and functions, and computational complexity.

I can not stress to you how WORTHLESS this class is. I actually enjoyed the class on this topic that I took, but it has NO bearing on actual real work that pretty much anyone will ever do.
Ever.
A lot of this class involves using computational theories developed in the 1970s that are really nice but have almost no real world application.


EECS 496. Major Design Experience Professionalism
Design principles for multidisciplinary team projects, team strategies, entrepreneurial skills, ethics, social and environmental awareness, and life long learning.

GREAT class.
Unfortunately they probably don't actually teach you what you need to know in order to pass this class, but whatever experience you can gain from this class is likely worth it's weight in gold.


So after slinging all the mud at this degree program, I can tell you some of the key components that are missing.
Basically I believe that the assumption about students with Computer Science degrees from places like U of M is that they are technical experts in the latest computing fields, and that they know everything about computers.
That may be the case, but odds are the students learned it on their own, not through the classes.

Nowhere on the degree program does it tell you how to do anything like this:
- Install an operating system (Windows, Linux, etc)
- Troubleshoot software problems (Office, FireFox, MySQL, anything!)
- Work with a database
- Work with a network (TCP/IP?)
- Troubleshoot hardware problems or device drivers
- Basic graphic design


Here's what I do every day, and I am among the majority of the masses of programmers:
- Write a program to connect a user to a database

The closest they get is in EECS 280, and that's pretty much their intro to programming class!

The trouble is that the CS degree is a broad umbrella where they try to require the "basics" and then expect you to take the proper electives.
They are requiring the wrong basics.

I think they also start off a little too easy on the programming topics too.
Engineering programs don't start you off with algebra, they assume you are ready for calculus.
Computer Science should assume you have already done some programming, and if not you can sign up for an elective to learn it.
Classes should be fast paced, you can NOT afford to miss a day, and there are assignments due each week.

Since they require 6 classes, I'll take a stab at replacing those 6 with a better set.

COMP 101: Programming 101
Basic concepts of programming, along with development toward a realistic application.
If a student aced just this class they should be able to go get a job.


Weeks 1-3: OOP, data structures, etc.
Weeks 4-6: Basic web programming
(NOTE: Use a current language! Java, C#, Ruby, Python, etc.)
Weeks 7-10: Basic executable programming (i.e. winforms)
Weeks 11-13: Basic database programming
Weeks 14-16: Tie all of it together and end up with a nice looking application

COMP 102: Computer maintenance
Basic concepts of computer administration on multiple CURRENT platforms.
Someone who aced this class could do helpdesk or PC deployment.

Weeks 1-3: Microsoft Windows - Install the OS, some applications (Office, IE, Firefox), device drivers and services, check out the registry
Weeks 4-6: Command prompt - Put your mouse away
Weeks 7-10: Linux - Install the OS, some applications, drivers and daemons
Weeks 11-14: Shells: Bash, TCSH, KSH, etc
Weeks 15-16: MacOS - Install some apps, click away

COMP 103: Multimedia Design
Basic concepts of multiple aspects of design using CURRENT technologies. (CS3)
Someone who aced this could be an entry level graphic designer.


Weeks 1-3: Image editing (Photoshop, Gimp, etc)
Weeks 4-6: Video editing
Weeks 7-9: Audio editing
Weeks 10-12: CSS
Weeks 13-16: Flash

COMP 201: Advanced Programming
Broader discipline for programming.

Someone who aced this would be considered an expert programmer.


Weeks 1-3: SQL query language (Use a current language! MSSQL or Oracle)
Weeks 4-6: Network programming - Write actual code to open ports and send info over the wire
Weeks 7-9: Assembly language - Write some, learn about different processor architectures, etc
Weeks 10-13: Hardware programming - Interface with a piece of programmable hardware, write some PWMs, etc
Weeks 14-16: Advanced web based programming - AJAX, internet APIs, jQuery, cloud computing

COMP 202: Advanced computer maintenance
More complex administrative topics, more server and infrastructure based.
Someone who aced this could get a job as an entry level server administrator.


Weeks 1-4: Microsoft Windows Server, SQL Server, Exchange, IIS - Install and configure
Weeks 5-8: Unix, Oracle (Unix, Windows or Linux), Apache
Weeks 9-12: Network software - NDIS, (snort, ethereal), learn what RFCs are
Weeks 13-16: Network hardware - Routers, firewalls, etc


COMP 301: Hacking
NOTE: Hacking, not cracking. Yes there is a difference.
What to do when the standard programming methods don't work.


Weeks 1-4: Programming attacks: Hex editors, process viewers, memory editors, registry, decompilers
Weeks 5-8: Programming defense: Writing secure code, type checking, managed code, obfuscators, digital certificates
Weeks 9-12: Admin Attacks: DDOS, buffer overflows, trojans, malware, spyware, viruses (in depth education, not writing them)
Weeks 13-16: Admin Defense: Creating a secure infrastructures, antivirus, intrusion detection

There is a TON still missing from this list, but like I promised, six classes.

I think in the end what needs to happen is a NEW degree program needs to be created, called something like Software Engineering or something.
Structure it right, and then watch as the MASSES flock to it and the old Computer Science degree program dies a horrible death when no one signs up.

Wednesday, December 14, 2011

Mixed Variable Types

Some languages like VB and VBScript allow for what is commonly referred to as "evil coercion" meaning that the system will do it's best to do automatic type conversion between two variable types.

This can be helpful in situations like this:
Dim x As Integer
Dim s As String

s = "7"

x = s 'No need to call Convert functions

But this can also cause major problems, especially in VBScript where variables aren't explicitly typed and everything is a "Variant", meaning a variable that can dynamically change it's internal type.

In these cases if you don't explicitly stick to rules of variable handling, initialization and comparison, you can run into serious logical errors, as well as confuse anyone trying to troubleshoot your code.

Sad Code:
'Variable is prefixed with "int"
'and value is initialized to a number
'but in quotes so it's treated as a string
Dim intNew : intNew = "0" 

'The database bit field is a Boolean,
'so the variant intNew should change to act like a Boolean
intNew = objRSLeadStage("bNew") 

'What's going to happen here?
'Is intNew a string, boolean or number?
If (intNew = "True") Then

Oddly enough, the above Sad Code works, in the sense that the comparison between the string value "True" coerces to the Boolean value True for the If statement.

The intNew variable here clearly has an identity crisis, and anyone trying to debug this code amongst a thousand other lines is most likely going to end up pulling there hair out asking WHY?

So remember that when you're working with dynamic variable types like Variants or Objects, and languages that perform evil coercion you should be VERY strict with how you handle your data types and variable names to avoid confusion.

Happy Code:
Dim bNew : bNew = False

bNew = CBool(objRSLeadStage("bNew"))

If (bNew) Then

As you can see here, there is no confusion in any area as to the behavior of your variable.

Wednesday, November 16, 2011

Documentation

I'm a big fan of what they call "Self Documenting Code" meaning code that is so straightforward and simple that just about any programmer could understand based on variable names, function names, context etc.

But of course there are times when you may have to write complex algorithms, or you're working in a module that's very large and you have to put in documentation to help make it easier for you or someone else to troubleshoot your code in the future.

Just make sure that your documentation is accurate and correct and belongs where it is in the code!

The only thing worse than NO documentation is INCORRECT documentation.

Trying to troubleshoot a function assuming that the comments are accurate only to find out later they are out of date or just copied and pasted from a different non applicable section can really drive you crazy!

Wednesday, October 12, 2011

Boolean Variables

Don't use non-Boolean data types for Boolean type operations.

i.e. Don't create a string variable and then check if it's equal to "Yes", "True", "On", or an integer variable and check for 1.

If the your flag is contained in a session variable or textbox, just declare a Boolean variable and use it going forward.

Sad Code:
If (sAccess = "Yes") Then
 'Go ahead

Happy Code:
Dim bAccess: bAccess = False

If (sAccess = "Yes") Then bAccess = True

If (bAccess) Then
 'Go ahead

Wednesday, September 14, 2011

Variable Declarations

1. Declare your variables outside of Try / Catch blocks

- AND -

2. Don't initialize your variables in the declaration block.

1 - If you declare your variables inside your Try Catch block you won't be able to access them at exception time.

Sad Code:
Try
 Dim MyString As String

 MyString = "Hey"

Catch ex As Exception
 'Can't view value of MyString here
End Try

Happy Code:
Dim MyString As String

Try
 MyString = "Hey"
Catch ex As Exception
 Response.Write(MyString) 'Yay!
End Try

2 - If you initialize your variables when you declare them, there are two issues.
A - You are creating objects that may never get used
B - Since your declarations are outside the try / catch blocks, you could throw an unhandled exception

Sad Code:
Dim MyObj As New CustomObject() 'Oops, this could cause an error!
Dim MyString As String

Try
 MyString = CInt("Hey") 
'Or it could get thrown out because
'this error happened before it was used

Catch ex As Exception
 'Stuff
End Try

Happy Code:
Dim MyObj As CustomObject 
Dim MyString As String

Try
 MyString = CInt("Hey")
'Now if we get an error here,
'we haven't wasted valuable resources!

 MyObj = New CustomObject()
'Yay! We waited until we needed the object to create it!

Catch ex As Exception
 'Stuff
End Try

Wednesday, August 17, 2011

HTML Tags

Don't leave HTML tags open, or close HTML tags that aren't there.

Sure you can write Sad Code like this:
<%
If (HasAccess) Then
%>
      <a href="Secure.asp">
<%
End If
%>
      Secure Link</a>

and it will most likely still show a link, but look at the messy source!

-- If HasAccess = True:
Secure Link

Source:
<a href="Secure.asp">Secure Link</a>

-- If HasAccess = False:
Secure Link

Source:
Secure Link</a>

That little closing anchor tag is not a happy tag!

Wednesday, July 13, 2011

Wasted Objects

Don't create objects unless you need them

Sad Code:
Dim MyTable As New DataTable 'Creates 1st data table

MyTable = MyFunction.GetDataTable()  'Destroys 1st data table and creates another

Happy Code:
Dim MyTable As DataTable

MyTable = MyFunction.GetDataTable()

Or if you prefer the quickie version:
Dim MyTable As DataTable = MyFunction.GetDataTable()

Wednesday, June 15, 2011

Naming Conventions

Do not name your local variables or subroutine arguments the same as your module level variables.

i.e.

Sad Code:

Private MyVar As Integer
Public Sub MySub(ByVal MyVar As Integer) Also Sad Code: Public Sub MySub() Dim MyVar As Integer


Tip: Use a character prefix to define the scope and type of your variables.

Happy Code:

Private mnVar As Integer

Public Sub MySub(ByVal vnVar As Integer)
 Dim nVar As Integer

Wednesday, May 11, 2011

Process map for upgrading from Classic ASP to ASP.Net

When Microsoft published ASP.Net they made a very large architecture change from their old product of Classic ASP.

Unfortunately when they made this change, they didn't provide a very good upgrade path from the old code to the new, so many programmers still support Classic ASP pages as upgrading them can be very time consuming without a lot of return on investment.

There is no silver bullet for upgrading Classic ASP pages, but I've come up with a standard method that I follow when I have to upgrade pages that seems to work well.

Process map for upgrading from Classic ASP to ASP.Net

1 - Upgrade the majority of your SQL queries to stored procedures

Having your SQL queries as simple calls to stored procedures makes your upgrade easier because when you are trying to debug problems during the transition phase you can rule out syntax problems with your queries.
It also helps if you are trying to migrate from include files to business logic libraries.

This is also something you can do while your Classic ASP site is running, so you can go through the testing and debugging phase with the existing site and rule out any problems that may come about after converting to stored procedures.

2 - Turn your page headers, navigation and footers into a master page

If you have common page headers, tabs along the top, links on the side, copyright links on the bottom, style sheets, javascript libraries or any other common elements that are used across all of your ASP pages, set up a master page to handle as much of it as you can.

3 - Create a base page class

A lot of ASP pages will start out with validation for a user login, initialization of session variables, and loading some database values into memory for later use.
You can create separate business object class libraries to handle all of this, but it helps if you create a simple base page class for all of your .aspx pages to inherit from.
That way you can have your base page's "Page_Load" routine handle any initialization you would normally have to do, as well as declare any variables that will be used across your codebehind page.

4 - Turn include files with HTML output into user controls

If you use include files to spit out large chunks of HTML either through code breaks <% or calls to response.write, create a user control (.ascx file) so that you can have the same functionality through your .aspx page

5 - Turn include files with functions into classes

If you have include files that you use across your application to make database calls or crunch some code, the best place for those is in class files.
If you have common routines that are just used for parsing inputs or just generic functionality, you can create shared classes.
Otherwise you can create specific classes to handle each section of your application.

6 - Turn page functions into functions in your codebehind

If you have functions that you use for crunching code for your .asp page, you should be able to convert them easily to functions in your codebehind for .aspx page.
If it is a function mostly used for outputting HTML to the page, it may not be worth converting.

7 - Grab the HTML from your browser

Load up your current Classic ASP page in the browser, view source and grab the HTML as it is presented.
Paste that into the content placeholder in your .aspx page, cut out the common areas covered by your master page and you have a pretty good starting point.
From there you can paste in your user controls where necessary, and start adding data grids, drop down lists or other server controls that you can bind from your codebehind.

8 - Rewrite the rest

Unfortunately since Classic ASP and ASP.Net are such different animals, you're pretty much guaranteed to lose a lot of code that can't really be migrated very well.
In most cases once you've done all the previous steps it's time to just throw out whatever code hasn't been migrated of the page and put all the pieces together in .Net.

Tuesday, October 19, 2010

Mixed Content Object Naming

Don't use the same name for multiple objects of different scope and type, and don't give names to objects that are incongruous with their types or meanings.
Try to give each variable and object names that identify their scope, type and meaning.

Sad Code:
<%
Dim MyVar: MyVar = 0
Dim MyVar_A: MyVar_A = 0
Dim MyVar_B: MyVar_B = 0
%>
<script type="text/javascript">
function DoStuff() {
 MyVar_X = txtMyVar.innerText + intMyVar.value + MyVar.value;
}
</script>
<html>
<input type="text" id="MyVar" value="<%=MyVar%>" />
<input type="hidden" id="intMyVar" value="<%=MyVar_A%>" />

<table><tr><td id="txtMyVar"><%=MyVar_B%><td></tr></td>
</html>

Happy code:
<%
Dim mnMyVar: mnMyVar = 0
Dim mnMyVar_A: mnMyVar_A = 0
Dim mnMyVar_B: mnMyVar_B = 0
%>
<script type="text/javascript">
function DoStuff() {

 var nMyVar;

 nMyVar = tdMyVar_B.innerText + hidMyVar_A.value + txtMyVar.value;
}
</script>
<html>
<input type="text" id="txtMyVar " value="<%=mnMyVar%>" />
<input type="hidden" id="hidMyVar_A" value="<%=mnMyVar_A%>" />

<table><tr><td id="tdMyVar_B"><%=mnMyVar_B%><td></tr></td>
</html>