Using "Ctrl+Enter, Enter" Instead of "Ctrl+., Enter" for C# Quick Actions on Visual Studio 2015 Preview

One of the new features of the Roslyn based code editor is Quick Actions. Let's see how you can use Ctlr+Enter, Enter combination instead of Ctrl+., Enter :)
2014-11-13 20:46
Tugberk Ugurlu


Visual Studio 2015 preview went public yesterday and we can enjoy the new Roslyn based code editor for C# and Visual Basic :) You can learn more about these new cool things about the code editor on Visual Studio blog.

One of the new features is something ReSharper user are very familiar with: quick actions. Sometimes inside the editor, you will see a yellow lamp popping up:

Screenshot 2014-11-13 22.14.49

This indicates that there are possible actions that you can take on this piece of code. You can bring up these actions by hitting "Ctrl+."

Screenshot 2014-11-13 22.15.54

Later, you can chose the action from the list and apply it by hitting ENTER. For very obvious stuff like the above removing unused using sample, you want to apply the action instantly. If you are using ReSharper before, I’m 99.9% sure that you will find yourself hitting "Ctrl+., ." :) as it’s easier than moving your finger from "." key to "Enter" key :) Luckily, we can come with a better keyboard shortcut for this which is "Ctrl+Enter, Enter" :)

Inside Visual Studio, go to Tools > Options:

Screenshot 2014-11-13 22.26.16

Search for keyboard and you will see the "Keyboard" section under "Environment" pane:

image

Search for "lineopenabove" command there which actually uses "Ctrl+ Enter" shortcut. Remove that by hitting "Remove" button:

image

Now, search for "quickaction" and apply the "Ctrl + Enter" shortcut as shown below:

vs-quickaction

Hoping that this will be the default at some day :) Happy "Ctrl+Enter, Enter"ing :)

Exciting Things About ASP.NET vNext Series: Middlewares and Per Request Dependency Injection

From the very first day of ASP.NET vNext, per request dependencies feature is a first class citizen inside the pipeline. In this post, I'd like to show you how you can use this feature inside your middlewares.
2014-11-09 21:20
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 weeks ago, I started a new blog post series about ASP.NET vNext. 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 show you one of my favorite features in ASP.NET vNext: per-request dependencies.

BIG ASS CAUTION! At the time of this writing, I am using KRE 1.0.0-beta2-10679 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.

If you follow my blog, you probably know that I have written about OWIN and dependency injection before. I also have a little library called DotNetDoodle.Owin.Dependencies which acts as an IoC container adapter into OWIN pipeline. One of the basic ideas with that library is to be able to reach out to a service provider and get required services inside your middleware. Agree or disagree, you will sometimes need external dependency inside your middleware :) and some of those dependencies will need to be constructed per each request separately and disposed at the end of that request. This is a very common approach and nearly all .NET IoC containers has a concept of per-request lifetime for ASP.NET MVC, ASP.NET Web API and possibly for other web frameworks like FubuMVC

From the very first day of ASP.NET vNext, per request dependencies feature is a first class citizen inside the pipeline. There are a few ways to work with per request dependencies and I’ll show you two of the ways that you can take advantage of inside your middleware.

Basics

For you ASP.NET vNext web application, you would register your services using one of the overloads of UseServices extension method on IApplicationBuilder. Using this extension method, you are registering your services and adding the ContainerMiddlware into the middleware pipeline. ContainerMiddlware is responsible for creating you a dependency scope behind the scenes and any dependency you register using the AddScoped method (in other words, any dependency which is marked with LifecycleKind.Scoped) on the IServiceCollection implementation will end up being a per-request dependency (of course it depends how you use it). The following code is a sample of how you would register your dependencies inside your Startup class:

public void Configure(IApplicationBuilder app)
{
    app.UseServices(services =>
    {
        services.AddScoped<IFarticusRepository, InMemoryFarticusRepository>();
        services.AddTransient<IConfigureOptions<FarticusOptions>, FarticusOptionsSetup>();
    });

    app.UseMiddleware<FarticusMiddleware>();
}

