Bootstrap + The Asp.Net Mvc Framework: Building Your Site on Bootstrap

Looking for a quick overview of Bootstrap and what it can offer your project?  Add a little flavor to your Html with easy-to-apply CSS and JavaScript components. Here’s how!  This intro video uses Visual Studio, the Bootstrap NuGet package and the Asp.Net Mvc Framework to build out a little eye candy.

Bootstrapping your Asp.Net MVC Projects

This is quick and dirty! Fear not the Package Manager Console and you, too, can conform to the awesomeness of Web 2.0.  The UXiness of it, the CSS3isms, the jQuery, oh, yes, the jQuery!

A Note on Versions

Twitter.Bootstrap is evolving and changing quickly. As such, I highly recommend viewing these posts as guidelines and inspirations that you can apply in your projects. Keep in mind that there have been several significant updates to the library since I started this series and I can’t possibly keep all the videos up to date. If you’d like me to refresh one, please let me know!

That said, the topics I’m going to cover include (links to completed ones):

  1. Installing Bootstrap (this post) 
  2. Setting up a template
    1. The Completed Template
  3. Using Twitter.Bootstrap.Mvc4 as a kick-starter
  4. Reviewing and integrating the plugins, including:
    1.  Carousel  <li>Typeahead  <li>Alerts  <li>Buttons
        1.  [Say no to Checkboxes](http://oldblog.jameschambers.com/blog/bootstrapping-mvc---say-no-to-checkboxes)! <li>Collapse  <li>Modals  <li>Dropdowns  <li>Popovers  <li>Togglable Tabs (hey, that’s not even a word!)  <li>Tooltips  <li>Scrollspy <li>Leveraging coolness in the Mvc Framework to make Bootstrap even more strapping.&nbsp; See what I did there? ![Smile](http://oldblog.jameschambers.com/Media/Default/Windows-Live-Writer/Bootstrapping-Asp.Net-Mvc_FC7A/wlEmoticon-smile_2.png)
    1.  [Controlling Template Rendering](http://oldblog.jameschambers.com/blog/bootstrap-mvc-controlling-template-rendering)  <li>[Fixing the Navbar and Starting Authentication](http://oldblog.jameschambers.com/blog/bootstrap-mvc---fixing-the-navbar) 
    

If you want to have a look at the code I’m developing as I write this, be sure to check out the repo on GitHub: https://github.com/MisterJames/BootstrappingMvc

Stay tuned and I’ll keep this page updated as I go.

A Great Time at Prairie Dev Con

It’s amazing how great a conversation can be had at a conference.  The conversation flows through topics, traversing different folks from different walks and never really ends until you check out of the hotel to return home.  Prairie Dev Con 2011 was full of rich conversation with interesting people, enthusiastic about technology and excited about a brief window where they could share cool information about the tools and tech they work with on a regular basis.

Thanks especially to everyone who came out to my sessions; as you start to work with MVC or NuGet I would love to hear how you make out and the kinds of things you do with your projects. And if you have any questions, please feel free to drop me a line via Twitter, here on my blog or via email.

See you all next year at PrDC12!

Regular Expressions in Visual Studio - Turning A Querystring into a Class

This post will help you create a class that can be used in MVC Framework model binding, but is also a good demonstration of the Regular Expression support in Visual Studio’s Find & Replace feature.  The class created can be used with PayPal’s IPN notifications.

I just started working with the PayPal “Instant Payment Notification” API again. I wanted to use the model binding capabilities of Asp.Net MVC, so the first task was to extract the querystring variables and make properties out of them.  The sample querystring from the PayPay documentation for IPN is as follows:

mc_gross=19.95&protection_eligibility=Eligible&address_status=confirmed&payer_id=LPLWNMTBWMFAY
&tax=0.00&address_street=1+Main+St&payment_date=20%3A12%3A59+Jan+13%2C+2009+PST&payment_status=Completed
&charset=windows-1252&address_zip=95131&first_name=Test&mc_fee=0.88&address_country_code=US&address_name=Test+User
&notify_version=2.6&custom=&payer_status=verified&address_country=United+States&address_city=San+Jose
&quantity=1&verify_sign=AtkOfCXbDm2hu0ZELryHFjY-Vb7PAUvS6nMXgysbElEn9v-1XcmSoGtf&payer_email=gpmac_1231902590_per%40paypal.com
&txn_id=61E67681CH3238416&payment_type=instant&last_name=User&address_state=CA&receiver_email=gpmac_1231902686_biz%40paypal.com
&payment_fee=0.88&receiver_id=S8XGHLYDW9T3S&txn_type=express_checkout&item_name=&mc_currency=USD&item_number=
&residence_country=US&test_ipn=1&handling_amount=0.00&transaction_subject=&payment_gross=19.95&shipping=0.00

As you can see, it’s a bit of a mess.  It’s all on one line (if you copy and paste their sample) and you will need to break out the key-value pairs. This is made especially easy in Visual Studio, if you know a few tricks.

Start by adding a blank Text Document to your project and then paste in the IPN querystring provided by PayPal.  Here are the steps to build the class:

  1. Press CTRL + H to invoke the replace dialog. The first replace operation is to search for & and to replace with \n. Make sure you have “Use Regular Expressions” enabled in the options pull down.  We’re simply searching for an ampersand character and replacing it with a new line.
    image
  2. Press the button for Replace All and it’ll break everything on to separate lines for you.
  3. Next, search for =.* and replace it with nothing. This blanks out everything from the = sign on.
  4. Finally, we need to capture the text on the entire line. I had a couple of hiccups trying to get the capture working in Visual Studio, but this worked for me:
    1. Search for: ^{.*}$
    2. Replace with: public string \1 { get; set; }
      image

 

^ is a character for “start of line” and $ is the character representing “end of line”. The {.*} bits in between captures everything else on the line into a numbered group. Captured groups are numbered and start at 1.  In our replace statement, we’re basically writing out properties and using the \1 to insert the property name that we captured in the curly braces.

Note: at the time of this writing, I had to use VS2010 to do this last operation because VS11 Beta is not really giving the regex a lot of love.

When you’ve completed all those bits, you’ll have a bunch of properties ready to paste into a class:

image

If you’re interested, this is the class you need as an action parameter in an Asp.Net MVC project to capture the querystring parameters provided by the PayPal Instant Payment Notification (or IPN):

    public class PayPalIpnRequest
{
public string mc_gross { get; set; }
public string protection_eligibility { get; set; }
public string address_status { get; set; }
public string payer_id { get; set; }
public string tax { get; set; }
public string address_street { get; set; }
public string payment_date { get; set; }
public string payment_status { get; set; }
public string address_zip { get; set; }
public string first_name { get; set; }
public string mc_fee { get; set; }
public string address_country_code { get; set; }
public string address_name { get; set; }
public string notify_version { get; set; }
public string custom { get; set; }
public string payer_status { get; set; }
public string address_country { get; set; }
public string address_city { get; set; }
public string quantity { get; set; }
public string verify_sign { get; set; }
public string payer_email { get; set; }
public string txn_id { get; set; }
public string payment_type { get; set; }
public string last_name { get; set; }
public string address_state { get; set; }
public string receiver_email { get; set; }
public string payment_fee { get; set; }
public string receiver_id { get; set; }
public string txn_type { get; set; }
public string item_name { get; set; }
public string mc_currency { get; set; }
public string item_number { get; set; }
public string residence_country { get; set; }
public string test_ipn { get; set; }
public string handling_amount { get; set; }
public string transaction_subject { get; set; }
public string payment_gross { get; set; }
public string shipping { get; set; }

}</pre>

Removing Tracked Files After Adding A Rule to .gitignore

As I learn some of the workings of git in the normal flow of daily use, I struggled for a few minutes this afternoon trying to scrub a directory of DLLs that had been committed to a repo.  These files were previously tracked, so even though the rule was correct, git wasn’t dropping tracking to the files.

Here’s the fix from the mouth of the horse:

.gitignore

If you create a file in your repo named .gitignore git will use its rules when looking at files to commit. Note that git will not ignore a file that was already tracked before a rule was added to this file to ignore it. In such a case the file must be un-tracked, usually with git rm --cached filename

There ya be.  So, create your rule, rm the files and then do your git status to see the changes.  The removing them from tracking is also a change that will have to be committed.

Cloudy With a Chance of Mobile: Building Our Data Model & API

Interested in having a web site that supports user-specific data? Perfect, use Asp.Net and the built in membership providers. Want to put it in the cloud? Sweet, jump on the Azure bandwagon. Want to easily define your data model and store it? No worries, EF Code First will make you cry, you love it so much. Want to access that data from Windows Phone? Well, my friend, you’ve come to the right place. If you want to follow along from the beginning, please check out the first post in the series.

With my projects roughly set up the way I’d like them to be I can now start building my data model using Entity Framework or “EF”.  I’ll use the model definition to quickly scaffold some UI and add some data to my project.

I will then expose that data via the new Web API available in Mvc 4.  Though I have two solutions set up, I’ll only be working in the Mvc 4 project for this tutorial.  A reminder that if you’re opening the IDE to follow along after a break you’ll need to open it up in Administrator mode for the Azure environment to run correctly.

Our Data Class

To keep things simple I’m going to use a single entity class – and ultimately a single table – for this exercise.  In the Mvc 4 project, use the Solution Explorer to locate and then right-click on the Models folder to add a new class called PhoneNumberEntry.  The class will look like the following:

    public class PhoneNumberEntry
    {
        public int PhoneNumberEntryId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string PhoneNumber { get; set; }
        public string UserName { get; set; }
    }

Hey, don’t judge. I said I was keeping it simple. Winking smile

Next, I need to tell EF how to create the database, namely, I have to tell it what tables to create and of which entity. I do this through inheritance and attributes on our classes.  You can put this definition in the same file as the PhoneNumberEntry class.  Again, it’s very light weight.

    public class ContactContext: DbContext
    {
        public DbSet<PhoneNumberEntry> PhoneNumberEntries { get; set; }
    }

Perfect, now I’m rolling. To create the UI, I’m simply going to use the tooling that’s built into the MVC Framework through Visual Studio 2010. In order to fully leverage this, I need to compile my classes so that the IDE can reflect on my project and show me a list of them.  I like to use the keyboard shortcut Shift + Ctrl + B to build.

Building the Views

With my project compiled, I right-click on the Controllers folder in Project Explorer and select Add –> Controller. I name my controller appropriately, select my PhoneNumberEntry class and name a new Data Context Class.  I choose the Controller with read/write actions and views, using Entity Framework as the template.

image

The tooling builds my controller and scaffolds out my views for me.

I only want members who have registered to create entries, and I want to each user to have their own list. I created a UserName property on my model, so I now need to deal with that field on my own. In my Create and Edit views, I remove the UserName field. Here’s an example of what that HTML looked like before I removed it:

image

With that out of the way (in both Create and Edit) I need to update my controller accordingly. I open PhoneNumberEntryController in the Controllers folder and add the Authorize attribute to my class.

    [Authorize]
    public class PhoneNumberEntryController : Controller
    {
        // ...rest of class here
    }

By attributing the controller in this way (at the class level), I am telling the Asp.Net runtime that any user who accesses any action on this controller needs to be logged in using the authentication scheme of the site.  Now, all users who try to navigate to any of my Phone Numbers pages will first be prompted to log in.

image

Driven By the Logged in User

Next, I want to make sure that the user only ever sees the phone numbers that they create.  The index method needs to be adjusted to only return the appropriate entries.

    public ActionResult Index()
    {
        string username = User.Identity.Name;

        var phoneNumbers = db.PhoneNumberEntries
            .Where(p => p.UserName == username)
            .ToList();

        return View(phoneNumbers);
    }

In the Create and Edit methods decorated with the HttpPost attribute (these are the methods that accept the PhoneNumberEntry parameters from the form) I add a bit of code to capture the user’s login name and store that in the model.

    [HttpPost]
    public ActionResult Create(PhoneNumberEntry phonenumberentry)
    {
        string username = User.Identity.Name;
        phonenumberentry.UserName = username;

        if (ModelState.IsValid)
        {
            db.PhoneNumberEntries.Add(phonenumberentry);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(phonenumberentry);
    }
> **Important note**: There are many more security considerations to take and I am only demonstrating some bare minimums. In a real-world scenario you would use a repository outside of the controller and would do the appropriate checks to protect your data at various levels of your project. Particularly, any code to retrieve or modify the data should have checks in place to ensure the user is authorized to view or modify the resource in question.  As an exercise to the reader, work through the PhoneNumberEntryController and firm up the user access/rights to a better degree. Everything should be set here to capture some data, but I want to be able to easily access these bits of UI.  I open up my _Layout.cshtml file, located in Views\Shared in the Solution Explorer and modify the snippet of code that creates the menu elements.  When finished, it looks like so:
    <nav>
        <ul id="menu">
            <li>@Html.ActionLink("Home", "Index", "Home")</li>
            <li>@Html.ActionLink("About", "About", "Home")</li>
            <li>@Html.ActionLink("Phone Numbers", "Index", "PhoneNumberEntry")</li>
            <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
        </ul>
    </nav>

The LI elements are formatted through the default site template and the UL is used as a wrapper to generate the menu at the top of the page. The ActionLink helper method renders an anchor tag for the specified controller/action.

Getting Some Data In There

Before I move onto the API portion of this exercise, I press F5 to run my site and use the newly created Phone Numbers menu to get at the UI the framework generated for me.  I add several entries as you can see below.

image

Now, I want to go one step further. This is about accessing the data for a specific user, so I want to have some other data in there as well to prove out that we can isolate the data and make use of the Authentication providers in Asp.Net.  I create another user and add more entries as I did above, and you can see in the database now how there is data in there for two users.

image

I now have data specific to a couple of users and can build out the service piece.

Cutting a Web API Controller

This piece is really easy and uses the tooling and templates from the MVC Framework.  I add a new folder called Api to my Controllers folder and then right-click on the Api folder and select Add –> Controller.  I name it PhoneNumberEntryController and select the Empty Api controller as the scaffolder. Even though it’s the same name, it ends up in a different namespace so everyone’s happy.

image

Much like the controller returning a view, I want the ApiController to only allow authenticated requests, and I want the method to return only phone numbers for the current user.

    [Authorize]
    public class PhoneNumberEntryController : ApiController
    {
        private CloudyWebSiteContext db = new CloudyWebSiteContext();

        public ICollection<PhoneNumberEntry> Get()
        {
            string username = ControllerContext.Request.GetUserPrincipal().Identity.Name;

            var phoneNumbers = db.PhoneNumberEntries
                .Where(p => p.UserName == username)
                .ToList();

            return phoneNumbers;

        }
    }

There’s one more thing I want to do: I want to suppress the Xml formatter that is on by default in WebAPI.  By turning it off, the only remaining default serializer is Json.  Glenn Block shows us the most performant way to do this in our Global.asax’s Application_Start menthod:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

People. We are now awesomely rocking.  I will coin the term “awesrocking” because of the awesomeness here.

imageTesting Out the Api

This is the part where I could start to hit some roadblocks if I didn’t have the right tools. I love Fiddler and use it first whenever I’m, uh…fiddling around, but I can’t use Fiddler to poke around the API because I need a user to see what I’m doing and authentication is forms based in this context. I can’t use IE efficiently because every time I get a Json document returned it prompts me to open the file of an unknown file type. I could use Notepad here (or a registry hack), I know, but it’s a pain and I like to see my data all nicely formatted Winking smile.

FireFox to the rescue, along with a little helper plugin called JsonView.  In Visual Studio 11 this will be even easier because I can choose the browser to launch, rather than launching a separate browser or setting the OS default.  Regardless, I run the app in FireFox, log in to my site, then I hit http://127.0.0.1:81/api/phonenumberentry to see the data. JsonView takes over and I see my phone numbers as we expect.

You can see the result in the image to the right.

Wrapping Up and Next Steps

Okay, here’s the quick breakdown for the steps we have taken to this point:

  1. Added our model (class)
  2. Added our data context
  3. Scaffolded our views
  4. Secured our views
  5. Tied the data entry and loading to specific users
  6. Added some data
  7. Created a Web API controller
  8. Secured the controller and started returning the correct data

 

With these things in place, I can now start work on my phone client. Our project is already set, so we can get to the heavy lifting right away! Stay tuned for the next post where I’ll get the phone client lined up to consume the data and display it.  Later on we’ll talk about some things we can do to better improve the code and get us closer to best practices.

Cloudy With a Chance of Mobile: Mvc Framework, Windows Azure and Windows Phone

Interested in having a web site that supports user-specific data? Perfect, use Asp.Net and the built in membership providers. Want to put it in the cloud? Sweet, jump on the Azure bandwagon. Want to easily define your data model and store it?  No worries, EF Code First will make you cry, you love it so much. Want to access that data from Windows Phone? Well, my friend, you’ve come to the right place. I will take you from start-to-finish in creating an application that encompasses all of these pieces:

  1. An Asp.Net Mvc 4 web site with a Web API controller to serve up some data. This data will be protected by the built-in Asp.Net membership providers.
  2. A local Service Deployment using the Windows Azure SDK.  This will be how we host the Mvc web site & Web API.
  3. A Windows Phone 7.1 client that accesses the protected data using the Asp.Net membership provider.

 

Getting Tooled Up

We need to have the right kit in place to make this happen.  Please make sure you have the tools below if you want to follow along:

  1. Visual Studio 2010 with SP1 installed
  2. An internet connection.  Oh, wait…
  3. The latest Azure bits downloaded and installed
  4. The Windows Phone 7.1 SDK setup on your machine
  5. Laurent Bugnion’s MVVM Light Toolkit

 

Bootstrapping the Projects

I use two instances of Visual Studio to develop in scenarios like this as we’ll need elevated privileges to run the Compute Emulator for Windows Azure and I like to be able to leave my web project running while I work on my Windows Phone client application.

Launch the first IDE in Adminstrative mode.  Create a new project from the “Cloud” templates and select Windows Azure Project.

image

Next, we’re prompted to add our new role project, we’ll select MVC 4:

image

Finally, we’ll pick Internet Application from the available templates in the Mvc 4 templates:

image

Now, simply run the application by pressing F5.  Windows Azure needs a moment to start up, then you’ll see the web site launch. Proceed to register in the site so that you have a valid log in.

image

Start your second IDE up, pick File –> New Project and navigate to the Silverlight for Windows Phone templates. Pick the vanilla Windows Phone Application project, and when you’re prompted be sure to target Windows Phone 7.1. 

image

You can quickly run your phone app to get your emulator running by pressing F5.

Next Steps

At this point, though we’re not doing too much that is interesting, we have our two core projects up and ready to go. We created an Mvc 4 web role inside our Azure project and created a user account that we will late use to log in from the phone.  Next, we created the shell of our Windows Phone project that will hold a simple UI to display data that we load from the Mvc site.  With very little effort, we have our two major components in place and will be able to quickly advance our project.

Stay tuned for the next article where I will show you how to define a simple model and expose it via Web API.