This post is a little info on how I went about coming up with a design for a winform app I'm building.
OK. I still use paper. This is what I started with today(very bad quality photo of paper):
Although simple, it took me awhile to figure out where to start on the UI. Once this was on paper, I had a better idea of where I wanted to start with Balsamiq Mockups. After a pretty short amount of time(like maybe 30 minutes), I came up with this(click to enlarge):
I spent very little time in the winform designer once i mocked up what I wanted. I ended up with this as a first cut:
OK. Here's part 2 of the TDD in practice dealio. I decided a screencast would be appropriate. I'm just getting over a cold so my voice is shot, this is a silent movie.
In part 1 I typed in code that I want, to solve my problem. Most of the code did not exist. So in part 2, we need to create everything that's missing and make the test pass. Play the video to see how I did it(I used all CodeRush features to generate code - with a little manual intervention; but most of this can also be done with raw Visual Studio shortcuts).
Ok, so I've been meaning to do a screencast on this, i've done one but it's lame. I figured I'd do more a photo slash journal-ish type thing and describe my real world(yes this is for an actual project) usage of TDD. So here goes, I just typed the following into my test, this is what I want to do:
And that's pretty much it. Notice the red squiggly lines? Yep, I haven't created that stuff yet, cuz this is what I want to do, not what I've done. Next part will be making those red lines go away...
Today I noticed this post on the ModelBinder attribute that ships with Preview 5 of ASP.NET MVC. I looked at the example and it doesn't make any sense. I had come up with something I call AutoBinder and until today didn't think it was anything worth mentioning. I could swear I saw somewhere that something like this would be included in the RTM of MVC but I can't remember where I saw that.
IModelBinder
IModelBinder is a simple interface with one method to implement, it looks like this:
publicstatic T UpdateFrom<T>(ControllerContext controllerContext) where T : class, new(){
T result = new T();
NameValueCollection form = controllerContext.HttpContext.Request.Form;
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(result)){
objectvalue = null;
//if the property type is boolean, make sure it's not an array, the//default behavior of Html.CheckBox is to create the checkbox, plus//a hidden field with the same name as the checkbox, to cover the behavior//of when a checkbox is unchecked, it won't get postedif (property.PropertyType == typeof(bool)){
string[] values = form[property.Name].Split(',');
if (values.Length > 0){
value = ConvertUtils.ChangeType(values[0], property.PropertyType);
}
}else{
value = ConvertUtils.ChangeType(form[property.Name], property.PropertyType);
}
property.SetValue(result, value);
}
return result;
}
Using this requires either registering the types with their appropriate binder at app startup or adorning your models with the ModelBuilder attribute like so:
[ModelBinder(typeof(AutoBinder<Customer>))]
publicclass Customer{
//guts of Customer here
}
1
2
3
4
Now in a controller we might have a method that looks like this:
[AcceptVerbs("POST")]
public ActionResult Edit(Customer customer){
//blah blah blah
}
1
2
3
4
Assuming that all of the fields on the form have the same name attribute as the properties on the model, the customer arg will be mapped up with the posted form values automagically through the ModelBinder attribute.
Anyway, here's the spectacular example: ModelBinder.zip. It assumes that you have Preview 5 of ASP.NET MVC installed.
I'm havin alot of fun with Balsamiq Mockups today. Here's my latest endeavor, I'm still learning so it's not great but it did help get over a hump with the project i'm working on.
via Tobin, i decided to check out Balsamiq Mockups. Wow. This tool is frickin awesome.
Food Tracker
As part of starting a cross fit program, I'm tracking(trying to anyway), I want to get better at tracking what I eat. Since I suck at coming up sample project ideas, i figured that a food tracking app would be a good way to play around with ASP.NET MVC and MonoRail as a sample application. I had come up with a sketch of the input form this weekend, but this morning the one I did with Balsamiq's online tool came out WAY better. Check out the sketch:
The tools is surprisingly fun to use. There are a ton of controls to pick from and anything you choose you can customize the text and data.
The grid in my sketch was a snap to set up, drag a grid, type in what you want for the header text, and a few rows beneath and you're done.
The designer also hasguidelines, so when you drag a control, similar to Visual Studio's WinForm designer, you get the vertical and horizontal guidelines that help you make stuff look good.
Anyway, if you have drawn diagrams of screen layouts before on paper, it's worth takin a look at.
OK. So I added some server side rule checking as a backup to the client side stuff. In order to test this out, I had to turn off client side validation. Right now it only returns a list of validation error messages, but I have some plans for that mechanism. The controller method that handles the form post now looks like this:
And the customer class looks like this(i updated the validation attribute constructors to match the changes i made.
[ModelBinder(typeof(CustomerBinder))]
publicclass Customer : IModel
{
publicint ID { get; set; }
[ValidateLength(3, 30,
"First name must be between 3 and 30 characters in length.", true)]
publicstring FirstName { get; set; }
[ValidateMaxLength(30,
"Last name is required and cannot exceed 30 characters.", true)]
publicstring LastName { get; set; }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
and the server side validation ends up rendering the following view(reminiscent of lammo validation summary in webforms):
This one bugs me. Scott Guthrie has a huge post on some new form stuff that comes with preview 5. Great info there. However, looking at the validation examples, you can see that the validation depends on on checking business rules and throwing exceptions if any of the rules fail; then in the controller you catch a general System.Exception, update some stuff for the view, and return the same view. Why is this bad?
Well, an exception didn't really occur, it was made up because of failing a known business rule. So basically, now you're using the throwing of exceptions to guide your workflow which makes your code hard to test and hard to follow. I wouldn't normally comment on something like this, but I saw another example of this by Stephen Walther here.
People, please don't throw exceptions in non-exceptional situations.
OK. So why is it, that most of the validation examples I see for ASP.NET MVC always include allowing the user to submit potentially invalid form fields to the server??
If your validation "framework" requires you to submit a form to the server prior to being validated, then your framework sucks. Period. Definitely have the server side validation. Server side validation exists to double check that you didn't fuck up and miss something on the front end with client side validation.
I implemented a VERY lame outline of something that I would expect from a framework. Simple attributes are applied to properties that are bound in the view. My example expects that you are using jQuery. This is not good.
A validation framework that works on the client, should not care about it's implementation but should have a default implementation. So it shouldn't care if you're a jQuery fan, or prototype fan, or not a fan of javascript at all;it should establish some common methods that you are free to implement yourself.
If Microsoft were to implement a good validation framework, here's what I would require from them. Zero installation. Requiring that you install the Enterprise Library to get any sort of validation bennies is absurd, please stop doing this.
The framework would default to Microsoft's home grown javascript library, but with VERY little effort, could be switched out with prototype, jQuery, or any javascript framework you want.
Here's my scratch project trying to come up with a better validation framework. It's tied to jQuery, which I don't like. It looks for any element(i've only concentrated on an input element of type="text", so it doesn't do much) that contains a 'validate' attribute. then inspects other css classes that have been tacked on that indicate some sort of validation to perform on the element. I'm thinking of also sticking other attributes on the element when it's generated, not XHtml-ish, but oh well.
It's based on attributes that implement my IModelValidator interface which looks like this:
There were some quirks in my last bare bones mvc project. Some stuff wouldn't work when rendering views in the browser. Long story short, I needed this:
These files are not needed in asp.net mvc views, but when you add the default mvc pages supplied with the mvc install, you will get them by default. I decided to play around with removing them completely and remembered that there are some things to consider when adding views to your asp.net mvc application(and this also applies to "old school" webforms style apps).
@Page Directive and Web.Config
Most, if not all of the attributes of the @Page directive can be set sitewide in the web.config via the pages element and the compilation element, eliminating the need for the @Page directive altogether. The important attributes are Language, MasterPageFile, and Inherits.
Weird Errors
Removing the @Page directive however causes some weird errors to appear in the errors list. They appear to be indicating some VB.NET type errors(note the End Namespace reference below). They don't affect anything, they are just annoying.
Beware: Master Pages Everywhere
This is one to think about, maybe. Everytime you add a new mvc view content page, you have to pick a master page. If you did this on every single view content page and then decide you want to use a different master page, you would have to go to each view content page and change the name of the master page file. Unless of course if you decide to just replace the contents of one master page.
Sometimes you want the ability to test different master pages concurrently. Perhaps you are coming up with several site designs you need to show your customer to let them pick which one looks best. This requires easily switching master pages files. You can do this in the web.config in the pages element. After specifiying a base page for all view pages and the master page file, the element would look something like this:
Here's the upgrade for my previous bare bones preview 4 project template. Follow the directions here to install the template. Download the template here. The difference in this template is that i left the references to to the assemblies to their default install location(where the preview 5 installer places them by default). Also added in jQuery to the content folder and master page reference.
According to Martin Fowler, the Active Record pattern is described like this:
An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.
So I set out to implement this pattern in a quick spike. With no thought to performance, good coding, etc, I came up with a working Active Record implementation.
I started with the model. I used the greatly abused concept of a blog and created a Post model with two properties, and it looks like this:
publicclass Post {
publicstring Title { get; set; }
public DateTime CreateDate { get; set; }
}
1
2
3
4
Notice how there's no id property. I'm noticing that, recently anyway, all of the primary keys I define are identity columns, so I wanted to remove any concept of id from the models and keep that as something for a base class to define and manage.
I'm heavily influenced by Castle's ActiveRecord, so of course I have a base class named ActiveRecord that takes a model as a generic type parameter, the shell of the class looks like this:
publicclass ActiveRecord<T> where T : new(){
}
1
2
One of the things I was thinking was that it would be nice to also have a mechanism that allowed the creation of the schema from the model, similar to how Rails works.
Here's the source code file for my naive ActiveRecord implementation.
I couldn't help but constantly thinking about how much work would be involved in defining relationships and the corresponding tables from code, maybe that'll be my next attempt.
Here's how you define an ActiveRecord class:
publicclass Post : ActiveRecord<Post> {
publicstring Title { get; set; }
public DateTime CreateDate { get; set; }
}
There's one controller, ARController that handles all of the operations of List, Save, and Edit. It's a generic type that takes the ActiveRecord class as a type parameter. There is one ARController per ActiveRecord class in any assembly you tell the start up code to look at. There are 2 shared views, one for listing and one for editing. Only the bare minimum was used for the edit form, pretty just enough to get a form on the screen with zero logic and no concern for the type of field being edited. Both views use a single mvc style master page.
The ARControllerModule is a Ninject StandardModule that's used to wire up each ActiveRecord classs in the project to an ARController of the same type. Here's the CreateARControllers method responsible for finding all of ActiveRecord classes in an assembly and creating a new ARController of the same type as the ActiveRecord class:
public IDictionary<string, Type> CreateARControllers(Assembly assembly)
{
Dictionary<string, Type> controllers = new Dictionary<string, Type>();
Type[] types = assembly.GetExportedTypes();
foreach (Type type in types)
{
object[] attribs = type.GetCustomAttributes(typeof(ActiveRecordAttribute), false);
if (attribs != null && attribs.Length == 1)
{
Type controller = typeof(ARController<>).MakeGenericType(type);
controllers.Add(type.Name, controller);
}
}
return controllers;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
I included the Sql Server CE flavor of the Northwind database. It works. But a few screens break for reasons I didn't tackle yet, that'll be another post. The cool thing is that all you do is load up whatever assemblies contain your active record classes and it'll build a web ui to edit them. It's a first pass, but it should work with minimal effort on your machine, lemme know otherwise. You can grab a zip of the code here(it's about 10 megs).
I have couple of folders that get a fair share of abuse, one is a dev folder, it's where I put all those one off scratch apps that are created usually to test out one thing. usually poorly named. Those pile up fast. So implemented a Death Row folder. It's awesome. grab every project that's older than say a month, or named something like craptester or crackmonkey or MvcApplication1, MvcApplication2, MvcApplication3, etc, and sentence them to the Death Row folder. Where they sit for say a month? you choose. Then you delete them. Keeps the clutter down.
My other folder that gets abused is my svn folder, where i checkout crap from every place that lets me. Now i'm in the habit of Death Row, so I can keep that folder nice and clean.
In the source, the devs either have TODO comments indicating that they need to use TypeDescriptor for determining properties, or they are using the TypeDescriptor. A little digging got me this post and I put it on my delicious todo list. So now it all makes sense. I'm sure there is a cleaner way to do this but here's an overload I added to OrderBy:
Now reading the code *usage* is easier and there are no enums. The only problem is that now you have to make sure and document the possible values for that object parameter, cuz using an api that has a parameter of type object can be a little confusing unless you know what's supposed to go in there.
I've been in discussions in the past about this one. Let's say you have a method signature, and one of the parameters to the method can either be true or false. What Type do you use? Boolean? seems simple enough. But it's becoming increasingly annoying to have to discover boolean values in method signatures.
Recently I created a method with a signature like this:
Using the above signature, my client code looked like this:
myRepository.OrderBy("FirstName", true)
1
Reading that code kinda makes sense, but that true as the second arg is a mystery. What's true?? Intellisense tells me, but only after I put effort into this; effort I don't want to have to put in when I'm reading code. So I went back and changed it to this:
While testing out some more asp.net mvc stuff, I came up with a need to order a list of objects by property name(a string value). Assuming I have a list of customers named customerList, i want to do something like: customerList.OrderBy("FirstName"), and get back a list of customers sorted by the FirstName property of each customer instance in the list.
Originally, I used something based on this post. It looked like this:
public IEnumerable<TModel> OrderBy(string propertyName, bool sortAscending){
if (String.IsNullOrEmpty(propertyName))
thrownew ArgumentNullException("propertyName");
PropertyInfo property = typeof(TModel).GetProperty(propertyName);
if (property == null)
thrownew NullReferenceException(
String.Format("property '{0}' was not found on type '{1}'",
propertyName,
typeof(TModel).Name));
if (sortAscending)
return _models.OfType<TModel>().OrderBy(mo => property.GetValue(mo, null));
elsereturn _models.OfType<TModel>().OrderByDescending(mo => property.GetValue(mo, null));
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
But then I found dynamic.cs located in the DynamicQuery project in the CSharpSamples.zip file. Wicked cool shizzle. Now that method above looks like this:
public IEnumerable<TModel> OrderBy(string propertyName, Sort sortDirection){
if (String.IsNullOrEmpty(propertyName))
thrownew ArgumentNullException("propertyName");
return _models.AsQueryable<TModel>()
.OrderBy(propertyName, sortDirection.ToString());
}
One minor annoying thing about starting a new ASP.NET MVC project, is the template that's installed has a bunch of stuff that belongs in a Starter Kit type project, not a new project template. So I created my own empty project template that has the bare minimum to get started. I removed all the membership crap and .NET 3.5 shite that clutters the web.config, and stuck the preview 4 assemblies in a libs directory, within the project. Here's the template http://panteravb.com/downloads/ASP.NET MVC Preview 4 Project.zip.
First, find out where your user project templates directory is located. Tools > Options > Projects and Solutions:
Next, download and copy the zip from above to the that directory:
Next, run this command from the command line devenv -installvstemplates. Once that completes fire up visual studio, choose new project, and you should see this:
This is a pretty cool free tool from Mindscape you can find here. I was almost going to uninstall it though until unexpectedly it saved me some clicks, so it stays in my toolbox. I hooked up CTRL + SHIFT + E to launch it.
In the first part Michael mentions the reason why he chose ASP.NET MVC over MonoRail. He references Ben Scheirman's blog post on the topic of picking a Microsoft(this is the M word) tool, just because it has the M word attached to it not because it's necessarily the best choice. This is the exact reason why we're picking ASP.NET MVC over MonoRail at my current gig, one of those frameworks comes out of Redmond, the other does not, it was that simple.
I've gotten used to building off of the trunk. However, I can never remember every single assembly that Castle.ActiveRecord.dll and NHibernate.dll need nearby. If I create new projects using those tools, I usually put the required assemblies in a lib folder within the solution I'm building, then any project in the solution references the assemblies in lib(and not the gac or anywhere else).
To help me just copy all referenced assemblies those two assemblies require, I wrote a little snippet to help(you can run this straight out of snippetcompiler):
publicvoid RunSnippet(){
string sourceDir = @"C:\svn\castle\trunk\build\net-3.5\debug\";
string[] targetAssemblies = new String[]{ "Castle.ActiveRecord.dll", "NHibernate.dll" };
List<string> baseFileNames = new List<string>();
//add the two assemblies we're starting with
baseFileNames.Add("Castle.ActiveRecord");
baseFileNames.Add("NHibernate");
//get a distinct list of referenced assemblies for all targetAssembliesforeach(string targetAssembly in targetAssemblies){
Assembly asses = Assembly.LoadFrom(Path.Combine(sourceDir, targetAssembly));
foreach(AssemblyName ass in asses.GetReferencedAssemblies()){
if (ass.Name.StartsWith("System"))
continue;
if (File.Exists(Path.Combine(sourceDir, ass.Name + ".dll")))
baseFileNames.Add(ass.Name);
}
}
//get a list of file names that match the ref assemblies regardless of file extension; so//basically we want not only .dll, but .xml and .pdb files as well(and anything else that matches)
List<string> files = new List<string>();
foreach(string baseFileName in baseFileNames){
foreach(string f in Directory.GetFiles(sourceDir, baseFileName + ".*")){
if (!files.Contains(f))
files.Add(new FileInfo(f).Name);
}
}
//copy everything from source to destination, overwriting if we need tostring destDir = @"C:\dev\Awish.Security\lib";
foreach(string file in files){
File.Copy(Path.Combine(sourceDir, file), Path.Combine(destDir, file), true);
}
}
As I'm testing features of ASP.NET MVC, I'm noticing that it would be really nice to be able perform non-persistent CRUD operations on POCO's. Meaning, i need data, i need objects, but I don't want to set up a test database for these tests. I need to be able to create a class, and then create lists of instances of that class, and then add new ones, edit existing ones, delete some, exactly the same stuff I'd normally do, just no database.
I searched on "IRepository" and came back with awesome examples, most of which enabled you to do almost if not everything you would need to do in your app, many of which I'll be revisiting. But I couldn't find one that did almost nothing. So I wrote one. And it does...well, almost nothing.
It's pretty simple, and does only the bare minimum. Every class that wants to participate in a repository must implement IModel, this tells the repository that anything in it is guaranteed to have an int ID property, by which it can query:
publicinterface IModel{
int ID { get; set; }
}
1
2
3
Let's say you create a class, Customer. In order to enable it to be usable in a repository, it needs to implement IModel, so the class might look something like this:
//first create a customer repository
IRepository<Customer> repo = new Repository<Customer>();
//now add some customers
repo.Save(new Customer() { FirstName = "Chris", LastName = "Carter" });
repo.Save(new Customer() { FirstName = "Emmitt", LastName = "Carter" });
//make sure they are in there
Assert.AreEqual(2, repo.Count);
Assert.AreEqual("Emmitt", repo.Find(2).FirstName);
//let's remove one
repo.Delete(repo.Find(2));
//make sure it's gone
Assert.AreEqual(1, repo.Count);
Assert.IsNull(repo.Find(2));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
I bundled up the code in a project inspired by Rhino Commons called EPS.Common, the source is here: http://svn.chrisjcarter.com/public/EPS. I have a sample ASP.NET MVC(Preview 4) solution available for download here(less than 100k).
I've spent the last few days exploring the MVC offering from Microsoft. I like it. Alot.
Remove everything that sucks about webforms, which is pretty much everything, but more specifically, the page and control lifecycles, and you have ASP.NET MVC. Well, Microsoft MonoRail really.
Brail
I started with the Brail ViewEngine from the MvcContrib project. I was impressed with how it was identical in usage as compared to the actual MonoRail flavor. However, I noted that ViewComponentswere not implemented for whatever reason. I find them very useful in MonoRail, so I'm not sure they were left out intentionally or not, but after too many yellow screens of death I bailed and went to the out of the box stuff.
Out Of The Box
The out of the box stuff is pretty good. I don't like the casting that has to take place when requesting things out of the ViewData dictionary. The runtime should be doing this for us, the Brail ViewEngine does this, the out of the box ViewEngine(what the hell is that called anyway?) should as well. Maybe that's on the radar for the MVC team.
Source Code
I'm glad they posted the source code. There some things that were hard to figure out[without documentation], like how to create your own helper class that were difficult without the source code to refererence. And creating the helper class wasn't the hard part, getting the ViewContext was the hard part(in hind site, not hard at all).
Add New Item
When you add a new item like an MVC View Page, MVC View Content Page, or MVC MVC View User Control, it automatically adds the .aspx(or .ascx) fle, as well as the code behind file and designer file. This is a little annoying being that I'm not seeing why they're included as they are not needed. In the .aspx(or .ascx) file, you can set the inherits attribute to either the ViewUserControl or ViewPage, and that's good enough for the ViewEngine.
Html Should Be Simple
Webforms made html complicated. ASP.NET MVC is bringing back the simplicity. If you've ever stepped into System.Web, and viewed the source code for MVC, you'll see a HUGE difference in the amount of code needed to produce simple html.
Natali commented on this post about a visual search engine for kids. It's not exactly a visual search in terms of searching by image, but search results are all visual. Check it out, it's really pretty cool.
On the surface it looks like the devenv.exe's are in the lead. But I bet if i leave my instance of firefox open, by tomorrow those results will be different.
Although I don't smoke the stuff, my clothes reek of it; even my camera has that smell.
Music
Last night was Cruefest, and Motley Crue rocked! Vince Neil sounded incredible.
Shout at the Devil amazing, check out the video we took(it's not great cuz it's dark, but the sound is pretty good). And a little snip of a guitar solo thing here.
I did find out that apparently I'm not a fan of Buckcherry or Papa Roach. Just not my kind of music. Here's a vid of Papa Roach.
Parking
I have never been to Fiddlers Green before but it's a good place to hear music, great sound. However, we got to the show early enough to hit up a bar. When we pulled into the parking lot some guy asked for 20 bucks to park there. I flipped, dropped a "Are you f*cking kidding?" and he said, "Ok, how bout 15".... long story short, i said i'm going to a bar so i'm parking here and not paying. He said fine, just don't go to the concert. Ya, we went to the bar for one drink, then went to the concert.
Beer
Wow, how beer prices have increased. OMG, 9 bucks for a Miller Genuine Draft. Those guys must rake in cash hand over fist.
Interesting search idea at like.com. You click on the visual search button, and draw a rectangle on an area of the product and then search for similar items based on shape or color of whatever is inside the rectangle you drew. I'm not sure how accurate the search is, but it's nice to see attempts at changing and/or improving the way we look for things.
I wish they had something similar for music, you know, when you can't remember the name of a song but you know the melody, a search engine could give close matches for that melody...
I found this cool syntax highlighter Iris yesterday. Not sure how I missed this one in my quest for syntax highlighters. I've used Wilco Bauwer's(as of the time of this posting, Wilco's site was having some issues) tools which are cool,and squishyware was cool too.
At some point yesterday, I clicked into this blog post by Gustavo Duarte. The post had nothing to do with syntax highlighting but after poking around the site I noticed Iris was one Gustavo's projects so I checked it out. It totally trumps the other two highlighters I was using so I integrated it last night into my blog software. Since I highlight code on the fly, all of my code examples have picked up the new flavor of highlighting.
I like how it separates the line numbers from the code, that way when you select the code you don't get the line numbers too.
Here's some SQL:
select first_name, last_name
from customer
where last_name like'c%'
Anyway, it's a cool tool, check it out. Since I found the tool useful, I made a small donation to the children in Uganda via ICCF Holland per the suggestion by the Iris team.
I just saw a preview of the new Terminator movie due out next summer, holy crapper Batman, Christian Bale is John Connor, how bomb ass is that! Trailer here, they don't show much which is good.
OK. So I had no clue when I posted previously about the C# var keyword that the use of var is a religious war that's going on right now. I'm not sure where I stand right now, I'd have to say, "it depends".
I wouldn't use it in my current work, it would confuse other devs not up on the var usage and would unnecessarily complicate things at this time.
I'm also not sure due to the fact that people far smarter than me are on both sides of the fence, so right now is a good time to sit back and REALLY think before introducing var into my everyday code.
This is an 11 minute(or so) long screencast demonstrating how to pull down the latest bits from the castle folks and get a monorail project up and running. It goes through configuration and creating a simple controller/view using the build from 7/11/2008 off of the castle build servers.
I've been seeing a lot of people posting codeexamples that have the C# var keyword sprinkled liberally through their code. It's a handy little feature that helps you with LINQ queries, anonymous types, etc. For example, you can create a new type on the fly like this:
var person = new { Name = "Chris" };
Console.WriteLine(person.Name);
1
2
Not everyone reads from left to right, but I do, as does every single person who works with me and every single blog and code example I've ever seen. This is important when considering the liberal use of var because now one would have read a whole line of code and figure out the type for themselves, rather than just reading the first word on the line(if declaring a local variable).
Look at the following snippet:
var bus = FacilityConfig.Children["bus"];
if (bus == null)
thrownew InvalidOperationException("bus is a mandatory element");
1
2
3
What type is bus in the previous example? You would have to hope that you're in visual studio and can hover over it with the mouse pointer so you could see the type which is lame.
The var keyword should be used sparingly, only when the type is unknown, like in a linq query that returns an anonymous type. Using it in situations where you know what the type is makes your code hard to read.
This is nothing major, and actually producing the screencast was harder than normal. It's silent so you don't have to hear my awesome voice. Check it out here: View It!
So, I'm not seeing any good ways of returning a script block that can be executed on the client side. What i was doing was having a block of javascript validation code below my block of html form elements. I couldn't get this working, it may just not be possible, I'll try again later. However, you can put all of the javascript you need into the onclick event of a button. So trying that, I now have this, which isn't pretty, but my intentions are that the form would be autogenerated anyway, so I don't think I'll care about how pretty it is.
<form><table><tr><td><label>
First Name:</label></td><td><inputtype="text"id="FirstName" /></td></tr><tr><td> </td><td><inputtype="button"value="Save"onclick="
if($('FirstName').value.length == 0){alert('First Name is required!');
$('FirstName').activate();
returnfalse;
};
" /></td></tr></table></form>
My forms need to be simple. Can you tell I'm talking this one out? I have some really good ideas, and some mediocre solutions so far.
The area of a form to concentrate on is just the middle contents of a page. The type of target application is a business application, so there will be a lot of standard things we can do, think Microsoft CRM sort of(and I'm really sick of that flavor of blue we stole from the CRM follks).
The look and feel needs to be super easy to swap out, not just the stylesheets, but the layout as well. Not sure if this is a pipe dream, but I think it's doable.
How do you build forms? We are tasked with building a toolkit that's pretty framework agnostic, meaning it should work in asp.net webforms, asp.net mvc, castle monorail, or any other framework. It needs to only be tied to html, meaning all it does is generate the html for a form that has nothing to do with any framework.
Whatever "it" is, needs to generate forms, in an intelligent way, not just CRUD forms that have no life. By intelligent, I mean they need to fit the destination application in look, feel and behavior, and they are not generic in any way shape or form, other than that they have to fit most of the cases for the destination application.
How fast can you build forms? And by speed I mean, what's the least amount of code you can write to get no less than 100% of the desired form functionality. This includes any field validation, etc.
I never liked that "...can you fit your hand..." question. It's abstract-ish but has an answer.
I've seen some ridiculous microsoft questions(eg, "What would you do if you were to meet the Prince of Darkness?"), but they are intended to get you to show your creativity and thought process, there is no actual answer.
An interview for a technical position ideally would be conducted by the people that the individual fulfilling the position would have to interact. The interview questions slash activities are driven by the job description and the candidate themselves.
The Technical Interview
There are different facets of an interview(assuming anyone actually cares about who they are hiring). Sure you wanna know if they are professional and passionate about technology, that makes sense. How do you find out if someone is professional? You'll find out during the interview, do they trash past employers or employees? Note: Trashing previous employers and/or employees is perfectly acceptable, just not in the interview :) Are you passionate about technology? Too easy to answer yes to, so interviewers have to plan some questions that cause candidates to give up examples of how they are passionate. But is that all? Nope.
The Job Description and Hands On Test
Let's say you're hiring a software developer with at least 3 years experience developing websites using ASP.NET, C#, and Sql Server(or any other database for that matter). A laptop would be required for the interview, something I'd bring for the candidate(or a desktop, whatever is easiest). And since I'm into the virtual image kick, I'd have one created already for the candidate, complete with visual studio 200x and Sql Server 200x, and firefox set as the default browser;i'd actually hide all of the ie shortcuts too :)
Requirements
I would have some requirements typed up, preferrably written by a business analyst or someone who's not a software developer. And I would make some of the requirements vague(so they have to ask questions in order to complete the task). I'd hand the requirements over to the candidate with the instructions, "fulfill the requirements, no visual designers are allowed in either of visual studio or sql management studio".(details like connection strings would be included). At that point the interviewers would sit back and watch the show.
Watching the Show
Watch what? Well did they clarify the requirements, remember, they're written too vague to be able to actually complete correctly, so questions are expected.
How do they type? I'm convinced that if you're clumsy on the keyboard, or if you're poking around visual studio menus for the "Build" menuitem, you lied on your resume about having ANY experience with visual studio. I would expect that for someone who types, and is not used to the provided equipment, would type fast and make a lot of fat finger mistakes, which is fine.
The database part would interest me the most. How many people put "Sql Server Expert" on their resume, and can't issue a CREATE TABLE command in a query window(and yes, it has to actually create a table)? OK. Don't know the command? that's no problem, but i wanna see how or if the candidate can find the answer. This also downgrades their status of "Sql Server Expert" to "i've connected my .NET app to MS Sql Server and that's about it".
The task would be simple enough to complete within say an hour, actually maybe even 30 minutes. I'd love to see if they're smart and pick up some tool of their choice(Subsonic, LLBLGEN trial version, their own CodeSmith templates, whatever) to help them complete the task on time; or is most of the time spent writing sql. The data access code would drill their knowledge of System.Data as well. Did they write something like "select * from blah where somefield = '" + somevar + "'"? or did they write "select * from blah where somefield=@somefield"(note the use of the parameter). Lack of parameter use is a pet peeve of mine.
Lack of a designer is good too. If you're really passionate about what you do, you'll know, maybe not prefer, but you'll know how to type html into the text editor.
Other Questions
What your favorite unit testing framework? How many computers do you have at home and what are they? What OS? What hardware? Who's blogs do you subscribe to? What was the last project your were proud of? What made you proud of it? Do you own an IPhone? MP3 player? Any other geeky gadgets? What would you do if you met the Prince of Darkness? Have you ever been to the Rio? What's your favorite beer? Which is better, Blade or Roadhouse? (It's a trick question, they are both awesome). Who's better, Killswitch Engage or Motley Crue? (again, another trick question; and yes I am going to the Cruefest next month) How many times have you watched Old School? How bout Office Space?
For those who know me, you might be thinking, but all of those questions reflect things specific to me, they're not general questions, but they're things that _I_ look for, and that, my friends, is the point. Questions like that have to, at some point, come from those the candidate would be working with as part of the interview process. Can the candidate get along with the people already working there? Candidates interviewed by recruiters or anyone else they won't be working with are ultimately going to suck.
Questions I Don't Care About
I could only think of one off the top of my head: Can you draw a UML diagram? If you can, sweet, teach me the next time I'm finding it difficult to fall asleep, I don't how to do that, and I don't plan on learning. UML == BORING.
I've seen many blog posts recently that give guidance on late binding with reflection versus early binding with casting. What seems to always be missing is any data supporting the claims. How can you tell me something is better without showing me how you know this? Here's my sooper scientific(read, not scientific) performance test to help demonstrate how much faster early binding can be over late binding using reflection. I ran each routine through 100 iterations, 1000, 10000, and 100000 iterations.
Late Bound Test Code
OK. The main point I wanted to test was the cost of getting a value from a property on an instance of "something" through reflection. This means calling type.GetProperty("SomeProperty").GetValue(instance, null). So here's the late bound code:
privatevoid LateBinding(IList orders, int iterations)
{
for (int i = 0; i < iterations; i++)
{
foreach (object item in orders)
{
Type type = orders[0].GetType();
StringBuilder html = new StringBuilder();
html.AppendFormat("<td>{0}</td>", type.GetProperty("ID").GetValue(item, null).ToString());
html.AppendFormat("<td>{0}</td>", type.GetProperty("Date").GetValue(item, null).ToString());
html.AppendFormat("<td>{0}</td>", typ