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!

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:

gulp-watch

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.

image

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:

<div>
    @Html.Action("widget")
</div>

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.

image

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 = "http://twitter.com/tourismgeek", FaName = "twitter" },
        new ProfileLink { Name = "linkedIn", Url = "http://www.linkedin.com/in/tugberk", FaName = "linkedin" },
        new ProfileLink { Name = "GitHub", Url = "http://github.com/tugberkugurlu", FaName = "github" },
        new ProfileLink { Name = "Stackoverflow", Url = "http://stackoverflow.com/users/463785/tugberk", 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.AddMvc();
    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.

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

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:

image

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>
    }
</ul>

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

image

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