Category Archives for ASP.NET

Cmder is the Cadillac of Windows Consoles

Like fashion, computing works in cycles. Things that were once looked at as passe come back with retro vengeance. For .NET development, the console is back. Consoles combined with lightweight editors like Visual Studio Code are becoming increasingly popular. Call me a hipster, but I’m all for this change. I hate waiting around for my editor and I never have to do that in a console or Visual Studio Code.

Unfortunately, if you’re living in the world of Windows, the default command line options are lacking. Not only are CMD and Powershell ugly, they lack basic usability features found in Linux and OSX. There is a better way. Cmder is a Windows console emulator that bundles several command line tools together into one fantastic package. It’s the Cadillac of Windows consoles.

Here’s what it looks like:

Cmder has a nice tabbed interface. You can run multiple consoles without having to deal with a bunch of windows. It also supports several different types of consoles including: CMD (enhanced with Clink), Powershell, and Bash.

You also get full control of the appearance of the shells including the font, color, etc… Cmder has many themes, but the default Monokai theme is good enough for me.

More importantly, you can create custom tasks. A custom task is a specific command window that you can define. You can specify the shell, what parameters it’s called with, and what directory is opened. You can have a command line setup for each application you work on. You no longer need to open a command line and manually navigate to your app folder each time you open up the console.

To make a custom task, do the following:

From Cmder, type Win + Alt + T. This takes you the tasks windows. You can also click the arrow next to the plus sign and click “Setup Tasks”.

This window allows you to reorder and reorganize the different defaults in Cmder. Hit the plus sign to add your own.

In this case, this is a console task that opens a specific project I’m working on.

After you setup your new task, click “Save Settings”. You should see your new shell in the list of available presets. Then you can open that exact shell whenever you want.

If you want to supercharge your Windows console, check out Cmder.

4 Tips For Blazing Fast ASP.NET Core Applications

I’m a huge fan of ASP.NET Core. It’s a great iteration on the ASP.NET platform and it should be your default choice for any new web development. I’m also a big fan of apps that don’t take a week to load. Fortunately, ASP.NET Core doesn’t skimp in the speed department. The framework has some great features for building fast applications. Some things that used to be hard are now easy.

In this post, I’m going to go over a few tips for building blazing fast ASP.NET applications.

Async Everything

 

One important way to help your application scale is to use asynchronous methods. The async and await keywords make building asynchronous code as easy as building synchronous code. Using async and await frees up your threads while waiting for calls to return. Because you are using up fewer threads, more people can use your application at the same time.

Async is usually a good default practice. But, it’s especially important when calling slower processes, like database calls and service requests. You don’t want to hog up a thread waiting around for database results to come back. When building your application favor async versions when they are available. Entity Framework has async versions of most data access methods, so make use of them.

One thing to keep in mind is that using async and await will help you scale, but it won’t run your requests in parallel. If you have several slow requests, consider running them in parallel using the Task Parallel Library. That will compress your wait time to the longest running call, as opposed to waiting for each one to return sequentially.

Cache Rules Everything Around Me

Getting data out of a database is the largest performance bottleneck in most applications. One way to reduce that cost is to cache things that are slow to retrieve or slow to change. ASP.NET Core has a few built in cache mechanisms.

The easiest cache to use is the built in memory cache. This cache stores items in the memory of your applications server. While this is easy to use, there are two downsides. The first downside is your cache goes away if your server goes down. Often, this is a non-issue, but if your application caches things are costly to calculate, this can be a real downer. The second problem is that if you want to scale your application to more than one server, your’re out of luck.

The solution to this problem is to use a distributed cache. This cache uses either a REDIS instance or a SQL Server table to hold your cached data. I’ve used both flavors and they both work great. One thing I liked about using the SQL Server cache is that I could add fields to the table to enable more detailed caching logic.

Regardless of which caching mechanism you use, you should hide it behind your own cache abstraction. (I call mine ICacheProvider) By using your own cache abstraction, you can easily swap out one caching mechanism for another. Most people start off with the memory caching, but eventually outgrow it. If you put your caching behind an abstraction, you can swap it out for a distributed cache without having to change a bunch of places in your app.

Crush Those JSON Responses With Middleware

