Uncategorized

My First Real ASP.NET Site

Posted in Uncategorized on April 12th, 2008 by Brian – 7 Comments

I’m fortunate enough to be one of the first developers at my current employer to create a site using ASP.NET.  Currently, almost all our internet and intranet applications are built with classic ASP.  Yeah, I know.  Early adopters we ain’t.  As cool as it is that I’m getting to blaze this trail, it also means that there’s little guidance to be had, and no internal examples to look at.  Even the guys I usually go to for advice at work (Kerry Jenkins and David Mohundro) haven’t used ASP.NET that much.

Right now, I’m still struggling to come up with an architecture that I think will be clean, but will also be understandable by people that come along behind me.  I know this problem has been solved a bazillion times before, but I’ve found it a bit hard to find some examples that are close enough to real-world complexity.  I took a look at Code Camp Server, but it uses NHibernate, which I don’t think is an option for us.  Using open-source software to build applications is viewed with more than a little apprehension by management.  Their reasoning is that if something goes wrong with the software, no one has a responsibility to offer us support.  I think that hinders us in a lot of ways, but that’s a topic for another post. ;-)

So, lacking any good examples, I came up with something myself.  To illustrate, I’ll use an example scenario:  creating a new user account.  I’m going to simplify it and just talk about the architecturally relevant parts.  (I’m sure nobody cares what my CSS looks like.) 

The solution has four main projects:

  • Web (Controls and aspx’s)
  • BusinessLogicLayer (so there’s as little code in the aspx.vb’s as possible)
  • DataAccessLayer (DB2 Database stuff)
  • ObjectModel (DTOs and stuff)

So, say I have a Register.aspx that looks like this:


   
       
        Please choose a user name and password:

        User Name:
       

        Password:
       

        Confirm Password:
       
       
                    onclick=”submitButton_Click” />
       
   

Standard stuff.  One thing that gave me a bit of trouble was how to get error messages back to the UI.  I toyed with the idea of having something named Context that would contain both the object the UI needed, plus messages about any errors that happened while performing the request.  I eventually rejected that in favor of having my pages implement an interface like this:

    public interface IView
    {
        string ErrorMessage { set; }
    }

So my business logic services can take an IView in their constructors, then set the ErrorMessage property when it encounters an error.  So I end up with something like this:

public partial class _Default : System.Web.UI.Page, IView
    {
        WebUserService _userSvc;

        protected void Page_Load(object sender, EventArgs e)
        {
            _userSvc = new WebUserService(this);
        }

        protected void submitButton_Click(object sender, EventArgs e)
        {
            WebUser user = _userSvc.CreateNewWebUser(userNameTextBox.Text, passwordTextBox.Text);

            if (user != null)
            {
                FormsAuthentication.SetAuthCookie(user.UserName, false);
                Response.Redirect(“Home.aspx”);
            }
        }

        #region IView Members

        public string ErrorMessage
        {
            set
            {
                serverValidator.ErrorMessage = value;
                serverValidator.IsValid = false;
            }
        }

        #endregion

}

public class WebUserService
    {
        private IView _view;

        public WebUserService(IView view)
        {
            _view = view;
        }

        public WebUser CreateNewWebUser(string userName, string password)
        {
            WebUserRepository rep = new WebUserRepository();
            WebUser user = null;

            if (rep.GetWebUserByUserName(userName) == null)
            {
                user = rep.CreateNewWebUser(userName, password);
            }
            else
            {
                _view.ErrorMessage = “That username is not available.  Please choose a different one.”;
            }

            return user;
        }
    }

public class WebUser
    {
        public string UserName { get; set; }
    }

Another thing I had a bit of trouble with was deciding where to check for things like duplicates in the database.  I thought that if I did most of that in the data access layer, I’d have the same problem communicating error messages back to the business logic layer that I did to the UI.  So, I decided to try to make the data access layer methods as granular as possible so I could do all that kind of validation in the business logic layer.  It’s more chatty than I’d like, but I think it will work for me, since we really don’t have any logic in the database.  (We don’t use stored procs or anything, because higher-ups don’t want any logic in the DB). 

I think this setup ought to work for most cases, but I don’t really have enough experience to know if I’m on the right track here.  If someone with more ASP.NET experience than me has any suggestions, I’m wide open.  I’ll post more of my experiences as I go along.

More Adventures with Witty

Posted in Uncategorized on April 4th, 2008 by Brian – 5 Comments

