May 2006 Entries


Interesting Switch

I have been a fan of Nunit for a while now but recently I have noticed that I never open my UI project on my application. If I add new functionality I write a test case for it to ensure that it works. When I change something internally I run Nunit. I guess I am just amazed at how smoothly it has transitioned to this since I hav added a wack load of test coverage to my project. One of the cool things just happened now and inspired me to write this post. I am refactoring some redundant tables and...

SQL basic like goto statements

A lot of people do not know is that SQL supports the GOTO command and labels just like good old basic. An example is worth a 3.3337 words:       BEGIN TRAN UpdateDetails                update     details         set        payer = @payer         where      payerId=@PayerId                IF @@error <> 0            GOTO   Errorhandler        update     payer        set        lastActivityDate=getdate()        where      payerId = @PayerId        IF @@error <> 0            GOTO Errorhandler    commit tran UpdateDetailsErrorHandler:        BEGIN    ROLLBACK TRAN UpdateDetails        END As you can see that after every statement we run we check the error status and if there is an error we go to ErrorHandler. Pretty easy (and ugly) Now you might wonder why I am checking the @@error after every statement and not just at...

SQL Reformater

I just built a quick little SQL reformater that makes your sql a bit more readable. It takes this:select pmtlndet.pmtlndet_amt, glcdty.glcdty_desc from pmtlndetjoin pmtln on pmtln.pmtln_ID = pmtLndet.pmtln_IDjoin pmt on pmt.pmt_id = pmtln.pmt_idjoin GlCdTy on pmtlndet.GlCdty_id = GlCdTy.GlCdty_idwhere pmt.hostappl_inv_num = @HostApplInvNum and pmtln.pmtStatSubTy_id=@RCRYty_IDand turns it into this: select pmtlndet.pmtlndet_amt, glcdty.glcdty_descfrom pmtlndetjoin pmtlnon pmtln.pmtln_ID=pmtLndet.pmtln_IDjoin pmton pmt.pmt_id=pmtln.pmt_idjoin GlCdTyon pmtlndet.GlCdty_id=GlCdTy.GlCdty_idwhere pmt.hostappl_inv_num=@HostApplInvNumand pmtln.pmtStatSubTy_id=@RCRYty_ID This tool was just a quick one off and does not reformat subqueries very well as well as function calls in the select statement (i.e. isnull(col, 'replacement')) but so far has saved me a ton of time. NOTE: When you click the parse button it automatically copies the reformated SQL to the clipboard.Download

Vista takes 15GB?

I just ran the vista upgrade advisor (tells you if you have the requirements to run vista). and was shocked to get this error:We're sorry, but your PC cannot currently install and run the core experiences of Windows Vista. However, you may be able prepare your computer for Windows Vista by upgrading your PC hardware. You will need to take the following actions to run Windows Vista. Additional hard drive storage15GB free space required (Your computer currently has 3.53 GB)You will either need to:a) upgrade your hard drive to increase its capacity, or b) create additional free space on...

Backups are important

