Showing posts with label ASP. Show all posts
Showing posts with label ASP. Show all posts

Wednesday, January 7, 2015

Intro to ASP.NET MVC 4

The ASP.Net MVC 4 framework was introduced in August of last year and it boasts tons of improvements over MVC 3. If you’re considering building a large application in .Net, you should consider MVC 4 for your project. Today we’re going to take a look at it and build a quick website in MVC 4.

What you’ll need

In order to complete this tutorial you will need Visual Studio. I have decided to use Visual Studio Express 2012 for Web to do this tutorial. I made this choice because it’s a free download and not everyone can afford the professional version of Visual Studio, but if you’re using Visual Studio 2010 or 2012 you can still go along as well.

Software needed:

Microsoft Visual Studio Express 2012 for Web (or a licensed version of Visual Studio 2010/2012)
Microsoft Web Matrix 2 - This is a handy little stack to help organize your server and projects for development
Microsoft ASP.Net MVC 4 - The package you’ll need to install to deploy this on your website.
Keep in mind all of this is free! The MVC package is also Open Source. It’s nice to see Microsoft come around with stuff like this.

Let’s get set up

One of the things every Visual Studio has been raving about lately is the NuGet package manager, for good reason. It makes setting things up super easy. We want to make sure we have it installed for our project.
Go to Tools -> Extensions and Updates
How to Program ASP.Net MVC 4
And make sure the NuGet Package Manager is installed:
How to Program ASP.Net MVC 4
This will enable you to install stuff into your website easily. They have a lot of great plugins and templates available.

Create the Project

Go to the start section and click “New Project” or select it from the File menu. You want make sure to select an ASP.NET MVC 4 Web Application.
How to Program ASP.Net MVC 4
On the next screen, select “Internet Application”. As you can see there are various options here, feel free to play around with them and see what you come up with.
How to Program ASP.Net MVC 4
Now you’ve created your new MVC application. Let’s take a look at it. If you press F5 you’ll see it’s already assembled into a site. But that doesn’t do much yet.
How to Program ASP.Net MVC 4

The parts of your MVC application.

You’ll notice the controller is opened automatically. Let’s take a look at it and see what it does:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }

As you can see this is the “Home” controller that extends the controller class. Since Home is your default route it will control what’s seen on your site root.

1
2
3
4
5
public ActionResult Index()
    {
        ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
        return View();
    }

This is the “Index” method, and it’s not too tough to guess it’s place. This is what shows up when you hit a root directory. Whatever you put in here gets shown on the page. But let’s look a little closer inside the method.
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
The ViewBag is a wrapper object used to store dynamic data for the ViewData dictionary object. There are some arguments circulating about which one to use, but since Visual Studio stuffs this in, we’ll use it. Let’s change it to something else:
ViewBag.Message = "This is my first MVC Project!";
Where does this data go? If you open up /Views/Home/Index.cshtml you’ll see where this object is used.
How to Program ASP.Net MVC 4
First, at the top you’ll see where the ViewBag.Title property is assigned a value:

1
2
3
@{
    ViewBag.Title = "Home Page";
}

This is a part of the Razor engine and it’s how you change the title of the page when it loads. You can also change it later. Then further down the page you’ll see:

1
2
<h1>@ViewBag.Title.</h1>
 <h2>@ViewBag.Message</h2>

As you can see, this is where the ViewBag.Message you changed earlier will go.
One advantage of this is you can make the text displayed dynamic, pulled from a database, object or other data source without touching the design. You can also use this for localization if needed. The Razor engine is pretty sweet, this is just scratching the surface of it.

Creating a New Page

By now you’ve probably figured out that the methods in the controller correlate with pages: Index(), About(), and Contact(). So let’s look at creating a new page. We will be creating a page located at “http://(your site url)/Home/Newpage”.
1. Create a new ActionResult Method
Inside your HomeController, create a new method:

1
2
3
4
5
public ActionResult Newpage()
{
  ViewBag.Message = "This is a new page! ";
  return View();
}

The home controller is found in /Controllers/HomeController.cs
What is this? The HomeController is the controller for your home directory and each ActionResult is a function of that controller or page. In our case the url would be
Http://www.yoursite.com/home/newpage
Each action must have a view, which we’ll create next.
2. Create a view page
A view is simply an HTML page that displays data and interacts with the controller. You create views for pages or parts of pages, such as menus.
In the /Views/Home/ folder, create a new view by right-clicking on the /Views/Home folder and selecting “New View”:
How to Program ASP.Net MVC 4
You’ll see a dialog box that looks like this:
How to Program ASP.Net MVC 4
As you can see, this dialog box has a few options. For the view engine, you can choose Razor or ASPX(C#). Choose Razor for this, and leave the rest of the options open. You can create a strongly typed view that’s based of an object, but we’ll leave that for another tutorial. Hit add.
You’ll see the page now in your views folder.
How to Program ASP.Net MVC 4
Open up that page, and you’ll see the following code:

1
2
3
4
5
@{
    ViewBag.Title = "Newpage";
}

<h2>Newpage</h2>

Add some html for fun in there. Also, add the following line:

1
Hi! Today is @DateTime.Now.DayOfWeek

Save the file, and press F5 to run.

Your new MVC Page

To load the page you just created, type in
/home/newpage
after the URL. For instance my local URL is http://localhost:59312/home/newpage but yours may vary. You should see something like this:
How to Program ASP.Net MVC 4
This is your newly created view! Feel free to experiment with the views and the Razor view engine. The best way to learn is to break it!

Summary

In this tutorial we built a very basic MVC 4 page in ASP.Net. I hope it gets you excited enough to start really experimenting. The MVC package really does a lot of the work for you, you can actually create whole websites without a lot of code at all. But I do hope you will dig into the code, and get rid of some that atrocious HTML that’s generated and fiddle around.

Building C#/ASP.NET Apps on a Mac With vNext

In case you’ve been away from the internet for the last week, you’ve probably heard the big news from the ASP.Net team. They’re embracing open source in a major way. Scott Hanselman wrote a fantastic post about the news that nearly broke the internet (and certainly tested his hosting provider). Microsoft is really backing up their claims that they are committed to Open Source in a major way.
Up until now the only ASP/C# development I do on my Mac is under a Virtual Machine. I have a couple “bleeding edge” VMs I use for CTP versions of the framework and Visual Studio. But I never truly develop things on the platform and thought I’d give it a try.

You need Sublime Text

Ok, so this one goes without saying but you probably already have Sublime Text on your machine. It’s a fantastic editor that works well on all three platforms, and well worth $70. Having the same interface on Mac, Windows and Linux was what first attracted me to Sublime, and after using it a while I do nearly everything in it. I naturally decided to use it for this experiment. It’s not a true IDE like WebStorm (which also runs on all three) but it will work great for what we’re doing here.

1. Getting Started

First we need to get Mono and the K version manager set up. We can install this with Homebrew:

1
2
brew tap aspnet/k
brew install kvm

This will install K and pull down Mono if you don’t have it installed. You will want to add a line to your .bashrc file:

1
nano ~/.bashrc

and add

1
source kvm.sh

and save it the file.
Next you’ll want to install the K Runtime environment (KRE). To do that, you type in

1
kvm upgrade

You’re now ready to start running ASP.NET vNext on your machine.

2. Running a Sample App

Just to try it out, let’s run a sample application from the vNext GitHub.
create a project folder, and from the command line run

1
git clone https://github.com/aspnet/Home.git

Now let’s go to /Home/samples/HelloWeb. You’ll see a file in there called Startup.cs, let’s open that up in Sublime.
It looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
using Microsoft.AspNet.Builder;

namespace KWebStartup
{
  public class Startup
  {
      public void Configure(IApplicationBuilder app)
      {
          app.UseStaticFiles();
          app.UseWelcomePage();
      }
  }
}

As you can see, this is extremely simple file. It uses the IApplicationBuilder interface to build a simple app, and build a Welcome page.
Also we have a project.json file that’s pretty important. You use this to configure the application and load in dependencies:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
  "dependencies": {
      "Kestrel": "1.0.0-beta1",
      "Microsoft.AspNet.Diagnostics": "1.0.0-beta1",
      "Microsoft.AspNet.Hosting": "1.0.0-beta1",
      "Microsoft.AspNet.Server.WebListener": "1.0.0-beta1",
      "Microsoft.AspNet.StaticFiles": "1.0.0-beta1"
  },
  "commands": {
      "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5001",
      "kestrel": "Microsoft.AspNet.Hosting --server Kestrel --server.urls http://localhost:5004"
  },
  "frameworks": {
  "aspnet50": {},
      "aspnetcore50": {}
  }
}

Pretty straightforward stuff. To run our application we’re going to need to pull in these packages, to do that run

1
kpm restore

Once you do that you’ll see it start to pull down packages from NuGet for your application. Let’s run the application. Since this a web app we’ll use Kestrel to serve it,

1
k kestrel

