Category Archives: CodeProject

Get Started with ASP.NET MVC TagHelpers

Tag HelperWe are almost to the BETA cycle of ASP.NET vNext, and I’ve been following the ASP.NET team’s development on GitHub.  If you didn’t know already, the all-star developers at Microsoft are cranking away on the next version of ASP.NET in a completely open-source model.One of the cool new features set to be released with the next version is a significant addition to the HTML Helper model that we currently have in MVC 5, and its called TagHelpers. Continue reading

Authentication, Authorization and OWIN – Who Moved My Cheese?

I was working with one of my ASP.NET projects this weekend and ran into an interesting

problem while I was debugging.  This application was written from the ground up to use ASP.NET identity and OAuth security for all of my authentication and authorization needs.  That also means that my application follows the new default layout for an ASP.NET web forms application, with account management and login capabilities reside in the /Account folder structure.

An interesting series of things happens to web.config when we adapt the OAuth security management in ASP.NET 4.5+  What follows is what I have learned the hard way…

Authentication Information in Web.Config disappears

If you’re a long time developer with ASP.NET like me, you’re accustomed to the FormsAuthentication configuration in web.config.  With the new authentication and identity modules in ASP.NET 4.5, all of this goes away.  This really tweaked me at first, I got confused and followed the code… and trust me, its all good.

Web.Config has its authentication turned off and all identity providers removed.  Check out this snippet from a fresh web.config in a new ASP.NET 4.5 application:

  <system.web>
    <authentication mode="None" />
    <!-- other stuff -->
    <membership>
      <providers>
        <clear />
      </providers>
    </membership>
    <profile>
      <providers>
        <clear />
      </providers>
    </profile>
    <roleManager>
      <providers>
        <clear />
      </providers>
    </roleManager>
    <!-- other stuff -->
    </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
  </system.webServer>

That’s some scary stuff right there.  Everything that I’ve known since ASP.NET was released in 2002 screams out: NOOOOOooooooo!  This is the necessary configuration to turn off all of the embedded and automatically activated security modules in ASP.NET  With that functionality shut off, the OAuth security module can step in.

OAuth Security Configuration

Instead, all of the security configuration goodness is kicked off in a new OWIN-compliant manner from within Startup.cs on the root of the application.

[assembly: OwinStartup(typeof(MyApplication.Startup))]

namespace MyApplication
{
  public partial class Startup
  {
    public void Configuration(IAppBuilder app)
    {
      ConfigureAuth(app);
      app.MapSignalR();
    }
  }
}

Check out that attribute at the top of the file, an OwinStartupAttribute that points to this class that contains the codified configuration of the application.  The class is required to have a Configuration method with the same signature in this snippet.  I’m not clear why the class does not adhere to an interface that enforces the presence of this method, but this is the requirement.  You can see from here, that it calls the ConfigureAuth method in the App_Start/Startup.Auth.cs file.  Its in there that we can find all of the configuration for managing the authentication of resources in the application.

public void ConfigureAuth(IAppBuilder app)
{
 
  // Stuff to configure the Identity data storage
  
  // Enable the application to use a cookie to store information for the signed in user
  // Configure the sign in cookie
  app.UseCookieAuthentication(new CookieAuthenticationOptions
  {
      AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
      LoginPath = new PathString("/Account/Login")
      // other stuff
  });
  
  // more stuff down here
}

This is where I was thrown for a loop.  How does ASP.NET know where my login page is?  Its defined right here with the LoginPage configuration property inside of the CookieAuthenticationOptions class.

How is Authorization Handled?

Finally, how is authorization to pages handled?  In the past, I would write blocks of XML with authorization elements that looked similar to the following…

  <location path="Admin">
    <system.web>
      <authorization>
        <deny users="?" />
        <allow roles="Admin" />
      </authorization>
    </system.web>
  </location>

The good news is that none of that has changed, and we can continue to code high-level authorization rules inside of web.config files in ASP.NET 4.5.

Summary

Its not a good idea to tinker with the default security configuration of ASP.NET unless you know where all of the moving pieces are.  In the past, I knew where everything was referencing from web.config through global.asax.cs to verify connections to my application where authenticated and authorized. In the new Owin enabled ASP.NET, those pieces have moved and are now very descriptive in their new locations.  Coming soon, I have a Pluralsight course that will discuss all of the cool things that you can do to configure ASP.NET OWIN security and other Advanced topics.  I look forward to delivering it for you in the very near future.

