Angular JS with ASP.NET MVC – Part 2

In the first part we just configured angular JS application in ASP.NET MVC. You may have noticed that we accessed the scope variables of DemoController using $ sign. This time we will use the $route variable to route and open different views in a single page container where ng-view will be defined.

$ is a prefix that could be a property, method, variable that part of the core of AngularJS. When naming services controllers etc. it is recommended to not use $ prefix with your custom object names to avoid conflicting issues.

In this exercise we will add routing module in the MyApp.js, configure routing statements and open the ASP.NET MVC views inside a div on a single page container.

  1. First of all add the Angular Route package from NuGet Manager.
  2. Add a reference using NuGet Package Manager and search angular js route. You will see the AngularJS Route package in the Manage NuGet Packages windows. Just add it.1
  3. Now in the MyApp add ngRoute module
  4. Add the Angular-route.min.js in the BundleConfig.cs file under App_Start folder
  5. 4
  6. Edit the MyApp.js file and add ngRoute as belo
  7. This tells the angular app to use the routing module.
  8. Let’s add three actions in HomeController namely Test1, Test2 and Test3
  9. Add views to these actions, Note: all view should be partial
  10. In order to add view, just right click the Test1 function and select Add View
  11. It opens up the window where you can specify the name Test1 and check on “Create as partial view”2
  12. Once added, do these steps for ou can specify the name Test1 and check on foldera div on a single page container. d confilcting rest two methods as well namely Test2 and Test3.
  13. Now, inorder to open these view from angular we have to add a routing.
  14. In the MainApp.js we can add a routing as below3
  15. After adding this, we need to add a div on our landing page. In last post, Home/Index was our landing page (that acts as a single page container)
  16. Now add a div with ng-view attribute on it. Angular automatically opens up the page on all the containers like div, body etc where the ng-view is defined on the landing page container.5
  17. Now add, these links that opens up the page inside div6
  18. You can put any content in the partial view
  19. Let’s build and run. Click on link1 and it opens up the page inside div where ng-view is defined.7
  20. Click on second link
  21. 8
  22. At last, Click on third link 9

This covers up our second part where we used the routing feature of Angular JS. In the next post we will create factories to access database using Web API and Entity Framework as data access persistence.

AngularJS in ASP.NET MVC – Part 1

This is the first part from the series of posts I have planned for AngularJS in which I will provide an in-depth knowledge about AngularJS and how to use that in developing business applications with ASP.NET MVC, WEB API and Entity framework

In this post we will discuss about the core features of AngularJS and bootstrap with ASP .NET MVC using Visual Studio. I assume that the readers should have an in depth knowledge of ASP.NET MVC and Web APIs as I would mostly focus on the AngularJS features.

What is AngularJS

AngularJS is a web framework developed by Google tp provide responsive UI on web. It is supported for Single Page Applications where the landing page remains the same and single or multiple view can render inside it with usage of server side functions asynchronously and updating the model and control values dynamically.

You can check out the complete tutorial over here https://angularjs.org

Step by Step exercise of configuring Angular JS in ASP.NET MVC application

  1. Start Visual Studio
  2. Select ASP.NET Web Application and then MVC as project template
  3. Add references to AngularJS through NuGet
  4. Search AngularJS on the Package Manager console
  5. And then Select AngularJS Core and install

11

6. After adding AngularJS Core, add the bundle

bundles.Add(new ScriptBundle(“~/bundles/angular”)

.Include(“~/Scripts/angular.js”));

7.  Now add these bundles in the HTML head section of _Layout.cshtml

@Scripts.Render(“~/bundles/angular”)

8. Now In order to bootstrap angular JS in our MVC app we have to define the ngApp on the page body or html tag. ngApp reference to the application JS file where you can define routing, controllers etc. ngApp is a directive to auto-bootstrap an AngularJS application. Also, note that only one ngApp can be used per HTML document.

9. Let’s create two JavaScript files, one MyApp.js and the other DemoController.js

10.  Create an app folder under root in MVC project

11. Add a new JavaScript file named as MyApp.js

12. Inside MyApp.js write following snippet

var MyApp = angular.module(‘MyApp’,[]);

13. This line initialize the application level global object of angular app and a central point where you can add modules like routing, ui etc. Through this object you can add controllers, directives etc and access it globally.

