Thursday, April 24, 2008

Thanks to everyone for coming to the phillydotnet presentation tonight.  There were a lot of great questions, but a few recurring themes.  The big one I noticed had to do with dealing with the UI, and how much we're going to sacrifice in leaving the WebForms world. 

In the example we covered during the presentation, I showed how to bind basically everything in the .aspx page.  For those that were put off by how 'Classic ASP' that looked, I've created another example that may look a little more familiar.  Below, you're looking at the code for a page that that will show all of the products in the site using a repeater and a user control for each product.

<%@ Register Src="~/Views/Shared/ProductViewer.ascx" TagPrefix="eg" TagName="ProductViewer" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
    <asp:Repeater ID="rptProducts" runat="server">
        <ItemTemplate>
            <%# Html.RenderUserControl("~/Views/Shared/ProductViewer.ascx", Container.DataItem) %>
        </ItemTemplate>
    </asp:Repeater>
</asp:Content>

And the codebehind:

public partial class Index : ViewPage<List<Model.Product>>
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            rptProducts.DataSource = ViewData;
            rptProducts.DataBind();
        }
    }

As it turns out, there is a special MVCUser control you can add to your project which gives you access to the same ViewData available to the page.  If you want access to just one portion of your ViewData (eg: If you used a Dictionary of values to pass data from your Controller to your view), you could further specify the ViewDataKey, which is simply the key of the item in the Dictionary you wanted the UserControl to bind.  Finally, if you're doing something like what I am doing above (needing to bind to an instance in a collection, you can use the Html.RenderUserControl helper method, which allows you to bind whatever data you want.  There's a good read on this here: Matt Hidinger: ASP.NET MVC UserControls Start to Finish

Bear in mind that you could just create a regular, non-MVC usercontrol too.  You would just create whatever properties you wanted to bind to in that UserControl, and set them in the containing CodeBehind.  WARNING: Doing this means you have to again be aware of the PageLifecycle, because your user control can't try to bind its data until that data has been set. 

DesignMode_MVC

Sunday, January 06, 2008

I'm very excited to see this product so close to fully baked.  It's already light years ahead of web forms, but being in the middle of the first major rewrite of the site in who knows how long, I'm just not quite ready to bet my job on it.  (I am using it for a friend's site though)

That said, this post is just about the gotchas I've bumped into while trying to get myself grounded.  It's kind of some notes I'll be using for my presentation at the forthcoming phillydotnet Code Camp. 

 

Where Are The Bits?

This always seems to happen with MS's new bits.  It becomes difficult to know what and where everything is.  Well as of now, there are 3 components you will want (assuming you already know you need Visual Studio 2008):

  • ASP.NET 3.5 Extensions Preview - This is the primary download.  Install first
  • MVCToolkit - This download contains a project with some very handy extension methods that will help you recoup some of the functionality that sacrificing WebForms forces you to make.  At the time of this writing there are a number of bugs with this project, so I would recommend adding the project to your solution, rather than just using the dlls directly.  (Things like link errors, and XHTML validation failures). 
  • MVCContrib - Finally, this is an open source project on CodePlex that is focusing on adding the following (ripped shamelessly from the link provided)
    • IoC container controller factories for the popular containers: StructureMap, Windsor, Spring.Net, etc (i.e. whoever wants to contribute others)
    • Extra view helpers
    • Generic test doubles to aid unit testing
    • Visual Studio - Code Snippets
    • Resharper Live Templates

Where to Learn

I'm going to be posting some of my experiences here, but if you really want to get the best overview, start with Scott Guthrie's initial posts.  (Note that I started to put this list together myself, and then realized that Eilon Lipton had already compiled every single article I was going to link, and a few other.)

 

Ok, now on to a few issues I'm sure you'll run into as you start working with this code.

 

Problems With the Project Templates

Can't Access Controls in Code Behind

The first bug you're likely to run into is that you won't have access to your server controls in the code behind.  The solution to this is to right click in the Solution Explorer, and select Convert to Web Application.  This will create the .designer.cs files that define the partial classes needed for this to work.

Development Issues

Some Server Controls Don't Work

Next, you'll find that by default, a number of server controls do not work with the asp.net framework.  This is because they require a form with a runat="server" somewhere in the page.  By default, the MVC framework does not provide this.  Generally, the input controls will have this problem.  So does the BulletedList control for some reason. 

Remember, no ViewState

Lacking the form w/ runat=server, you'll also find that you don't have ViewState available to you. 

Other Tools (Resharper)

