Showing posts with label design. Show all posts
Showing posts with label design. Show all posts

Monday, June 11, 2012

Making Prettier Forms: Converting Checkboxes into Images

A couple weekends ago I went to the Big Design Conference in Dallas (recap coming soon), and I always come back inspired to help the user’s experience with the applications I write. One of the things mentioned (several times) was making forms simpler. Basically, you don’t have to make the end-user feel like they’re filling out a form. There are ways to make it seem less intimidating. One way is to swap out the typically hard-to-click checkbox or radio button with an image. It gives the user a larger click area and it looks nice…at least in my opinion.

Basically, I’m helping a friend with a small project, and the image below is what I wanted to create.

image

If you buy Stephen Anderson's book "Seductive Interaction Design", you will see a similar form to the one above...primarily just the name and contact info stuff. By the way, I definitely recommend this book.

As you can see, the “Select Classification” is not your typical radio button setup. I googled for a bit if there was already a jQuery plugin to do this type of thing and came up empty. I’m sure you almighty readers know of one, but I couldn’t find it…so I made one.

So far I’ve tested it in Firefox, IE9, Chrome, and JAWS, and it works pretty good in all of them. The way I set it up to work is based on the input and label. So you’d have the most accessible standard markup with your preferred styles for the label, and that’s how you get the effect shown above. I think it’s probably better said with code:

So it looks like a pretty typical setup so far, right? You have an input with a label. To make it more accessible, you wrap it with a fieldset and give it a legend. The primary reason you’d do this is to give screen readers some context. If you don’t need to worry about that, you could just as easy wrap it all with a div. You’re going to want to wrap it so your jQuery selector is more precise. After you markup the form, you just add the following JavaScript.

Now you’re all wired up, and you just add in your styles to whichever stylesheet classes you specified. The default stylesheet class names I specified are:

  • .Selected-Checkbox – this class is added to the label after it has been clicked
  • .Checkbox-in-focus – this class is added to the label when the checkbox/radio button is in focus

If you’re not sure the plugin is working properly, you can put it in “testMode”, like this:

$('#classification_radio_wrapper label').checkMate({testMode: true });

If you need to override my default class names, you can do that too by specifying class or focusClass in the options. I might rename class to selectedClass in the near future.

Please leave a comment if you have any questions or feedback.

The source code is available on github at https://github.com/derans/checkMate

The demo is located on 1pg.it at http://1pg.it/v9etvtn5 (also on github as the example.htm file)



Shout it

kick it on DotNetKicks.com

Thursday, May 26, 2011

New jQuery Plugin: FunkyFocus


So this jQuery plugin was built to help my end-users know immediately what section of a form they’re working on. Also, don’t blame me for the name. It was given to my new plugin by my wife because I couldn’t think of anything “catchy”. Basically what this thing does is changes the background of sections of forms or individual inputs. It’ll be better to post screenshots to get the idea…so…here you go…

image

So as soon as you tab to the password textbox, you get this:

image

Here’s how you use it:

  1. Add a reference to jQuery
  2. Add a reference to the jquery.funkyfocus.js
  3. Add this line afterward: $('form').funkyFocus();

If you want to customize how you use it, you have some options. Here they are:

  • class – default is selected
  • sectionOnly – default is true
  • selectorOverride – default is form#{id} input,form#{id} select,form#{id} textarea

If you don’t want to use selected as your class, you’d use this code:

    $('form').funkyFocus({class: 'yourclassname'});

If you don’t want to change the background, but want to change the individual input, do this:

    $('form').funkyFocus({sectionOnly: false});

It would look something like this (assuming you changed the selected style to have a green background):

image

Here’s the actual plugin code:

(function($) {
    $.fn.funkyFocus = function(options) {
  var defaults = {
    class: 'selected',
    sectionOnly: true,
    selectorOverride: 'form#{id} input,form#{id} select,form#{id} textarea'
  };
  var options = $.extend(defaults, options);
  return this.each(function() {
    var selector = options.selectorOverride.replace('{id}', this.id);
    $(selector).focus(function() {
      if (options.sectionOnly)
        $(this).closest("div").addClass(options.class);
      else
        $(this).addClass(options.class);
    });
    $(selector).blur(function() {
      if (options.sectionOnly)
        $(this).closest("div").removeClass(options.class);
      else
        $(this).removeClass(options.class);
    });
        });
    };
})(jQuery);

If you’d like to know how to create a jQuery plugin, check out this post.

