How do I setup an AngularJS application in Visual Studio 2013

Q: How do I setup an AngularJS application in Visual Studio 2013?

Not trying to avoid the answer, however, I think the answer to this question depends on the type of application that you need for the solution. Your decision is based on how much of ASP.NET do you want or need. And if you are going to integrate AngularJS with ASP.NET features or not. There are some purists out there that wouldn’t think of integrating AngularJS with an ASP.NET MVC application. They want pure HTML and JavaScript (no Microsoft). That is ok too! I would love to work on that kind of project.

I like to take the approach that AngularJS is a tool and if it is used correctly for the specific job or solution then it could be integrated along with an ASP.NET MVC application – OR NOT. If so, I think you need to determine what the boundaries are for its use and when it is appropriate – there should be a good division of responsibility for MVC and AngularJS. When, Where, and How are you going to use it.

Angular’s MVC approach on the client-side of things using models, views, and controllers all self-contained in neat .js files is a great improvement in the structure and management of JavaScript code. The structure and conventions used in Angular make it a great choice for teams – the conventions are the same. And they will be the same for the next project and the project after that. So Angular is still a good choice whether or not you are combining it with ASP.NET MVC technologies.

Q: Which project template should I use?

Again, it depends based on what you need. You can use the ones that come installed with your version of Visual Studio or you can use some that are created by other concerned developers like yourself.

AngularJS-SPA-Template @ https://github.com/kriasoft/AngularJS-SPA-Template

Here are some project template options provided by Visual Studio 2013

  • Singe Page Application: Setup for a single page application that is ASP.NET MVC specific. There are controller, model, and view folders setup for your application with all of the other MVC goodness.
  • Empty Web Application: Only contains a web.config file. I guess you can delete it if you don’t need it. This is as basic as you get.
  • Web API: This template provides you with basic ASP.NET MVC, but it includes a sample “Value” Web API controller that uses the new ApiController base class. This project template will allow you to implement Web APIs along with Angular – you have the option of adding as much MVC that you want or not.

Q: When would I use Angular with no ASP.NET MVC (i.e., Angular straight up)?

Recipe: AngularJS ONLY :: Single Page Application (No ASP.NET MVC).

You would make this choice when ASP.NET MVC features are not required or needed. Also, it might be a requirement – you would only be using the Visual Studio 2013 as an IDE or development environment for your application. Visual Studio is a good option to use as an IDE for an AngularJS application. There are some intellisense templates out there that make it a rich experience. You can also use Resharper Extensions for Angular.

This is a great choice when you do not require any HTTP calls for data or data persistence (same application). Or you are using a different HTTP source that is well-known or exposed API to provide data for the application.

Suggested Project Template: Empty Web Application

image

Q: Should I mix Angular with ASP.NET MVC Views (i.e., mixed or blended mode)?

Recipe: ASP.NET MVC Application + Web API + AngularJS SPA

This might be a good choice if you want to use the ASP.NET MVC views to serve up the pages of your web site and/or application. It provides some SEO benefits – or so I’ve heard. Basically, you are using ASP.NET to load up the page initially and supply it with whatever it requires for the initial display.

Most likely, you will use Angular for subsequent displays and requests for models. In this recipe, there is a good separation of concerns. ASP.NET is responsible for the initial loading of pages and subsequent calls for information are done by Angular. You might even have just partial sections or partial templates within the ASP.NET MVC page that use specific Angular controllers, models, and views. This would be considered another example of a mixed-mode.

Suggested Project Template: Single Page Application

image

Q: When would I use ASP.NET MVC, Web API and AngularJS (i.e., mixed mode with a splash of Web API)?

I could see this recipe with or without the ASP.NET MVC. The interesting part here is the Web API mixed in. The Angular controllers may need to make some HTTP calls to retrieve or persist information. Web APIs make this possible. The routing and model binding provided by Web API make the implementation a lot easier.

This would be a great choice when your Angular controllers need a place to call for data.

Suggested Project Template: Web API Application

image

Q: What packages do I need to implement an AngularJS application?

If you are using Visual Studio, it is probably a good idea to use the Package Manager to retrieve the packages you require.

  • AngularJS (required)
  • jQuery (required)
  • Bootstrap (optional)

ASP.NET Web API

