Clean Code: 5 Tips for Best Practices

Last week, another developer from Hyland and I had the opportunity to go out and give a talk to computer science students at Bowling Green State University, courtesy of the university’s Women in Computing club.  They were kind enough to let us choose our own topic, and after tossing out our first 50 ideas, we decided to talk about how to write clean code.

Both Rebecca and I are second-career developers, and the two of us are called on to give the “second-career-woman-in-tech” talk fairly often, so we wanted to talk about something technical!  Besides which, university comp sci majors are probably not a group that needs a “second career” talk.  We headed out to Bowling Green after work on aWednesday, had a lovely drive out, and spent a few hours giving the presentation and chatting with the students.

I don’t want to dump the entire presentation here, but I did want share some of our key points.  Also, if you have an organization that’d be interested in hearing the talk, drop me a line and one/both of us can make arrangements to come give it!

Point #1: Coding is a social activity.  Programmers spend more time reading code than we do writing it!  The ratio on reading to writing code when it comes to development is something like 60:40.  This is because programming languages don’t exist for computers.  Think about it!  All the computer cares about are ones and zeros; the switch is either on or off.  We have high-level programming languages because programmers have made them for other programmers.  Languages are a tool that lets us share ideas with each other and communicate what we’re trying to achieve with our code–which is why you should always write clean code.  Pretend that the next developer to touch your code is a psychotic serial killer who knows where you live; you don’t want to make them angry.

Point #2: The two hardest things in computer programming are cache invalidation and naming things.  (Admission: I stole this saying from my dude Dave Goerlich).  You want to make sure that your names for things convey your intent!  Follow common conventions for whatever language you’re using, use one word per concept (i.e. don’t use “get”, “fetch”, and “retrieve” if they all mean the same thing), and avoid one-letter variable names (unless it’s a short scope or you’re naming an iterator variable).  Variables (customerAccountNumber) and classes (customerAccount) are nouns, booleans are yes/no answers (isValidAccount, isNotFlagged), functions are verbs (getCustomerAccountNumbers).  You also don’t want to mislead your reader–so don’t name an array of Customer objects a “customerList”.  Names should also be pronounceable and understandable–don’t make weird acronyms, or use nonsense words that have no meaning outside of very specific knowledge set.

Point #3: Classes and functions/methods should be small!  Very small!  Very, very small!  They should also obey the SRP (Single Responsibility Principle).  Functions should do one thing and do it well; classes should only have one reason to change.  For functions, the ideal number of arguments is nil–then one, then two, perhaps, three, but after that, many input arguments are a bad smell and indicate that the function is probably not adhering to the SRP.  Stay away from output arguments if at all possible–we’re far more used to seeing input arguments, and output args can lead to confusion.

Point #4: Keep it DRY.  Don’t Repeat Yourself!  This argument may have been done to death a thousand times before, but it’s worth repeating in every talk about clean coding practices.  We can also talk about organization here: try listing your functions ordered by level of abstraction.  One function should call those functions directly beneath it, although there are (of course) exceptions to this rule (I had one in my example code!).  Try making your code as easy to read as possible so that they next developer doesn’t have to keep scrolling up and down lines, looking for the next function call.

Point #5: Comments can be evil.  It’s very, very tempting to comment away badly-written code, but that’s a cardinal sin of clean coding.  Comments are not an excuse for skipping refactoring–if you think developers are bad at maintaining clean code, imagine how bad we can be about keeping comments up-to-date!  Comments that are redundant, misleading, or arbitrarily-required need to go, as do large block of commented-out code.  End-of-block comments are a smell that your code block is too long and refactoring is needed, and log comments on every file aren’t needed with any good modern version-control system.  Documentation comments, TODO comments, legal disclaimers, and short informative or clarifying comments can be good, but these all still run the risk of becoming outdated, and care should be taken to update them along with the surrounding code.