As you may have noticed, I haven’t been keeping up with my desired posting rate lately.  That’s mostly because I’ve been spending most of my outside-of-work “geek time” working on Witty, an open source Twitter client written in C# using WPF.  After my positive experience building in proxy support, I decided to implement another feature that I particularly wanted to see, namely “toast” popups.  (You know, those little mini windows that show up at the bottom right of your screen when you get a message in some IM clients.)

This enhancement was already posted as an issue on Witty’s issue board, so I knew I wasn’t off base thinking it was missing.  The person who originally asked for the enhancement suggested that we send messages using Snarl, an application aimed at recreating Growl on the Mac, to minimize the additional code needed to achieve the toast functionality.  So I visited the site, looked at the API, and set about trying to send Snarl messages from a C# program.

Even though the site listed C# as one of the supported environments, it turned out that the only semi-useful library available was unmanaged C++.  “No problem,” I thought.  All Snarl requires that you do is send a Windows message to the Snarl application, so I figured that I could translate the needed Win32 calls by looking at pinvoke.net (a wonderful resource for Win32 interop programming, btw).

I was half right, I suppose.  The SendMessage call was easy enough to duplicate, but the kicker was the data structure I needed to pass to the Snarl application.  As I would soon discover, even though the type names in C++ and C# are very similar, they mean different things behind the scenes. 

For example, a “long” that was part of the data structure in C++ is actually only 32 bits in size, whereas a “long” in C# is 64 bits.  Those were easy enough to fix, since C#’s “int” type is the appropriate length.  The character arrays were a bit trickier.  First of all, a “char” in C++ is one byte, while in C# it is 2 bytes.  You can get around that by changing the char arrays to byte arrays.  But the thing is, arrays in .NET are a totally different animal than they are in C++.  In order to use fixed-length arrays like Snarl wanted I had to use the “fixed” keyword, like this:

public fixed byte text[1024];

The problem with that is that in order to get it to compile, you have to mark the struct using it with the keyword “unsafe.”  Yuck, that doesn’t sound good, does it?  And it’s not.  When you do things like that, you open yourself up to all kinds of mess that you thought you left behind when you started writing .NET code.  Not fun.

But, hey, it got messages to from Witty to Snarl, so I submitted a patch.  The guys were happy to see progress made, but the unsafe marker made everybody nervous.  Plus, it meant relying on an outside application for notifications.  So, I got to work doing what I probably should have in the first place:  creating integrated popups in WPF.

Meanwhile, Michael Letterle got wind of the Snarl integration that we were trying to do, and fixed those notifications faster that should be humanly possible.  The trick was a couple of attributes I’d never heard of before:  [StructLayout] and [MarshalAs].  The structure ended up looking like this:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    struct SNARLSTRUCT
    {
        public int cmd;
        public int id;
        public int timeout;
        public int lngData2;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = SnarlInterface.SNARL_STRING_LENGTH)]
        public char[] title;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = SnarlInterface.SNARL_STRING_LENGTH)]
        public char[] text;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = SnarlInterface.SNARL_STRING_LENGTH)]
        public char[] icon;
    };

Normally, the CLR will store a structure’s component parts wherever it feels like, so the parts of the struct could be separated.  In a managed world, this doesn’t bother us, we can always get back to the data if we need it.  But if we need to pass this struct to unmanaged code, we have to tell the CLR specifically to keep all the parts in one place, which we can do by specifying the [StructLayout] attribute.  I’m a little fuzzier about what the [MarshalAs] attribute does, but it’s pretty obvious that it’s telling the CLR how this managed data needs to be translated when passed to unmanaged code, and it lets us specify a length for the arrays.

Back in WPF land, I got to play around with a bunch of neat stuff.  Even just copying the look and feel of the login window, I started to get a feel for XAML, at least in some of its simper forms.  I thought that the way it defines animations was particularly interesting.  To do a fade-out for the popups, I used something like this:


     
       
       
       
     

   

I just think it’s cool that you can declaratively define an animation sequence.  It just seems a lot more self-contained and comprehendible when it’s laid out like this, as opposed to a chunk of imperative code.  It’s hard to define why it feels better, but it just does.  I think that’s what they call getting the zen of a particular technology, and I think I may have gotten a whiff of the zen of WPF here.  I’m hopeful that we’ll be able to start using WPF in my workplace within the next couple of years.  We’ve still got some Win2k machines out in the field, so they will have to be phased out before that can happen.  That, and they’ll have to spring for VS 2008 for the developers ;-) .