Download the plugin here.

Check out the demo here.

As always, please let me know if there’s a way to improve it. Thanks for reading!

Shout it

kick it on DotNetKicks.com

Tuesday, May 25, 2010

Creating a Fluent Interface with C#




So I’ve been using fluent interfaces for a while now and I’ve really grown to like them. It made me want to write one, so I did. I made a simple interface for creating an LDAP URL. It’s really basic, but I thought it was cool nonetheless. Here’s what I ended up doing…

I wrote a test of how I wanted it to read, which looked like this:

[Test]
public void LDAP_WithBaseDN_WithHost_Should_Return_Valid_URL()
{
var ldapurl = new LDAP()
.WithBaseDN(dc =>
"ad", dc => "derans", dc => "lab")
.WithHost(
"noc-dc01")
.URL;

Assert.That(ldapurl, Is.EqualTo("LDAP://noc-dc01/dc=ad,dc=derans,dc=lab"));
}

So what does this look like in inteface form…

    public interface ILDAP
{
ILDAP WithBaseDN(params Func<string, string>[] dnitems);
ILDAP WithHost(string hostName);
string URL { get; }
}

As you can see here, I’m using one of my favorite new methods to map/pass data, the good ole Func<string,string>. I could pass create the WithPort, WithScope, etc, but I wanted to keep this short and simple.

So here’s the actual implementation of ILDAP:

    public class LDAP : ILDAP
{
private const string _protocol = "LDAP://";
private string _ldap = _protocol;
private bool hasBaseDN;

public ILDAP WithBaseDN(params Func<string, string>[] dcitems)
{
hasBaseDN =
true;
_ldap += BuildBaseDN(dcitems);
return this;
}

public ILDAP WithHost(string hostName)
{
if (_ldap.Length > _protocol.Length)
_ldap = _protocol + hostName +
"/" + _ldap.Remove(0, _protocol.Length);
else
_ldap += hostName + "/";

return this;
}

public string URL
{
get
{
if (!hasBaseDN)
throw new InvalidOrMissingBaseDN();
return _ldap;
}
}

private static string BuildBaseDN(IEnumerable<Func<string, string>> dcitems)
{
var baseDN = "";
foreach (var dc in dcitems)
{
var dnitem = dc.Method.GetParameters()[0].Name;
if (!Enum.IsDefined(typeof(LdapOptions), dnitem))
throw new InvalidOrMissingBaseDN();

baseDN +=
"," + dnitem + "=" + dc.Invoke(null);
}
return baseDN.Remove(0, 1);
}
}

One thing about being fluent is that you don’t know which order someone is going to do something in. If someone knows how to handle this, that would be great. I suppose I could look in the NUnit code or fluent NHibernate, but haven’t really had a chance to do a whole lot of research into how to do this…so hopefully this is an okay start :)

So here’s what the LdapOptions looks like:

    internal enum LdapOptions
{
dc, cn, ou
}

Not a great name, but it works for now. Here are all the tests:

[TestFixture]
public class LDAP_Tests
{
[
Test]
public void LDAP_WithBaseDN_WithHost_Should_Return_Valid_URL()
{
var ldapurl = new LDAP()
.WithBaseDN(dc =>
"ad", dc => "derans", dc => "lab")
.WithHost(
"noc-dc01")
.URL;

Assert.That(ldapurl, Is.EqualTo("LDAP://noc-dc01/dc=ad,dc=derans,dc=lab"));
}

[
Test, ExpectedException(typeof(InvalidOrMissingBaseDN))]
public void WithBaseDN_Should_Throw_InvalidOrMissingBaseDN_If_BaseDN_Is_Invalid()
{
var ldap = new LDAP().WithBaseDN(dc => "ad", test => "test", dc => "derans", dc => "lab");
}

[
Test, ExpectedException(typeof(InvalidOrMissingBaseDN))]
public void URL_Should_Throw_InvalidOrMissingBaseDN_If_BaseDN_Is_Invalid()
{
var ldap = new LDAP().URL;
}

[
Test]
public void WithBaseDN_Should_Return_Valid_LDAP_URL()
{
var ldapurl = new LDAP().WithBaseDN(cn => "employees", dc => "ad", dc => "derans", dc => "lab").URL;
Assert.That(ldapurl, Is.EqualTo("LDAP://cn=employees,dc=ad,dc=derans,dc=lab"));
}

[
Test]
public void WithHost_And_WithBaseDN_Should_Return_Valid_LDAP_URL()
{
var ldapurl = new LDAP().WithHost("noc-dc01").WithBaseDN(cn => "employees", dc => "ad", dc => "derans", dc => "lab").URL;
Assert.That(ldapurl, Is.EqualTo("LDAP://noc-dc01/cn=employees,dc=ad,dc=derans,dc=lab"));
}
}

