MSP Turkey Kickoff 2014 ASP.NET Web API and SignalR Presentation Slides, Recording and Links

I was at Microsoft Turkey office yesterday and I gave a presentation on ASP.NET Web API and SignalR in context of this year’s MSP Kickoff. This post covers where you can reach out to presentation slides, recording and several relevant links.
2014-10-19 13:44
Tugberk Ugurlu

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 ;)