That’s not the entirely of the presentation, but those five tips are our key points for code cleanliness.  Also, if you’d like to see our slide deck, you can see it here!

 

The Black Magic of HTML5 Data Attributes

Okay, so, rewind to about a year and a half ago, when I was lying on the sofa, having a whine about my retail job du jour, and remembered that I actually had some skills outside of smiling and accepting the blame for my store being out of arbitrarily-sized t-shirts. This train of thought ended up with a friend of mine sending me copies of a couple front-end ebooks to get me up to speed on HTML5 (which had just come out) and CSS3, since I was a little out of date with what was going on in the Great Big Hello World of Web Development.

So, I’m reading this HTML5 book, all like:

But, there was one thing that it either didn’t cover, or—more likely—I got bored and quit reading before I got that part, because it wasn’t like I couldn’t already HTML, and reading about HTML is not the most exciting thing on Earth. (Also, HTML is now a verb, I’ve decided.) The thing that I missed? Data attributes, or, as they are also known, black freakin’ magic. The first time I saw them being used, I was like:

…look, kids, back in the day, we had to come up with weird names for CSS classes and use JavaScript to parse them into something meaningful if we wanted data available in the DOM. Now, you just prefix with “data-*” on an element, and you can store whatever the heck kind of string you want in there (within reason). You can store JSON in it, for example, which is just—whaaaaaat, where has this been all my life? (Or maybe not—HTML5 is only two years old, so for the vast majority of my life it hasn’t existed… still, have I totally been living under a rock for two years?!)

So now, say I have an unordered list, and I want to grab a value (or several values) and display it when the user selects a list item, without making an Ajax call or querying a database or any of that nonsense. I’ll just stick my data in some data attributes—let’s call them “data-registration-number”, “data-color”, and “data-codename”:

  • <ul id="nonsenseList">
    
     <li data-registration-number="1701" data-color="yellow"
    
     data-codename="Enterprise">Nonsense</li> 
    
     <li data-registration-number="74656" data-color="blue"
    
     data-codename="Voyager">More Nonsense</li>
    
     <li data-registration-number="74205" data-color="red"
    
     data-codename="Defiant">Even More Nonsense</li>
    
     </ul>

So now, I can use JavaScript to grab one of those values from my list items, and use it however I want:

<script> 
//this first script uses the element.getAttribute() function to nab the value from our data attribute:
var nonsenseList = document.getElementById("nonsenseList"); 
var firstItem = nonsenseList.children[0]; 
firstItem.onmouseover = function(){ 
 var regNumber = firstItem.getAttribute("data-registration-number"); 
 window.alert("Registration Number: " + regNumber); 
}; 
</script>

Admittedly, this is a pretty lame example with little/no practical application. The point is, I was able to tell my script to get the value of the attribute named “data-number” off a particular element, and it did. You should note that in order to have to a valid data attribute, the attribute name must be prefixed with “data-”, have at least one character after the first hyphen, be XML-compatible, and contain no uppercase ASCII letters (as per w3 spec for HTML documents, read more here).

But wait! There’s more. There is actually an even better way to access what is stored in your data attributes, and it’s through the new HTML5 dataset API. This API exposes an element attribute named dataset, which returns a DOMStringMap object. The DOMStringMap keys are the names of the data attributes (without the “data-” prefix), and the corresponding values are the string values contained in the attributes themselves. If the data attribute name is made of multiple words (like our data-registration-number), it’s converted to camelCase (in this case, registrationNumber). The dataset API is dead simple to use, too—just call it using dot notation on a chosen element:

<script>
//let's try it again using the dataset API:
var nonsenseList = document.getElementById("nonsenseList"); 
var secondItem = nonsenseList.children[1]; 
secondItem.onmouseover = function(){
 var regNumber = secondItem.dataset.registrationNumber; 
 window.alert("Registration Number: " + regNumber); 
}; 
</script>

