Dev: Visual Studio 2013 Single Page Application with BackBoneJS

Introduction:
As part of my exploration from the last blog post I have been digging into BackBoneJS. Here I take a look at getting started with BackBoneJS in a Microsoft environment. Ultimately, I don’t think this is a very clean solution, so I’ll follow up with another that’s not integrated with ASP.Net’s MVC.

There’s a few requirements for this post.

Our goals with this website is to get a basic MVC website up and running using the BackBoneJS framework.
You can learn more about BackBoneJS here: http://backbonejs.org/
So, once you’ve got Visual Studio installed and running, and the BackBoneJS template installed, go ahead and create a new Visual C#  Web ASP.NET Web Application. It should look like this:
vs2013-spa-backbonejs-01
This will give you a new window of options; choose the Single Page Application.
vs2013-spa-backbonejs-02
Okay, let that build the solution. If you want to see what it does right off, run it with F5.
This theme uses the popular Bootstrap theme (CSS3) to achieve a “responsive” look and feel. Responsive simply means the website will attempt to mold itself to whatever screen size your users browse the site with. Be that a tiny screen through a smartphone or a big screen through a desktop computer. This concept can save you a lot of development time down the road when clients ask for a version of your site to work on their iPad. Responsive is better, in my opinion, than a mobile version of a website. This comic attempts to explain precisely why: http://xkcd.com/869/

You can learn more about Bootstrap at their website: http://getbootstrap.com/

We’re using Bootstrap with this theme automatically, but I don’t want to use the default Bootstrap theme. It’s unoriginal and sort of lazy to use the default theme. So, I’ll go to a website that offers other themes that work with Bootstrap: http://bootswatch.com/ and download the “Slate” theme. Save the “bootstrap.css” and “bootstrap.min.css” to your projects “Content” folder. This will overwrite the defaults that came with the project.

Centering images in the JumboTron

Personally, I’m going for a pretty simple page here. A centered logo at the top, followed by some page content with images. For the “header” section of a web page, Bootstrap delivers JumboTron. In their words, “A lightweight, flexible component that can optionally extend the entire viewport to showcase key content on your site.” You can learn more about the JumboTron on their website: http://getbootstrap.com/components/#jumbotron

What JumboTron does not do out of the box is give you a class to center your image. Developers will waste hours trying to hack the CSS, but, CSS requires finesse, not muscle. Here’s the code that accomplishes a centered image without much fuss:


<div class="jumbotron">
<div class="row well well-lg">
<div class="col-md-6 col-md-offset-3">
             <img src="~/Content/logo_bw_trans.png" alt="header" class="img-responsive text-center" />
        </div>
</div>
</div>

I found this, like almost all code snippets, on stackoverflow: http://stackoverflow.com/questions/18706544/jumbotron-alignment-issues

The Grid System

Bootstrap uses a popular CSS technique for laying out web pages. In bygone years, this was popularized by the creators of CSS frameworks like the 960, http://960.gs/, and BluePrint, http://www.blueprintcss.org/. From my perspective, these CSS frameworks became popular when UI developers realized the middle tier devs weren’t going to take the time to learn CSS and would keep using HTML tables to layout sites. So, they made CSS frameworks to try to help those same devs. Even then it took several years for frameworks like Bootstrap to make it easier. I believe Twitter’s Bootstrap may have grown up from HTML5Boilerplate http://html5boilerplate.com/, but, I don’t know.

The default template starts me off with a 3 section layout, but I only want 2. So, here is what they give us in the template:


<div class="row">
<div class="col-md-4">
        …content…
    </div>
<div class="col-md-4">
        …content…
    </div>
<div class="col-md-4">
        …content…
    </div>
</div>

Without understanding the grid system, you can quickly see there’s some logic to this. The class “col-md-4” seems to have a naming convention to it. It does and it is explained in detail here: http://getbootstrap.com/css/#grid. If you’re guess was that they all add up to 12, then you’re right! I want 2 columns, so mine is reduced to this:

<div class="row">
<div class="col-md-6">
        …content…
    </div>
<div class="col-md-6">
        …content…
    </div>
</div>

Now, I want four rows of content with two columns, so I’ll just copy and paste that a few times and fill in the content. Once that’s done I want a section at the bottom with a big button telling my users what to do. As you are dropping content and images onto the page, you might notice that your images don’t come out the size you made them.

So if we look at this piece of code:


<img src="~/Content/dojo-path.png" alt="header" class="img-responsive text-center" />

You can see the class “img-responsive.” This is one of those magic Bootstrap CSS3 classes that makes your website scale for smartphones or big websites. While you may be tempted to take this off, I advise you leave it and let Bootstrap do what it knows best.
At the end of the page I want an email sign-up form so I can keep in touch with my prospective customers. Email sign up forms are something that almost every website in existence uses, so, there should be very little coding here. But you searched through the Bootstrap website and didn’t find it. Luckily there’s another website, http://bootsnipp.com/, and if you do a quick search on sign up forms, you’ll see there are a few to choose from. I liked this one: http://bootsnipp.com/snippets/featured/sign-up-form.

Well, that’s enough to get your basic functionality so you can wire in some email server. But I’d like to go a bit further.
I already have an account with MailChimp, a popular mailing list website, http://mailchimp.com/, so let’s just see what it takes to wire up a signup form to a mailchimp auto-responder list. So, if you have a mailchimp account, you can get your basic code for a signup form and combine with some of the Bootstrap visual enhancements and end up with code like this:


<!-- Begin MailChimp Signup Form -->
<div id="mc_embed_signup" class="text-center">
<form action="http:/url" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
<input type="email" value="" name="EMAIL" class="span6" id="mce-EMAIL" placeholder="email address" required>
                <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;"><input type="text" name="b_31c7d2f366bf7abc8b70e0bf3_64a94b06cb" value=""></div>

                    <button type="submit" id="mc-embedded-subscribe" class="btn btn-default btn-lg">
                        <span class="glyphicon glyphicon-off btn-lg"></span> Subscribe
                    </button>
                
</form>
</div>
<!--End mc_embed_signup-->

This gives you a decent looking sign up like this:
vs2013-spa-backbonejs-03
Which works. And when you hit submit, it opens a new window from mailchimp for the user to confirm their information… which sucks.
What I really want is to use the MailChimp API so you can handle the request from within your application. Since we’re not using WordPress or Drupal, we need to do this with ASP.Net. Unsurprisingly, someone has already done this, and their GitHub project is here: https://github.com/danesparza/MailChimp.NET

So, let’s get to it. We’re going to install this into our project using the Package Manager Console [Tools–Library Package Manager–Package Manager Console] and type: Install-Package MailChimp.NET

That should get you a bunch of successful messages. Next I need my API Key from MailChimp. That’s covered here: http://kb.mailchimp.com/article/where-can-i-find-my-api-key essentially, it’s: primary dashboard–Account Settings–Extras–API Keys

Okay, you’ve imported the MailChimp API, you have your secret API key, now it’s time to go to your Controller and write your function.
Throw these imports into the top of the Controller:


using MailChimp;
using MailChimp.Lists;
using MailChimp.Helper;
Then add a function:
public void SubscribeEmail() {
            MailChimpManager mc = new MailChimpManager(&#8220;YourApiKeyHere-us2&#8243;);
            //  Create the email parameter
            EmailParameter email = new EmailParameter()
            {
                Email = &#8220;customeremail@righthere.com&#8221;
            };
            EmailParameter results = mc.Subscribe(&#8220;YourListID&#8221;, email);
        }

But that will wait till next time.

Django & Python Adventure Part 6

Today I am going to focus on incorporating JQuery into Django. If you’re following along this is material covered in chapter 6 of Ayman Hourieh’s “Django 1.0 Web Site Development”. The book was published in March 2009, so this will be an interesting test of what’s changed in JQuery in 21 months. It was common practice back then to download a copy of JQuery, but, today I believe utilizing CDNs (Content Delivery Network) is the preferred method.

The big players run these CDNs:
• Microsoft: http://www.asp.net/ajaxlibrary/cdn.ashx
• Google: http://code.google.com/apis/libraries/
• JQuery: http://code.jquery.com/

As an interesting aside, some developers worry about their applications being unable to connect to the CDN 100% of the time. If you want to read more on this, read this blog about getting around it:

http://code-inside.de/blog-in/2011/02/06/howto-jquery-hosted-cdn-version-local-fallback/

One final note, it’s best to use the .min version of whatever JQuery as it has been “minified” to work faster for you application.

We only want to reference this once, so we’ll drop it in the Master Page base.html:

The first thing I want to implement is AJAX-enabled search functionality on the bookmarks. The book suggests the best practice of writing the search form without AJAX (so it should work if the AJAX fails) and then add on the AJAX functionality. This is called “Progressive Enhancement” and it simply means we try not to leave anyone out of the fun.

First: bookmarks/forms.py:

Second: bookmarks/views.py
Notice the search is already implemented in Django. We’re calling it with Bookmark.objects.filter(). When we passit arguments, they must be in the format: field__operator. For a .Net programmer I still find the double underscore a little odd, but, whatever. There are other operators we could use aside from “icontains”. “contains”, “startswith”, and “exact” are some others. You can see this gives you similar power to a SQL SELECT blah FROM blah WHERE… Again, Django is handling the ORM code for us so this is what we’ll use to query the Model.

Third: implement templates/search.html

Fourth: update urls.py
(r’^search/$’, search_page),

Now test it out:

Very cool. We’ve now created our base search functionality with a few lines of code. Now we can add in the AJAX for browsers that can handle it (have JavaScript enabled).

First: update base.html to have a link to the search page:

Second: update the views.py

Third: update the search.html

Fourth: create the search.js file. This…

Again, we can test it. Notice this time the page does not reload. That is the JQuery AJAX call handling the manipulation of the innerHTML of the page for you:

AJAX accomplished! It’s a brand new day. Next time I’ll be doing something a little more advanced, but this was a good start.

Thanks,
Mike

JQuery Addon: Masked Date Input

Simple, elegant, and effective date inputs.  The following example is mocked up as an age verification, but just to show how to do custom validation.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="en">
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script src="http://cloud.github.com/downloads/digitalBush/jquery.maskedinput/jquery.maskedinput-1.3.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $(function() {
            $("#frm-verify-age").submit(function(){
                var age = 18; 
                var mydate = new Date($("#bday").val());
                mydate.setFullYear(mydate.getFullYear());
                var currdate = new Date();
                currdate.setFullYear(currdate.getFullYear() - age);
                if ((currdate - mydate) < 0){
                    alert("Sorry, only persons over the age of " + age + " may enter this site");
                    return false;
                }
                    return true;
            });     
            $("#bday").datepicker({
                buttonText: 'Choose a Date'
            });
            $("#bday").mask("99/99/9999");
        });
    });
</script>
</head>
<body>
<form name="frm-verify-age" id="frm-verify-age">
Birthdate <input style="background-color:#FFFFa0" type="text" id="bday" name="bday" size="12" />
<input name="frm-verify-submit" id="frm-verify-submit" type="submit" value="submit" />
</form>
</body>

Why is this better than just a normal JQuery Datepicker for me?
I’ve found that while developers and designers love visual date pickers, the common user will more often default to typing in their date. The date they are being asked for is often something they’ve memorized and typed in countless times: birthdates, hire dates, etc. So it is important to allow both user types to use the control and make sure both allow valid dates to be selected. Thus the mask functionality works very well.
It doesn’t solve all my validation. If they type it in I’ll still need to validate that they did not type in 99/99/9999. That can be done in the same space I’m checking age.

© Copyright Duke Hall - Designed by Pexeto