Currently, Resharper is at version 3.1.  It's generally passable for most .net 3.5 development, but it's more of a burden than a help if you're using MVC, because the framework takes so much advantage of extension methods, anonymous types, and lambda expressions.  Basically, Resharper chokes on all of these.  I'd recommend turning off the Intellisense instead, and instead trying CodeRush for the time being.  (I'm seeing what I think of CodeRush now).

Thursday, May 17, 2007

So I upgraded to Vista as soon as it was released, and needed a compatible Antivirus program.  Knowing how wrong these things can go (I'm the family computer guy), I did a fair amount of research.  In the end, I went with BitDefender, because the limited reviews I saw had it ranked pretty high, and the price was reasonable.  Oh how I wish I had gone into the future to read PCWorld's review.  They VERY MISTAKENLY still ranked it "Very Good", but they at least mentioned the painful performance drop.  To that though, I would add that I have no end of trouble with getting Windows Update to work w/ the antivirus on, so I effectively have to manage things manually.

I'm going to switch to a free alternative until I see whether BitDefender is going to update this piece of junk or not.

Wednesday, May 16, 2007

We've got some great community leaders in our neck of the woods.  I am going to a Code Camp set up for this Saturday, and we've been having frequent, and quality speakers come in for phillydotnet.  I've met a number of very cool people through these events, but it has occurred to a few of us, that the one thing missing is some solid peer to peer networking opportunities. 

My friend Marc Ziss has already started to tackle the problem in the best way he knows how.  Pub Night.  Cheers to Z.  I'm definitely looking forward to it.

I'm hoping to complement this new focus, by way of the Philadelphia .Net Users group on yahoo.  The idea is to allow us all to communicate about relevant topics at any time, rather than just at specific, physical events.  The idea has worked well for some of my friends back in Arizona, and so I figured it was time we gave it a shot. 

So I'm hoping we'll all sign up, and then be able to support one another during our day to day working lives.  The expectation is that we'll all get to know one another better, get answers/input from people we know and trust, and further strengthen our community.

If you have any ideas on how this could be further augmented and leveraged for all of our betterment, please post it to the group!

Thursday, May 10, 2007

Is Silverlight a Flash killer?  Not really.   Sure, flash is gonna die, but that's not what Silverlight has its sites set on. 

Silverlight IS AN HTML killer.  It's a tool for total Web revolution.  Silverlight, or a technology that provides what it provides, will bring us the WebOS. 

Why?  Well that will require several posts, but first let me address why calling it a Flash killer (or Java killer if you like), is doing Silverlight a disservice. 

Flash

Flash was an almost complete an utter failure.  That's a strong accusation to levy against the most popular browser plug-in in the world, so I'd better explain myself.  Why didn't Flash become THE web platform?  The graphics are better, the interaction is fluid, the support for web services is there.  So why do you only see it on banner ads, widgets (YouTube videos, Photo slide shows etc), and movie web sites?  Because Flash was meant for designers.  I've no doubt it does a best in class job in this arena.  However, designers don't program, and they don't handle data.  Lets face it, geeks are important to the equation if you want to create a site people come back to.  Adobe/Macromedia never invited the geeks.  As a result, flash has been relegated to a subservient position to, of all miserable, out-dated technologies, HTML/CSS/JS.  (It's possible that Flex is supposed to be Adobe's Silverlight, but I know nothing about it.  I don't think I'm unusual in that ignorance.  Most developers gave up on Flash years ago.  They've had at least a decade to run with this unimpeded, and they let it slip.)

Java

While I'm at it, what about Java?  Wasn't it supposed to be the killer web platform also?  Yeah it was, but it suffered from the exact opposite problem.  Java let developers do very intense, powerful things in a browser.  3D interactive web trees, chess games...  flat gray buttons.  Java on the browser is ugly.  Really REALLY ugly.  Designers weren't invited to that party. 

So the moral of the story is that designers and developers are both critical pieces to the puzzle.  You can't do anything compelling w/out buy-in from both sides.  Enter Silverlight.

Silverlight

Microsoft has created a platform that provides development tools to the developer, designer tools to the designer, and a data format that tries to be as agnostic as possible.  They saw the problem, and designed a solution to solve it. 

So this really just explains why Silverlight will sweep Flash aside as the dominant rich media platform.  It hints at why Silverlight will likely begin overtaking HTML/CSS/JS, but there are 2 other very critical pieces to this story.

Sunday, May 06, 2007

So being one of the few people from Philadelphia to choose Mix07 over TechEd, I was asked by Schwammy what he should focus on at TechEd.  There are a lot of cool things coming down the pipe right now.  It's a really exciting time to be a developer.  However, if it comes down to choosing a session of X vs Y, focus on:

  • Silverlight 1.1 - Note, 1.1 has .net integration, 1.0 does not.  1.0 is cool, and would be a worth Flash competitor.  1.1 is totally revolutionary.  It's not a Flash competitor.  It's an HTML/CSS killer.  Once this reaches fruition, you won't recognize the web anymore.  Plan accordingly.  If you get a chance to hear from Nikhil Kothari, or Scott Guthrie, be sure you cancel anything else you had going on.  Scott obviously is the man when it comes to ASP.Net.  Nikhil is so far ahead of the game, that he has to write his own tools to support his efforts. 
  • Astoria - This product hasn't gotten the coverage it deserves.  This project basically brings the power of Linq to your web services.  It's tied heavily to the Entity Framework (which has been delayed til some time in '08).  Nevertheless, this is going to be a huge game changer in it's own right, as it will further the concept of the programmable web.  If you get a chance to attend a talk by Pablo Castro, drop just about anything else.  This guy delivers a very animated, exciting, informative presentation.  Probably the best pure presenter at all of MIX07.  The guy clearly enjoys his work.
  • WCF - Communication Foundation is set to take a front row seat, as it is foundational for the products above.  My predicition is that this technology is going to be central to many of Microsoft's innovations going forward.  I just picked up this book:
  • Jasper - Honestly, I missed it if there was something at MIX07 on this, but I wish there had been.  As it was, I only barely caught the Astoria presentation.  This project is really more of VB.Net IronPython thing.  Apparently, it leverages some new dyncmic languages stuff.  Obviously, I'm weak in the area.  Hopefully I won't be for long.

So hopefully that helps.  I'll be blogging about some of the strengths and weaknesses I've noticed in these upcoming tools, and how you can start architecting for them immediately.

Sunday, April 22, 2007

So I'm beginning to look into the new c# language features coming with Orcas, and probably the simplest is Extension Methods.  Below is some code I have migrated to 3.0 to convert unix timestamps to proper DateTime objects. 

 
public static class MyExtensions
{
    private static DateTime _baseDate = new DateTime(1970, 1, 1);
    public static DateTime ConvertUnixTimestampToDateTime(
       this double secondsAfter1970)
    {
        if (secondsAfter1970 == double.NaN)
            throw new ArgumentOutOfRangeException(
                      "Number of seconds since Jan 1, 1970 required");
        return _baseDate.AddSeconds(secondsAfter1970);
    }
}

So what is going on here?  There are only 2 things to notice. 

  1. This is a static class, which means everything in the class must likewise be static.  I'll explain why this restriction exists shortly.
  2. The "this" in the method signature indicates that this method may be used to extend the double class. 

From there, you may simply call the method on any double value as if it had been there all along.

 

static void Main(string[] args)
{
    double oneWeek = 60 * 60 * 24 * 7;
    Console.WriteLine("Called as Extension Method: " +
        oneWeek.ConvertUnixTimestampToDateTime()
        .ToShortDateString());
    Console.WriteLine("Called as Static Method: " + 
        MyExtensions.ConvertUnixTimestampToDateTime(oneWeek)
        .ToShortDateString());
    Console.ReadLine();
}

The output:

Notice that I can still call this method as I would any other static method.  The only difference is that now I can use it from instances of the double class as well. 

So how is this functionality provided?  The compiler simply replaces your extension method invocation with the static method when it compiles your code.  As a result, there is no difference in how the two calls are made.

Also of note, is that you must create a using statement for your extensions class if it is located in a different namespace.  No surprise here, you have to follow the same rules that you would have used to call the static method in .net 2.0.

To be honest, I haven't quite decided what I think of extension methods just yet.  I think they'll be pretty benign, but a friend of mine who is a killer developer in his own right is concerned that the "this" keyword is a little too easy to miss.  I can certainly see his point.  Hopefully the way you organize these methods, or the static classes you enclose them with, will provide enough context.  Regardless, there's nothing earth shattering here, just some new syntactic sugar.

Friday, April 20, 2007

I've had a two unrelated events in the span of just 24 hours lead me to this minor rant regarding some common issues I've noticed in many technical articles / presentations.  It appears that when most authors write articles or presentations, they tend to:

  1. Focus on the features being taught in as much of a vacuum as possible. 
  2. Paint the technology in a glowing light. 

While I can understand the pedagogic (1), and psychological (2) reasons here, I believe that the ease and confidence with which the content is presented can inflict harm on our developer community. 

How?  Consider the reader's mindset.  First of all, they're likely to be implicitly swayed by the author's credentials due to the context of the situation.  It's a reputed web site, a developer conference, etc.  Second, the positive tone with which the content is presented leads the reader to assume that the author had an entirely positive experience with the technology.  This interpretation is further validated by the ease with which the author's straw man succumbs to the power of the new technology.

So off we readers go, secure in the knowledge that this is going to take care of all of our problems.  How often have I made this exact error, only to meet with disillusionment when I try to apply the solution to a REAL (even simple) business problem?  Sometimes, it is because the technology simply is not ready for prime time.  Often the technology is fine, but the article's simplistic problems simply don't illuminate many of the critical issues that you really need to understand in order to apply the technology effectively.

What can be done about this as an author / instructor?  Certainly, having been blogging for 1 week, I don't profess to have all of the answers here, but here's a few things I've noticed that seem to help:

  1. Choose your scope carefully.  If you are writing 1 article, choose a small topic you can really discuss thoroughly.  Don't try and cover everything.  If you really want to cover a large topic, you're going to have to break it out into multiple parts. 
  2. Chronicle your experience using the technology on a real application
  3. Share the gotchas you struggled with along the way, not just the successes.  What you found and solved could save many readers many hours of pain.
  4. Try to explain what's going on behind the scenes.  I don't mean you need to show me ILDasm output.  But, if I'm teaching ViewState, I want to make sure readers understand that it serializes ALL of the control state to a string that gets passed BACK AND FORTH on EVERY PAGE HIT, not just the form data itself.  I want to highlight specific situations in which this could be a problem, like in a GridView.

As a reader, you may want to consider:

  1. Buying a book on the topic.  They often times do a more thorough job of explaining what's really going on.  Around 2002, most of my books were all red (Wrox).  Today, I've found that most of my purchases are yellow and black.  (APress).  As a general rule, the books on narrower topics are a better bet, because they provide more complete coverage than the broad "ASP.Net", or "C#" books.
  2. Design Patterns.  Learn 'em, live 'em, love 'em.  This will improve every aspect of your programming life, and you'll be more likely to see the gaps in an article intuitively.

Thursday, April 19, 2007

Update: So it appears that the Nike McFLY's I linked to were a hoax.  Still funny though.  Thanks Michael for the heads up.

So I attended a presentation on CardSpace last night, easily the least publicized new feature of .net 3.0  The presentation was well done, and I certainly gained what I felt was a good insight into the how and the why, but I couldn't help but be struck by how 1999 it felt from an end user perspective.

I'm not going to even summarize the technology as it pertains to web site operators, merchants, etc.  That is all extremely high level security work that I am simply not qualified to evaluate. 

It's CardSpace (the client-side piece) that kills me.  I'm utterly mystified by two key design decisions that were made that seem to make the product critically inferior to existing solutions.

Identity Tied To A single?! Computer

2005-2006 - Applications begin to move online.  Things like calendaring, document management, word processing, bookmarks etc., all start appearing online in a sophisticated, finally useful way.

2007 - Identity Aggregation and Mashups  - We're increasingly seeing an open environment where your identity in one location can be mapped to your identity in another.  Host your flickr pictures on your blog, your YouTube vids on your social network page, etc. 

Later in 2007...  (I think)  How can my swanky new identity remain LOCKED ON A SINGLE COMPUTER?  (Your files are encrypted in a manner that inextricably ties them to a single machine)  At best, you can apparently call a utility that will manually export your data, and then you reimport it on other machines.  Why on earth would I need to create a NEW IDENTITY for DIFFERENT DEVICES?!  What I want is an automatic syncing mechanism that keeps everything about me wherever I am, using whatever device I'm currently using.

No Benefit Today

I've been using Vista for almost 2 months now, and I've yet to come across any site using CardSpace.  However, if you've created this single repository of your identity information on your machine, why can't you use it to log in to existing sites and network shares today?  It seems like CardSpace could provide this functionality, since it already knows about me, and interacts with both browsers? 

A Solution Available Today

2 very slick applications already fill these two gaps, plus a few others.

http://www.roboform.com

This is a password management program that I've used for several years now.  What does it do and how does it work?  Here's a copy and paste from the web site:

  • Memorizes your passwords and Logs You In automatically.
  • Fills long registration and checkout forms with one click.
  • Encrypts your passwords to achieve complete security.
  • Generates random passwords that hackers cannot guess.
  • Fights Phishing by filling passwords only on matching web sites.
  • Defeats Keyloggers by not using keyboard to type passwords.
  • Backs up your passwords, Copies them between computers.
  • Synchronizes passwords between computers using GoodSync.
  • Searches for keywords in your passwords, notes and Internet.
  • Portable: RoboForm2Go runs from USB key, no install needed.
  • PDA-friendly: sync your passwords to Pocket PC and Palm.
  • Neutral: works with Internet Explorer, AOL/MSN, Firefox.
  • IE 7 and Vista are now supported.

I would recommend you let roboform generate crazy passwords for you.  If you use the same username/password over and over, a hack into one site can easily compromise your security on all of your others.  I generated this: E9x$fKpoU41TVQJwvkHq with 1 click. 

The only shortcoming is that you have to manually sync your passwords.  So if you log on to your bank, and let RoboForm generate a killer password for you, but then forget to sync your files, you can be in some pain when you try and 'recollect' this monstrosity on another machine.

http://www.foldershare.com

This is a free app, courtesy of the Microsoft small company acquisitions team, that you can set up to automatically keep all of your files in sync via the internet. You HAVE TO CHECK THIS OUT.  Here's a list of features:

  1. Automatically keep your files synced across your windows machines.  You configure it to select the directories to sync, and that's it.  Anytime you're online, it figures out what has changed on all connected machines, and responds appropriately.  I keep a lot of personal files, including my Roboform data synced in this manner.
  2. On a public machine, or want to access files that aren't being synced?  Log in, and you can either browse any machine online via the web interface, or it will even tie in to whatever desktop search application you're using (Live Desktop, Google Desktop) and let you search that way.  This has saved me several times.
  3. Have you read security / backup advice that goes something like: "Periodically burnd DVD's of your data, and mail them to your family"?  Do you do it?  Foldershare.  Remote backups.  Done.

Few other tidbits. 

If you're considering springing for the USB drive version of RoboForm, and are of the personal opinion that lanyards do little to increase your sex appeal, consider this drive that will fit in your wallet:

2Gb Super thin USB memory (Currently $23 + $5 Shipping)

And finally, I use roboform to store the CD Keys for all of my software, so I can ditch the jewel cases, or easily lost slips of paper.

Wednesday, April 18, 2007

The last two times I've been on the job market, I've been asked a fair number of logic puzzles during the interviews.  There are contrasting opinions on whether or not they give accurate insight into the quality of a candidate, but they're easily among the most stressful tasks to be presented with.  If nothing else, they definitely test how easy it is to rattle a candidate.  It's very tempting to want to try to fill the silence as you toil, or not waste the interviewer's time and just give up.  Neither mindset is a productive one.  What I do, is think out loud, and where applicable, diagram the situation.  This helps me in a few ways:

  1. It helps me understand the problem.  Have you ever noticed that explaining a problem to someone often helps you solve it yourself?  Vocalizing your thought process slows you down, and often times forces you to notice something that your mind was glossing over when you were just thinking to yourself. 
  2. It gives the interviewer some insight into your thought process, which is really the point.  Even if you don't get the answer, you can get 'partial credit' for the insights you do identify.
  3. It helps fill a little of the dead silence, which slows the impending dread that otherwise begins building immediately. 

At what point should you cry uncle?  Probably much later than you think.  Why?

  1. It hasn't been as long as it feels.  Time seems to speed up in these situations.  5 minutes will probably feel like an hour
  2. The interviewer probably wants to know how tenacious you are.  Is this person going to just give up when I give them a problem on the job?
  3. The interviewer probably isn't as bored as you think.  Do you remember the last time you told one of these?  It was kind of fun watching them struggle to puzzle it out, probably going through the same ideas you had. 

Ok, enough of my interviewing perspectives.  Here's the first puzzle.  I'll post more as time permits.

Puzzle 1 - Visual, Logical

Question

You have 3 points, A, B, and C in the shape of a triangle on a piece of paper.  To begin, choose any location on the paper, and place a dot there.  From there on, you repeat the following pattern.

  1. At random, choose point A, B, or C
  2. Place a new point midway between the last dot you placed, and the point you selected.

The question is, after you do this a few thousand times, what will your paper look like? 

Answer

I don't want to post the image inline.  It's too hard to avert your eyes.  here's a link to an image: Answer

This problem lends itself to a programmatic solution.  When I was asked this question, the stakes were high (my instructor was giving away gmail invites, which were hard to come by at the time) so I wrote a quick and dirty winform app that shows the answer.  You can download a programmatic solution here: Answer (The code, and a .net 2.0 winform executable are included)