By default, ASP.NET only compresses a few types of requests by default. These include the content of Razor pages, but not the results of api calls (JSON is not compressed by default). This means that if you have an api request heavy application (ie. a SPA), you can save some serious bandwidth by compressing those responses. This is especially important if you are serving mobile customers, who may have a low bandwidth signal.

Unlike the previous version of ASP.NET, Core has a handy built in middleware that you can add to your app. You can specify the type of compression and what mime types to compress. I’ve tested this in my application and the compression saves a noticeable amount of bandwidth.

Bundle Those Client Side Assets

Modern applications tend to use lots of JavaScript libraries, images, and fonts. Getting those assets to the client efficiently is important. Especially if those clients are on a low bandwidth connection. We rely on two strategies to minimize what we send to the client. The first strategy is bundling. This is where you take several assets and send them down in one request. This saves you bandwidth because you have less headers sent over the wire. The other strategy is minification. This is where you run JavaScript through a process that strips out any extraneous code, shrinking down the file size.

In the ASP.NET world, there are two paths to do this. If you are building a JavaScript heavy application, like a SPA application, use a JavaScript build tool. Webpack is my preferred JavaScript build tool. It can iterate through your dependencies and then bundle them into files. If you’re using Angular (2+), you should use the Angular CLI. It uses Webpack under the hood, but hides away it’s complexity.

The second way to do bundle and minify assets is to use the Bundler and Minifier Visual Studio extension. This extension compiles your client side assets on build. It is easier to use than JavaScript build tools like Webpack. If you’re using Razor views with a little bit of client side code, this is the way to go.

 

How about you?

If you have a good performance tip, feel free to leave it in the comments.

Angular CLI With .NET Core

Angular is a fantastic platform for building rich client side apps, but let’s not forget about the back end. My choice for the back end is ASP.NET Core. If you’re not shy about spending a bunch of time setting up Webpack, Angular and ASP.NET Core is a fantastic combination.

However, I prefer to spend my time building applications, not configuring build tools. Angular CLI takes a lot of the pain out of using Angular, but it’s a self contained command line tool. Fortunately, Angular CLI and ASP.NET Core can happily co-exist. In this post, we’re going to build an application using these two technologies together. By the end, you’ll be ready to have all the goodness of Angular and ASP.NET Core without spending a week setting up Webpack.

Prerequisites

Make sure you have .NET Core, Node.js and Angular CLI installed.

https://www.microsoft.com/net/core#windowsvs2017

https://nodejs.org/en/

npm install -g @angular/cli 

Getting Started: ASP.NET Core App Setup

Fire up Visual Studio (I’m using VS 2017) and create a new ASP.NET Core Web Application. Select the Web API Starter. This doesn’t bring in any web stuff, which is ideal. We’re going to use Angular CLI to generate the client files.

Then go ahead and disable automatic Typescript compilation. We want CLI to compile our Typescript, not Visual Studio. Do this by adding the “TypeScriptCompilerBlocked” line to your csproj file.

Head on over to the Startup.cs and add in the static files middleware. You’ll have to install the “Microsoft.AspNetCore.StaticFiles” NuGet package. After that, add app.UseDefaultFiles() and app.UseStaticFiles() to your Configure() method.

After you get those setup, you’ll want to add some middleware to redirect those pesky 404s to the root file. This will allow you to navigate the application without having to start at the root each time you hit refresh. For this app, api routes are prefixed with “api”, so we’re excluding those routes from the check. We’re also excluding routes with a file extension since those are likely static assets.

To prevent the app from loading up the api/values endpoint by default, go to properties/launchSettings.json and change the “launchUrl” keys from “api/values” to “”.

At this point, our .NET Core app should be ready to go. Let’s move on to the Angular code.

Setting Up Angular CLI

We’re going generate our Angular app on top of our ASP.NET core app. To do this, go to the command line and navigate to the directory of your solution file. Then run “ng new <your app name>”.

You want the <app name> part to be the same as your .NET Core source folder. This will drop all of the CLI files into your ASP.NET Core root folder. It should look like this:

Gluing It All Together

Angular has a default file structure, but it’s not ideal for the existing ASP.NET Core application. Fortunately, Angular CLI has some options that will allow us to change this structure. We want the client side code to be in a folder called “client-src” and the client side build artifacts to go to the wwwroot folder. To do this, rename the “src” folder to “client-src”. Then go to go to .angular-cli.json. This is the primary configuration file for Angular CLI. First, change “src” to “client-src”. Then change the “outDir” attribute from “dist” to “wwwroot”. This will drop all of the compiled assets into the wwwroot folder.

At this point, we can build the Angular application using Angular CLI. Navigate a command prompt into the main application folder and run “ng build”. This command will build the client side part of the application, dropping the build artifacts into wwwroot. The wwwroot folder should look like this:

  

At this point we should be able to run the app by hitting the Run button in Visual Studio. Unfortunately, we still have a two stage build pipeline. The first step being “ng build” to generate the client side files and then running the .NET Core app. To fix this, we can drop in a post build script: “ng build — aot”. This will compile the client side files (with ahead of time compiling) after the app builds.

Bonus Points

If you’re using git, you’ll want to add the wwwroot folder to your .gitignore file. These files are generated, so you probably don’t want to check them in.

Example Code

All of the demo code used in this post is available here:

https://github.com/DustinEwers/shiny-angular-demos/tree/master/ninjas-quest-cli-core/ninjas-quest

This demo includes a full Angular application on top of ASP.NET core. Feel free to use this as a template or something to look at while building your own. You now have everything you need to get started building shiny applications using Angular CLI and ASP.NET Core.

The State of Local Profiling on ASP.NET Core

If you want to improve it, you need to measure it. We use profiling tools to get the insight required to find and destroy application bottlenecks. I’m a big fan of local profiling tools that you can install and run from within your application. My favorites are Miniprofiler and Glimpse. Unfortunately, many of the tools that are available on regular ASP.NET are not available for ASP.NET Core. In this post, we’re going to explore our options for local profiling in ASP.NET Core. Currently, it’s slim pickings, but there are a few tools available.

Combing the Desert

The state of .NET Core Local Profiling Tools

For standard ASP.NET (non-core) Applications, there are a variety of profiling tools available. Some of those tools cost money and others are free. Unfortunately, most of them lack ASP.NET Core support. This is, in part, because ASP.NET Core is new. Additionally, our good friends at Microsoft have thrown the community a few curve-balls with the last few versions of the .NET Core. Most companies don’t want to waste their time building tools if the framework is going to have a ton of breaking changes. This is especially true for free tools.

Here’s the status of a few popular tools (as of January 2017):

MiniProfiler
The folks at Stack Overflow are waiting for a more stable version .NET Core to build their .NET core version of Miniprofiler. They said they will build a new version, but they only want to do it once.

dotTrace
JetBrains has not released a .NET Core version of dotTrace, though they claim some functionality with the current version. I’ve never tried this one, so I have no idea if it’s worth waiting for.

Glimpse
I love Glimpse. It’s one of my favorite profiling tools. The folks behind Glimpse put out a Beta version of Glimpse about a year ago. It lacked full functionality and no longer works. They appear to be working on the new version now. Their GitHub repo has recent check ins, so I’m hoping a new version appears soon.

Application Insights
This is Microsoft’s default solution for application performance monitoring. It’s meant to be used in conjunction with Azure, but you can run it locally and use Visual Studio to look at the results. Once hooked up to Azure, you can use this as a general application performance monitoring (APM) tool. It’s installed by default in new ASP.NET Core Projects (look at the startup.cs), so Microsoft really wants you to use it. I kicked the tires a bit. Prefix is a competent option for ASP.NET Core.

Application Insights in action:

Stackify Prefix
Stackify prefix is a free tool you can install on your PC that monitors your ASP.NET applications. You’ll need to also install it in your project, but once you do so, you get access to detailed information about your application’s requests. They have a paid version of the Prefix and a related APM product, so there’s some commercial backing here. I’ve tried out Prefix a few times and the tool is adequate for local profiling. It gives you the data you need, but I’m not a huge fan of the development experience. That being said, the tool gives you access to lots of data and works on .NET Core.

Stackify Prefix in action:

Conclusion

I’m still waiting for a new version of Glimpse (or Miniprofiler), but Stackify Prefix and Application Insights are good tools. I miss the easy to use inline monitoring of Glimpse, but Prefix and Application Insights have their advantages. Not only are they supported on .NET core, they also hook into more robust monitoring systems. You will be well served by either option. Go forth and monitor your apps, it’ll save you a lot of pain down the road.