I’ve had a lot of fun working on this, but after this feature is declared finished, I think I ought to work on a bug fix next.  One of the things I’ve heard about OS projects is that most people just want to work on new features, and it’s hard to get people to fix bugs.  I want to be more responsible than that, so I think I’ll take one (or a few) for the team and do something that may not be quite as fun next time.

Keep checking for new releases, Witty is getting better all the time!

My First Contribution to Open Source

Posted in Uncategorized on March 21st, 2008 by Brian – 2 Comments

As you probably know from previous posts, I am a recent convert to Twitterism.  I totally dig the dirt simple minimalist web UI that the service provides, but I noticed that several of the people I was following were using some other kind of client to tweet with.  So I checked out the one I saw The Elder using, called Witty

Well, it turns out that he helped write the thing, along with Jon Galloway, project owner Alan Le, and several others.  It was a nice piece of WPF-y eye candy, and worked perfectly, too.  At least, as long as you weren’t behind a proxyI’ve mentioned my utter loathing of my employer’s proxy before (and in association with Twitter), and this just added insult to injury.  So, since it was open source, I decided to make a patch to add proxy support for Witty.

It took me most of an afternoon, but I’m sure others could have done it much more quickly.  The real meat of the changes were pretty darn simple, since the .NET API for performing HTTP requests allows a proxy configuration as an optional parameter.  But I’d never used TortoiseSVN before (a popular application used to interact with a Subversion source control repository), I’d never written an angle bracket of XAML, and I was looking at the codebase for the first time, so I cut myself some slack.  ;-)

So, by that afternoon, I had the changes working.  A few days later, after getting in contact with Alan and him patiently explaining the proper way to post changes (there’s a “Create Patch” option in TortoiseSVN), I submitted my changes for review.  Frankly, having never contributed to an open source project before, and coming from a development shop that is really just getting started in .NET (and thusly hasn’t provided a whole lot of guidance on good design), I was afraid my code wasn’t going to be up to snuff.  However, Alan contacted me later that day to tell me he thought my changes looked solid and that he had merged them with lots of other improvements contributors had made to the project.  That evening, he posted Witty version 0.1.7 Beta 1 to it’s Google Code page.  Code I wrote was officially available to the whole world!

It was a lot of fun working on the enhancement, and rewarding to think that I may have helped a person or two out.  There’s a lot still to work on, though.  For example, even though you can receive tweets through an authenticated proxy on Witty now, the avatar images don’t show up if you’ve got that same proxy configuration on IE.  That’s because the XAML elements used for the avatar images use the real twitter URLs as their source property, so the application uses IE’s configuration when going to get those images.  Since there’s no way to authenticate when the app makes those requests, you never get the images back. 

Anyway, such is the life of an OS app.  Always more to do.  I highly encourage you to find an open source project you like and take a crack at adding a feature or fixing a bug.  I had a great time doing it, and I plan to continue.  Not only is it rewarding to help someone out, but it also exposes you to others’ code, which can only help you improve your own style and technical chops. 

P.S. – Don’t forget to check out Witty:-)

P.P.S. – Note to other people at the company I work for: this doesn’t mean Witty works for us now.  The net nanny still blocks any web requests to a Twitter URL, so we’re pretty much out of luck. :-/

Excellent ALT.NET Podcast

Posted in Uncategorized on March 14th, 2008 by Brian – Be the first to comment

Today’s Hanselminutes episode has Scott interviewing David Laribee, the guy who coined the name “ALT.NET.”  I think he went a long way toward explaining the motivations of the movement, as well as its position regarding Microsoft.  Several things he said actually surprised me. 

First, he said that an Agile approach may not be appropriate for all scenarios (specifically very large teams)…  Wha?  You mean Agile is not the panacea for all your development ills?  Sarcasm aside, even though many knowledgeable developers believe that Agile environments can benefit most teams (and I have neither the experience nor the will to contradict them), it’s good to hear such a non-dogmatic statement coming from an ALT.NET leader.

Also, in the same vein, he said that waterfall might not be bad in all cases, and that he had been a part of several successful waterfall-style projects.  Now that really surprised me.  Even mentioning the waterfall approach to building systems has been kind of a cue to pounce on someone (as in the case of Frans Bouma), so in this case as well, it’s refreshing to hear what seems to be a moderate voice.

It’s possible that David held back a bit during the interview; I really don’t know, since I haven’t read much of his blog.  But it could also be that I have committed the cardinal sin of letting the commenters on ALT.NET blogs color my perception of what the actual leaders of the movement believe.  All I know for sure is that I’ve got a new entry on my blogroll, and I feel like I really do need to stay tuned in to this influential segment of the software development community.

