Bootswatch and Gulp as a Stepping Stone for Your Theme Switch Feature

This short blog posts shows you a way of combining bootswatch and gulp together to have an easily useable theme switching support for your web application.
2014-10-15 17:06
Tugberk Ugurlu

Bootswatch has awesome themes which are built on top of Bootstrap. To integrate those themes to your web application, you have a few options. One of them is to build the css file by combining bootstrap.less file with the less files provided by bootswatch. This is the way I chose to go with. However, what I actually wanted was a little bit more complex:

  • Install bootswatch with bower and have every theme available for me to use.
  • Compile each bootswtch theme to CSS.
  • Concatenate and minify each generated bootstrap file with my other CSS files and have separate single CSS file available for me for each theme.

With this way, switching between themes would be just as easy as changing the filename suffix. I achieved this with gulp and you can find the sample in my GitHub account: gulp-bootswatch-sample. To get the sample up and running, run the following commands in order:

// install bower globally if you don't have it already
npm install bower -g

// install gulp globally if you don't have it already
npm install gulp -g

// navigate to my sample projects root folder and run the following commands
npm install
bower install

// finally run gulp the tasks

Here is how my gulpfile.js file looks like:

var gulp = require('gulp'),
    minifycss = require('gulp-minify-css'),
    concat = require('gulp-concat'),
    less = require('gulp-less'),
    gulpif = require('gulp-if'),
    order = require('gulp-order'),
    gutil = require('gulp-util'),
    rename = require('gulp-rename'),
    foreach = require('gulp-foreach'),
    debug = require('gulp-debug'),
    path =require('path'),
    merge = require('merge-stream'),
    del = require('del');

