Building Single Page App using ASP.NET Core and Angular

Amazon Link:- http://bit.ly/spa-asp-core

You can also find Chander’s View about the book here http://bit.ly/chander-spa.

Hi Friends,

Thought to share my latest project in collaboration with Chander Dhall.  Chander and I started discussing on this project couple of months back and thought to collaborate in the project which is going to give more meaningful and professional product as an end result. Before talking anything about this book, I would like to put one disclaimer ahead of time. “This book doesn’t mean for freshers or for those computer professionals” . This I am saying because this book uses tons of client/server and many more sophisticated concepts which may appear overwhelming to freshers or to those just started programming. This book is all about how to marry all these technologies together and come out with a final industry standard product. Hence this book is meant for professionals who are good with basics at least. Having said that, now let me give glimpse of the book with complete first chapter.

Contents

About The Author

Who This Book is for

Foreword

Preface

How this book is structured?

Project Download

Chapter 1: – Getting Started

WHAT do you find in this Chapter?

Introduction

What is SPA

Technologies used to build SPAs

Glimpses of the Movie Review App

Glimpses of the Movie Review Solution

Summary

Chapter 2: Creating Solution from the Blank Slate

WHAT do you find in this CHAPTER?

Introduction

Solution Creation

Project Structure

Application Startup

DotNet Watch Tool

Adding Class Libraries

Adding Project References

Adding Entity Framework

Important Tools

Data Technologies

Creating Models

Creating Entity Framework

Creating Entity Framework DbContext Class

Using the DbContext Class

Installing DotNet CLI for EF

Creating a Database

Seeding the Database

Implementing the Repository Pattern

Applying Database Constraints

Creating the Unit of Work Pattern

Questions

Summary

Chapter 3: Creating Data Context

WHAT do you find in this CHAPTER?

Introduction

Creating Models

Creating the Entity Framework

Creating Entity Framework DbContext Class

Using the DbContext Class

Installing DotNet CLI for EF

Creating the Database

Seeding the Database

Implementing the Repository Pattern

Applying Database Constraints

Creating the Unit of Work Pattern

Questions

Summary

Chapter 4: Implementing Web API

WHAT do you find in this CHAPTER?

Introduction

Creating the First Web API Controller

Implementing HTTP Put Request

Implementing HTTP Post Request

Implementing HTTP Delete Request

Improvising Web APIs

Adding More Controllers

Questions

Summary

Chapter 5: Getting Started with Angular

WHAT do you find in this CHAPTER?

Introduction

Creating a New Angular Component

Creating a New Route

Adding the Bootstrap Form

Creating Angular Service

Creating a New Movie

Questions

Summary

Chapter 6: Deeper into Angular

WHAT do you find in this CHAPTER?

Introduction

Client-Side Validation

Displaying Toast Notifications

Logging Errors

Editing a Movie

Fixing Multiple Selections

Removing a Movie

Questions

Summary

Chapter 7: Adding More Features using Angular

WHAT do you find in this CHAPTER?

Introduction

Listing Reviews

Fixing URL Refresh Issues

Creating Reviews

Editing Reviews

Deleting Reviews

Questions

Summary

Chapter 8: Adding More Features to the App

WHAT do you find in this CHAPTER?

Introduction

Adding Movie Filters

Adding Review Filters

Adding Paging Control

Creating a Detail View

Creating a Tabbed View

Adding the Image Model

Creating a New Migration

Adding Images Controller

Testing Upload Functionality

Building Client Side

Creating Image Service

Rendering an Image While Uploading

Questions

Summary

Chapter 9: Authentication & Authorization

WHAT DO you find in this CHAPTER?

Introduction

Understanding the Authentication LifeCycle

Setting Auth0

Testing Movies API

Securing Client Apps

Implementing Login/Logout

Using Custom Login Pages

Audience Setting

Getting User Profiles

Adding More Fields in the Sign Up Form

Adding Rules

Adding Roles

Showing/Hiding Contents Based on Roles

Route Guards

Calling Secured Server-Side APIs

Restricting API Access

Questions

Summary

Chapter 10: Introduction to Azure and CosmosDb

WHAT DO you find in this CHAPTER?

Introduction

