CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Raymond Lewallen

Framework Design, Agile Coach, President Oklahoma City Developers Group, Microsoft MVP C#, TDD, Continuous Integration, Patterns and Practices, Domain Driven Design, Speaker, VB.Net, C# and Sql Server

January 2005 - Posts

  • British psychologist calculates most depressing day of the year

    In this article entitled Monday, Jan. 24, called worst day of the year, a British psychologist came up with some odd way of calculating the most depressing day of the year using the following formula:
    
    [W + (D-d)] x TQ
          M x NA
    
    

    The equation is broken down into six identifiable factors: (W) weather, (D) debt, (d) monthly salary, (T) time since Christmas, (Q) time since failed quit attempt, (M) low motivational levels and (NA) the need to take action.

    Now, normally I wouldn't care about something like this, but January 24th just happens to be my birthday. Now THATS depressing.
  • Exception Handling in Sql Server 2005

    SQL Server 2005 provides a new exception-handling mechanism in the form of TRY...CATCH. In current version of Sql Server you have to include GOTO statements, and check @@ERROR after every statement is executed to determine if an error had occurred at that particular point and terminate your process or rollback your transaction. This is very ugly indeed. Now Sql Server 2005 provides us with a way to handle those exceptions with the familiar TRY...CATCH blocks. Note: TRY...CATCH blocks in Sql Server cannot handle errors that cause a connection to be lost, i.e. any severity 21 error.

    Let's look at this simple block of code:
    
    BEGIN TRY
      BEGIN TRAN
      INSERT Northwind.dbo.Region(RegionId, RegionDescription) VALUES (5,'CENTRAL')
      PRINT 'Added Central Region'
      INSERT Northwind.dbo.Region(RegionId, RegionDescription) VALUES (5,'ANOTHER REGION')
      PRINT 'Added Another Region'
      COMMIT TRAN
    END TRY
    BEGIN CATCH
      PRINT 'The following error has occurred:  ' + ERROR_MESSAGE()
      ROLLBACK TRAN
    END CATCH
    

    The following output will be produced:
    Added Central Region
    The following error has occurred: Violation of PRIMARY KEY constraint 'PK_Region'. Cannot insert duplicate key in object 'Region'.


    Well that is simple enough. Note that unlike .Net, you cannot leave out the CATCH statement in T-SQL. Not much change to existing code in order to get this implemented, other than taking out a bunch of labels, GOTOs and @@ERROR > 0 checks.
    Here's another example:
    
    BEGIN TRY
      BEGIN TRAN
      INSERT Northwind.dbo.Region(RegionId, RegionDescription) VALUES (5,'CENTRAL')
      PRINT 'Added Central Region'
      INSERT Northwind.dbo.Region(RegionId, RegionDescription) VALUES (6,NULL)
      PRINT 'Added NULL Region'
      COMMIT TRAN
    END TRY
    BEGIN CATCH
      PRINT 'The following error has occurred:  ' + ERROR_MESSAGE()
      ROLLBACK TRAN
    END CATCH
    

    The following output will be produced:
    Added Central Region
    The following error has occurred: Cannot insert the value NULL into column 'RegionDescription', table 'Northwind.dbo.Region'; column does not allow nulls. INSERT fails.


    Now lets combine the two examples together and look at how we capture a specific error that occurred using ERROR_NUMBER(). Also, I'm introducing the new XACT_STATE() into this example. XACT_STATE() does exactly what you think it does, it returns the state of the transaction. Return values 0 for no transaction is open and you cannot commit or rollback, 1 means that a transaction is open and can committed or rolled back based on how you need to handle your situation, and new to Sql Server 2005 is a transaction state of -1, which means that a transaction is open but cannot be committed. A transaction within a TRY block reaches this state when an error occurs that would normally cause the transaction to be aborted. You cannot continue to change data once the transaction reaches a point of not being able to be committed because an uncommittable transaction keeps all locks open and allows you to only read data. At this point, the only way to terminate the transaction is to roll it back. Let's look at this example:
    
    BEGIN TRY
      BEGIN TRAN
      INSERT Northwind.dbo.Region(RegionId, RegionDescription) VALUES (5,'CENTRAL')
      PRINT 'Added Central Region'
      INSERT Northwind.dbo.Region(RegionId, RegionDescription) VALUES (5,'ANOTHER REGION')
      PRINT 'Added Another Region'
      INSERT Northwind.dbo.Region(RegionId, RegionDescription) VALUES (6,NULL)
      PRINT 'Added NULL Region'
      COMMIT TRAN
    END TRY
    BEGIN CATCH
    IF ERROR_NUMBER() = 2627
    BEGIN
        PRINT 'Statement violates primary key constraints.'
        IF (XACT_STATE()) <> 0 -- We are in a transaction and want to roll it back
            ROLLBACK TRAN
    END
    ELSE IF ERROR_NUMBER() = 515
    BEGIN
        PRINT 'Statement attempted to insert a NULL where a NULL is not allowed.'
        IF (XACT_STATE()) = -1 -- Can only rollback
            ROLLBACK TRAN
        ELSE IF (XACT_STATE()) = 1 -- We can do whatever we want, commit or roll back
            COMMIT TRAN
    END
    
    PRINT 'Error Number:   ' + CAST(ERROR_NUMBER() AS VARCHAR(10))
    PRINT 'Error Message:  ' + ERROR_MESSAGE()
    PRINT 'Error Severity: ' + CAST(ERROR_SEVERITY() AS VARCHAR(10))
    PRINT 'Error State   : ' + CAST(ERROR_STATE() AS VARCHAR(10))
    END CATCH
    

    Now the following output will be produced for this block of code:
    Added Central Region
    Statement violates primary key constraints.
    Error Number: 2627
    Error Message: Violation of PRIMARY KEY constraint 'PK_Region'. Cannot insert duplicate key in object 'Region'.
    Error Severity: 14
    Error State : 1

    Notice how I can still COMMIT the transaction if I want to depending on the specific error that occurred. I may not care so much that the NULL didn't get inserted, but I want to go ahead and commit the other inserts. By checking the ERROR_NUMBER() in my CATCH block, I can exactly determine which error occurred and how I want to handle the situation.
  • Random Password Generators and sourcecode

    These are probably the simplest of random password generators you can come up with in C# or VB.Net. The T-Sql is a little bit fancier, with actually two different random strings being procuded from two choices of "character arrays". Its pretty easy to see whats going on there and pick and choose which way you would want to use. I also programmatically loaded the alphanumeric characters in T-Sql rather than typing them in. Also, the T-Sql isn't in UDF format or SP format, so you will have to make a few minor changes (basically just creating an OUTPUT parameter for the @password variable) to make it work outside of Query Analyzer.
    Update:Changed the C# code per Gerd's comment.

    Update: Get the lastest and greatest Random Password Generator in T-Sql for Sql Server here.

    C#
    
    using System;
    using System.Text;

    public class PasswordGenerator
    {
    private char[] characterArray;
    private Int32 passwordLength = 10;
    Random randNum = new Random();

    public PasswordGenerator()
    {
    characterArray = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray();
    }

    private char GetRandomCharacter()
    {
    return this.characterArray[(int)((this.characterArray.GetUpperBound(0) + 1) * randNum.NextDouble() )];
    }

    public string Generate()
    {
    StringBuilder sb = new StringBuilder();
    sb.Capacity = passwordLength;
    for (int count = 0; count <= passwordLength - 1; count++)
    {
    sb.Append(GetRandomCharacter());
    }
    if ((sb != null))
    {
    return sb.ToString();
    }
    return string.Empty;
    }
    }

    VB.Net
    
    Imports System
    Imports System.Text
    
    Public Class PasswordGenerator

    Private characterArray() As Char Private passwordLength As Int32 = 10

    Public Sub New()
    characterArray = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray
    End Sub Private Function GetRandomCharacter() As Char Randomize()
    Dim location As Int32 = -1
    While Not (location >= 0 AndAlso location <= Me.characterArray.GetUpperBound(0))
    location = Convert.ToInt32(Me.characterArray.GetUpperBound(0) * Rnd() + 1)
    End While Return Me.characterArray(location)
    End Function Public Function Generate() As String Dim count As Int32
    Dim sb As New StringBuilder

    sb.Capacity = passwordLength

    For count = 0 To passwordLength - 1
    sb.Append(GetRandomCharacter())
    Next count

    If (Not sb Is Nothing) Then Return sb.ToString
    End If Return String.Empty End Function End Class

    T-Sql
    
    declare @string varchar(10)
    declare @string2 varchar(10)
    declare @choices varchar(100)
    declare @count int
    
    set @choices = ''
    
    -- load up numbers 0 - 9
    set @count = 48
    while @count <=57
    begin
        set @choices = @choices + Cast(CHAR(@count) as char(1))
        set @count = @count + 1
    end
    
    -- load up uppercase letters A - Z
    set @count = 65
    while @count <=90
    begin
        set @choices = @choices + Cast(CHAR(@count) as char(1))
        set @count = @count + 1
    end
    
    -- load up lowercase letters a - z
    set @count = 97
    while @count <=122
    begin
        set @choices = @choices + Cast(CHAR(@count) as char(1))
        set @count = @count + 1
    end
    
    declare @whatever varchar(100)
    set @whatever = 'JackAndJillWentUpTheHillToFetchAPailOfH20'
    set @whatever = @whatever + 'PittsburghWinsTheSuperBowl'
    
    set @count = 0
    set @string = ''
    set @string2 = ''
    
    while @count <= 10
    begin
        set @string = @string + SUBSTRING(@choices,CAST(ABS(CHECKSUM(NEWID()))*RAND(@count) as int)%LEN(@choices)+1,1)
        set @string2 = @string2 + SUBSTRING(@whatever,CAST(ABS(CHECKSUM(NEWID()))*RAND(@count) as int)%LEN(@whatever)+1,1)
        set @count = @count + 1
    end
    print @string
    print @string2
    
    

  • Data Design Team accomplishments in VS 2005 Beta 2

    Steve Lasker, a program manager over at Microsoft, has posted a great listing of what the Data Design Team has accomplished from Beta 1 to Beta 2. His list is full of intersting items, including Bridging the gap between CLR Null/Nothing and DBNull, TableAdapter Partial Classes and the Typed DataSet, to name a few. Click here to see the post.
  • Oddly named and funny method names

    Brad has a post on "Best" method names ever. There are some pretty good ones in there, and sure to be some more. Go to Brad Abram's blog and post some of your favorites.

    If you want to know one of my favs, my current project has function "f" that takes "this" as a parameter.
  • Satellite photos of the tsunami effect

  • The very first web page ever

    According to Tim Berners-Lee, who is the Director of the World Wide Web Consortium, a copy of the very first webpage ever can be found here. (via Google Blogoscoped.)
  • I've started an online superbowl riot

    Didn't think it would really go this far, but my post of my Superbowl Predictions has gotten 128 comments in the last 8 days and is getting more by the hour. I figured a few of the dotnetjunkies readers would comment and there would be 4 or 5 predictions, but google has kept that from happening. If you go to google and type in Superbowl Predictions, my blog entry comes up first on the list. How far will it go? Its certainly going to keep growing as the big game gets closer. If you want to see some funny banter, and perhaps comment yourself, take a look. Beware, there is a certain degree of profanity and name-calling going on there. Would it be an NFL discussion otherwise?
  • .Net and Sql Server webcasts from Microsoft in January

    For those of you who don't go look, here is a list of .Net and Sql Server related webcasts from Microsoft coming this month:

    1.   
    Wednesday, January 05, 2005 8:00 AM (GMT-08:00) Pacific Time (US & Canada)
    Audience: IT Professional 
    2.   
    Wednesday, January 05, 2005 9:00 AM (GMT-08:00) Pacific Time (US & Canada)
    Audience: Developer 
    3.   
    Friday, January 07, 2005 9:00 AM (GMT-08:00) Pacific Time (US & Canada)
    Audience: Developer 
    4.   
    Tuesday, January 11, 2005 9:00 AM (GMT-08:00) Pacific Time (US & Canada)
    Audience: Developer 
    5.   
    Tuesday, January 11, 2005 1:00 PM (GMT-08:00) Pacific Time (US & Canada)
    Audience: Developer 
    6.   
    Thursday, January 13, 2005 9:00 AM (GMT-08:00) Pacific Time (US & Canada)
    Audience: Developer  
    7.   
    Tuesday, January 25, 2005 1:00 PM (GMT-08:00) Pacific Time (US & Canada)
    Audience: Developer  
    8.   
    Wednesday, January 26, 2005 8:00 AM (GMT-08:00) Pacific Time (US & Canada)
    Audience: IT Professional   
    9.   
    Tuesday, February 01, 2005 1:00 PM (GMT-08:00) Pacific Time (US & Canada)
    Audience: Developer 
  • SQL Server 2005 Technical Overview

    Wednesday, January 5th, Technet webcast for the SQL Server 2005 Technical Overview
    Microsoft SQL Server 2005 is the next version of the SQL Server product family. This new edition offers a number of enhancements to meet the needs of today's environment. This session presents the key areas of SQL Server of interest to the IT professional. We look at various security enhancements including the authentication changes, and we discuss the increased granularity of permissions that the new product allows. We look at availability and the changes to improve service availability and replication of data. We also cover the improvements in the manageability of the product.
  • Must have tools for the .Net developer

    Here are four URLS that contains some must haves for anyone doing .Net development. If you have any more links to great tools you use, post them here so I can add them to my bookmarks. Thanks!



    There you have it. I'm sure there are many tools on those lists that you have and many you don't. A couple of my favs from the list that I use all the time are:
    WhosLocking
    Have you ever tried to copy a DLL and had an "Access Denied" or "Shared Violation" error? Did you have to reboot everytime you needed to upgrade a DLL? If yes, this program is for you!

    Reflector for .Net
    Reflector is a class browser for .NET components. It supports assembly and namespace views, type and member search, XML documentation, call and callee graphs, IL, Visual Basic, Delphi and C# decompiler, dependency trees, base type and derived type hierarchies and resource viewers.

    I don't think this one is on any of those lists, but I use it all the time:
    NDoc Code Documentation Generator for .NET
    NDoc generates class library documentation from .NET assemblies and the XML documentation files generated by the C# compiler (or with an add-on tool for VB.NET).

    And related to NDoc for the VB people, again not on any of the above lists:
    VBCommenter
    Helps to create xml style comments in your VB code, the same way C# does.

More Posts