How to Turn Off TypeScript Automatic Compilation in Visual Studio

TypeScript is a first class citizen in the Visual Studio universe. By default, Visual Studio will compile your typescript files whenever you save them. This is great for many types of TypeScript projects, unless you’re using a tool like Webpack or Gulp. These tools handle TypeScript compilation by themselves. You don’t want Visual Studio to waste your time generating spurious files. Fortunately, it’s easy to disable automatic TypeScript compilation. Just add a “TypeScriptCompileBlocked” element to your project’s xproj file and give it a value of “True”. This will prevent Visual Studio from making those pesky extra files.

Set the TypeScriptCompiledBlocked to True in the Xproj file

Disabling automatic TypeScript Compilation

Taming the JavaScript Dragon with TypeScript

 

The year was 1995. “Gangsters Paradise” topped the music charts. Pixar released Toy Story, the first wholly computer generated film. And, in just 10 days, Brendan Eich created a language for adding dynamic content to web pages. From these humble beginnings, JavaScript has become one of the most popular programming languages in the world. Outgrowing its initial purpose by several orders of magnitude. You can now use JavaScript to build nearly anything, from web pages to robots. JavaScript is the Swiss army knife of programming languages and one of the best tech career investments you can make. Not bad for a language someone threw together in a few weeks.

Unfortunately, it’s not all puppy dogs and rainbows. JavaScript is a landmine ridden kludge of a language. It uses a class system that most programmers are unfamiliar with (prototypical class), is loosely typed, encourages the use of global variables, and has lots of weird quirks like the “this” keyword. Despite all this, JavaScript has two things going for it. First, JavaScript runs on every web browser, which means it’s available on every computer. It’s the only scripting language that can run on any browser. Second, smart people have created patterns that expose the “good parts” of JavaScript and overcome the bad parts. The current popularity of JavaScript today is made possible by a community of highly skilled developers that have figured out how to make the most of an imperfect language.

Even with smart design patterns, JavaScript’s failures are magnified on larger projects. It’s simply not built for 100+ kloc applications.

Additionally, the lack of static typing means it’s hard to implement the static code analysis that’s common in tools for enterprise languages like C# and Java. This means that you also miss out on refactoring tools, which you would want on a large code base. I’m sure there’s a contingent of Notepad lovers who think tooling is for sissies, but most of us have better things to do than spend six hours staring at a screen looking for a typo an IDE could of dropped a squiggly line under in two seconds. It’s a craft, not a religion.

Dependency management in JavaScript can also be a chore. The lack of a proper module system makes it tough to break apart functionality. Node.js does a great job of getting around this limitation with it’s module pattern and NPM, but it should be baked into the language.

Fortunately, we have some options. ECMAScript6 (ES6), the new version of JavaScript, has recently been ratified. This new standard addresses many of the issues with building large JavaScript applications. Unfortunately, most browsers don’t support ES6 yet. Why let little things like browser support stop you? There are lots of tools that allow you to use ES6 features today. These tools will take your code and transpile it down into plain JavaScript that can run on any browser. Among these tools, my favorite is TypeScript.

What’s TypeScript?

TypeScript is a language developed by Microsoft. The goal of TypeScript is to add features to JavaScript that make it usable on large projects. TypeScript is a superset of JavaScript. This means that valid JavaScript is also valid TypeScript. All you have to do is rename your *.js files to *.ts files and they’ll usually work. Also, the compiled output of TypeScript is readable, which makes debugging much easier. If you’re used to C# and you hate how loose JavaScript is, Typescript will help fix that. If you’re primarily a JavaScript developer, Typescript gives you additional powers without having to learn a totally new language.

TypeScript has two primary features:

Optional Static Typing

The namesake feature of TypeScript is the addition of an optional static typing system. While this doesn’t sound like much, it gives you access to much better tooling. Modern IDE’s, like Visual Studio, rely on static typing to provide robust code analysis and intellisense. JavaScript has some of these features, but lacks the level of code analysis available to C# and VB.

New JavaScript (ES6 / ES7) features

