Simplicity is the ultimate sophistication. - Leonardo da Vinci

Twitter Bootstrap in Visual Studio 2010 with Chirpy and Dotless

For my latest side project, I decided to play around with ASP.NET MVC 4 and Twitter Bootstrap. Bootstrap is a  front-end toolkit open sourced by Twitter engineers, and comes chock-full of goodies like a responsive grid framework, LESS, jQuery plugins and CSS3 styling.

I’ve heard a lot about CSS compilers like Sass and LESS, but thought I would start with LESS first simply because I didn’t have to learn any new syntax. When using LESS in Visual Studio you essentially have three options for compiling:

  • Client-side (JavaScript) – Include the LESS.js script in your site and link directly to your .less files. The script will compile your LESS into CSS at runtime. Unfortunately, this means any errors will cause your CSS files to vomit on your live site.
  • Server-side (dotless) – Install via NuGet or GitHub. Compiles dynamically via ASP.NET HttpHandler or compiler .EXE. The compiler will convert your .less files into .css files.
  • Server-side (Chirpy) – Install via Codeplex (NuGet packages are out of date). This VS add-in not only compiles LESS files it also minimizes JS, CSS, LESS files. You name your LESS files with a .chirp.less extension and Chirpy will compile them in realtime. You can also use a .less.css extension so you can retain Intellisense for CSS.

Installing Twitter Bootstrap
I installed two NuGet packages, the Bootstrap, from Twitter package for the base files and then the Bootstrap, from Twitter Less Source package since I wanted to use LESS. It created /less and /images subfolders under the standard /Content folder in MVC, and loaded the appropriate files from Bootstrap. It added bootstrap.js and less.min.js to the /Scripts folder.

Installing Chirpy
Chirpy’s minify capabilities seemed like a good deal in addition to the LESS compilation so I installed the NuGet package. According to the Chirpy documentation and this blog post  from John Hoff (The Brain Donor) on using Chirpy, I set up file groups to “mash” the files together into single .css files which I could then reference from my site. I created a file called

mash.less.chirp.config

and put it in the /Content folder. Here’s what the file contained:

<root>
  <FileGroup Name="style.css">
    <File Path="less/bootstrap.less" />
    <File Path="less/responsive.less" />
  </FileGroup>
</root>

Bootstrap.less and response.less import and load all of the individual .less files included in Bootstrap, so they were the only ones I needed to include.

I also created a file to mash together my JavaScript files. I named the file

mash.js.chirp.config

and put it in the /Scripts folder. Here is what it contained:

<root>
  <FileGroup Name="site.js">
    <File Path="AjaxLogin.js" />
    <File Path="bootstrap.min.js" Minify="false" />
    <File Path="jquery-1.6.2-vsdoc.js" />
    <File Path="jquery-ui-1.8.11.min.js" Minify="false"/>
    <File Path="jquery.validate.min.js" Minify="false"/>
    <File Path="knockout-2.0.0.js" />
    <File Path="less.min.js" Minify="false"/>
  </FileGroup>
</root>

I then saved, and nothing happened. No magical .css or .js file appeared underneath my special chirp.config files. No errors. Even after I rebuilt the solution, it was eerily Chirpy silent. Something was wrong. So, since Chirpy was technically an Add-In, I went to the Add-Ins menu in Visual Studio and Chirpy was not there! I then poked around on the interwebs and realized the NuGet packages were NOT up to date. So I went ahead and downloaded the .vsi file from Codeplex and installed Chirpy the old-fashioned way.

Almost immediately, my compiled .css file appeared, along with a whole host of CSS errors from the Bootstrap LESS files. I turned to Google, and it led me to lo and behold, another post from John Huff about Twitter Bootstrap woes with Chirpy. Apparently the Chirpy compiler does not like the Bootstrap LESS. His recommended solution was to use the dotless library to compile the LESS files and then use Chirpy to mash and minimize the files.

Installing dotless
So I installed dotless via NuGet. Following the instructions in Huff’s blog post, I added two calls to the dotless .EXE compiler in my MVC project’s Pre-build events (Project -> Properties -> Build Events tab):

"$(SolutionDir)packages\dotless.1.3.0.0\tool\dotless.compiler.exe" 
       "$(ProjectDir)Content\less\bootstrap.less" 
       "$(ProjectDir)Content\css\bootstrap.css"