Architecture

Setting Up Cosmos Db in Azure

Figure Explained

Cosmos Db Emulator

CRUD using Web API and Cosmos Db

Product Code

IDocdb Repository Code

Adding Logic

Postman Call

Summary


About the Author

thumbnail_chander dhall

 

 

 

 

 

 

 

Chander Dhall is an awarded Microsoft MVP and world-renowned technology leader in architecting and implementing solutions. He’s not only rescued software development teams, but also implemented successful projects under tight deadlines and difficult business constraints. His company has a proven track record of not just saving the client millions of dollars, but also providing an expedited delivery time. Chander’s team of experts are internationally-acclaimed speakers in top technical conferences in the world.

As a Microsoft Azure Advisor, ASP.NET Insider, Web API Advisor, DocumentDB Advisor, and an MVP for Visual Studio and Development Technologies, Chander has insight into new releases on technologies used by millions of developers. His critical advice, impeccable vision, futuristic strategy backed with creating and establishing best practices in the industry are some of the reasons for his unparalleled success.

At the same time, he’s a voracious and highly-respected speaker. Chander is known to elucidate critical and complex concepts while making them easy to understand. He’s one man who can talk to anyone from a junior developer, a senior architect all the way to an executive and knows how to speak their language. He has utilized his amazing business sense having started a company with zero funding and turned it into a multi-million-dollar company in less than two years.

me1

 

Rahul Sahay is a Microsoft MVP specializing in Web technologies. Rahul is technical fellow at Kongsberg Digital. He has been working in various aspects of the software development life cycle for 9+ years, focusing on web stack development. He has been part of software development in different applications, ranging from client applications to web services to websites. As a code junkie, Rahul loves to craft software, not only he enjoys writing software, he loves sharing his knowledge via his blog https://myview.rahulnivi.net. He also speaks at conferences, web camps, and code camps. For any queries, questions, one can directly reach Rahul @rahulsahay19.  You can also refer his works at https://github.com/rahulsahay19.

Who This Book is for

Let me put this part first. Building Single Page App using ASP.NET Core and Angular is not at all meant for freshers or for those who just started programming. This Book covers tons of client-server side technologies. For example it uses ASP.NET Core, Entity Framework Core, Web API, Repository Pattern, Unit of Work Pattern, Angular, Responsive design principles, HTML 5, Solid Principles, Design Patterns, etc. to name a few. Now to illustrate each and every concepts right from the scratch is fairly impossible as it kills the purpose of writing this book. This book is for my readers who regularly ask me to write something combining all these principles. There are tons of developers and professionals around the world who know these concepts in bits and pieces but don’t know how to connect the dots to build as an application. This book is entirely written around industry standard coding standard and design principles. Hence, if you are fresher or just started your job, I would recommend to understand basics first and then refer this book. Otherwise this will appear overwhelming at the beginning. From second chapter, you will find questions section at the end of every chapter. If you are following this book precisely, you should be able to answer these questions on your own. These are project specific questions which are generally asked in any technical interviews.

Foreword

Both .NET and the Angular platform continue to play a critical role for enterprises across the world. The web and its surrounding ecosystem continue to evolve at an accelerating pace. Every day developers are asked to build applications that are more focused on successful outcomes for users. At the same time developers have to contend with an explosion of new technologies and techniques for building these rich and engaging experiences.

This book is a fantastic guide for intermediate and advanced developers who want to expand their skills and who want to be a part of the future of the web. There are a lot of challenges and hurdles to building full-stack applications that are engaging, reliable, maintainable, and extensible. This comprehensive guide covers everything a developer needs to know to apply their existing skills to building end-to-end real world applications.

By covering the entirety of the process, from first setting up a new project in the right way to developer operations concerns such as capturing and logging client-side errors that real users encounter in production, this book ensures that developers will be prepared with all of the best practices they need to be effective, and it ensures that developers will be prepared to deal with the complexity and ambiguity that are inherent in software development. Many of the the skills and techniques covered here are timeless, and will serve developers well as they stay productive in the constantly changing world of technology.

Stephen Fluin

Angular Team @ Google