The TypeScript team is committed to implementing new JavaScript features in TypeScript. While they don’t have the level of support dedicated ES6 transpilers like Babel have, TypeScript is close behind. Much like HTML5, ES6 was created with large scale modern web applications in mind. The most important features in ES6 are classes and modules. TypeScript implements both of them.

What about the competition?

While TypeScript is a great language, it does have competitors. In fact, there are over 250 different languages that compile to JavaScript. There are two major categories of compile to JavaScript technologies.

Replace JavaScript with another language

This category includes languages like CoffeeScript and Dart. Their general philosophy is that JavaScript is broken and we need a new language to fix it. I don’t buy that argument. JavaScript is not broken because it doesn’t behave like your pet language. TypeScript has two advantages over these types of languages.

The first is that you don’t need to learn a totally new language to use TypeScript. You’re just adding features to existing JavaScript. If you don’t like the way TypeScript does something, just do it the vanilla JavaScript way. You can go as far down the rabbit hole as you like. Your existing JavaScript knowledge remains useful.

Second, languages like this are leaky abstractions. Because you’re compiling down into JavaScript, you’re going to have to debug in JavaScript. You still need to have strong JavaScript knowledge. TypeScript adds to your JavaScript skills instead of replacing them.

Implement ES6 features today

This category includes transpilers like Babel and Traceur. These options support more new features than TypeScript, but TypeScript still has static typing. Also, TypeScript is also built into Visual Studio, which makes it easier to use (for ASP.NET developers) than ES6 transpilers. TypeScript is going to give you a better tooling experience than ES6 transpilers.

How to get started?

The easiest way to get started with TypeScript is to use the TypeScript Playground. It’s an interactive tool that walks you through the features of TypeScript. You can play with the TypeScript code and see how it compiles into JavaScript. It’s a good way to quickly get a feel for the language.

Visual Studio and Visual Studio Code both support TypeScript out of the box. You can also use NPM to install a TypeScript compiler for use in your Node.js or Cordova projects. TypeScript is also supported (via extensions) by many text editors, including Atom and Sublime Text. Regardless of what your preferred tools are, TypeScript is likely a viable option.

Additional Resources:

The TypeScript Handbook
Kangax ES6 Compatibility Table

Purify Your Razor Views With Tag Helpers

Hate mixing HTML and C# code in your Razor views? Work with designers who are markup ninjas, but scratch their heads at a view full of HTML helpers?

If so, then ASP.NET vNext has a feature for you. It’s called tag helpers. Tag helpers are custom HTML attributes or tags that you place in your view code. Using tag helpers, you can remove most of the C# code from your views. You can use them instead of HTML helpers. Like HTML Helpers, they render in the browser as standard HTML.

Note – This post covers Tag Helpers in the *-beta4 version of ASP.NET MVC.

All of the source code used in this post can be found on github at https://github.com/DustinEwers/dot-net-mvc-ui-demos. Look in the ASPNET5 folder.

Using Tag Helpers

Here’s an example of tag helpers in action:
Tag Helper View Photo

Notice the lack of C# code. Almost everything here is markup. All the HTML attributes that begin with “asp-” are tag helpers. This form is from the default ASP.NET template. For comparison, here’s a similar form (from the template in the last version of ASP.NET MVC) built using standard HTML helpers:
Standard View Photo

ASP.NET MVC comes with lots of built in tag helpers. Here’s some of the more notable ones:

  • asp-for -> Adds the model specific attributes to the HTML element. This replaces HTML Helpers like “Html.LabelFor” and “Html.TextBoxFor”
  • asp-controller and asp-action -> Works with your form tags to emit the appropriate route. These replace “Html.BeginForm”
  • asp-items -> Populates your dropdown list with items from the model.
  • asp-validation-for -> This attribute is used to populate the validation summary at the bottom of each element.

To use tag helpers in your project, you need to ensure the tag helper directive is in your project.

@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"

This directive points to the assembly that contains the tag helpers. This will give your project access to the standard ASP.NET tag helpers. You can either put this on the page that uses tag helpers, or you can put it in a global page like _ViewStart.cshtml. In the default template it’s in _GlobalImport.cshtml.

Making Custom Tag Helpers