That’s it. Please let me know if you see ways to improve on the fluent goodness. Thanks for reading!


Shout it

kick it on DotNetKicks.com

Tuesday, February 02, 2010

Take Control of Your Web.Config




After reading a Paul Sheriff article in CODE Magazine, I ended up creating a base WebConfig class to handle getting values out of my web.config. I’ve hated the ConfigurationManager.AppSettings since they deprecated it from ConfigurationSettings.AppSettings. So now I have my own GetAppSetting so I never have to worry about it again. 

My base class looks like this:

public class BaseWebConfig
{
protected static string GetAppSetting(string appSettingName)
{
if (ConfigurationManager.AppSettings[appSettingName] == null)
throw new NullReferenceException(appSettingName
+
" AppSettings value cannot be null or empty in the web.config.");

return ConfigurationManager.AppSettings[appSettingName];
}

protected static bool GetBoolAppSetting(string appSettingName)
{
return Convert.ToBoolean(GetAppSetting(appSettingName));
}

protected static string[] GetStringArraySetting(string appSettingName)
{
var values = GetAppSetting(appSettingName).Split(new[] { ',' });
return values;
}

protected static int GetIntAppSetting(string appSettingName)
{
int i;
if (!int.TryParse(GetAppSetting(appSettingName), out i))
throw new InvalidCastException(appSettingName
+
" AppSettings value is an invalid integer.");

return i;
}

protected static DateTime GetDateTimeAppSetting(string appSettingName)
{
DateTime dt;
if (!DateTime.TryParse(GetAppSetting(appSettingName), out dt))
throw new InvalidCastException(appSettingName
+
" AppSettings value is an invalid DateTime.");

return dt;
}

protected static string GetConnectionString(string connectionStringName)
{
if (ConfigurationManager.ConnectionStrings[connectionStringName] == null)
throw new NullReferenceException(connectionStringName
+
" ConnectionStrings value cannot be null in the web.config.");

if (String.IsNullOrEmpty(ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString))
throw new NullReferenceException(connectionStringName
+
" ConnectionStrings value cannot be null or empty in the web.config.");

return ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
}
}

Here’s the breakdown:



  • GetAppSetting – Gets a string value

  • GetBoolAppSetting – Gets a bool value

  • GetStringArraySetting – Gets a string[] value

  • GetIntAppSetting – Gets an int value

  • GetDateTimeAppSetting – Gets a DateTime value

  • GetConnectionString – Gets a connection string value

Pretty simple stuff here…well I think it’s self-explanatory. Note they’re all protected so the inheriting class can access them, but nothing else. The reason I do this is because I never want a magic string passed in and risk getting a run-time error with a simple typo.


So with this base class, I inherit it in another WebConfig class in my actual project. Here’s an example of one:

public class WebConfig : BaseWebConfig
{
public static string ReturnEmail
{
get { return GetAppSetting("ReturnEmail"); }
}

public static bool IsTestEnvironment
{
get { return GetBoolAppSetting("IsTestEnvironment"); }
}

public static DateTime ShutOffDate
{
get { return GetDateTimeAppSetting("ShutOffDate"); }
}

public static string DbConnectionString
{
get { return GetConnectionString("DbConnectionString"); }
}
}

You can see above, I can reference my web.config all day long and never worry about mistyping something. If I need to rename something, I can easily do that as well. If you’re a reader of my blog, you know I’m a huge fan of being strongly-typed. I love for intellisense to help me out :)


I really like the simplicity of this method because it’s easy for beginner team members to use. That’s all I got…let me know if you have comments.


Thanks for reading!


Shout it

kick it on DotNetKicks.com

Thursday, January 28, 2010

Linq to Sql Generic Repository with AutoMapper




We, my teammates and I, have been playing with creating a generic repository for Linq to Sql using AutoMapper. We haven’t used it in production or anything, but I figured I’d blog about it and see if anyone has any comments about it. It’s fun just to toy around sometimes.

A couple of posts ago, I blogged about Func<> and that’s going to play an important part in what I’m about to show you. So basically we started off coding what we would do without generics and then converted that into a generic method. The ending interface looks like this:

public interface ILinq2SqlRepository<TDataContext, TDomainModel, TLinqModel>
where TDataContext : DataContext
{
IList<TDomainModel> GetAll(Func<TDataContext, IQueryable<TLinqModel>> func);
TDomainModel GetById(
Func<TDataContext, TLinqModel> func);
void Save(TDomainModel model, Func<TDataContext, TLinqModel> func);
}

So there is the GetAll and the GetById methods. I’m also working on the Save, but it’s a little more tricky because I believe there’s a bug in Linq to Sql Attach(entity, original) when the primary key is a Guid, but that’s just me :) My Save method right now keeps returning a cannot insert duplicate key error and I’ve Googled it, but to no avail. I’m also not sure how to handle the using(DataContext)…just know it’s a work in progress! Anyhow…


The implementation looks like this:

public class Linq2SqlRepository<TDataContext, TDomainModel, TLinqModel> 
:
ILinq2SqlRepository<TDataContext, TDomainModel, TLinqModel>
where TDataContext: DataContext
{
private readonly TDataContext DataContext;

public Linq2SqlRepository(TDataContext dataContext)
{
DataContext = dataContext;
}

public IList<TDomainModel> GetAll(Func<TDataContext, IQueryable<TLinqModel>> func)
{
var list = Mapper.Map<TLinqModel[], TDomainModel[]>(func.Invoke(DataContext).ToArray());
return list.ToList();
}

public TDomainModel GetById(Func<TDataContext, TLinqModel> func)
{
return Mapper.Map<TLinqModel, TDomainModel>(func.Invoke(DataContext));
}

public void Save(TDomainModel model, Func<TDataContext, TLinqModel> func)
{
using (DataContext)
{
var original = func.Invoke(DataContext);
var entity = Mapper.Map<TDomainModel, TLinqModel>(model);
DataContext.GetTable(
typeof(TLinqModel)).Attach(entity, original);
DataContext.SubmitChanges();
}
}
}

Well here’s the base implementation and it looks a lot easier if you have a good understanding of .Net generics. You can see the common AutoMapper Mapper.Map<> method in there, which is what we’re using to do the left to right mapping and basically we’re just passing in simple Linq commands. So we still have to do our AutoMapper configuration, but my hope is that maybe this post will strike up a good idea in someone else’s head…hopefully!


I thought it’d work best to implement this into a repository by just setting it as a private field like this:

public class SampleRepository : IRepository<DomainPerson>
{
private readonly ILinq2SqlRepository<SampleDataContext, DomainPerson, DataPerson> _repository;
public SampleRepository(string connstring)
{
_repository =
new Linq2SqlRepository<SampleDataContext, DomainPerson, DataPerson>(
new SampleDataContext(connstring));
}

public IList<DomainPerson> GetAll()
{
return _repository.GetAll(x => x.DataPeople);
}

public DomainPerson GetById(Guid id)
{
return _repository.GetById(x => x.DataPeople.SingleOrDefault(y => y.Id == personId));
}

public void Save(DomainPerson person)
{
_repository.Save(person, x => x.DataPeople.SingleOrDefault(y => y.Id == person.Id));
}
}

I went the inheritance route and didn’t really care for it, mainly because it was much uglier in the implementation. So you’ll notice this inherits from a generic IRepository, which could’ve been IDomainPersonRepository that inherits from the generic or was just a plain ole repository. Anyhow, it looks like this:

    public interface IRepository<T>
{
IList<T> GetAll();
T GetById(
Guid id);
void Save(T model);
}

I wanted to show prettier things in the public side of the API like GetById with just Guid instead of pass me an ugly lambda :) (Even though I love the lambdas, a lot of devs don’t care for them) So the users of this API would just reference the IRepository<T>, but I’d actually probably end up renaming to a friendlier name like this:

    public interface IDomainPersonRepository : IRepository<DomainPerson> {}

Then I’d go ahead and inherit my SampleRepository from IDomainPersonRepository…I should really plan these posts out more than I do before typing them so the post is better structured. As I get more practice in, I’ll try to do that for you!


So that’s my thinking on some type of generic repository for Linq to Sql with AutoMapper. Please keep in mind that this was a fly by thing we came up with this afternoon and I thought it was pretty cool. It could definitely use more testing & refactoring!


Let me know if you have any thoughts, questions, or comments.


Thanks for reading!