Ambivalence and ALT.NET

Posted in Uncategorized on March 11th, 2008 by Brian – 4 Comments

It pains me to say it, but ever since I tuned in to the ALT.NET movement, it’s kind of rubbed me the wrong way.  The content of the posts that I read are generally pretty good (and at times great), but what gets to me is the overall negative tone of the community.  Rather than just trying to get the word out about the cool open source (or just non-Microsoft) technologies that are out there, and the Agile methods and practices that can make your life easier, the prevailing message seems to be, “If you’re not already doing this, you’re a sub-par developer.”

I understand the need for a foil for Microsoft, the need for a periodic reminder that not everything that comes out of Redmond is gold.  But I think it can be accomplished in a more positive way.  In an email conversation with Jeffrey Palermo, I asserted that what we need are “Agile Evangelists,” missionaries into the land of Mort that can spread the word about the good news of a more Agile approach to software development.  But what we seem to get most of the time are complaints that Microsoft isn’t doing enough, and that bosses, co-workers, or fellow .NET community members are too dull to realize the benefits of what they’re touting.

You can see this dynamic in action if you watch the video of ScottGu presenting the very first peek at ASP.NET MVC to the ALT.NET conference in Austin.  For the most part, things go fine, but there a few tense moments where people asking questions are downright belligerent.  Since the MVC framework is a genuine (IMHO) attempt by Microsoft to reach out to this community, you’d think they would be a bit more cordial.

That said, I think their message is a sound one.  Most developers that I know don’t devote a lot of extra time to learning new technologies, and thusly have a limited perspective.  That’s not intended as an insult.  These guys program for 9 hours a day, there’s no reason to expect them to take more time away from their friends and families to tinker with the newest language they heard about on Twitter.  Those of us that feel compelled to do so, however, (I think) have a responsibility to at least make them aware that there are other things out there.  If the only exposure they have to this outside community is a blog post they stumble upon that rants for hundreds of words about how Microsoft will never release anything worth using and that all developers who don’t use technology X are just wasting their time, how likely do you think they’ll be to try technology X?  Ever? 

This isn’t in any way intended to be some kind of personal attack on those who actively participate in this sub-culture.  I think the ALT.NETers have a lot of good things to say, and a lot that they can teach the larger .NET community.  If they can temper their message a bit, I think they will reach enough of us that I think of as the “tuned-in small names” that there can be some progress in exposing Agile practices and open-source tools to the masses.

Inaugural Fort Smith .NET User Group Meeting

Posted in Uncategorized on March 6th, 2008 by Brian – Be the first to comment

Thanks to the hard work of several people in the Fort Smith area, our first DNUG meeting was a great success.  Raymond Lewallen spoke on Behavior Driven Development, a subject I had been curious about.  I’d heard that it was the right way to do Test Driven Development, but little other than that.  Ray did a great job explaining the gist of it.  Since Mo has already listed some great resources on learning about BDD, I’m just going to highlight some of the things that were interesting to me.

First of all, the way Ray named his test fixtures and tests jumped out at me.  Normally in TDD (in my limited experience), you’d have a fixture named AccountTests to test an Account object, and tests named something like New_balance_should_reflect_old_balance_plus_deposit_amount.  Rather than doing that, Ray’s fixture would be named When_depositing_money_into_an_account and the test would be named New_balance_should_reflect_old_balance_plus_deposit_amount.  The difference there is that the context of the tests is defined by the fixture name, and the test describes the event and the expectation of the results of that event.  I think that’s a much better way to name your fixtures, and better leads you to what tests you need to write.  Ray said that that was one of the main goals of BDD, not just writing tests, but writing the right tests.

Also, he demonstrated a project he worked on called Spec Unit, which makes using assertions in NUnit easier.  Normally, you’d write an assertion in NUnit like this: 

Assert.AreEqual(250.00, account.Balance);

By using extension methods, Spec Unit allows you to write this instead:

account.Balance.ShouldEqual(250.00);

That reads a whole lot more like English, and thus makes it easier to understand what the test is doing (which is another goal of BDD).  It also includes some stuff to let you run some reports on your tests that help you track your development.  Definitely worth checking out if you’re writing tests in NUnit.

I’m afraid a subject this in-depth may have scared off some of the people attending the meeting who are fairly new to .NET, and may have not ever seen unit testing frameworks before.  I think the meeting on March 31st may be a little more accessible.  Chris Koenig will be coming to speak on Silverlight, which ought to be cool.  I’m hoping that he shows us some Silverlight 2.0 code, since that’s what’s really interesting to me.  If you’re in the area, please come to the meeting!  And stay tuned to the user group’s site for information on future events.