The way you reach out to per-request dependencies also vary and we will go through this topic in a few words later but for now, we should know that request dependencies are hanging off of HttpContext.RequestServices property.

Per-request Dependencies Inside a Middleware (Wrong Way)

Inside the above dependency registration sample code snippet, I also registered FarticusMiddleware which hijacks all the requests coming to the web server and well..., farts :) FarticusMiddleware is actually very ignorant and it doesn’t know what to say when it farts. So, it gets the fart message from an external service: an IFarticusRepository implementation. IFarticusRepository implementation can depend on other services to do some I/O to get a random message and those services might be constructed per request lifecycle. So, FarticusMiddleware needs to be aware of this fact and consume the service in this manner. You can see the implementation of this middleware below (trimmed-down version):

public class FarticusMiddleware
{
    private readonly FarticusOptions _options;

    public FarticusMiddleware(
        RequestDelegate next, IOptions<FarticusOptions> options)
    {
        _options = options.Options;
    }

    public async Task Invoke(HttpContext context)
    {
        IFarticusRepository repository = context
            .RequestServices
            .GetService(typeof(IFarticusRepository)) as IFarticusRepository;

        if(repository == null)
        {
            throw new InvalidOperationException(
                "IFarticusRepository is not available.");
        }

        var builder = new StringBuilder();
        builder.Append("<div><strong>Farting...</strong></div>");
        for(int i = 0; i < _options.NumberOfMessages; i++)
        {
            string message = await repository.GetFartMessageAsync();
            builder.AppendFormat("<div>{0}</div>", message);
        }

        context.Response.ContentType = "text/html";
        await context.Response.WriteAsync(builder.ToString());
    }
}

So, look at what we are doing here:

  • We are getting the IOptions<FarticusOptions> implementation through the middleware constructor which is constructed per-pipeline instance which basically means per application lifetime.
  • When the Invoke method is called per each request, we reach out to HttpContext.RequestServices and try to retrieve the IFarticusRepository from there.
  • When we have the IFarticusRepository implementation, we are creating the response message and writing it to the response stream.

The only problem here is that we are being friends with the notorious service locator pattern inside our application code which is pretty bad. Invoke method tries to resolved the dependency itself through the RequestServices property. Imagine that you would like to write unit tests for this code. At that time, you need know about the implementation of the Invoke method here to write unit tests against it because there is no other way for you to know that this method relies on IFarticusRepository.

Per-request Dependencies Inside a Middleware (Correct Way)

I was talking to a few ASP.NET team members if it was possible to inject per-request dependencies into Invoke method of my middleware. A few thoughts, Louis DeJardin sent a pull request to enable this feature in a very simple and easy way. If you register your middleware using the UseMiddleware extension method on IApplicationBuilder, it checks whether you are expecting any other parameters through the Invoke method rather than an HttpContext instance and inject those if you have any. This new behavior allows us to change the above Invoke method with the below one:

public async Task Invoke(HttpContext context, IFarticusRepository repository)
{
    if(repository == null)
    {
        throw new InvalidOperationException("IFarticusRepository is not available.");
    }

    var builder = new StringBuilder();
    builder.Append("<div><strong>Farting...</strong></div>");
    for(int i = 0; i < _options.NumberOfMessages; i++)
    {
        string message = await repository.GetFartMessageAsync();
        builder.AppendFormat("<div>{0}</div>", message);
    }

    context.Response.ContentType = "text/html";
    await context.Response.WriteAsync(builder.ToString());
}

Nice and very clean! It’s now very obvious that the Invoke method relies on IFarticusRepository. You can find the sample application I referred here under my GitHub account. When you run the application and send an HTTP request to localhost:5001, you will see the log which shows you when the instances are created and disposed:

I am still adding new things to this sample and it's possible that the code is changed when you read this post. However, here is latest state of the sample application at the time of this writing.

image

Getting the Client’s IP Address in ASP.NET vNext Web Applications