14. Now specify “MyApp” to the ng-App attribute in html tag.

<html ng-app=”MyApp”>

15. Now, let’s add a DemoController.js file in your project under app folder.

16. Add following snippet in DemoController.js

MyApp.controller(‘DemoController’, [‘$scope’,

function DemoController($scope) {

$scope.Name = “ovais mehboob”;

}]);

17. Now add a div tag inside Home/Index.cshtml file and specify ng-controller as DemoController

<div ng-controller=”DemoController”>

<h1>{{Name}}</h1>

<input type=”text” ng-model=”Name” />

</div>

18. In the above code, I have specified DemoController in div tag and access scope varialbes that were defined under DemoController. Using “double curly braces” {{ }} you can access the scope variables throughout controller.

19. In order to bind the values of scope variables with input fields like textbox etc you can use ng-model and ng-bind to bind with other controls like span etc.

20. Add MyApp.js and DemoController.js inside BundleConfig.cs

bundles.Add(new ScriptBundle(“~/bundles/angular”)

.Include(“~/Scripts/jquery-1.10.2.js”,

“~/Scripts/angular.js”,

“~/app/MyApp.js”,

“~/app/DemoController.js”));

21. Let’s build and run the application

44

In the next post I will discuss about routing and rendering views inside a single page application.

Understanding OWIN by developing a custom OWIN middleware component

OWIN stands for Open Web Interface for .NET that decouples the Web Application from Web Server through an interface. In this article I will try to show some basic example of creating custom OWIN middle ware component and using it in self-host console application. The idea is to clarify the working of OWIN and what we can achieve with this new paradigm.

OWIN classifies web application into 4 parts

  1. Host
  2. Server
  3. Middleware
  4. Application
    ASP.Net MVC web application Fully OWIN compatible web applications
    Host IIS Any application Console App, Windows Service, IIS etc.
    Server IIS An application that hooks up the HTTP Listener to listen for a request.
    Middleware IHTTP Modules OWIN Middleware
    Application ASP.NET MVC 5 in IIS ASP.NET vNext, Web API 2 etc.

How is the request processed by OWIN Host?

When the request comes in to the OWIN server, the request properties like query string, path, content type, and so many others added into the IDictionary<string, object> object. This dictionary object is then sent to the request pipeline and then middleware components in the request pipeline can use this dictionary object and process accordingly.

OWIN expose following interface

System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>;

Func is a new way of defining delegates in .NET framework. The first parameter denotes the input parameter and second as a return parameter. Here we have IDictionary<string,object> as input and Task as the resultant output.

When the request comes to the server, OWIN host calls the Invoke method of all the middleware components defined in order and pass the dictionary object. Each middleware component gets the complete request properties as dictionary object.

Startup.cs class is an entry point to build the request pipeline. In the Startup class, Configuration method is mandatory that takes IAppBuilder as a parameter. Using IAppBuilder you can add the OWIN based middleware and define the request pipeline. Developers can develop their own pipeline for incoming request. In IIS there are many components configured through which the request is passed through and for simple or mid-sized applications that seems to be an overkill. With OWIN based host it is quite easy to use only those OWIN extensions or middleware components that are required for your web application.

In order to elaborate, let’s create a simple OWIN middleware that logs the incoming request message into the console application and host the OWIN server in console application itself.

  1. Open Visual studio 2013 and create a new Console Application project
  2. Add OWIN NuGet references using NPM
  3. We need to add three NPM packages i.e.
    1. Microsoft.Owin – contains helper types and abstractions for simplifying the creation of OWIN components
    2. Microsoft.Owin.Host.HttpListener – OWIN server used for self-hosting
    3. Microsoft.Owin.Hosting- provides infrastructure types for hosting
  4. These libraries are part of Katana project, an implementation of OWIN by Microsoft
  5. In order to use OWIN on IIS, you can use Microsoft.Owin.Host.SystemWeb. Normally in IIS the request pipeline consists of HttpModules that are subscribes to events like BeginRequest, AuthenticateRequest etc. When you add this assembly in ASP.Net web applications you can define the OWIN based middle ware components in your Startup.cs and at runtime the Katana runtime mapped each of the middleware component to PreExecuteRequestHandler that corresponds to the PreRequestHandlerExecute event. Thus, the middleware components are invoked by the IIS integrated HTTP pipeline. This is not supported with classic HTTP pipeline.
  6. Once these references are added, we have to create a Startup.cs class and add Configuration method as below

    public void Configuration(IAppBuilder app){ }