I’m starting a new project that will be using ASP.NET Web API. I have used WCF in the past to create RESTful services – so I’m very interested in how I can achieve the same using Web API. It relies on the HTTP methods:

  • Get (retrieves a list of items)
  • Get (retrieves an item by id)
  • Post (creates a new item)
  • Put (updates an item)
  • Delete (removes an item)

So, if I am working with a Customer entity, I would have the following web api:

  • // GET api/Customers –> public List<Customer> Get(){..}
  • // GET api/Customers/123 –> public Customer Get(in id){..}
  • // POST api/Customers –> public void Post(Customer c){..}
  • // PUT api/Customers/123 –> public void Put(int id, Customer c){..}
  • // DELETE api/Customers/123 public void Delete(int id){..}

API Method Names

Notice that the method names correspond to the HTTP Method type. This is by convention. However, you have another option by convention as well, you can prefix the methods with the HTTP Method type name. You can use the same URI and ASP.NET Web API will know which method to call in the CustomersController.

  • // GET api/Customers –> public List<Customer> GetAllCustomers(){..}
  • // GET api/Customers/123 –> public Customer GetCustomer(in id){..}
  • // POST api/Customers –> public void PostCustomer(Customer c){..}
  • // PUT api/Customers/123 –> public void PutCustomer(int id, Customer c){..}
  • // DELETE api/Customers/123 public void DeleteCustomer(int id){..}

You can also modify the default convention by using Web API attributes. Using our GET as an example, we can use the default Get() method, or we can

  1. Use the default: Get()
  2. Prefix the method name with the HTTP Method: GetCustomers()
  3. Use the [HttpGet] attribute and name the method whatever we want.
  4. Use the [AcceptVerbs(“GET”)] attribute and also name the method whatever we want.

// GET api/values
//1. public List<Customer> Get()
//2. public List<Customer> GetCustomers
//3. [HttpGet]
//public List<Customer> GetAllllllCustomerss()
// 4. Use [AcceptVerbs(..)]
[AcceptVerbs(“GET”)]
public List<Customer> GetAllllllCustomersWithAcceptVerbs(){..}

As we can see, the mapping the actual URI to the Controller’s method is flexible. Each of the implementations noted above will return the same result. There is also another option to configure the mapping of the URIs to the Controller methods – this is an RPC style, where you actually include the name of the method in the URI – this requires you to modify the HttpRoutes to include the name of the Action in the URI. It is an option – however, I’m going to stick with the more conventional approach.

API Routing

Really, both approaches use Routing. You can modify the route map and register the new route by modifying the WebApiConfig class. If you wanted to use the RPC style (with the Action name), you would just update the RouteTemplate with “api/{Controller}/{Action}/{id}”.

imageC

There may be other parameters to put into the route template. For example, in a multi-tenant application, you might include an additional parameter and provide a constraint for the value.

image

Http-Compliant ASP.NET Web API

There are specific things that you will want to do to keep you API Http-Compliant. This is a good thing. We want users of the API to understand the API and have certain expectations when they are working with it. We’ll talk about the message body, Request and Response, and Http status codes.

When we are working with Http Methods what we return in the response and what status codes we use matters. For example, using our simple Get() method – the following implementation is fairly naïve. We are not returning any status codes in the response. The id value supplied may not even be a valid Customer identifier. So we have to be concerned with the how we handle the response and what status codes we use.

image

An improvement would be to provide a response and a status code if the specified item was not found. Otherwise, the status code would 200 OK.

image

When the request for a Get is valid, I get the XML in the response and the status code is 200 – OK.

image

When I inspect the HTTP request and response in Fiddler, I see the expected status code.

image

Let’s see if I get the 422 status code when the customer is not found during the request. I not only get the correct status code when I do not find the customer, but the Reason Phrase value is also provided in the response. This information will help users of you API to understand the responses when they do not get the expected results. In a more comprehensive solution, we would want to provide other status codes to indicate other causes of not providing the expected response: 200 OK.

image

Create a new Resource using the Web API

Just as there is special handling in processing a GET request, there is a protocol to use when creating a new resource using HTTP POST. The information used to create a new resource is contained in the body of the Http Request. The data or information can be either XML or JSON format – it just needs to represent the target we are trying to create. The response is also different – we not only need to return a status code, but we need to include some details about the new item that was created. This includes a URI to retrieve the item that was just created.

