Archive for the ‘Visual Studio 2005’ Category

Bubbling up Methods in Composite Controls

A while back, I wrote a couple of articles (here and here) regarding encapsulating the ModalPopupExtender into a spiffy little template control that you could toss onto a page.  It’s worked GREAT over the past few months, however, I hit a snag today.

I needed to call the base ModalPopupExtender’s .Show() method from code behind; however, I hadn’t bubbled that up to the Composite Control.

At first, I expected to simply add a private instance of the MPE (which is assigned to when the control is built) and then add a method to my composite control that calls the .Show() method.

private ModalPopupExtender _control;

public void Show()




That sounds good, but it never fired and the _control field was always null (even though I could step through and it was assigned).

What it needed was a little reminder—a reminder to EnsureChildControls existed before trying to call Show().  Now, a quick update to the code:

public void Show()





Now I can call the Show() method of the Composite Control and it works like a charm!  Here’s an example (for what I’m working with at the moment) of dynamically iterating through an IDictionary and returning the values in a Modal Popup.


<tiredstudent:ModalPopupTemplate HeaderText=”ERC” runat=”server”

        ID=”PopupDialogBox” DefaultStyle=”YUI” TargetControlId=”fakeButton” />

<asp:Button ID=”fakeButton” runat=”server” style=”display: none” />


foreach (var entry in results)


       sb.AppendLine(string.Format(“<p>{0} – {1}</p>”,

                     entry.Key, entry.Value));



PopupDialogBox.BodyText = sb.ToString();




Basic Benchmarking in ASP.Net

April 10, 2008 1 comment

I’m not sure why I’ve always rewrote this “simple” code—over and over again, project after project.  I should know better, but perhaps time has gotten the best of me (though I’m betting on lazy).

What code might this be?  The basic “stopwatch” for evaluating page performance and outputing the results to Page.Trace. You can do page speed analysis using Visual Studio 2008, but for quick Trace output, I prefer this method.

The class is almost totally private, but could be expanded later on to log to console, log to files, whatever.

public class BenchmarkToTrace


private TimeSpan ElapsedTime { get; set; }

       private DateTime StartTime { get; set; }

       private DateTime EndTime { get; set; }

       private Page PageToTrace { get; set; }

       private string TraceCategory { get; set; }


       public BenchmarkToTrace(Page pageToTrace, string category)


              PageToTrace = pageToTrace;

TraceCategory = category;

PageToTrace.Trace.IsEnabled = true;



       public void Start()


              StartTime = DateTime.Now;



       public void Stop()


EndTime = DateTime.Now;

ElapsedTime = EndTime – StartTime;




“Start: {0} “ + Environment.NewLine +

“Stop: {1} “ + Environment.NewLine +

“Elapsed: {2}”,

StartTime, EndTime, ElapsedTime));



As far as usage, here’s how I am using the benchmarker to evaluate different data retrieval methods (in this example, measuring Oracle performance):

BenchmarkToTrace bench =

new BenchmarkToTrace(this.Page, “Reports-GetAllBy”);



Reports.GetAllBy(123465789, 3, “2007-2008”);




Reports.GetAllBy(123456789, 4, “2007-2008”);


When I load up the page, I see the trace log:

BenchmarkToTest Results

Cool, and I won’t rewrite this NEXT time.

Verifying Extensions and MIME Types of FileUpload

April 7, 2008 Comments off

The FileUpload control is REALLY handy to upload files from a client, through the web, into a database table or the web server.  The control wraps up the HttpPostedFile object (into .PostedFile); however, there isn’t a way to “filter” on the fly.  This was a recent discussion in the Microsoft newsgroups today, so I figured I’d work out what it’d take to implement a “better” file upload control.

The control, inheriting the FileUpload class as a base class, implements quite quickly.  I’m sure you could go farther, but this works out nicely.

NOTE: In my experience, filtering by MIME type (aka content type) is much more reliable than parsing out the uploaded file’s file name and trying to grok the extension.  Extensions are far too easily changed. ๐Ÿ˜‰

public partial class BetterFileUpload : FileUpload


public BetterFileUpload()


              ValidContentTypes = new List<string>();



public IList<string> ValidContentTypes { get; private set; }


public void AddValidContentType(string contentType)





public void AddValidContentType(string[] contentTypes)


              foreach (var contentType in contentTypes)






public bool HasValidContentType()






This partial class simply adds a few methods and a single property to the FileUpload class—ValidContentTypes.

HasValidContentType looks through the ValidContentTypes and tries to match it to the PostedFile’s content type—then returns a boolean.

Using this code is simple.

To setup a few valid content types, you can either pass them one-by-one or as an array (you could also pass in a collection of some sort and use the ToArray() method to convert it back into an array).  You could also store these in the web.config file or another reusable source to keep the code clean.

protected void Page_Load(object sender, EventArgs e)





              new[] {“application/msword”, “application/pdf”});


After the valid content types have been added and we’re ready to fetch the stream from the FileUpload object, we now have a tidy boolean method to check.

protected void ReadFileButton_Click(object sender, EventArgs e)


if (betterFileUpload.HasValidContentType())


              InfoLabel.Text = “Valid ContentType: “ +





              InfoLabel.Text = “Invalid ContentType: “ +




Works well and is reusable!

SVNing in Visual Studio 2008

March 26, 2008 1 comment

At work, we’re still a Visual SourceSafe shop.  It works, don’t knock it.

However, at home, I’ve become VERY happy with SVN.  TortoiseSVN is great to drop and pick up repositories, update, and all that jazz, but I really missed the convenience of having those functionalities in Visual Studio.

I remember Will mentioning that having the VS plugins “dirtied” up the environment with junk.  Maybe, but damn it… a hot key to sync to SVN, apply patches, see differences, etc., to me, is a productivity boost.  Maybe I’m not as hardcore as Will—or I’m just more lazy.

So, after looking around, I found two rather attractive plugins for SVN.


VisualSVN is pretty darn slick.  The Server itself works very well, adds a beautiful MMC console for managing repositories, and just makes sense.  The VS integration plugin works great and it works hand-in-hand with TortoiseSVN.

I liked the interface for logging messages, checking in, and looking at differences the best.

The downfall—it costs a bit of money, but just a bit.

A personal license (well, and a corporate too, haha) is 49$US per individual.  If you are part of an active open source project, you’re in luck because it’s free (I’m assuming they appreciate the free advertising).

The advantage—while the connector for Visual Studio costs 49$US, the VisualSVN SERVER license is FREE.  That keeps us out of the command prompt for creating and managing the basics.  Good deal.


AnkhSVN is a free, open source solution for using SVN with Visual Studio.  Rather than relying on Tortoise, AnkhSVN actually fully integrates into Visual Studio—for Diffs, logging, snap-ins for the repositories, additional Solution explorer windows, and more.

It has the snazzy icons as well.

Unlike VisualSVN, it feels a bit rough. 

The menus are all over the place (the AnkhSVN menu is actually hidden in Tools and then adding the repositories is under File).  It also doesn’t register as a Source Control plug-in with Visual Studio (I’m assuming it’s working AROUND Visual Studio, not through it), so the File > Source Control menu never appears and cannot be used.

So what am I using?

Both.  The VisualSVN server is great and saves me some headaches for setting up repositories—I also love the web interface.  AnkhSVN, while a bit rough, works very well.  I’m using the 1.0.3 Preview release for VS2008, so I’m assuming it’ll continue to improve and I look forward to contributing where I can to that process.  The Server is running on Windows Server 2003 R2 and AnkhSVN works like a champ under both Windows Vista SP1 and Windows Server 2003 R2.


Visual SourceSafe 2005 – “HotFixes”

March 11, 2008 Comments off

I’ve apparently been out of the SourceSafe bit for a while now (now that I’m happy wiht SVN), but had to reinstall it today to touch a few old projects (from back in 2004).  After I installed, I tried to move a few files around and the SourceSafe Administrator kept locking up. 

Angry and frustrated, I hit up Google and found that a “hotfix” was published for SourceSafe back in December 2007 that summed up over 64 updates to the program—including fixes with Visual Studio 2008.

It notes:

This update is a rollup of hotfixes for Visual SourceSafe 2005. This update includes many stability improvements, performance improvements, data improvements, integrity improvements, and usability improvements. This update also improves compatibility with Microsoft Visual Studio 2008 and with Windows Vista.

After installing the updates, SourceSafe is working better than it ever has.  Cool.


.NET Tip of the Day

February 28, 2008 Comments off

I stumbled upon the site earlier today while watching my system Ghost—and it’s pretty cool.

If you haven’t checked it out, they provide a single “tip” or trick to using .NET (from using Visual Studio to performance considerations oc concatenation) and is available ala RSS (just the way I like it).  The site is clean, which is an added bonus.

Check it out.


LOLCode – Implementing “Fuzzy” Logic on Domain Driven Design

January 14, 2008 1 comment

Yeah, it’s still a Monday.  A week or so ago, a friend and I spent far too much time laughing at the LOLCats page—one of the most popular blogs here on WordPress (I’m not quite sure what that says about humanity, but none-the-less).

Earlier in 2007, a few developers coded up a compiler for the “leet” language of LOLCats called LOLCode.  I remember Scott Hanselman doing an article on it, but glossed over it.  I came across the site again today and, while’s totally insane, it did get me laughing.

Here’s an example of a try/catch block.


What’s scary is that this isn’t much more difficult to read than some code I’ve inherited from others.  Heh.  If you’re totally bored, I suggest giving it a shot.  Scott’s article explains a .NET version of LOLCode, with compiler, for lots of coding fun!


Visual Studio 2008 "Consolas" Theme

November 16, 2007 4 comments

A few readers have emailed in asking what my Visual Studio font was–and how I had my development environment setup based on the screen shots I’ve posted up.

I’m a big fan of the Consolas font for development.  Consolas is part of Office 2007 and Vista, so you can grab it from those packs.  To me, it’s clean and crisp while still being very easy to read hundreds of lines of code.  I blogged and have an example about the font and it’s history here.

Here’s a link to download the font without needing Office 2007 and Vista (it’s from Microsoft, so no theft involved as long as you’re putting it into use in Visual Studio).

Finally, here’s a link to my Visual Studio environment settings; to save you some time.  Right now, I have the font size set to 11 (I use a 24″ or 30″ wide screen monitor depending where I am, so a bit larger size.  Changing the size is pretty easy.

To import the settings, open up Visual Studio, go to Tools | Import and Export Settings…


Creating a Countdown Image Handler in ASP.NET

November 11, 2007 Comments off

I love WordPress—it’s by far one of the best packaged blogging engines I’ve come across and has kept my DIY tendancies at bay for several years now.  With the structure of WordPress, however, comes restrictions.  My biggest complaint is that I can’t place JavaScript tools or components on my page. 

In the past few months, one thing I would have liked to have was a little “countdown” to graduation, the holidays, whatever.  That’s brilliantly simple with JavaScript.  Meh. ๐Ÿ˜ฆ  I looked at a few other sources, but they required registration and made the images HUGE.

So, this afternoon while catching up on my Top Gear obsession on BBCA, I coded up a quick HttpHandler.

You can see an example of the image created by this on the right side of the blog—the Graduation countdown ticker.

Download Code: .NET 2.0

The handler accepts two optional variables, width and height, and two required variables, eventText and eventDate.

By default, the width of the image is 100px and the height is 120px—about the size of a standard small banner.

For this code, the most important namespaces are System.Drawing and System.Drawing.Imaging.

First, we need to create a new Bitmap image to hold our graphic.

Bitmap imageBitmap = new Bitmap(width, height);

Next, create a drawing pad, of sorts, in a Graphics object and associate it with our new bitmap image.

Graphics graphicObject = Graphics.FromImage(imageBitmap);


new SolidBrush(Color.White), 0, 0, width, height);

Since, by default, the background is Black, call FillRectangle (from 0,0 to the max width and height) to fill the background with White.

Our next task is to create a border around the image.  I chose a black border with a 2px width.  The draws are in order of top, left, right, and bottom lines.  Note: I’m sure there’s a better way to do this by creating an empty rectangle or something…

Pen borderPen = new Pen(Color.Black, 2);



new Point(0, 0),

new Point(width, 0));



new Point(0, 0),

new Point(0, height));



new Point(width, 0),

new Point(width, height));



new Point(0, height),

new Point(width, height));

Our final touch is to put the text onto the image.

Font textFont = new Font(“Arial”, 8, FontStyle.Bold);

SolidBrush textBrush = new SolidBrush(Color.Black);


string imageText = eventText + “: “ + countdown.Days + “d”;





new PointF(2, 2),


To “type” onto an image, create a “font brush” with the assigned color, font face, and size.  Instead of drawing a line or shape, use DrawString.  The fourth paramenter(new PointF(2,2)) specifies where to begin the text—you can get more creative than this and figure exact locations based on image size.

Finally, use the context supplied by the ProcessRequest method to return the image to the consumer.

context.Response.ContentType = “image/gif”;

imageBitmap.Save(context.Response.OutputStream, ImageFormat.Gif);

That’s it! 

If you’re interested in the source code, the link is at the top of the post—download and enjoy!  As I update the code, I’ll post it up.  This has lots of room for improvement, but is a nice starting point for those who want to put a dynamic image on their hosted blogs. ๐Ÿ™‚

Behind the Scenes – ModalPopupTemplate

November 8, 2007 3 comments

The ModalPopupTemplate control is a Composite Control—or a control that is a collection of other controls and implements the CreateChildControls method.

This post demonstrates how the ModalPopupTemplate (MPT) was created and also points out a few of its current weaknesses and areas for improvement (hey, I’m honest…).

Attaching Custom Events

As with any control, the MPT has an array of external properties available.  Most importantly are the three events and the styling properties.

To attach custom events to a control, they are implemented similar to a property; however, the method used to attach the event is a virtual method.  Let’s take a look at our OkClick event.  The other events follow suit in functionality.

// Events of Popup

public event EventHandler OkClick;

protected virtual void OnOkClick(EventArgs e)


if (OkClick != null)


              OkClick(this, e);



Our OkClick accepts EventHandler events and can be used for UpdatePanel triggers, etc; however, our control needs action methods (On_) to link events to methods on your page.  That’s where the virtual method comes in.

Later in the code, when the Ok, Close, and Cancel buttons are generated, there’s one more bit of code.  The Click events are optional so we still need to tie a bit of functionality to them to close the popup window.  This is done by mixing a bit of JavaScript into the mix.

if (OkClick != null)


// If an OK Behavior is assigned, use it.

       okButton.Click += OkClick;




// If not, the OK button just hides the popup.

       okButton.OnClientClick = “$find(‘popup’).hide(); return false;”;


Prefabricated Style Sheets and Custom Style Sheets

A template has to have a few styles built into it.  This is currently an “under construction” area of the control as there has to be a way to generic it up a bit and lose the ugly case statements.

When the DefaultStyle property is set to Custom, this code is bypassed or simply there isn’t a “style” attached to the control.  You’ll get plain black text, white background, and no borders.  If DefaultStyle isn’t specified in the control, the YUI theme is applied.

if (DefaultStyle != PopupStyle.Custom)


string includeLocation = “”;

switch (DefaultStyle)


case PopupStyle.YUI:

       includeLocation =





case PopupStyle.Clean:

       includeLocation =








HtmlLink cssLink = new HtmlLink();

cssLink.Href = includeLocation;

cssLink.Attributes.Add(“rel”, “stylesheet”);

cssLink.Attributes.Add(“type”, “text/css”);



This code retrieves the embedded resource URL from the library and adds a link to it in the page’s header.

Generating the ModalPopupExtender

The GenerateExtender method accepts one parameter: the control you wish to add the popup extender into.  You could remove the parameter and simply add it to the composite control’s ControlCollection, but I wanted to keep it open for later development.

private void GenerateExtender(Control container)


// Todo: Fix these hardcoded ID values for PopupControlId.

ModalPopupExtender mpe = new ModalPopupExtender();

mpe.BehaviorID = popupBehaviorId;

mpe.BackgroundCssClass = ModalBackgroundStyle;

mpe.PopupControlID = “popupPanel”;

mpe.TargetControlID = TargetControlId;



The code sets every property that you’d normally set on a ModalPopupExtender.  The only matter of disconnect at the moment is the PopupControlID’s value—I don’t like that hardcoded between this and the GeneratePanel method, but it’s minor for the time being.

Generating the Popup Panel

The popup panel’s code is cut down a bit for the post as it’s repetative: generate a Panel control, several labels for the header and body text, a few buttons and a link button, and then put it all together.

The most important part is to ensure that the DIV containers enclose the proper controls and that every tag closes itself, etc.

First off, we see the popupPanel setting it’s ID (to match the ID set in the ModalPopupExtender), CSS Class, and an additional style attribute to hide it (to prevent the blip of it appearing on page load).

The rest of the HTML and controls are interwoven between LiteralControls for exact HTML output.

popupPanel.ID = “popupPanel”;

popupPanel.CssClass = PanelStyle;

popupPanel.Style.Add(HtmlTextWriterStyle.Display, “none”);



new LiteralControl(“<div class='” +

ContainerStyle + “‘>\n\t<div class='” +

HeaderStyle + “‘>\n\t\t”));




new LiteralControl(“\n\t</div>”));



new LiteralControl(“\n\t<div class='” +

BodyStyle + “‘>\n\t\t”));



new LiteralControl(“\n\t</div>”));



new LiteralControl(“\n\t<div class='” +

FooterStyle + “‘>”));




new LiteralControl(“\n\t</div>\n</div>”));

Finally, this method, GeneratePanel, also accepts a control parameter to add the control to a specified collection.

Putting it together — CreateChildControls

The Composite Control’s method — CreateChildControls — is where the magic happens. 

protected override void CreateChildControls()




if (!this.ChildControlsCreated)








It’s usually a good practice to clear the composite control’s ControlCollection before starting—just to be sure that you know exactly what’s being rendered.  From there, call our Extender and Panel generation methods and place them in Composite Control’s control collection (this).

That’s it, you’re ready to add it to the page.  For more information about how to add it to the page and the control’s parameters, as well as the full source code and a demonstration site, visit the Creating a Modal Popup Template Control posting from 5 November 2007.