The dataset API is widely supported in modern desktop and mobile browsers (aside from in Internet Explorer, which only supports it in IE11, because it’s Internet Explorer). There is a shim out there for it (only a Google search away), but if you’re concerned about compatibility, you can always fall back on using more vanilla Javascript functions like getAttribute(). I’ve also read that using the dataset API is slower, but unless you’ve got a load of stuff stored in your attributes or need to read out of a whole bunch of them very quickly, performance shouldn’t be a concern—and, side note, if this is an issue, it’s my opinion that you’re probably weighing down the DOM with too much data, and need to rethink your architecture.

Another side note: data attributes should only be used when a suitable HTML5 element or attribute does not already exist. Additionally, unlike microformats, data attributes are meant to be private—that is, they are not intended to be read by outside software, and are meant only for custom data in the context of the site they are located on. Data attributes are meant to be used by the site’s own scripts, meaning that you shouldn’t be implementing them to store publicly-usable metadata. If you want to do that, use microformats, that’s what they’re for!

If you’d like to try it with some quick and dirty code, here’s the pointlessness that I threw together for this post–feel free to pop it into your editor of choice and use it as a starting point for playing around with data attributes:

<html> 
<head>
 <!--doing some quick/dirty styling so that things aren't as ugly-->
 <link href="https://fonts.googleapis.com/css?family=Homemade+Apple" rel="stylesheet"> 
 <style>
 .container { 
 width: 25%; 
 text-align: center;
 }
 li { 
 display: block; 
 margin: 10%; 
 padding: 10%;
 border: 5px solid black; 
 border-radius: 10px;
 font-family: 'Homemade Apple', cursive;
 }
 </style>
</head>
<body>
 <div class="container">
 <ul id="nonsenseList">
 <li data-registration-number="1701" data-color="yellow"
 data-codename="Enterprise">Nonsense</li> 
 <li data-registration-number="74656" data-color="blue"
 data-codename="Voyager">More Nonsense</li>
 <li data-registration-number="74205" data-color="red"
 data-codename="Defiant">Even More Nonsense</li>
 </ul>
 </div>
</body>
</html>

<script> 
//this first script uses the element.getAttribute() function to nab the value from our data attribute:
var nonsenseList = document.getElementById("nonsenseList"); 
var firstItem = nonsenseList.children[0]; 
firstItem.onmouseover = function(){ 
 var regNumber = firstItem.getAttribute("data-registration-number"); 
 window.alert("Registration Number: " + regNumber); 
}; 
</script>

<script>
//let's try it again using the dataset API:
var nonsenseList = document.getElementById("nonsenseList"); 
var secondItem = nonsenseList.children[1]; 
secondItem.onmouseover = function(){
 var regNumber = secondItem.dataset.registrationNumber; 
 window.alert("Registration Number: " + regNumber); 
}; 
</script>

So, I’m Building a Web App (Part Three: CheckBoxList(For) the Best)

After dealing with the dropdown fiasco in part two of my struggle to build a working ASP.NET MVC app, I worked on getting project functionality in place instead of continuing with the unsatisfactory method of adding and removing people from subgroups.

The thing is, though, that I knew the dropdown wasn’t a good fix.  Using the dropdown meant that a person could only be added or removed from one group at a time, and I had slung it together so that different views were needed for addition and removal.  It was pretty much the epitome of bad UX–clunky, frustrating, and there was absolutely no need for it to be as difficult as it was.

I got projects and stuff working, but the problem I ran into after that was that my code was super ugly.  It’d turned into spaghetti all over the place, tons of logic in the controllers, everything was a mess.  I wanted to go back and turn the dropdowns into checkboxes, but I was afraid to touch anything because I’d cobbled everything together in such a delicate fashion.  (That’s what happens when you’re learning and don’t really know what you’re doing, I guess.)

So, naturally, I decided I’d just start over again.  Open up a new project in Visual Studio and just start over.  Y’know.  I only have to present this project to potential employers in a week and a half, no big deal.

