Brendan Enrick

Daily Software Development

Using CodeRush™ with Refactor!™ Pro After Losing to a Model

Recently I've started using CodeRush™ with Refactor!™ Pro after being defeated in a programming competition at DevConnections by Sarah (a hired model) at the DevExpress booth. There should be two recordings of my painful defeat. Steve Smith made one and Carl Franklin made the other recording of my battle. Just for the record Steve faced her days earlier when she was still learning and he also lost.

Overall I've found the tools to be extremely useful. They make a lot of tasks quick and painless. Classes, methods, and properties are extremely quick to write now. Refactoring catches me off guard sometimes, but I am often pleasantly surprised.

For simplicity I was calling a method inside of a foreach loop. I did this because I didn't need the collection except that I was performing an action on each of the returned elements in the collection. When I realized that I needed to perform an extra action with that collection I decided I would move it from the foreach loop.

At first I had a foreach loop similar to this one.


As you can see my foreach loop is using a MembershipUserCollection returned from a function and is going to loop through each MembershipUser. It is at this point I decide to refactor and pull the GetUsers method out of there and I am going to make a variable to store this collection. I highlight then cut the method and paste in in the line above and this is what I get.


It knew what I was trying to do! It created the collection and even inserted the variable into the foreach loop for me. When I then rename the variable it also changed it in the foreach loop for me which was quite nice. I didn't even have to check and see what type of collection it was returning before creating the variable. That might have been a generic list, but it didn't matter because the tool figured it out for me and filled in the rest. I was amazed.

There is one annoyance that bugs me though. I have habits I've gotten in to while writing code. I don't like hitting ctrl+space to bring up intellisense. I prefer removing a comma or a parenthesis and typing it again. This works very well without having any extra tools installed. It also works well most of the time. I've only run into a problem a few times.

I start out with code that looks like this. There is a long function call so I keep the parameters below the function.


Now I want to get intellisense back just to confirm the first parameter or maybe to see the overloads for this function so I delete the "(" and put it back in place and I get the following.


Now it has added in an extra ")" that I did not want. I wish it could have seen that my function was complete and I was at the start. Sure that might have been convenient if my code wasn't already written, but in this instance it got annoying. Visual Studio got confused and gave me nice red squiggly lines. DOH! Not too terrible. Most of the time the tools work well there are just a few quirks like this that get me sometimes. Perhaps this blog post will help get the ball rolling to make this product smarter and better able to see what I'm doing. Overall I think the tool is excellent.

If you're interested in buying any cool software from Dev Express I recommend you check out Steve Smith's Dev Express Tech Summit blog post. He mentions a good discount code there that will get you 10%. His coupon code is SMITH07 you can use it to save 10% when you buy great programming tools from DevExpress.

Happy coding!

Why the TextBoxWatermark is the Best AJAX Control

bertiebotts-bag-promoThere are plenty of AJAX tools being used everyday. The AJAX Control Toolkit can be likened to a pack of Bertie Bott's Every Flavor Beans; there are far too many choices. Some tools you'll love and some are as useless to you as an earwax flavored bean. Likely no individual developer will find a use for every control in the toolkit, but there is one which I think has a simple use which can be applied to nearly all sites; the TextBoxWatermark control.

When using the TextBoxWatermark control a developer is able to easily place text inside of a TextBox for a user to see. In my experience I've noticed that users tend to read as little text as they can when using forms. It is also difficult sometimes to write necessary information within strict size constraints. Plenty of text boxes require a title on the left so a user know what to type in the box, and then there might be another message below giving more specific instructions.

My personal favorite method for using this control is to place the title of the TextBox to the left and then placing an example in the TextBox as a watermark. This gives the user a nice example which cannot be easily ignored. Overall a very useful control. It is also very simple to use.

<ajaxToolkit:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender1" runat="server"
    WatermarkCssClass="watermark" />
<asp:TextBox ID="TextBox1" runat="server" />