Shout it

kick it on DotNetKicks.com

Friday, January 15, 2010

Validator Injection with C# and StructureMap




I recently had a need to setup validation rules for a registration system. I thought I would share how I was able to create a generic Validator with rules to pass through. Let’s get started.

So I had a rule that an email address couldn’t already exist in the database. So first I needed to define what a rule would look like and this is what I came up with:

    public interface IValidationRule<T>
{
bool IsValid(T model);
}

Here is the implementation:

 public class EmailAddressDoesNotExistRule : IValidationRule
{
private readonly string _connstring;

public EmailAddressDoesNotExistRule(string connstring)
{
_connstring = connstring;
}

public bool IsValid(User user)
{
using (var db = new DataContext(_connstring))
return !db.EmailAddress.Any(x => x.EmailAddress == user.EmailAddress);
}
}

So now do I pass in an IValidationRule to where I want to validate? No. Do I create an array of IValidationRule in the constructor of what I want to validate? Nope. Do I create an IValidator and pass that in? YEP! Let’s take a look at the IValidator and the implementation.


Here is the interface:

public interface IValidator<T>
{
bool IsValid(T model);
}

Here is the implementation:

public class Validator<TModel, TRule> : IValidator<TModel>
where TRule : IValidationRule<TModel>
{
private readonly TRule[] _validationRules;

public Validator(TRule[] validationRules)
{
_validationRules = validationRules;
}

public bool IsValid(TModel model)
{
var isValid = false;
foreach (TRule rule in _validationRules)
{
if (rule.IsValid(model))
isValid =
true;
else
{
isValid =
false;
break;
}
}

return isValid;
}
}

If you’re not familiar with .NET generics, you might want to do some research about them. They’re awesome!


Okay, so how do we tie it into our service? Well, we’re going to inject it into the constructor like so:

        private readonly IUserValidator _userValidator;

public UserRegistrationService(IUserValidator userValidator)
{
_userValidator = userValidator;
}

I’m sure you’re asking…where did the IUserValidator come from? Well, IUserValidator looks like this:

    public interface IUserValidator : IValidator<User>
{
}

Very simple and basically I only do this to make my code more readable. So the implementation of this IUserValidator looks like this:

public class UserValidator : Validator<User, IValidationRule>, IUserValidator
{
public UserValidator(IValidationRule[] validationRules)
:
base(validationRules)
{
}
}

So now back in our UserRegistrationService, we have a method that just calls the IsValid on the validator like this:

        public void CreateNewRegistration(User user)
{
if (_userValidator.IsValid(user))
//CreateAccountFor(user);
else
//throw new InvalidUserException();
}

Okay, so now for my FAVORITE part of this method for validating…the StructureMap code.


In my DependencyRegistry configure(), I added this code:

            ForRequestedType<IUserValidator>()
.TheDefault.Is.OfConcreteType<UserValidator>()
.TheArrayOf<IValidationRule>().Contains(x =>
{
x.OfConcreteType<EmailAddressDoesNotExistRule>()
.WithCtorArg(
"connstring")
.EqualTo(WebConfig.TeamsConnectionString);

//add more here like the line above
});

So as you add validation rules, you simply add them to your configure() and they’re lined up and ready to go! I’ve also seen this method used with formatting rules. I think it’s pretty awesome!


NOTE: If you have a lot of DB calls for validation, you may want to include some type of loader in the Validator and just pass in the items so you’re not making a ton of DB calls.


Let me know what you think and thanks for reading!


Shout it

kick it on DotNetKicks.com

Thursday, January 07, 2010

ASP.NET MVC Bootstrapper




Thanks to a comment by thangchung in my last post about the global.asax, I’m going to write up a post using a bootstrapper in my global.cs. So what does that mean? Well basically it’s a technique to boot up your mvc app. Let’s get started!

Step 1: Create your task interface. Mine looks like this:

public interface IStartUpTask
{
void Configure();
}

Pretty simple right? Let’s keep on…


Step 2: Configure StructureMap, otherwise you’re going to have a mess. In my Scan() from my DependencyRegistry, I added x.AddAllTypesOf<IStartUpTask>(); and the completed Scan looks like this:

  Scan(x =>
{
x.TheCallingAssembly();
x.AddAllTypesOf<
IStartUpTask>();
x.WithDefaultConventions();
});