I think backups are usually the most poorely done thing in any organization. Even if you have a backup solution it is very rarely checked to ensure that it is working.1. How often are backups verified / tested. If possible I recommend taking a system and restoring your backup to it and see if everyone can still work.2. How old are your tapes? They don't last forever you know. I don't know the average life but I am guessing at 1-2 years depending on rotation.3. Do you have a rotation (i.e. a tape for every day of...

Paradigm Shift

I like to post on technical things but the state of the industry has really been getting to me so I thought I would right a post about it.In summary: Most of us have no clue what we are doing.I say this because of my experiences in the past year. I can teach anyone to code. Its really not that hard to do the basics but to make a large application is where people stumble (myself included). The reasons for this is that there is no set way to do things. Everyone has their own way...

TDD Last Night

Normally I don't post about life stuff but this is code related. Last night I went to the first edmonton .NET user group meeting and had a great time. Jean-Paul Boodhoo was the presenter and did a great talk about test driven development amongst other things.I have read about TDD and all sorts of patterns books but found them hard to know when to apply them in the real world. JP's presentation was a begging to middle (we ran out of time unfortunately) coding sesssion using TDD to build an application. The cool thing was that we built the application from the presentation tier down pretending that other...

Globalization Link

Here is an interesting article about number grouping in different countries.http://blogs.msdn.com/oldnewthing/archive/2006/04/17/577483.aspx

Canadian Law And The Web Part 3: Peer 2 Peer

Now this is not really a development talk but there is a lot of concern about the legalities of downloading music in Canada and I thought I would set the record straight on it. Part of Canadian copyright grants a fair use for copying things for personal enjoyment as long as it is not shared or sold publically.We actually pay a levy on all media (i.e. blank cassette tapes, blank cds and dvds). This levy is a tax to compensate artists for revenue lost to the copying of their works. So technically we already pay to make copies of music. Unfortunately from what I have read is that...

Setting JPEG Quality

I have many applications that create thumbnails or manipulate images. When I save these as jpegs the quality kind of sucks though. Took me a while but found a way to set it by way of using one of the image.save overloads to pass the encoder to use (in this case the jpeg encoder) and parameters to that encoder.Here is the method taht finds the right encoder based on mime type: 1 private static ImageCodecInfo GetEncoderInfo(String MimeType) 2 { 3 ...

~= friend

One of those nice little things not many people know about is the use of a ~ character in relative URLS. The ~ allows you to access the document root.i.e. <a href="~/showlog.aspx">Show the log</a> If this was in a virtual directory called sampleapp the url would render to behttp://localhost/sampleapp/showlog.aspxbut when deployed to a production and not in a sample app it would behttp://www.sampleapp.com/showlog.aspxif we just had a link without the tilde like this:i.e. <a href="/showlog.aspx">Show the log</a>then it would work in production but in development it would render to the root of the serveri.e. http://localhost/showlog.aspxinstead of the vdir like we...

Sending a file to the client

Sometimes you need to send a file to the client by them clicking a link. If it is stored on your hard drive (appologies for the bad formatting. busy day today):private sub SendFile(fileName as string)dim filepath as string = Server.MapPath("files") & fileNamefilepath = Server.UrlPathEncode(filepath) 'encoded to remove special characters i.e. spacesresponse.clear() 'clear the output bufferResponse.ContentType = "application/binary" 'binaries are almost always downloaded. If it was set to excel for an excel file the browser might try to open it in the browser windowResponse.AddHeader("Content-Disposition", "attachment;filename=" + fileName) 'This is what tells the browser the filename to prompt the user with when they save it...

Canadian Law And The Web Part 2: Copyright

Copyright BasicsCopyright is the right granted to an individual to protect a peice of work he/she has created. This applies to literary, dramatic, musical, and artistic works.Copyright is automatic. Meaning that once you have created a work it is already protected by copyright and you have rights to defend that work from being copied.Copyright protection does not extent to ideas, facts, or information. Meaning that if I came up with an idea for an invention and even wrote it down. It does not prevent someone else from creating that idea. The only thing they can not do is copy what I wrote down. Patents can be used to protect...

Canadian Law and the Internet Part 1

I have a mild interest in law and how it affects me. I have been working with technology for most of my life and there is still not much I can find about how the law relates to what we do in everyday cases. In a series of posts I am going to make I will talk about some of them.DISCLAIMER: I am not a lawyer and the following guides are for information only. They should not be treated as legal advice. Contact a lawyer for any legal questions you might have. Don't play with fire. It is hot. You might get burned. Yada yada yada.Accessability:From what I...

Determining if a session has expired

The first thing to discuss is Session.IsNewSession() this returns true if a session was just created on this request.On the first request to a page this will return true.durring the session it will return falseafter a timeout error occurs this will also return true (the session no longer exists so it gets recreated).So we know that if IsNewSession() returns true that either this is a new request or the session has timed out.Now the way that sessions work is the server sends the browser a cookie with the session ID. On every request the client sends this cookie and the server loads...

Why not to depend on client side validation

A great example on why not to depend on client side validation only:http://thedailywtf.com/forums/65974/ShowPost.aspx

GUIDS in the Database

For those of you who don't know what a GUID is it is a 128 bit value that is "Unique across space and time". A GUID looks like this: B2658C9D-A76G-4D72-B0E4-B732332408D6. There garanteed uniqueness has been used by the com+ system in windows for years. This is why two com components with the same name can be installed without conflicting (they each have a GUID that keeps them seperate).Developers seem to be pessimistic about GUID collissions in their systems. I just have to say that it will not happen. As I said com+ has been using this forever and I have never heard of a GUID collission ever....

Removing while iterating through a collection

Often times developers want to loop through a collection and filter out items. Unfortunatley they get the error that they can not change the contents while enumerating it. There are 2 solutions to this problem1. Copy the records to be removed to an array or collection of some sort and then remove them in a second loop2. Run it through a for loop backwards and remove the entries as needed Dim refRow As dataRow For i As Integer = ds.tables(0).Rows.Count - 1 To 0 Step -1 ...

Javascript rounding errors

I have this in code:var total = parseFloat(txtGLItemAmount1.value) + parseFloat(txtGLItemAmount2.value)when I insert 110.16 and 7.74 I should get 117.90 but instead get 117.8999999999Pretty freakin weird! I assume this has something to do with floating point math and all its weirdness. The fix I found for this was this line:total = total.toFixed(2);This yeilds the correct value. I bet that I could do this as well to get it correct:var total = txtGLItemAmount1.value.toFixed(2) + txtGLItemAmount2.value.toFixed(2);

Thread Locking

One thing that you have to worry about in a multithreaded application is the problem of concurrency in that you do not want two seperate threads acessing a value as it is changing. .NET has a method to solve this and it is called locking.In c# it is Lockvb it is SyncLockpublic property GetId() as integer get syncLock me return _id end syncLocl end get set (value as integer)...

Controls and Threading

    Controls are not thread safe! you should never try to access a control or modify it from a different thread than the one the control exists on. If you do strange results will happen.Fortunately controls have two methods that help us overcome this issue with ease.control.invoke() to do simple tasks and control.beginInvoke() for longer running tasks that we want to have happen on a background thread.Here is a simple example of using beginInvoke()dim params() as object = {me, System.EventArgs.Empty}control.BeginInvoke(new System.EventHandler(Addressof UpdateUi), params)private sub UpdateUi(sender as object, e as eventArgs){ lblStatus.text = "Finished"}as you can see we pass in an array...

Objects make code expandable

    thats pretty much it. I am a big fan of oop and am working on a project that is not. It now takes me so much longer to do anything and it has a huge impact on the code base and its consumers.I have one method like this:CreateCashout(clerkId as integer, officeId as integer, cashTotal as double, creditCardTotal as double, debitTotal as double, PaymentIds() as integer)This is then validated and passed to the same method signature in the data layer.So for one I have a long method signature. Some of these items will be zero (i.e. debit totals for some consumers) so why make them put...

Backing up all user databases

I run a small hosting provider and one of my issues is backing up SQL databases. Everytime I create a database I have to create a script to back them up. Here is a handy script that I found and modified a bit that will backup all databases to a specified folder. It also keeps a retention history for a user defineable number of dayshere is a sample usage:isp_FullBackup_UserDBs 'c:\backups', 10this will backup all user databases (note it wil not backup the master database) and keep a history of 10 days.------------------------------------------------------------------------------------------------------ OBJECT NAME ...

Security Rant

Just a quick note on security while it is in my head1. Use an accept list instead of a deny list. i.e. use a regular expression that matches [A-Za-z0-9] vs. ![/*.()<>\......] if you miss one character then your validation is useless. The first validation allows only alphanumeric characters. All else are excluded by the rule.Microsoft had this issue with IIS 5 (I beleive) in that people were exploiting it by using the urlencoded values to do directory transversal i.e. www.victim.com/%2c%2c/%2c%2c/%2c%2c/c:\windows\system32\command\cmd.exe(now that is from memory so don't shoot me)If the processor only accepted .. instead of %2c things would have...

Throwing Exceptions Part 2

Sometimes you need to change an exceptions type (usually to a custom exception type) but still want to maintain stacktrace information (read about this issue in part1). Well it is really easy just look at this example 1 2 Public Sub Layer2() 3 Throw New NotImplementedException 4 End Sub 5 6 Public Sub LogError(ByVal ex As Exception) 7 ...

Throwing Exceptions

    Don't do this: 1 Public Sub DoTask() 2 Throw New NotImplementedException 3 End Sub 4 5 Public Sub LogError(ByVal ex As Exception) 6 'TODO: log the error 7 End Sub 8 9 Private Sub Button1_Click(ByVal sender As...

System.Net and max number of connections

when using HttpWebRequest, HttpWebResponse, The webBrowser class or pretty much anything relating to doing HTTP transactions there is a limit on the number of connections you can have to a server. This limit is defined by the HTTP RFC (no idea what number it is). This is why with internet explorer you can only download 2 files from a server at the same time.Unfortunately with building an application you might have 30 clients all requesting a component that calls out using one of the HTTP classes.<configuration> <system.net> <connectionManagement> <clear/> ...

Boggled by Logistics

Check this out: http://preview.local.live.com/basically allows you to drive down streets in Seattle or San Fran.What really amazed me was turning to the side and seeing a picture of a store front. I have no idea how all of these pictures could have been taken and assembled.I am waiting for a real time driving simulator now so that I can get around a city before I arrive there (sorry I am a dork).

Side by Side Versioning With COM+

Today I discovered that when you try to install a com+ (or enterprise service if you want) componenet written in 1.1 of the framework on a system that has 2.0 also installed that you can not install some componenets. I have no idea why or how to fix it besides uninstalling 2.0 then installing your componenet. Then reinstall 2.0 after if you need it....weird!

Unit testing and the database

I have been playing with unit testing for over a year now and really see the value in it. Most of the time you build your tests along with (or before in the case of test driven development) your code. But I have even found it valuable to write tests for code I have already written in the past if I am going to have to make a change. I usually only write a test for the method I am about to change, make my change and then see if my test still passes.One of the things that I hate is how many articles recommend to mock...

My toolbox

-FxCop. Great tool for keeping code consitant-Nunit. Unit testing tool-CopyAsHTML (great for blogging / documentation)-DataSet Quick Watch (http://www.codeproject.com/csharp/DSWatch/DSWatchSetup.zip) Great tool for seeing a dataset in a datagrid while debugging-Firefox FFox plugins -IE Tab (opens a page that is only ie compatible within firefox) -Sage (nice little newsreader) -Web Developer (if you do work with the web get this... period) -Adblocker

What are we doing wrong

I recently had a rant about us as developers not having a clue what we are doing. I want to try and narow this down into a few areas that I think need improvement.1. Testing. We don't take a step back and look at different scenarios. Whenever I develop something it is to do a task and that is what I test. I never test a method to see how it react when different data then the scenario is added.2. UI. I never make an application useable. Its not because I hate the user but that...

Marking a method as obsolete

I am currently working on an enterprise system that already has several consumers. There are several methods that have been replaced by newer methods and I want the clients to stop consuming the old ones. Unfortunately if I just tell them to use the new ones they wont, and when I release a new version and it breaks they will complain. I found a neat way to deprecate a method 1 _ 2 Public Function oldWay() As Boolean 3 4 End Functionnow whenever...

XSTL / XML and the information bar

I am trying out XSLT w/ XML for a project I am doing. Basically the website has a page for each staff memeber with a bio, phone, website, email, photo, etc. The client does not want to pay for a database solution which I would normally do so I decided to try XSLT (If you have no idea what XSLT is you should check out the quick tutorial at www.w3schools.com). Well found a few snags but the one that bugs me the most is the information bar in internet explorer that says it "blocked content that may harm my computer". After some playing and diggiing I found that...

State management technique

One thing that I hate is how most developers access session or cookies like this 1 Dim firstname As String = Session("firstName")and then 100 times in the application you have the hard code of firstName. About a year ago Tim showed me this very simple and effective way to centralize this. I don't know if there is a name for this technique but I sure love it: 1 Public Class StateManager 2 Public Shared Property FirstName() As String 3 Get...

Gateway Pattern

One of my favorite patterns is the gateway pattern. Basically it is setting up one class that all requests for a certain action run through. The time I use this the most often is when accessing an external service.For example lets say that I use an external service multiple times in an application (in this case I am accessing over a webservice but it could be com, remoting, a database, almost anything)In my example I have an external web service that I use to find the customers ID via a phone number. 3 Public Class Payment 4 ...

Classifying Programers

I was recently asked in an interview how I classify programmers. I found it interesting as there is no set classification of programmers. Here is what I came up with:Junior Programmer-Programmer has difficulties with the language itself (e.g. declaring objects, using properties, sizing of arrays)-Programmer is not familiar with a lot of the builtin functions/objects in the language (e.g.-Programmer is not comfterable / aware of OOP.-Programmer usually has no understanding of interfaces-Programmer usually can not forsee how to implement a solution and needs to be instructed on the steps to take to acheive the end result.Intermediate Programmer-Programmer is comfterable with the programming language-Programmer is...

Getting current method info via reflection

I have an application that logs information when each method runs: 1 Public Function GetRefundsByID(ByVal id As Integer) 2 'implementation 3 4 LogMessage(String.Format("GetRefundsByID found {0} records", count)) 5 End FunctionI dont really like this as I have now hardcoded the name of the function into each method which really sucks when I rename a method.I managed to figure a way to get the current method name...

Dynamic Order By's

Here is cool technique I saw here (http://www.sqlteam.com/item.asp?ItemID=2209)Basically I knew of no way to do a dynamic order by / group by without creating dynamic sql i.e.DECLARE @SortOrder varchar(30)DECLARE @sql varchar(8000)SET @SortOrder = 'CompanyName'set @sql = 'SELECT CompanyName, ContactName, ContactTitle FROM Customers ORDER BY ' + @SortOrderexec(@sql)This sucks as SQL can not validate the syntax, the engine can not cache the execution plan, and this could open up a SQL injection attack (I am pretty sure that sql will filter...

Why I Hate oracle

I unfortunately keep running into places that need to migrate oracle or I have had the unfortunate responsibility of teaching it. I absolutely can not stand this product and I have a list why:1. Cost. what an expensive POS.2. useless junk. Oracle ships with tons of utilities that will never need to be used3. Bloated install. Installes several apache instance / services I don't need4. GUI = the suck. I have never used such hard management tools5. no good query tool. The query tools appear to be wrappers around their dos sql utility. Its like microsoft word using dos's edit command for an engine.6. TNS...

Parsing File / Directory Strings The Easy Way

I recently discovered some builtin classes to parse file paths instead of awkward .IndexOf / substring combinationsdim filename as string = "c:\windows\temp\stuff\myfile.txt"the IO.Path has many shared methods that allow parsing and manipulationIO.Path.ChangeExtension(filename, "xml") 'c:\windows\temp\stuff\myFile.xmlIO.Path.Combine() 'have not played with this one yetIO.Path.GetDirectoryName(filename) 'c:\windows\temp\stuffIO.Path.GetExtension(filename) ...

Custom Event Args

I don't know if there is a name for this pattern or not but I have found that it is quite helpfull. When creating custom events it should only have two parameters. One being the object that raised the event and the other should be an object containing data.I like examples so lets start with these two classes:public class MyApp private withEvents eventClass as MyEventRaiser private sub DoTask() eventClass.DoTask() ...

Heap vs. Stack

I found these three articles really good regarding the heap and stack.Part Ihttp://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx?ArticleID=9adb0e3c-b3f6-40b5-98b5-413b6d348b91&PagePath=/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspxPart IIhttp://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory2B01142006125918PM/csharp_memory2B.aspx?ArticleID=c31e9a39-d364-429f-a4fa-0a60444d3add&PagePath=/UploadFile/rmcochran/csharp_memory2B01142006125918PM/csharp_memory2B.aspxPart IIIhttp://www.c-sharpcorner.com/UploadFile/rmcochran/chsarp_memory401152006094206AM/chsarp_memory4.aspx?ArticleID=4f58d369-9e0c-4f7a-8a84-5883faade356&PagePath=/UploadFile/rmcochran/chsarp_memory401152006094206AM/chsarp_memory4.aspx

Delegates in vb.net Part 3

The next item in delegates I want to cover is returning data. In my previous example we called a sub that did a task (writing out a file) but it did not return any data or notify us that we were done. To accomplish this we are going to use a delegate with a callback method.Here is the code I am going to start with:Private Sub StartTask() Dim del As New DoLongTaskDelegate(AddressOf DoLongTask) del.BeginInvoke("c:\temp.txt", Nothing, Nothing)End SubPrivate Delegate Function DoLongTaskDelegate(ByVal filename As String) As IntegerPrivate Function DoLongTask(ByVal filename As...

Delegates in vb.net Part 1

    A delegate also has built in methods that allow background execution of the method it points to which is what we are going to use here. Most times I start a task on a background thread I use Thread.Start(). Unfortunately if you have a method that takes parameters you can not use Thread.Start. Instead we will use a delegate which will allow us to pass parameters to a method running on another thread.I have a project where I need to write to a file on a background thread. The WriteFile method takes one parameter (the file path).public sub WriteFile(byVal outputFile as String) ...

Delegates in vb.net

    For those of us that are not C# developers we rarely deal with delegates. A delegate is simply a strong typed pointer to a method. C# uses this extensively for wiring of events. VB.NET actually builds the event delegates for us behind the scenes.Here is a quick example of a simple delegate:Public Delegate Sub TrafficLightChangedEventHandler(ByVal color As String)Private Sub TrafficLightChanged(ByVal color As String) MsgBox(color)End SubPrivate Sub StartDelegate() Dim del As TrafficLightChangedEventHandler del = New TrafficLightChangedEventHandler(AddressOf TrafficLightChanged) del.Invoke("Red")End SubWhen startDelegate gets called we create an instance of the Delegate and...

Image overlay using GDI

Recently I was asked to build a website that when a property got sold a little sold sticker appeared in the upper corner of the image. I thought this would be really hard based on my experience with php image manipulation. With .NET and GDI+ it was so easy. Here it is:Dim baseImage As ImageDim overlayImage As ImagebaseImage = Image.FromFile("c:\house.jpg")overlayImage = Image.FromFile("c:\loginButton.jpg")Dim gr As Graphicsgr = Graphics.FromImage(baseImage)gr.DrawImage(overlayImage, 10, 10)Me.PictureBox1.Image = baseImageThis is easy to change to load from a stream / save it to a web output stream (baseImage.Save(Response.OutputStream)).

Alternating item color in Reporting services report

    To my supprise Reporting services does not seem to have support for an alternating item color when displaying a table (well that I can find at least). After some playing I came up with a simple little iif statement.Simply set the rows Background color in the properties pane to this:=iif(RowNumber(Nothing) Mod 2, "LightGrey", "White")

Determine a drive type

I am currently working on a project that imports data from a SD card and I wanted an easy way to find the drive letter that windows creates for the device so that it was defaulted for the user. After a bit of searching I found that I could use WMI to do this and it is quite easy. Here is my implementation: Public Enum DiskDriveType Unkown = 0 NotRootDirectory = 1 RemovableDisk = 2 ...

Checking if you are connected to the internet

I have not tested this but it looks legit:[DllImport("wininet.dll")]private extern static bool InternetGetConnectedState (out int connectionDescription, int reservedValue ) ;public bool IsConnected() { int connectionDescription = 0; return InternetGetConnectedState(out connectionDescription, 0);}

Refactoring and Comments

If you have not read Martin Fowlers book Refactoring then you should. There is no book that I have read that has helped me more in what I do everyday. The book basically gives techniques on how to make code better and easier to work with after it has been written. One of the most used and common refactorings is "extract method". This is where you take a chunk of code and pull it into its own method. (eg. http://www.refactoring.com/catalog/extractMethod.html).I so love the idea that a method does one task and that is it. If it does two tasks then the method calls two methods (one for...

SQL Reporting Services: Deploying Reports To Production

I can not beleive how hard it is to deploy reports to production! Its easy for development. Just tell visual studio where the server is and bang! its done. I spent most of today trying to figure out how to deploy to production without having to manually upload each report through the web interface and then manually linking them to my shared data source.I tried writing a vb script to do it which I got 90% their but could not link to a shared datasource. Microsofts documentation of the scripting commands you can do ARE GARBAGE! when trying to set a property you need to send a name...

Lostfocus = crap?

I discovered something interesting with the LostFocus method. Leaving a feild by clicking out of it does not always fire the LostFocus event. The reason for this (from my understanding) is that if the control runs through validation the CancelEventArgs object is set to true. This causes all events after it (in this case LostFocus) to not be fired. In order to work around this use the Leave, Validating, or Validated events.

.NET string comparisons

typically most developers compare strings in a case instensitive way like this:if var.toLower = "expected" then ...end ifthis way is a little inneficient and does not take into account cultural differnces (some languages use groups of letters to signify one letter, some letters follow uppercase / lowercase rules differently).for comparisons I use this everywhere now:If String.Compare(var, "expected", True) = 0 Then...end ifI wish it would return a boolean though. it returns less than 0 is var is less than expected0 if they are equalgreater than 0 if expected is greater than var

Debug and Release config files

One of my biggest issues was having certain lines in my config file for working in my developement shop and others for production. Whenever a bug was found or the application was released you would have to swap configs around. After a few years of reading I happened accross this method:AppDomain.CurrentDomain.SetData()The first paramaeter is the name of the domain property we want to change, and the second is the value.I have this line in my application as the first line of code to be called#If DEBUG Then AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", "c:\debug.config")#End Ifyou can also retreive the data using this:appDomain.CurrentDomain.GetData("APP_CONFIG_FILE")for a list of...

How did I miss this? Not that I care.

I discovered an "interesting" feature in vs2003 (and assumedly others). For a winform application when I went to "add new item" there is an entry in their called "Data Form Wizard". This little wizard allows you to connect to a database and build a quick screen that is bound to the data that you can add, edit, delete from. It looks terrible, it has no sepration of tiers but if I need to make a quick screen to access a database this tool saves tons of time. I think there is also an output to a datagrid so that you can edit in the grid. I don't...

Exceptions are a good thing (well custom ones at least)

I have been playing with FxCop for the past 4 months and I just love it. For those of you who don't know FxCop is a code analysis tool that spots violations of coding standards, i.e. casing of methods, parameters,etc. but it also makes recomendations like when to convert a method to a property, when to make a method static / shared, unused methods / fields, and a whole host of other things. You can get it from www.gotdotnet.com.This program recommends that any public method that takes an object be checked to see if the obejct is null and throw an exception if it is.public sub DoTask(addy as...

VB.NET and and also

this statement will fail if the column is dbnullif not reader.item("age") is dbnull.value and reader.item("age") <>....It fails because vb for some reason evaluates all conditions in the statement and then determines wether it is true or false. To get around this use andalsoif not reader.item("age") is dbnull.value andAlso reader.item("age") <>....this will evaluate the first condition and if the first condition is true it will evaluate the second one. This can also be usefull when the second statement is process intensive.

Not so handy SQL function

I ran into a strange situation today. I need to make a comma seperated list of values in tsql here is what I came up withdeclare @cycles varchar(8000)set @cycles = ''SELECT @cycles = @cycles + CAST(producer_cycle_id AS varchar(100)) + ', 'from cyclesNote that this function does not work very with nulls (hence why @cycles is initialized to ''. If you have null data make sure you have an isnull() in their to convert it!

Handy SQL Function

I have a lot of stored procedures that I need to retreive, update, delete multiple records based on ID (usually on a screen where a user can select the customers to run a report on). I have seen a lot of developers create dynamic sql (which I hate) or call the same stored proc multiple times (which I hate). I created a little sql function that takes a string of delmited data and turns it into a table:CREATE fuNCTION fnStringToCol (@data varchar(8000), @delimiter varchar(100))RETURNS @output TABLE (data varchar(8000))ASBEGIN declare @position int declare @start int declare @end int declare @part varchar(8000) if (charindex(@delimiter, @data) =...

Cool web tool

It has been a long time since I saw a peice of software (Especially a plugin) that makes me go "Wow how did I ever live without this / why didn't I think of that?". I have only played with the IE Dev toolbar for 5 mins now and I had to write about it.1. Allows you to hightlight all tables or table cells or divs on a page2. Show the DOM of a page in a handy little treeview3. Easily disable Cache, Images, Cookies, script, or the popup blocker4. Validate a pages HTML, CSS, XHTML, Feed, links, and some other stuff I...

I finally caved to AJAX

I had played a little with AJAX (Async Java and XML) but I finally caved and started to use it in an app. I must say that it is pretty freakin sweet but I am still concerned (as always with javascript) how it will behave in different browsers and operating sysystems.<script>;function CreateRequestObject(){if (navigator.appName == "Microsoft Internet Explorer") return new ActiveXObject("Microsoft.XMLHTTP")else return new XMLHttpRequest();}var http = CreateRequestObject();function getData(){ http.open('get', 'info.ext') http.onreadystatechange = handleResponse http.send(null);}function handleResponse(){ if (http.readyState == 4) { var data = http.responseText; var arr = data.split(""); alert(arr[0]); }}</script><a onclick="getData()" href="#">get stuff</a>Now this is a basic example but one thing that I have done...

Permission Generation Script

Here is a hany security script that will generate the grant execute / select /delete permissions on all objects in your database if you have the need to do so:Declare @RevokeSQL varchar(1000)Declare @GrantSQL varchar(1000)declare @EveryoneRoleName varchar(30)set @EveryoneRoleName='Public'set nocount onselect P.ID, U.Name as UserName, o.name as ObjectName,case P.ProtectTypewhen 204 then 'GRANT_W_GRANT'when 205 then 'GRANT'when 206 then 'REVOKE'end as ProtectType,case p.actionwhen 26 then 'REFERENCES'when 178 then 'CREATE FUNCTION'when 193 then 'SELECT'when 195 then 'INSERT'when 196 then 'DELETE'when 197 then 'UPDATE'when 198 then 'CREATE TABLE'when 203 then 'CREATE DATABASE'when 207 then 'CREATE VIEW'when 222 then 'CREATE PROCEDURE'when 224 then 'EXECUTE'when 228 then 'BACKUP DATABASE'when 233...

Dynamic SQL Avoidance

I have several stored procs that take a flag that tells them wether to show expired records or not and usually looks something like this:DECLARE @ShowExpired tinyintSET @ShowExpired = 1declare @sql varchar(1000)set @sql = 'SELECT * FROM TABLE'IF @ShowExpired = 1 set @sql = @sql + ' WHERE eff_end_dt is NULL"execute (@sql)While this works fine if I loose the advantages of stored procs and if I rename a table and recreate the procedure (I periodically recreate all procedures to test this) then I will not see any error.Instead I came up with this:DECLARE @ShowExpired tinyintSET @ShowExpired = 1select * from Tablewhere...

SQL Coding Standards

I love the formatting of SQL from this article.http://msdn.microsoft.com/sql/default.aspx?pull=/library/en-us/dnsqlpro04/html/sp04l9.asp

Interesting article

    http://blogs.msdn.com/oldnewthing/archive/2006/05/09/593605.aspx

Code Camp Calgary Review

I decided to make the trip down to Calgary to check out code camp and I thought I would share with everyone.WinFX - John BristoweWas a fairly good presentation about the new things comming out from MS.Windows Presentation Foundation - Nice look at the unification of mfc, forms, directx but a little bit of overkill. I hate the idea of XAML (markups for forms). Its cool to have 3D apps with animations but not usefull in the business world. Users want fast, functional, easy. Users have a hard enough time with their coffee cup holder let alone a 3D animated interface.Windows Communication Foundation - Was a...

Refactoring an Enterprise Application

I am in the process of refactoring a fair sized com application that is consumed by many other applications. When the system was designed all data between the com system and the clients was via a dataset interface. This has caused lots of issues with naming, required fields, etc. so here is my plan to refactor it out while still preserving client compatability1. As I do work create objects that are representitive of the entities being passed in2. Create transformer objects that change the method from a dataset to an object and back again (testing this thoroughly of course)3. Change the Data layer to use these new...

Dave's 9 rules of Business

Here are a few of my rules for business. Some of these don't apply to programmers but they are observations I wanted to share.1. Business certificates can make a lot of money. -For one they are usually gifts to people and either the receiver will not have a use for the item or else they will loose it. I have no stats to back this up the number of unused gift certs out there must be high. ...

Validator Controls and IE

I developed a little app last night that used the builtin ASP.NET validators. Now that I am running firefox as my default browser I have discovered that the validators client script does not work in anything other than IE. The reason for this is that the BaseValidator class (all validation controls derive from this class) have methods the emit javascript to do the validation. This script also contains an array of validator controls and summaries that looks like this:var Page_ValidationSummaries = new Array(document.all["ValidationSummary1"]);var Page_Validators = new Array(document.all["RequiredFieldValidator1"], document.all["RequiredFieldValidator2"], document.all["RequiredFieldValidator3"], document.all["RequiredFieldValidator4"], document.all["RegularExpressionValidator1"], document.all["RequiredFieldValidator5"]);And therin lies the problem. Only IE uses document.all every other browser I know off does not recognize document.all. Instead what should...

Paradigm Shift

I like to post on technical things but the state of the industry has really been getting to me so I thought I would right a post about it.In summary: Most of us have no clue what we are doing.I say this because of my experiences in the past year. I can teach anyone to code. Its really not that hard to do the basics but to make a large application is where people stumble (myself included). The reasons for this is that there is no set way to do things. Everyone has their own way...

Transparent Backgrounds

For some reason by default user controls do not support background colors making it a real pain when placing the controls on gradient or image backgrounds. to overcome this put the following line in the initilize component method of your user control:Me.SetStyle(ControlStyles.SupportsTransparentBackColor, True)

URL Generation Code

Here is a little method I made to build the query string to pass to reporting services.-showToolbar shows or hides the toolbar with paging, printing, exporting, etc.-showParameters shows or hides the entry fields that allow a user to change what values the report is generated from-properties is a name value collection of parameters that you can supply to the report to generate it instead of the user having to type them into the boxes if ShowParameters is on.Private Function BuildPropertyString(showToolbar as boolean, showParameters as boolean, properties as NameValueCollection) As StringIf _properties Is Nothing Then Return ""Dim sb As New System.Text.StringBuilderif ShowToolbar then sb.Append("&rc:Toolbar=true")if ShowParameters then...

Printing Data

Working on more reports today and discovered that reports print in standard format and I have several I need to print in landscape mode. I finally figured out howgoto report -> report properties -> layoutset the width to be 29.7cmset the height to be 21cmI wish there was an option that just said landscape though!

Formatting Data

One of the cool things I discovered today was that you can use .NET formatting codes when formatting data for output with reporting services1. Right Click on the field2. goto properties3. Check the Custom Radio box and type one inyou can type in 'c' for currency formatting that is locale specific, 'd' for decimal output, or 'p' for percentage.I needed a custom one that had a number formatted by commas with no decimal places so I simply typed in ###,###,### and viola!More info on format stringsStandard numeric formattings: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconstandardnumericformatstrings.aspCustom numeric formattings: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconcustomnumericformatstrings.aspDate time formatting: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemGlobalizationDateTimeFormatInfoClassTopic.asp

SQL Reporting Services: Impression after two weeks

Beefs:1. Report wizard comes back with weird errors when a query is not right. When you run it in query analyzer the actuall issue gets reported and is easy to correct.2. Can not use a stored proc that has multiple result sets.3. The report wizard will not work in some scenarios when using a temp table or a table variable.4. MSDN documentation = the suck5. The designer in visual studio does not remember the parameters entered when switching between layout and preview mode6. I can not find a place to change my rules to metric.7. Does not seem to be any way to...