November 28, 2006

Tips For Exam 70-536

I'm happy to report that I recently passed Exam 70-536: .NET Framework 2.0 - Application Development Foundation. This test is one of the requirements necessary to obtain Microsoft's new MCTS certification. And since the MCTS certification is a pillar in the new accreditation structure, its relevance to the professional developer cannot be ignored.

Here are a few suggestions I'll toss out to anyone interested in preparing for this exam:

  1. Purchase a good certification study guide. I used the one by Microsoft Press (click here for details) mainly because it was the only one available at the time I needed it. The book wasn't terribly noteworthy (and it even contained some minor errors) but at the end of the day it served its purpose as a prompt to direct my personal study times. By next year new study guides with even better authors (such as Amit Kalani) should be hitting the shelves.

  2. Take notes on topics as you learn. I found it valuable to jot down notes as I studied the API's in the framework. These notes were also a helpful review during the last few days leading up to the exam.

  3. Become good friends with MSDN. Though a study guide is good, it will only get you so far. The scope of this exam is very large and MSDN provides many helpful supplements to fill in the gaps.

November 08, 2006

.NET Framework 3.0 Released!

The .NET Framework version 3.0 was released this week. This iteration sees no change to the existing class library or the underlying CLR. Instead, it simply adds some significant new APIs on top of the existing 2.0 framework.

The new APIs are as follows: Windows Communication Foundation, Windows Presentation Foundation, Windows Workflow Foundation and Windows CardSpace. Click here to download the redistributable.

October 13, 2006

Windows Vista as a Development Platform

As Windows Vista RC2 hit last week I've come across several mildly disturbing articles regarding the integrity of Vista as a development platform. First off was the announcement of SP1 Beta for Visual Studio 2005 on Somasegar's blog. Sounds like good news, right? Well, further down he also reveals that Vista will not support Visual Studio 2002 or Visual Studio 2003. In addition, he admits that Visual Studio 2005 will most likely suffer from compatibility issues beyond those addressed in SP1. In my mind this doesn't communicate strong support for what is supposed to be Microsoft's flagship development platform. I imagine this issue could easily stop most developers from trying Vista anytime soon due to the fact that they still need to continue supporting older applications via older versions of Visual Studio.

There have also been rumors going back and forth debating Java's ability to keep up with the new "Aero" look and feel in Vista. Thankfully, it appears as if this will only be an issue for older versions of Java.

On a positive note, IIS 7 in Vista will finally elevate PHP to a first class citizen. The newest version of Microsoft's webserver is on target to introduce a FastCGI host. Such a change will honor the single-process-per-request execution model of PHP, but do so much more efficiently than traditional CGI. For more information check out this blog entry by Mike Volodarsky (member of the IIS team).

September 23, 2006

The C# Coalesce Operator

This week I was excited to learn about the coalesce operator, a feature new to C# in .NET 2.0. Coded as a double question mark (??), it works by yielding the first non-null item from a group of two or more objects (as you might expect, this behavior is very much like the COALESCE function in MS SQL). Using this operator can help produce more elegant code if, for example, you've got something like this:
if (object1 != null)
{
return object1;
}
else if (object2 != null)
{
return object2;
}
else if (object3 != null)
{
return object3;
}
else
{
return null;
}

With the coalesce operator the above code block can be refactored into the following:
return object1 ?? object2 ?? object3;

August 23, 2006

Using FontInfo in a Custom Server Control

In many circumstances it's appropriate to assign a FontInfo structure as part of a custom server control. This easily allow programmers to adjust the look at feel of certain areas of text but can be a little tricky to implement because FontInfo doesn't have a public constructor. One way to accomplish this is to create a CSS Style object and use it's Font property to do the dirty work. This technique would look something like this:
private Style _headerFontStyle;

[Bindable(true),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
NotifyParentProperty(true),
Category("Appearance"),
Description("The font for the header."),
Localizable(true)]
public FontInfo HeaderFont
{
get
{
if (_headerFontStyle == null)
{
_headerFontStyle = new Style();
}
return _headerFontStyle.Font;
}
set
{
_headerFontStyle.Font.CopyFrom(value);
}
}

So is that all there is to it? Well, not exactly. Unfortunately, FontInfo is not serializable, nor does it implement IStateManager making it difficult for us to track it's state if any changes are programmatically made to the structure.