ASP.NET core is in many ways the resurgence of .NET. The platform has always been relevant, but it has a new cross-platform life now. Angular on the other hand is one of the most popular Javascript or should I say, Typescript frameworks. There are plenty of basic, getting started books on the topic. But the practical knowledge of putting these two together needs many years of experience that Chander and Rahul bring to the table. In this book, you get to see the next step, beyond the basics, learning to do, the why’s behind the what’s.  As active members of the community, they also have a keen eye on changing technologies and trends.

 Sahil Malik

Preface

Building Single Page App using ASP.NET Core and Angular is written in such a way, that while reading you will be building fully functional End-To-End app which you will be starting from basics to advanced concepts in every area. This book uses tons of concepts like Solid Principles, Repository Pattern, Unit of Work Pattern, Entity Framework, Design Principles and many other things to name a few. One point to note here that Author expects to have basic knowledge around these technology stacks to understand the book completely. This book is all about building industry standard application by coupling variety of technologies together. Hence, readers are expected to have basic knowledge on the same.

Angular is used as Single Page Framework for client side. Soon after Angular creation in 2009, AngularJS grew like widely popular framework for building Single Page Application. It started with AngularJS, where in AngularJS still exists and it will remain for the years to come. Now a days it’s also known as Angular 1. In order to make this framework more robust and lightning fast, google overhauled this framework completely and decided to change the architecture. They re-written entire framework in Typescript, which means type system is baked in into its core.

Angular is wholly different component written for futuristic web. It is written on top of ES6, web components, web workers, reactive programming and Typescript to name a few. Modularity is the key concept in Angular on which everything is built around. It also offers bountiful collection of configuration and tooling which makes an Angular app very fast.

How this book is structured?

This book is divided into broad sections, and comprising several chapters. First part of this book is structuring the project in and then introducing server side components first and then client side components.

Chapter 1, “Getting Started”, helps you get the feel of overall book. Here, you will understand, what you are going to build throughout the book. You will also get to see what technology, you will be using through. You will also get the glimpse of the finished project.

Chapter 2, “Creating Solution from the Blank Slate”, in this chapter, you will be creating solution from scratch. Here, you will be doing all tooling and project setup to get started with application. Here, you will also add necessary library references to other class library projects.

Chapter 3, “Creating Data Context”, in this chapter, you will be implementing data technology part of project. First you will be creating models here, then for filling the same, you will be using Entity Framework approach. Here, you will also learn variety of different concepts like data seeding, implementing Repository Pattern, applying database constraints etc.

Chapter 4, “Implementing Web API”, in this chapter, you will implementing Web API. You will start with simple API design, then you will be writing complex API designs for custom queries. Lastly, you will be adding couple of more controllers for custom based query.

Chapter 5, “Getting Started with Angular”, in this chapter, you will be starting with Frontend design like Angular Implementation. We will start with simple Angular component creation. Further we will delve into routing techniques followed by simple Form design and service implementation.

Chapter 6, “Deeper into Angular” in this chapter, we will delve further and look into the guts of application. Here, we will start with client side validation. In that course, we will third party libraries like toasty. We will also see how to handle errors in Angular. We will be using cloud based logging scheme in this case.

Chapter 7, “Adding More Features using Angular”, in this chapter, we will continue from the last section and extend the application further. Here, we will begin with listing reviews and implementing CRUD pattern for reviews. Here, we will be fixing some crucial navigation issues as well.

Chapter 8, “Adding More Features to the App”, this is the bonus section of the book; I can say as all mandatory application based functionality is over by this time. Here, we will be extending the same by adding features like image upload and rendering the same using angular. We will also see how to work with tabbed view in angular.

Chapter 9, “Authentication & Authorization”, in this chapter, you will begin by learning the concepts of authentication and authorization. Here, we will be using third party library like Auth0 for the same. Once completed, then you will learn how to use JWTs bearer token for the same. Here, you will implement complete authentication cycle. Here, you will also learn how to create custom login pages. Apart from that, you will see how to implement rules, roles, protect routes etc.

