Boxing and Unboxing

I want to begin the series by covering some “advanced basics”. You can find a million “Hello World” tutorials, so I want to avoid those and cover topics frequently overlooked in beginners books. Boxing is just such a topic.

As you may be aware, there are two kinds of variables in .Net, value types and reference types. A value type is stored in an area of memory called the stack, which is a very fast place to get to. Value types are simple data types like integers, doubles, and so on. Things the compiler can always guarantee the size of.

Reference types, on the other hand have a variable size, and thus don’t fit nicely on the stack. So .Net puts them in a memory location called the heap, and stores a reference to the stack.

It’s a lot like having a post office box. For small items, like letters, you just go to the post office box and remove them, quick and easy. Let’s say you get a huge package, maybe that spiffy new laptop has finally arrived. Obviously that laptop won’t fit in your post office box, so the mail service puts a little yellow slip that says “you’ve got a package, it’s stored in this location, come get it”.

The post office box in this case would be the stack. Letters are like value types, small, fast to get to, and usually one of a few predictable sizes. The little yellow slip saying you’ve got a package would be a reference type, it’s pointing to a specific spot in the heap of packages stored in the back room.

Now, boxing occurs whenever you try to put a value type, such as an integer, into a reference type, such as an object.

      int myLetter = 42;

      object myBox = (object)myLetter;

Because .Net doesn’t know in advance how big the myBox object will be, it has to make it a reference type. Placing an int into it makes no difference. .Net will happily take the value 42, place it on the heap, and store a reference to the memory location in the myBox variable.

As you might guess, extending our PO Box analogy would have the post office take the letter out of your PO Box, shove it in a big box, put it in the back and stick one of those yellow slips in your slot.

This entire process is called Boxing. The reverse, putting a refernce type back into an value type is called Unboxing.

      object myBox = 42;

      int myLetter = (int)myBox;

Boxing and unboxing are very slow processes. Additionally, they are fraught with danger. What if we’d tried this instead?

      object myBox = 3.1415719;

      int myLetter = (int)myBox;

Gold star to anyone who blurted out “run time error” or “invalid cast exception”. There is no implicit type checking when moving from a value type back to a reference. You will have to add additional code to be sure that no errors happen.

In general you should try to avoid boxing and unboxing, and instead use generics (more on them later). Occasionally you can’t avoid it, for example:

      int recordCount;

      // Some code here that loads records and increments recordCount

      MessageBox.Show(“You loaded “ + recordCount.ToString()

         + ” records.”);

You may not realize it, but when you call ToString, you are creating a boxing operation, converting our nice value type int into a reference type string. As I mentioned, sometimes you can’t avoid these types of operations. Which brings us to the obvious question, when is it “safe” to box?

Typically when you perform a widening operation, moving a smaller variable into a larger one, you’re OK. For instance, moving an int into a double or string is safe because you are taking a smaller data type and moving it to a larger one. Much like taking an envelope out of your post office box, and placing into one of those large overnight mailers, or a shipping carton.

A narrowing conversion on the other hand is when you take a big variable and try to shove it into a smaller one, such as a double into an int. These are dangerous and you should be sure what you are doing before attempting.

By the way, not all widening operations are necessarily a boxing operation. Going from int to double is widening, but not boxing because there are two value types involved. Moving from int to string is both widening and boxing, as you are going from a value to a reference type. Whichever the case, just know that both are “safe” things to do. You can rest easy knowing this particular type of operation is safe.

Boxing is one of those arcane pieces of knowledge, understanding it will help you to be a better programmer so you will know when using it appropriately, and when to avoid it.

And now for something completely different….

Over the last few months I’ve been talking about the development environment. I’ve been exposing you to tools that will make your Visual Studio programming life easier. Some were Add-Ins for Visual Studio, some Windows add-ins, some applications to help debug things outside VS.