How to Automate ASP.NET Custom Controls with the Gulp JavaScript Task Runner

Here I am, writing a module for my next Pluralsight course and I ran into an interesting problem.  When I write a custom ASP.NET control, I now have lots of JavaScript and CSS libraries that I want to ship with it.  With the introduction of the Task Runner Explorer in Visual Studio, I decided to try my hand at writing a Gulp script that will combine and compress these static resources inside of my class library project.

Introducing Gulp for the ASP.NET Developer

Gulp is another task runner for use with NodeJS, similar to Grunt.  Unlike Grunt, Gulp runs based on a JavaScript file of instructions and can be run in an asynchronous manner.  This leads to Gulp being a bit easier to read as a series of functions that will run faster than the Grunt JSON configuration file.

To get started with Gulp and Visual Studio:

1. Install NodeJS from www.nodejs.org

2. Install Gulp with the NPM package manager as follows:

npm install gulp -g

This will install Gulp globally and make the gulp command-line executable available.

3. Create a package.json file in the root of your project.  This can be a file that contains just a pair of curly braces.

4. Configure gulp locally to the project by running the following script on the command line at the project root folder:

npm install gulp --save-dev

5. Install a handful of gulp plugins to manage the concatenation, renaming, minifying and notification processes:

npm install gulp-minify-css gulp-concat gulp-uglify gulp-notify gulp-rename --save-dev

With those command issued, we’re ready to build our gulpfile.js to contain the instructions for how to automate working with our static resources.

Create a file called gulpfile.js on the root of the project.  This file should be excluded from the project.  Begin by defining a series of variables using gulp’s built-in require commands:

var gulp = require('gulp'),
  concat = require('gulp-concat'),
  minifycss = require('gulp-minify-css'),
  rename = require('gulp-rename'),
  notify = require('gulp-notify'),
  uglify = require('gulp-uglify');

Next, we can define a simple gulp task to minify the bootstrap.css file that is in our project:

gulp.task('css', function() {

  return gulp.src('css/bootstrap.css')
    .pipe(rename('mycontrols.min.css'))
    .pipe(minifycss())
    .pipe(gulp.dest('css'))
    .pipe(notify({message: 'Styles minified'}));

});

The name of the task is “css” and it will trigger a function.  The function returns the result of operations on the css/bootstrap.css file.  The file is piped from one operation to the next with the pipe method.  First, the file is renamed to mycontrols,min.css so that the file matches the “mycontrols” project name.  Next, the contents of the CSS file are minified with the minifycss command and then piped to the css folder using the gulp.dest method.  Finally, a notification is triggered with the notify method and the message text specified.

The JavaScript processing is similar:

gulp.task('js', function() {
  
  return gulp.src(['scripts/jquery-1.10.2.js','scripts/respond.js','scripts/bootstrap.js'])
    .pipe(concat('mycontrols.js'))
    .pipe(gulp.dest('scripts'))
    .pipe(rename({suffix: '.min'}))
    .pipe(uglify())
    .pipe(gulp.dest('scripts'))
    .pipe(notify({message: 'Scripts merged and minified'}));

});

This time, I am passing an array of files in to be processed.  The collection are concatenated together with the concat method into the mycontrols.js file and written into the scripts folder with another gulp.dest method.  The filename is renamed with a suffix of .min and sent into the uglify processor for minification.  The results of the uglification are written back to the scripts folder and a notification is triggered with an appropriate message.

Finally, I wrote a default task to call the JS and CSS tasks.  I called this task default:

gulp.task('default', ['js','css'], function() {});

The second argument in this method call is the collection of dependent tasks that should be called before the function is executed.  In this way, the js and css tasks are called asynchronously.

Automating Gulp with Task Runner Explorer

With the Task Runner Explorer extension in Visual Studio, I can connect any and all of these tasks to various steps in the build process.  In my case, I right-clicked on the ‘default’ task and chose to bind it to the ‘Before Build’ run time.

Now, every time I build my MyControls project, the gulp default task will run and deliver appropriate CSS and JS files for my controls to use.

 

Custom Control Project Considerations

Importantly, for this project I marked my gulpfile, package.json, and all of my original CSS and JS files as  Build Action None and Do not copy to output directory.  I did mark the new mycontrols.min.js and mycontrols.min.css as Embedded Resources so that they would be delivered inside of the DLL I will distribute with my controls.

Summary