The built in tag helpers are great, but you can also make your own tag helpers. A tag helper is a filter. They allow you to change the tag’s output while it’s being written to the view. Here’s a tag helper that creates a Bootstrap form group container:

    public class FormgroupTagHelper : TagHelper
    {
        private const string SizeAttributeName = "size";

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            int size;
            Int32.TryParse(context.AllAttributes[SizeAttributeName].ToString(), out size);

            output.TagName = "div";
            output.Attributes["class"] =  string.Format("form-group col-md-{0}", size);
            output.Attributes.Remove(SizeAttributeName);
        }
    }

In this example, we change the name of the tag to a div, take a parameter from an attribute, add a css class, and remove the size attribute (a custom attribute we are using as a parameter).

To build a custom tag helper, you first need to build the tag helper class. Naming is important. The class name must end with “TagHelper” and inherit the TagHelper class. Then you can override the Process or ProcessAsync methods to add your custom logic. In the process method, you can alter the tag in any way you like. You can add or remove attributes and classes. You can also change the name of the tag.

After building your tag helper class, you need to add another addTagHelper directive to your view. This one will be for the assembly that contains the tag helper.

Then, you can use your tag helper in your views. Here’s our formgroup tag helper in action. The “size” parameter is used by the tag helper to set the container size for the form group.

<formgroup size="4">  
   <label asp-for="Address1"></label>
   <input asp-for="Address1" class="form-control" />
   <span asp-validation-for="Address1"></span>
</formgroup>  

And this is a whole page using both custom and built in tag helpers:
Custom Tag Helpers Photo

Conclusion

Tag helpers are a great new feature in ASP.NET vNext. With them, you can make views that look more like web pages than a weird hybrid of web pages and C#. Start up a project in Visual Studio 2015 or grab my demo code and check out tag helpers for yourself.

Additional Resources:
Demo Code

Tag Helpers Source Code

Visual Studio Goes Cross Platform with Visual Studio Code

Today, Microsoft kicked off Build 2015. Among the long list of exciting developments, Microsoft released the first cross platform version of Visual Studio. This new version of Visual Studio is called Visual Studio Code (or VSCode). It’s a lightweight code editor that runs on Windows, Linux, and OSX.