7. Now let’s create a custom logging component to log incoming HTTP Request

      public class LoggingMiddleware

         {

              private AppFunc appFunc;

              public LoggingMiddleware(System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task> func)

           {

                 this.appFunc = func;

            }

            public async Task Invoke(IDictionary<string,object> env)

{

                  Console.WriteLine(“Request method is “+ env[“owin.RequestMethod”]);

                  var task = appFunc.Invoke(env);

}

}

8. Add this logging middleware in the configuration method using IAppBuilder use method

public void Configuration(IAppBuilder app)

{

app.Use<LoggingMiddleware>();

}


9. In the Main method of console app start the server using following WebApp.Start

Microsoft.Owin.Hosting.WebApp.Start<Startup>(http://localhost:12345&#8243;);

Console.ReadLine();


Following is a complete code

     

public class Startup

{

public void Configuration(IAppBuilder app)

{

app.Use<LoggingMiddleware>();

}

}

public class LoggingMiddleware

{

private AppFunc appFunc;

public LoggingMiddleware(System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task> func)

{

this.appFunc = func;

}

public async Task Invoke(IDictionary<string,object> env)

{

Console.WriteLine(“Request method is “+ env[“owin.RequestMethod”]);

var task = appFunc.Invoke(env);

}

}

class Program

{

static void Main()

{

Microsoft.Owin.Hosting.WebApp.Start<Startup>(http://localhost:12345&#8243;);

Console.ReadLine();

}

}

}

10. Now run the application and access the URL http://localhost:5555

11. You will see the logging on your console app.

Reviewed book “Bootstrap for ASP.NET MVC” by Pieter van der Westhuizen

I have gotten this opportunity to review the book named “Bootstrap for ASP.NET MVC” from Packt (UK based publishing company specializing in focused IT books).

Following is a review I made for this book

This book is a perfect guide to learn about using Bootstrap in ASP.NET MVC applications. Pieter does not only provided the basic information about incorporating Bootstrap in ASP.NET MVC but for almost each topic there are steps provided with code snippets that helps the reader to perform hands-on on the fly.

 

Developing and Self-Hosting Simple ASP.Net vNext Application using Command Line Tools

In this post I will walk you through the latest version of ASP.Net i.e. ASP.Net vNext and talk about some core characteristics as well as some command line tooling options that allows developers to build, run and manage ASP.NET Applications.

ASP.Net vNEXT

ASP.Net vNext is the next version of ASP.Net that comes with some major changes when compared to ASP.NET. It’s open source and comes under .Net Foundation. Now the developers can contribute and get a clone from https://github.com/aspnet

Core characteristics of ASP.Net vNEXT

  • Single programming model for websites (MVC, Web Pages) and services (Web APIs). No more APIController base class for Web API and unified Controller class that serves both MVC Controller and Web API Controller.
  • Introduced Project.json file where developers can define assemblies followed with versions, commands and versions of ASP.Net. Assemblies resolved by the Visual Studio CTP 14 immediately once you save the file and downloaded via NuGet. On the other hand if working in non Visual Studio environment you can use command line KPM restore command to download dependencies.
  • There is no dependency of System.Web.dll.
  • ASP.Net vNEXT is a Cloud optimized framework which is more robust and less in size. The full version of .Net is around 200 MB whereas the cloud optimized one is only 11 MB in size.
  • Dynamic compilation is a big feature provided in Roslyn (.Net Compiler Platform). Now developers can change code and refresh the browser without building the whole project.
  • Side by side support to deploy own version of .NET framework with each application. Each application have its own .net framework version running side by side on single machine.

In ASP.Net vNext, you have an option to run, compile and manage application versions etc. using different command line tooling options. First of all, in order to setup environment for executing KVM, KPM and K commands you have to execute the below powershell script.

@powershell -NoProfile -ExecutionPolicy unrestricted -Command “iex ((new-object net.webclient).DownloadString(‘https://raw.githubusercontent.com/aspnet/Home/master/kvminstall.ps1&#8242;))”

Following are the command line tools ASP.NET vNext provides

  • KRE (K Runtime)
  • KVM (K Version Manager)
  • KPM (K Package Manager)
  • K (To run commands)

What is KRE (K Runtime)?

K Runtime contains the SDK tools, compilation system and CLR hosts. It’s an actual ASP.Net vNext runtime that visual studio itself uses to provide intellisense, compilation errors etc.

What is KVM (K Version Manager)?

KVM stands for K Version Manager. This is used to get the K Runtime (KRE) to host ASP.Net vNext applications. This also allows managing the default version on app to app basis. KVM is essential when you want to self-host ASP.Net vNext application and running the self-host web listener using command line tool.

You can install KVM by running this command via command prompt

KVM install 1.0.0-alpha4

On installing KVM, all the kvm files are copied into the current users directory i.e. %windir%:\Users\%username%\.kre folder. It also places the environment variables on windows PATH so you can execute commands without directing to the KVM folder path.

Some widely used KVM commands

  • kvm upgrade

Checks the latest KRE version if available and install it on the machine

By default, we are running full .Net Framework but you can switch to the cloud optimized one using kvm upgrade –runtime CoreCLR

  • kvm list

To list the installed version of KRE the * denotes the active version and you can choose another version on app to app basis using kvm use version command

What is KPM (K Package Manager)?

KPM is the K Package Manager tool that you can use after installing KVM. Through this tool you can restore packages defined in the project.json file.

  • kpm restore

To restore the packages defined in the project.json file of your ASP.Net vNext application.

What is K?

K is the command line tool to run ASP.Net vNext application. You can use K run to run the HTTP listener to listen for the incoming request specified in the project.json file.

  • k web

Let’s do some Action!

In this exercise we will develop a simple ASP.Net vNext application without using Visual Studio 14.

  • Create a folder named “SampleKProject” in any of your machine drive.
  • Now create the project.json file inside that folder and copy below content.

    {

    “webroot” : “wwwroot”,

    “exclude”: “wwwroot/**/*.*”,

    “dependencies”: {

    “Microsoft.AspNet.Diagnostics”: “0.1-alpha-build-0682″,

    “Microsoft.AspNet.Hosting”: “0.1-alpha-build-0572″,

    “Microsoft.AspNet.Server.WebListener”: “0.1-alpha-build-0520″

    },

    “commands”: {

    “web”: “Microsoft.AspNet.Hosting –server Microsoft.AspNet.Server.WebListener –server.urls http://localhost:8090&#8243;

    },

    “frameworks”: {

    “aspnet50″: {},

    “aspnetcore50″: {}

    }

    }

    If you see the project.json, there are several sections namely webroot, dependencies, exclude, commands, frameworks etc.

webroot To specify the web server root folder where all the static files should be placed. In above code snippet we have specified wwwroot which means all the static files will be placed under wwwroot folder.
dependencies List all the dependent assemblies name followed with version information. All the dependencies will be loaded using kpm restore and downloaded via NuGet.
exclude You can provide folder path to exclude files from compilation
commands When running K command you can pass the name of a command to execute it. For example K web where web is the command name
frameworks To define the target frameworks that will be build or the dependencies that are specific to configuration.
  • Now create the Startup.cs file that is the starting point for ASP.Net vNext application. In this class you can configure the components for the application pipeline. The Startup class must contain a method named “Configure” that takes IAppBuilder as a parameter. Following is a full code snippet of the Startup class.

    using System;

    using Microsoft.AspNet.Builder;

    namespace WebApplication5

    {

    public class Startup

    {

    public void Configure(IBuilder app)

    {

    app.UseWelcomePage();

    }

    }

    }

    app.useWelcomePage adds a middleware component that shows the welcome page on navigating the URI

  • After creating project.json and Startup.cs files, open up a command prompt and go to the root folder that we created earlier i.e. SampleKProject and run kpm restore. When running the kpm restore it searches the project.json file and resolves the dependencies by downloading them via NuGet.

  • Once this is done you can run k web to start the self-host web listener.

Hint: web server can be stopped by using Ctrl+C and typing ‘Y’

Follow

Get every new post delivered to your Inbox.

Join 82 other followers

%d bloggers like this: