Hugoware

The product of a web developer with a little too much caffeine

Archive for October 2009

Render Partial — But With Arguments!

with 6 comments

One thing that I haven’t really liked about MVC was using RenderPartial instead of an actual UserControl. Its not that you can’t use them but that there is a disconnect between the control state and the render phase which makes it pretty much impossible to really work with them inline.

I say ‘pretty much’ because I’ve done a lot of work to let people use WebControls inline with MVC code.

Using the existing RenderPartial requires that you pass in the name of the UserControl that you want to render. You can also provide an object argument that is passed in as the ‘Model’ for the partial view. The UserControl can access the passed in object via the ‘Model’ property — even cast it into the correct type directly.

Personally, I use a lot of Models in my projects now. I used to suggest that you pass around objects using a wrapper for anonymous types but I’ve found that if you plan to move it from a Controller to a View or from a View to a UserControl then you ought to define a class.

Using RenderPartial Without Really Using It

So instead of calling RenderPartial directly, what about using the Model that we have in place to make the call for us. Not only that, we can even define our class to accept arguments directly. Here is an example of a simple dialog box…

using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace MvcTest.Models {

    //simple dialog box example
    public class DialogBox {

        //rendering the dialog box
        public static void Render(ViewPage insideView, string title, string message) {
            insideView.Html.RenderPartial(
                "DialogBox",
                new DialogBox() {
                    Title = title,
                    Message = message
                });
        }

        //Properties
        public string Title { get; set; }
        public string Message { get; set; }

    }

}

Then we could simply use our code inline by calling the DialogBox.Render instead of the RenderPartial method.

<% DialogBox.Render(this, "My Title", "This is the message to display."); %>

You could also use an approach like this to make creating UserControl templates easier.

using System;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace MvcTest.Models {

    //simple product list example
    public class ProductListing {

        //rendering the list of controls
        public static void Render(ViewPage insideView, List<Product>, Action<Product> renderRow) {
            insideView.Html.RenderPartial(
                "ProductListing",
                new DialogBox() {
                    AllProducts = products,
                    RenderRow = renderRow
                });
        }

        //Properties
        public List<Product> AllProducts { get; set; }
        public Action<Product> RenderRow { get; set; }

    }

}

And then you could call your method inline and provide the template action.

[View.aspx]

<!-- snip -->
<% DialogBox.Render(
         this,
         products,
         (item) => { %><li><% =item.Name %></li><% }
         ); %>
<!-- snip -->

[UserControl.ascx]

<%@ Control Language="C#" 
    Inherits="System.Web.Mvc.ViewUserControl<MvcTest.Models.ProductListing>" %>

<h3>Featured Products</h3>
<ul>
<% 
    foreach (Product item in this.Model.AllProducts) {
        this.Model.RenderRow(item);
    } 
%>
</ul>

The above example is probably over simplified but you probably get the idea. This may not be a big gain, but if you plan to use the same UserControl often, then this might help simplify the call.

Written by hugoware

October 26, 2009 at 11:38 pm

Spelling It Out With Booleans

with 4 comments

Code complexity has been a big issue for me lately. I’ve been realizing that the quality of my code has degraded over the years to the point that I’m finding I cram large chunks of code into a vaguely named method like Load() or Render(). It wasn’t until I got an assistant and I likened programming to ‘painting by number’ that I realized that I wasn’t following my own instructions anymore.

It wasn’t that I was intentionally writing complex code but rather that a large complex function wasn’t hard to read anymore — my definition of complexity has changed.

The last time that I discussed code complexity I explained that writing short, clear methods was an ideal way to decrease code complexity. This post continues the discussion by looking at using booleans to improve the readability of code.

Clarity With Booleans

Maybe you’ve seen a snippet of code like this before…

if (value % 2 == 0) { 
    //do something
}
else {
    //do something else
}

Most programmers are going to immediately recognize what this code is going to do — but imagine for a second that you don’t know what that code does. How is a less seasoned programmer going to have any clue what just happened there? Try Googling ‘value % 2 == 0’? I don’t think that is going to work out so well.