This was the third time that I’d written up the add/remove functionality and it went so much easier this time.  MVC has a lot of HTML helpers, but it lacks one to make model-based checkbox lists.  So some absolute angels wrote an extension called CheckBoxList(For), which you can find at http://mvccbl.com/ or, y’know, just install through NuGet Package Manager in Visual Studio, like a normal person.  It makes checkbox lists almost stupid easy, and I had my functionality up and running in a couple hours.  The first time I attempted to make it work, it took me a couple weeks.

I can’t stop playing with it.  The checkboxes are such a better experience than the dropdown, and since I need another checkbox list to add groups and members to projects, I’m actually looking forward to using CheckBoxList(For) again.  That’s right, a MVC extension has actually got me excited about checkboxes!

…in other, unrelated news, I had a dream about jQuery last night.  Sometimes I wonder what I’m doing with my life.

 

How I Won my Coding Bootcamp by Ponyrolling

If you’ve been on the internet for longer than ten minutes, you are probably familiar with Rickrolling–tricking someone into listening to the earbug that is Rick Astley’s Never Gonna Give You Up under the guise of sending them legitimate information.  Before Rickrolling, there was Duckrolling, which is where you’d get sent this stupid wheeled duck instead of Rick Astley.  Either way, *rolling is bait-and-switch, you expect one thing and get another.  For example, I won my bootcamp by ponyrolling.

It all started three weeks into the program.  We had whiteboard tabletops, and I drew this on the table:

My Little Pony: Coding is Magic

It was pretty funny, the instructor took a photo of it, I took a photo of it, everyone laughed.  So a week later, I drew another pony while we were talking about data structures.  And I drew a couple ponies when we talked about exception handling.  And it got to be a thing that I was making ponies out of programming concepts and computer languages.  Just a quirky little thing, right?  Ponies on whiteboards.  Nothing extravagant.

We were assigned final projects with a week to go: make a portfolio website using ASP.NET MVC, hook it up to a database, do some other stuff, it has to have this, this, and this other thing.  By the middle of the week, a classmate had told me that I had to put a pony on it, because of the whiteboard ponies.  So I brought in my Macbook, opened up Photoshop and made a good version of that original C# pony:

C# Pony

Originally, I just had C# Pony hanging out on the home index view as a way to take up space.  I was going to remove her and put in another image later, but people would walk by and comment on the pony, and then they were upset when I said I wasn’t going to keep her there.  So I tweaked the stylesheet to make the site purple, and kept the pony, because so many people said they really liked the pony.

I got done with the site pretty quickly, and decided to make another pony.  Since the site was done in C# + HTML and drew project information and image URLs from a database, I decided that C# Pony’s companion would be SQL Pony:

SQL Pony

People were getting a pretty good laugh out of the ponies, which made me happy.  I really like My Little Pony, although I’m not completely sure why.  At least part of it is nostalgia value, having watched the cartoons and played with the toys growing up.  The newest incarnation of My Little Pony, Friendship is Magic, is actually a really good cartoon, if you can get over the characters being colorful small horses.  Plus the main character reminds me a lot of myself (Twilight Sparkle is a total nerd unicorn who special talent is being a total nerd), and her friend Pinkie Pie is a dead ringer for my dear friend Terri (in personality, of course, Terri is a real person and not a pony).  I don’t really have a large problem with being an adult who likes a little kid cartoon, either, although it’s also not as though I go to parties and introduce myself to people by comparing myself to Twilight Sparkle the nerd unicorn.

Moving on.  People were getting a pretty good laugh out of the ponies, and I liked that.  I like it when I can make other people laugh, especially when it’s over something small and silly.  I also don’t particularly mind making a fool of myself for a joke, so long as I’m sure people are going to laugh and not just silently wonder if I need to be institutionalized.