Chapter 10, “Introduction to Azure and CosmosDb”, in this chapter, you will begin by learning the concepts of CosmosDb. Cosmos DB is a NoSql database that provides strong consistency. It’s schema free, supports sql-like querying, even has stored procedures, triggers and UDFs (User Defined Functions) written in Javascript. It’s really Microsoft’s answer to MongoDb, Cassandra, Couchbase and others. According to Cosmos DB, “Azure Cosmos DB guarantees less than 10 millisecond latencies on reads and less than 15 millisecond latencies on writes for at least 99% of requests.” With that kind of performance guarantees, Cosmos DB is set to take over the world. Here, you will learn how to get started with Cosmos DB.

Project Download:-

GitHub Link: – https://github.com/rahulsahay19/MovieReviewSPA-NG4.You can download project from here for your reference. In case, if you find any discrepancies, you can report the same in issues’ link on git page. In case if you like to have provide any suggestions, that also you can provide at below link https://github.com/rahulsahay19/ama/issues. You can also download my asp.net core plugin for VS Code from http://bit.ly/ASP-NET-CORE-Ext. If you are doing asp.net core project using code, then that link is must have tool for that.

Chapter 1: – Getting Started

 WHAT do you find in this Chapter?

 

  • Introduction
  • What is SPA
  • Technologies used to build SPAs
  • Glimpses of the Movie Review App
  • Glimpses of the Movie Review Solution
  • Summary

INTRODUCTION: –

In this section, I am going to introduce this whole new story of building a Single- Page Application right from scratch. Here in this context, I am going to talk about a bunch of different client/server-side technologies and demonstrate how these small pieces come together and create a robust End-to-End application. However, I do expect readers to have basic working knowledge of ASP.NET Core and Angular 2 or 4. Then, only you will be able to grasp the techniques comfortably. Hence, without wasting time let’s get started.

 

What is SPA: –

Single Page Application is all about user experience. People will love your app if you give them a nice user experience which not only fits nicely on your laptop or desktop rather it goes nicely with many devices such as tabs, phones, etc. without breaking any single functionality. As shown in the following diagram, these are the basic requirements for building any SPA.

  • Reliability: People know that it’s reliable and it’s going to work. This kind of reliability only comes with positive experience.
  • Responsiveness: Responsiveness means it’s going to work quickly for them. Quick is the key thing which any user expects to have in the app which he is using.
  • Reach: Reach is often substituted with mobility. Mobility is again one of the key ingredients which every user is looking for. They always want to have the data handy irrespective of what device they are on.
  • Available: Availability is really important when it comes to working offline. Hence, delivering a good user experience is a must while building SPA.

Therefore, in a nutshell, a Single Page App is a web application which fits in a single page providing a fluid UX by loading all the necessary data in a single load.

Now, apart from this, there are many other attributes linked to SPA. They are as follows:

  • Maintain History: When you flip between pages, it maintains your history in the same order you visited them. Actually, it does not go to different pages but loads different information on the same page. It looks as if it’s presenting different pages to them.
  • Persisting Information: Persisting information is also a very important aspect of the SPA. This doesn’t mean that you need to save each and every thing in the cache but you can store important things in the cache to improve the performance.
  • Mostly loaded on Page Load: Mostly loaded on the page load means a majority of information a user requires gets loaded initially to avoid a round trip back to the server.
  • Dependent Elements: As and when a user needs to access different features of the application, the app will download the features for the user.

Technologies used to build SPA: –

Movie Review App is built using tons of different client-side and server-side technologies. Some of these are listed below: –

Client-Side Technologies:

  • HTML 5
  • CSS 3
  • Modernizer & LESS
  • Responsive Design
  • Media Queries
  • Angular 4
  • Toastr JS
  • Bootstrap Templates
  • Font Awesome Icons

 

Server-Side Technologies: –

  • ASP.NET Core
  • SQL Server
  • Entity Framework Core – Code First Approach
  • Repository Pattern
  • Unit of Work Pattern
  • Web API
  • JSON & AJAX
  • NuGet
  • IOC
  • POCO Models

Design Techniques:

  • Solid Principles
  • Factory Pattern

Tools Used:

  • Visual Studio 2017

Glimpse of Movie Review APP:

I think it would be a great idea to show you the finished application before directly jumping to creating the same. The following figure shows a glimpse of the finished product in the best possible way. Once you download the app and run it, it will look like this.