This is a good example where a boolean can be used to create clarity in a program. A boolean is used to determine the flow of a program — so why not use well named booleans to further clarify your intent?

bool isEvenNumber = (value % 2 == 0);
if (isEvenNumber) { 
    //do something
}
else {
    //do something else
}

This is a simple example but it applies everywhere. What stops you from spelling it out with a boolean?

Describe Intent Without A Comment

MVC is a good example of where well named booleans can improve the readability of code. How much harder is the first snippet to read compared to the second.

Logic Performed Inline

<div class="<% if (allItems.IndexOf(entry) % 2 == 0) { %>alt-item %<% } %><% if (entry.DatePosted.Date < DateTime.Now.Date.AddDays(-7)) { %>old-post<% } %>" >
<div class="subject" ><% =entry.Subject %></div>
<% if (string.IsNullOrEmpty((entry.Location ?? string.Empty).Trim())) { %><div class="location" ><% =entry.Location %><% } %>
<% if (string.IsNullOrEmpty((entry.Description ?? string.Empty).Trim())) { %><div class="desc" ><% =entry.Description%><% } %>
</div>

Logic Performed In Advance

<%
    bool isEvenItem = (allItems.IndexOf(entry) % 2 == 0);
    bool olderEntry = (entry.DatePosted.Date < DateTime.Now.Date.AddDays(-7)); 
    bool hasLocation = (string.IsNullOrEmpty((entry.Location ?? string.Empty).Trim()));
    bool hasDescription = (string.IsNullOrEmpty((entry.Description ?? string.Empty).Trim()));
%>

<div class="<% if (isEvenItem) { %>alt-item %<% } %><% if (olderEntry) { %>old-post<% } %>" >
<div class="subject" ><% =entry.Subject %></div>
<% if (hasLocation) { %><div class="location" ><% =entry.Location %><% } %>
<% if (hasDescription) { %><div class="desc" ><% =entry.Description%><% } %>
</div>

Snippet one is much shorter than snippet two — but does that really make it better? Or less complex?

You could argue that the logic shouldn’t be inline with MVC to begin with and you’d be correct. Instead those same comparisons would be well named boolean properties attached to the the model being used — which is exactly what I’m suggesting here.

It doesn’t matter where they are but using well-named booleans can improve and clarify the flow of logic in your application.

Written by hugoware

October 19, 2009 at 8:30 pm

MonoDevelop – Pure Awesome!

with 10 comments

I’ve always been envious of Java developers since they could essentially write their code and then run it on any device. It might not be a perfect translation each time, but its still much better than what a pure Windows dev could put together.

I recently started doing some iPhone development and decided to investigate MonoTouch. I downloaded the a copy of MonoDevelop (which is still in beta at this time) and installed it. After starting up the application I was shocked to see what came up…


Picture 4

Uh… what? Wow! Is this for real? This really looks pretty nice!

Not What You’d Expect

When you first mess with the IDE you’ll be pleased to see it works just like you’d hope. Intellisense is quick and accurate; Syntax highlighting works as you would expect; Believe me when I say, it is just that impressive.

But having a pretty IDE is nice but it doesn’t mean anything if the language doesn’t work the way you need it to. Honestly, I figured it had to be some sort of watered-down version of the same .NET C# language that I work with every day. The first thing I did was hack out something that was certain to fail… but…


Picture 5

Incredible! Granted this isn’t that hard of code, who would have thought so much was already available!

And that isn’t all – You have LINQ support, Generics… heck, even ASP.NET MVC is already packed in here!!

Not only that, but check out this “little” dialog. I’m sure it doesn’t mean much… 🙂


Picture 6

If I’m reading this correctly, we can import existing .NET assemblies – How awesome would that be! (but I’m just guessing here… I’ll test it later…)

See It To Believe It

Mono and MonoDevelop are going to open up a lot of existing C#/Windows devs to an entirely new world. Don’t just take my word for it though — try it out for yourself. It doesn’t take a lot of effort, download a copy of VirtualBox and setup a virtual instance of another OS and prepare to be impressed.

Great job Mono Team! I think the benefits of .NET cross-platform development are yet to be realized!