That Saturday evening, a little more than 24 hours before the project was due, it came to me:  it’s not enough to have two ponies.  If my bootcamp pals wanted ponies, then by all means, I would give them ponies.  I would give them so many ponies. 

Just as I had finished reading about session data and writing up some very basic code that switched the CSS the site used based on a session variable, my classmate Stephanie posted something on my Facebook wall.  She was at Plato’s Closet, which is a kind of resale clothes shop, and she had found a marvelously pink My Little Pony sweater, in my size, for $8:

pony sweater

Just as I was about to ask her to get it for me and I’d pay her back, she asked if I wanted her to get it for me and I could pay her back.  Of course I wanted it, because it was the perfect accompaniment for my plan to unleash so many ponies on my unsuspecting classmates.

I spent most of Sunday at Panera, eating an almost sickeningly sweet carrot cake muffin, drawing ponies and giggling to myself in the corner.  Late in the afternoon, I had a stylesheet that my eight-year-old self and her collection of My Little Ponies would have been immensely proud of.  I just still felt as though it was missing something

Only one of my classmates knew of my daring plan.  When I confessed on Facebook Messenger that I felt as though my utterly ridiculous style change was not ridiculous enough, this happened:

Him: My recommendation: have the ponies dance by tilting them left and right with 2 stunning frames of animation.
Me: …oh my god
Me:  You’re a genius.
Me:  That idea was too much for Visual Studio, apparently, because it’s crashed.
Him:  You should be able to do it with the same CSS animation tools I used for blinky text.
Me:  It’s perfect.
Me:  You don’t know why it’s perfect because you are not looking at the pony extravaganza right now, but trust me, it’s perfect.
Him:  I’m helping!
Me:  You’ve just saved Christmas.

It ended up being more a gentle rocking motion than the original vision of “two stunning frames of animation”, but that actually ended up as a good thing.  The effect is mesmerizing.  He also suggested making the cursor into a pony, which is surprisingly easy to do with CSS3.  I remember back in the day when loading up a horrible, hard-to-use custom cursor on your Geocities page required a ton of JavaScript, but now all you have to do is something like this in your stylesheet:
body {
cursor: url("Other_Images/ponycursor.png"), auto;
}

So I had a custom pony cursor, dancing ponies, a rainbow gradient header background, fluffy clouds for the body background, I had a very girly cursive font courtesy of Google Fonts… and the majority of my content was the same.  For all intents and purposes, I had taken a very boring, adult website and overloaded it with pink/purple/rainbow/ colors and so many ponies.

Stephanie brought my awesome new pony sweater to class on Monday morning, and I parted with $8.  I put the sweater on and waited until just before lunch to present my masterpiece.

I got my laptop plugged into the projected and started.  The site begins looking like this:

site with normal stylesheet (boring!)

I clicked through the pages, pretending like nothing was wrong and like I also wasn’t wearing a pink fuzzy pony sweater.  A couple people who had seen the site that Friday were disappointed that the ponies were removed.  Good.

The project page has all of my bootcamp projects laid out in little display boxes.  There is actually a box for the ponies, and, because I have the projects being sorted alphabetically on the back end, they ended up right next to box for the portfolio project.  So I could laugh it off, haha, yeah, I put the ponies on here for you guys, you can find the ponies on Github.  (You can, for the record, find the ponies on my Github.)  I clicked into the detail view for the portfolio project to show off the jQuery lightbox (Fancybox) I’d used to scroll through the screenshots for the project… I had included one of the second stylesheet.

Down at the bottom of the page, tucked under the copyright information in the footer, are three small icons.  Clicking an icon fires an AJAX post to the server that resets the session variable; when the post is successful, some jQuery takes care of scrolling back to the top of the page and refreshing the browser window.  Some Razor at the top of the layout partial view for the site loads the session variable and uses it to determine which stylesheet to apply, so clicking the second icon flips it from the above image to looking like this:

moderate pony stylesheet