The new Task Runner Explorer combined with the NodeJS command line interface and Gulp have made automating packaging assets for my custom controls much easier than previously.  Now, visitors to my applications will download one script file and one css file for my controls.  This will provide a faster and easier experience for my visitors and my developers that use my custom ASP.NET controls

Connecting the dots with jQuery, JSONP, and WebAPI

No problem!

This morning, I jumped in to help out my friend Julie Lerman with a question about using jQuery with ASP.NET WebAPI.  In my mind, that’s easy… something I’ve wired up lots of times and shouldn’t be a problem. I offered to pair program for a bit and take a look at the code, after all… how hard could it be?

This was an interesting and simple block of jQuery that was expecting JSON from a service.  A simple WebAPI controller, similar to the one we were attempting to query looked a little like this:

  public class ValuesController : ApiController
  {
    // GET api/values
    public IEnumerable<string> Get()
    {
      return new string[] { "value1", "value2" };
    }
  }

That’s easy to get data from with jQuery, I can use an AJAX call to get the data from my server with JavaScript like the following:

$.ajax({
  url: "http://localhost:64948/api/values",
  type: 'GET',
  dataType: 'json'
}).done(function(data) { alert(data.length); });

When I run this page from the same server that is hosting my service, no problem.  I get a simple alert box with the number 2.

That wasn’t our problem.

In this scenario, Julie was querying a different server that was hosting WebAPI and needed the services of JSONP to make that cross-origin request.  The jQuery documentation indicates that you can simply switch the dataType of your AJAX call to “JSONP” and everything will just work.

No...

No dice… nothing.  We poked and prodded that JavaScript code and got nothing from it.  Then it hit us:  the problem isn’t the JavaScript, its the callback coming from the server.  WebAPI needs to know how to issue a command back to our script.

To complete the task and get WebAPI responding properly to a JSONP request, install the JSONP MediaTypeFormatter from NuGet.  Once that is installed, enter your App_StartWebApiConfig.cs and add to the bottom of the Register method the following line:

GlobalConfiguration.Configuration.AddJsonpFormatter();

Rebuild and re-run the JavaScript and now the done method of the AJAX call is being executed.

We were happy, and all was right in the world.  

What did we learn about this problem and how to write better software?

The short answer is: JavaScript development is REALLY HARD without proper error messages and with connections that fail silently.  There was no indication that the WebAPI was not attempting to call the Done callback method from jQuery.  Additionally, WebAPI wasn’t throwing any warning message to indicate that there were arguments passed in that it didn’t know what to do with.  This lack of verbose messaging in a debugging environment made it difficult for two experts to be able to track down a problem.

How would an average developer handle this?  We can do better…  I’ll write more about this approach to making debuggable (yea, I just invented that word…) software tools next time and how we can improve this experience.

 

MultiTasking is a Myth

Yesterday, I took my family to the Franklin Institute in Philadelphia (we have a membership there) and visited their new permanent exhibit on the brain.  While going through, I found this display and it really hit home for me:

I have always had a problem with multitasking.  Its not something that I can do well, as I prefer to focus on one thing at a time, giving it my undivided attention.  Once I’ve completed that task, I move on to the next task.  As someone who works from home, I’ve found several benefits from this approach, and I’ve also found several pitfalls.

Successful Techniques

1. Make a list and stick to it

I’ve made task lists all sorts of ways in the past.  I’ve used a paper notepad, notepad.exe, Outlook Tasks, OneNote, and Trello.  They all are used for the same thing: allow me to forget future tasks and only focus on the current item.

This is one of the concepts behind Kanban and Scrum.  You can only take one task card at a time to be worked on.  Once the task card is finished, it gets placed into another queue for review and validation by other team members.  Trello is an excellent free tool for this, but has its drawbacks, as do all online task managers.

The biggest problem I have with the online task list manager is what I can the “in your face” problem.  I need to open the application or navigate to the website in order for me to face my task list of the day.  It is all to easy for me to say, “lemme open Facebook first” or “hey what’s going on at LinkedIn” before I face my list of tasks for my work session.

However, by keeping a paper list of tasks and leaving them on my desk chair, or on my keyboard.  Now, I need to look at my to-do list before I begin working on anything.  It may seem simple, but it keeps someone like me who can get distracted very easily on task right from the get go.

2. My Office is My Work Space

This sounds like a simple idea, but let me describe for you my mindset.  I have a room in my home dedicated as my home office.  When I am in that room, I am in there for one purpose only: to accomplish ‘work tasks’.  After a bit of practice of this habit, I now get in the “working mood” just when I walk into the room.  My mind knows that good stuff will be accomplished once I sit down.