The good news is that in the code above we're using a Style object to get at the underlying FontInfo. Since Style implements IStateManager we can override the following methods to make sure that the FontInfo property is always kept in ViewState across post backs.

protected override object SaveViewState()
{
object[] state = new object[2];
state[0] = base.SaveViewState();
state[1] = ((IStateManager)_headerFontStyle).SaveViewState();
return state;
}

protected override void LoadViewState(object savedState)
{
object[] state = (object[])savedState;
base.LoadViewState(state[0]);
((IStateManager)_headerFontStyle).LoadViewState(state[1]);
}

protected override void TrackViewState()
{
base.TrackViewState();
if (_headerFontStyle != null)
{
((IStateManager)_headerFontStyle).TrackViewState();
}
}

July 29, 2006

Approximating Master Pages in PHP

Most sites on the Internet have common design elements that do not change from page to page. Usually, only content or minor navigational cues vary. To handle the unchanging aspects, developers have often relied on server-side includes - dividing regions like headers, side navigations and footers into separate files.

But now with the advent of ASP.NET 2.0 Master Pages offer a more complete templating alternative. With Master Pages an entire template common to the site is stored in one file with a .master extension. Developers add a ContentPlaceHolder control inside a Master Page to indicate where they would like their page specific content to appear. Then one or more Web Forms may be set up to automatically dress themselves with the shared visual components defined in the Master Page.