Step 3: Create the Bootstrapper class. Mine looks like this:

    public class Bootstrapper
{
static Bootstrapper()
{
DependencyResolution.
DependencyRegistrar.EnsureDependenciesRegistered();
}

public static void StartUp()
{
var startUpTasks = ObjectFactory.GetAllInstances<IStartUpTask>();

foreach (var task in startUpTasks)
task.Configure();
}
}

The DependencyRegistrar mentioned above, I basically stole from the sample code in the ASP.NET MVC in Action book. I made a few modifications, but not much.


Step 4: Configure your configuration files for all the junk you need to start up.



  • Routes - I took my RouteConfigurator and made it implement IStartUpTask and renamed RegisterRoutes to Configure.
  • MvcContrib InputBuilder – Just made a new class that looks like this:
public class MvcContribConfigurer : IStartUpTask
{
public void Configure()
{
MvcContrib.UI.InputBuilder.
InputBuilder.BootStrap();
}
}


  • Automapper - I already had a configure, so I just tacked on the : IStartUpTask like this:
    public class AutoMapperConfigurator : IStartUpTask
{
public void Configure()
{
Mapper.Initialize(x => x.AddProfile<MyProfile>());
}
}


  • ControllerFactory – I created a new class for it and it looks like this:
 public class ControllerConfigurer : IStartUpTask
{
public void Configure()
{
ControllerBuilder.Current.SetControllerFactory(new ControllerFactory());
}
}

That’s it! So essentially the Global.cs went from this:

protected void Application_Start()
{
MvcContrib.UI.InputBuilder.InputBuilder.BootStrap();
DependencyRegistrar.EnsureDependenciesRegistered();
new RouteConfigurator().RegisterRoutes();
AutoMapperConfigurator.Configure();
ControllerBuilder.Current.SetControllerFactory(new ControllerFactory());
}

to this:

        protected void Application_Start()
{
Bootstrapper.StartUp();
}

Pretty cool stuff! Thanks thangchung for bringing it up!


As always, please comment and thanks for reading!




Shout it

kick it on DotNetKicks.com

ASP.NET MVC Routing: Global.asax & Single Responsibility Principle




Okay, so let’s continue talking about ASP.NET MVC routing. Basically I wanted to talk about extracting the C# code from my global.asax in the UI project and putting it in my Core project. I also want to talk about removing the routing code from the global.asax.cs. We need to stick with the Single Responsibility Principle. You can see a basic approach to routing in this post.

Step 1: Copy everything between the namespace {} from the global.asax.cs and create a new class (I call mine Global) in your Core project and paste the code into it. You’ll probably need to add a reference to System.Web & System.Web.Mvc.

Step 2: Delete the global.asax.cs. Be sure not to delete the whole global.asax, you only want to delete the global.asax.cs.

Step 3: Open global.asax and delete the Codebehind="Global.asax.cs" and modify the inherits to inherit from your new class (Global.cs). Like this:

<%@ Application Inherits="Core.UI.Global" Language="C#" %>

Okay, now your global.asax doesn’t depend on any C# code in your UI project. This is a good thing!


Step 4: Let’s extract your routes from the new Global.cs and put them into a new class (I call mine RouteConfigurator). By the way, the naming and route extraction is in the ASP.NET MVC in Action sample code. To do so, follow these steps:



  1. Cut everything in the RegisterRoutes() method in the new Global.cs class and paste it into your new RouteConfigurator class so it will now look like this:
    public class RouteConfigurator
{
public virtual void RegisterRoutes()
{
var routes = RouteTable.Routes;
routes.IgnoreRoute(
"{resource}.axd/{*pathInfo}");

routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
}

Notice I added a var routes = RouteTable.Routes; to the top of this method.



  1. Okay, so now we need to tie these things together and we just need to put one line of code in the Global.cs and that will look like this:
        protected void Application_Start()
{
new RouteConfigurator().RegisterRoutes();
//StructureMap Configuration Here
//AutoMapper Configuration Here
//etc
}

So now when Application_Start is called, it will call our RegisterRoutes in our extracted code.


Step 5: Enjoy having single responsibility classes and NO CODE in your UI!


As always, please comment if I can improve or you have questions and thanks for reading!

kick it on DotNetKicks.com

Wednesday, December 30, 2009

Wife’s Site Launched…YAY for MVC!




After weeks of writing new posts about everything I was learning and doing, the wife’s site has finally launched! Please visit it and let us know what you think. We are very excited!

We had several things that were important to both of us in the development. See below.

Deran’s List

Amy’s List

