:::: MENU ::::

Thursday, November 27, 2008

Packer for .NET has been updated to include a CSS Minify mode which does the same for CSS that JSMin does for JavaScript. Thanks for this addition goes to Chris Lienert who updated the open source project with work done by Daniel Crenna and Michael Ash to port YUI Compressor.

Why Minify CSS?

CSS can be very complex and it helps to place inline comments in your stylesheets to assist with maintenance. These comments can explain workarounds which are used to support cross-browser layouts. We all have workarounds or even hacks to support legacy browsers like IE6. Often these techniques do not make much sense when they are viewed months later without any context. Normally comments are left out of CSS files because they increase the size of the documents and reveal internal details to any curious developer digging through your code. Now you can minify your CSS during your deployment process with Packer for .NET to strip your comments and unnecessary whitespace. The minification process also uses other techniques to further reduce the size of the output document.

More information:

Update: Version 4.0.2 is out which includes updates to includes wildcard expansion for the command-line utility. There was also a bug where the output file could not match the input file which has been fixed.

 

Monday, November 24, 2008

Last month I blogged about how Microsoft is extending support for jQuery.  Over the last few weeks we've been working with the jQuery team to add great jQuery intellisense support within Visual Studio 2008 and Visual Web Developer 2008 Express (which is free).  This is now available to download and use.

Steps to Enable jQuery Intellisense in VS 2008

To enable intellisense completion for jQuery within VS you'll want to follow three steps:

Step 1: Install VS 2008 SP1

VS 2008 SP1 adds richer JavaScript intellisense support to Visual Studio, and adds code completion support for a broad range of JavaScript libraries.

You can download VS 2008 SP1 and Visual Web Developer 2008 Express SP1 here.

Step 2: Install VS 2008 Patch KB958502 to Support "-vsdoc.js" Intellisense Files

Two weeks ago we shipped a patch that you can apply to VS 2008 SP1 and VWD 2008 Express SP1 that causes Visual Studio to check for the presence of an optional "-vsdoc.js" file when a JavaScript library is referenced, and if present to use this to drive the JavaScript intellisense engine.

These annotated "-vsdoc.js" files can include XML comments that provide help documentation for JavaScript methods, as well as additional code intellisense hints for dynamic JavaScript signatures that cannot automatically be inferred.  You can learn more about this patch here.  You can download it for free here.

Step 3: Download the jQuery-vsdoc.js file

We've worked with the jQuery team to put together a jQuery-vsdoc.js file that provides help comments and support for JavaScript intellisense on chained jQuery selector methods.  You can download both jQuery and the jQuery-vsdoc file from the official download page on the jQuery.com site:

More

Matt Warren, who provides the most detailed HOWTO for creating your own LINQ IQueryable provider, has now published a dedicated toolkit on CodePlex:

IQToolkit is essential if you are building your own LINQ IQueryable provider. It contains common tools and source code you can apply to your own project.
In the toolkit you will find useful techniques for manipulating LINQ expression trees, implementing IQueryable providers, and a host of extensible components for building providers that target translation of LINQ expressions into SQL like languages.

http://www.codeplex.com/IQToolkit

Creating a LINQ provider is not a walk in the park, but at least if you have to, you have everything you need at hand.

 

Friday, November 21, 2008

If you’ve ever written any non-trivial ASP.NET control, you’re probably familiar with the concept of a Control Builder.  Basically, it’s a class that you associate with your control and that affects the way your control gets processed at parse time.  While ControlBuilder has been around since the ASP.NET 1.0 days, a very powerful new feature was added to it in 3.5 (i.e. VS 2008).  Unfortunately, we never had a chance to tell people about it, and a web search reveals that essentially no one knows about it!  Pretty unfortunate, and obviously, the point of this post is to change that. :-)

So what is this super cool feature?  Simply put, it lets the ControlBuilder party on the CodeDom tree used for code generation of the page.  That means a ControlBuilder can inspect what’s being generated, and make arbitrary changes to it.