"$(SolutionDir)packages\dotless.1.3.0.0\tool\dotless.compiler.exe" 
       "$(ProjectDir)Content\less\responsive.less" 
       "$(ProjectDir)Content\css\responsive.css"

I included quotations around both the .exe and the source and target file paths because my solution and project directories both contain spaces in the path folder names. I created a /css subfolder in my /Content directory to hold the generated .css files. After doing an initial build, I navigated to the /css folder, saw the two new files (with shiny CSS culled from all those Bootstrap LESS files), and added them to my VS project.

Updating Chirpy
I then updated my mash.less.chirp.config file to mash together the newly compiled .css files instead:

<root>
  <FileGroup Name="style.css">
    <File Path="css/bootstrap.css" />
    <File Path="css/responsive.css" />
  </FileGroup>
</root>

And voila, my style.min.css file appeared within a few seconds after saving and building the project, and it included the minified CSS from both .css files! I then updated my site template to use “style.min.css” as my stylesheet.

Sure, it would have been nice to only have to use Chirpy, but since I really wanted to use Bootstrap for this project, and for some reason Bootstrap and Chirpy just don’t get along at the moment, this is a perfectly fine workaround for the time being.

DevConnections 2012: Day Two

Here are my notes from Day Two of the DevConnections conference. A particular highlight of the day was the Women in Tech luncheon! 100 women attended and a four woman panel of conference presenters answered questions from the crowd.

Morning Keynote: Windows Azure – Scott Guthrie, Microsoft

  • He showed a short video of one of their data centers; the servers are literally stored within shipping containers stacked on top of one another. When enough servers in the same container fail, they’ll replace the container with another and fix the faulty servers. Since everything can be done remotely, they don’t need a large staff. I think he said they have 1 data center employee for every 10,000 servers.
  • Microsoft Patterns & Practices group has modules you can install to help you monitor CPU and consumption with your Azure account.
  • “Extra Small” instance = 1/4 core
  • Your two VM instance are spun up on separate servers, separate racks, separate routers, etc. for fail-safe.
  • Production vs. Staging in Azure – when you publish your staging instance to production the production VM automatically becomes your staging VM, in case you need to rollback.
  • Messaging services allow you to move from tightly coupled apps with high chance of cascading failures to a loosely coupled app. Example was a storefront integrated with shipping services. If the shipping services fail, the Order Queue can still accept orders until it comes back online.
  • Scott did a demo with a MVC 4 mobile app that accepted text strings, sent them to the Service Bus Queue, and then were pulled from the queue and displayed on a local desktop app checking for new messages continuously. He also demo’ed a hybrid relay app – cloud app that pulled from Service Bus Relay which pulled from local WCF service.
Visual Studio Leadership Unplugged – Jason Zander, Brian Prince, moderated by Scott Hanselman
  • Visual Studio 11 is not the final name – the branding is coming…
  • They are putting out less milestones so don’t expect a bunch of additional releases between the Beta and release.
  • Feedback about the new UI has centered on three areas: 1) Color – they removed some of the color, meant to drive the eye toward code and text. 2) Contrast – they toned down a lot of the color, though some of it now looks grayed out, they will continue to tweak it. 3) Typography – working on fonts, spacing/kerning, etc. to bring the product more in line with Metro style.
  • Same level of theming support as 2010.
  • When determining what features will go in what SKU, they look to release a reasonable end-to-end scenario, one that flows and makes sense, instead of being a random collection of features. Also, what engineering trends they are seeing. For example, VS11 incorporates greater emphasis on DevOps and Agile.
  • Don’t see offering “ala carte” features for Visual Studio in the near future. Engineering and practical challenges. Product designed to work together as total solution. They are exploring the possibility of renting/leasing features in the cloud.
  • Intellitrace will again be offered only in Ultimate.
  • Developers who have VS license at work should read license language, because they can probably install a copy of the software at home.
  • The Visual Studio team does indeed use the TFS Scrum tools in-house. They have a “pioneer team” who are the first to use the newest versions, before it is rolled out to the rest of the team. There are currently two feature teams who are using the cloud version, including the cloud Build Service.
  • There will be a more rapid update cadence with VS11. Instead of a major release every 2 years with a Service Pack in between, they hope to to roll out more features via Visual Studio updates and gallery. As part of the new release, they have invested a lot into updating the service so they have the ability to push updates to most of Visual Studio.
  • Ultimate Architect has been improved so it can scale on a much greater level and handle larger projects.
  • T4 editor – no Intellisense or syntax highlighting, but Brian and Jason thought it was a good idea. They will look into the syntax highlighting; the intellisense will be more involved.
  • PowerTools – more rapid release cycles. Want to be responsive to customers and community demands. All existing PowerTools will work with VS11, except for the ones rolled into the product itself.