I was wondering about how to get client’s IP address inside an ASP.NET vNext web application. It’s a little tricky than it should be but I finally figured it out :)
2014-10-30 10:04
Tugberk Ugurlu


I was wondering about how to get client’s IP address inside an ASP.NET vNext web application. It’s a little tricky than it should be but I finally figured it out. So, I decided to write it down here so that anyone else can see how it’s done right now.

BIG ASS CAUTION! At the time of this writing, I am using KRE 1.0.0-beta2-10648 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.

First thing to highlight here is "HTTP Features" feature (mouthful, I know :)). It’s a really exciting design if you ask me and basically, the HTTP server underneath your application will implement certain features and your application can work with these implementations. Some of the features that a server might implement can be found inside the Microsoft.AspNet.HttpFeature package. However, it’s not limited to these features only. You watch Chris Ross talking about HTTP Features on Web Camps TV to find out more about this as he gives a nice overview on HTTP Features design.

One of these HTTP features is HTTP connection feature (IHttpConnectionFeature if you want to be more specific). This feature is responsible for giving local and remote connection information for current request and this is where we can get client’s IP Address. You can try to get IHttpConnectionFeature from the HttpContext instance which you get per each request. HttpContext has two methods called GetFeature and one of them accepts a generic parameter. You can use this method to retrieve a specific feature you want to reach out to. The below Startup class shows you how you can get the client’s IP Address through the IHttpConnectionFeature.

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using System.Threading.Tasks;
using Microsoft.AspNet.HttpFeature;

namespace RemoteIPAddressSample
{
    public class Startup
    {
        public void Configure(IApplicationBuilder app)
        {
            app.Run(async (ctx) =>
            {
                IHttpConnectionFeature connection = ctx.GetFeature<IHttpConnectionFeature>();
                string ipAddress = connection != null
                    ? connection.RemoteIpAddress.ToString()
                    : null;

                await ctx.Response.WriteAsync("IP Address: " + ipAddress);
            });
        }
    }
}

When I hit the HTTP endpoint now, I’ll see my client’s IP address inside the response body:

image

We can even make this look nicer by refactoring this into an extension method.

public static class HttpContextExtensions
{
    public static string GetClientIPAddress(this HttpContext context)
    {
        if(context == null)
        {
            throw new ArgumentNullException("context");
        }

        IHttpConnectionFeature connection = context.GetFeature<IHttpConnectionFeature>();

        return connection != null
            ? connection.RemoteIpAddress.ToString()
            : null;
    }
}

Way better. We can now use this nice looking HttpContext extension instead:

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.Run(async (ctx) =>
        {
            await ctx.Response.WriteAsync("IP Address: " + ctx.GetClientIPAddress());
        });
    }
}

One thing to mention here is that the HTTP server which your application is running on top of may choose not to implement this feature. It sounds like a very unreasonable situation as something this fundamental should be there all the time but it’s what it is. So, you should be always careful when reaching out to properties of this feature as you may get null values when you call GetFeature<T>. This rule probably applies most of the HTTP features but I wasn’t able to find any certain information whether there is a check at the very early stages of the pipeline to refuse to use the server if specific features are not implemented by the server. I’ll probably update the post when I find this out.

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
gulp

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 = [
        'bower_components/bootstrap/dist/fonts/*', 
        'bower_components/fontawesome/fonts/*'
    ];
    
    return gulp.src(fileList)
        .pipe(gulp.dest('assets/fonts'));
});

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 = [
        'client/less/main.less', 
        'bower_components/bootswatch/**/bootswatch.less', 
        'bower_components/fontawesome/css/font-awesome.css'
    ];
    
    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(less())
        .pipe(gulp.dest('assets/css'))
        .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(gulp.dest('assets/css'))
                .pipe(rename({suffix: '.min'}))
                .pipe(minifycss())
                .pipe(gulp.dest('assets/css'));
        })))
});

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) }))
    this.push(null)
  }
  return src
}

End result :)

image

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

Tags