To improve the ASP.NET Web API default Post method – we update the return type to HttpResponseMessage. This will allow to provide a nice response with a status code, the resource just created, and a URI that will allow the user of the API to retrieve the item just created.

image

To make the request, we need to create the information used in the body of the request:

{“Name”:”Maria”}

I’ll use Fiddler to compose a request.I updated the body with the JSON that represents a new Customer, I changed the Http Method to POST and updated the URL.

image

When I execute the request using Fiddler, I expect to receive the information described above. I get the 201 Status – Created and the JSON data in the content represents my new Customer.

image

Conclusion

We covered a little bit of ground in setting up a GET and a POST. I’ll continue later with a blog entry about PUT and DELETE. But so far, we see how we can use Fiddler to generate a request and/or replay a request. We can retrieve data from our application using HTTP method calls – which has so many uses.

ASP.NET Identity Security

The new ASP.NET Identity framework provides membership features for your application – well kind of. Compared to the previous membership providers there appears to be not much there. However, do not be fooled. Although, many of the typical membership method calls just don’t’ exist, this new membership implementation is very extensible – which allows you the developer to customize the implementation to your specific needs. You can use SQL Server as your data store, but there are a lot more options now, especially the integration with other social platforms. This ain’t your dad’s membership provider.

Typically, you would create an ASP.NET MVC web application and implement the new ASP.NET Identity within the web application – this means making calls directly from the controllers to the database using the new Entity Framework IdentityDbContext<IdentityUser>. I think for most demos and simple applications this may work fine. However, I like a little more abstraction between the UI, business, and data access “parts” of my application. Therefore, since this new version doesn’t have any dependencies on any web assemblies – I can implement and customize my security in a separate class library.

I start by creating a new C# Class Library project and add the required packages from NuGet to support my custom implementation of AspNet.Identity.

https://www.nuget.org/packages/Microsoft.AspNet.Identity.EntityFramework/1.0.0

image

The NuGet installer also installs other required packages for Identity.

image

IdentityUser :: The ApplicationUser

I start by creating a new entity called ApplicationUser. This entity implements the IdentityUser interface from the Microsoft.AspNet.Identity.EntityFramework namespace. You will need to reference the namespace with a using statement.

image

The IdentityUser interface is shown below with its implementation of the IUser interface – these interfaces provide the default structure for the new user in the Identity framework.

image

image

It is interesting to note that the Id property is a string type. The value stored in the database from the Identity framework looks like a GUID – it is the string representation of a GUID value. It appears that you would have to re-implement the IUser interface and the IUserStore of the Identity framework to make a change to an Id property using an int. I’m not sure if I’m ready to tackle this task yet. I’m trying to leverage as much as possible from the default implementation. See StackOverflow.

UserManager

The AccountController creates an instance of the UserManager<TUser> through its constructor. This class provides all of the methods to manage a specific user via the ApplicationUser class. When the UserManager is created it requires a new UserStore<TUser> where TUser is of type IdentityUser. The UserStore object requires an instance of the IdentityDbContext<TUser>. I would consider the UserStore as the “repository” that uses Entity Framework for database transactions since it depends on the IdentityDbContext. The UserManager is the business end of the managing users. You can imagine that this is where additional data validation and business rules are implemented before making a call to the database using the UserStore<ApplicationUser>, right?

This is why the ApplicationUser entity is so important. It is used to create generic implementations of the UserManager, UserStore, and IdentityDbContext. In the code below, I’m beginning to refactor the Register() method to use the entity defined in my custom project, I will then implement the CreateUser() call using my new SecurityService (code currently commented out).

image

Enterprise Patterns :: Vergosity Framework

I have quite a bit of infrastructure setup already complete using the Vergosity Framework that includes: Business Actions for implementing business logic and the rule engine to take of processing my data validation and business rules. I’m also experimenting with a new set of pattern that take advantage of dependency injection. Therefore, I’m relying a lot on the Autofac DI container to do this for me. The framework also includes Logging of an application error or failed business rule evaluations.

This implementation confirms to me that I can abstract the ASP.NET Identity references from my ASP.NET MVC web application and put the implementation into a new project – this will allow me to reuse the new implementation in other applications.