Written by hugoware

October 11, 2009 at 9:39 pm

MVC Post Round-Up

with one comment

I thought I’d bring back a few of my previous ASP.NET MVC posts just in case they were missed before.

Include Stylesheets and Scripts To Your Header With MVC

A while back I wanted to include some stylesheets in my header of a MVC View, but I wanted to do it from a WebControl. Since you’re using inline code the standard Page properties like “header” aren’t going to do you much good (since you’re already in the render event). Fortunately, with a little magic with the HttpContext.Current.Response.Filter stream, you can make all the changes you need before the content is sent to the user.

Using WebControls With Inline MVC

Just for fun I wanted to see if it was possible to actually create WebControls that worked inline with MVC Views. It took a little bit of work to do (it actually ended up spanning 4 different posts) but it finally came together fairly well.

This series was actually inspired at the idea of just rendering controls inline, without postbacks.

Combining MVC with Existing Web Services

I like the idea behind WebServices, but the hassle of creating SOAP envelopes and modifying headers makes them difficult to use in places other than .NET applications. Being able to create a MVC Controller that automatically maps to an existing WebService would make it easier to use the same functionality, but all from a standard HTTP call.

Anonymous Types (Sorta MVC related…)

If you’ve worked with Anonymous Types in MVC then you’ve probably noticed that you can’t just pass them into your view and expect them to be available. Personally, recommend creating a unique class for anything that you’re passing into a view – but if you’re looking for something that you can use in a hurry, then this Anonymous Type wrapper class might come in handy. Just pass in an anonymous type and the class does the rest!

You can change values, assign new methods — basically you have a little bit of dynamic programming goodness all wrapped into a single .NET class!

Written by hugoware

October 5, 2009 at 7:30 pm

Outlook Web Access via iPhone

with 14 comments

You may have seen my post a little while back about how I was starting to do some iPhone development for my job. For the most part the app is nothing more than a nice pretty front end to a handful of Web Services (hint: last blog post was along the same lines)

In any case, I’d rather my first attempt at iPhone development be a throw away project since I’m going to probably going to have to start over several times.

Learning Through Development

Whenever I offer up advice to a new programmer on what is the best way to learn programming I always say – “write a program that does something you want — you’ll learn a lot along the way and have motivation to finish it.”. Learning Objective-C was no exception for me.

Even though we use Exchange for our e-mail server at work, we don’t have the “Active Sync” enabled so you can’t link up with the iPhone through the built in e-mail application. So, instead, I decided to go a different route — use the existing Outlook Web Access and parse the HTML.


Picture 1

So with a couple of nice Regular Expressions and some HTTP calls we have a nice clean display of all the e-mails in my mailbox. Yep, that’s right — screen scraping via HTML… a little cheesy, but not bad since it works even if Exchange isn’t configured to allow it!

This was a perfect example of writing an application that met my need and allowed me to learn a new language at the same time… of course I’m not suggesting that I’m an Objective C expert or anything but at least now I can ditch my BlackBerry! 🙂

Hey, Who Puked On My Screen… Oh Wait, That’s Objective C

I’m definitely a spoiled programmer. Using .NET and C#/VB has definitely shielded me from some ugly languages out there. Objective-C is the kind of stuff that makes babies cry.

Developing iPhone is WAY different that anything that you have ever done in .NET. You’re adding all sorts of weird things like IBOutlet and IBAction so you can link them around all over the place — it is definitely a new experience. I’m going to have to write a ‘C# Developers Guide To iPhone Development’ to maybe save some other poor guy a lot of grief.

Still a .NET Guy

Getting into new languages and technologies on different platforms is always a good idea. You gain added perspective while increasing your skill sets (not to mention you look better on paper for your next job). Even if you don’t want to buy a Mac and play with the iPhone you can always tinker with a myriad of other languages on any number of free operating systems — Go do it!!

Don’t think that I’m converting – If anything using a Mac this much has solidified why I’m still die-hard Windows/ASP.NET/PC…

…But then again… MonoDevelop for Mac is looking kinda slick…

Written by hugoware

October 1, 2009 at 7:54 pm