Warning: this post assumes some basic knowledge of CodeDom.  If you are not familiar with it, you may want to get a basic introduction to it on MSDN or elsewhere before continuing.

How do you use this?

To use this feature, all you have to do is override the new ProcessGeneratedCode() method on ControlBuilder.  here is what this method looks like:

//

// Summary:

//     Enables custom control builders to access the generated Code Document Object

//     Model (CodeDom) and insert and modify code during the process of parsing

//     and building controls.

//

// Parameters:

//   codeCompileUnit:

//     The root container of a CodeDOM graph of the control that is being built.

//

//   baseType:

//     The base type of the page or user control that contains the control that

//     is being built.

//

//   derivedType:

//     The derived type of the page or user control that contains the control that

//     is being built.

//

//   buildMethod:

//     The code that is used to build the control.

//

//   dataBindingMethod:

//     The code that is used to build the data-binding method of the control.

public virtual void ProcessGeneratedCode(CodeCompileUnit codeCompileUnit, CodeTypeDeclaration baseType, CodeTypeDeclaration derivedType, CodeMemberMethod buildMethod, CodeMemberMethod dataBindingMethod);

So basically you get passed a bunch of CodeDom objects and you get to party on them.  It may seem a bit confusing at first to get passed so many different things, but they all make sense in various scenarios.

  • The CodeCompileUnit is the top level construct, which you would use for instance if you wanted to generate new classes.
  • Then you have the two CodeTypeDeclarations, which represent the classes that are generated for this page.  The reason there are two has to do with how the page is generated.  First, there is a partial base class just has control declaration, and gets merged with the code behind class the user writes (in Web Sites, Web Applications are a bit different).  Then we derive another class from it, which has the bulk of the code that makes the page run.  I know this seems confusing, so let me give you a rule of thumb: when in doubt, use baseType rather than derivedType.
  • Finally, we have the two CodeMemberMethods, which represent methods that relate to the particular control that’s being built.  One is for the method that builds the control (e.g. assigns its properties from the markup, …), and the other one deals with data binding.

Tip to make more sense of all that stuff: a great way to learn more about the code ASP.NET generate is simply to look at it!  To do this, add debug=”true” on your page, add a syntax error in there (e.g. <% BAD %>) and request the page.  In the browser error page, you’ll be able to look at all the generated code.

 

How about a little sample to demonstrate?

Let’s take a look at a trivial sample that uses this.  It doesn't do anything super useful but does demonstrate the feature.  First, let’s write a little control that uses a ControlBuilder:

[ControlBuilder(typeof(MyGeneratingControlBuilder))]

public class MyGeneratingControl : Control {

    // Control doesn't do anything other than generate code via its ControlBuilder

}

Now in the ControlBuilder, let’s implement ProcessGeneratedCode so that it spits out a little test property:

// Spit out a property that looks like:

//protected virtual string CtrlID_SomeCoolProp {

//    get {

//        return "Hello!";

//    }

//}

var prop = new CodeMemberProperty() {

    Attributes = MemberAttributes.Family,

    Name = ID + "_SomeCoolProp",

    Type = new CodeTypeReference(typeof(string))

};

 

prop.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Hello!")));

 

baseType.Members.Add(prop);

So  it just generates a string property with a name derived from the control ID.  Now let’s look at the page:

        <test:MyGeneratingControl runat="server" ID="Foo" />

And finally, let’s use the generated property in code.  The simple presence of the this tag allows me to write:

Label1.Text = Foo_SomeCoolProp;

And the really cool things is that Visual Studio picks this up, giving you full intellisense on the code generated  by your ControlBuilder.  How cool is that! :)

Full runnable sample is attached to this post.

What about security?