gulp.task('default', ['clean'], function() {
    gulp.start('fonts', 'styles');

gulp.task('clean', function(cb) {
    del(['assets/css', 'assets/js', 'assets/less', 'assets/img', 'assets/fonts'], cb)

gulp.task('fonts', function() {
    var fileList = [
    return gulp.src(fileList)

gulp.task('styles', function() {
    var baseContent = '@import "bower_components/bootstrap/less/bootstrap.less";@import "bower_components/bootswatch/$theme$/variables.less";@import "bower_components/bootswatch/$theme$/bootswatch.less";@import "bower_components/bootstrap/less/utilities.less";';

    var isBootswatchFile = function(file) {
        var suffix = 'bootswatch.less';
        return file.path.indexOf(suffix, file.path.length - suffix.length) !== -1;
    var isBootstrapFile = function(file) {
        var suffix = 'bootstrap-',
            fileName = path.basename(file.path);
        return fileName.indexOf(suffix) == 0;
    var fileList = [
    return gulp.src(fileList)
        .pipe(gulpif(isBootswatchFile, foreach(function(stream, file) {
            var themeName = path.basename(path.dirname(file.path)),
                content = replaceAll(baseContent, '$theme$', themeName),
                file = string_src('bootstrap-' +  themeName + '.less', content);

            return file;
        .pipe(gulpif(isBootstrapFile, foreach(function(stream, file) {
            var fileName = path.basename(file.path),
                themeName = fileName.substring(fileName.indexOf('-') + 1, fileName.indexOf('.'));
            return merge(stream, gulp.src(['assets/css/font-awesome.css', 'assets/css/main.css']))
                .pipe(concat('style-' + themeName + ".css"))
                .pipe(rename({suffix: '.min'}))

function escapeRegExp(string) {
    return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");

function replaceAll(string, find, replace) {
  return string.replace(new RegExp(escapeRegExp(find), 'g'), replace);

function string_src(filename, string) {
  var src = require('stream').Readable({ objectMode: true })
  src._read = function () {
    this.push(new gutil.File({ cwd: "", base: "", path: filename, contents: new Buffer(string) }))
  return src

End result :)


I wished I had something like this when I started doing this so I hope this was helpful to you somehow. Enjoy!

Building and Running Your ASP.NET vNext Application with Gulp

Wanna see ASP.NET vNext and Gulp working together? You are at the right place :) Let's have look at gulp-aspnet-k, a little plugin that I have created for ASP.NET vNext gulp integration.
2014-10-09 11:28
Tugberk Ugurlu

I love gulp! It has been only a few weeks since I started getting my hands dirty with gulp but it’s ridiculously simple and good. I am actually using gulp with one of my ASP.NET vNext applications to see how they fit together. I am compiling my less files, doing concatenation and minification for scripts/styles files with gulp. It’s also extremely comforting that gulp has file watch capability. For example, I can change my less files during the development and they are being recompiled as I save them:


As I am working with my ASP.NET vNext application in this project, I found myself jumping between command prompt windows. I imagined for a second that it would be cool to have a gulp plugin for ASP.NET vNext to build and run the application. It would also take advantage of k --watch so that it would restart the host when any code files are changed. Then, I started digging into it and finally, I managed to get gulp-aspnet-k (ASP.NET vNext Gulp Plugin) out :) gulp-aspnet-k is also available on npm and you can install it right from there. Check out the readme for further info about its usage.

This is an insanely simple plugin which wraps kpm and k commands for you. In its simplest form, its usage is as below:

var gulp = require('gulp'),
    aspnetk = require("gulp-aspnet-k");

gulp.task('default', function(cb) {
    return gulp.start('aspnet-run');

gulp.task('aspnet-run', aspnetk());

You can find a sample application that uses gulp-aspnet-k plugin in my ASP.NET vNext samples repository: GulpSample. It is also working with gulp watch in peace.


Be sure to watch the following short video of mine to see this tiny plugin in action.

ASP.NET vNext with Gulp from Tugberk Ugurlu on Vimeo.

Keep in mind that, currently, this only works on windows :s Also remember that little things matter in your daily life and this thing is one of them :)

Exciting Things About ASP.NET vNext Series: MVC View Components

A few days ago, I started a new blog post series about ASP.NET vNext. Today, I would like to talk about something which is MVC specific and takes one of our pains away: view components :)
2014-10-06 11:46
Tugberk Ugurlu

Web development experience with .NET has never seen a drastic change like this since its birth day. Yes, I’m talking about ASP.NET vNext :) I have been putting my toes into this water for a while now and a few days ago, I started a new blog post series about ASP.NET vNext (with hopes that I will continue this time :)). To be more specific, I’m planning on writing about the things I am actually excited about this new cloud optimized (TM) runtime. Those things could be anything which will come from ASP.NET GitHub account: things I like about the development process, Visual Studio tooling experience for ASP.NET vNext, bowels of this new runtime, tiny little things about the frameworks like MVC, Identity, Entity Framework.

Today, I would like to talk about something which is MVC specific and takes one of our pains away: view components :)

BIG ASS CAUTION! At the time of this writing, I am using KRE 1.0.0-beta1-10494 version. As things are moving really fast in this new world, it’s very likely that the things explained here will have been changed as you read this post. So, be aware of this and try to explore the things that are changed to figure out what are the corresponding new things.

Also, inside this post I am referencing a lot of things from ASP.NET GitHub repositories. In order to be sure that the links won’t break in the future, I’m actually referring them by getting permanent links to the files on GitHub. So, these links are actually referring the files from the latest commit at the time of this writing and they have a potential to be changed, too. Read the "Getting permanent links to files" post to figure what this actually is.

Do you remember ugly, nasty child actions in ASP.NET MVC? I bet you do. Child actions were pain because it’s something so weird that nobody understood at the first glance. They were sitting inside the controller as an action (hence the name) and can be invoked from the view like below:


In MVC, if your HTTP request reaches that view and starts rendering, it means (most of the time with the default flow at least) that you already have gone through a controller and an action. Now, we are also invoking a child action here and this basically means that we will go through the pipeline again to pick the necessary controller and action. So, you can no longer tell that only HTTP requests will hit your controller because the child actions are not HTTP requests. They are basically method calls to your action. Not to mention the lack of asynchronous processing support inside the child actions. I’m guessing that a lot of people have seen a deadlock while blocking an asynchronous call inside a child action. In a nutshell, child actions are cumbersome to me.

View Components in ASP.NET vNext

In ASP.NET vNext, all of the ugly behaviors of child actions are gone. To be more accurate, child actions are gone :) Instead, we have something called view components which allows you to render a view and it can be called inside a view. It has the same features of child actions without all the ugliness.

Let me walk you though a scenario where view components might be useful to you. In my website, you can see that I’m listing links to my external profiles at the right side.


Possibly, the links are stored in my database and I’m retrieving them by performing an I/O operation. Also, I am viewing these links in all my pages at the right side. This’s a perfect candidate for a view component where you would implement your links retrieval and display logic once (separately), and use it whenever you need it. At its core, your view component is nothing but a class which is derived from the ViewComponent base class. It has a few helper methods on itself like View, Content and Json methods. However, you are not restricted to this. Thanks to new great DI system in K Runtime, we can pass dependencies into view components as well. Let’s build this up.

First of all, I have the following manager class which is responsible for retrieving the profile link list. For the demo purposes, it gets the list from an in-memory collection:

public interface IProfileLinkManager
    Task<IEnumerable<ProfileLink>> GetAllAsync();

public class ProfileLinkManager : IProfileLinkManager
    private static readonly IEnumerable<ProfileLink> _profileLinks = new List<ProfileLink> 
        new ProfileLink { Name = "Twitter", Url = "", FaName = "twitter" },
        new ProfileLink { Name = "linkedIn", Url = "", FaName = "linkedin" },
        new ProfileLink { Name = "GitHub", Url = "", FaName = "github" },
        new ProfileLink { Name = "Stackoverflow", Url = "", FaName = "stack-exchange" }

    public Task<IEnumerable<ProfileLink>> GetAllAsync()
        return Task.FromResult<IEnumerable<ProfileLink>>(_profileLinks);

public class ProfileLink
    public string Name { get; set; }
    public string Url { get; set; }
    public string FaName { get; set; }

Inside the Startup.cs file, we need to register the implementation of IProfileLinkManager:

app.UseServices(services => 
    services.AddScoped<IProfileLinkManager, ProfileLinkManager>();

View Components and How They Work

We can now create our view component which has a dependency on ProfileLinkManager:

public class ProfileLinksViewComponent : ViewComponent
    private readonly IProfileLinkManager _profileLinkManager;

    public ProfileLinksViewComponent(IProfileLinkManager profileLinkManager)
        if (profileLinkManager == null)
            throw new ArgumentNullException("profileLinkManager");

        _profileLinkManager = profileLinkManager;

    public async Task<IViewComponentResult> InvokeAsync()
        var profileLinks = await _profileLinkManager.GetAllAsync();            
        return View(profileLinks);

There are couple of things to highlight here. Let’s start with the name of the view component which is very important as we need to know its name so that we can refer to it when we need to process it. The name of the view component can be inferred in two ways:

  • The name can be inferred from the name of the view component class. If the class name has a suffix as "ViewComponent", the view component name will be the class name with "ViewComponent" suffix. If it doesn’t have that suffix, the class name is the view component name as is.
  • You can specifically give it a name by applying the ViewComponentAttribute to the view component class and setting its Name property.

The other thing that is worth mentioning is our ability to inject dependencies into our view component. Any dependency that we have inside the request scope at the time of invocation can be injected into the view component class. Have a look at CreateComponent private method on the DefaultViewComponentInvoker (we will touch on this later) to see how the view component class is activated by default.

The last thing I want to mention is the method of the view component that will be called. By default, you can have two method names here: InvokeAsync or Invoke. As you can guess, InvokeAsync is the one you can use for any type of asynchronous processing. As these two methods are not part of the base class (ViewComponent), we can have as many parameters as we want here. Those parameters will be passed when we are actually invoking the view component inside a view and the registered IViewComponentInvoker (DefaultViewComponentInvoker by default) is responsible for calling the InvokeAsync or Invoke method (if you have both InvokeAsync and Invoke method on your view component, the InvokeAsync will be the one that’s called). From the method, you can return three types (if it’s InvokeAsync, the following types are for the generic parameter of the Task<T> class): IViewComponentResult, string and HtmlString. As you can see, I am using the View method of the ViewComponent base class above which returns IViewComponentResult.

Using the View Components

We covered most of things that we need to know about view components except for how we can actually use them. Using a view component is actually very similar to how we used child actions. We need to work with the Component property inside the view (which is an implementation of IViewComponentHelper). There are a few methods for IViewComponentHelper that we can call. You can see below that I am calling the InvokeAsync by only passing the component name.

    <div class="col-md-8">
        <hr />
            Main section...
    <div class="col-md-4">
        <hr />
        @await Component.InvokeAsync("ProfileLinks")

And yes, you can await inside the razor view itself :)

InvokeAsync method here also accepts "params object[]" as its second parameter and you can pass the view component parameters there (if there are any). Let’s run the application and see what we are getting:


To be able to see this rich error message, you need to pull down the Microsoft.AspNet.Diagnostics package and activate the diagnostic page for your application as I did. Unlike the old ASP.NET world, we don’t get any special feature for free in this world. Remember, pay-for-play model :)

We got an error which is expected:

An unhandled exception occurred while processing the request.

InvalidOperationException: The view 'Components/ProfileLinks/Default' was not found. The following locations were searched: /Views/Home/Components/ProfileLinks/Default.cshtml /Views/Shared/Components/ProfileLinks/Default.cshtml.

Microsoft.AspNet.Mvc.ViewViewComponentResult.FindView(ActionContext context, String viewName)

This’s actually very good that we are getting this error message because it explains what we need to do next. As we didn’t pass any view name, the Default.cshtml the view file is the one our component is looking for. The location of the view needs to be either under the controller that we now rendering (which is Views/Home/ProfileLinks) or the Shared folder (which is Views/Shared/ProfileLinks). Let’s put the view under the Views/Shared/Components/ProfileLinks directory:

@using ViewComponentSample
@model IEnumerable<ProfileLink>

<ul class="profilelink-list">
    @foreach(ProfileLink profileLink in Model)
        <li><a class="btn btn-info" title="@profileLink.Name" href="@profileLink.Url"><i class="fa fa-@(profileLink.FaName) fa-lg"></i></a></li>

When we now run the application, we should see that the component is rendered successfully:


Nice and shiny! You can find the sample I have gone through here inside the ASP.NET vNext samples repository: ViewComponentSample.

Debugging ASP.NET vNext Beta Builds with Visual Studio 14 CTP 3

Visual Studio CTP 3 has launched a while back and I was expecting to have trouble working with ASP.NET vNext beta builds. I was partially right. I wasn’t able to run the web application from Visual Studio. However, it’s still possible to debug the application and I have a workaround for you :)
2014-10-05 16:17
Tugberk Ugurlu

Today, I was working on a sample project with ASP.NET vNext. I have been working on this application without any Visual Studio IDE support but I decided to discover what Visual Studio 14 CTP 3 is bring to the table. I know that Visual Studio CTP 3 has launched a while back and I was expecting to have trouble working with ASP.NET vNext beta builds (hot from the developer machine. Find them here). I was partially right. I wasn’t able to run the web application from Visual Studio. However, it’s still possible to debug the application and I have a workaround for you :)

As I was thinking from the very beginning that I would have trouble with VS 14 CTP 3 + vNext beta builds, I started setting up my environment from the command line instead of letting the VS handle this.


However, Visual Studio still insisted on installing the Aplha3 builds of the K Runtime but anyways. That’s not big of a deal as long as I have the beta one as the active runtime. When I open up the solution, everything looked OK. Even the package restore was successful.


The build was also working. Awesome!


So, it was all going great till I realized that I was building with the OutputType set to "Class Library".


As soon as I changed it to Web Application, the build broke:


This is OK and expected as things have changed since Visual Studio 14 CTP 3 shipped. However, I’m unable to debug my application now. Hmm, not entirely. There are still options and I went with the easier one.  I switched back to command line and ran the application from there with "k web" command:


All good as you can see. Now, back to Visual Studio and press CTRL + ALT + P to bring up the Attach Process dialog box. We are looking for klr.exe to attach but you will probably see two instances of klr there. We need the one that actually hosts our application. You can find out which one is the actual host by looking at the command line arguments from the Task Manager.


In my case, it’s with the PID 1472. Finally, attach the process and you should be able to debug the application now.



Enjoy ;)

Exciting Things About ASP.NET vNext Series: The Ultimate Guide

As of today, I am starting a new blog post series about ASP.NET vNext. To kick things off, I would like to lay out the resources about ASP.NET vNext here which is probably going to be an ultimate guide on ASP.NET vNext.
2014-10-03 11:49
Tugberk Ugurlu

Web development experience with .NET has never seen a drastic change like this since its birth day. Yes, I’m talking about ASP.NET vNext :) I have been putting my toes into this water for a while now and as of today, I am starting a new blog post series about ASP.NET vNext (with hopes that I will continue this time :)). To be more specific, I’m planning on writing about the things I am actually excited about this new cloud optimized (TM) runtime. Those things could be anything which will come from ASP.NET GitHub account: things I like about the development process, Visual Studio tooling experience for ASP.NET vNext, bowels of this new runtime, tiny little things about the frameworks like MVC, Identity, Entity Framework.

To kick things off, I would like to lay out the resources about ASP.NET vNext here. Enjoy them and start discovering what is coming up for the web development with .NET :)

Getting Started Material

Here and There ASP.NET vNext

Development Environment and Tooling Experience


Deep Dive

MVC Specific

Badass Repositories

KRuntime: The core of the ASP.NET vNext. Compilation, bootstraping, package discovery and all other core stuff is handled here. Do not miss on this one!

kvm: K Runtime version manager which works on Windows and Unix based systems.

MVC: Written from scratch MVC framework on top of ASP.NET vNext. This new framework unifies the efforts on ASP.NET MVC and ASP.NET Web API. So, all is in one now.

HttpAbstractions: Contains HTTP abstractions for ASP.NET vNext such as HttpRequest, HttpResponse. Also contains IApplicationBuilder and types to create your application's hosting pipeline.

Home: ASP.NET vNext Home repository where you can get a head start on ASP.NET vNext really quickly. Its README file gives you a nice guide to get your machine up and running with the new tools. It also contains tiny samples which you can run and see how things are working in no time.

KestrelHttpServer: This repo contains a development web server for ASP.NET vNext based on libuv.

Configuration: Configuration is a framework for accessing Key/Value based configuration settings in an application.

Caching: Contains libraries for caching for ASP.NET vNext. Another sign that everything is now composable.

Options: Options is a framework for accessing and configuring POCO settings. Tiny thing that makes me happy that even this thing is thought of.

SignalR-Server: ASP.NET SignalR is a is a new library for ASP.NET developers that makes it incredibly simple to add real-time web functionality to your applications. This repository exposes ASP.NET SignalR on top of ASP.NET vNext.

Hosting: The Hosting repo contains code required to host an ASP.NET vNext application, it is the entry point used when self-hosting an application.


INTRODUCING: The Future of .NET on the Server: Very first video on ASP.NET vNext. Join the Lesser Scotts, Hunter and Hanselman, as they introduce you to new thinking around ASP.NET and the .NET Framework. What does ASP.NET look like in 2014 and beyond? In a world of NuGets and modular frameworks, of lightweight VMs, how could ASP.NET change and get faster, leaner, meaner, and more.

DEEP DIVE: The Future of .NET on the Server: Scott Hanselman joins developer David Fowler for this Part 2 Deep Dive into what’s coming in Microsoft ASP.NET. We explore what a decoupled stack looks like, how modules plug together, what this means for performance, and more. We explore the Project codenamed “Helios” and how this new way of writing ASP.NET applications uses OWIN and plugs into IIS giving you more power and choice than ever before.

Channel 9 Live: ASP.NET Developer Q&A with Scott Hunter & Scott Hanselman: The Scotts and David Fowler answer your questions live!

The Future of ASP.NET Part I: Scott Hanselman’s awesome intro talk on ASP.NET vNext at NDC Oslo 2014 conference.

The Future of ASP.NET Part II: David Fowler and Damian Edwards Q&A session on ASP.NET vNext at NDC Oslo 2014 conference.

An Introduction to ASP.NET vNext: Awesome introduction talk by Daniel Roth at TechEd New Zealand 2014.

ASP.NET vNext 101: Another great introduction talk on ASP.NET vNext by Damian Edwards and David Fowler at dotnetConf 2014.

ASP.NET MVC 6 (now with integrated Web API!): Awesome introduction at dotnetConf 2014 by Daniel Roth on ASP.NET MVC 6 which is a new baby from head to toe. ASP.NET MVC and Web API are being combined into a single framework, ASP.NET MVC 6, for handling all of your Web UI and services. We'll learn how to use ASP.NET MVC and Web APIs in ASP.NET vNext to support connected applications for browsers, Windows Phone, Windows Store and more!

Entity Framework: Rowan Miller gives us an introduction talk at dotnetConf 2014 about Entity Framework 7 which is built on this new .NET Runtime optimized for server. Entity Framework is Microsoft's recommended data access technology for new applications in .NET. We'll explore how the current release of Entity Framework can be used to build applications. We'll also look at an early preview of EF7, a modern, lighter weight, and composable version of Entity Framework (EF) that can be used on a variety of platforms, including ASP.NET vNext, Windows Phone and Windows Store. This new version will also support targeting non-relational data stores.

ASP.NET vNext with Chris Ross: On Web Camps TV, this week Cory is joined by Chris Ross from the ASP.NET team to talk about the vNext bits of ASP.NET. The next version of ASP.NET ("ASP.NET vNext") has been redesigned from the ground up. The goal is to create a lean and composable .NET stack for building modern cloud-based apps.

ASP.NET vNext Community Standup: Meeting recordings from the weekly ASP.NET vNext Community Standup meetings, covering live community Q&A, product team discussion and the most recent updates.

ASP.NET vNext - Everything you need to know in 4 minutes!: Nice intro on new ASP.NET vNext in a short, 4 minutes video. This nicely wraps up what are the new things.

ASP.NET vNext Giriş (in Turkish): 30 minutes webcast on ASP.NET vNext by Tugberk Ugurlu in Turkish.

Dev: ASP vNext: Scott Hunter and Brady Gaster talk about ASP.NET vNext at TechEd Europe 2014

The Future of Microsoft .NET on the Server: Scott Hunter’s TechEd session on ASP.NET vNext at TechEd Europe 2014.


Reconciling ASP.NET vNext with Damian Edwards: Hanselman sits down with Damian Edwards and talks about ASP.NET vNext. There's been a lot of talk around ASP.NET vNext. How did development start, and what's been the thinking about how to manage a new world while still innovating on the current generation of technology? In what ways does ASP.NET vNext break from the past, and in what ways does it build on our existing power and experience?

ASP.NET vNext with Jeff Fritz: Carl and Richard chat with Jeff Fritz about ASP.NET vNext at DotNetRocks.

Evolving ASP.NET Web Development with Scott Hunter: Carl and Richard chat with Scott Hunter about how Microsoft is working to evolve web development for ASP.NET developers. Scott talks about ASP.NET vNext as well.

Herding Code 198: Damian Edwards on ASP.NET vNext, Tag Helpers and SignalR: The guys talk to ASP.NET team member Damian Edwards about ASP.NET vNext (the next version of ASP.NET), Tag Helpers, and what’s new with SignalR.

Code Samples

MusicStore: Best sample out there for ASP.NET vNext by the team. It has two projects: one is for static-rendered Music Store application and the other one is a SPA (Single Page Application). Check out this article for further information about the sample.

BugTracker: Another sample application from ASP.NET team. This one is also uses SignalR. Check out the this article for further information about this sample.

MVC Samples: Lots of tiny MVC samples that ASP.NET team is using for functional tests.

Entropy: ASP.NET vNext feature experience playground of ASP.NET team.

MvcSample.Web: ASP.NET MVC 6 sample which highlights quite a lot of its features.

KLoggy: My playground for a few cool things such as ASP.NET vNext, Gulp, Bower, AngularJS. Check it out for sure. I have big plans for this :)

conch: Nice sample on ASP.NET vNext by Mark Rendle. The repo description says "Nothing to see here. Move along". So, keep that in mind :)

vNextLanguageSupport: A sample by David Fowler that has examples of how to support different languages in the vNext project system.

AspNetVNextSamples: My repository on ASP.NET vNext samples. It’s sort of tiny right now but I’m putting this here anyway hoping that it will get big in near future.