  • Use Best Practices
  • Learn New Tools
  • Make it Accessible
  • Keep the Code Clean & Maintainable
  • Keep Version Control
  • Make it Fast
  • Must be Clean Design
  • Easy to Update
  • Friendly
  • Navigation Easy

As you can see below, the site is VERY clean.

image

I hope you’ve read my previous posts and you believe that I used best practices. If not, please let me know because I will absolutely redo some things. I definitely learned A LOT during the process in particular, ASP.NET MVC, jQuery, & StructureMap. Amy thinks the site is easy to update…at least the pictures! Everything else is static XHTML and I know she’ll make me update that text, but it rarely changes.

I think I’ve made it as accessible as I know how. All the images have alt tags, the links have titles, access keys are all in place (including the standard 1,2,3,4), skip navigation is there, all forms have fieldsets & labels, and it’s all laid out with CSS. If I am missing ANY accessibility things, PLEASE let me know because that is VERY important to me.

I tried to make it friendly, I set the textbox focus where necessary, I have friendly messages like “Oops! Invalid email address.”, there are messages for just about everything, the textboxes change colors when invalid, the URLs are VERY friendly, so I think that goal was met.

The code is probably some of the cleanest and most maintainable code I’ve written in a LONG time. So no worries there.

The navigation is VERY straight-forward. Categorized at the top of the page and then you have the standard links at the bottom. Simple!

I kept version control with GIT and it’s backed up to my WHS nightly.

I’ve run the site through YSlow and optimized as much as possible.

I’ve encrypted the web.config settings, turned off debug, and enabled customErrors. I think it’s done! Yay :)

Warning…vent session here:
In case any of you are wondering what I laid the site out with, I used Fireworks 8. Fireworks 8 is single-handedly the BEST Web layout tool ever…then Adobe bought it and turned it into a bloated piece of crap like the rest of their software. Just my opinion, but Fireworks was built to be a Web layout tool and that is EXACTLY what it does…nothing more…nothing less. I love it!

Thanks for reading and PLEASE give us your feedback on her new site!

Related Posts:

Final Project MVC Structure
image

kick it on DotNetKicks.com

Tuesday, December 29, 2009

JavaScript – Not Required




As an end-user of many different sites, it appears to me that it is becoming increasingly difficult to have JavaScript turned off and increasingly dangerous to have it on. I’m a huge fan of JavaScript, but I think it’s unfair to design my web sites to force my end-users to have JavaScript turned on. So I try and make everything accessible without JavaScript. It might not look as fancy, but everything on my sites function and that’s what’s important.

Take my latest project, my wife’s re-design (not yet published as of this post), we’ve added several JavaScript niceties. However, EVERYTHING still works with JavaScript disabled and we pop-up nice little messages to let the end-user know why something is appearing the way it is. Here’s what we’ve done:

  • We have a group of images that fade in and out using jQuery on the homepage. When JS is disabled, the first picture is displayed and that’s it.
  • We have a Join Mailing List feature that uses ajax via the jquery.form plugin by Mike Alsup, which converts our form into an ajax form otherwise it leaves the default action. When JS is disabled, the call is the same, but our messages are formatted so the end-user will see a specific error or message stating why it’s formatted a certain way. To read more on how we implemented this, see the “jQuery AJAX with ASP.NET MVC” post.
  • For her portfolio page, we used jquery.lightbox, which pops up a nice modal effect for her images. When JS is disabled, every link just links to the picture and the picture pops up in the browser and then the end-user has to click back to get back to the gallery.
  • On her contact page, we use jQuery to decode her email adddress. To get around this issue, we use a real address for the mailto:, but it’s meant for spammers and we display a nice message letting the end-user know why they’re seeing email [[at]] domain [[.]] com. To see more on how we did this, see the “Trick Bots from Stealing Email Address with jQuery...” post.

Bottom line, don’t force users to do something they shouldn’t HAVE to do and make your web site accessible and friendly. Provide <noscript> messages when necessary and try disabling JavaScript on your browser and browsing your web site to see how people feel.

That’s it! As always, please comment if you see anywhere that I could improve or you just have a comment. Thanks for reading!

kick it on DotNetKicks.com

Saturday, December 19, 2009

Refactoring my MVC & Photo Repository

If you’ve been keeping up with my blog, you know that I’ve been working on my wife’s new website. Well, this post is going to involve a bit of refactoring on some of the code mentioned in the following previous posts.

