ANGULARJS Create a simple access system

Source: Internet
Author: User
Tags jquery library

ANGULARJS Create a simple permission system I. INTRODUCTION

The previous blog post has introduced some of the ANGULARJS core Knowledge points in this blog post that will show you how to apply ANGULARJS to real projects. This blog post will use Angularjs to create a simple rights management system. Below not much to say, directly into the subject.

Second, the overall structure design introduction

First look at the architectural design of the entire project:

As you can see an overall structure of the whole project, next, I'll cover the overall architecture of the project in detail:

Use the ASP. NET Web API to implement REST services. This implementation has reached the common, deployment, and better expansion of the backend services. The Web tier relies on the application service interface and uses Castle Windsor to implement dependency injection.

    • Display layer (user UI)

The display layer uses the ANGULARJS to implement the Spa page. All of the page data is asynchronous loading and local refresh, so the implementation will have a better user experience.

    • Application layer (Application Service)

Angularjs through the HTTP service to request the Web API to obtain data, and the implementation of the Web API is to invoke the application layer to request data.

    • Infrastructure Layer

The infrastructure layer includes the implementation of warehousing and some common methods.

The implementation of the warehousing layer is implemented using EF Code First, and the EF migration is used to create the database and update the database.

The Lh.common layer implements some common methods, such as the implementation of classes such as log helper classes, expression tree extensions, and so on.

    • Domain Layer

The domain layer mainly implements all domain models of the project, including the implementation of the domain model and the definition of the warehousing interface.

After describing the overall structure, the next step is to introduce the project's backend service implementation and web front-end implementation respectively.

Third, back-end service implementation

Back-end services mainly use the ASP. NET Web API to implement backend services, and use Castle Windsor to complete dependency injection.

This is where user management in rights Management describes the implementation of the rest Web API service.

The implementation of a rest service that provides user data:

 public class Usercontroller:apicontroller {private readonly iuserservice _userservice;        Public Usercontroller (Iuserservice userservice) {_userservice = UserService;        } [HttpGet] [Route ("Api/user/getusers")] public outputbase getusers ([fromuri]pageinput input)        {return _userservice.getusers (input); } [HttpGet] [Route ("Api/user/userinfo")] public outputbase getuserinfo (int id) {RE        Turn _userservice.getuser (ID);        } [HttpPost] [Route ("Api/user/adduser")] public outputbase CreateUser ([frombody] userdto userdto)        {return _userservice.adduser (userdto);        } [HttpPost] [Route ("Api/user/updateuser")] public outputbase UpdateUser ([frombody] userdto userdto)        {return _userservice.updateuser (userdto); } [HttpPost] [Route ("Api/user/updateroles")] public outPutbase updateroles ([frombody] userdto userdto) {return _userservice.updateroles (userdto);            } [HttpPost] [Route ("Api/user/deleteuser/{id}")] public outputbase deleteuser (int id) {        return _userservice.deleteuser (ID); } [HttpPost] [Route ("Api/user/deleterole/{id}/{roleid}")] public outputbase deleterole (int id, int ro        LeId) {return _userservice.deleterole (ID, Roleid); }    }

As can be seen from the above code implementation, the User rest service relies on the Iuserservice interface, and there is no traditional way to put all the business logic in the Web API implementation, but to encapsulate specific business implementations into the corresponding application layer, REST The API is only responsible for invoking services in the corresponding application tier. The advantages of this design are:

    1. Rest services rely on the interface with the application layer, separating the duties, and handing the instantiation of the application-layer service to a separate dependency injection container, while the rest service is only responsible for invoking the method of the corresponding application service to fetch the data. Using a dependency interface instead of relying on the implementation of a specific class makes the class-to-class low-coupling.
    2. A specific business logic implementation is not included within the rest service. This design allows for better separation of services, and if you later want to use WCF to implement REST services, you do not need to repeat the logic in the Web API repeatedly in WCF's Rest service class, when you can invoke the Application service's interface method to implement the WCF rest service. So by pumping the business logic implementation into the application service layer, such a design would make rest service responsibilities more singular and rest service implementations easier to scale.

Implementation of user application services:

View Code

In fact, the application service layer can be further optimized to achieve code-level read-write separation, define the Ireadonlyservice interface and Iwriteservie interface, and write operations can be used in the way of generic methods abstracted into the baseservice to achieve. Such a number of additions and deletions to implement the public, the reason can be implemented here common, because these operations are very similar, but the operation of the entity is not the same. In fact, this implementation in my other open source project has been used: Onlinestore. You can refer to this by yourself to achieve.

The implementation of the storage layer:

User application services are also not directly dependent on the specific warehousing classes, but also on their interfaces. The implementation of the corresponding user warehousing class is as follows:

public class baserepository<tentity>: irepository<tentity> where Tentity:class, ientity { Private readonly threadlocal<usermanagerdbcontext> _localctx = new Threadlocal<usermanagerdbcontext> (() =        > New Usermanagerdbcontext ());        Public Usermanagerdbcontext DbContext {get {return _localctx.value;}} Public TEntity Findsingle (expression<func<tentity, bool>> exp = null) {return dbcontext.set <TEntity> (). Asnotracking ().        FirstOrDefault (exp);            } public iqueryable<tentity> Find (expression<func<tentity, bool>> exp = null) {        Return Filter (exp); } public iqueryable<tentity> Find (expression<func<tentity, bool>> Expression, expression<func& Lt TEntity, dynamic>> sortpredicate, SortOrder SortOrder, int pagenumber, int pageSize) {if (pagenum ber <= 0) throw new ArgumentoutofrangeexcEption ("PageNumber", PageNumber, "pagenumber must great than or equal to 1.");  if (pageSize <= 0) throw new ArgumentOutOfRangeException ("PageSize", PageSize, "pageSize must great than            or equal to 1. "); var query = dbcontext.set<tentity> ().            Where (expression);            var skip = (pageNumber-1) * pageSize;            var take = pageSize; if (sortpredicate = = null) throw new InvalidOperationException ("Based on the paging query must specify sort            ing fields and sort order. "); Switch (sortOrder) {case SortOrder.Ascending:var pagedascending = query. SortBy (sortpredicate). Skip (Skip).                    Take (take);                return pagedascending; Case SortOrder.Descending:var pageddescending = query. Sortbydescending (sortpredicate). Skip (Skip).                    Take (take);            return pageddescending; } throw new InvalidoperaTionexception ("Based on the paging query must specify sorting fields and sort order."); } public int GetCount (expression<func<tentity, bool>> exp = null) {return Filter (exp ).        Count (); public void Add (TEntity entity) {dbcontext.set<tentity> ().        ADD (entity); public void Update (TEntity entity) {Dbcontext.entry (entity).        state = entitystate.modified; public void Delete (TEntity entity) {Dbcontext.entry (entity).            state = entitystate.deleted; Dbcontext.set<tentity> ().        Remove (entity); } public void Delete (icollection<tentity> entitycollection) {if (Entitycollection.count ==0            ) return; Dbcontext.set<tentity> ().            Attach (Entitycollection.first ()); Dbcontext.set<tentity> ().        RemoveRange (entitycollection); } Private Iqueryable<tentity>Filter (expression<func<tentity, bool>> exp) {var dbSet = dbcontext.set<tentity> ().            AsQueryable ();            IF (exp! = null) DbSet = Dbset.where (exp);        return dbSet;        } public void Commit () {dbcontext.savechanges (); }}public class Userrepository:baserepository<user>, Iuserrepository {}
Four, Angularjs front-end implementation

The implementation of Web front-end is implemented by using ANGULARJS, and the modular development mode is adopted. The code structure for the specific Web front-end is as follows:

App/images//Storage of picture resources used by the Web front end app/styles//Store style file app/scripts//script file for entire Web front end/                Controllers//ANGULARJS Controller Module Storage Directory c3/>/  directives//ANGULARJS instruction Module Storage directory              /   filters  //filter Module storage Directory/   Services//Service Module storage directory            / App.js//Web front-end Program configuration module (routing configuration) App/modules//  project dependent Library, angular, Bootstrap, jquery library app/views//ANGULARJS View Template Storage Directory

The call hierarchy and backend are basically consistent between the code of the Web application developed with ANGULARJS and the Web API service, the view page-the Controller module-service module.

And the Web front-end CSS and JS resources loaded using bundles to reduce the number of requests for resources, thereby speeding up page load time. Configuration of the specific bundle class:

public class Bundleconfig {//For more information on bundling, visit http://go.microsoft.com/fwlink/?            linkid=301862 public static void Registerbundles (Bundlecollection bundles) {//class library dependent file Bundles. ADD (New Scriptbundle ("~/js/base/lib"). Include ("~/app/modules/jquery-1.11.2.min.js", "~/app/modules/angular/angular.min.js "," ~/app/modules/angular/angular-route.min.js "," ~/app/modules/bootstrap/js/ui-boot Strap-tpls-0.13.0.min.js "," ~/app/modules/bootstrap-notify/bootstrap-notify.min.js ")            ); Angularjs project file bundles. ADD (New Scriptbundle ("~/js/angularjs/app").                    Include ("~/app/scripts/services/*.js", "~/app/scripts/controllers/*.js", "~/app/scripts/directives/*.js", "~/app/scripts/filters/*.js", "~/app/scrip   Ts/app.js "));         Style bundles. ADD (New Stylebundle ("~/js/base/style"). Include ("~/app/modules/bootstrap/css/bootstrap.min.css", "~/app/styles/dashboard.cs        S "," ~/app/styles/console.css ")); }    }

Home index.cshtml

<! DOCTYPE html>Five, the Operation effect

After introducing the implementation of the front and back end, let's look at how the whole project works:

Vi. Summary

Here, all the content of this article is finished, although the ANGULARJS application project in this article has many perfect places, such as no buffering support, no read/write separation, no stress test for some APIs, etc. However, the application of Angularjs in the actual project is basically the case, if you need to use ANGULARJS in the project, just the backstage of your company is. NET, I believe the sharing of this article can be a good reference. In addition, the design of the architecture can also refer to my other Open source project: Onlinestore and Fastworks.

This article all source code:privilegemanagement

ANGULARJS Create a simple access system

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.