Using this control it is simple and easy to pass along great information to the user which he or she cannot ignore. It can also make a form look more professional. I am not saying that the TextBoxWatermark is the only useful control. Most of the tools are very useful, but some have some obscure uses. Some of them I know when people use them I just think they shouldn't use them.

Happy AJAXing.

Exploring IronPython

  Earlier today I downloaded IronPython, and I've tested it out a little bit. The command line interpreter is nice and works pretty painlessly whether you are compiling the source or just executing the binaries. Python is a great language IMHO. Just like every language that has ever been written, it has a few problems. Python emphasizes short readable code.

IronPython's interpreter, ipy, allows interactive sessions as well as execution of files. It acts very similarly to Python's Official interpreter, IDLE. This makes transitioning easy for someone who already knows how to program using the Python language.

I sat down and took a couple of seconds writing a simple fibonacci number program to print out the first 10 fibonacci numbers as an example of how Python code is used.


def fib(number):
    if number == 0:
        return 0
    elif number == 1:
        return 1
        return fib(number-1) + fib(number-2)

def main():
    for i in range(10):
        print fib(i)



If this code is in the file I can execute it using the following command.


It generates the following output.



People have integrated IronPython into Visual Studio as well, and I'll soon look into doing that as well. I like how simply and easily I am able to create this little program. Now with IronPython I also have access to the .NET Framework's libraries.

Visual Studio 2008 and the .NET Framework 3.5 Released

In my attempt to add to the monotony, I'll say that not long ago Visual Studio 2008 was released to all of the MSDN subscribes. With the news spreading so quickly the downloads are all taking forever. Good luck! Scott Guthrie, as usual, posted some good content about this Visual Studio 2008 release. There will be some trial versions of the professional available in the not too distant future. You can also read a nice tour of all of the new features added into this new release. Scott wrote short overviews for a lot of the information and linked to more in-depth descriptions of these features. Make sure you follow those links if you're not well informed about this release.

The Visual Studio Express Editions and  the .NET Framework 3.5 runtime are currently available for download. These downloads should work better than the MSDN full version of Visual Studio. These are not multiple gigabyte files and also are probably not as popular right now.

I've been hearing complaints all day about difficulties trying to download it. I am assuming the problems result from too many users attempting to download. Good luck and enjoy some of the great new features.

Visual Studio Extensibility

While I was at DevConnections last week, I watched an interesting demo showing off Visual Studio's extensibility. In the demo the visual studio shell is being used to edit Lua script; the scripting language used by World of Warcraft for designing custom interfaces. The demo showcased Visual Studio's flexibility and captured the audience's attention pretty well.

The speaker added an interesting interface into World of Warcraft which showed images and played sounds when she killed enemies. I think it will be nice to use Visual Studio for almost any programming language. The familiar environment will make things easier. Perhaps more add-ons for Visual Studio will be available in the near future. This WoW Lua add-on is supposed to be available on CodePlex soon.

I don't play World of Warcraft, so I will be waiting to see what extensions other people will decide to make.

SimpleCMS on CodePlex

A couple of weeks ago Steve Smith and I released SimpleCMS as an open source project on CodePlex. SimpleCMS is, as the name suggests, a Simple Content Management System. It is a small ASP.NET 2.0 Plug-in which allows dynamic creation of simple pages. I've not gotten much opportunity to work on it in a long time, but I did manage to get enough time to put it on CodePlex. 

The main goal of SimpleCMS is to be simple. It isn't designed to support a lot of features or be bloated. It is designed to be lightweight. I recommend checking it out if you get the chance. The project could use some more development, and if I get the free time I'll try to work on it a bit.

Let me know what you think about SimpleCMS.

Memory Management: Generics vs objects

One of the most important parts of software development is memory management. Memory management is important for every software application. If one is to write a well developed software application, one must have a fair bit of knowledge in the area of memory managament. It is important to understand the underlying technology which allows programs to function. There are many aspects of programs which come into play often in .NET applications; variables, functions, garbage collection.