So There! :-P

Posted in Uncategorized on March 4th, 2008 by Brian – Be the first to comment

What do you do when the Twitter site gets blocked?  Host a Twitter client yourself, of course!  Since Twitter exposes a public API (http://groups.google.com/group/twitter-development-talk/web/api-documentation), it’s very easy to set something up that gets your personal timeline and lets you update your own status.  Twitteroo makes it even easier to do from a .NET environment; many thanks to the guys at RareEdge for providing a library that abstracts away all of the WebRequest stuff. 

What I have is pretty ugly-looking right now, since I wasn’t very worried about how it looked, just that it worked.  I’m not displaying people’s pictures, since the images tags would result in requests to the Twitter server from the end-user’s browser and would get blocked.  I’ll make it work eventually, but it’ll require some gymnastics.  Something like having the aspx page do a web request for the image, save the bytes off in some temp directory, then change the tag to point to the temp directory.  That, plus a little bit of styling, and it should be passable. 

Feel free to use it as-is here.   You’ll just have to trust that I’m not stealing your username and password and using it to post embarrassing messages to your account.  ;-P  Also, be forewarned, it’s not the most secure thing in the world.  Just to get it to work quickly, I save off the password to a session variable, since I have to have it to pass to the Twitter API. 

I’m becoming a big fan of these open web APIs and services.  I’m thinking of using the Virtual Earth API in the site that I’m currently developing.  It fits the problem well, and it’s just so darn easy to use.  Conveniently, there’s also a DNRTV episode this week about using it in ASP.NET that I’m looking forward to watching tomorrow. 

Hooray for a web-enabled world!

Net-Nannies Suck

Posted in Uncategorized on February 27th, 2008 by Brian – 1 Comment

So I finally signed up for Twitter, since that seems to be the hip thing to do, only to discover that the service is blocked at work.  Categorized as “Dating” by WebSense.  Just out of curiosity, is anybody in the world really using Twitter to hook up?  Half the information I need when researching a problem these days is on a blog, which is under the similarly scandalous category of “Personal.”  Seriously, we’re not children.  Just let us do our jobs, and judge us on the work that we get done for you.

We’ll Miss You, Eric

Posted in Uncategorized on February 27th, 2008 by Brian – 1 Comment

Last night around midnight while looking at Facebook, I discovered that one of my friends from college named Eric Myers died suddenly on Sunday evening.  The only warning signs were some flu-like symptoms.  I hadn’t spoken to him since I got out of school, but this still came as quite a shock.

I met Eric while we were pledging for Delta Chi Delta, our social club (kind of like a fraternity, but lose the booze and frat house and add Bible studies and devotionals).  Eric immediately became everyone’s favorite, and the unofficial leader of our pledge class.  He had a sort of casual charisma; he was the kind of guy that you’d follow not just because he could inspire you almost without thinking about it, but because you just genuinely liked to be around the guy.  In a campus full of nice people, Eric stood out because when he talked to you, you could tell he wasn’t just being polite, but that he really cared.  It’s no wonder we made him Vice President. 

You will be missed, Eric.  We’ll see you soon, but in the meantime, enjoy that mansion, robe, and crown. 

eric

MultiComparer

Posted in Uncategorized on February 22nd, 2008 by Brian – 1 Comment

My friend and co-worker Kaelin was working on an application that was using a grid to display some custom objects, but wanted to be able to sort by multiple fields like you would do with an SQL query.  He came up with something that I think is pretty cool, and very reusable:

Public Class MultiComparer(Of T)

   Implements IComparer(Of T)

   Private _comparers As List(Of IComparer(Of T))

   Public Sub New(ByVal comparers As List(Of IComparer(Of T)))

      Me._comparers = comparers

   End Sub

   Public Function Compare(ByVal x As T, ByVal y As T) As Integer Implements System.Collections.Generic.IComparer(Of T).Compare

      For Each comparer As IComparer(Of T) In Me._comparers

         Dim i As Integer = comparer.Compare(x, y)

         If i <> 0 Then

            Return i

         End If

      Next

      Return 0

   End Function

End Class

 

 

Let that sink in for a minute… 

 

So, if you wanted to sort, say, a list of Person objects by last name, then first name, then birthday, you’d create a new MultiComparer passing in a list consisting of a LastNameComparer, a FirstNameComparer, and a BirthdayComparer (in that order).  Mad props to Kaelin for his understanding of generics!