You should see this:
image
This means you have a server running. Load up a web browser and point it to: http://localhost:5004/
image
ASP.NET vNext on your Mac Desktop! Pretty sweet, right? Actually you’ve been able to do this for about 6 months now, and it’s not first class yet, but they’re working on it every day.

3. Set up Sublime Text for C# Coding.

Now we’re going to get Sublime Text set up for C#/ASP.Net development. First we’ll install Kulture, a Sublime extention for ASP.Net vNext.
  • Bring up the Command Palette (Cmd + Shift + P)
  • Select Package Control: Install Package
  • Select Kulture when the list appears.
With Kulture we’ll be able to run K commands from within Sublime.
We’re also going to install OmniSharp for Sublime.
  • Bring up the Command Palette (Cmd + Shift + P)
  • Select Package Control: Install Package
  • Select OmniSharp when the list appears.
With OmniSharp you can build, run and refactor C# code with vNext, within sublime. Check the Readme for more details.
Let’s set our C# language-specific settings. (This is also outlined in the Readme)
Go to Sublime Text -> Preferences -> Settings - More -> Syntax Specific - User
image
And paste in the following:

1
2
3
4
5
 {
  "auto_complete": true,
  "auto_complete_selector": "source - comment",
  "auto_complete_triggers": [ {"selector": "source.cs", "characters": ".<"} ],
 }

Now, lets open up that startup.cs file we opened earlier (The sample web app)
Now open the command pallette (Cmd + Shift + P)
Type a “K” and you’ll see “run k commands” come up.
You now see a list of selections:
image
After a while, this will save you save you some time.
To get Intellisense working, you need to create a project file (again this is from the Readme)
To get intellisense with ASP.Net vNext projects you need to create a project file in Sublime. Go to Project - Save Project As and enter in a name for your project. OmniSharpSublime will use this to know what files and assemblies it needs to provide intellisense for (TIP : Close & Re-Open Sublime if you do not see intellisense, it may take 10 secs for the intellisense server OmniSharpServer to start once Sublime has loaded all the plugins)
Once OmniSharpSublime is installed and you have a project file you should be able to see intellisense.
Hint: There’s also a C# Snippets Extension worth looking at.

4. Let’s build a console app

Here I will show you how to do a console application, and we’ll do it a little differently. We’re going to use the fantastic Yeoman generator for this. If you’ve never used Yeoman you should try it out, it’s pretty awesome.
This assumes you have Node.JS and NPM installed. If you don’t, You can follow these quick steps here.
So first we’ll install the generator:

1
npm install -g generator-aspnet

If you don’t have Yeoman it will install it for you.
Then, we create a folder we want the project in, and type

1
yo aspnet

You’ll be greeted with a screen like this:
image
You can select between the types of application it can generate. Let’s select Console Application. I named mine “HelloWorld” because I lack creativity today.
After it generates, you’ll see it has created some files:
image
These files should look pretty familiar, but we now have a global JSON config as well as our project config.
Modify this file a little if you want, and bring up the command pallete, type k to run K commands and select K run:
image
Pretty cool huh? For some reason I’ve always been a huge fan of Console applications. I’m also a huge fan of C#. For years throughout my career I’ve built tons of awesome console apps, and the idea that soon I’ll be able to build first class C# console apps in Linux is pretty exciting to me.

Conclusion

This is pretty exciting stuff for so many reasons. I am a fanboy of all three operating environments (Windows, OSX, Linux) depending on what I’m doing. When I’m working with Python, PHP, or JS stuff I really like working in Linux. When I’m building graphic intense web pages / CSS or video editing I use OSX. When I build .Net stuff I use Windows. My Mac is the most powerful machine I own, so the idea that I can soon build anything I want in that environment is pretty awesome to me. As I said C# is one of my favorite languages to work in, and the ASP.Net architecture is awesome for building larger websites. The idea that it’s all coming together is awesome.
I’m just scratching the surface here, and this article focused on Web/Command Line stuff. But the Mobile development world is also being disrupted right now with work from the Xamarin Team, and vNext. The potential to develop great software has never been better, and it’s a great time to be a developer.
I think it’s great that Microsoft is “putting their money where their mouth is”. There has been a lot of talk the last couple years about the ASP.NET team embracing open source, and they’re taking a very serious approach to it. This is not a half hearted attempt at lip service, they’re opening all of it, and they’re working with everyone. In the end we as developers will be reaping the benefits from this latest push.
I’ll create some more vNext stuff in the future and write about some of the “gotchas” I’ve already run into building stuff. The vNext stuff is not “first class” yet, but it will be soon. Stay tuned, and be sure to comment if you’re working on any of this cutting edge stuff.