At first glance, it may seem like this feature gives too much power to ControlBuilders, letting them inject arbitrary code into the page that’s about to run.  The reality is that it really doesn’t let an evil control do anything that it could have done before.  Consider those two cases:

  • Full trust: if the Control and ControlBuilder are running in full trust, then they can directly do anything that they want.  They gain nothing more from  generating code that does bad things
  • Partial trust: if the Control and ControlBuilder are running in partial trust, then they can’t do much damage themselves directly, and can attempt to do additional damage indirectly via code they generate.  However, if the app is running in partial trust (as is typical in hosted environments), then the dynamically generated page code also runs in partial trust.  So effectively, it can’t do any more than the control could do directly.

Conclusion

ProcessGeneratedCode is a pretty powerful feature, giving your ControlBuilders full control over the code generation.  It’s also a pretty advanced feature, and you can certainly shoot yourself in the foot with it if you’re not careful.  So be careful!

 

Tuesday, November 18, 2008

Sometimes I see myself in weird situations, having to debug applications in test environments, but for some reason I'm not able to use Visual Studio. Not going to specific details about my environments here. However, it's possible that someone out there have a similar issue. For these cases, I use Reflection to dump the contents of my objects into a string and save it in a text file to analyze later.

This is the "Dump" method:

public static string Dump(Object obj) {
    string dump = string.Empty;
    try {
        Dictionary<string, string> dictionary =
 
            new Dictionary<string, string>();
        Type type = obj.GetType();
        System.Reflection.PropertyInfo[] propInfo = type.GetProperties();
        for (int i = 0; i < propInfo.Length; i++) {
            System.Reflection.PropertyInfo pi = (System.Reflection.PropertyInfo)propInfo.GetValue(i);
            dictionary.Add(pi.Name,
                (null == pi.GetValue(obj, new object[] { })) ?
                "null" : pi.GetValue(obj, new object[] { }).ToString());
        }
        foreach (System.Collections.Generic.KeyValuePair<string, string> pair in dictionary) {
            dump += string.Format("{0}\t{1}\n", pair.Key, pair.Value);
        }
    }
    catch (Exception ex) {
        // use a proper log instead of a text file..
        System.IO.File.AppendAllText(@"C:\myapplicationname.dump.exception.txt",
            "--------------------------------------\n"+
            "Exception:\n\tSource: " + ex.Source +
            "\n\tMessage: \n" + ex.Message +
            "\n\tStack: \n" + ex.StackTrace +
 
            "\n------------------------------------");
 
    }
    return dump;
}

 

Monday, November 10, 2008

Tracking down those pesky flaws in a piece of code is, in my humble opinion, the most challenging part of software development. Thankfully we have a top-notch debugger built into Visual Studio. Unfortunately, the debugger is one of the features of Visual Studio that I am the least proficient with. I know how to set a breakpoint and take a look at the values of my local variables when that breakpoint is reached, but beyond that I'm pretty much clue-less. Well, I was lucky enough to attend John Cunningham's talk at PDC last week and learned quite a few valuable tips that enhanced my debugging abilities.

1. Step over simple properties*. The Visual Studio debugger now allows you to automatically step over simple properties (your getters and setters) when stepping through your code. This feature is automatically turned on with VS2008 SP1, so you don't need to do anything at all to get this functionality. However, since there are times when you might want to step into your properties, you can disable this feature in Tools | Options | Debugging | General and deselecting the Step over properties and operators checkbox.

 

1

 

Alternatively, when debugging you can right-click in your code and deselect the Step over properties and operators option in the context menu. One final option available to you for more fine-tuned control is the Step Into Specific menu, which appears in your context menu when debugging. This menu contains all of the target methods that the line of code you are on can invoke, and allows you to select them individually so that you can step into them and debug them as needed.

 

2

 

*This tip requires Visual Studio 2008 Service Pack 1 (or a later version).

 