There were some laughs, oh, I got them good, haha, the site is purple and there’s ponies!  I clicked through all the pages on this, too, just to show that it was the same site with a different stylesheet.

But wait.  There are three icons at the bottom of the page.

I toyed with my sweater a little.  The thing about being an adult who likes My Little Pony, I said, not quite looking at anything, is that you really have to own up to it.  It’s not just a casual thing, you kind of have to really go big or go home… so I decided to go big.

Are you ready for Super Bonkers Pony Mode?

Are you really ready for Super Bonkers Pony Mode?

Because here it is:

super bonkers pony mode

The ponies in the header sway gently back and forth.  Constantly.  The cursor is a tiny pony (unfortunately, Windows screenshots don’t pick up the cursor).  The only thing it doesn’t do is play the My Little Pony theme song, because I absolutely hate websites that auto-play music… but I’m kind of thinking that maybe it should do that.  I was also hoping to get some things to sparkle, but the jQuery plugin I found to make DOM elements sparkle didn’t work, and I ran out of time to futz with it.

The reaction to Super Bonkers Pony Mode was outstanding.  I wish I could have taken a photo.  There was so much laughter.  It was everything I had hoped it would be.

On my peer review form, under the question, “What could be improved?  How?”  someone wrote:

Nothing.  She won, it’s over.

…and that, ladies and gents, is the story of how I won my coding bootcamp by ponyrolling.  Please hire me, I’m funny.

So, I’m Building A Web App (Part Two: Dropdown Fiasco)

In Part One, I introduced you guys to my personal project, a web app for leaders of small groups.  Now I want to provide you with gruesome details of how I snottily cried over attempting to make a dropdown list.

If you google “DropDownListFor MVC” or some variant thereof, you will actually get a half-billion search results from Stack Overflow, etc where people are wondering why their dropdown menu doesn’t work.  It turns out that making effective dropdown lists in ASP.NET MVC is really tough!  Like, really tough.  When I set out to change my text box to a dropdown, I thought, how hard can it actually be?  I’ve made dropdowns in HTML like, at least a dozen times. 

I don’t even remember what all I tried before blinding grasping the solution, but to be honest, I struggled with it for over a week.  Here’s my final word on how to make it work:

Step One:  Use a viewmodel.

Using a viewmodel makes life with dropdowns so much easier.  Actually, they make life in MVC much easier all over, because you can easily deal with “extra” data that you know you’ll need to include in your view, plus you won’t have superfluous data hanging around.  For me, this meant a viewmodel class that looks like this:
public class PersonGroupingViewModel
{
[Key]
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set;}
public virtual IList Memberships { get; set; }
public SelectList AllGroups { get; set; }
public int SelectedGroupId { get; set; }
}

I needed the ID of my Person object, the person’s first and last name, the list of groups they were a member of, and finally–here’s the important part for the dropdown–a SelectList of all the groups in the database and an int to store the ID of the selected group.

Step Two: Create a view that is strongly-typed to your viewmodel. 

You need your view to be strongly-typed to your viewmodel so that you can easily access the data fields in the viewmodel.  This part is kind of a no-brainer.

Step Three:  Populate your viewmodel in your controller and pass it off to the view.

Step three involved spinning up up a new instance of my viewmodel class and passing it off to the view instead of the domain model.  I also had to spin up a new SelectList with all of the groups available and make sure it was included in the viewmodel so that the dropdown would work.  I did it in the controller it shouldn’t matter if you do it in the default constructor for the viewmodel class:

SelectList allthegroups = new SelectList(db.Groups, "GroupId", "Name");

There are about eleven million constructors for SelectList objects, but the one I’m using here is SelectList(IEnumerable, String, String), which specifies list items and also assigns the data value field (GroupId) and data text field (Name).  This allows me to display the group names in the dropdown, but post the group ID back to the controller.  Set it to the appropriate property in the viewmodel (viewmodel.AllGroups = allthegroups;)  and off you go!