Understanding Garbage Collection, Heaps, and Stacks

When using a language with a heap, it is important to understand that memory will be allocated dynamically. This is separate from where the basic program memory resides; the stack. On the stack memory builds as the program executes. Local variables are stored with the function information. This is the memory used in pretty much every language. When a heap is involved there is basically an area of memory where variables may be dynamically defined and only references to these variables are stored as pointers on the stack.

When the variable is out of scope or removed it is merely the reference to the variable which is removed. A garbage collector will come by later to free the memory for later use. Whenever there is not enough room to allocate memory in the heap the garbage collector wil come and clear unused memory.

Understanding Variable Types

There are basically two types of variables; value and reference. The value types tend to be the simpler variables and the reference types tend to be the more advanced variables. Some examples of value types are enums, ints, doubles, bools, chars, and structs. Some reference types are arrays, lists, and classes. The value types are the ones stored locally with the stack and the reference types are stored in the heap, and a reference to them is stored on the stack. When using the new keyword, memory is allocated on the heap and a referenced object is created.

Passing Parameters to Functions.

When passing variables as parameters to functions, it is important to understand the two main ways in which these variables may be passed. Variables may be passed by reference or by value. Passing by value means that we make a copy of the local variable and use that in the function. This means that our value type variable will be copied and if we use a reference type it means that only the reference will be copied. This means that we will still be accessing the same location in the heap even if we pass by value. By using the ref keyword you may pass a parameter by reference. This means for a value type you are able to just pass a reference to the original value. Do not pass a reference type by reference, because it will just make a reference to the reference to the value and that will slow things down for no reason. Passing by reference is a good idea if the value is large, so with a large struct you may want to pass by reference instead of copying all of the data.

Generics vs. Objects

When using parameters of type object, boxing and unboxing is used to take the variable and changing it to and from object. This seems pretty easy because one can simply add (object) when passing the parameter. The problem here is that this will create a new instance of an object. This means we will be making a copy of the variable instead of just using a reference to the variable. This will take time, and will also allocate extra memory which will need to be collected by the garbage collector later. This will also decrease the performance of our program. This is why it is important to use generics to prevent this performance hit. When we use generics we do not have to make a copy of the value, we merely pass a reference to the original value.

Be careful, and try to use Generics whenever possible. Your memory will thank you.

Table Variables vs. Temporary Tables in SQL

Temporary tables and table variables can be used in pretty much the same way. One question which is asked, "Which one is better". To answer that it is important to understand a few of the differences between the two. Once we understand how these two types of tables are different we will better understand which we need to use when.

Creating a temporary table is very similar to creating a regular table. In order to do this we use the following code

create table #myTempTable (columnA typeA, columnB typeB, ...)

Table variables are created as regular variables are declared. The type of the variable is just defined as a table.

declare @myTableVariable table (columnA typeA, columnB typeB, ...)
Scope is another important factor to consider. With a table variable its scope is similar to other variables. A temporary table however does not share this scope, and can even be accessed in a stored procedure called by your code. This is one very nice feature of temporary tables over table variables.

Table variables do not record any entries in transaction logs. Temporary tables do store their transactions. Depending on what you are trying to accomplish this can be a benefit for either of the two types of tables. It is often very important to keep track of the transaction log, and in these instances a temporary table is far better for your needs, but other times the transaction log is simply unnecessary and a table variable would be the optimal choice.

I've heard of great performance gains in temporary tables because of their ability to be pre-compiled. I've also heard that table variables are faster than temporary tables in general. I believe this has to do with the nicely defined scope of table variables. Because of this they may use fewer resources than temporary tables. An example of this is the transaction log I mentioned earlier.

For the most part a table variable is just as flexible as a temporary table, and in most instances it also out performs temporary tables in my experience.

One thing to watch out for when using temporary tables is the possibility of causing your store procedure to recompile. Microsoft has a Knowledge Base Article about Troubleshooting stored procedure recompilation which discusses this danger. Table variables will not cause this problem.