It’s time to switch gears now, and start looking at some code. Specifically I’ll be going over C# and the .Net Framework, looking at some of the more arcane pieces of code. From time to time I’ll throw in a new tool or arcane thought or two, but for the most part I’ll be focusing on code for a bit. I’ll also throw in the occasional database tidbit from time to time, as I work a lot with both Oracle and SQL Server.

What I post on will be driven by a combination of what I’m working on and what you request. Something you want to know more about? Drop me an e-mail, or leave a comment.

Ready? Great, let’s get started…

Visual Studio Add-Ins: CodeRush

Every so often a software package comes along that drastically changes your life. Makes it easier, makes you more productive, and is fun to use. For me, that product was CodeRush.

CodeRush is a code authoring tool that works with both the 2003 and 2005 versions of Visual Studio .Net. Note I say code authoring, not code generating. With a code generator, you give it some input and it whirs and grinds and boom out comes a big hunk of code.

CodeRush on the other hand helps while you are writing code. For example, let’s do something like a C# switch statement. First, let’s see we have a parameter passed in named Switcher. I’ll set a local variable to it:

      int localSwitch = Switcher;

Next, I’ll copy the localSwitch variable to the clipboard. Now I’ll type in the word switch, and hit space. When I do, this is what you’ll see:

      switch (localSwitch)

      {

        case 0:

 

          break;

      }

CodeRush made the assumption since I had a variable already in the clipboard, that’s probably what I wanted to switch on. It then constructed the basic swich for me, including braces, my break and what you see above. It also placed my cursor right on the L in localSwitch with the variable highlighted, so that if it’s not what I wanted all I have to do is start typing.

That’s just one example, CodeRush has hundreds of built in templates that will make your coding faster. In addition, when you buy CodeRush you also get it’s sister product RefactorPro. RefactorPro makes that critical refactoring stage of development so much nicer.

Let’s take a tiny example. Suppose you need to change the order in which two parameters occur in a method. Not only will RefactorPro simply let you drag one parameter in front of the other, it will then search through your code and automatically update all references to the method for you.

There are way more features then I could cover in a single, or even a week’s worth of blog posts. Instead, I want you to go look at their training videos, which you will find here:

http://www.devexpress.com/Products/NET/IDETools/CodeRush/training.xml

or http://shrinkster.com/jx0

There’s no charge to watch, no special software, and they’ll give you a great idea on what CodeRush and RefactorPro can do for you.

For a complete product overview you can visit:

http://www.devexpress.com/Products/NET/IDETools/CodeRush/Index.xml

or http://shrinkster.com/jwz

If you asked me what could I name that was negative about the product, about the only thing I could point to is the price. At $250 (US) it’s not cheap. However this product has saved me so many hours it’s well worth the money. If you work for even a small company it shouldn’t be a great effort to get them to cover the cost.

If you asked me what the best thing was, I’d say the support. Developer Express runs it’s own news server, and the developers are right in there as often as they can, answering questions, and asking the users what features they want in the next release. I’ve never seen any company provide the level of support DevExpress does with this product.

The best part of all this is you can discover CodeRush for yourself, for free. You can look at the training videos and newsgroups, then download an evaluation version which you can run with no restrictions (it’s not crippleware). Last I checked they asked you to send an e-mail to their support staff and they’d send you the details.

CodeRush is a great tool that I can’t recommend enough. It has made me so much more productive, and with a minimal amount of effort I think you will be to.

Standard disclaimer, I don’t work for DevExpress, make no money off sales, or receive any compensation what so ever, I just think it’s a cool developer tool!

Arcane Thoughts: The Fourth Estate

Over the weekend I’ve been continuing to think about what I wrote Friday. In looking over other opinions on the web, I see a lot of folks who seem to want to blur the distinction between bloggers and journalists. This is dangerous. Let me say this once, and clearly so everyone can understand.

BLOGGERS ARE NOT JOURNALISTS.

Journalists are paid for their words. It’s their job. What they say reflects not only on them but upon the organization for which they work. When you go to the website of a major newspaper, often you don’t even know or care who it is that wrote the story you read. The paper as a whole carries a reputation, a credibility.