Techniques, Strategies and Patterns for Structuring JavaScript Code – Dan Wahlin, Wahlin Consulting
  • JavaScript prone to spaghetti code, so closures gives us a way to emulate classes.
  • Closures get us “ravioli code”: data encapsulation, decoupled code, separation of concerns.
  • Douglas Crockford, author of JavaScript: The Good Parts, says: a variable/parameter returned from a nested inner function within a closure will remain in scope.
  • The closure function then behaves like a class: it preserves state.
  • Object literals are a way to store name/value pairs in JSON & AJAX operations.
  • To declare a namespace in JavaScript: var myNamespace = myNamespace || {};
  • Use the namespace to scope variables.
  • Self-invoking functions create a singleton called when page first loads.
  • Three main patterns: Prototype, Revealing Module, Revealing Prototype
  • Prototype Pattern: Constructor, Prototypes can be overridden
    • Benefits include modular, reusable code, JS inheritance, move variables & functions out of global namespace, functions load into memory once, ability to override functions. Cons include “this” keyword craziness & constructor separate from prototype definition.
    • Rule: If you need to use the “new” keyword, capitalize your variable name. If not , use lowercase.
    • Prototype only gets called one time; the variables and values will not be unique to each instance.
    • The “this” keyword is required for every instance variable, which can get overwhelming.
  • Revealing Module Pattern:
    • Benefits include “modularize” code into reusable objects, variables/functions fall out of global namespace. Cons include functions duplicated across objects in memory and not easy to extend. Some people also think private members/functions do not belong in JavaScript.
  • Revealing Prototype Pattern:
    • A combination of Prototype and Revealing Module Patterns.
    • Best of both worlds – you get public/private members and ability to override functions.
  • http://tinyurl.com/CleanJS
HTML5 and JavaScript Fundamentals with MVVM & KnockoutJS – John Papa
  • Knockout.js is a JS library that gives you rich client-side interactions, MVVM-like pattern, and web browser support. Separates behavior and structure.
  • Knockout is 3 steps:
    • Declarative Binding to HTML elements – “data-bind=”
    • Create Observable – ko.observable(). If observable value changes, KO will notify the UI.
    • Bind the ViewModel to the View – ko.applyBindings(viewModel). If you want one time binding, you don’t need “ko.observable”. If you want two-way binding, it’s required.
  • Without data binding, you have to manually push and pull JSON values from the source object to the target and vice versa. jQuery can assist, but it requires a lot of manual coding.
  • Now we can use Observables:
    • Wrap property in observable function => similar to iNotifyPropertyChanged
    • Automatic two-way binding: both sides updated when value is changed
  • Also check out “Subscribable”
  • For computed properties:
    • Define the function to evaluate the computed value, and use it for binding.
    • When its observable changes, it notifies that the change occurred.
  • Containerless Control of Flow Bindings
    • No need for script template. No unnecessary HTML elements just to use for flow (like div tag). Moves binding logic outside of HTML elements.
    • You instead use HTML comment-based control flow syntax.
    • <code><!– ko with: blah –> do stuff here <!– /ko –></code>