Here, I have different options like Login and Movies. The other two options are from the scaffolding project; you can skip those. I have not removed the menus. We will come later to the Login menu. Let’s first check Movies’ menu. Once, you click on Movies, it will show you the following screen:

Here, Filter Movie is a drop down which shows the following:

Therefore, if I select Avatar, then my Movies List will filter out other movies, as shown below:

Now, if I click on the Reset button or if I select the Blank option from the drop-down menu, then the list will get reset. Next, when I click on Movie Reviews link, then it will show the following screen:

Once the review is fetched successfully, the following toast message will appear on the screen.

 

We can also filter by review rating by selecting the Filter Reviews by Rating option.

This is the same filter concept we had seen earlier. After this screen appears, we can go ahead and add new reviews as well, as shown below:

You will notice that the Submit button is disabled here, which means you can’t submit the form until you fill the valid details. Once I fill in the details, the Submit button gets enabled, as shown below:

Now, I can submit the form. Once I click on the Submit button, it will show the following toast message:

And then it will get redirected to Movies’ page.

Here, I can see that Movie Reviews has now changed to 2. Similarly, I can Edit Movie as well, as shown below:

On the edit screen, it will show the existing movie, which I can modify, as shown in the following screenshot:

Once I click on the Submit button, it will show the following toast message and get redirected to the Movies’ page.

Let me change the year back to 2009. Now, when I click on Detail View, it will appear like this.

This is a tabbed view, which by default is Movie, which basically shows the movie details in read-only mode. Here, I have one button “View All Movies” to go back to the Movies’ page. The second tab is for images. Therefore, when I click on the Pics tab, it will fetch the images corresponding to the movie.

By clicking on the Pics tab, we can browse the movie images as well upload them one by one, as shown in the following screenshot:

Upon successful upload, it will display the following toast message:

And a new image will also appear on the page, as shown below.

We now go back to the Movies page. Here you can see the Delete Movie tab. When you click on the Delete Movie tab, it will show you a prompt as shown below.

If you click on OK, then it will delete the movie; else it will remain on the same page like normal delete functionality. Now, Click on the “Create New Movie” link as shown below.

It will get redirected to login page as shown below. Here, you can either sign-up with Google or you can create a new user with auth0 Site. I have discussed about auth0 in detail in the next chapter.

Here, I have logged in with my ID and I am the admin here. I have created rules in such a way that only admin users can create movies. This is just for demonstration purpose; you can extend this feature to expensive operations like delete, update, etc. Once you log in successfully, you will notice that the New Movie option for creating the movie appears on the screen.

Once I click on the New Movie tab, the following screen will appear:

Here, I can create any movie, as shown below.

Here, when I click on the Submit button, a new movie will be created and will show the below toast message.

Now, I can see the new movie I just created on the Movies page, as shown below.

Similarly, I can add/update/delete reviews. We have already seen that.

Glimpse of Movie Review SOLUTION: –

Let me go ahead and show you the solution structure of a finished app. In the following screenshot, you can see four different projects. Each of them has its own dependency and responsibility.

Here, the highlighted one is the web project which is dependent on other infrastructure projects like Data, Contracts, and Model. The Data project is a place where you can maintain the initial seed data, Entity Framework DbContext and many other things that interact directly with the database. Data Contract is the place where in you can manage your repositories and apply the Unit of Work Pattern on repositories like Movies and Moviereviews. Model is the section where you will have your POCOs (Plain Old CLR Objects). This is also a place where you can maintain all properties attributed to the tables. Here is a glimpse of all the projects in their expanded form.

SUMMARY: –

In this section, we saw the bits and bytes of the Single-Page Application that we used while building the application. We also saw a glimpse of the app and solution. In the next chapter, we’ll create the application right from scratch. I recommend that you download the app from GitHub URL, which will help you while building, https://github.com/rahulsahay19/MovieReviewSPA-NG4. This will enable you to quickly check and fix any issues you face while building the app.

Amazon Link:- http://bit.ly/spa-asp-core

Note:- Book will also be available in print format as well in few days.

Thanks,
Rahul Sahay
Happy Coding

1,122 total views, 1 views today


Also published on Medium.