The main thing I’m going to be talking about is the way I’m handling the different images on all the different pages. So let’s get started.

We’ll start with my IPhotoRepository (resides in Core) interface that originally looked like this:

    public interface IPhotoRepository
{
IList<Photo> GetHomePhotos();
IList<Photo> GetPhotosBy(string portfolio);
}

It ended up growing to look like this and it started to SMELL!

    public interface IPhotoRepository
{
IList<Photo> GetHomePhotos();
IList<Photo> GetContactPhotos();
IList<Photo> GetSessionPhotos();
IList<Photo> GetPhotosBy(string portfolio);
}

I did some refactoring and now it looks like this:

    public interface IPhotoRepository
{
IList<Photo> GetPhotosFor(Enumeration photoViewType);
IList<Photo> GetPhotosBy(string portfolio);
}

Okay, so my implementation called PhotoRepository (resides in Impl) now looks like this:

    public class PhotoRepository : IPhotoRepository
{
public IList<Photo> GetPhotosFor(Enumeration photoViewType)
{
return GetPhotosBy(photoViewType.DisplayName);
}

public IList<Photo> GetPhotosBy(string portfolio)
{
var flickr = new Flickr("yourflickerapikey");
var ps = flickr.PhotosSearch("yourflickruserid", portfolio, PhotoSearchExtras.OriginalFormat);
return Mapper.Map(ps.PhotoCollection, new List<Core.Domain.Model.Photo>());
}
}

The main difference is the addition of the Enumeration (resides in Core) class, which I literally copied off Jimmy Bogard’s blog post here. I believe you can also see it in use within the Code Camp Server project.


The Enumeration class I pass in is called PhotoViewType (resides in UI) and it’s implementation looks like this:

    public class PhotoViewType : Enumeration
{
protected PhotoViewType() { }
protected PhotoViewType(int value, string displayName) : base(value, displayName) { }

public static readonly PhotoViewType Home = new PhotoViewType(0, "Home");
public static readonly PhotoViewType Sessions = new PhotoViewType(1, "Sessions");
public static readonly PhotoViewType Contact = new PhotoViewType(2, "Contact");
}

I also refactored my view models. I basically extracted out the Photos and created a PhotoView() that returns a ViewResult. Here’s what the model looks like:


image I’m going to go ahead and show you the GetRandomIndex method just because I think it’s a good example of easy to read code and I’ll show my first implementation of it too. You can decide which is better!


First Implementation:

        private int GetRandomIndex()
{
return new Random().Next(0, Photos.Count);
}

More readable implementation…I think. It makes more sense to me and is simpler for someone to understand what’s going on.

        private int GetRandomIndex()
{
var minIndex = 0;
var maxIndex = Photos.Count;

return new Random().Next(minIndex, maxIndex);
}

So, I created a new SmartPhotoController that inherits from my base controller called SmartController. The SmartPhotoController has the responsibility of getting me my photos basically. The implementation looks like this:

    public class SmartPhotoController : SmartController
{
private readonly IPhotoRepository _photoRepository;
public SmartPhotoController(IPhotoRepository photoRepository)
{
_photoRepository = photoRepository;
}

protected ViewResult ViewWithPhotos<TModel>(TModel viewModel, Enumeration photoViewType)
where TModel : PhotoView
{
viewModel.Photos = _photoRepository.GetPhotosFor(photoViewType);
return View(viewModel);
}
}

I originally had the ViewWithPhotos<TModel> look like this:

protected ViewResult ViewWithPhotos<TModel>(TModel viewModel, Func<IPhotoRepository, IList<Photo>> func)
where TModel : PhotoView
{
viewModel.Photos = func(_photoRepository);
return View(viewModel);
}

I thought that was really cool because when I called it from my controller, it looked like this: ViewWithPhotos(new HomeView(), x => x.GetHomePhotos()); Obviously, I refactored my repository, so it was no longer necessary to do the lambda or the generic func. I think it’s unfortunate because I love lambdas, but they tend to confuse people so I usually end up refactoring them out with something easier to understand. My new code from the controller looks like this: ViewWithPhotos(new HomeView(), PhotoViewType.Home); So now my Home, Sessions, & Contact controllers inherit from the SmartPhotoController because they all deal with photos in some way.


I guess that’s it for now. As always, please comment if you see anywhere that I could improve or you just have a comment. Thanks for reading!

kick it on DotNetKicks.com

Related Posts Plugin for WordPress, Blogger...