I would recommend the use of table variables for everyday use, and only using temporary tables when they're required. Instances of this include the need for a transaction log. Or any time you feel like writing extra lines of code simply to perform cleanup on your temporary table. But that is just my $0.02 on this issue.

Happy SQL writing!

Accessing Controls inside of Templated Controls

One question that seems to come up often in the forums is from people who are trying to access controls within controls using templates. LoginViews and CreateUserWizard controls are two commonly used templated controls. These templated controls don't actually have their contents known until run-time because it is dependant on something else; data from a database, user permissions, etc.

Since this information is not known you can't just access the inner controls as you would normal controls, because it is not known until run-time what the controls are. You will get compiler errors if you try to access them. The easiest way to get the controls you need is to use a recursive find control function. Steve Smith has blogged about Using a Recursive Find Control as well as about a very important Code Optimization for using a recursive find control.

The cool thing about the recursive find control is that it will dig down into the controls collection of a control you specify looking for the control you are looking for. It is great for templated controls, because it is a lot neater than trying to statically go after it like this.

Bad Code Do Not Use This

Label Label1 = LoginView1.Controls[2].Controls[2].Controls[1].Controls[3].FindControl("Label1") as Label;

The problem with the above code is that if you move anything you'll break the code. It is not very stable, and is even hard to tell what is being done. Do not worry there is a better way of handling this. A recursive find control is an expensive operation, and this is why Steve's code optimization is important. You don't want to execute the find control more times than needed.

Good Code Use This

public static System.Web.UI.Control FindControl(System.Web.UI.Control start, string id)
    System.Web.UI.Control foundControl;
    if (start != null)
        foundControl = start.FindControl(id);
        if (foundControl != null)
            return foundControl;
        foreach (Control c in start.Controls)
            foundControl = FindControl(c, id);
            if (foundControl != null)
            return foundControl;
    return null;

The above code will find controls nested within templated controls for you. This code will probably go in one of your class libraries where you keep utility functions. When you're calling this function, I would recommend you call it within a property as in Steve's optimization. The following code shows how you would do the previous example in a better way.

Good Code Use This

private Label _label1 = null;
private Label Label1
        if (_label1 == null)
            _label1 = Utilities.FindControl(LoginView1, "Label1") as Label;
        return _label1 ;

This allows you to access the control as you normally would try. You can just type in the name of the property and it will let you use it as if it were the control and there were no templated control there at all. Makes working with LoginViews and CreateUserWizard controls.

Repeating templated controls such as the GridView can also benefit from this functionality, but you need to be more careful with them because there is a control with the name you're looking for in each row of the repeating control. Make sure when using this there that you get the correct row first, and only search within that row.

Have fun finding your controls.

Public Strongly Typed Resource Generator

I recently installed an interesting custom tool. It is an Extended version of the resource generator in Visual Studio. The nicest part of this for me is that this one is public instead of internal like the default one. In order to have a centralized resource file it needs to be usable between projects in Visual Studio, but the internal class made this difficult. I could just manually update the generated code each time after using the file, but that would just be stupid.

This is a great answer to the problem I needed to solve because it allows me to keep the resource file in one spot and not have to do and weird tricks to accomplish my goals.

The article accompanying this tool is well-written and explains a bit about how to use and install it.

This little tool is easy to install. It comes with an MSI installer or the source code whichever you prefer. I'd say just go with the MSI.

Note: Make sure if you are on Vista you run it as administrator though or it will not work. Since it is an MSI file you will not see an option to run as administrator, so you will want to create a batch file to do this. In the batch file you will execute the MSI file. You will run the batch file as administrator. The following code should be in the batch file.

msiexec /i "Absolute path to the installer \ResXFileCodeGeneratorEx.msi"

That should get it installed. You then need to create a resource file and in the "Custom Tool" field of the properties window type "ResXFileCodeGeneratorEx" into the field. This will then make your new generated Strongly Typed resources a public class.

Congratulations you may now use your resource file between projects!