2. Setting Tracepoints. Most of us know and love breakpoints. They're those awesome little red dots that you place next to a line of code to halt execution so you can examine the current state of the application. But there is this cool new feature introduced in Visual Studio 2008 that allows you to perform some action automatically when that line of code is reached . This feature is called a tracepoint.

Tracepoints weren't really introduced in Visual Studio 2008; they are also available in VS 2005. In fact, they were only distinguished from breakpoints (with a new name and a spot in the context menu) in the newer version. Those of you who haven't yet upgraded can get this functionality too. But I digress...

To insert a tracepoint, simply right-click on a line of code and select Breakpoint | Insert Tracepoint.

 

1

 

This will launch a dialogue from which you can define a behavior for that tracepoint. First, you can print any message you want. This is handy if you are an old-school developer who loves to use Console.Writeline() to output variable values, but with this method you do not have to dirty up your code. You can also associate a macro with the tracepoint and you can decide whether or not you want the code to halt at the tracepoint (at which time it becomes a breakpoint?) by selecting or deselecting the Continue execution checkbox.

 

2

 

Finally, you'll notice that when using a tracepoint you get a red diamond indicator next to the line of code instead of the typical red circle associated with breakpoints.

 

4

 

When the code execution reaches the tracepoint, the debugger will print your message, run your macro, and/or halt execution, depending on the preferences you set.

 

3

 

For those of you using Visual Studio 2005, you can get this same functionality by setting a breakpoint, right-clicking on it and selecting the "When hit..." option from the context menu.

 

3. Conditional Breakpoints. Sometimes in order to track down a bug or verify your code's behavior, you need the debugger to break on a certain line of code, but only if a certain condition is met. I don't know how many times I've had a breakpoint inside a foreach loop and been forced to hit the Continue button in Visual Studio over and over until the variable I was interested in finally had a certain value. Imagine how delighted I was when I learned how to set conditional breakpoints so that the code would simply continue chugging along until that condition was met.

To set a condition on your breakpoint, right-click on it and select Condition... You will be greeted with a dialogue which allows you to set an expression as your condition, and two radio buttons which specify whether to break when the expression is satisfied (Is True) or when the value of the expression has changed (Has Changed).

 

7

 

Notice now that the breakpoint contains a white "plus" sign in the middle of it, indicating that it is a conditional break point.

 

8

 

Another condition you can set is a hit count. You set this by right-clicking on your breakpoint and selecting the Hit Count... option. Again you'll be greeted with a dialogue that asks you to specify a condition which will cause the debugger to halt code execution.

 

9

 

You are given 4 options: Break Always, Break when hit count is equal to <insert value>, Break when hit count is a multiple of <insert value>, and Break when hit count is greater than or equal to <insert value>. A "hit" occurs only when the other conditions for that breakpoint are met. So if I have the condition "i % 2 == 0" on a breakpoint inside a for loop and a hit count set as "Break when hit count is a multiple of 2" the debugger will break when i = 2, 6, 10, 14, 18, etc...

 

4. Enable .NET reference support. Earlier this year, Microsoft announced that it would make the .NET Framework source code available to developers for debugging support. While this was great news for developers, there were a few steps that had to be taken in order to make the source code available in Visual Studio. You see, you can't just go download the source and browse through it; instead, you must reference the symbol files from Microsoft's source server and download them when you are ready to step into some framework code. Shawn Burke posted some detailed instructions on how to do this in Visual Studio 2008.

Now, with Visual Studio 2008 SP1 you can skip all of those steps and set a single option to get .NET reference support. Simply go to Tools | Options | Debugging | General and select the Enable .NET Framework Source Stepping checkbox. When you hit OK, Visual Studio will download the .NET Framework symbols to your symbol cache. If you want to change the default location of your symbol cache, go to Tools | Options | Debugging | Symbols. 

 

5

 

Now whenever you want to step into a .NET Framework method, you can do so just like you do with the methods in your project. In the picture below, I hit F11 to step into the Trim() method of the System.String class.

 

6