ASP.NET Core and .NET Core Overview

ASP.NET Core and .NET Core Overview

Microsoft’s big shift

A lot is happening in Microsoft land and the future looks very exciting as a .NET developer with the introduction of .NET Core and ASP.NET Core, making it possible to run .NET on any platform.

Times are changing, also within Microsoft. They created the .NET foundation and open sourced a lot of projects. For instance .NET is now open source and developed on Github, making it possible for everyone to contribute.

Red Hat has partnered up with Microsoft and joined the .NET foundation alongside with JetBrains and Unity. Microsoft partnered with Canonical – the company behind Ubuntu, making it possible to run Ubuntu on Windows.

Not long ago Microsoft acquired Xamarin, open sourced its SDK under the MIT license and made it a part of the .NET foundation. With Xamarin along came Mono. Microsoft changed the license of Mono from GPGL to MIT and put it in the .NET foundation as well.

SQL Server will be released for Linux and is scheduled for 2017.

ASP.NET 5 is killed and renamed to ASP.NET Core 1, because as the name indicates, it’s a totally new framework. With .NET Core and ASP.NET Core Microsoft takes a huge step in becomming platform independent, as both run on Windows, Linux and Mac. ASP.NET 4.6 will continue to be developed and supported, and new features are yet to be added. ASP.NET Core is still fresh from the oven, and lacks several of the features from ASP.NET 4.6, but we will most likely see it mature and be up to speed in version 1.3 or 1.4. Microsoft have been a bit vague about the future for ASP.NET 4.6 and onwards, but it looks like it’s slowly getting phased out. My idea is that the development of ASP.NET will stop when ASP.NET Core is fully matured.

The future of .NET

Let’s take a glance at the .NET family to get a better understanding of what the future holds and how the different frameworks will be structured. On the top layer in the diagram below we have the app models; .NET Framework, .NET Core and Xamarin, which all share the same base class library (BCL) called .NET Standard Library. Instead of adding new features to either of the 3 stacks, they will be added in the .NET Standard Library and shared across.

.NET Framework is meant for Windows Presentation Foundation (WPF) apps, Windows Forms and ASP.NET, where as .NET Core is meant for Universal Windows Platform (UWP) and ASP.NET Core applications.

.NET Core

On microsoft.com/net things are clarified further. Basically the .NET Framework is meant for Windows development. That being native, mobile and web applications running in the Windows ecosystem.

.NET Core on the other hand is meant for cross-platform applications, which can run on either Windows, Linux or Mac.

Any developer, any app, any platform

.NET Overview | Build 2016

In the following video from Build 2016 Scott Hunter and Scott Hanselman gives an overview of the future for .NET. In the end of the video Todd Mancini from Red Hat demonstrates how to deploy a ASP.NET/Core application to Red Hat Enterprise Linux, running in a Docker container.

Go checkout redhatloves.net (how cool is that!?) and signup for the Red Hat developer program and download Red Hat Enterprise Linux for free, and play around with it yourself.

ASP.NET Core

ASP.NET Core 1 can run on both .NET Framework 4.6 and .NET Core 1.0, whereas ASP.NET 4.6 is meant to only run on .NET Framework 4.6.

ASP.NET Core

ASP.NET Core even though not yet fully matured, holds a lof of exciting features. First and foremost it allows us to run our applications on Linux and Mac. It’s modular, which means that it’s stripped for most frameworks and libraries we might not even need in our application. For instance you have to include error pages yourself, which also opens up for customization  so we can have company specific error pages. You can choose if you want to include MVC or Nancy, should you prefer the latter.

ASP.Net Core is fast! According to Microsoft you’ll see a 10x speed increasement, moving your current MVC application to ASP.Net Core.

ASP.NET/Core Overview | Build 2016

The two Scotts are at it again in this next video from Build 2016, where they show some really cool features of ASP.NET Core. For instance the best demo in the entire world – must watch!

Now, go code…

We are moving towards a more platform independent future, and it has never been more exciting to be a .NET developer as it is today. The cool thing I’m stoked about and think a lot of fellow developers are as well, is that we can now develop .NET applications directly from OS X, without having to open up Parallels. We are not fully there yet though, with frameworks and libraries still missing, but it’s a start. Head over to microsoft.com/net to get going!

Visual Studio 2013 high CPU usage

If you experience extreme typing latency and Visual Studio is using high amount of CPU, even when idling, check if you have “Browser Link” enabled. I started experiencing latency when typing, after working just 5 minutes in Razor Views. CPU usage was consistent at 37-40%. Browser Link is a new feature in Visual Studio 2013 and enables dynamic data exchange between Visual Studio and your web application.

If you are interested in knowing exactly how Browser Links works, you can read more here.

Or if you just want to disable it straight away, do as shown in the picture.

Visual Studio 2013 Browser Link

WCF return JSON, AJAX-enabled WCF Service in less than 3 minutes

I was about to set up some WCF services to handle POST requests to SolrNet and was digging around for solution. Goal was to post a string query to the web service and get JSON objects returned. This can be obtained pretty easily with an AJAX-enabled WCF Service and a bit of jQuery.

Actually you can have this example going in less than 3 minutes!

To serialize my objects to JSON I’m using a ToJson extension method written by Scott Gu. This makes it very easy to just use .ToJson() on your objects or collections, just like using ToString().

Steps to build the web service

1. Create a new WCF Service Application and delete the files IService1.cs and Service1.svc
2. Right click your solution and Add New Item. Search for “Ajax enabled” and choose AJAX-enabled WCF Service.
3. Create a folder called “Helpers” in which you create a static class called “JsonHelper” with the following methods:
[csharp]
public static class JsonHelper
{
public static string ToJson(this object obj)
{
var serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}

public static string ToJson(this object obj, int recursionDepth)
{
var serializer = new JavaScriptSerializer();
serializer.RecursionLimit = recursionDepth;
return serializer.Serialize(obj);
}
}
[/csharp]

The method takes your object, serializes it to JSON and returns it.

4. Open up your newly created AJAX-enabled WCF Service – Service1.svc and delete the method OperationContract method DoWork().
5. Create a new OperationContract method called HelloWorld() which will look like this:
[csharp]
[OperationContract]
public string HelloWorld(string personName)
{
return (new HelloWorldWrapper
{
Response = string.Format("Hello, {0}", personName),
Error = "",
TimeExecuted = DateTime.Now.ToString(CultureInfo.InvariantCulture)
}).ToJson();
}
[/csharp]

6. Create a wrapper class for your Hello World method, which we will create a new object of, serialize to JSON and return.
[csharp]
public class HelloWorldWrapper
{
public string Response;
public string TimeExecuted;
public string Error;
}
[/csharp]

Test test test!

Now you are actually done, but lets test the service. For that we’ll need a HTML page where we execute some jQuery and call our web service. Note that this service will be hosted on a IIS, where as your your front-end call can be on what ever server and site you want.

Right click your project and Add New Item. Create a Web Form for the ease of it.
In the head section insert:
[js]
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
var personNameVar = "Paul";
var dataIn = ‘{‘ + ‘"personName":"’ + personNameVar + ‘"}’;
$.ajax({
url: "/Service1.svc/HelloWorld",
type: "POST",
contentType: "application/json; charset=utf-8",
data: dataIn,
dataType: "json",
success: function (data) {
var object = JSON.parse(data.d);
if (object.Error == ”) {
//Alert the persons name
alert(object.Response);
}
},
error: function (error) {
alert("Error: " + error.Error);
}
});
</script>
[/js]

We are making an AJAX-call to our web service, located at “/Service1.svc/HelloWorld”, sending a post request in JSON format, containing the string personName. In our success function we receive our JSON serialized object and get the Reponse string returned in a alert box.

CTRL+SHIFT+B your project, right click HelloWorld.aspx and “View in Browser”.

For the lazy ones i made a Visual Studio 2012 project on .NET 4.5 framework containing the example. Download: Ajax WCF Test

.gitignore Windows

It’s a good idea to add a .gitignore file to your Git-repository, to keep Git from keeping track of certain files and/or folders. This could be Visual Studio debug/build files, etc.

The problem in Windows however, is that you can’t just create a text file and rename it to “.gitignore”, as you’ll see the error:

Gitignore Windows

A little trick, is to create a text file and rename it to:
[code].gitignore.[/code]

Windows now lets you create the file.

Here’s a sample .gitignore, which tells Git to ignore the most common files not needed in the repository.
Place the file in your Git-repositories root directory (/projectname/.gitignore).

[code]
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.

# User-specific files
*.suo
*.user
*.sln.docstates

# Build results

[Dd]ebug/
[Rr]elease/
x64/
build/
#[Bb]in/ #(Keep "bin" folder in repo. Uncomment to remove)
[Oo]bj/

