Thursday, December 13, 2007

I'm still so SO super busy. That said there's some sql stuff I wanted to post.

Copying One Table To Another
Want to copy all the data including the structure (with the exceptions of the constraints) to a new database?

Insert Into NewDatabaseName
Select * From OldDatabaseName

Want to just copy the structure without the rows?

Insert Into NewDatabaseName
Select * From OldDatabaseName
Where 1 = 2

What could be easier.

Unions
Unions are pretty cool. That said if you're using text, ntext, or image types you need to use a Union All. If you don't you'll get an ugly error like this:

Server: Msg 8163, Level 16, State 4, Line 1
The text, ntext, or image data type cannot be selected as DISTINCT.

Stored Procedure Output Parameters
If you're running a stored procedure that returns a data set you'll need to call SqlCommand.ExecuteReader(). If you also have an output parameter specified in the procedure you might be tempted to do something like this:

sqlDataReader = command.ExecuteReader();

string outputParam = command.Parameters["foo"].Value;

while (reader.Read()) {
//read your rows
}

reader.Close();
command.Connection.Close();

The above code will compile fine but you'll get strange exceptions on the line where you're reading out the param value. If you investigate you'll find that even though command.Parameters["foo"] isn't null command.Parameters["foo"].Value is. That's because when you're using a sql reader you need to close the reader before you can read the output param(s):

sqlDataReader = command.ExecuteReader();

while (reader.Read()) {
//read your rows
}

reader.Close();
string outputParam = command.Parameters["foo"].Value;
command.Connection.Close();

Now you know. And knowing is half the battle.

Friday, November 16, 2007

I've been crazy busy lately. I'm still crazy busy but I've decided to make a post here. I'm going to start posting little snippets of code that I've found useful or problems that I've resolved that I want to keep the solution to around.

Log story short I needed a TreeView to postback when the checkbox associated with an element changed. This search led me to This Post. The solution proposed there works great however there's one issue that took me a long time to hunt down. The last post on the page lists some script to spit out after you've created your object:

<script type=\"text/javascript\">
if (document.all) {
document.getElementById(YOURIDHERE).onclick = foo;
}
</script>

This code works great in IE but doesn't in Firefox. It took me a long time to figure out why but it's due to the document.all like. Firefox doesn't support document.all. If you see that somewhere and like supporting firefox users then don't use it. That's all for now.

Monday, October 22, 2007

On Prefix and Postfix Increment Operators

For those familiar with increment operators and their prefix and postfix usage skip down to just below the pseudo-code.

When you have a number and you want to increment it while stepping through a collection or something you can use the increment operator ("++"). That will add one to whatever number you pair with the operator. When using increment operators there are prefix and postfix forms. The prefix form is when you put the operator before the variable containing the number and the postfix is afterwards (++i vs. i++). Functionally these the placement results in very different functionality, if you use the prefix form then the number is incremented before it is evaluated whereas if you use postfix then it is evaluated after it's value is used. In other words (this is really simplified pseudo-code):

variable n = 0;
print n;
print n;

Will print the number 00.

variable n = 0;
print ++n;
print n;

Will print 11.

variable n = 0;
print n++;
print n;

Will print 01.

Awesome, let's continue.

The issue I have with this is that I can only use one at a time. I just came across a scenario where I actually got kind of excited about a line of code I had just written (which doesn't happen very often). The scenario was that I had a string containing tokens I needed however each token I needed was surrounded on both sides by tokens that I don't need. So I had something like:

;junk;ValueICareAbout;junk;junk;ValueICareAbout;junk;

This led me to writing the following lines of code:

for (int i = 0; i < tokens.Length; i++) {
  string token = tokens[++i++];
  Trace("Found Token: " + token);
}


Sadly the compiler informed me that what I had done is totally not allowed. Which made me sad. Because ++i++ looks awesome. And yes, I do realize that I'm a huge dork.

Tuesday, October 16, 2007

Freelance Finances

While I'm waiting for a 175mb SDK to download I thought I'd update since it's been a while.

Last month I brought in about a third of what I was bringing in at my former real job. This month is looking like it'll be a little more but it might not be by much. While I can have a month or two like this I don't know that I can have 3 months in a row like this. Savings can certainly help support us but that's not their intended usage. There are several things that I think I've learned or that have been reinforced by the current lack of extra funding:

Save In Times Of Plenty
I'm really good at spending money. REALLY good at it. It's really easy to look at your bank account balance and justify some purchase or another since you have the money when in reality you're not going to get a whole lot of use out of something. Having money saved away will help get through the sparse times.

Lower Your Standards
One thing I struggle with is pride. Especially when it comes to the things I have. This is especially true of the car that I drive. We have a Mini Cooper that we recently paid off. It's nice having it paid off (and certainly helps for months when I'm not bringing in a whole lot) but we're still paying more on insurance and it's expensive to maintain since it's more or less a BMW. My car has been a source of pride since I finished college and got a shiny new Subaru WRX.