That’s why there are so many standards when it comes to journalistic ethics, and rightly so. An organization is responsible for all of the people who write for it, and one bad apple can spoil it for everyone. Remember Jayson Blair? He made up or outright stole stories that went to the New York Times. The entire paper’s credibility suffered. (see http://en.wikipedia.org/wiki/Jayson_Blair)

On the other hand, I as a blogger stand alone. My words are just that, mine. My blog is not affiliated with anyone else’s, and if I say something outrageous only I will suffer. Likewise, if I do something wrong such as libel someone, only I will be responsible for the consequences, not my coworkers and not my company.

Nor do I get paid for my words. Granted I hope to recoup my time investment some day, perhaps through notoriety, writing magazine or book articles, or public speaking engagements. But for now, my only reward is the satisfaction that comes from (hopefully) helping others with my blog entries. Thus, bloggers should be held to a totally different standard.

Of course we muddy the waters some with the corporate bloggers, those companies who have one or more individuals blogging, and that blog represents the company. Don’t get me wrong, I love the concept of a corporate blog. It’s a great way to communicate with your customer base. But just as no two companies are the same, it’s impossible to set one standard for all corporate bloggers. What would be appropriate for Billy Bob’s Beer and Bait might be totally inappropriate for Fred’s Fine Wines. Each company needs to decide for itself what standards it’s corporate bloggers need to uphold.

There’s also the rare coincidence where you have a journalist who blogs, someone like Mike Cassidy (http://www.mercextra.com/blogs/cassidy/). In those cases, unless it is clear the blog is a personal one, and not professional, as far as I’m concerned the blog entry is no different from an article that appears in the printed paper. The person is acting as a journalist, and thus should be held to the journalistic standard.

Finally, I have seen a few instances where a blogger claimed some sort of legal protection, claiming to be a journalist. Most notable is Josh Wolf, who took some video of an anarchist protest and now refuses to turn over his raw footage to a grand jury. He’s now in jail for contempt of court. Let me say up front I admire Josh Wolf, it takes a lot of guts to be willing to go to jail for something you believe in. That said though, I have to disagree with his conclusions.

I said it before, but let me reiterate in case you weren’t paying attention:

BLOGGERS ARE NOT JOURNALISTS.

When Mr. Wolf took the video, he was not representing any news organization, nor at the time did he sell it to a news outlet, he instead posted it on his personal blog. He was a private citizen, using his first amendment rights to express a viewpoint. He happened to choose a blog to do it on, but he could just have easily stood on the street corner and played it on his portable TV. From the standpoint of his personal, first amendment rights there is no difference.

My blog is merely a medium for expressing my thoughts and creations. You could read these words on printed paper, say a magazine, or on the bathroom wall. I could yell them at you from a soapbox, or you could read them right here on your computer screen. No matter what the medium, the result is the same. I’m a private citizen, expressing my views, not a journalist.

Those are my arcane thoughts, feel free to leave yours…

Arcane Thoughts: Do you trust me?

I’ve been watching an interesting debate between Scoble and Joel on the recent giveaway of Vista loaded laptops to bloggers. (No, I didn’t get one, dang it.) First, let me see if I can summarize their opinions, with apologies to both gentleman if I over simplify.

Scoble’s most recent posting on the subject can be found at http://scobleizer.com/2007/01/02/why-bash-microsoft-and-not-nokia/. His basic position is that it’s acceptable for bloggers to accept items from companies as long as there is full disclosure.

Joel in his posting at http://www.joelonsoftware.com/items/2006/12/28.html has the position that by accepting any item we destroy any credibility and lose trust with our readers.

As a relatively new blogger, I’ve spent a lot of time over the last few days thinking about both viewpoints. And while an admirer of his work I have come to a conclusion.

Joel is wrong.

Trust and credibility are something a blogger builds with his readership over time. Scoble is a perfect example of this. Microsoft paid his salary for many years, yet he still managed to gain an enormous amount of respect in the blogging community. Why?

Simply put, Scoble’s posts about the company he worked for rang true. Readers trusted him when he wrote something good about Microsoft, because he also wrote when Microsoft did bad things. Additionally, his experiences were reflected in the user community, who could hold his feet to the fire through comments. Finally, and most importantly, Scoble quickly and openly admits when he is wrong, publicly correcting his mistakes.

For a blogger who is willing to accept hardware / software, whether to review or not, his credibility will be born out over time. A blogger who only writes love letters about the things he accepts will soon be found out for the untrustworthy individual they are.

On the other hand, bloggers who are willing to be honest, provide full disclosure, and write negatively when justified, as well as positively (like Scoble did with Microsoft), those bloggers will gain that high level of trust and credibility regardless of whether they accepted freebies or not.

Those are my arcane thoughts, feel free to leave yours…

Outlook and “Macros are Disabled” error

One error some people seem to be getting when trying to run macros in Outlook is: “The macros for this project have been disabled.” It then goes on to tell you to review some help that isn’t very helpful.

The scenario is generally the same, you create your macro and it runs fine, you close Outlook and when you re-enter the macros no longer run. Some blogs suggested lowering your security settings, or signing the thing, but I tried both of these to no avail.  

The only way I was able to solve the problem was to follow these steps:

  1. Copy EVERYTHING out of your VB macro project, into a text file. Save the textfile to your drive. 
  2. Close everything, reboot the computer.
  3. Go to your C:\Documents and settings\<yourusernamehere>\Application Data\Microsoft\Outlook folder.
  4. Either delete the file VBAProject.otm, or (better and safer) rename to VBAProject.old or some similar name.
  5. Open Outlook
  6. Reopen the VB Macro editor
  7. Paste in the code from your text file.

After doing the above, I was able to start running the SaveAttachements macro I blogged about yesterday. From my research, no one is really quite sure why this headache occurs, and why this is the only way to fix it, but it does work. 

Enhancing the Save Attachments Outlook Macro

Update: Feb. 28, 2007: Due to numerous requests I’ve created a branch of this macro that saves attachments for all messages / calendar items, selected or not. To see it, please see my post https://arcanecode.wordpress.com/2007/02/28/saving-all-attachments-in-outlook/ or http://shrinkster.com/mhn. There I have uploaded a new file with both the macro below and the new one that saves all items, selected or not.

Yesterday I blogged about a macro I wrote for my wife to allow her to save attachments for multiple messages in Outlook. After using it today she asked for a few enhancements. First, she wanted to be able to select the directory to save the attachments to. Second, she wanted the macro to detect that a file already existed, and allow her to rename the new file or skip it.

To accomplish the first item, I found a handy routine in a google groups thread. I’ll let you read it for yourself, the code is about half way down in a message by Joe Earnest, and can be found at http://shrinkster.com/l0v. I took Joe’s code and created a function out of it called GetOutputDirectory. I made one enhancement, at the end I make sure the output directory ends in a backslash.

For the second enhancement I used the good old scripting runtime library. Use the Tools, References menu in the VBScript editor and set a reference to the “Microsoft Scripting Runtime”, scrrun.dll. Rather than reposting all the code I’ve put the entire macro in a txt file you can download here: https://arcanecode.com/wp-content/uploads/2007/01/saveattachments2.txt

Here is the heart of the code

fileExists = fso.fileExists(outputDir + outputFile)

Do While fileExists = True
outputFile = InputBox(“The file ” + outputFile _
+ ” already exists in the destination directory of ” _
+ outputDir + “. Please enter a new name, or hit cancel to skip this one file.”, “File Exists”, outputFile)
‘If user hit cancel
If outputFile = “” Then
‘Exit leaving fileexists true. That will be a flag not to write the file
Exit Do
End If
fileExists = fso.fileExists(outputDir + outputFile)
Loop

‘Save it to disk
If fileExists = False Then
att.SaveAsFile (outputDir + outputFile)
AttTotal = AttTotal + 1
End If

As you can see, I check to see if the file exists and store that in a variable. I then enter a loop if the file exists, ask for a new name, then check to see if the new name exists. I stay in the loop as long as it does.

Should the user click the cancel button on the input box, I exit the loop prematurely and use the fileexists as a flag to write or not write the file.

There you go, an enhanced version of the SaveAttachments macro. Take a look at the full file I’ve uploaded, and leave a comment with any questions.

Saving Attachments in Outlook

I spent my new years day recovering from a nasty cold. My wife asked me if there was a way to save the attachments in Microsoft Outlook for multiple messages. I spent a little time and came up with a handy macro, I thought others might find it useful as well.

First, in Outlook click on Tools, Macro, Visual Basic Editor. Now in the editor on the left you’ll see Project. Drill down Project1, Microsoft Office Outlook, ThisOutlookSession, and paste the code below in:

Public Sub SaveAttachments()

‘Note, this assumes you are in the a folder with e-mail messages when you run it.
‘It does not have to be the inbox, simply any folder with e-mail messages

Dim App As New Outlook.Application
Dim Exp As Outlook.Explorer
Dim Sel As Outlook.Selection

Dim AttachmentCnt As Integer
Dim AttTotal As Integer
Dim MsgTotal As Integer

Set Exp = App.ActiveExplorer
Set Sel = Exp.Selection

‘Loop thru each selected item in the inbox
For cnt = 1 To Sel.Count

‘If the e-mail has attachments…
If Sel.Item(cnt).Attachments.Count > 0 Then

MsgTotal = MsgTotal + 1
AttTotal = AttTotal + Sel.Item(cnt).Attachments.Count
‘For each attachment on the message…
For AttachmentCnt = 1 To Sel.Item(cnt).Attachments.Count

‘Get the attachment
Dim att As Attachment
Set att = Sel.Item(cnt).Attachments.Item(AttachmentCnt)
‘Save it to disk
att.SaveAsFile (“C:\Attachments\” + att.FileName)

Next

End If

Next

‘Clean up
Set Sel = Nothing
Set Exp = Nothing
Set App = Nothing

‘Let user know we are done
Dim doneMsg As String
doneMsg = “Completed saving ” + Format$(AttTotal, “#,0″) _
+ ” attachments in ” + Format$(MsgTotal, “#,0″) + ” Messages.”
MsgBox doneMsg, vbOKOnly, “Save Attachments”

Exit Sub

ErrorHandler:

Dim errMsg As String
errMsg = “An error has occurred. Error ” + Err.Number + ” ” _
+ Err.Description

Dim errResult As VbMsgBoxResult
errResult = MsgBox(errMsg, vbAbortRetryIgnore, _
“Error in Save Attachments”)
Select Case errResult

Case vbAbort

Exit Sub

Case vbRetry

Resume

Case vbIgnore

Resume Next

End Select

End Sub

Note some browsers trash the html I tried to do above, so I uploaded it as a text file. Just save to your hard drive and paste into the VBScript Editor or rename the txt to cls and do a File, Import and browse to this file: https://arcanecode.com/wp-content/uploads/2007/01/saveattachments1.txt

And of course save it. Now switch back to Outlook, and click on View, Toolbars, Customize. Click on the Toolbars tab, and click New. I named my new toolbar ArcaneCode, but name yours what you will.

Once you have the new toolbar, click on the Commands tab. Scroll down on the left to Macros and click on it. You should see your new macro in the Commands window on the left. Drag it on to your new toolbar. Now you can shorten the name a little, right click on the tool, to see it’s pop up menu. Go to Name and click on it, then shorten the name to what you want. I then drug my new toolbar up with the rest of my other toolbars.

Two notes, I made it easy on myself and am saving all attachments to C:\Attachments, which I’ve hardcoded in the macro. Feel free to change to what you want or add code to have it ask you for the folder.

Second, I have tested with Outlook 2002 and 2003, but have not tested under 2007. Your milage may vary.

And there you go, a way to save attachments on all the messages you have selected within Outlook.