So is it possible to make PHP emulate this behavior? To some degree, yes, with output buffering and one server-side include file that represents the "Master Page." Lets say we are aiming to create our HTML by combining this template file and a content file (we'll call these master.php and index.php, respectfully). Our simplified example will aim to achieve the following end result:



The template that will act as our "Master Page" will need to contain all aspects of the design labeled "Template Specific." Since no such control like the ContentPlaceHolder exists, we will use PHP variables to indicate where we would like our page specific content to appear.

master.php
<html>
<head>
<title><?php echo $pagetitle; ?></title>
</head>
<body style="margin-top:20px;margin-left:20px;margin-right:20px;">
<table width="100%" border="0" cellpadding="10" cellspacing="0"border="0">
<tr bgcolor="#33FFFF">
<td colspan="5"><h2>Template Specific Header</h2></td>
</tr>
<tr bgcolor="#EEEEEE">
<td nowrap><a href=#">Navigation Link 1</a></td>
<td nowrap><a href="#">Navigation Link 2</a></td>
<td nowrap><a href="#">Navigation Link 3</a></td>
<td nowrap><a href="#">Navigation Link 4</a></td>
<td width="100%">&nbsp;</td>
</tr>
</table>
<br />
<table width="100%" cellpadding="10" cellspacing="0" border="0">
<tr>
<td width="30%" valign="top" bgcolor="#EEEEEE"><strong>Template Specific
Navigation</strong><br /><br />
<a href="#">Link 1</a><br />
<a href="#">Link 2</a><br />
<a href="#">Link 3</a><br />
</td>
<td width="70%" valign="top"><?php
echo $pagemaincontent;
?></td>
</tr>
</table>
<br />
<table width="100%" cellspacing="0" cellpadding="10" border="0">
<tr>
<td colspan="2" bgcolor="#33FFFF">Template Specific Footer</td>
</tr>
</table>
</body>
</html>

Now any pages that we would like to have adhere to the template only need to define the page specific variables and include our master.php file.

index.php
<?php
//Buffer larger content areas like the main page content
ob_start();
?>
<em>Page Specific Content Text</em><br />
Lorem ipsum dolor sit amet, consectetuer adipiscing
elit, sed nonummy nibh euismod tincidunt ut laoreet
dolore magna aliat volutpat. Ut wisi enim ad minim
veniam, quis nostrud exercita ullamcorper
suscipit lobortis nisl ut aliquip ex consequat.
<br /><br />
Duis autem vel eum iriure dolor in hendrerit in
vulputate velit molestie consequat, vel illum
dolore eu feugiat nulla facilisis ats eros et
accumsan et iusto odio dignissim qui blandit
prasent up zzril delenit augue duis dolore te
feugait nulla facilisi. Lorem euismod tincidunt
erat volutpat.
<?php
//Assign all Page Specific variables
$pagemaincontent = ob_get_contents();
ob_end_clean();
$pagetitle = "Page Specific Title Text";
//Apply the template
include("master.php");
?>

Even though it's not perfectly aligned with ASP.NET's Master Page feature set, the technique described above allows us to consolidate what might otherwise be numerous server-side include files.

July 21, 2006

Control Designer Gotcha

This week I've been programming a custom web server control. It required some specific behavior while being manipulated in the design view of Visual Studio 2005. To achieve this I decided to extend a ContainerControlDesigner to suit my needs. In order to test my new control as I worked on it, I added my efforts to a web project.

However, despite importing the ContainerControlDesigner's namespace (System.Web.UI.Design), the class definition could not be found and as a result it wouldn't compile. I discovered that the classes in the System.Web.UI.Design namespace belong to the System.Design.dll assembly which is not referenced by default in a Visual Studio 2005 web project. I had mistakenly assumed this class was already a part of the referenced System.Web.dll. After adding a reference to System.Design.dll (see image below) my custom control designer compiled flawlessly.

July 08, 2006

MacBook Pro 10.4.7 Kernel Panic Issue

I encountered an issue with my MacBook Pro today that was somewhat troublesome to fix. After months of flawless operation my Mac suddenly started experiencing kernel panics on every boot occuring less than a minute after arriving at the login screen. Since Boot Camp is installed I feared the worst, especially after catching wind of some horror stories on Apple's support forums.

After further research I was relieved to find a simple solution. It turns out that two versions of Apple's 10.4.7 upgrade were released on the same day. I was able to boot into OS X's "Safe Mode" by restarting the computer and holding down the Shift key. Once booted I checked my version of the OS by clicking the "Apple Menu -> About This Mac" option, clicking the "More Info" button and highlighting the "Software" header in the left navigation area. Software update had installed build 8J2135, the first version of the 10.4.7 upgrade that happened to be missing some key files. I downloaded and installed the fixed upgrade (build 8J2135a) from here and encountered no further problems.

June 24, 2006

Getting Visual Studio 2005 and IIS 5.1 to Play Nice

Visual Studio 2005The other day I installed Visual Studio 2005 on one of my workstations and proceeded to create an ASP.NET web service. For the most part the Casinni webserver that's built into Visual Studio served my testing needs. But I eventually reached a point where I wanted to run the application on IIS just to make sure it encountered no problems in the target environment.

IISSo I installed IIS 5.1 on my Windows XP box and created a virtual directory containing the project. I set IIS to run it as an ASP.NET 2.0 application and was greeted with this error message when I browsed to the .asmx file:

Failed to access IIS metabase.
The process account used to run ASP.NET must have read access to the IIS metabase (e.g. IIS://servername/W3SVC).

I was referred to a Microsoft Knowledge Base article. The problem supposedly happened because the ASP.NET worker process didn't have permissions to the mystery that is the IIS metabase. My guess is that this ocurred because I installed IIS after I installed Visual Studio. Microsoft recommended running the following command line as a remedy:

aspnet_regiis –ga [WindowsUserAccount]

I substituted ASPNET (the ASP.NET account on Windows XP) in for [WindowsUserAccount]. Unfortunately this did not solve the problem and I continued getting the same error mentioned above.

After searching some forums I found others who had encountered this issue who advised reinstalling the .NET 2.0 Framework. I went ahead and did this as follows and it resolved the incident:

  • Run the Visual Studio 2005 Disk

  • Select "Change or Remove Visual Studio 2005"

  • Choose Repair/Reinstall

June 11, 2006

Retrieving "Date Taken" EXIF Metadata From a JPG

For the most part the GDI+ API in the .NET Framework 2.0 is powerful enough to match almost any image related challenge. However, I encountered some functionality that I found to be lacking in regards to how EXIF embedded metadata is retrieved from JPG files. My goal was to get the "Date Taken" property from an image using C#.

Unfortunately each slice of the image's metadata (AKA the PropertyItem object) can only be retrieved using a rather unintuitive integer-based ID look up. For example, you have to know that the "Date Taken" information can be accessed using a PropertyItem ID of 36867. Perhaps an enumeration of these IDs will be added to a future version of the Framework to help make this task easier for programmers? Justin Rogers made such an object available here to help folks out in the meantime.

Once the "Date Taken" PropertyItem has been defined we still run into problems after decoding it to a UTF8 string. To have the most flexibility in addressing this information it would be ideal to convert it to a DateTime object. However, the PropertyItem string value is decoded in a "YYYY:MM:DD HH:MM:SS" format. Sadly, the colons between the year and the month and the month and the day throw off both the Convert.ToDateTime() and DateTime.Parse() methods.

I've listed the GetDateTaken() method below as an example of the remaining string manipulation necessary to complete this task:

public DateTime GetDateTaken(Image targetImg)
{
//Property Item 36867 corresponds to the Date Taken
PropertyItem propItem = targetImg.GetPropertyItem(36867);
DateTime dtaken;

//Convert date taken metadata to a DateTime object
string sdate = Encoding.UTF8.GetString(propItem.Value).Trim();
string secondhalf = sdate.Substring(sdate.IndexOf(" "), (sdate.Length - sdate.IndexOf(" ")));
string firsthalf = sdate.Substring(0, 10);
firsthalf = firsthalf.Replace(":", "-");
sdate = firsthalf + secondhalf;
dtaken = DateTime.Parse(sdate);
return dtaken;
}

March 07, 2006

Embedded Video

I was recently asked to enhance a site with some embedded video. The specifications of the project required that the user be able to choose between QuickTime or Windows Media formats for each file.

My goal was to make sure that the media would run properly in Internet Explorer, Firefox and Safari. Most of the tutorials I encountered detailed various basic implementations of "object" and "embed" tags that did not end up meeting my requirements.

Finally, I found a web application from the University of California that automatically generates HTML to easily embed your video format of choice (Windows Media, QuickTime, Real Media, etc) in a cross-browser compatible manner.

Check out the Embedded Media HTML Generator for yourself.

February 23, 2006

PHP to ASP.NET Scalar Query Port

Lets pretend for a moment that you are writing a bit of PHP code that determines if a value is present in your database. Such code might look something like the following:
<?php
function UserExists($username, $db) {
$sql = "SELECT * FROM Accounts WHERE UserName = '" . $username . "'";
$result = mysql_query($sql, $db);
if (mysql_num_rows($result) > 0) {
return true;
}
else {
return false;
}
}
?>

Now suppose you've been asked to switch this application to ASP.NET 2.0/C#. What would you do? One possible port of this scalar query is listed below:
protected bool UserExists(string userName)
{
int results = 0;
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["Sample ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT COUNT(*) FROM Account WHERE UserName = @username";

try
{
SqlParameter paraUserName = new SqlParameter("@username", SqlDbType.NChar, 40);
paraUserName.Value = userName;
conn.Open();
cmd.Parameters.Add(paraUserName);
results = (int)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
finally
{
conn.Close();
}

//Return true if userName was found in the database
if (results > 0)
{
return true;
}
else
{
return false;
}
}

January 31, 2006

Internet Explorer 7 Beta 2

Set the way back machine for five years ago. The flux capacitor flutters with light and goes still. There...that was easy. So what did 2001 give us? In addition to the September 11th terrorist attacks, the first iPod and Jackson's The Fellowship of the Ring, Microsoft delivered Internet Explorer version 6. Fast forward to the present. After five years the advances in Safari, Firefox and Opera have eroded Microsoft's browser initiative and left it stagnant.

Nevertheless, Microsoft has been working on Internet Explorer 7 and released it's first public beta (Beta 2) today. In addition to tabbed browsing, improved security, integrated RSS and layout enhancements, Internet Explorer 7 will feature updated style sheet support bringing it more up to speed with the CSS 2 specification. These changes might not seem earth shattering but they are important. Given the fact that Microsoft controls over half the browser market any changes at all tend to reach a wider sphere of influence.

Overall, IE 7 seems like a nice incremental upgrade. The changes are not revolutionary, but merely put it back in the running with its competition. The Phishing filter seems like a nice idea in theory, although I haven't had much time to play with it yet. I appreciate the simple layout of buttons, integrated search and RSS...probably because I have come to expect this from other browsers. Again - not much innovation going on here.

The one new feature that I haven't seen anywhere else is the ability to "Zoom" in on sites. However, I am at a loss as to why this was even included. Perhaps it could be useful for those who are visually impaired? In my mind, however, the "Text Size" feature from Internet Explorer 6 sufficed for this purpose. Can anyone give me a good answer as to why this feature might be important?

I must admit that from a web developer's perspective I am most excited about Internet Explorer 7's CSS support. For myself, Firefox and Safari have always been quite responsive when I've pushed CSS technology...it is IE that has held me back. With the style sheet changes promised in this iteration of Internet Explorer I think it might help usher in a period of easier cross-browser development.

Check out this page to download and test IE 7 for yourself.