AppFabric Caching: How It Works and When You Should Use It – Shy Cohen, IDesign
  • Data Categorization
    • Reference Data – read-only mostly, changes slowly. Like user profile photos, product descriptions.
    • Resource Data – read-write, concurrent. Like number of units in stock, online survey results.
    • Activity Data – Read/write, user specific, not concurrent. Like shopping cart items, individual survey responses.
  • Determine what to cache
    • Categorize your data and cache – where, how long, explicit deletion.
    • Cache the right data – output cache is not always efficient. Create meaningful subsets used independently.
  • Use efficient caching strategy
    • Balance number and size of objects. Cache the smallest objects possible. Minimize round trips. Measure performance to determine optimal point.
    • Keep data coherent – don’t break down large objects into multiple smaller ones if you can’t reconstruct them.
  • Assume “best effort” caching
    • Your app must be able to withstand the cache being unavailable and the cached data being unavailable.
    • Don’t store critical/important information only in the cache; it’s costly to reproduce.
  • Craft your keys wisely
    • Minimal but complete set of unique identifiers for data.
    • Keys consume space in the cache.
  • Automatic Object Removal
    • Explicit Deletion – remove manually.
    • Expiration – staleness, proactively remove. Hint for system on how long to keep object.
    • Eviction – reactively remove due to low memory.

Visual Studio Unplugged [pic]

image

Visual Studio Unplugged: Q&A with Brian Prince and Jason Zander

DevConnections 2012: Day One

Today was the first full day of the DevConnections 2012 conference, held in Las Vegas. Since I tend to get overwhelmed by all my conference notes and materials when I return home, I thought I would post the interesting bits from the sessions I attended on Day One. This is by no means a complete summary of all the session material, just things I found noteworthy and want to follow-up on later.

Morning Keynote: Connected Devices, Continual Services – Jason Zander, Corporate Vice President, Visual Studio (Microsoft)

  • 90% of Visual Studio 11 development teams use Scrum. Approximately 1,000 developers and they have set half the milestones as the last version, with no loss in productivity.
  • New “Page Inspector” feature  - brings IE “Developer Tools”-like functionality  into the Visual Studio environment. Lets you hover over sections of page in Design view and see highlighted sections in code, CSS, JS, etc. all on one screen. I might actually use it instead of Firebug. Maybe. :)
  • Windows 8 emulator was pretty cool and sexy.
  • Expression Blend 11 will now have development environment for HTML, previously missing.
  • PowerPoint storyboarding, bringing Balsamiq-like mockup functionality to PowerPoint.
  • Brian Keller demo’ed the new feedback functionality baked into VS11: can request/give feedback, take screenshots, edit screenshots, add comments, etc.
  • Intellitrace diagnostics added to Systems Center Essentials. Our team has been moving toward greater logging/monitoring capacity, starting with the third-party tool Gibraltar. Having Intellitrace data on production apps would be very useful.
  • Visual Studio Ultimate Feature Packs

What’s New in  SQL Server 2012 Reporting Services – Chuck Heinzelman, Microsoft

  • PowerView – new UI design experience and data visualization tool. Self-service data exploration. Requires Tabular BI Semantic Model and SharePoint integrated mode. Uses Silverlight, requires IE or Firefox. PowerView reports can be embedded into PowerPoint; if connected to server/data source, can interact with report within PowerPoint slide.
  • Data Alerts – can send email to users upon report conditions. Report feed is simply an Atom feed, so you can subscribe to it. Schedule it to be checked down to the minute and/or when results change. Runs as background service on SharePoint. Requires stored credentials. Email will include link to launch report. Only available if report is running in SharePoint integrated mode.
  • SharePoint integrated mode should run faster, though still not quite on par with Native mode.
  • Designer for VS2010 can support reports from 2008 and up.
  • SQL Azure – SSRS is now available as a service on Azure. Operational reporting against SQL Azure data. Renders reports in ReportViewer controls. Can develop within Visual Studio using SQL Server Data Tools.
  • When Chuck asked the audience who was using SQL Azure, no one raised their hands. He seemed surprised.
  • SQL Server 2012 Early Adoption Cookbook

 Async: New Feature for Responsive Programming in Visual Studio 11 and .NET 4.5 – Lucian Wischik, Microsoft

  •  Born from Microsoft Research, team has spent two years bringing it to developer fruition.
  • The UI message pump is key to async.
  • With async, the message pump spins continuously like usual, but is not blocked by long-running processes.
  • The Await keyword is like a placeholder for tasks. It helps the program remember where it left off, before it returns to the caller. When the task process finishes, it notifies the message pump, and continues execution at the placeholder.
  • Repercussions: you will need to disable UI elements/methods to prevent multiple invokes. It is easy to deadlock when you mix sync and async code, so don’t do it!
  • Tasks are a promise of future results.
  • Async functions are required to return tasks. As a result, only top level callers can have async subs; otherwise, you must use functions.
  • Console apps: since there is no message pump, calls are passed to the thread pool. Returned tasks are posted to another thread. This is not parallelism, just different threads. As a result, you cannot use ThreadLocal storage.
  • CancellationTokenSource – cancel requests no longer needed.
  • The UI thread is like a single waiter (thread) serving multiple  customers (tasks).
  • Asynchrony and concurrency don’t need multiple threads.
  • No multiple threads = no race conditions!

