Thursday, November 24, 2005

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 have a ton of time to play with it but its still handy. I would not recommend using it for any quality code but damn its fast :)

Exceptions are good

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 Address)
if addy is nothing then throw new ArgumentNullException("addy")
end sub

I though this was a lot of extra work but the second a null object gets passed to a method I catch it right where it happens instead of further down the call stack where the object might actually be called. Also when I get the exception I know exatly where to look to solve the issue instead of getting an "object reference not set to an instance of an object" exception somewhere in my code.

Another thing that has really helped (and I did not think it would) was writing in methods that I was going to write later (I have a huge select case statement to handle menu item clicks). In a lot of spots I throw NotImplementedExceptions with details of what is not implemented as the argument. Now I quickly see where I have work to do by searching the code (I could use TODO's I know but usually TODO's are for thinks that are partially complete). Also when testing I get that exception and know that I really need to do that chunk of code as it is accessable to the client in the next itteration.

I have also started making my own generic exception classes. Mainly for the different layers to add a bit of distinction between where an exception happened.



<Serializable()> _
Public Class GrowerBusinessException
Inherits Exception

Public Sub New(ByVal message As String)
MyBase.New(message)
End Sub

Public Sub New()
MyBase.New()
End Sub

Public Sub New(ByVal message As String, ByVal innerException As Exception)
MyBase.New(message, innerException)
End Sub

Protected Sub New(ByVal serializationInfo As System.Runtime.Serialization.SerializationInfo, ByVal streamingContext As System.Runtime.Serialization.StreamingContext)
MyBase.new(serializationInfo, streamingContext)
End Sub

End Class


pretty simple? I think so and it is nice to be able to quickly look at a logged exception and spot where the exception happened even by its type.

Tuesday, November 22, 2005

VB.NET: Stupid ands!

this statement will fail if the column is dbnull

if 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 andalso

if 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.

SQL: not so handy 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 with

declare @cycles varchar(8000)
set @cycles = ''
SELECT @cycles = @cycles + CAST(producer_cycle_id AS varchar(100)) + ', '

from cycles

Note 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!

SQL: Handy 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))
AS
BEGIN
declare @position int
declare @start int
declare @end int
declare @part varchar(8000)

if (charindex(@delimiter, @data) = 0) --if only one value append a , so that it still gets parsed
set @data = @data + ','

set @position = charindex(@delimiter, @data)
insert into @output values (ltrim(rtrim(substring(@data, 0, @position))))

while ((charindex(@delimiter, @data, @position)) <> 0)
begin
set @start = charindex(@delimiter, @data, @position)
set @end = charindex(@delimiter, @data, @start+1)
if (@end = 0)
set @end = len(@data) - @start

set @part = ltrim(rtrim(substring(@data, @start+1, abs(@end - @start-1))))
insert
into @output
values (@part)
set @position = charindex(@delimiter, @data, @position) + 1
end
return
END


To use this is quite easy:

declare @producers
set @producers = '1,7,35,26'

select *
from producer
where producer_id in (select * from dbo.fnStringToCol(@producers, ','))

Friday, November 18, 2005

Tools that make me moist in the pants

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 page
2. Show the DOM of a page in a handy little treeview
3. Easily disable Cache, Images, Cookies, script, or the popup blocker
4. Validate a pages HTML, CSS, XHTML, Feed, links, and some other stuff I don't know about
5. Show image dimensions, filesizes, alt tags, and paths
6. Resize the browser window to any size you want (great for testing a site that needs to be 800x600 compatible)
7. Shortcuts to clear cookies, cache, and possibly session (i.e. server side cookies)
8. A ruler that you can draw on a page and get the pixel measurements of items on the page

thats what I have discovered in ten minutes.

The IE download is here:
http://www.microsoft.com/downloads/details.aspx?FamilyID=e59c3964-672d-4511-bb3e-2d5e1db91038&displaylang=en

Also for the Mozilla/Firefox people out there there is apparently a tool like it that can be found here:
http://chrispederick.com/work/webdeveloper/

AJAX: I finally caved!

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 that most other samples have done is not use xml at all in this (my info.ext file contains only this: "testtest2"). I have no real need to use xml. xml would take more bandwidth, more complex code, and a dependancy on the microsoft XML parser activeXobject. Simple text parsing will do fine for me :)

If your info.ext file is a dynamic page (i.e. asp, php, jsp, etc.) and you want to pass parameters to it do this:

function getData(params)
{
http.open('get', 'info.ext' + params)
http.onreadystatechange = handleResponse
http.send(null);
}


and then in the html:

<a onclick="getData('?action=getdata&id=37)" href="#">get stuff</a>

I assume that you can send post data by changing the method to post in the http.open line and then replace the null in http.send() with the post data you want to send. I have not tried this as it is a bit more than I need.

I hope that gets you started. It really is quite easy even though js is a pain and makes me a little twitchier!

Thursday, November 17, 2005

Windows User Controls: 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)

Wednesday, November 16, 2005

SQL Reporting Services: 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 String
If _properties Is Nothing Then Return ""
Dim sb As New System.Text.StringBuilder

if ShowToolbar then sb.Append("&rc:Toolbar=true")
if ShowParameters then sb.Append("&rc:Parameters=false&")
For Each key As String In properties.Keys
sb.Append(key)
sb.Append("=")
sb.Append(System.Web.HttpUtility.UrlEncode(properties(key)))
sb.Append("&")
Next
sb.Remove(sb.Length - 1, 1) 'remove the trailing &
Return sb.ToString
End Function


NOTE: this function will exit if no properties are passed to it.
Also it would have been beter of me to rename properties to parameters now that I look at it :)

SQL Reporting Services: Print Layout

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 how

goto report -> report properties -> layout
set the width to be 29.7cm
set the height to be 21cm

I wish there was an option that just said landscape though!

Tuesday, November 15, 2005

SQL Reporting Services: 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 services

1. Right Click on the field
2. goto properties
3. Check the Custom Radio box and type one in

you 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 strings
Standard numeric formattings: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconstandardnumericformatstrings.asp

Custom numeric formattings: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconcustomnumericformatstrings.asp

Date time formatting: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemGlobalizationDateTimeFormatInfoClassTopic.asp



Monday, November 14, 2005

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 suck
5. The designer in visual studio does not remember the parameters entered when switching between layout and preview mode
6. I can not find a place to change my rules to metric.
7. Does not seem to be any way to pass a dataset to it or an XML file. I really liked this feature in crystal especially when the reporting layer does not have permssions / access to the physical database
8. Data designer does not like it when objects have different owners. i.e. (I am calling dbo.sp_report which internally joins to a view not owned by dbo... might work if I prefix the view with the owner though)
9. Expressions are VB based which is case insensitive but field names ARE case sensitive!
hence the expression below do not evaluate the same.
iif(Fields!Transaction_Type_code.Value = "BRM", Fields!amount.Value, "")
iif(Fields!Transaction_type_code.Value = "BRM", Fields!amount.Value, "")

Pros:
1. Easy to use
2. .NET formatting support
3. Easy to export reports
4. Easy to design simple reports
5. Integrated designer is awsome as I don't have to publish to preview or reset any databindings
6. Many methods to use the system (url, soap, etc.)


EDIT: Ok you can connect datasets to the report but seems a little involved
http://msdn.microsoft.com/SQL/2000/learn/bi/reporting/default.aspx?pull=/library/en-us/dnsql2k/html/rsdsetex3.asp