This also has the side-benefit of ‘training my family’ that when Daddy is in his office, he’s working and we should leave him alone.  Not that I want to be an office hermit, but this bit of training can grant me several hours at a time of uninterrupted work.  In a home with two young daughters, this can be a welcome retreat.

3. Get in “The Zone”

If you’ve ever been there, you know what I’m talking about.  “The Zone” or “Flow” as psychologists call it can be intoxicating.  This is when your mind is fully immersed in a task and everything around you just falls away as unimportant.  You’ll exit the zone and find out that five to ten hours have gone by and you haven’t eaten or been to the restroom in that time.

In the film The Social Network, they refer to this phenomena again and again as being “wired in”.  The coders in the movie are oblivious to what’s going on around them and solely focused on their code:

This is, how programers should be working

For me, when I am analyzing some source code to better understand it, I start to enter this mindset.  I’ll move further into it as I begin to write code and see the fruits of my progress.  When I need to wait for a compilation or other process to complete, I’ll grab a Rubik’s cube and solve it while sitting at my desk.  I can usually complete a cube in less than two or three minutes, and this has been an effective tool to keep my mind active.

Another trick I use to keep my mind going involves poker chips.  Yes, I enjoy an occasional game of hold ’em, but in this case I’m not playing poker, just shuffling the chips.  What I do is take a stack of 10 chips, typically of two different colors, and break them into two equal stacks of the same color.  I then merge the two stacks, inserting a white chip between two blue chips.  This should result in the stack perfectly merged, with white chips alternating between blue chips.  I’ll repeat this separate and merge process until I get the chips back in a state where the two sets of colored chips are completely isolated from each other, like in the pic above.

Former co-workers will tell you, when they hear the sound of the shuffling poker chips, they know I am deep in thought and stuff is getting accomplished.

Carl and Richard on .NET Rocks had a great episode this week talking to Mark Seeman about getting in the zone.  They have some great tips there, and its worth a listen.

Problem Areas

These are 3 great ideas to help me get in the zone, get focused and get going at a high speed.  Unfortunately, the following problems arise that prevent my productivity.

1. The list runs empty

When I run out of tasks on my list, I end up wandering aimlessly.  This can be a good thing, but typically its a bad thing.  It is a good thing when I can take time to relax, grab a frosty adult beverage from my friends at Redds Apple, and take it easy.  However, my mind is constantly racing at new ideas, and even when I’m not actively working on something, I like to write down ideas in OneNote on my phone.

2. Interruptions – Arrgh!

This is the killer one for me, and where that passage I read at the Franklin Institute grabbed me.  Interruptions murder my productivity.  This can be anything from a text message, a new tweet that mentions me, or some great post from a friend on Facebook.  Kids wandering in to my office complaining about what their mother has chosen for dinner and buggy software that I’m using that prevents me from working productively are more time sinks that I try to avoid.

Like the sign at the beginning of this piece said, you can’t truly multi-task.  The best you can hope for is context switching, and synchronizing your current mindset to paper or some other medium that you can use to pick up and return to your previous state quickly.  Coworkers and family members have gotten very frustrated at me when they have attempted to engage me while I am ‘in the zone’ and I need to take that minute to “save my progress” so that I can resume after I’ve addressed their questions.

I’ve also learned to shut those things out, to silence my phone and to use a pair of gaming headphones with decent noise cancelling capabilities to limit the amount of ambient (read: distracting) noise that enters my head.  Combine that with some mellow music (my current preferred tunes are from Lindsey Stirling) and I can stay very focused for hours on end.

3. Outside of my space

When I’m out of my space and can’t get comfortable, it is very hard for me to get in the zone.  Sitting at the airport, in a coffee shop, in an office with lots of traffic going by my desk… these are all places that I have found very difficult to enter the zone.  However, I have found tremendous value in the desk in a quiet hotel room.

I’ll pull the drapes shut, turn the lights down, so that the only light is coming from my laptop.  With a nice venti caramel macchiato by my side, I can code anything!  Its a strange experience, being away from home and feeling like I’m back in my comfortable office, but it works.

Summary

This is just a collection of tip about what works for me.  Productivity and getting in the zone are difficult things to manage, and I like to manage them as best as possible through these simple environment management techniques.  What works for you?  Share your tips in the space below.