Using ASP.NET MVC 4, Web API, jQuery Mobile to Create an Engaging Web App Targeting Modern Tablets and Mobiles – Scott Hanselman, Microsoft

  • Users accessing web via mobile only: US-UK: 25%; China: 30%; India: 59%; Egypt: 70%.
  • If you do nothing else to make your site mobile friendly, add the viewport meta tag.
  • To fix your site on the client: custom CSS, media queries, adaptive rendering (responsive design).
    • Scott demo’ed his own blog and how it uses adaptive rendering, including the “opt group” syntax to handle his main navigation menu. Also has a post on how to make embedded YouTube videos fluid and responsive.
    • Mediaqueri.es - Gallery of cool responsive designs, with four different breakpoints for each site.
    • 51degrees.mobi - open source database of devices along with dpi, width, etc. You can query the database for your custom CSS.
    • ImageResizer – NuGet package provides API for manipulating images. Works server side.
  • To fix your site on the server:
    • Custom mobile views using display modes.
    • Mobile UI frameworks: jQuery Mobile comes included with MVC, but Sencha Touch, Kendo UI are others.
    • Electric Plum – mobile device simulator.
    • MobileFirst movement – design for mobile first, desktop second.
    • GetSkeleton – Boilerplate HTML/CSS template for responsive design.
    • 320AndUp – Another boilerplate template.
    • In the global.asax, use the DisplayModeProvider to add new “displayModes” for different devices.
Fundamentals of Windows 8 XAML Metro Style Apps – John Papa
  • Unlike desktop apps, Metro apps use the same WinRT APIs whether they are XAML or HTML/CSS based.
  • Use the skillset you have, whether it’s XAML or HTML. Both have same tooling, same WinRT.
  • If you’re a XAML developer, you’re already a Win8 developer.
  • Windows 8 is a content-centric UX: it’s about what you don’t see, what’s left out: extra chrome, extraneous navigation, etc.
  • File types/templates are all about consuming and displaying data: grid groupings, split applications, etc.
  • Windows 8 has new namespace, new controls.
  • Handling events is about handling the Touch APIs: pointers, gestures, and manipulations.
  • WinRT consolidates mouse, stylus, and touch inputs; handle via Case statements?
  • Styling  is like painting a wall from blue to red.
  • Templates are like changing a wall to a window.
  • Three ways to use animations: use baked in animations, roll your own custom animations, and use the Animations library.
Evening Keynote: One ASP.NET – Scott Hanselman, Principal Program Manager, Community Architect for Web Platform & Tools (Microsoft)
  • One ASP.NET – feedback has been that the New Project dialog in Visual Studio is like a frightening fork in the road, and once you make a decision you are stuck with it forever. Team wants to change that perception.
  • MVC 4 comes with Modernizr, jQuery, jQuery Mobile. HTML5 requires polyfilling for browsers that don’t support those elements yet.
  • jQuery Intellisense in Visual Studio 11
  • Scott Hanselman was joined by Scott Hunter and Scott Guthrie to announce the “open-sourcing” of ASP.NET MVC, Razor, and Web API on Codeplex. http://aspnetwebstack.codeplex.com
  • Miguel de Icaza was the first “third-party” to request a pull on the project. Watched it live during presentation. :)
  • Contributors will have to submit an agreement, stating that the code is theirs (and not their employer’s, etc.)
  • All code will go through same review, unit testing, security testing, etc. as code written by Microsoft team. Same standards applied to other open source project incorporated into ASP.NET MVC: jQuery, Modernizr, JSON.NET.
  • Subscribe to project’s RSS feed to follow check-ins.

Visual Studio Continuous Value Delivery

image

Lots of new process goodies baked into Visual Studio 11.

Jason Zander Keynote [pic]

image

Jason Zander keynote this morning at DevConnections.