VSCode is built for Node.js and ASP.NET web app development, but it also support lots of other languages. In addition to the languages you’d expect from a Microsoft code editor (C#, JavaScript, TypeScript, F#, etc…), VSCode also supports a laundry list of other languages like C++, PHP, Python, Java, R, Objective-C, PowerShell, and Markdown ( full fist of supported languages ).

While VSCode isn’t a full IDE like the Visual Studio we all know and love, but it does have a lot of features that take it beyond a basic text editor.

Features:
  • Node.js debugging (ASP.NET 5 and other languages are on in progress)
  • Built in Git support
  • Multiple cursors, just like Sublime Text or Atom
  • Intellisense (for Node.js and ASP.NET)
  • Static Code Analysis and Refactoring (for C#, JavaScript, and Typescript)
  • Automatic updates
  • A fast release cadence, with releases coming every few weeks, instead of every few months.
  • Ability to customize keyboard shortcuts and add custom tasks

First Impressions

As a Mac owner who does ASP.NET development, I immediately downloaded a copy of VSCode and started playing with it. To me, VSCode feels like a cross between Visual Studio and Sublime Text (or Atom). On my Mac, it feels snappy and responsive. The intellisense is instant, but I’ve noticed some that it doesn’t include all the files (probably a setup issue on my part).

Visual Studio Goes Cross Platform with Visual Studio Code

VSCode also supports static analysis. This means you can find references and view definitions. I tried a “Find All References” and it took a little longer to pop up, but I like the inline reference window. “Goto Definition” and “Peek Definition” were instant, however.

Visual Studio Goes Cross Platform with Visual Studio Code

Multi-cursor is my favorite text editor feature. I bought a copy of Sublime Text specifically for it’s multi-cursor support. Multi-cursor has saved me tons of time. VSCode has the best multi-cursor support I’ve seen. ( More Info )

Visual Studio Goes Cross Platform with Visual Studio Code

Verdict

In the past few years, I feel like code editors have taken some huge steps forward. Sublime Text set a benchmark for excellence and several competitors have stepped up to the plate. The best one I’ve seen before VSCode was the Atom editor. While it wasn’t good enough to take me away from Sublime, I thought it was a solid piece of software.

At my day job, besides Visual Studio 2013, I use Sublime Text. Sublime has saved me countless hours of time by making repetitive code chores easier. VSCode does all the things I currently use Sublime for AND it has built in support for ASP.NET. I’m definitely going to add VSCode to my developer tool belt.

Where Can I Get It?

Visual Studio Code is available for free at https://code.visualstudio.com/

Documentation can be found at https://code.visualstudio.com/Docs

How to Build HTML Helpers like Html.BeginForm() in ASP.NET MVC

If you’ve used ASP.NET MVC for more than five minutes, you’ve probably used the Html.BeginForm helper method.


@using (Html.BeginForm()) {
// Form Fields go here
}

This method wraps your content in a form tag. It’s a handy way to build forms, but we can also create our own html helpers for other container elements. In this post, I’m going to show you how to wrap a Bootstrap row in an HTML helper.

Bootstrap, the UI library that comes with .NET, makes it easy to build professional looking web applications. One of it’s primary disadvantages, however, is that you have to write a lot of markup to get your layouts to work correctly. We can reduce this by creating a custom HTML Helper that works like Html.BeginForm().


@using (Html.BeginRow()) {
// Grid content goes here
}

Step 1

Create a Private Class that implements IDisposable. Have the constructor take a TextWriter object. Set the dispose method to use the text writer to output the closing tag for the row.


private class RowContainer : IDisposable {
    private readonly TextWriter _writer;

    public RowContainer(TextWriter writer) {
        _writer = writer;
    }

    public void Dispose()
    {
        _writer.Write("</div>");
    }
}

Step 2:

Create an HTML helper extenstion method that creates the beginning tag and returns the object created in Step 1. You can use ViewContext.Writer to directly output the markup.


public static IDisposable BeginRow(this IHtmlHelper htmlHelper, string cssClass = "") {
    var writer = htmlHelper.ViewContext.Writer;
    writer.WriteLine(string.Format("<div class='row{0}'>", cssClass));
    return new RowContainer(writer);
}
 

Step 3

Use the helper in your Razor view with a using statement, just like BeginForm(). When the using statement disposes the returned object, it’ll close out the tag.


@using (Html.BeginForm()) {
// Form Fields go here
}

Additional Information

Full Code

OR/M Pain: Maybe Stored Procedures Aren’t So Bad

When I first started using OR/M, I looked forward to not writing boilerplate SQL code. As a lazy developer, I prefer to automate boilerplate code generation. After using OR/M for couple of years, I am beginning to miss stored procedures. OR/Ms like Entity Framework reduce the need for cookie cutter code, but they have some major flaws.

The first flaw is that OR/Ms are a leaky abstraction. The goal of any abstraction is to hide the internals of the thing you are trying to abstract. OR/Ms fail at this. Entity Framework, the OR/M I use the most, falls down on complex queries. For example, if you want to join in a related entity, you can use the Include() statement. The problem with Include() is that it generates horrendous queries that have terrible performance. You can’t do more than three or four includes in a single query. You end up having to either do a bunch of small queries or build a stored procedure. This defeats the purpose of OR/M.

The second flaw is that configuring complex relationships can be painful. I’ve used nHibernate (Fluent API) and Entity Framework (Code First,). Configuration in both OR/Ms is painful. I have spent hours trying to configure a particular database relationship. I’ve done small model changes generate migration scripts that left me scratching my head. One major advantage of Entity Framework is that the documentation is excellent. MSDN does a good job of highlighting common configurations, and there’s lots of information on the web.

The final flaw of OR/M is that you lose the ability to use a lot of features of the database. For example, until recently, you couldn’t create a unique key in Entity Framework. Entity Framework still doesn’t support database triggers. You can live without these features, but it does limit what you can do with OR/M.

This leads us to the obvious question:

Are OR/Ms a waste of time?

The answer, of course, is “umm… maybe”.

If you have a project with a simple data model or low performance requirements, OR/Ms will save you time. If your project is more complex, then you should consider skipping the OR/M. There’s nothing wrong with using stored procedures. Sometimes the old ways are the best ways.

More on OR/M Pain:
Bendyworks: Actually Using the Database

Seldo.com ORM is an anti-pattern