All that said I don't need it. I don't need to spend money on every shiny object that catches my eye.

Re-Evaluate Your Priorities
This whole freelancing thing didn't start out as a way to make huge amounts of money. It would be nice if it started making me huge amounts of money but that's not one of the primary goals. I need to try to remember the other benefits of freelancing and weigh those into decisions that I make about my employment. What're the other benefits? I have so SO much more freedom with my time. I'm learning a whole lot in a variety of technologies. I'm my boss, if I'm working on projects that I don't like or don't like working with a specific client I don't have to. Overall I'm more in control of my time and how I spend it.

My download is done, back to work.

Thursday, September 27, 2007

Family-Work-Life Balance

The Family & Parenting Reporter for the Seattle Post Intelligencer Paul Nyhan made an interesting post last night about Work-Family Balance: Work-Family Balance is a Joke: Embrace the Chaos

The post talks briefly about efforts towards new family leave law in Washington and then moves on to an evaluation over whether a happy Work-Family Balance is actually realistic and attainable. He concludes that it isn't and that working parents need to roll with the punches.

I'm not sure how I feel about the phrase "Work-Family balance." Typically when I hear the term Work-Something Balance it's "Work-Life Balance" that's being talked about. I've never heard anyone without kids refer to their "Work-Family Balance." Perhaps it's only once we have kids that family actually factors into the equation.

I think that the phrase for everyone should be Family-Work-Life balance. Family comes first, then work (gotta pay the bills), and then you can squeeze in some time for yourself after you taken care of your family and your work is in order. Not that this is the arrangement of my priorities all the time but it's something to shoot for. Actually, the thing to shoot for is Family-Life-Work but that's really hard to do. Focus on your family and living your life and let work be an afterthough. Work to live vs. the other way around and all that.

Finding time for yourself is definitely a challenge even as a single person with a full time job let alone as a parent. Pamela Slim (who maintains the Escape From Cubicle Nation blog) posted yesterday morning about 8 Strategies to get the most from painful or awkward life transitions. A lot of the strategies she posted definitely apply to parenting and the attempt to maintain some sort of balance. In an effort to not copy the meat and potatoes of her post into mine I'll say you should go check out her post. I'll end this with a quote from that post that I really liked:

The interesting thing is that no matter what the ultimate benefit of a change, going from "what was" to "what will be" can be very unsettling.

Saturday, September 22, 2007

The Excel Interop

I just finished up a project working on a win32 client application that is used to import data from an Excel spreadsheet into a database via a secure web service. Working with the interop was interesting and it was nice to get exposed to something new. I'll post more about web services later (as well as returning custom data types via web service methods, serializable Dictionary objects, and converting rtf to html) but I wanted to rant about the Excel Interop a bit.

Indexing
When I started working with the interop I went in and created an instance of Excel:

Microsoft.Office.Interop.Excel.Application excelObj = new Microsoft.Office.Interop.Excel.Application();


This is all well and good. After that I set visible to false and went about starting to access some of the bits and pieces in my xls file. Oh, and because we're using C# and because Open isn't overloaded:

Microsoft.Office.Interop.Excel.Workbook workbook = excelObj.Workbooks.Open(
filename,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value
);

Microsoft.Office.Interop.Excel.Sheets sheets = workbook.Worksheets;
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(0);

Now, if you run this code you'll get an exception citing an invalid index:

System.Runtime.InteropServices.COMException (0x8002000B): Invalid index

If you're like me you'll immediately try starting your index off at 1 because I suppose it makes sense to start off your worksheets at 1. As much as this seems like VB and as much as I don't like VB I think I can live with it. So you change the sheet number to one and go on your merry way.

Then you try to access some data in your first worksheet:

string str = (string)((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[0, 0]).Value2;

Running this code gives you an exception and you want to assume it's because you started your indices off at 0 but it doesn't quite make sense because it gave you a different exception:
System.Runtime.InteropServices.COMException (0x800A03EC): Exception from HRESULT

Hopefully at this point you immediately try Cells[1, 1] and don't spend some time trying to figure out what you did to go from a meaningful exception that made sense to a generic COM Exception. If you try 1,1 you'll find that it works and all will be right in the world.

What bothers me about this isn't the fact that I have to start the index off at 1 rather than 0. What bothers me is that when I tried to open a worksheet with an out of bounds index I got an exception telling me that it was an index issue. When I tried cells that were out of bounds I got a generic exception. The worksheet exception was actually helpful and immediately let me know what the problem was whereas the cell exception wasn't even though it was pretty much the same exact issue.

Killing Your Instance:
I'm not even going to into detail on this as it's been beaten to death already. Killing off an instance of Excel is a pain though I don't think that's really the fault of the interop. You have COM to thank for that one. Essentially you have to make sure that for each Excel COM object you create you're calling ReleaseComObject:

Marshal.ReleaseComObject(excelObj);

And then calling the Garbage Collector:

GC.GetTotalMemory(false);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.GetTotalMemory(true);

I'm not really one to talk in this instance though since my client app still has a bug where when multiple instances of the Excel application are created once I close them out all of the processes go away except for the first one I created. It's really bizarre. See the references section for some links.

Hyperlinks
This isn't so much a beef with the Excel Interop as it is with Excel in general. In Excel you can't have a link within a cell. You can have the entire cell be a link to some location but you can't have the text "click HERE for pictures of my cat" and have only the text "HERE" act as a hyperlink. This ended up saving me some time on the rtf to html conversion but is kind of lame in my opinion.

References:
Here are some of the pages that I found the most helpful when working through this:
- MSDN: Excel Tasks
- Craig Murphy: Excel Interop - killing Excel.exe
- MS Help and Support: Office application does not quit after automation from Visual Studio .NET client
Excel Solutions Forum

Tuesday, September 18, 2007

Catching Up

I've found myself wanting to post fairly often lately. Typically it's about some technical aspect that's either irritating me or making me really happy. It's not very often that I'm working with something and I sit back and reflect on how much I love n technology because n technology makes my life easier or is just plain cool. I've gone through and made draft posts containing nothing more than a title and a brief description for some of them and at some point I may come back to them.

I need software that automatically extracts a topic along with my feelings towards and knowledge of that topic from my mind with minimal effort on my part. It would then take the randomness floating around in my head and structure it in a rational way, write up a few paragraphs, and post it to my blog. That way when I say to myself "wow, this is really cool" or "holy hell this is such a pain to work with" I can just hit a button and a post automagically appears on this blog (or whichever blog I choose).

Joel Spolsky

I know some people don't like Joel Spolsky and I know some people do. I'm in the latter camp and I don't care what other people think. Sure some of the things he writes and posts about aren't of a whole lot of interest to me. But then he'll post things like this and it makes up for all the posts of his that I only skim or skip over.

If you have time go read his most recent post (as of my posting this) here:
Strategy Letter VI

This article was particularly largely for the history of computing and software aspect. Being rather young in the grand scheme of things I don’t have the amount of experience and perspective that he has. Given that fact I appreciate hearing about things like the rise and fall of Lotus 1-2-3 and the changes in the business of writing software as a result of the progression of hardware. It’s even more interesting when patterns can be identified.

I'm not sure what happened to Strategy Letters 1 - 5 but I'm sure they were at the very least somewhat interesting. I may have to go dig those up at some point.

Tuesday, September 11, 2007

Restructuring

I've decided to change things up a little bit. From now on I will be trying to post a lot more often and on a larger variety of topics. I can only post about the struggles and triumphs of working from home so much. This doesn't mean I'll be posting pictures of my cat (I don't own a cat but I could always post photos of the neighbor's cat) or what I had for dinner tonight. From this point forward there will be more variety which will likely include little technical snippets, some details regarding what I'm working on, and my take on living with a kidlet.

Oh, and we're expecting kidlet #2. Good times.

Tuesday, August 21, 2007

Title Goes Here

I've been neglecting this thing lately. Almost two weeks since my last post.

I've fallen behind a bit as of late and as such am juggling multiple projects and running to catch up. This leads to me staying up late working after the family goes to bed (which I don't especially mind that much I just don't like worrying about not getting things done on time). Which then leads to me being rather exhausted most of the morning after our 14 month old gets us up (though huge thanks go out to my wife for letting me sleep in a little after the really late nights). I then become actually productive around 11am and the cycle continues.

It's almost 5am and I tried to go to bed around 3 but wasn't quite able to shut off my brain. Around 3:30 I decided to get back on the computer and get some work done. A little while after that I decided that drinking brain function impairing beverages (beer) was a stellar idea and a sure-fire way to get to sleep sometime soon-ish. I'm on #3 and I predict that by the time I finish this one I'll be lubricated enough to head to bed and get some sleep.

Casey's recipe for shutting your brain off when you're up way too late and can't sleep:
1 - Get beer #1 from fridge
2 - Continue to work.
3 - Get beer #2.
4 - Continue to work.
5 - Beer #3.
6 - Decide you're in no shape to work and post to your blog or go play what may very well be the most addictive and frustrating game ever or something.
7 - finish beer #3 and head to bed leaving empty bottles on desk in case anyone comes over and wonders what you do all day.

For best results the above steps should be completed inside of around 30 minutes.

On that note, I'm rounding the corner on 3 at which point I'm going to head to bed and try to sleep.