Step Four: Actually put that dropdown sucker in the view.

Now for the fun part!  This is where the magic happens:

<div class="form-group">
<label>Choose Group:</label>
@Html.DropDownListFor(model => model.SelectedGroupId, Model.AllGroups, "Select A Group")
</div>

DropDownListFor is an HTML helper than can be used with a strongly-typed model (in this case, the viewmodel).  What’s happening here is that the selected group will post back the value as SelectedGroupId, the dropdown will populate from the model SelectList named AllGroups, and the default selected value will just be a string called “Select A Group”.

Step Five: In the POST action, grab that sweet ID you got back from the dropdown and get to work.

I just grabbed the entire viewmodel back in the controller POST action and processed out the individual bits. Here’s the code to look up the person and group in the database, and perform the necessary person-into-group finagling:

int PersonId = viewmodel.PersonId;
int GroupId = viewmodel.SelectedGroupId;
Person person = db.People.Find(PersonId);
Group group = db.Groups.Find(GroupId);

group.Members.Add(person);
db.SaveChanges();

I cast off my viewmodel and spin a new one to pass back to the view, because in my app, a person can belong to more than one group.  This makes the group we just added show up on that view under a section called “Memberships”, and the person can then be added to another group.  It’s not the prettiest thing in the world and also not the best UX, but it’s good enough for now and will be revisited later.  The important part is that it works!

Stay tuned for part three, in which I tackle checkbox lists and cry about UX design.

So, I’m Building A Web App (Part One)

About three weeks ago, I started an ASP.NET MVC project.  What I’m attempting to do is build a web app that helps leaders of very small organizations (like a church small group or a scout troop) keep track of their members and projects.  For someone with a grand total of 4 weeks experience in C# and no real experience with model-view-controller architecture (I don’t think RailsBridge really counts), it was… not unambitious, I suppose.

Step one: get CRUD functionality for people and groups, and then functionality to add and remove people from groups.

At least, that was what step one was supposed to be.  I’m using Entity Framework (code-first) and the magic that was supposed to happen to set up my database + tables (pretty simple–Groups, People, join table for the many-to-many relationship between Groups and People) was just… not happening.  The entire first week and a half of my project time was dedicated to uninstalling and reinstalling SQL Server Express and trying to figure out a) why I could create databases in SQL Server Management Studio but did not have permissions to read/write to/from them anywhere else and b) why EF was refusing to cooperate with anything even vaguely related to data management.  Finally, I took my laptop to a friend who is an (ex) SQL DBA and, after futzing with it for over an hour, he finally hit upon that I was missing the SQLClient installer that allows SQL Server Express and everything else ever to talk to one another.  For some reason, it hadn’t downloaded and installed… still no clue what happened there, but hooray!  I finally had a working database and could do things!

Setting up CRUD actions with Entity Framework is stupid easy, so getting part one of step one ready to go went by fairly quickly.  I could create, read, update and delete (just in case you missed the acronym) people and groups, but now I had to somehow convince my app to put people into groups and take them out again.  Actually, to break down step one even further, I just had to get the people into groups.

Working with the MVC pattern when you only have a shaky grasp of what it actually is can be a little daunting (okay, a lot daunting).  I knew that I had a Person object, and a Group object, and the Person object had an ICollection<Group> called “Memberships” and the Group object had an ICollection<Person> called “Members”.  Now how did I get them to play nice?  I got it working (admittedly with some help from the prior-mentioned friend) so that the primary key (PersonId) of the Person into the view and inserted a text box so that the user could put in the primary key for the Group (GroupId) in.  This then passed back to the controller, which looked up the Person in the database and added them to the Group’s member list.  So, it worked, but it wasn’t nice.  No real user would remember the IDs of all their groups and use a text box, so I decided to do it with a dropdown menu.  Dropdown menus are easy, right?  Select a group, press a button, and off you go!

Not so much.  More on the dropdown fiasco  to come in Part Two…