# Enable "build/" folder in the NuGet Packages folder since NuGet packages use it for MSBuild targets
!packages/*/build/

# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*

*_i.c
*_p.c
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.scc

# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
*.cachefile

# Visual Studio profiler
*.psess
*.vsp
*.vspx

# Guidance Automation Toolkit
*.gpState

# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper

# TeamCity is a build add-in
_TeamCity*

# DotCover is a Code Coverage Tool
*.dotCover

# NCrunch
*.ncrunch*
.*crunch*.local.xml

# Installshield output folder
[Ee]xpress/

# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html

# Click-Once directory
publish/

# Publish Web Output
*.Publish.xml
*.pubxml

# NuGet Packages Directory
## TODO: If you have NuGet Package Restore enabled, uncomment the next line
#packages/

# Windows Azure Build Output
csx
*.build.csdef

# Windows Store app package directory
AppPackages/

# Others
sql/
*.Cache
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.[Pp]ublish.xml
*.pfx
*.publishsettings

# RIA/Silverlight projects
Generated_Code/

# Backup & report files from converting an old project file to a newer
# Visual Studio version. Backup files are not needed, because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm

# SQL Server files
App_Data/*.mdf
App_Data/*.ldf

# =========================
# Windows detritus
# =========================

# Windows image file caches
Thumbs.db
ehthumbs.db

# Folder config file
Desktop.ini

# Recycle Bin used on file shares
$RECYCLE.BIN/

# Mac crap
.DS_Store
[/code]

Run URL from ASP.NET/C#

Sometimes it can be handy to run a URL from a ASP.NET page (eg. aspx, ascx or MVC control). It could be simply executing one or more webservices, without wanting a result back.

It’s actually pretty simple!

[csharp]
string url = "http://egeek.dk/service.ashx";
using (System.Net.WebClient client = new System.Net.WebClient())
{
client.DownloadString(url);
}
[/csharp]

Create and pull from shared repository with Git in 5 steps

Earlier, I have been using Mercurial for source control, but at my new job, we decided to go with Git. Even though both solutions are much alike, there’s still new stuff to be learned and explored. I’ll try to post some guides and tips as I adventure into the world of Git.

First a quick 5 step guide to create a shared repository on your local disk or network drive, and then pull it to your working directory.

Create repository:
X:\Projects\git init --bare test_project.git

Pull repository:
C:\Projects\git clone file://X:/Projects/test_project.git
Put files into your repository

git add .
git commit -a -m"Initial commit"
git push

That’s basically it!
I’ll post a more in depth guide with explanations later on.

Visual Studio 2012, Web Essentials 2012, Net 4.5

The 15th of August Microsoft released Visual Studio 2012 and .NET Framework 4.5 to Web.
Several usefull tools and blog posts followed the hours after.
Download: Visual Studio 2012

Mads Kristensen from Microsoft also released a new version of Web Essentials for Visual Studio 2012. The essenstials extension let you perform common task faster and easier. Pretty essential indeed ;)
Download: Web Essentials 2012

While your at it, remember to grab the newest versions of JetBrains ReSharper for Visual Studio, which makes your life a lot easier as a programmer. Once you tried it, you wonder how you could ever live without. Resharping, code elimination, autocomplete, etc, etc…
Download: ReSharper

Schott Hanselman wrote a blogpost and posted several videos on getting up to speed with .NET 4.5 and Visual Studio 2012: Visual Studio 2012 and .NET Framework 4.5 is RELEASED – Here’s 5 minute videos to get you up to speed quick

Jason Zander, Vice President for the Visual Studio team wrote a “Top 12 of Visual Studio 2012

Visual Studio 2012

Add href to all img jQuery

This simple function will add a href to all images on your page and link them to the img src
[js]
$(‘img’).each(function ()
{
var currImg = $(this); // cache the selector
currImg.wrap(““);
});
[/js]

It is also possible to only append href to images with a certain class or in a specific div
[js]
$(“.myDiv”).find(‘img’).each(function () {
var currImg = $(this); // cache the selector
currImg.wrap(““);
});
[/js]

I have used this option to load images with Lightbox2, using the following code
[js]
$(“.myDiv”).find(‘img’).each(function () {
var currImg = $(this); // cache the selector
currImg.wrap(““);
});
[/js]

Use Enter as Tab in Windows Forms

Recently I made a Windows Form Application with a lot of text boxes for my work.
After hours of use and testing, we found out it would be more efficient if it was possible to tab from box to box hitting ‘enter’ instead of the tabulator key. Even though you by standard can’t assign it in Visual Studio, it’s actually fairly easy to implement.

All you need to make is one event handler and assign your text boxes ‘KeyDown’ action to use the handler.

[csharp]
//Event handler to handle ENTER as TAB in TextBoxes
private void General_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
this.ProcessTabKey(true);
}
}
[/csharp]

Select your Text Boxes, go to the properties windows and select the lightning icon. Scroll down to “Key”. Under ‘KeyDown’ select your newly created event handler “General_KeyDown’.

Use Enter as Tab in Windows Forms