前端技术
HTML
CSS
Javascript
前端框架和UI库
VUE
ReactJS
AngularJS
JQuery
NodeJS
JSON
Element-UI
Bootstrap
Material UI
服务端和客户端
Java
Python
PHP
Golang
Scala
Kotlin
Groovy
Ruby
Lua
.net
c#
c++
后端WEB和工程框架
SpringBoot
SpringCloud
Struts2
MyBatis
Hibernate
Tornado
Beego
Go-Spring
Go Gin
Go Iris
Dubbo
HessianRPC
Maven
Gradle
数据库
MySQL
Oracle
Mongo
中间件与web容器
Redis
MemCache
Etcd
Cassandra
Kafka
RabbitMQ
RocketMQ
ActiveMQ
Nacos
Consul
Tomcat
Nginx
Netty
大数据技术
Hive
Impala
ClickHouse
DorisDB
Greenplum
PostgreSQL
HBase
Kylin
Hadoop
Apache Pig
ZooKeeper
SeaTunnel
Sqoop
Datax
Flink
Spark
Mahout
数据搜索与日志
ElasticSearch
Apache Lucene
Apache Solr
Kibana
Logstash
数据可视化与OLAP
Apache Atlas
Superset
Saiku
Tesseract
系统与容器
Linux
Shell
Docker
Kubernetes
[C 与Visual Basic在NET中...]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
转载文章
...blog.csdn.net/gz19871113/article/details/108591802。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。 注:本文是【ASP.NET Identity系列教程】的第三篇。本系列教程详细、完整、深入地介绍了微软的ASP.NET Identity技术,描述了如何运用ASP.NET Identity实现应用程序的用户管理,以及实现应用程序的认证与授权等相关技术,译者希望本系列教程能成为掌握ASP.NET Identity技术的一份完整而有价值的资料。读者若是能够按照文章的描述,一边阅读、一边实践、一边理解,定能有意想不到的巨大收获!希望本系列博文能够得到广大园友的高度推荐。 15 Advanced ASP.NET Identity 15 ASP.NET Identity高级技术 In this chapter, I finish my description of ASP.NET Identity by showing you some of the advanced features it offers. I demonstrate how you can extend the database schema by defining custom properties on the user class and how to use database migrations to apply those properties without deleting the data in the ASP.NET Identity database. I also explain how ASP.NET Identity supports the concept of claims and demonstrates how they can be used to flexibly authorize access to action methods. I finish the chapter—and the book—by showing you how ASP.NET Identity makes it easy to authenticate users through third parties. I demonstrate authentication with Google accounts, but ASP.NET Identity has built-in support for Microsoft, Facebook, and Twitter accounts as well. Table 15-1 summarizes this chapter. 本章将完成对ASP.NET Identity的描述,向你展示它所提供的一些高级特性。我将演示,你可以扩展ASP.NET Identity的数据库架构,其办法是在用户类上定义一些自定义属性。也会演示如何使用数据库迁移,这样可以运用自定义属性,而不必删除ASP.NET Identity数据库中的数据。还会解释ASP.NET Identity如何支持声明(Claims)概念,并演示如何将它们灵活地用来对动作方法进行授权访问。最后向你展示ASP.NET Identity很容易通过第三方部件来认证用户,以此结束本章以及本书。将要演示的是使用Google账号认证,但ASP.NET Identity对于Microsoft、Facebook以及Twitter账号,都有内建的支持。表15-1是本章概要。 Table 15-1. Chapter Summary 表15-1. 本章概要 Problem 问题 Solution 解决方案 Listing 清单号 Store additional information about users. 存储用户的附加信息 Define custom user properties. 定义自定义用户属性 1–3, 8–11 Update the database schema without deleting user data. 更新数据库架构而不删除用户数据 Perform a database migration. 执行数据库迁移 4–7 Perform fine-grained authorization. 执行细粒度授权 Use claims. 使用声明(Claims) 12–14 Add claims about a user. 添加用户的声明(Claims) Use the ClaimsIdentity.AddClaims method. 使用ClaimsIdentity.AddClaims方法 15–19 Authorize access based on claim values. 基于声明(Claims)值授权访问 Create a custom authorization filter attribute. 创建一个自定义的授权过滤器注解属性 20–21 Authenticate through a third party. 通过第三方认证 Install the NuGet package for the authentication provider, redirect requests to that provider, and specify a callback URL that creates the user account. 安装认证提供器的NuGet包,将请求重定向到该提供器,并指定一个创建用户账号的回调URL。 22–25 15.1 Preparing the Example Project 15.1 准备示例项目 In this chapter, I am going to continue working on the Users project I created in Chapter 13 and enhanced in Chapter 14. No changes to the application are required, but start the application and make sure that there are users in the database. Figure 15-1 shows the state of my database, which contains the users Admin, Alice, Bob, and Joe from the previous chapter. To check the users, start the application and request the /Admin/Index URL and authenticate as the Admin user. 本章打算继续使用第13章创建并在第14章增强的Users项目。对应用程序无需做什么改变,但需要启动应用程序,并确保数据库中有一些用户。图15-1显示了数据库的状态,它含有上一章的用户Admin、Alice、Bob以及Joe。为了检查用户,请启动应用程序,请求/Admin/Index URL,并以Admin用户进行认证。 Figure 15-1. The initial users in the Identity database 图15-1. Identity数据库中的最初用户 I also need some roles for this chapter. I used the RoleAdmin controller to create roles called Users and Employees and assigned the users to those roles, as described in Table 15-2. 本章还需要一些角色。我用RoleAdmin控制器创建了角色Users和Employees,并为这些角色指定了一些用户,如表15-2所示。 Table 15-2. The Types of Web Forms Code Nuggets 表15-2. 角色及成员(作者将此表的标题写错了——译者注) Role 角色 Members 成员 Users Alice, Joe Employees Alice, Bob Figure 15-2 shows the required role configuration displayed by the RoleAdmin controller. 图15-2显示了由RoleAdmin控制器所显示出来的必要的角色配置。 Figure 15-2. Configuring the roles required for this chapter 图15-2. 配置本章所需的角色 15.2 Adding Custom User Properties 15.2 添加自定义用户属性 When I created the AppUser class to represent users in Chapter 13, I noted that the base class defined a basic set of properties to describe the user, such as e-mail address and telephone number. Most applications need to store more information about users, including persistent application preferences and details such as addresses—in short, any data that is useful to running the application and that should last between sessions. In ASP.NET Membership, this was handled through the user profile system, but ASP.NET Identity takes a different approach. 我在第13章创建AppUser类来表示用户时曾做过说明,基类定义了一组描述用户的基本属性,如E-mail地址、电话号码等。大多数应用程序还需要存储用户的更多信息,包括持久化应用程序爱好以及地址等细节——简言之,需要存储对运行应用程序有用并且在各次会话之间应当保持的任何数据。在ASP.NET Membership中,这是通过用户资料(User Profile)系统来处理的,但ASP.NET Identity采取了一种不同的办法。 Because the ASP.NET Identity system uses Entity Framework to store its data by default, defining additional user information is just a matter of adding properties to the user class and letting the Code First feature create the database schema required to store them. Table 15-3 puts custom user properties in context. 因为ASP.NET Identity默认是使用Entity Framework来存储其数据的,定义附加的用户信息只不过是给用户类添加属性的事情,然后让Code First特性去创建需要存储它们的数据库架构即可。表15-3描述了自定义用户属性的情形。 Table 15-3. Putting Cusotm User Properties in Context 表15-3. 自定义用户属性的情形 Question 问题 Answer 回答 What is it? 什么是自定义用户属性? Custom user properties allow you to store additional information about your users, including their preferences and settings. 自定义用户属性让你能够存储附加的用户信息,包括他们的爱好和设置。 Why should I care? 为何要关心它? A persistent store of settings means that the user doesn’t have to provide the same information each time they log in to the application. 设置的持久化存储意味着,用户不必每次登录到应用程序时都提供同样的信息。 How is it used by the MVC framework? 在MVC框架中如何使用它? This feature isn’t used directly by the MVC framework, but it is available for use in action methods. 此特性不是由MVC框架直接使用的,但它在动作方法中使用是有效的。 15.2.1 Defining Custom Properties 15.2.1 定义自定义属性 Listing 15-1 shows how I added a simple property to the AppUser class to represent the city in which the user lives. 清单15-1演示了如何给AppUser类添加一个简单的属性,用以表示用户生活的城市。 Listing 15-1. Adding a Property in the AppUser.cs File 清单15-1. 在AppUser.cs文件中添加属性 using System;using Microsoft.AspNet.Identity.EntityFramework;namespace Users.Models { public enum Cities {LONDON, PARIS, CHICAGO}public class AppUser : IdentityUser {public Cities City { get; set; } }} I have defined an enumeration called Cities that defines values for some large cities and added a property called City to the AppUser class. To allow the user to view and edit their City property, I added actions to the Home controller, as shown in Listing 15-2. 这里定义了一个枚举,名称为Cities,它定义了一些大城市的值,另外给AppUser类添加了一个名称为City的属性。为了让用户能够查看和编辑City属性,给Home控制器添加了几个动作方法,如清单15-2所示。 Listing 15-2. Adding Support for Custom User Properties in the HomeController.cs File 清单15-2. 在HomeController.cs文件中添加对自定义属性的支持 using System.Web.Mvc;using System.Collections.Generic;using System.Web;using System.Security.Principal;using System.Threading.Tasks;using Users.Infrastructure;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.Owin;using Users.Models;namespace Users.Controllers {public class HomeController : Controller {[Authorize]public ActionResult Index() {return View(GetData("Index"));}[Authorize(Roles = "Users")]public ActionResult OtherAction() {return View("Index", GetData("OtherAction"));}private Dictionary<string, object> GetData(string actionName) {Dictionary<string, object> dict= new Dictionary<string, object>();dict.Add("Action", actionName);dict.Add("User", HttpContext.User.Identity.Name);dict.Add("Authenticated", HttpContext.User.Identity.IsAuthenticated);dict.Add("Auth Type", HttpContext.User.Identity.AuthenticationType);dict.Add("In Users Role", HttpContext.User.IsInRole("Users"));return dict;} [Authorize]public ActionResult UserProps() {return View(CurrentUser);}[Authorize][HttpPost]public async Task<ActionResult> UserProps(Cities city) {AppUser user = CurrentUser;user.City = city;await UserManager.UpdateAsync(user);return View(user);}private AppUser CurrentUser {get {return UserManager.FindByName(HttpContext.User.Identity.Name);} }private AppUserManager UserManager {get {return HttpContext.GetOwinContext().GetUserManager<AppUserManager>();} }} } I added a CurrentUser property that uses the AppUserManager class to retrieve an AppUser instance to represent the current user. I pass the AppUser object as the view model object in the GET version of the UserProps action method, and the POST method uses it to update the value of the new City property. Listing 15-3 shows the UserProps.cshtml view, which displays the City property value and contains a form to change it. 我添加了一个CurrentUser属性,它使用AppUserManager类接收了表示当前用户的AppUser实例。在GET版本的UserProps动作方法中,传递了这个AppUser对象作为视图模型。而在POST版的方法中用它更新了City属性的值。清单15-3显示了UserProps.cshtml视图,它显示了City属性的值,并包含一个修改它的表单。 Listing 15-3. The Contents of the UserProps.cshtml File in the Views/Home Folder 清单15-3. Views/Home文件夹中UserProps.cshtml文件的内容 @using Users.Models@model AppUser@{ ViewBag.Title = "UserProps";}<div class="panel panel-primary"><div class="panel-heading">Custom User Properties</div><table class="table table-striped"><tr><th>City</th><td>@Model.City</td></tr></table></div> @using (Html.BeginForm()) {<div class="form-group"><label>City</label>@Html.DropDownListFor(x => x.City, new SelectList(Enum.GetNames(typeof(Cities))))</div><button class="btn btn-primary" type="submit">Save</button>} Caution Don’t start the application when you have created the view. In the sections that follow, I demonstrate how to preserve the contents of the database, and if you start the application now, the ASP.NET Identity users will be deleted. 警告:创建了视图之后不要启动应用程序。在以下小节中,将演示如何保留数据库的内容,如果现在启动应用程序,将会删除ASP.NET Identity的用户。 15.2.2 Preparing for Database Migration 15.2.2 准备数据库迁移 The default behavior for the Entity Framework Code First feature is to drop the tables in the database and re-create them whenever classes that drive the schema have changed. You saw this in Chapter 14 when I added support for roles: When the application was started, the database was reset, and the user accounts were lost. Entity Framework Code First特性的默认行为是,一旦修改了派生数据库架构的类,便会删除数据库中的数据表,并重新创建它们。在第14章可以看到这种情况,在我添加角色支持时:当重启应用程序后,数据库被重置,用户账号也丢失。 Don’t start the application yet, but if you were to do so, you would see a similar effect. Deleting data during development is usually not a problem, but doing so in a production setting is usually disastrous because it deletes all of the real user accounts and causes a panic while the backups are restored. In this section, I am going to demonstrate how to use the database migration feature, which updates a Code First schema in a less brutal manner and preserves the existing data it contains. 不要启动应用程序,但如果你这么做了,会看到类似的效果。在开发期间删除数据没什么问题,但如果在产品设置中这么做了,通常是灾难性的,因为它会删除所有真实的用户账号,而备份恢复是很痛苦的事。在本小节中,我打算演示如何使用数据库迁移特性,它能以比较温和的方式更新Code First的架构,并保留架构中的已有数据。 The first step is to issue the following command in the Visual Studio Package Manager Console: 第一个步骤是在Visual Studio的“Package Manager Console(包管理器控制台)”中发布以下命令: Enable-Migrations –EnableAutomaticMigrations This enables the database migration support and creates a Migrations folder in the Solution Explorer that contains a Configuration.cs class file, the contents of which are shown in Listing 15-4. 它启用了数据库的迁移支持,并在“Solution Explorer(解决方案资源管理器)”创建一个Migrations文件夹,其中含有一个Configuration.cs类文件,内容如清单15-4所示。 Listing 15-4. The Contents of the Configuration.cs File 清单15-4. Configuration.cs文件的内容 namespace Users.Migrations {using System;using System.Data.Entity;using System.Data.Entity.Migrations;using System.Linq;internal sealed class Configuration: DbMigrationsConfiguration<Users.Infrastructure.AppIdentityDbContext> {public Configuration() {AutomaticMigrationsEnabled = true;ContextKey = "Users.Infrastructure.AppIdentityDbContext";}protected override void Seed(Users.Infrastructure.AppIdentityDbContext context) {// This method will be called after migrating to the latest version.// 此方法将在迁移到最新版本时调用// You can use the DbSet<T>.AddOrUpdate() helper extension method// to avoid creating duplicate seed data. E.g.// 例如,你可以使用DbSet<T>.AddOrUpdate()辅助器方法来避免创建重复的种子数据//// context.People.AddOrUpdate(// p => p.FullName,// new Person { FullName = "Andrew Peters" },// new Person { FullName = "Brice Lambson" },// new Person { FullName = "Rowan Miller" }// );//} }} Tip You might be wondering why you are entering a database migration command into the console used to manage NuGet packages. The answer is that the Package Manager Console is really PowerShell, which is a general-purpose tool that is mislabeled by Visual Studio. You can use the console to issue a wide range of helpful commands. See http://go.microsoft.com/fwlink/?LinkID=108518 for details. 提示:你可能会觉得奇怪,为什么要在管理NuGet包的控制台中输入数据库迁移的命令?答案是“Package Manager Console(包管理控制台)”是真正的PowerShell,这是Visual studio冒用的一个通用工具。你可以使用此控制台发送大量的有用命令,详见http://go.microsoft.com/fwlink/?LinkID=108518。 The class will be used to migrate existing content in the database to the new schema, and the Seed method will be called to provide an opportunity to update the existing database records. In Listing 15-5, you can see how I have used the Seed method to set a default value for the new City property I added to the AppUser class. (I have also updated the class file to reflect my usual coding style.) 这个类将用于把数据库中的现有内容迁移到新的数据库架构,Seed方法的调用为更新现有数据库记录提供了机会。在清单15-5中可以看到,我如何用Seed方法为新的City属性设置默认值,City是添加到AppUser类中自定义属性。(为了体现我一贯的编码风格,我对这个类文件也进行了更新。) Listing 15-5. Managing Existing Content in the Configuration.cs File 清单15-5. 在Configuration.cs文件中管理已有内容 using System.Data.Entity.Migrations;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.EntityFramework;using Users.Infrastructure;using Users.Models;namespace Users.Migrations {internal sealed class Configuration: DbMigrationsConfiguration<AppIdentityDbContext> {public Configuration() {AutomaticMigrationsEnabled = true;ContextKey = "Users.Infrastructure.AppIdentityDbContext";}protected override void Seed(AppIdentityDbContext context) {AppUserManager userMgr = new AppUserManager(new UserStore<AppUser>(context));AppRoleManager roleMgr = new AppRoleManager(new RoleStore<AppRole>(context)); string roleName = "Administrators";string userName = "Admin";string password = "MySecret";string email = "admin@example.com";if (!roleMgr.RoleExists(roleName)) {roleMgr.Create(new AppRole(roleName));}AppUser user = userMgr.FindByName(userName);if (user == null) {userMgr.Create(new AppUser { UserName = userName, Email = email },password);user = userMgr.FindByName(userName);}if (!userMgr.IsInRole(user.Id, roleName)) {userMgr.AddToRole(user.Id, roleName);}foreach (AppUser dbUser in userMgr.Users) {dbUser.City = Cities.PARIS;}context.SaveChanges();} }} You will notice that much of the code that I added to the Seed method is taken from the IdentityDbInit class, which I used to seed the database with an administration user in Chapter 14. This is because the new Configuration class added to support database migrations will replace the seeding function of the IdentityDbInit class, which I’ll update shortly. Aside from ensuring that there is an admin user, the statements in the Seed method that are important are the ones that set the initial value for the City property I added to the AppUser class, as follows: 你可能会注意到,添加到Seed方法中的许多代码取自于IdentityDbInit类,在第14章中我用这个类将管理用户植入了数据库。这是因为这个新添加的、用以支持数据库迁移的Configuration类,将代替IdentityDbInit类的种植功能,我很快便会更新这个类。除了要确保有admin用户之外,在Seed方法中的重要语句是那些为AppUser类的City属性设置初值的语句,如下所示: ...foreach (AppUser dbUser in userMgr.Users) { dbUser.City = Cities.PARIS;}context.SaveChanges();... You don’t have to set a default value for new properties—I just wanted to demonstrate that the Seed method in the Configuration class can be used to update the existing user records in the database. 你不一定要为新属性设置默认值——这里只是想演示Configuration类中的Seed方法,可以用它更新数据库中的已有用户记录。 Caution Be careful when setting values for properties in the Seed method for real projects because the values will be applied every time you change the schema, overriding any values that the user has set since the last schema update was performed. I set the value of the City property just to demonstrate that it can be done. 警告:在用于真实项目的Seed方法中为属性设置值时要小心,因为你每一次修改架构时,都会运用这些值,这会将自执行上一次架构更新之后,用户设置的任何数据覆盖掉。这里设置City属性的值只是为了演示它能够这么做。 Changing the Database Context Class 修改数据库上下文类 The reason that I added the seeding code to the Configuration class is that I need to change the IdentityDbInit class. At present, the IdentityDbInit class is derived from the descriptively named DropCreateDatabaseIfModelChanges<AppIdentityDbContext> class, which, as you might imagine, drops the entire database when the Code First classes change. Listing 15-6 shows the changes I made to the IdentityDbInit class to prevent it from affecting the database. 在Configuration类中添加种植代码的原因是我需要修改IdentityDbInit类。此时,IdentityDbInit类派生于描述性命名的DropCreateDatabaseIfModelChanges<AppIdentityDbContext> 类,和你相像的一样,它会在Code First类改变时删除整个数据库。清单15-6显示了我对IdentityDbInit类所做的修改,以防止它影响数据库。 Listing 15-6. Preventing Database Schema Changes in the AppIdentityDbContext.cs File 清单15-6. 在AppIdentityDbContext.cs文件是阻止数据库架构变化 using System.Data.Entity;using Microsoft.AspNet.Identity.EntityFramework;using Users.Models;using Microsoft.AspNet.Identity; namespace Users.Infrastructure {public class AppIdentityDbContext : IdentityDbContext<AppUser> {public AppIdentityDbContext() : base("IdentityDb") { }static AppIdentityDbContext() {Database.SetInitializer<AppIdentityDbContext>(new IdentityDbInit());}public static AppIdentityDbContext Create() {return new AppIdentityDbContext();} } public class IdentityDbInit : NullDatabaseInitializer<AppIdentityDbContext> {} } I have removed the methods defined by the class and changed its base to NullDatabaseInitializer<AppIdentityDbContext> , which prevents the schema from being altered. 我删除了这个类中所定义的方法,并将它的基类改为NullDatabaseInitializer<AppIdentityDbContext> ,它可以防止架构修改。 15.2.3 Performing the Migration 15.2.3 执行迁移 All that remains is to generate and apply the migration. First, run the following command in the Package Manager Console: 剩下的事情只是生成并运用迁移了。首先,在“Package Manager Console(包管理器控制台)”中执行以下命令: Add-Migration CityProperty This creates a new migration called CityProperty (I like my migration names to reflect the changes I made). A class new file will be added to the Migrations folder, and its name reflects the time at which the command was run and the name of the migration. My file is called 201402262244036_CityProperty.cs, for example. The contents of this file contain the details of how Entity Framework will change the database during the migration, as shown in Listing 15-7. 这创建了一个名称为CityProperty的新迁移(我比较喜欢让迁移的名称反映出我所做的修改)。这会在文件夹中添加一个新的类文件,而且其命名会反映出该命令执行的时间以及迁移名称,例如,我的这个文件名称为201402262244036_CityProperty.cs。该文件的内容含有迁移期间Entity Framework修改数据库的细节,如清单15-7所示。 Listing 15-7. The Contents of the 201402262244036_CityProperty.cs File 清单15-7. 201402262244036_CityProperty.cs文件的内容 namespace Users.Migrations {using System;using System.Data.Entity.Migrations; public partial class Init : DbMigration {public override void Up() {AddColumn("dbo.AspNetUsers", "City", c => c.Int(nullable: false));}public override void Down() {DropColumn("dbo.AspNetUsers", "City");} }} The Up method describes the changes that have to be made to the schema when the database is upgraded, which in this case means adding a City column to the AspNetUsers table, which is the one that is used to store user records in the ASP.NET Identity database. Up方法描述了在数据库升级时,需要对架构所做的修改,在这个例子中,意味着要在AspNetUsers数据表中添加City数据列,该数据表是ASP.NET Identity数据库用来存储用户记录的。 The final step is to perform the migration. Without starting the application, run the following command in the Package Manager Console: 最后一步是执行迁移。无需启动应用程序,只需在“Package Manager Console(包管理器控制台)”中运行以下命令即可: Update-Database –TargetMigration CityProperty The database schema will be modified, and the code in the Configuration.Seed method will be executed. The existing user accounts will have been preserved and enhanced with a City property (which I set to Paris in the Seed method). 这会修改数据库架构,并执行Configuration.Seed方法中的代码。已有用户账号会被保留,且增强了City属性(我在Seed方法中已将其设置为“Paris”)。 15.2.4 Testing the Migration 15.2.4 测试迁移 To test the effect of the migration, start the application, navigate to the /Home/UserProps URL, and authenticate as one of the Identity users (for example, as Alice with the password MySecret). Once authenticated, you will see the current value of the City property for the user and have the opportunity to change it, as shown in Figure 15-3. 为了测试迁移的效果,启动应用程序,导航到/Home/UserProps URL,并以Identity中的用户(例如Alice,口令MySecret)进行认证。一旦已被认证,便会看到该用户City属性的当前值,并可以对其进行修改,如图15-3所示。 Figure 15-3. Displaying and changing a custom user property 图15-3. 显示和个性自定义用户属性 15.2.5 Defining an Additional Property 15.2.5 定义附加属性 Now that database migrations are set up, I am going to define a further property just to demonstrate how subsequent changes are handled and to show a more useful (and less dangerous) example of using the Configuration.Seed method. Listing 15-8 shows how I added a Country property to the AppUser class. 现在,已经建立了数据库迁移,我打算再定义一个属性,这恰恰演示了如何处理持续不断的修改,也为了演示Configuration.Seed方法更有用(至少无害)的示例。清单15-8显示了我在AppUser类上添加了一个Country属性。 Listing 15-8. Adding Another Property in the AppUserModels.cs File 清单15-8. 在AppUserModels.cs文件中添加另一个属性 using System;using Microsoft.AspNet.Identity.EntityFramework; namespace Users.Models {public enum Cities {LONDON, PARIS, CHICAGO} public enum Countries {NONE, UK, FRANCE, USA}public class AppUser : IdentityUser {public Cities City { get; set; }public Countries Country { get; set; }public void SetCountryFromCity(Cities city) {switch (city) {case Cities.LONDON:Country = Countries.UK;break;case Cities.PARIS:Country = Countries.FRANCE;break;case Cities.CHICAGO:Country = Countries.USA;break;default:Country = Countries.NONE;break;} }} } I have added an enumeration to define the country names and a helper method that selects a country value based on the City property. Listing 15-9 shows the change I made to the Configuration class so that the Seed method sets the Country property based on the City, but only if the value of Country is NONE (which it will be for all users when the database is migrated because the Entity Framework sets enumeration columns to the first value). 我已经添加了一个枚举,它定义了国家名称。还添加了一个辅助器方法,它可以根据City属性选择一个国家。清单15-9显示了对Configuration类所做的修改,以使Seed方法根据City设置Country属性,但只当Country为NONE时才进行设置(在迁移数据库时,所有用户都是NONE,因为Entity Framework会将枚举列设置为枚举的第一个值)。 Listing 15-9. Modifying the Database Seed in the Configuration.cs File 清单15-9. 在Configuration.cs文件中修改数据库种子 using System.Data.Entity.Migrations;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.EntityFramework;using Users.Infrastructure;using Users.Models; namespace Users.Migrations {internal sealed class Configuration: DbMigrationsConfiguration<AppIdentityDbContext> {public Configuration() {AutomaticMigrationsEnabled = true;ContextKey = "Users.Infrastructure.AppIdentityDbContext";}protected override void Seed(AppIdentityDbContext context) {AppUserManager userMgr = new AppUserManager(new UserStore<AppUser>(context));AppRoleManager roleMgr = new AppRoleManager(new RoleStore<AppRole>(context)); string roleName = "Administrators";string userName = "Admin";string password = "MySecret";string email = "admin@example.com";if (!roleMgr.RoleExists(roleName)) {roleMgr.Create(new AppRole(roleName));}AppUser user = userMgr.FindByName(userName);if (user == null) {userMgr.Create(new AppUser { UserName = userName, Email = email },password);user = userMgr.FindByName(userName);}if (!userMgr.IsInRole(user.Id, roleName)) {userMgr.AddToRole(user.Id, roleName);} foreach (AppUser dbUser in userMgr.Users) {if (dbUser.Country == Countries.NONE) {dbUser.SetCountryFromCity(dbUser.City);} }context.SaveChanges();} }} This kind of seeding is more useful in a real project because it will set a value for the Country property only if one has not already been set—subsequent migrations won’t be affected, and user selections won’t be lost. 这种种植在实际项目中会更有用,因为它只会在Country属性未设置时,才会设置Country属性的值——后继的迁移不会受到影响,因此不会失去用户的选择。 1. Adding Application Support 1. 添加应用程序支持 There is no point defining additional user properties if they are not available in the application, so Listing 15-10 shows the change I made to the Views/Home/UserProps.cshtml file to display the value of the Country property. 应用程序中如果没有定义附加属性的地方,则附加属性就无法使用了,因此,清单15-10显示了我对Views/Home/UserProps.cshtml文件的修改,以显示Country属性的值。 Listing 15-10. Displaying an Additional Property in the UserProps.cshtml File 清单15-10. 在UserProps.cshtml文件中显示附加属性 @using Users.Models@model AppUser@{ ViewBag.Title = "UserProps";} <div class="panel panel-primary"><div class="panel-heading">Custom User Properties</div><table class="table table-striped"><tr><th>City</th><td>@Model.City</td></tr> <tr><th>Country</th><td>@Model.Country</td></tr></table></div>@using (Html.BeginForm()) {<div class="form-group"><label>City</label>@Html.DropDownListFor(x => x.City, new SelectList(Enum.GetNames(typeof(Cities))))</div><button class="btn btn-primary" type="submit">Save</button>} Listing 15-11 shows the corresponding change I made to the Home controller to update the Country property when the City value changes. 为了在City值变化时能够更新Country属性,清单15-11显示了我对Home控制器所做的相应修改。 Listing 15-11. Setting Custom Properties in the HomeController.cs File 清单15-11. 在HomeController.cs文件中设置自定义属性 using System.Web.Mvc;using System.Collections.Generic;using System.Web;using System.Security.Principal;using System.Threading.Tasks;using Users.Infrastructure;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.Owin;using Users.Models; namespace Users.Controllers {public class HomeController : Controller {// ...other action methods omitted for brevity...// ...出于简化,这里忽略了其他动作方法... [Authorize]public ActionResult UserProps() {return View(CurrentUser);}[Authorize][HttpPost]public async Task<ActionResult> UserProps(Cities city) {AppUser user = CurrentUser;user.City = city;user.SetCountryFromCity(city);await UserManager.UpdateAsync(user);return View(user);}// ...properties omitted for brevity...// ...出于简化,这里忽略了一些属性...} } 2. Performing the Migration 2. 准备迁移 All that remains is to create and apply a new migration. Enter the following command into the Package Manager Console: 剩下的事情就是创建和运用新的迁移了。在“Package Manager Console(包管理器控制台)”中输入以下命令: Add-Migration CountryProperty This will generate another file in the Migrations folder that contains the instruction to add the Country column. To apply the migration, execute the following command: 这将在Migrations文件夹中生成另一个文件,它含有添加Country数据表列的指令。为了运用迁移,可执行以下命令: Update-Database –TargetMigration CountryProperty The migration will be performed, and the value of the Country property will be set based on the value of the existing City property for each user. You can check the new user property by starting the application and authenticating and navigating to the /Home/UserProps URL, as shown in Figure 15-4. 这将执行迁移,Country属性的值将根据每个用户当前的City属性进行设置。通过启动应用程序,认证并导航到/Home/UserProps URL,便可以查看新的用户属性,如图15-4所示。 Figure 15-4. Creating an additional user property 图15-4. 创建附加用户属性 Tip Although I am focused on the process of upgrading the database, you can also migrate back to a previous version by specifying an earlier migration. Use the –Force argument make changes that cause data loss, such as removing a column. 提示:虽然我们关注了升级数据库的过程,但你也可以回退到以前的版本,只需指定一个早期的迁移即可。使用-Force参数进行修改,会引起数据丢失,例如删除数据表列。 15.3 Working with Claims 15.3 使用声明(Claims) In older user-management systems, such as ASP.NET Membership, the application was assumed to be the authoritative source of all information about the user, essentially treating the application as a closed world and trusting the data that is contained within it. 在旧的用户管理系统中,例如ASP.NET Membership,应用程序被假设成是用户所有信息的权威来源,本质上将应用程序视为是一个封闭的世界,并且只信任其中所包含的数据。 This is such an ingrained approach to software development that it can be hard to recognize that’s what is happening, but you saw an example of the closed-world technique in Chapter 14 when I authenticated users against the credentials stored in the database and granted access based on the roles associated with those credentials. I did the same thing again in this chapter when I added properties to the user class. Every piece of information that I needed to manage user authentication and authorization came from within my application—and that is a perfectly satisfactory approach for many web applications, which is why I demonstrated these techniques in such depth. 这是软件开发的一种根深蒂固的方法,使人很难认识到这到底意味着什么,第14章你已看到了这种封闭世界技术的例子,根据存储在数据库中的凭据来认证用户,并根据与凭据关联在一起的角色来授权访问。本章前述在用户类上添加属性,也做了同样的事情。我管理用户认证与授权所需的每一个数据片段都来自于我的应用程序——而且这是许多Web应用程序都相当满意的一种方法,这也是我如此深入地演示这些技术的原因。 ASP.NET Identity also supports an alternative approach for dealing with users, which works well when the MVC framework application isn’t the sole source of information about users and which can be used to authorize users in more flexible and fluid ways than traditional roles allow. ASP.NET Identity还支持另一种处理用户的办法,当MVC框架的应用程序不是有关用户的唯一信息源时,这种办法会工作得很好,而且能够比传统的角色授权更为灵活且流畅的方式进行授权。 This alternative approach uses claims, and in this section I’ll describe how ASP.NET Identity supports claims-based authorization. Table 15-4 puts claims in context. 这种可选的办法使用了“Claims(声明)”,因此在本小节中,我将描述ASP.NET Identity如何支持“Claims-Based Authorization(基于声明的授权)”。表15-4描述了声明(Claims)的情形。 提示:“Claim”在英文字典中不完全是“声明”的意思,根据本文的描述,感觉把它说成“声明”也不一定合适,所以在之后的译文中基本都写成中英文并用的形式,即“声明(Claims)”。根据表15-4中的声明(Claims)的定义:声明(Claims)是关于用户的一些信息片段。一个用户的信息片段当然有很多,每一个信息片段就是一项声明(Claim),用户的所有信息片段合起来就是该用户的声明(Claims)。请读者注意该单词的单复数形式——译者注 Table 15-4. Putting Claims in Context 表15-4. 声明(Claims)的情形 Question 问题 Answer 答案 What is it? 什么是声明(Claims)? Claims are pieces of information about users that you can use to make authorization decisions. Claims can be obtained from external systems as well as from the local Identity database. 声明(Claims)是关于用户的一些信息片段,可以用它们做出授权决定。声明(Claims)可以从外部系统获取,也可以从本地的Identity数据库获取。 Why should I care? 为何要关心它? Claims can be used to flexibly authorize access to action methods. Unlike conventional roles, claims allow access to be driven by the information that describes the user. 声明(Claims)可以用来对动作方法进行灵活的授权访问。与传统的角色不同,声明(Claims)让访问能够由描述用户的信息进行驱动。 How is it used by the MVC framework? 如何在MVC框架中使用它? This feature isn’t used directly by the MVC framework, but it is integrated into the standard authorization features, such as the Authorize attribute. 这不是直接由MVC框架使用的特性,但它集成到了标准的授权特性之中,例如Authorize注解属性。 Tip you don’t have to use claims in your applications, and as Chapter 14 showed, ASP.NET Identity is perfectly happy providing an application with the authentication and authorization services without any need to understand claims at all. 提示:你在应用程序中不一定要使用声明(Claims),正如第14章所展示的那样,ASP.NET Identity能够为应用程序提供充分的认证与授权服务,而根本不需要理解声明(Claims)。 15.3.1 Understanding Claims 15.3.1 理解声明(Claims) A claim is a piece of information about the user, along with some information about where the information came from. The easiest way to unpack claims is through some practical demonstrations, without which any discussion becomes too abstract to be truly useful. To get started, I added a Claims controller to the example project, the definition of which you can see in Listing 15-12. 一项声明(Claim)是关于用户的一个信息片段(请注意这个英文单词的单复数形式——译者注),并伴有该片段出自何处的某种信息。揭开声明(Claims)含义最容易的方式是做一些实际演示,任何讨论都会过于抽象根本没有真正的用处。为此,我在示例项目中添加了一个Claims控制器,其定义如清单15-12所示。 Listing 15-12. The Contents of the ClaimsController.cs File 清单15-12. ClaimsController.cs文件的内容 using System.Security.Claims;using System.Web;using System.Web.Mvc; namespace Users.Controllers {public class ClaimsController : Controller {[Authorize]public ActionResult Index() {ClaimsIdentity ident = HttpContext.User.Identity as ClaimsIdentity;if (ident == null) {return View("Error", new string[] { "No claims available" });} else {return View(ident.Claims);} }} } Tip You may feel a little lost as I define the code for this example. Don’t worry about the details for the moment—just stick with it until you see the output from the action method and view that I define. More than anything else, that will help put claims into perspective. 提示:你或许会对我为此例定义的代码感到有点失望。此刻对此细节不必着急——只要稍事忍耐,当看到该动作方法和视图的输出便会明白。尤为重要的是,这有助于洞察声明(Claims)。 You can get the claims associated with a user in different ways. One approach is to use the Claims property defined by the user class, but in this example, I have used the HttpContext.User.Identity property to demonstrate the way that ASP.NET Identity is integrated with the rest of the ASP.NET platform. As I explained in Chapter 13, the HttpContext.User.Identity property returns an implementation of the IIdentity interface, which is a ClaimsIdentity object when working using ASP.NET Identity. The ClaimsIdentity class is defined in the System.Security.Claims namespace, and Table 15-5 shows the members it defines that are relevant to this chapter. 可以通过不同的方式获得与用户相关联的声明(Claims)。方法之一就是使用由用户类定义的Claims属性,但在这个例子中,我使用了HttpContext.User.Identity属性,目的是演示ASP.NET Identity与ASP.NET平台集成的方式(请注意这句话所表示的含义:用户类的Claims属性属于ASP.NET Identity,而HttpContext.User.Identity属性则属于ASP.NET平台。由此可见,ASP.NET Identity已经融合到了ASP.NET平台之中——译者注)。正如第13章所解释的那样,HttpContext.User.Identity属性返回IIdentity的接口实现,当使用ASP.NET Identity时,该实现是一个ClaimsIdentity对象。ClaimsIdentity类是在System.Security.Claims命名空间中定义的,表15-5显示了它所定义的与本章有关的成员。 Table 15-5. The Members Defined by the ClaimsIdentity Class 表15-5. ClaimsIdentity类所定义的成员 Name 名称 Description 描述 Claims Returns an enumeration of Claim objects representing the claims for the user. 返回表示用户声明(Claims)的Claim对象枚举 AddClaim(claim) Adds a claim to the user identity. 给用户添加一个声明(Claim) AddClaims(claims) Adds an enumeration of Claim objects to the user identity. 给用户添加Claim对象的枚举。 HasClaim(predicate) Returns true if the user identity contains a claim that matches the specified predicate. See the “Applying Claims” section for an example predicate. 如果用户含有与指定谓词匹配的声明(Claim)时,返回true。参见“运用声明(Claims)”中的示例谓词 RemoveClaim(claim) Removes a claim from the user identity. 删除用户的声明(Claim)。 Other members are available, but the ones in the table are those that are used most often in web applications, for reason that will become obvious as I demonstrate how claims fit into the wider ASP.NET platform. 还有一些可用的其它成员,但表中的这些是在Web应用程序中最常用的,随着我演示如何将声明(Claims)融入更宽泛的ASP.NET平台,它们为什么最常用就很显然了。 In Listing 15-12, I cast the IIdentity implementation to the ClaimsIdentity type and pass the enumeration of Claim objects returned by the ClaimsIdentity.Claims property to the View method. A Claim object represents a single piece of data about the user, and the Claim class defines the properties shown in Table 15-6. 在清单15-12中,我将IIdentity实现转换成了ClaimsIdentity类型,并且给View方法传递了ClaimsIdentity.Claims属性所返回的Claim对象的枚举。Claim对象所示表示的是关于用户的一个单一的数据片段,Claim类定义的属性如表15-6所示。 Table 15-6. The Properties Defined by the Claim Class 表15-6. Claim类定义的属性 Name 名称 Description 描述 Issuer Returns the name of the system that provided the claim 返回提供声明(Claim)的系统名称 Subject Returns the ClaimsIdentity object for the user who the claim refers to 返回声明(Claim)所指用户的ClaimsIdentity对象 Type Returns the type of information that the claim represents 返回声明(Claim)所表示的信息类型 Value Returns the piece of information that the claim represents 返回声明(Claim)所表示的信息片段 Listing 15-13 shows the contents of the Index.cshtml file that I created in the Views/Claims folder and that is rendered by the Index action of the Claims controller. The view adds a row to a table for each claim about the user. 清单15-13显示了我在Views/Claims文件夹中创建的Index.cshtml文件的内容,它由Claims控制器中的Index动作方法进行渲染。该视图为用户的每项声明(Claim)添加了一个表格行。 Listing 15-13. The Contents of the Index.cshtml File in the Views/Claims Folder 清单15-13. Views/Claims文件夹中Index.cshtml文件的内容 @using System.Security.Claims@using Users.Infrastructure@model IEnumerable<Claim>@{ ViewBag.Title = "Claims"; }<div class="panel panel-primary"><div class="panel-heading">Claims</div><table class="table table-striped"><tr><th>Subject</th><th>Issuer</th><th>Type</th><th>Value</th></tr>@foreach (Claim claim in Model.OrderBy(x => x.Type)) {<tr><td>@claim.Subject.Name</td><td>@claim.Issuer</td><td>@Html.ClaimType(claim.Type)</td><td>@claim.Value</td></tr>}</table></div> The value of the Claim.Type property is a URI for a Microsoft schema, which isn’t especially useful. The popular schemas are used as the values for fields in the System.Security.Claims.ClaimTypes class, so to make the output from the Index.cshtml view easier to read, I added an HTML helper to the IdentityHelpers.cs file, as shown in Listing 15-14. It is this helper that I use in the Index.cshtml file to format the value of the Claim.Type property. Claim.Type属性的值是一个微软模式(Microsoft Schema)的URI(统一资源标识符),这是特别有用的。System.Security.Claims.ClaimTypes类中字段的值使用的是流行模式(Popular Schema),因此为了使Index.cshtml视图的输出更易于阅读,我在IdentityHelpers.cs文件中添加了一个HTML辅助器,如清单15-14所示。Index.cshtml文件正是使用这个辅助器格式化了Claim.Type属性的值。 Listing 15-14. Adding a Helper to the IdentityHelpers.cs File 清单15-14. 在IdentityHelpers.cs文件中添加辅助器 using System.Web;using System.Web.Mvc;using Microsoft.AspNet.Identity.Owin;using System;using System.Linq;using System.Reflection;using System.Security.Claims;namespace Users.Infrastructure {public static class IdentityHelpers {public static MvcHtmlString GetUserName(this HtmlHelper html, string id) {AppUserManager mgr= HttpContext.Current.GetOwinContext().GetUserManager<AppUserManager>();return new MvcHtmlString(mgr.FindByIdAsync(id).Result.UserName);} public static MvcHtmlString ClaimType(this HtmlHelper html, string claimType) {FieldInfo[] fields = typeof(ClaimTypes).GetFields();foreach (FieldInfo field in fields) {if (field.GetValue(null).ToString() == claimType) {return new MvcHtmlString(field.Name);} }return new MvcHtmlString(string.Format("{0}",claimType.Split('/', '.').Last()));} }} Note The helper method isn’t at all efficient because it reflects on the fields of the ClaimType class for each claim that is displayed, but it is sufficient for my purposes in this chapter. You won’t often need to display the claim type in real applications. 注:该辅助器并非十分有效,因为它只是针对每个要显示的声明(Claim)映射出ClaimType类的字段,但对我要的目的已经足够了。在实际项目中不会经常需要显示声明(Claim)的类型。 To see why I have created a controller that uses claims without really explaining what they are, start the application, authenticate as the user Alice (with the password MySecret), and request the /Claims/Index URL. Figure 15-5 shows the content that is generated. 为了弄明白我为何要先创建一个使用声明(Claims)的控制器,而没有真正解释声明(Claims)是什么的原因,可以启动应用程序,以用户Alice进行认证(其口令是MySecret),并请求/Claims/Index URL。图15-5显示了生成的内容。 Figure 15-5. The output from the Index action of the Claims controller 图15-5. Claims控制器中Index动作的输出 It can be hard to make out the detail in the figure, so I have reproduced the content in Table 15-7. 这可能还难以认识到此图的细节,为此我在表15-7中重列了其内容。 Table 15-7. The Data Shown in Figure 15-5 表15-7. 图15-5中显示的数据 Subject(科目) Issuer(发行者) Type(类型) Value(值) Alice LOCAL AUTHORITY SecurityStamp Unique ID Alice LOCAL AUTHORITY IdentityProvider ASP.NET Identity Alice LOCAL AUTHORITY Role Employees Alice LOCAL AUTHORITY Role Users Alice LOCAL AUTHORITY Name Alice Alice LOCAL AUTHORITY NameIdentifier Alice’s user ID The table shows the most important aspect of claims, which is that I have already been using them when I implemented the traditional authentication and authorization features in Chapter 14. You can see that some of the claims relate to user identity (the Name claim is Alice, and the NameIdentifier claim is Alice’s unique user ID in my ASP.NET Identity database). 此表展示了声明(Claims)最重要的方面,这些是我在第14章中实现传统的认证和授权特性时,一直在使用的信息。可以看出,有些声明(Claims)与用户标识有关(Name声明是Alice,NameIdentifier声明是Alice在ASP.NET Identity数据库中的唯一用户ID号)。 Other claims show membership of roles—there are two Role claims in the table, reflecting the fact that Alice is assigned to both the Users and Employees roles. There is also a claim about how Alice has been authenticated: The IdentityProvider is set to ASP.NET Identity. 其他声明(Claims)显示了角色成员——表中有两个Role声明(Claim),体现出Alice被赋予了Users和Employees两个角色这一事实。还有一个是Alice已被认证的声明(Claim):IdentityProvider被设置到了ASP.NET Identity。 The difference when this information is expressed as a set of claims is that you can determine where the data came from. The Issuer property for all the claims shown in the table is set to LOCAL AUTHORITY, which indicates that the user’s identity has been established by the application. 当这种信息被表示成一组声明(Claims)时的差别是,你能够确定这些数据是从哪里来的。表中所显示的所有声明的Issuer属性(发布者)都被设置到了LOACL AUTHORITY(本地授权),这说明该用户的标识是由应用程序建立的。 So, now that you have seen some example claims, I can more easily describe what a claim is. A claim is any piece of information about a user that is available to the application, including the user’s identity and role memberships. And, as you have seen, the information I have been defining about my users in earlier chapters is automatically made available as claims by ASP.NET Identity. 因此,现在你已经看到了一些声明(Claims)示例,我可以更容易地描述声明(Claim)是什么了。一项声明(Claim)是可用于应用程序中的有关用户的一个信息片段,包括用户的标识以及角色成员等。而且,正如你所看到的,我在前几章定义的关于用户的信息,被ASP.NET Identity自动地作为声明(Claims)了。 15.3.2 Creating and Using Claims 15.3.2 创建和使用声明(Claims) Claims are interesting for two reasons. The first reason is that an application can obtain claims from multiple sources, rather than just relying on a local database for information about the user. You will see a real example of this when I show you how to authenticate users through a third-party system in the “Using Third-Party Authentication” section, but for the moment I am going to add a class to the example project that simulates a system that provides claims information. Listing 15-15 shows the contents of the LocationClaimsProvider.cs file that I added to the Infrastructure folder. 声明(Claims)比较有意思的原因有两个。第一个原因是应用程序可以从多个来源获取声明(Claims),而不是只能依靠本地数据库关于用户的信息。你将会看到一个实际的示例,在“使用第三方认证”小节中,将演示如何通过第三方系统来认证用户。不过,此刻我只打算在示例项目中添加一个类,用以模拟一个提供声明(Claims)信息的系统。清单15-15显示了我添加到Infrastructure文件夹中LocationClaimsProvider.cs文件的内容。 Listing 15-15. The Contents of the LocationClaimsProvider.cs File 清单15-15. LocationClaimsProvider.cs文件的内容 using System.Collections.Generic;using System.Security.Claims; namespace Users.Infrastructure {public static class LocationClaimsProvider {public static IEnumerable<Claim> GetClaims(ClaimsIdentity user) {List<Claim> claims = new List<Claim>();if (user.Name.ToLower() == "alice") {claims.Add(CreateClaim(ClaimTypes.PostalCode, "DC 20500"));claims.Add(CreateClaim(ClaimTypes.StateOrProvince, "DC"));} else {claims.Add(CreateClaim(ClaimTypes.PostalCode, "NY 10036"));claims.Add(CreateClaim(ClaimTypes.StateOrProvince, "NY"));}return claims;}private static Claim CreateClaim(string type, string value) {return new Claim(type, value, ClaimValueTypes.String, "RemoteClaims");} }} The GetClaims method takes a ClaimsIdentity argument and uses the Name property to create claims about the user’s ZIP code and state. This class allows me to simulate a system such as a central HR database, which would be the authoritative source of location information about staff, for example. GetClaims方法以ClaimsIdentity为参数,并使用Name属性创建了关于用户ZIP码(邮政编码)和州府的声明(Claims)。上述这个类使我能够模拟一个诸如中心化的HR数据库(人力资源数据库)之类的系统,它可能会成为全体职员的地点信息的权威数据源。 Claims are associated with the user’s identity during the authentication process, and Listing 15-16 shows the changes I made to the Login action method of the Account controller to call the LocationClaimsProvider class. 在认证过程期间,声明(Claims)是与用户标识关联在一起的,清单15-16显示了我对Account控制器中Login动作方法所做的修改,以便调用LocationClaimsProvider类。 Listing 15-16. Associating Claims with a User in the AccountController.cs File 清单15-16. AccountController.cs文件中用户用声明的关联 ...[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie); ident.AddClaims(LocationClaimsProvider.GetClaims(ident));AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);}... You can see the effect of the location claims by starting the application, authenticating as a user, and requesting the /Claim/Index URL. Figure 15-6 shows the claims for Alice. You may have to sign out and sign back in again to see the change. 为了看看这个地点声明(Claims)的效果,可以启动应用程序,以一个用户进行认证,并请求/Claim/Index URL。图15-6显示了Alice的声明(Claims)。你可能需要退出,然后再次登录才会看到发生的变化。 Figure 15-6. Defining additional claims for users 图15-6. 定义用户的附加声明 Obtaining claims from multiple locations means that the application doesn’t have to duplicate data that is held elsewhere and allows integration of data from external parties. The Claim.Issuer property tells you where a claim originated from, which helps you judge how accurate the data is likely to be and how much weight you should give the data in your application. Location data obtained from a central HR database is likely to be more accurate and trustworthy than data obtained from an external mailing list provider, for example. 从多个地点获取声明(Claims)意味着应用程序不必复制其他地方保持的数据,并且能够与外部的数据集成。Claim.Issuer属性(图15-6中的Issuer数据列——译者注)能够告诉你一个声明(Claim)的发源地,这有助于让你判断数据的精确程度,也有助于让你决定这类数据在应用程序中的权重。例如,从中心化的HR数据库获取的地点数据可能要比外部邮件列表提供器获取的数据更为精确和可信。 1. Applying Claims 1. 运用声明(Claims) The second reason that claims are interesting is that you can use them to manage user access to your application more flexibly than with standard roles. The problem with roles is that they are static, and once a user has been assigned to a role, the user remains a member until explicitly removed. This is, for example, how long-term employees of big corporations end up with incredible access to internal systems: They are assigned the roles they require for each new job they get, but the old roles are rarely removed. (The unexpectedly broad systems access sometimes becomes apparent during the investigation into how someone was able to ship the contents of the warehouse to their home address—true story.) 声明(Claims)有意思的第二个原因是,你可以用它们来管理用户对应用程序的访问,这要比标准的角色管理更为灵活。角色的问题在于它们是静态的,而且一旦用户已经被赋予了一个角色,该用户便是一个成员,直到明确地删除为止。例如,这意味着大公司的长期雇员,对内部系统的访问会十分惊人:他们每次在获得新工作时,都会赋予所需的角色,但旧角色很少被删除。(在调查某人为何能够将仓库里的东西发往他的家庭地址过程中发现,有时会出现异常宽泛的系统访问——真实的故事) Claims can be used to authorize users based directly on the information that is known about them, which ensures that the authorization changes when the data changes. The simplest way to do this is to generate Role claims based on user data that are then used by controllers to restrict access to action methods. Listing 15-17 shows the contents of the ClaimsRoles.cs file that I added to the Infrastructure. 声明(Claims)可以直接根据用户已知的信息对用户进行授权,这能够保证当数据发生变化时,授权也随之而变。此事最简单的做法是根据用户数据来生成Role声明(Claim),然后由控制器用来限制对动作方法的访问。清单15-17显示了我添加到Infrastructure中的ClaimsRoles.cs文件的内容。 Listing 15-17. The Contents of the ClaimsRoles.cs File 清单15-17. ClaimsRoles.cs文件的内容 using System.Collections.Generic;using System.Security.Claims; namespace Users.Infrastructure {public class ClaimsRoles {public static IEnumerable<Claim> CreateRolesFromClaims(ClaimsIdentity user) {List<Claim> claims = new List<Claim>();if (user.HasClaim(x => x.Type == ClaimTypes.StateOrProvince&& x.Issuer == "RemoteClaims" && x.Value == "DC")&& user.HasClaim(x => x.Type == ClaimTypes.Role&& x.Value == "Employees")) {claims.Add(new Claim(ClaimTypes.Role, "DCStaff"));}return claims;} }} The gnarly looking CreateRolesFromClaims method uses lambda expressions to determine whether the user has a StateOrProvince claim from the RemoteClaims issuer with a value of DC and a Role claim with a value of Employees. If the user has both claims, then a Role claim is returned for the DCStaff role. Listing 15-18 shows how I call the CreateRolesFromClaims method from the Login action in the Account controller. CreateRolesFromClaims是一个粗糙的考察方法,它使用了Lambda表达式,以检查用户是否具有StateOrProvince声明(Claim),该声明来自于RemoteClaims发行者(Issuer),值为DC。也检查用户是否具有Role声明(Claim),其值为Employees。如果用户这两个声明都有,那么便返回一个DCStaff角色的Role声明。清单15-18显示了如何在Account控制器中的Login动作中调用CreateRolesFromClaims方法。 Listing 15-18. Generating Roles Based on Claims in the AccountController.cs File 清单15-18. 在AccountController.cs中根据声明生成角色 ...[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(LocationClaimsProvider.GetClaims(ident)); ident.AddClaims(ClaimsRoles.CreateRolesFromClaims(ident));AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);}... I can then restrict access to an action method based on membership of the DCStaff role. Listing 15-19 shows a new action method I added to the Claims controller to which I have applied the Authorize attribute. 然后我可以根据DCStaff角色的成员,来限制对一个动作方法的访问。清单15-19显示了在Claims控制器中添加的一个新的动作方法,在该方法上已经运用了Authorize注解属性。 Listing 15-19. Adding a New Action Method to the ClaimsController.cs File 清单15-19. 在ClaimsController.cs文件中添加一个新的动作方法 using System.Security.Claims;using System.Web;using System.Web.Mvc;namespace Users.Controllers {public class ClaimsController : Controller {[Authorize]public ActionResult Index() {ClaimsIdentity ident = HttpContext.User.Identity as ClaimsIdentity;if (ident == null) {return View("Error", new string[] { "No claims available" });} else {return View(ident.Claims);} } [Authorize(Roles="DCStaff")]public string OtherAction() {return "This is the protected action";} }} Users will be able to access OtherAction only if their claims grant them membership to the DCStaff role. Membership of this role is generated dynamically, so a change to the user’s employment status or location information will change their authorization level. 只要用户的声明(Claims)承认他们是DCStaff角色的成员,那么他们便能访问OtherAction动作。该角色的成员是动态生成的,因此,若是用户的雇用状态或地点信息发生变化,也会改变他们的授权等级。 提示:请读者从这个例子中吸取其中的思想精髓。对于读物的理解程度,仁者见仁,智者见智,能领悟多少,全凭各人,译者感觉这里的思想有无数的可能。举例说明:(1)可以根据用户的身份进行授权,比如学生在校时是“学生”,毕业后便是“校友”;(2)可以根据用户所处的部门进行授权,人事部用户属于人事团队,销售部用户属于销售团队,各团队有其自己的应用;(3)下一小节的示例是根据用户的地点授权。简言之:一方面用户的各种声明(Claim)都可以用来进行授权;另一方面用户的声明(Claim)又是可以自定义的。于是可能的运用就无法估计了。总之一句话,这种基于声明的授权(Claims-Based Authorization)有无限可能!要是没有我这里的提示,是否所有读者在此处都会有所体会?——译者注 15.3.3 Authorizing Access Using Claims 15.3.3 使用声明(Claims)授权访问 The previous example is an effective demonstration of how claims can be used to keep authorizations fresh and accurate, but it is a little indirect because I generate roles based on claims data and then enforce my authorization policy based on the membership of that role. A more direct and flexible approach is to enforce authorization directly by creating a custom authorization filter attribute. Listing 15-20 shows the contents of the ClaimsAccessAttribute.cs file, which I added to the Infrastructure folder and used to create such a filter. 前面的示例有效地演示了如何用声明(Claims)来保持新鲜和准确的授权,但有点不太直接,因为我要根据声明(Claims)数据来生成了角色,然后强制我的授权策略基于角色成员。一个更直接且灵活的办法是直接强制授权,其做法是创建一个自定义的授权过滤器注解属性。清单15-20演示了ClaimsAccessAttribute.cs文件的内容,我将它添加在Infrastructure文件夹中,并用它创建了这种过滤器。 Listing 15-20. The Contents of the ClaimsAccessAttribute.cs File 清单15-20. ClaimsAccessAttribute.cs文件的内容 using System.Security.Claims;using System.Web;using System.Web.Mvc; namespace Users.Infrastructure {public class ClaimsAccessAttribute : AuthorizeAttribute {public string Issuer { get; set; }public string ClaimType { get; set; }public string Value { get; set; }protected override bool AuthorizeCore(HttpContextBase context) {return context.User.Identity.IsAuthenticated&& context.User.Identity is ClaimsIdentity&& ((ClaimsIdentity)context.User.Identity).HasClaim(x =>x.Issuer == Issuer && x.Type == ClaimType && x.Value == Value);} }} The attribute I have defined is derived from the AuthorizeAttribute class, which makes it easy to create custom authorization policies in MVC framework applications by overriding the AuthorizeCore method. My implementation grants access if the user is authenticated, the IIdentity implementation is an instance of ClaimsIdentity, and the user has a claim with the issuer, type, and value matching the class properties. Listing 15-21 shows how I applied the attribute to the Claims controller to authorize access to the OtherAction method based on one of the location claims created by the LocationClaimsProvider class. 我所定义的这个注解属性派生于AuthorizeAttribute类,通过重写AuthorizeCore方法,很容易在MVC框架应用程序中创建自定义的授权策略。在这个实现中,若用户是已认证的、其IIdentity实现是一个ClaimsIdentity实例,而且该用户有一个带有issuer、type以及value的声明(Claim),它们与这个类的属性是匹配的,则该用户便是允许访问的。清单15-21显示了如何将这个注解属性运用于Claims控制器,以便根据LocationClaimsProvider类创建的地点声明(Claim),对OtherAction方法进行授权访问。 Listing 15-21. Performing Authorization on Claims in the ClaimsController.cs File 清单15-21. 在ClaimsController.cs文件中执行基于声明的授权 using System.Security.Claims;using System.Web;using System.Web.Mvc;using Users.Infrastructure;namespace Users.Controllers {public class ClaimsController : Controller {[Authorize]public ActionResult Index() {ClaimsIdentity ident = HttpContext.User.Identity as ClaimsIdentity;if (ident == null) {return View("Error", new string[] { "No claims available" });} else {return View(ident.Claims);} } [ClaimsAccess(Issuer="RemoteClaims", ClaimType=ClaimTypes.PostalCode,Value="DC 20500")]public string OtherAction() {return "This is the protected action";} }} My authorization filter ensures that only users whose location claims specify a ZIP code of DC 20500 can invoke the OtherAction method. 这个授权过滤器能够确保只有地点声明(Claim)的邮编为DC 20500的用户才能请求OtherAction方法。 15.4 Using Third-Party Authentication 15.4 使用第三方认证 One of the benefits of a claims-based system such as ASP.NET Identity is that any of the claims can come from an external system, even those that identify the user to the application. This means that other systems can authenticate users on behalf of the application, and ASP.NET Identity builds on this idea to make it simple and easy to add support for authenticating users through third parties such as Microsoft, Google, Facebook, and Twitter. 基于声明的系统,如ASP.NET Identity,的好处之一是任何声明都可以来自于外部系统,即使是将用户标识到应用程序的那些声明。这意味着其他系统可以代表应用程序来认证用户,而ASP.NET Identity就建立在这样的思想之上,使之能够简单而方便地添加第三方认证用户的支持,如微软、Google、Facebook、Twitter等。 There are some substantial benefits of using third-party authentication: Many users will already have an account, users can elect to use two-factor authentication, and you don’t have to manage user credentials in the application. In the sections that follow, I’ll show you how to set up and use third-party authentication for Google users, which Table 15-8 puts into context. 使用第三方认证有一些实际的好处:许多用户已经有了账号、用户可以选择使用双因子认证、你不必在应用程序中管理用户凭据等等。在以下小节中,我将演示如何为Google用户建立并使用第三方认证,表15-8描述了事情的情形。 Table 15-8. Putting Third-Party Authentication in Context 表15-8. 第三方认证情形 Question 问题 Answer 回答 What is it? 什么是第三方认证? Authenticating with third parties lets you take advantage of the popularity of companies such as Google and Facebook. 第三方认证使你能够利用流行公司,如Google和Facebook,的优势。 Why should I care? 为何要关心它? Users don’t like having to remember passwords for many different sites. Using a provider with large-scale adoption can make your application more appealing to users of the provider’s services. 用户不喜欢记住许多不同网站的口令。使用大范围适应的提供器可使你的应用程序更吸引有提供器服务的用户。 How is it used by the MVC framework? 如何在MVC框架中使用它? This feature isn’t used directly by the MVC framework. 这不是一个直接由MVC框架使用的特性。 Note The reason I have chosen to demonstrate Google authentication is that it is the only option that doesn’t require me to register my application with the authentication service. You can get details of the registration processes required at http://bit.ly/1cqLTrE. 提示:我选择演示Google认证的原因是,它是唯一不需要在其认证服务中注册我应用程序的公司。有关认证服务注册过程的细节,请参阅http://bit.ly/1cqLTrE。 15.4.1 Enabling Google Authentication 15.4.1 启用Google认证 ASP.NET Identity comes with built-in support for authenticating users through their Microsoft, Google, Facebook, and Twitter accounts as well more general support for any authentication service that supports OAuth. The first step is to add the NuGet package that includes the Google-specific additions for ASP.NET Identity. Enter the following command into the Package Manager Console: ASP.NET Identity带有通过Microsoft、Google、Facebook以及Twitter账号认证用户的内建支持,并且对于支持OAuth的认证服务具有更普遍的支持。第一个步骤是添加NuGet包,包中含有用于ASP.NET Identity的Google专用附件。请在“Package Manager Console(包管理器控制台)”中输入以下命令: Install-Package Microsoft.Owin.Security.Google -version 2.0.2 There are NuGet packages for each of the services that ASP.NET Identity supports, as described in Table 15-9. 对于ASP.NET Identity支持的每一种服务都有相应的NuGet包,如表15-9所示。 Table 15-9. The NuGet Authenticaton Packages 表15-9. NuGet认证包 Name 名称 Description 描述 Microsoft.Owin.Security.Google Authenticates users with Google accounts 用Google账号认证用户 Microsoft.Owin.Security.Facebook Authenticates users with Facebook accounts 用Facebook账号认证用户 Microsoft.Owin.Security.Twitter Authenticates users with Twitter accounts 用Twitter账号认证用户 Microsoft.Owin.Security.MicrosoftAccount Authenticates users with Microsoft accounts 用Microsoft账号认证用户 Microsoft.Owin.Security.OAuth Authenticates users against any OAuth 2.0 service 根据任一OAuth 2.0服务认证用户 Once the package is installed, I enable support for the authentication service in the OWIN startup class, which is defined in the App_Start/IdentityConfig.cs file in the example project. Listing 15-22 shows the change that I have made. 一旦安装了这个包,便可以在OWIN启动类中启用此项认证服务的支持,启动类的定义在示例项目的App_Start/IdentityConfig.cs文件中。清单15-22显示了所做的修改。 Listing 15-22. Enabling Google Authentication in the IdentityConfig.cs File 清单15-22. 在IdentityConfig.cs文件中启用Google认证 using Microsoft.AspNet.Identity;using Microsoft.Owin;using Microsoft.Owin.Security.Cookies;using Owin;using Users.Infrastructure;using Microsoft.Owin.Security.Google;namespace Users {public class IdentityConfig {public void Configuration(IAppBuilder app) {app.CreatePerOwinContext<AppIdentityDbContext>(AppIdentityDbContext.Create);app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);app.CreatePerOwinContext<AppRoleManager>(AppRoleManager.Create); app.UseCookieAuthentication(new CookieAuthenticationOptions {AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,LoginPath = new PathString("/Account/Login"),}); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);app.UseGoogleAuthentication();} }} Each of the packages that I listed in Table 15-9 contains an extension method that enables the corresponding service. The extension method for the Google service is called UseGoogleAuthentication, and it is called on the IAppBuilder implementation that is passed to the Configuration method. 表15-9所列的每个包都含有启用相应服务的扩展方法。用于Google服务的扩展方法名称为UseGoogleAuthentication,它通过传递给Configuration方法的IAppBuilder实现进行调用。 Next I added a button to the Views/Account/Login.cshtml file, which allows users to log in via Google. You can see the change in Listing 15-23. 下一步骤是在Views/Account/Login.cshtml文件中添加一个按钮,让用户能够通过Google进行登录。所做的修改如清单15-23所示。 Listing 15-23. Adding a Google Login Button to the Login.cshtml File 清单15-23. 在Login.cshtml文件中添加Google登录按钮 @model Users.Models.LoginModel@{ ViewBag.Title = "Login";}<h2>Log In</h2> @Html.ValidationSummary()@using (Html.BeginForm()) {@Html.AntiForgeryToken();<input type="hidden" name="returnUrl" value="@ViewBag.returnUrl" /><div class="form-group"><label>Name</label>@Html.TextBoxFor(x => x.Name, new { @class = "form-control" })</div><div class="form-group"><label>Password</label>@Html.PasswordFor(x => x.Password, new { @class = "form-control" })</div><button class="btn btn-primary" type="submit">Log In</button>}@using (Html.BeginForm("GoogleLogin", "Account")) {<input type="hidden" name="returnUrl" value="@ViewBag.returnUrl" /><button class="btn btn-primary" type="submit">Log In via Google</button>} The new button submits a form that targets the GoogleLogin action on the Account controller. You can see this method—and the other changes I made the controller—in Listing 15-24. 新按钮递交一个表单,目标是Account控制器中的GoogleLogin动作。可从清单15-24中看到该方法,以及在控制器中所做的其他修改。 Listing 15-24. Adding Support for Google Authentication to the AccountController.cs File 清单15-24. 在AccountController.cs文件中添加Google认证支持 using System.Threading.Tasks;using System.Web.Mvc;using Users.Models;using Microsoft.Owin.Security;using System.Security.Claims;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.Owin;using Users.Infrastructure;using System.Web; namespace Users.Controllers {[Authorize]public class AccountController : Controller {[AllowAnonymous]public ActionResult Login(string returnUrl) {if (HttpContext.User.Identity.IsAuthenticated) {return View("Error", new string[] { "Access Denied" });}ViewBag.returnUrl = returnUrl;return View();}[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie); ident.AddClaims(LocationClaimsProvider.GetClaims(ident));ident.AddClaims(ClaimsRoles.CreateRolesFromClaims(ident)); AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);} [HttpPost][AllowAnonymous]public ActionResult GoogleLogin(string returnUrl) {var properties = new AuthenticationProperties {RedirectUri = Url.Action("GoogleLoginCallback",new { returnUrl = returnUrl})};HttpContext.GetOwinContext().Authentication.Challenge(properties, "Google");return new HttpUnauthorizedResult();}[AllowAnonymous]public async Task<ActionResult> GoogleLoginCallback(string returnUrl) {ExternalLoginInfo loginInfo = await AuthManager.GetExternalLoginInfoAsync();AppUser user = await UserManager.FindAsync(loginInfo.Login);if (user == null) {user = new AppUser {Email = loginInfo.Email,UserName = loginInfo.DefaultUserName,City = Cities.LONDON, Country = Countries.UK};IdentityResult result = await UserManager.CreateAsync(user);if (!result.Succeeded) {return View("Error", result.Errors);} else {result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);if (!result.Succeeded) {return View("Error", result.Errors);} }}ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(loginInfo.ExternalIdentity.Claims);AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false }, ident);return Redirect(returnUrl ?? "/");}[Authorize]public ActionResult Logout() {AuthManager.SignOut();return RedirectToAction("Index", "Home");}private IAuthenticationManager AuthManager {get {return HttpContext.GetOwinContext().Authentication;} }private AppUserManager UserManager {get {return HttpContext.GetOwinContext().GetUserManager<AppUserManager>();} }} } The GoogleLogin method creates an instance of the AuthenticationProperties class and sets the RedirectUri property to a URL that targets the GoogleLoginCallback action in the same controller. The next part is a magic phrase that causes ASP.NET Identity to respond to an unauthorized error by redirecting the user to the Google authentication page, rather than the one defined by the application: GoogleLogin方法创建了AuthenticationProperties类的一个实例,并为RedirectUri属性设置了一个URL,其目标为同一控制器中的GoogleLoginCallback动作。下一个部分是一个神奇阶段,通过将用户重定向到Google认证页面,而不是应用程序所定义的认证页面,让ASP.NET Identity对未授权的错误进行响应: ...HttpContext.GetOwinContext().Authentication.Challenge(properties, "Google");return new HttpUnauthorizedResult();... This means that when the user clicks the Log In via Google button, their browser is redirected to the Google authentication service and then redirected back to the GoogleLoginCallback action method once they are authenticated. 这意味着,当用户通过点击Google按钮进行登录时,浏览器被重定向到Google的认证服务,一旦在那里认证之后,便被重定向回GoogleLoginCallback动作方法。 I get details of the external login by calling the GetExternalLoginInfoAsync of the IAuthenticationManager implementation, like this: 我通过调用IAuthenticationManager实现的GetExternalLoginInfoAsync方法,我获得了外部登录的细节,如下所示: ...ExternalLoginInfo loginInfo = await AuthManager.GetExternalLoginInfoAsync();... The ExternalLoginInfo class defines the properties shown in Table 15-10. ExternalLoginInfo类定义的属性如表15-10所示: Table 15-10. The Properties Defined by the ExternalLoginInfo Class 表15-10. ExternalLoginInfo类所定义的属性 Name 名称 Description 描述 DefaultUserName Returns the username 返回用户名 Email Returns the e-mail address 返回E-mail地址 ExternalIdentity Returns a ClaimsIdentity that identities the user 返回标识该用户的ClaimsIdentity Login Returns a UserLoginInfo that describes the external login 返回描述外部登录的UserLoginInfo I use the FindAsync method defined by the user manager class to locate the user based on the value of the ExternalLoginInfo.Login property, which returns an AppUser object if the user has been authenticated with the application before: 我使用了由用户管理器类所定义的FindAsync方法,以便根据ExternalLoginInfo.Login属性的值对用户进行定位,如果用户之前在应用程序中已经认证,该属性会返回一个AppUser对象: ...AppUser user = await UserManager.FindAsync(loginInfo.Login);... If the FindAsync method doesn’t return an AppUser object, then I know that this is the first time that this user has logged into the application, so I create a new AppUser object, populate it with values, and save it to the database. I also save details of how the user logged in so that I can find them next time: 如果FindAsync方法返回的不是AppUser对象,那么我便知道这是用户首次登录应用程序,于是便创建了一个新的AppUser对象,填充该对象的值,并将其保存到数据库。我还保存了用户如何登录的细节,以便下次能够找到他们: ...result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);... All that remains is to generate an identity the user, copy the claims provided by Google, and create an authentication cookie so that the application knows the user has been authenticated: 剩下的事情只是生成该用户的标识了,拷贝Google提供的声明(Claims),并创建一个认证Cookie,以使应用程序知道此用户已认证: ...ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(loginInfo.ExternalIdentity.Claims);AuthManager.SignIn(new AuthenticationProperties { IsPersistent = false }, ident);... 15.4.2 Testing Google Authentication 15.4.2 测试Google认证 There is one further change that I need to make before I can test Google authentication: I need to change the account verification I set up in Chapter 13 because it prevents accounts from being created with e-mail addresses that are not within the example.com domain. Listing 15-25 shows how I removed the verification from the AppUserManager class. 在测试Google认证之前还需要一处修改:需要修改第13章所建立的账号验证,因为它不允许example.com域之外的E-mail地址创建账号。清单15-25显示了如何在AppUserManager类中删除这种验证。 Listing 15-25. Disabling Account Validation in the AppUserManager.cs File 清单15-25. 在AppUserManager.cs文件中取消账号验证 using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.EntityFramework;using Microsoft.AspNet.Identity.Owin;using Microsoft.Owin;using Users.Models; namespace Users.Infrastructure {public class AppUserManager : UserManager<AppUser> {public AppUserManager(IUserStore<AppUser> store): base(store) {}public static AppUserManager Create(IdentityFactoryOptions<AppUserManager> options,IOwinContext context) {AppIdentityDbContext db = context.Get<AppIdentityDbContext>();AppUserManager manager = new AppUserManager(new UserStore<AppUser>(db)); manager.PasswordValidator = new CustomPasswordValidator {RequiredLength = 6,RequireNonLetterOrDigit = false,RequireDigit = false,RequireLowercase = true,RequireUppercase = true}; //manager.UserValidator = new CustomUserValidator(manager) {// AllowOnlyAlphanumericUserNames = true,// RequireUniqueEmail = true//};return manager;} }} Tip you can use validation for externally authenticated accounts, but I am just going to disable the feature for simplicity. 提示:也可以使用外部已认证账号的验证,但这里出于简化,取消了这一特性。 To test authentication, start the application, click the Log In via Google button, and provide the credentials for a valid Google account. When you have completed the authentication process, your browser will be redirected back to the application. If you navigate to the /Claims/Index URL, you will be able to see how claims from the Google system have been added to the user’s identity, as shown in Figure 15-7. 为了测试认证,启动应用程序,通过点击“Log In via Google(通过Google登录)”按钮,并提供有效的Google账号凭据。当你完成了认证过程时,浏览器将被重定向回应用程序。如果导航到/Claims/Index URL,便能够看到来自Google系统的声明(Claims),已被添加到用户的标识中了,如图15-7所示。 Figure 15-7. Claims from Google 图15-7. 来自Google的声明(Claims) 15.5 Summary 15.5 小结 In this chapter, I showed you some of the advanced features that ASP.NET Identity supports. I demonstrated the use of custom user properties and how to use database migrations to preserve data when you upgrade the schema to support them. I explained how claims work and how they can be used to create more flexible ways of authorizing users. I finished the chapter by showing you how to authenticate users via Google, which builds on the ideas behind the use of claims. 本章向你演示了ASP.NET Identity所支持的一些高级特性。演示了自定义用户属性的使用,还演示了在升级数据架构时,如何使用数据库迁移保护数据。我解释了声明(Claims)的工作机制,以及如何将它们用于创建更灵活的用户授权方式。最后演示了如何通过Google进行认证结束了本章,这是建立在使用声明(Claims)的思想基础之上的。 本篇文章为转载内容。原文链接:https://blog.csdn.net/gz19871113/article/details/108591802。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-10-28 08:49:21
283
转载
.net
...来。 1. 前言 .NET是由微软公司开发的一个应用程序框架,它可以提供一些常用的功能和API供程序员使用,让开发者可以更加方便快捷地开发出高质量的应用程序。在.NET这个大家庭里,C和Visual Basic可是两位大主角,都是.NET的重要组成部分。不过呢,这哥俩虽然同在一个屋檐下,却各有各的特点和差异。所以啊,咱们得好好探究一下这两门语言的不同之处和各自的独特魅力所在。 2. C C是一种面向对象的编程语言,它的语法类似于Java,但是比Java更加简洁明了,而且支持更多的现代特性,如匿名方法、LINQ查询等。你知道吗?C这门编程语言有个大大的优点,那就是性能杠杠的!特别是在Windows系统上,用C编译出的代码那跑起来简直是飞一般的感觉,速度快到没朋友!另外,C还自带了一大堆超实用的类库和API工具箱,这让开发者们能轻轻松松地写出高效能的应用程序,就像在厨房里有了一整套齐全的厨具,做起菜来更加得心应手。 下面是一个简单的C程序示例: csharp using System; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine("Hello, World!"); } } } 在这个程序中,我们定义了一个名为HelloWorld的程序集,并在其中定义了一个名为Program的类。然后,在我们的程序中心点——Main方法里头,我们让计算机蹦出了“Hello, World!”这句话。这就是咱们这个小程序最核心、最精髓的部分啦! 3. Visual Basic Visual Basic是一种可视化编程语言,它的语法比较简单,易于学习和使用,非常适合初学者入门。你知道吗,Visual Basic有个超赞的优点——它自带了一大堆可视化的小玩意儿和控件,这就像是给开发者准备了一整套积木。用这些积木,开发者可以像搭房子一样轻松快速地搭建出既好看又实用的应用界面,省时又省力,可酷了!此外,Visual Basic还支持许多高级特性,如事件驱动编程、多线程编程等。 下面是一个简单的Visual Basic程序示例: vbnet Module Module1 Sub Main() Console.WriteLine("Hello, World!") End Sub End Module 在这个程序中,我们定义了一个名为Module1的模块,并在其中定义了一个名为Main的方法。然后,我们在Main方法中打印出了字符串"Hello, World!",这也是我们的程序的核心逻辑。 4. C和Visual Basic的区别 虽然C和Visual Basic都是.NET的一部分,但是它们之间还是存在很多差异的。首先,咱从语言这一块儿来说,C这门语言的语法确实有点儿绕,不过人家可是藏着更多的功能和特性呢,就像是个大宝箱。而Visual Basic呢,就更像是一本初级读物,学起来轻松简单,特别适合刚入门的小白朋友来上手。其次,从性能角度来看,C编译出来的代码运行速度更快,而Visual Basic则相对较慢。最后,从实际应用场景来瞅瞅,C这门语言就像是为开发大型企业级应用而量身定制的,特别对路。相比之下,Visual Basic更适合捣鼓些小型桌面应用或者小游戏啥的,更加接地气儿。 5. 总结 总的来说,C和Visual Basic都是.NET的重要组成部分,各自有着自己的优势和适用场景。选择哪一种语言,应该根据实际的需求和情况来决定。不论你挑了哪种语言,只要你摸透了它的基本脾性和使用窍门,就绝对能捣鼓出顶尖水准的应用程序来。 感谢您阅读这篇文章,希望我的回答能够帮助到您!如果您有任何其他问题,欢迎随时联系我,我会尽全力为您解答。
2023-07-31 15:48:21
567
幽谷听泉-t
转载文章
...期,VS Code(Visual Studio Code)以其强大的扩展生态系统、跨平台支持以及对现代Web技术(如Vue.js、React和Angular)的一流支持而备受开发者青睐,已逐渐成为主流的前端开发IDE之一。 与此同时,随着WebAssembly等技术的发展,Web开发工具正不断拓展边界,以适应更复杂的应用场景。例如,JetBrains公司推出的Theia项目,是一个基于浏览器的开源IDE框架,旨在为云端开发提供轻量级且功能全面的解决方案。 另外,在响应式设计和移动优先战略的推动下,诸如Figma这样的实时协作UI/UX设计工具也在Web开发流程中扮演了重要角色,使得设计师与开发者之间的协同工作更为高效便捷。 对于JavaScript生态,Chrome DevTools及其配套的Lighthouse性能审计工具也不断升级,提供了更详尽的网页性能分析报告及优化建议,帮助开发者打造高性能的Web应用。 此外,Web组件标准日益成熟,Polymer、Stencil等库和框架助力开发者快速构建可复用的自定义元素,相关开发工具和教程资源也越来越丰富。 综上所述,无论是代码编辑器、调试工具还是设计协作平台,Web开发领域的工具链正在不断创新和完善,以满足日益增长的多元化开发需求,为广大开发者提供了更加先进、高效的开发环境。
2023-02-12 17:23:46
136
转载
转载文章
...blog.csdn.net/m0_46843484/article/details/125283328。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。 万年历显示系统报告 一、描述 大家好!我是小浝仔,今天给大家分享C/C++语言期末课程设计——万年历显示系统,这个程序是用C/C++语言程序编写的,运行环境为VisualC++6.0,实现了①输入一个年份,在屏幕上显示该年的日历。假定输入的年份在1940—2040年之间。②输入年月,输出该月的日历。③如何让星期与下面的数字对齐,且第一行显示星期,从周日到周六,从第二行开始显示日期。④主函数显示主菜单界面,并进行多分支选择用循环结构造功能等等,是学 本篇文章为转载内容。原文链接:https://blog.csdn.net/m0_46843484/article/details/125283328。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-08-04 16:46:08
496
转载
转载文章
...blog.csdn.net/weixin_30429201/article/details/98226373。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。 作者:Flyingis ArcGIS 9.3已经发布,还没有仔细研究what's new in arcgis 9.3,但这次版本升级确实带来了不少新的变化,等新版本全面铺开之后,我们可以渐渐体会到新版本所带来的改进与新功能。 ArcGIS Server始终是关注的焦点,新版本的软件到用户手上还需要一段时间,如果现在就迫不及待想了解ags9.3新的特性,可以看ESRI刚刚发布的在线文档: ArcGIS Server 9.3 Web Help ArcGIS Server 9.3 Javascript API 标准和Mushup是这次ags更新的主题,wfs、using SLDs in wms、wcs、kml、javascript extension for google map api、javascript extension for visual earth等等,从9.3beta提交之前,不少基于ags9.2(including arcims9.2)的应用就已经开始向标准(事实标准)和其他服务整合,比如2007年ESRI中国应用开发大赛一等奖作品(作者Mars)就是arcims9.2+openlayer整合,一些ags项目使用google map服务作为底图,加上业务图层实现数据层面的整合,还有开发人员将google earth和ags发布的二维地图的地理坐标联动起来,下载安装google earth plugin之后,可以同时浏览某一地理位置的google earth三维地图和ags二维地图,当业务的侧重点在于地理展示和客户端体验时,不能不说Google树立了一个典范,从ags抽取地理核心服务,从Google Earth/Map或是其他服务提取基础地图和应用展示,两者结合实现某种需求。 虽然从ags9.2-9.3的功能改进,可以看出ESRI在过去以GIS核心服务为重心的基础上,开始增强客户端的应用开发(ADF模板程序、javascript api),但是它并没有停止服务层面的不断改进,各种新增的各种server服务以及REST API就是最好的体现。思想到位了,还需要实际检验,估计不少bug等着我们挖掘,后面会向大家介绍一些比较流行的server基本开发模式。 相关链接: Javascript API Samples ArcGIS Server Resource Center 转载于:https://www.cnblogs.com/flyingis/archive/2008/07/09/1239585.html 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_30429201/article/details/98226373。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-04-22 09:33:23
116
转载
转载文章
...blog.csdn.net/AdrianAndroid/article/details/127860988。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。 资料 Java Swing 介绍 JavaFX快速入门 Java Swing 图形界面开发简介 GUI Designer Basics scrcpy ScrcpyController Services 创建一个Gui Form文件(类+form文件) 创建一个Gui Form 此时生成两个类, 是自动关联的 鼠标可以拖入控件,每拖入一个组件,在TestForm.java类中会自动生成对应的属性名. 界面显示 显示在ToolWindow的右侧 我们拿ScrcpyController举例,显示如下的界面 需要用到如下三个文件 其中ScrcpyController显示的就是界面, ScrcpyToolWindowFactory是把界面放入的的工厂类. 声明这个工厂类 <extensions defaultExtensionNs="com.intellij"><toolWindowanchor="right"canCloseContents="false"factoryClass="com.codertainment.scrcpy.controller.ui.ScrcpyToolWindowFactory" icon="/toolWindowIcon.svg"id="scrcpy"/>...</extensions> 设置界面 需要如下三个类 ScrcpyControllerSettingsComponent是界面, ScrcpyControllerconfigurable是绑定的工厂类. 在plugin.xml中声明 <extensions defaultExtensionNs="com.intellij"><applicationConfigurabledisplayName="Scrcpy Controller" id="com.codertainment.scrcpy.controller.ui.ScrcpyControllerConfigurable"instance="com.codertainment.scrcpy.controller.ui.ScrcpyControllerConfigurable"parentId="tools"/></extensions> 存储服务 本篇文章为转载内容。原文链接:https://blog.csdn.net/AdrianAndroid/article/details/127860988。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-05-01 10:38:51
437
转载
转载文章
...blog.csdn.net/u011153667/article/details/52483856。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。 The new dependency injection system in Angular 2 comes with a feature called “Multi Providers” that basically enable us, the consumer of the platform, to hook into certain operations and plug in custom functionality we might need in our application use case. We’re going to discuss what they look like, how they work and how Angular itself takes advantage of them to keep the platform flexible and extendible. Recap: What is a provider? If you’ve read our article on Dependency Injection in Angular2 you can probably skip this section, as you’re familiar with the provider terminology, how they work, and how they relate to actual dependencies being injected. If you haven’t read about providers yet, here’s a quick recap. A provider is an instruction that describes how an object for a certain token is created. Quick example: In an Angular 2 component we might have a DataService dependency, which we can ask for like this: import { DataService } from './data.service';@Component(...)class AppComponent {constructor(dataService: DataService) {// dataService instanceof DataService === true} } We import the type of the dependency we’re asking for, and annotate our dependency argument with it in our component’s constructor. Angular knows how to create and inject an object of type DataService, if we configure a provider for it. This can happen either on the application module, that bootstrap our app, or in the component itself (both ways have different implications on the dependency’s life cycle and availability). // application module@NgModule({...providers: [{ provide: DataService, useClass DataService }]})...// or in component@Component({...providers: [{ provide: DataService, useClass: DataService }]})class AppComponent { } In fact, there’s a shorthand syntax we can use if the instruction is useClass and the value of it the same as the token, which is the case in this particular provider: @NgModule({...providers: [DataService]})...// or in component@Component({...providers: [DataService]})class AppComponent { } Now, whenever we ask for a dependency of type DataService, Angular knows how to create an object for it. Understanding Multi Providers With multi providers, we can basically provide multiple dependencies for a single token. Let’s see what that looks like. The following code manually creates an injector with multi providers: const SOME_TOKEN: OpaqueToken = new OpaqueToken('SomeToken');var injector = ReflectiveInjector.resolveAndCreate([{ provide: SOME_TOKEN, useValue: 'dependency one', multi: true },{ provide: SOME_TOKEN, useValue: 'dependency two', multi: true }]);var dependencies = injector.get(SOME_TOKEN);// dependencies == ['dependency one', 'dependency two'] Note: We usually don’t create injectors manually when building Angular 2 applications since the platform takes care of that for us. This is really just for demonstration purposes. A token can be either a string or a type. We use a string, because we don’t want to create classes to represent a string value in DI. However, to provide better error messages in case something goes wrong, we can create our string token using OpaqueToken. We don’t have to worry about this too much now. The interesting part is where we’re registering our providers using the multi: true option. Using multi: true tells Angular that the provider is a multi provider. As mentioned earlier, with multi providers, we can provide multiple values for a single token in DI. That’s exactly what we’re doing. We have two providers, both have the same token but they provide different values. If we ask for a dependency for that token, what we get is a list of all registered and provided values. Okay understood, but why? Alright, fine. We can provide multiple values for a single token. But why in hell would we do this? Where is this useful? Good question! Usually, when we register multiple providers with the same token, the last one wins. For example, if we take a look at the following code, only TurboEngine gets injected because it’s provider has been registered at last: class Engine { }class TurboEngine { }var injector = ReflectiveInjector.resolveAndCreate([{ provide: Engine, useClass: Engine},{ provide: Engine, useClass: TurboEngine}]);var engine = injector.get(Engine);// engine instanceof TurboEngine This means, with multi providers we can basically extend the thing that is being injected for a particular token. Angular uses this mechanism to provide pluggable hooks. One of these hooks for example are validators. When creating a validator, we need to add it to the NG_VALIDATORS multi provider, so Angular picks it up when needed @Directive({selector: '[customValidator][ngModel]',providers: [provide: NG_VALIDATORS,useValue: (formControl) => {// validation happens here},multi: true]})class CustomValidator {} Multi providers also can’t be mixed with normal providers. This makes sense since we either extend or override a provider for a token. Other Multi Providers The Angular platform comes with a couple more multi providers that we can extend with our custom code. At the time of writing these were NG_VALIDATORS - Interface that can be implemented by classes that can act as validators NG_ASYNC_VALIDATORS - Token that can be implemented by classes that can act as async validators Conclusion Multi providers are a very nice feature to implement pluggable interface that can be extended from the outside world. The only “downside” I can see is that multi providers only as powerful as what the platform provides. NG_VALIDATORS and NG_ASYNC_VALIDATORS are implemented right into the platform, which is the only reason we can take advantage of those particular multi providers. There’s no way we can introduce our own custom multi providers (with a specific token) that influences what the platform does, but maybe this is also not needed. 原文链接:http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html 本篇文章为转载内容。原文链接:https://blog.csdn.net/u011153667/article/details/52483856。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-03-31 11:22:56
526
转载
转载文章
...的文本编辑器。Vi(Visual Editor)是一种基于命令行的文本编辑器,最初设计用于在终端环境下进行高效文本处理。而Vim(Vi Improved)则是对Vi编辑器的增强版本,它不仅保留了Vi的所有功能,还增加了许多改进,如可视化模式、语法高亮、代码折叠、宏录制与回放等高级特性,使得在编写和编辑程序代码、配置文件等方面更为便捷和高效。 crontab定时任务调度 , crontab是Linux系统中的一种计划任务调度工具,允许用户按照预设的时间间隔或特定时间点执行指定的命令或脚本。通过编辑crontab文件,用户可以灵活地安排各种周期性任务,例如系统日志清理、数据备份、应用程序更新等。每个系统用户都可以拥有独立的crontab任务列表,确保操作系统的自动化运维和管理。 LVM逻辑卷管理 , LVM(Logical Volume Manager)是Linux下的一种磁盘存储管理技术,通过将物理硬盘分区转换为逻辑卷,提供了一个更为灵活和动态的磁盘空间管理方案。LVM能够实现卷组的创建、扩展和缩减,以及逻辑卷的移动、快照和克隆等功能,无需关心底层物理存储的具体细节,极大地提高了存储资源的利用率和管理效率。在Linux环境中,当需要调整分区大小或重新分配存储空间时,LVM提供了比传统分区方式更为方便的操作手段。
2023-02-08 09:55:12
291
转载
转载文章
...abit Ethernet(千兆以太网接口)。在本文中,GigE接口被用于连接Basler_acA1300-30gc网络摄像机与个人电脑或笔记本,实现高达1吉比特每秒的数据传输速率,为实时图像采集和传输提供了稳定高效的通信链路。 OpenCV (Open Source Computer Vision Library) , OpenCV是一个开源的计算机视觉库,提供了一系列图像处理和计算机视觉相关的算法。在本篇文章的语境下,开发者使用Windows 7操作系统结合Visual Studio 2010开发环境以及OpenCV库,能够方便地调用VideoCapture类来控制和获取网络摄像机拍摄的图像数据,无需依赖特定的SDK,简化了摄像机设备的编程接入流程。 SDK (Software Development Kit) , SDK是软件开发工具包的简称,通常包含一组预编译的程序库、API接口、文档说明以及其他相关资源,旨在帮助开发者更便捷高效地创建应用软件。在本文所讨论的场景中,虽然传统观念认为调用工业级摄像机可能需要特定的SDK支持,但实际操作中,通过OpenCV的VideoCapture类已经可以实现对Basler_acA1300-30gc摄像机的基本功能操控,对于一般应用场景而言,不再强制要求使用相机厂商提供的SDK进行开发。
2023-09-02 09:33:05
581
转载
.net
...者朋友们,当你踏入.NET的世界,特别是面对Windows Communication Foundation(简称WCF)这一强大的框架时,你是否对如何利用它构建高性能、安全且灵活的Web服务感到好奇和跃跃欲试呢?今天,就让我们一起深入探讨并实践如何在.NET中使用WCF进行Web服务开发,以期能帮你理解其核心概念,并掌握实际操作技巧。 1. WCF基础认识 首先,我们要明确一点:WCF是微软为.NET平台提供的一体化通信解决方案,旨在简化不同应用程序之间的互操作性。用WCF这个工具,我们能够亲手打造面向服务的应用程序,甭管是网络协议、消息格式还是传输方式,都能支持多种多样。这样一来,不管平台怎么变,技术栈怎么不同,数据交换都能轻松跨过去,畅通无阻地实现。 2. 创建WCF服务项目 (1)启动Visual Studio,选择新建项目,然后在模板列表中找到“WCF服务库”,点击创建。此刻,你会看到一个默认生成的服务接口(IService1.cs)和其实现类(Service1.svc.cs)。 csharp // IService1.cs [ServiceContract] public interface IService1 { [OperationContract] string GetData(int value); } // Service1.svc.cs public class Service1 : IService1 { public string GetData(int value) { return string.Format("You entered: {0}", value); } } 这段代码展示了如何定义一个基本的WCF服务契约(通过ServiceContract属性标记接口)以及其实现(通过实现该接口)。嘿,你知道吗?在编程里头,有个叫做OperationContract的小家伙可厉害了。它专门用来标记接口里的某个方法,告诉外界:“瞧瞧,这个方法就是我们对外开放的服务操作!”这样说是不是感觉更接地气啦? 3. 配置WCF服务 打开App.config文件,你会发现WCF服务的核心配置信息都在这里。例如: xml 这部分配置说明了服务的终结点信息,包括地址、绑定和合同。在这儿,我们捣鼓出了一个借助HTTP搭建的基础接口,专门用来应对各种服务请求;另外还搞了个小家伙,它的任务是负责交换那些元数据信息。 4. 部署与调用WCF服务 完成服务编写和配置后,将项目部署到IIS或直接运行调试即可。客户端想要调用这个服务,有俩种接地气的方式:一种是直接在程序里头添加服务引用,另一种则是巧妙地运用ChannelFactory这个工具来实现调用。就像我们平时点外卖,既可以收藏常去的店铺快速下单,也可以灵活搜索各种渠道找到并订购心仪美食一样。下面是一个简单的客户端调用示例: csharp // 添加服务引用后自动生成的Client代理类 var client = new Service1Client(); var result = client.GetData(123); Console.WriteLine(result); // 输出 "You entered: 123" client.Close(); 这里,我们创建了一个服务客户端实例,并调用了GetData方法,实现了与服务端的交互。 5. 进阶探讨 当然,WCF的功能远不止于此,还包括安全性、事务处理、可靠会话、多线程并发控制等诸多高级特性。比如,我们可以为服务操作添加安全性验证: csharp [OperationContract] [PrincipalPermission(SecurityAction.Demand, Role = "Admin")] string SecureGetData(int value); 这段代码表明只有角色为"Admin"的用户才能访问SecureGetData方法,体现了WCF的安全性优势。 总的来说,WCF在.NET中为我们提供了便捷而强大的Web服务开发工具,无论是初级开发者还是资深工程师,都需要对其有足够的理解和熟练应用。在实践中不断探索和尝试,相信你会越来越感受到WCF的魅力所在!
2023-07-18 11:00:57
456
红尘漫步
转载文章
...blog.csdn.net/suxinpingtao51/article/details/37765457。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。 首先我们需要问一个问题是:为什么两个类不能互相包含头文件? 所谓互相包含头文件,我举一个例子:我实现了两个类:图层类CLayer和符号类CSymbol,它们的大致关系是图层里包含有符号,符号里定义一个相关图层指针,具体请参考如下代码(注:以下代码仅供说明问题,不作为类设计参考,所以不适宜以此讨论类的设计,编译环境为Microsoft Visual C++ 2005,,Windows XP + sp2,以下同): //Layer.h // 图层类 pragma once include "Symbol.h" class CLayer { public: CLayer(void); virtual ~CLayer(void); void CreateNewSymbol(); private: CSymbol m_pSymbol; // 该图层相关的符号指针 }; // Symbol.h // 符号类 pragma once include "Layer.h" class CSymbol { public: CSymbol(void); virtual ~CSymbol(void); public: CLayer m_pRelLayer; // 符号对应的相关图层 }; // TestUnix.cpp : 定义控制台应用程序的入口点。 // include "stdafx.h" include "Layer.h" include "Symbol.h" void main( void ) { CLayer MyLayer; } 现在开始编译,编译出错,现在让我们分析一下编译出错信息(我发现分析编译信息对加深程序的编译过程的理解非常有好处)。 首先我们明确:编译器在编译文件时,遇到#include "x.h"时,就打开x.h文件进行编译,这相当于把x.h文件的内容放在include "x.h"处。 编译信息告诉我们:它是先编译TestUnix.cpp文件的,那么接着它应该编译stdafx.h,接着是Layer.h,如果编译Layer.h,那么会编译Symbol.h,但是编译Symbol.h又应该编译Layer.h啊,这岂不是陷入一个死循环? 呵呵,如果没有预编译指令,是会这样的,实际上在编译Symbol.h,再去编译Layer.h,Layer.h头上的那个pragma once就会告诉编译器:老兄,这个你已经编译过了,就不要再浪费力气编译了!那么编译器得到这个信息就会不再编译Layer.h而转回到编译Symbol.h的余下内容。 当编译到CLayer m_pRelLayer;这一行编译器就会迷惑了:CLayer是什么东西呢?我怎么没见过呢?那么它就得给出一条出错信息,告诉你CLayer没经定义就用了呢? 在TestUnix.cpp中include "Layer.h"这句算是宣告编译结束(呵呵,简单一句弯弯绕绕不断),下面轮到include "Symbol.h",由于预编译指令的阻挡,Symbol.h实际上没有得到编译,接着再去编译TestUnix.cpp的余下内容。 当然上面仅仅是我的一些推论,还没得到完全证实,不过我们可以稍微测试一下,假如在TestUnix.cpp将include "Layer.h"和include "Symbol.h"互换一下位置,那么会不会先提示CSymbol类没有定义呢?实际上是这样的。当然这个也不能完全证实我的推论。 照这样看,两个类的互相包含头文件肯定出错,那么如何解决这种情况呢?一种办法是在A类中包含B类的头文件,在B类中前置盛明A类,不过注意的是B类使用A类变量必须通过指针来进行,具体见拙文:类互相包含的办法。 为何不能前置声明只能通过指针来使用?通过分析这个实际上我们可以得出前置声明和包含头文件的区别。 我们把CLayer类的代码改动一下,再看下面的代码: // 图层类 //Layer.h pragma once //include "Symbol.h" class CSymbol; class CLayer { public: CLayer(void); virtual ~CLayer(void); // void SetSymbol(CSymbol pNewSymbol); void CreateNewSymbol(); private: CSymbol m_pSymbol; // 该图层相关的符号 // CSymbol m_Symbol; }; // Layer.cpp include "StdAfx.h" include "Layer.h" CLayer::CLayer(void) { m_pSymbol = NULL; } CLayer::~CLayer(void) { if(m_pSymbol!=NULL) { delete m_pSymbol; m_pSymbol=NULL; } } void CLayer::CreateNewSymbol() { } 然后编译,出现一个编译警告:>f:\mytest\mytest\src\testunix\layer.cpp(16) : warning C4150: 删除指向不完整“CSymbol”类型的指针;没有调用析构函数 1> f:\mytest\mytest\src\testunix\layer.h(9) : 参见“CSymbol”的声明 看到这个警告,我想你一定悟到了什么。下面我说说我的结论: 类的前置声明和包含头文件的区别在于类的前置声明是告诉编译器有这种类型,但是它没有告诉编译器这种类型的大小、成员函数和数据成员,而包含头文件则是完全告诉了编译器这种类型到底是怎样的(包括大小和成员)。 这下我们也明白了为何前置声明只能使用指针来进行,因为指针大小在编译器是确定的。上面正因为前置声明不能提供析构函数信息,所以编译器提醒我们:“CSymbol”类型的指针是没有调用析构函数。 如何解决这个问题呢? 在Layer.cpp加上include "Symbol.h"就可以消除这个警告。 本篇文章为转载内容。原文链接:https://blog.csdn.net/suxinpingtao51/article/details/37765457。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2024-01-02 13:45:40
570
转载
转载文章
...hon编程语言的广泛应用,其周边工具生态也在不断壮大和发展。近日,Python社区迎来了一些新的开发工具和功能更新。 首先,Microsoft Visual Studio Code(VS Code)通过其Python扩展插件新增了对Jupyter Notebook的支持,使得开发者能够在熟悉的代码编辑器环境中直接创建、运行和分享Jupyter Notebook项目,大大提升了数据科学家和机器学习工程师的工作效率。 其次,PyCharm 2023.1版本发布,该版本强化了对异步编程的支持,并优化了Type Checking与类型提示功能,为Python开发者提供更为智能和高效的编程体验。同时,PyCharm继续深化对Django、Flask等主流Web框架的支持,以及对大型项目的管理和调试能力。 此外,Anaconda近期发布的Conda 4.11版,增强了对Mamba协议的支持,进一步加快了包管理的速度,特别是对于包含大量依赖项的数据科学项目,显著提高了环境配置的时间效率。 在在线教育领域,CodeHS新近推出了针对Python初学者的互动教程,结合Python Tutor的理念,以游戏化的方式教授编程基础知识,让更多学生能够轻松入门Python编程。 Python社区的发展永不停歇,这些工具和平台的持续更新与迭代,不仅反映出Python在各领域的广泛应用,也预示着未来Python开发将更加便捷高效,助力开发者们实现更多的创新与突破。
2023-11-14 09:38:26
43
转载
转载文章
...blog.csdn.net/yangdelong/article/details/3946113。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。 标 题: 我的windows下的mpich的经验 发信站: 南京大学小百合站 (Tue Nov 2 22:02:25 2004) 弄了好久的mpich,现在终于弄懂了 感谢pink, johnsmith给予的帮助 下面是跟都志辉老师的邮件,与还不会的同学共享 希望能给在windows下用的同学有帮助 到这封邮件,我已经懂了,相信大家会比我更快 如果还有不懂的,站内联系 /// 发件人: "Zhihui Du" <duzh@tsinghua.edu.cn> 添加到地址簿 收件人: "zhyi" <zhyi100@yahoo.com.cn> 主题: Re: 请教mpi 日期: Tue, 2 Nov 2004 08:31:20 +0800 我想主要的问题是权限的问题,你先在本机将config文件设置为只有自己的机器,运行一 下该程序看看,如果不能运行,多机当然就更不行了,这说明本机的设置有问题。如何解 决这一问题,我的经验是,你可以在两台机器上分别建立普通帐号,然后用mpiregister对 该帐号进行注册,如果两台机器上分别运行都可以,则可以试试多机,如果多机连接不同 ,则可能是防火墙等安全设置的问题,可以将防火墙去掉,这样就应该可以了,我们在XP 以及NT上实验都是可行的。 ------------------------------ Dr. Zhihui Du Department of Computer Science and Technology Tsinghua University. Beijing, 100084, P.R. China Phone:86-10-62782530 Fax:86-10-62771138 http://hpclab.cs.tsinghua.edu.cn/~duzh ----- Original Message ----- From: zhyi To: Zhihui Du Sent: Monday, November 01, 2004 4:39 PM Subject: Re: 请教mpi 单机模拟的命令为: mpirun -np 2 -localonly d:/cpi.exe 成功 两机器名分别为 liu1 liu2,命令为 mpirun -hosts 2 liu1 liu2 d:/cpi.exe 失败 config文件为 config.cfg exe d:/cpi.exe hosts liu1 2 liu2 2 命令为 mpirun d:/config.cfg 失败 加选项-tcp也没用 可执行文件的存放路径都在d盘根目录下 都老师,我想你们都是用linux 的,能不能请您的研究生给在两台 机器上试一下,估计两个小时够了,有你的指点,就会知道问题出在哪。 我们这边也有很多同学在你的书的指引下在linux下进行的,我是进行数值计算,不敢弄那 么复杂,只好在windows下进行,可也不知问题究竟在哪。 Zhihui Du <duzh@tsinghua.edu.cn> wrote: 你运行的具体命令是什么?可以用mpirun -np 2 xxx 和 mpirun configfile 两种方式都 试试,可执行程序两台机器上都要有。 ------------------------------ Dr. Zhihui Du Department of Computer Science and Technology Tsinghua University. Beijing, 100084, P.R. China Phone:86-10-62782530 Fax:86-10-62771138 http://hpclab.cs.tsinghua.edu.cn/~duzh ----- Original Message ----- From: zhyi To: Zhihui Du Sent: Sunday, October 31, 2004 11:50 AM Subject: Re: 请教mpi 任务管理器里发现有mpd进程,mpiconfig也能找到对方, 我们是在同一个宿舍,用hub相连,这在局域网内应该没问题了, 共享也是可读写的,盘符的格式是一样的,单机可以运行 mpirun -np 2 -localonly c:/ .exe 有结果 Zhihui Du <duzh@tsinghua.edu.cn> wrote: 安装mpich后应该有一个新的mpi进程在运行,用mpiconfig应该能够列出其他的机器才行, 还有这些计算结点的网络配置应该在一个子网内,另外共享的权限是否是任何用户可以读 写?你用mpirun -localonly -np x abc方式是否可以运行? ------------------------------ Dr. Zhihui Du Department of Computer Science and Technology Tsinghua University. Beijing, 100084, P.R. China Phone:86-10-62782530 Fax:86-10-62771138 http://hpclab.cs.tsinghua.edu.cn/~duzh ----- Original Message ----- From: zhyi To: Zhihui Du Sent: Saturday, October 30, 2004 5:55 PM Subject: Re: 请教mpi 我是严格按照mpich的要求进行的, 1。使用管理员权限在两机器上新建同一个名称的用户及相同的口令 2。分别在上面的两用户里安装mpich,然后mpiregister ,用户名和口令同 3。同一名称的盘符共享 4。mpiconfig,显示了对方的mpich 的版本号,说明已找到。 5。运行mpi程序 这样还是没有用,我们这边在windows系统下进行的很少有人成功过 我们都在网上问这个问题 Zhihui Du <duzh@tsinghua.edu.cn> wrote: 如果仅仅是自己做实验用,就可以不要考虑太多的安全问题,把MPI程序所在的盘共享出来 让其他的机器都可以访问,按照MPICH自己的设置,你可以运行MPIREGISTER程序先注册一 下用户名和口令。 ------------------------------ Dr. Zhihui Du Department of Computer Science and Technology Tsinghua University. Beijing, 100084, P.R. China Phone:86-10-62782530 Fax:86-10-62771138 http://hpclab.cs.tsinghua.edu.cn/~duzh ----- Original Message ----- From: zhyi To: duzh@tirc.cs.tsinghua.edu.cn Sent: Friday, October 29, 2004 9:26 PM Subject: 请教mpi 都老师: 你好! 我是南京大学系学生,现在正在用mpi进行数值并行编程, 是在windows系统下,同实验室的两台机器,总是显示登陆失败 不知怎么设置的。两台机器用的是同一用户名和相同密码,同样的注册。 希望能得到您的指点。 此致 -- ※ 来源:.南京大学小百合站 http://bbs.nju.edu.cn [FROM: 172.16.78.68] -- ※ 转寄:.南京大学小百合站 bbs.nju.edu.cn.[FROM: 202.120.20.14] -- ※ 转寄:.南京大学小百合站 bbs.nju.edu.cn.[FROM: 202.120.20.14] 一、预备工作 0. 二、下载 1. 下载mpich 三、安装 2. 用具有管理权限的帐户登陆计算机 3. 执行mpich.nt.1.2.5.exe,选择所有缺省安装 4. 在每台计算机上均执行上述过程2、3 四、配置 5. 运行配置工具 start->programs->MPICH->mpd->MPICH Configuration tool 6. 加入已经安装mpich的主机 7.点击 [Apply] 保存 8 点击 [OK] 退出 五、测试 9. 打开MSDEV工作空间文件 MPICH/SDK/examples/nt/examples.dsw 10. 编译调试该cpi 项目 11. 拷贝MPICH/SDK/examples/nt/basic/Debug/cpi.exe 到每一台机器某一共享目录。 如: c:/temp/cpi.exe 注意:确保每台机器均有同样的共享目录,并且可以互相访问!! 12. 打开命令窗口,改变当前路径到 c:/temp 下(与前相同) 13. 执行命令 MPICH/mpd/bin/mpirun.exe -np 4 cpi 本篇文章为转载内容。原文链接:https://blog.csdn.net/yangdelong/article/details/3946113。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-04-09 11:52:38
113
转载
转载文章
...blog.csdn.net/m0_67155975/article/details/123351126。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。 文章目录 1 BootStrap基础 1 什么是BootStrap 2 BootStrap的版本 3 BootStrap 下载 4 CDN服务 5 目录结构 6 基本模板 7 浏览器支持 8 浏览器兼容 让 IE8 支持H5新标签 IE兼容模式 国产浏览器切换webkit内核 2 BootStrap布局 1 概览 1.1 移动设备优先 1.2 Normalize.css 1.3 布局容器 2 栅格系统 2.1 栅格系统简介 2.2 栅格参数 2.3 栅格系统使用 2.4 不同屏幕设置不同宽度 2.5 列偏移 2.6 列位置移动 3 排版 3.1 标题 3.2 突出显示 3.3 对齐 3.4 改变大小写 3.5 引用 3.6 列表 4 代码 4.1 内联代码 4.2 用户输入 4.3 代码块 4.3 变量 4.4 程序输出 5 表格 5.1 基本 5.2 条纹状表格 5.3 带边框的表格 5.4 鼠标悬停 5.5 紧缩表格 5.6 状态类 5.7 响应式表格 6 表单 6.1 基本实例 6.2 内联表单 6.3 水平排列的表单 6.4 表单控件 输入框 文本域 多选和单选框 下拉列表 静态内容 帮助文字 校验状态 添加额外的图标 控件尺寸 7 按钮 7.1 可作为按钮使用的标签或元素 7.2 预定义样式 7.3 尺寸 7.4 激活状态 7.5 禁用状态 8 图片 8.1 响应式图片 8.2 图片形状 9 辅助类 9.1 文本颜色 9.2 背景色 9.3 三角符号 9.4 浮动 9.5 让内容块居中 9.6 清除浮动 9.7 显示或隐藏内容 9.10 图片替换 10 响应式工具 10.1 不同视口下隐藏显示 10.2 打印类 1 BootStrap基础 1 什么是BootStrap 由Twitter的设计师Mark Otto和Jacob Thornton合作开发,是一个CSS/HTML框架简洁、直观、强悍的前端开发框架,让web开发更迅速、简单。 2 BootStrap的版本 BootStrap2 BootStrap3 BootStrap4 3 BootStrap 下载 用于生产环境的Bootstrap Bootstrap Less 源码Bootstrap Sass 源码 4 CDN服务 <!-- 新 Bootstrap 核心 CSS 文件 --><link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css"><!-- 可选的Bootstrap主题文件(一般不用引入) --><link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"><!-- jQuery文件。务必在bootstrap.min.js 之前引入 --><script src="http://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script><!-- 最新的 Bootstrap 核心 JavaScript 文件 --><script src="http://cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> 5 目录结构 生产环境版 bootstrap/├── css/│ ├── bootstrap.css│ ├── bootstrap.css.map│ ├── bootstrap.min.css│ ├── bootstrap-theme.css│ ├── bootstrap-theme.css.map│ └── bootstrap-theme.min.css├── js/│ ├── bootstrap.js│ └── bootstrap.min.js└── fonts/├── glyphicons-halflings-regular.eot├── glyphicons-halflings-regular.svg├── glyphicons-halflings-regular.ttf├── glyphicons-halflings-regular.woff└── glyphicons-halflings-regular.woff2 6 基本模板 <!DOCTYPE html><html lang="zh-CN"><head><!-- 上述3个meta标签必须放在最前面,任何其他内容都必须跟随其后! --><title>Bootstrap 101 Template</title><!-- Bootstrap --><link href="css/bootstrap.min.css" rel="stylesheet"><!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --><!-- WARNING: Respond.js doesn't work if you view the page via file:// --><!--[if lt IE 9]><script src="//cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script><script src="//cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script><![endif]--></head><body><h1>你好,世界!</h1><!-- jQuery (necessary for Bootstrap's JavaScript plugins) --><script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script><!-- Include all compiled plugins (below), or include individual files as needed --><script src="js/bootstrap.min.js"></script></body></html> 7 浏览器支持 手机浏览器 ——- Chrome Firefox Safari Android Supported Supported N/A iOS Supported Supported Supported 桌面浏览器 ——— Chrome Firefox Internet Explorer Opera Safari Mac Supported Supported N/A Supported Supported Windows Supported Supported Supported Supported Not supported 8 浏览器兼容 让 IE8 支持H5新标签 页面中引入respond.js <!-- 注意: 页面必须通过服务器访问 --><script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script> IE兼容模式 页面中添加如下代码 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 国产浏览器切换webkit内核 页面中添加如下代码 <meta name="renderer" content="webkit"> 2 BootStrap布局 1 概览 1.1 移动设备优先 为了确保适当的绘制和触屏缩放,需要在 <head> 之中添加 viewport 元数据标签。 在移动设备浏览器上,通过为视口(viewport)设置 meta 属性为 user-scalable=no 可以禁用其缩放(zooming)功能。这样禁用缩放功能后,用户只能滚动屏幕,就能让你的网站看上去更像原生应用的感觉。注意,这种方式我们并不推荐所有网站使用,还是要看你自己的情况而定! 1.2 Normalize.css BootStrap内置了Normalize.css 1.3 布局容器 Bootstrap 需要为页面内容和栅格系统包裹一个 .container 容器。我们提供了两个作此用处的类。注意,由于 padding 等属性的原因,这两种 容器类不能互相嵌套。 .container 类用于固定宽度并支持响应式布局的容器。 <div class="container">...</div> .container-fluid 类用于 100% 宽度,占据全部视口(viewport)的容器。 <div class="container-fluid">...</div> 2 栅格系统 Bootstrap 提供了一套响应式、移动设备优先的流式栅格系统,随着屏幕或视口(viewport)尺寸的增加,系统会自动分为最多12列 2.1 栅格系统简介 栅格系统用于通过一系列的行(row)与列(column)的组合来创建页面布局,你的内容就可以放入这些创建好的布局中。下面就介绍一下 Bootstrap 栅格系统的工作原理: “行(row)”必须包含在 .container (固定宽度)或 .container-fluid (100% 宽度)中,以便为其赋予合适的排列(aligment)和内补(padding)。 通过“行(row)”在水平方向创建一组“列(column)”。 你的内容应当放置于“列(column)”内,并且,只有“列(column)”可以作为行(row)”的直接子元素。 类似 .row 和 .col-xs-4 这种预定义的类,可以用来快速创建栅格布局。Bootstrap 源码中定义的 mixin 也可以用来创建语义化的布局。 通过为“列(column)”设置 padding 属性,从而创建列与列之间的间隔(gutter)。通过为 .row 元素设置负值 margin 从而抵消掉为 .container 元素设置的 padding,也就间接为“行(row)”所包含的“列(column)”抵消掉了padding。 负值的 margin就是下面的示例为什么是向外突出的原因。在栅格列中的内容排成一行。 栅格系统中的列是通过指定1到12的值来表示其跨越的范围。例如,三个等宽的列可以使用三个 .col-xs-4 来创建。 如果一“行(row)”中包含了的“列(column)”大于 12,多余的“列(column)”所在的元素将被作为一个整体另起一行排列。 栅格类适用于与屏幕宽度大于或等于分界点大小的设备 , 并且针对小屏幕设备覆盖栅格类。 因此,在元素上应用任何 .col-md-栅格类适用于与屏幕宽度大于或等于分界点大小的设备 , 并且针对小屏幕设备覆盖栅格类。 因此,在元素上应用任何 .col-lg-不存在, 也影响大屏幕设备。 2.2 栅格参数 超小屏幕 手机 (<768px) 小屏幕 平板 (≥768px) 中等屏幕 桌面显示器 (≥992px) 大屏幕 大桌面显示器 (≥1200px) .container 最大宽度 None (自动) 750px 970px 1170px 类前缀 .col-xs- .col-sm- .col-md- .col-lg- 最大列(column)宽 自动 ~62px ~81px ~97px 2.3 栅格系统使用 使用单一的一组 .col-md- 栅格类,就可以创建一个基本的栅格系统,在手机和平板设备上一开始是堆叠在一起的(超小屏幕到小屏幕这一范围),在桌面(中等)屏幕设备上变为水平排列。所有“列(column)必须放在 ” .row 内。 <div class="row"><div class="col-md-1">.col-md-1</div><div class="col-md-1">.col-md-1</div><div class="col-md-1">.col-md-1</div><div class="col-md-1">.col-md-1</div><div class="col-md-1">.col-md-1</div><div class="col-md-1">.col-md-1</div><div class="col-md-1">.col-md-1</div><div class="col-md-1">.col-md-1</div><div class="col-md-1">.col-md-1</div><div class="col-md-1">.col-md-1</div><div class="col-md-1">.col-md-1</div><div class="col-md-1">.col-md-1</div></div><div class="row"><div class="col-md-8">.col-md-8</div><div class="col-md-4">.col-md-4</div></div><div class="row"><div class="col-md-4">.col-md-4</div><div class="col-md-4">.col-md-4</div><div class="col-md-4">.col-md-4</div></div><div class="row"><div class="col-md-6">.col-md-6</div><div class="col-md-6">.col-md-6</div></div> 2.4 不同屏幕设置不同宽度 <div class="row"><div class="col-xs-12 col-sm-6 col-md-8">.col-xs-12 .col-sm-6 .col-md-8</div><div class="col-xs-6 col-md-4">.col-xs-6 .col-md-4</div></div><div class="row"><div class="col-xs-6 col-sm-4">.col-xs-6 .col-sm-4</div><div class="col-xs-6 col-sm-4">.col-xs-6 .col-sm-4</div><!-- Optional: clear the XS cols if their content doesn't match in height --><div class="clearfix visible-xs-block"></div><div class="col-xs-6 col-sm-4">.col-xs-6 .col-sm-4</div></div> 2.5 列偏移 使用 .col-md-offset- 类可以将列向右侧偏移。这些类实际是通过使用 选择器为当前元素增加了左侧的边距(margin)。例如,.col-md-offset-4 类将 .col-md-4 元素向右侧偏移了4个列(column)的宽度。 <div class="row"><div class="col-md-4">.col-md-4</div><div class="col-md-4 col-md-offset-4">.col-md-4 .col-md-offset-4</div></div><div class="row"><div class="col-md-3 col-md-offset-3">.col-md-3 .col-md-offset-3</div><div class="col-md-3 col-md-offset-3">.col-md-3 .col-md-offset-3</div></div><div class="row"><div class="col-md-6 col-md-offset-3">.col-md-6 .col-md-offset-3</div></div> 2.6 列位置移动 通过使用 .col-md-push- 和 .col-md-pull- 类就可以很容易的改变列(column)的顺序。 <div class="row"><div class="col-md-9 col-md-push-3">.col-md-9 .col-md-push-3</div><div class="col-md-3 col-md-pull-9">.col-md-3 .col-md-pull-9</div></div> 3 排版 3.1 标题 HTML 中的所有标题标签,<h1> 到 <h6> 均可使用。另外,还提供了 .h1 到 .h6 类,为的是给内联(inline)属性的文本赋予标题的样式。 <h1>h1. Bootstrap heading</h1><h2>h2. Bootstrap heading</h2><h3>h3. Bootstrap heading</h3><h4>h4. Bootstrap heading</h4><h5>h5. Bootstrap heading</h5><h6>h6. Bootstrap heading</h6> 在标题内还可以包含 <small> 标签或赋予 .small 类的元素,可以用来标记副标题。 <h1>h1. Bootstrap heading <small>Secondary text</small></h1><h2>h2. Bootstrap heading <small>Secondary text</small></h2><h3>h3. Bootstrap heading <small>Secondary text</small></h3><h4>h4. Bootstrap heading <small>Secondary text</small></h4><h5>h5. Bootstrap heading <small>Secondary text</small></h5><h6>h6. Bootstrap heading <small>Secondary text</small></h6> 3.2 突出显示 通过添加 .lead 类可以让段落突出显示。 <p class="lead">...</p> 3.3 对齐 <p class="text-left">Left aligned text.</p><p class="text-center">Center aligned text.</p><p class="text-right">Right aligned text.</p><p class="text-justify">Justified text.</p><p class="text-nowrap">No wrap text.</p> 3.4 改变大小写 <p class="text-lowercase">Lowercased text.</p><p class="text-uppercase">Uppercased text.</p><p class="text-capitalize">Capitalized text.</p> 3.5 引用 <blockquote><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.</p></blockquote><blockquote><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.</p><footer>Someone famous in <cite title="Source Title">Source Title</cite></footer></blockquote><blockquote class="blockquote-reverse">...</blockquote> 3.6 列表 无样式列表 <ul class="list-unstyled"><li>...</li></ul> 内联列表 <ul class="list-inline"><li>...</li></ul> 水平排列的内联列表 <dl class="dl-horizontal"><dt>...</dt><dd>...</dd></dl> 4 代码 4.1 内联代码 通过 <code> 标签包裹内联样式的代码片段。 For example, <code><section></code> should be wrapped as inline. 4.2 用户输入 通过 <kbd> 标签标记用户通过键盘输入的内容。 To switch directories, type <kbd>cd</kbd> followed by the name of the directory.<br>To edit settings, press <kbd><kbd>ctrl</kbd> + <kbd>,</kbd></kbd> 4.3 代码块 多行代码可以使用 <pre> 标签。为了正确的展示代码,注意将尖括号做转义处理。 <pre><p>Sample text here...</p></pre> 还可以使用 .pre-scrollable 类,其作用是设置 max-height 为 350px ,并在垂直方向展示滚动条。 4.3 变量 通过 <var> 标签标记变量。 <var>y</var> = <var>m</var><var>x</var> + <var>b</var> 4.4 程序输出 通过 <samp> 标签来标记程序输出的内容。 <samp>This text is meant to be treated as sample output from a computer program.</samp> 5 表格 5.1 基本 为任意 <table> 标签添加 .table 类可以为其赋予基本的样式 <table class="table">...</table> 5.2 条纹状表格 <table class="table table-striped">...</table> 5.3 带边框的表格 <table class="table table-bordered">...</table> 5.4 鼠标悬停 <table class="table table-hover">...</table> 5.5 紧缩表格 <table class="table table-condensed">...</table> 5.6 状态类 通过这些状态类可以为行或单元格设置颜色。 Class 描述 .active 鼠标悬停在行或单元格上时所设置的颜色 .success 标识成功或积极的动作 .info 标识普通的提示信息或动作 .warning 标识警告或需要用户注意 .danger 标识危险或潜在的带来负面影响的动作 5.7 响应式表格 将任何 .table 元素包裹在 .table-responsive 元素内,即可创建响应式表格,其会在小屏幕设备上(小于768px)水平滚动。当屏幕大于 768px 宽度时,水平滚动条消失。 6 表单 6.1 基本实例 单独的表单控件会被自动赋予一些全局样式。所有设置了 .form-control 类的 <input>、<textarea> 和 <select> 元素都将被默认设置宽度属性为 width: 100%;。 将 label 元素和前面提到的控件包裹在 .form-group 中可以获得最好的排列。 <form><div class="form-group"><label for="exampleInputEmail1">Email address</label><input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email"></div><div class="form-group"><label for="exampleInputPassword1">Password</label><input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password"></div><div class="form-group"><label for="exampleInputFile">File input</label><input type="file" id="exampleInputFile"><p class="help-block">Example block-level help text here.</p></div><div class="checkbox"><label><input type="checkbox"> Check me out</label></div><button type="submit" class="btn btn-default">Submit</button></form> 6.2 内联表单 为 <form> 元素添加 .form-inline 类可使其内容左对齐并且表现为 inline-block 级别的控件。只适用于视口(viewport)至少在 768px 宽度时(视口宽度再小的话就会使表单折叠) 6.3 水平排列的表单 通过为表单添加 .form-horizontal 类,并联合使用 Bootstrap 预置的栅格类,可以将 label 标签和控件组水平并排布局。这样做将改变 .form-group 的行为,使其表现为栅格系统中的行(row),因此就无需再额外添加 .row 了 <form class="form-horizontal"><div class="form-group"><label for="inputEmail3" class="col-sm-2 control-label">Email</label><div class="col-sm-10"><input type="email" class="form-control" id="inputEmail3" placeholder="Email"></div></div><div class="form-group"><label for="inputPassword3" class="col-sm-2 control-label">Password</label><div class="col-sm-10"><input type="password" class="form-control" id="inputPassword3" placeholder="Password"></div></div><div class="form-group"><div class="col-sm-offset-2 col-sm-10"><div class="checkbox"><label><input type="checkbox"> Remember me</label></div></div></div><div class="form-group"><div class="col-sm-offset-2 col-sm-10"><button type="submit" class="btn btn-default">Sign in</button></div></div></form> 6.4 表单控件 输入框 包括大部分表单控件、文本输入域控件,还支持所有 HTML5 类型的输入控件: text、password、datetime、datetime-local、date、month、time、week、number、email、url、search、tel 和 color。 只有正确设置了 type 属性的输入控件才能被赋予正确的样式。 文本域 支持多行文本的表单控件。可根据需要改变 rows 属性。 多选和单选框 默认样式 <div class="checkbox"><label><input type="checkbox" value="">Option one is this and that—be sure to include why it's great</label></div><div class="checkbox disabled"><label><input type="checkbox" value="" disabled>Option two is disabled</label></div><div class="radio"><label><input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked>Option one is this and that—be sure to include why it's great</label></div><div class="radio"><label><input type="radio" name="optionsRadios" id="optionsRadios2" value="option2">Option two can be something else and selecting it will deselect option one</label></div><div class="radio disabled"><label><input type="radio" name="optionsRadios" id="optionsRadios3" value="option3" disabled>Option three is disabled</label></div> 内联单选和多选框 <label class="checkbox-inline"><input type="checkbox" id="inlineCheckbox1" value="option1"> 1</label><label class="checkbox-inline"><input type="checkbox" id="inlineCheckbox2" value="option2"> 2</label><label class="checkbox-inline"><input type="checkbox" id="inlineCheckbox3" value="option3"> 3</label><label class="radio-inline"><input type="radio" name="inlineRadioOptions" id="inlineRadio1" value="option1"> 1</label><label class="radio-inline"><input type="radio" name="inlineRadioOptions" id="inlineRadio2" value="option2"> 2</label><label class="radio-inline"><input type="radio" name="inlineRadioOptions" id="inlineRadio3" value="option3"> 3</label> 不带文本的Checkbox 和 radio <label><input type="checkbox" id="blankCheckbox" value="option1" aria-label="..."></label></div><div class="radio"><label><input type="radio" name="blankRadio" id="blankRadio1" value="option1" aria-label="..."></label></div> 下拉列表 <select class="form-control"><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option></select> 静态内容 如果需要在表单中将一行纯文本和 label 元素放置于同一行,为 <p> 元素添加 .form-control-static 类即可 <form class="form-horizontal"><div class="form-group"><label class="col-sm-2 control-label">Email</label><div class="col-sm-10"><p class="form-control-static">email@example.com</p></div></div><div class="form-group"><label for="inputPassword" class="col-sm-2 control-label">Password</label><div class="col-sm-10"><input type="password" class="form-control" id="inputPassword" placeholder="Password"></div></div></form> 帮助文字 <label class="sr-only" for="inputHelpBlock">Input with help text</label><input type="text" id="inputHelpBlock" class="form-control" aria-describedby="helpBlock">...<span id="helpBlock" class="help-block">A block of help text that breaks onto a new line and may extend beyond one line.</span> 校验状态 Bootstrap 对表单控件的校验状态,如 error、warning 和 success 状态,都定义了样式。使用时,添加 .has-warning、.has-error或 .has-success 类到这些控件的父元素即可。任何包含在此元素之内的 .control-label、.form-control 和 .help-block 元素都将接受这些校验状态的样式。 <div class="form-group has-success"><label class="control-label" for="inputSuccess1">Input with success</label><input type="text" class="form-control" id="inputSuccess1" aria-describedby="helpBlock2"><span id="helpBlock2" class="help-block">A block of help text that breaks onto a new line and may extend beyond one line.</span></div><div class="form-group has-warning"><label class="control-label" for="inputWarning1">Input with warning</label><input type="text" class="form-control" id="inputWarning1"></div><div class="form-group has-error"><label class="control-label" for="inputError1">Input with error</label><input type="text" class="form-control" id="inputError1"></div><div class="has-success"><div class="checkbox"><label><input type="checkbox" id="checkboxSuccess" value="option1">Checkbox with success</label></div></div><div class="has-warning"><div class="checkbox"><label><input type="checkbox" id="checkboxWarning" value="option1">Checkbox with warning</label></div></div><div class="has-error"><div class="checkbox"><label><input type="checkbox" id="checkboxError" value="option1">Checkbox with error</label></div></div> 添加额外的图标 你还可以针对校验状态为输入框添加额外的图标。只需设置相应的 .has-feedback 类并添加正确的图标即可 <div class="form-group has-success has-feedback"><label class="control-label" for="inputSuccess2">Input with success</label><input type="text" class="form-control" id="inputSuccess2" aria-describedby="inputSuccess2Status"><span class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span><span id="inputSuccess2Status" class="sr-only">(success)</span></div> 控件尺寸 通过 .input-lg 类似的类可以为控件设置高度,通过 .col-lg- 类似的类可以为控件设置宽度。 高度尺寸 创建大一些或小一些的表单控件以匹配按钮尺寸 <input class="form-control input-lg" type="text" placeholder=".input-lg"><input class="form-control" type="text" placeholder="Default input"><input class="form-control input-sm" type="text" placeholder=".input-sm"><select class="form-control input-lg">...</select><select class="form-control">...</select><select class="form-control input-sm">...</select> 水平排列的表单组的尺寸 通过添加 .form-group-lg 或 .form-group-sm 类,为 .form-horizontal 包裹的 label 元素和表单控件快速设置尺寸。 <form class="form-horizontal"><div class="form-group form-group-lg"><label class="col-sm-2 control-label" for="formGroupInputLarge">Large label</label><div class="col-sm-10"><input class="form-control" type="text" id="formGroupInputLarge" placeholder="Large input"></div></div><div class="form-group form-group-sm"><label class="col-sm-2 control-label" for="formGroupInputSmall">Small label</label><div class="col-sm-10"><input class="form-control" type="text" id="formGroupInputSmall" placeholder="Small input"></div></div></form> 7 按钮 7.1 可作为按钮使用的标签或元素 为 <a>、<button> 或 <input> 元素添加按钮类(button class)即可使用 Bootstrap 提供的样式 <a class="btn btn-default" href="" role="button">Link</a><button class="btn btn-default" type="submit">Button</button><input class="btn btn-default" type="button" value="Input"><input class="btn btn-default" type="submit" value="Submit"> 7.2 预定义样式 <!-- Standard button --><button type="button" class="btn btn-default">(默认样式)Default</button><!-- Provides extra visual weight and identifies the primary action in a set of buttons --><button type="button" class="btn btn-primary">(首选项)Primary</button><!-- Indicates a successful or positive action --><button type="button" class="btn btn-success">(成功)Success</button><!-- Contextual button for informational alert messages --><button type="button" class="btn btn-info">(一般信息)Info</button><!-- Indicates caution should be taken with this action --><button type="button" class="btn btn-warning">(警告)Warning</button><!-- Indicates a dangerous or potentially negative action --><button type="button" class="btn btn-danger">(危险)Danger</button><!-- Deemphasize a button by making it look like a link while maintaining button behavior --><button type="button" class="btn btn-link">(链接)Link</button> 7.3 尺寸 需要让按钮具有不同尺寸吗?使用 .btn-lg、.btn-sm 或 .btn-xs 就可以获得不同尺寸的按钮。 通过给按钮添加 .btn-block 类可以将其拉伸至父元素100%的宽度,而且按钮也变为了块级(block)元素。 7.4 激活状态 添加 .active 类 7.5 禁用状态 为 <button> 元素添加 disabled 属性,使其表现出禁用状态。 为基于 <a> 元素创建的按钮添加 .disabled 类。 8 图片 8.1 响应式图片 在 Bootstrap 版本 3 中,通过为图片添加 .img-responsive 类可以让图片支持响应式布局。其实质是为图片设置了 max-width: 100%;、 height: auto; 和 display: block; 属性,从而让图片在其父元素中更好的缩放。 如果需要让使用了 .img-responsive 类的图片水平居中,请使用 .center-block 类,不要用 .text-center <img src="..." class="img-responsive" alt="Responsive image"> 8.2 图片形状 <img src="..." alt="..." class="img-rounded"><img src="..." alt="..." class="img-circle"><img src="..." alt="..." class="img-thumbnail"> 9 辅助类 9.1 文本颜色 <p class="text-muted">...</p><p class="text-primary">...</p><p class="text-success">...</p><p class="text-info">...</p><p class="text-warning">...</p><p class="text-danger">...</p> 9.2 背景色 <p class="bg-primary">...</p><p class="bg-success">...</p><p class="bg-info">...</p><p class="bg-warning">...</p><p class="bg-danger">...</p> 9.3 三角符号 <span class="caret"></span> 9.4 浮动 <div class="pull-left">...</div><div class="pull-right">...</div> 9.5 让内容块居中 <div class="center-block">...</div> 9.6 清除浮动 通过为父元素添加 .clearfix 类可以很容易地清除浮动(float) <!-- Usage as a class --><div class="clearfix">...</div> 9.7 显示或隐藏内容 <div class="show">...</div><div class="hidden">...</div> 9.10 图片替换 使用 .text-hide 类或对应的 mixin 可以用来将元素的文本内容替换为一张背景图。 <h1 class="text-hide">Custom heading</h1> 10 响应式工具 10.1 不同视口下隐藏显示 .visible-xs- .visible-sm- .visible-md- .visible-lg- .hidden-xs .hidden-sm .hidden-md .hidden-lg.visible--block .visible--inline .visible--inline-block 10.2 打印类 .visible-print-block.visible-print-inline.visible-print-inline-block.hidden-print 打印机下隐藏 本篇文章为转载内容。原文链接:https://blog.csdn.net/m0_67155975/article/details/123351126。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-10-18 14:41:25
150
转载
转载文章
...blog.csdn.net/mypongo/article/details/38388381。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。 豆瓣 当当 亚马逊 China-pub 京东 中国图书网 淘宝 PDF样章试读微盘下载 微云下载 中英词汇索引表 本页内容 基本信息 作者:Jason Gregory (杰森.格雷戈瑞) 译者:Milo Yip(叶劲峰) 原书名:Game Engine Architecture 出版社:电子工业出版社 出版时间:2014-1-1 开本:16 页数:800 字数:1093400 ISBN:9787121222887 内容简介 《游戏引擎架构》同时涵盖游戏引擎软件开发的理论及实践,并对多方面的题目进行探讨。本书讨论到的概念及技巧实际应用于现实中的游戏工作室,如艺电及顽皮狗。虽然书中采用的例子通常依据一些专门的技术,但是讨论范围远超于某个引擎或API。文中的参考及引用也非常有用,可让读者继续深入游戏开发过程的任何特定方向。 《游戏引擎架构》为一个大学程度的游戏编程课程而编写,但也适合软件工程师、业余爱好者、自学游戏程序员,以及游戏产业的从业人员。通过阅读《游戏引擎架构》,资历较浅的游戏工程师可以巩固他们所学的游戏技术及引擎架构的知识,专注某一领域的资深程序员也能从本书更为全面的介绍中获益。 內容包括: 游戏开发中的大规模C++软件架构 游戏编程所需的数学 供调试、源代码控制及性能剖析的游戏开发工具 引擎基础系统、渲染、碰撞、物理、角色动画、游戏世界对象模型等引擎子系统 多平台游戏引擎 多处理器环境下的游戏编程 工作管道及游戏资产数据库 作者/译者简介 作者介绍:Jason Gregory在1994年开始任职专业软件工程师,自1999年3月开始在游戏产业中任职软件工程师。在圣迭哥Midway Home Entertainment公司开始游戏编程的他,为《疯狂飞行员(Freaky Flyers)》及《Crank the Weasel》开发PlayStation 2/Xbox上的动画系统。在2003年,他转到洛杉矶艺电,为《荣誉勋章:血战太平洋(Medal of Honor: Pacific Assault)》开发游戏引擎及游戏性技术,并在《荣誉勋章:空降神兵(Medal of Honor: Airborne)》中担任首席工程师。他现时是顽皮狗公司的通才程序员,为《神秘海域:德雷克船长的宝藏(Uncharted: Drake's Fortune)》及《神秘海域:纵横四海(Uncharted: Among Thieves)》开发引擎及游戏性软件。他也在南加州大学教授游戏技术的课程。 译者简介:叶劲峰(Milo Yip)从小自习编程,并爱好计算机图形学。上中学时兼职开发策略RPG《王子传奇》,该游戏在1995年于台湾发行。其后他获取了香港大学认知科学学士、香港中文大学系统工程及工程管理哲学硕士。毕业后在香港理工大学设计学院从事游戏引擎及相关技术的研发,职至项目主任。除发表学术文章外,也曾合著《DirectX9游戏编程实务》。2008年往上海育碧担任引擎工程师开发《美食从天而降(Cloudy with a Chance of Meatballs)》Xbox360/PS3/Wii/PC,2009年起于麻辣马开发《爱丽丝:疯狂回归(Alice: Madness Returns)》Xbox360/PS3/PC,2011年加入腾讯互动娱乐引擎技术中心担任专家工程师,所研发的技术已用于《斗战神》、《天涯明月刀》、《众神争霸》等项目中。 推荐序1 最初拿到《Game Engine Architecture》一书的英文版,是编辑侠少邮寄给我的打印版。他建议我接下翻译此书的合同。当时我正在杭州带领一个团队开发3D游戏引擎,我和我的同事都对这本书的内容颇有兴趣,两大本打印的英文书立刻在同事间传开。可惜那段时间个人精力顾及不来,把近千页的英文读物精读而后翻译成中文对个人的业余时间是个极大的挑战,不能担此翻译任务颇为遗憾。 不久以后听说Milo Yip(叶劲峰)已开始着手翻译,甚为欣喜。翻译此巨著,他一定是比我更合适的人选。我和Milo虽未曾蒙面,但神交已久。在网络上读过一些他的成长经历,和我颇为相似,心有戚戚。他对游戏3D实时渲染技术研究精深为我所不及,我们曾通过Google Talk讨论过许多技术问题,他都有独到的见解。翻译工作开始后,Milo是香港人,英文技术术语在香港的中文译法和大陆的有许多不同。但此书由大陆出版社出版,考虑到面对的读者主要是大陆程序员,Milo希望能更符合大陆程序员的用词习惯,所以在翻译一开始就通过Google Docs创建了协作页面,邀请大家共同探讨书中技术名词的中译名。从中我们可以一窥他作为译者的慎重。 三年之后,有幸在出版之前就拿到了完整的译本。这是一本用LaTeX精心排版的800页的电子书,我只花了一周时间,几乎是一口气读完。流畅的阅读享受,绝对不仅仅是因为原著精彩的内容,精美的版面和翔实的译注也加了不少分。 在阅读本书的过程中,我不只一次地获得共鸣。例如在第5章的内存管理系统的介绍中,作者介绍的几种游戏特有的内存管理方法我都曾在项目中用过,而这是第一次有书籍专门将这些方法详尽记录;又如第11章动画系统的介绍,我们也同样在3D引擎开发过程中改进原有动画片段混合方法的经历。虽然书中介绍的每个技术点,都可能可以在某篇论文,某本其他的书的章节,某篇网络blog上见过,但之前却无一本书可以把这些东西放在一起相互参照。对于从事游戏引擎开发的程序员来说,了解各种引擎在处理每个具体问题时的方案是相当重要的。而每种方案又各有利弊,即使不做引擎开发工作而是在某一特定游戏引擎上做游戏开发,从中也可以理解引擎的局限性以及可能的改进方法。尤其是第14章介绍的对游戏性相关系统的设计,各个开发人员几乎都是凭经验设计,很少见有书籍对这些做总结。对于基于渲染引擎做开发的游戏程序员,这是必须面对的工作,这一章会有很大的借鉴意义。 本书作者是业内资深的游戏引擎开发人,他所参于的《神秘海域》和《最后生还者》都是我的个人最爱。在玩游戏的过程中,作为游戏程序员的天性,自然会不断地猜想各个技术点是如何实现的,背后需要怎样的工具支持。能在书中一一得到印证是件特别开心的事情。作者反复强调代码实践的重要性,在书中遍布着C++代码。我不认为这些代码有直接取来使用的价值,但它们极大地帮助了读者理解书中的技术点。书中列出的顽皮狗工作室用lisp方言作为游戏配置脚本的范例也给我很大的启发,有了这些具体的代码示例以及作者本身的一线工程师背景,也让我确信书中那些关于主机游戏开发相关等,我所没有接触过的内容都也绝非泛泛而谈。 国内的游戏开发社区的壮大,主要是随最近十年的MMO风潮而生。而就在大型网络游戏在中国有些畸形发展,让这类游戏偏离电子游戏游戏性的趋势时,我们有幸迎来了为移动设备开发游戏的大潮。游戏开发的重心重新回到游戏性本身。我们更需要去借鉴单机游戏是如何为玩家带来更纯粹的游戏体验,我相信书中记录的各种技术点会变的更有帮助。 资深游戏开发及创业者 云风 @简悦云风 推荐序2 在我认识的许多游戏业开发同仁中,只有少数香港同胞,Milo Yip(叶劲峰)却正是这样一位给我印象非常深刻的优秀香港游戏开发者。我俩认识,是在Milo加入腾讯互动娱乐研发部引擎技术中心后,说来到现在也只是两年多时间。其间,他为人的谦逊务实,对待技术问题的严谨求真态度,对算法设计和性能优化的娴熟技术,都为人所称道。Milo一丝不苟的工作风格,甚至表现在对待技术文档排版这类事情上(Milo常执著地用LaTeX将技术文档排到完美),我想这一定是他在香港读大学、硕士及在香港理工大学的多媒体创新中心从事研究员,一贯沿袭至今的好作风。 我很高兴腾讯游戏有实力吸引到这样优秀的技术专家;即使在其已从上海迁回香港家中,依然选择到深圳腾讯互动娱乐总部工作。叶兄从此工作日每天早晚过关,来往香港和深圳两地,虽有舟车劳顿,但是兼顾了对家庭的照顾和在游戏引擎方面的专业研究,希望这样的状况是令他满意的。 认识叶兄当时,我便知道他在进行Jason Gregory所著《游戏引擎架构》一书的中译工作。因为自己从前也有业余翻译游戏开发有关书籍的经历,所以我能理解其中的辛苦和责任重大,对叶兄也更多一分钦佩。我以为,本书以及本书的中文读者最大的幸运便是,遇到叶兄这位对游戏有着如同对家对国般强烈责任感,犹如“游戏科学工作者”般的专业译者! 现在(2013年年末)无疑是游戏史上对独立游戏制作者最友好的年代。开发设备方便获得(相对过往仅由主机厂商授权才能获得专利开发设备,现在有一台智能手机和一台个人电脑就可以开发)、技术工具友好、调试过程简单方便,且互联网上有丰富的例程和开源代码参考,也有网上社区便于交流。很多爱好者能够很快地制作出可运行的游戏原型,其中一些也能发布到应用商店。 但是不全面掌握各方面知识,尤其是游戏引擎架构知识,往往只能停留在勉强修改、凑合重用别人提供的资源的应用程度上,难以做极限的性能改进,更妄谈革命式的架构创新。这样的程度是很难在成千上万的游戏中脱颖而出的。我们所认可的真正的游戏大作,必定是在某方面大幅超越用户期待的产品。为了打造这样的产品,游戏内容创作者(策划、美术等)需要“戴着镣铐跳舞”(在当前的机能下争取更多的创作自由度),而引擎架构合理的游戏可以经得起──也值得进行──反复优化,最终可以提供更多的自由度,这是大作出现的技术前提。 书的作者、译者、出版社的编者,加上读者,大家是因书而结缘的有缘人。因叶兄这本《游戏引擎架构》译著而在线上线下相识的读者们,你们是不是因“了解游戏引擎架构,从而制作/优化好游戏”这样的理想而结了缘呢? 亲爱的读者,愿你的游戏有一天因谜题巧妙绝伦、趣味超凡、虚拟世界气势磅礴、视觉效果逼真精美等专业因素取得业界褒奖,并得到玩家真诚的赞美。希望届时曾读叶兄这本《游戏引擎架构》译作的你,也可以回馈社会,回馈游戏开发的学习社区,帮助新人。希望你也可以建立微信公众号、博客等,或翻译游戏开发书籍,造福外语不好的读者,所以如果你的外语(英语、日语、韩语之于游戏行业比较重要)水平仍需精进,现在也可以同步加油了! 腾讯《天天爱消除》游戏团队Leader 沙鹰 @也是沙鹰 译序 数千年以来,艺术家们通过文学、绘画、雕塑、建筑、音乐、舞蹈、戏剧等传统艺术形式充实人类的精神层面。自20世纪中叶,计算机的普及派生出另一种艺术形式──电子游戏。游戏结合了上述传统艺术以及近代科技派生的其他艺术(如摄影、电影、动画),并且完全脱离了艺术欣赏这种单向传递的方式──游戏必然是互动的,“玩家”并不是“读者”、“观众”或“听众”,而是进入游戏世界、感知并对世界做出反应的参与者。 基于游戏的互动本质,游戏的制作通常比其他大众艺术复杂。商业游戏的制作通常需要各种人才的参与,而他们则需要依赖各种工具及科技。游戏引擎便是专门为游戏而设计的工具及科技集成。之所以称为引擎,如同交通工具中的引擎,提供了最核心的技术部分。因为复杂,研发成本高,人们不希望制作每款游戏(或车款)时都重新设计引擎,重用性是游戏引擎的一个重要设计目标。 然而,各游戏本身的性质以及平台的差异,使研发完全通用的游戏引擎变得极困难,甚至不可能。市面上出售的游戏引擎,有一些虽然已经达到很高的技术水平,但在商业应用中,很多时候还是需要因应个别游戏项目对引擎改造、整合、扩展及优化。因此,即使能使用市面上最好的商用引擎或自研引擎,我们仍需要理解当中的架构、各种机制和技术,并且分析及解决在制作中遇到的问题。这些也是译者曾任于上海两家工作室时的主要工作范畴。 选择翻译此著作,主要原因是在阅读中得到共鸣,并且能知悉一些知名游戏作品实际上所采用的方案。有感坊间大部分游戏开发书籍并不是由业内人士执笔,内容只足够应付一些最简单的游戏开发,欠缺宏观比较各种方案,技术与当今实际情况也有很大差距。而一些Gems类丛书虽然偶有好文章,但受形式所限欠缺系统性、全面性。难得本书原作者身为世界一流游戏工作室的资深游戏开发者(注1),在繁重的游戏开发工作外,还在大学教授游戏开发课程以至编写本著作。此外,从与内地同事的交流中,了解到许多从业者不愿意阅读外文书籍。为了普及知识及反馈业界社会,希望能尽绵力。 或许有些人以为本著作是针对单机/游戏机游戏的,并不适合国内以网游为主的环境。但译者认为这是一种误解,许多游戏本身所涉及的技术是具通用性的。例如游戏性相关的游戏性系统、场景管理、人工智能、物理模拟等部分,许多时候也会同时用于网游的前台和后台。现时,一些动作为主、非MMO的国内端游甚至会直接在后台运行传统意义上的游戏引擎。至于前台相关的技术,单机和端游的区别更少。此外,随着近年移动终端的兴起,其硬件性能已超越传统掌上游戏机,开发手游所需的技术与传统掌上游戏机并无太大差异。还可预料,现时单机/游戏机的一些较高级的架构及技术,将在不远的未来着陆移动终端平台。 译者认为,本书涵括游戏开发技术的方方面面,同时适合入门及经验丰富的游戏程序员。书名中的架构二字,并不单是给出一个系统结构图,而是描述每个子系统的需求、相关技术及与其他子系统的关系。对译者本人而言,本书的第11章(动画系统)及第14章(运行时游戏性基础系统)是本书特別精彩之处,含有许多少见于其他书籍的内容。而第10章(渲染引擎)由于是游戏引擎中的一个极大的部分,有限的篇幅可能未能覆盖广度及深度,推荐读者参考[1](注2),人工智能方面也需参考其他专著。 本译作采用LaTeX排版(注3),以Inkscape编译矢量图片。为了令阅读更流畅,内文中的网址都统一改以脚注标示。另外,由于现时游戏开发相关的文献以英文为主,而且游戏开发涉及的知识面很广,本译作尽量以括号形式保留英文术语。为了方便读者查找内容,在附录中增设中英文双向索引(索引条目与原著的不同)。 本人在香港成长学习及工作,至2008年才赴内地游戏工作室工作,不黯内地的中文写作及用字习惯,翻译中曾遇到不少困难。有幸得到出版社人员以及良师益友的帮助,才能完成本译作。特别感谢周筠老师支持本作的提案,并耐心地给予协助及鼓励。编辑张春雨老师和卢鸫翔老师,以及好友余晟给予了大量翻译上的知识及指导。也感谢游戏业界专家云风、大宝和Dave给予了许多宝贵意见。此书的翻译及排版工作比预期更花时间,感谢妻子及儿女们的体谅。此次翻译工作历时三年半,因工作及家庭事宜导致严重延误,唯有在翻译及排版工作上更尽心尽力,希望求得等待此译作的读者们谅解。无论是批评或建议,诚希阁下通过电邮miloyip@gmail.com、新浪微博、豆瓣等渠道不吝赐教。 叶劲峰(Milo Yip) 2013年10月 原作者是顽皮狗(Naughty Dog)《神秘海域(Uncharted)》系列的通才程序员、《最后生还者(The Last of Us)》的首席程序员,之前还曾在EA和Midway工作。 中括号表示引用附录中的参考文献。一些参考条目加入了其中译本的信息。 具体是使用CTEX套装,它是在MiKTeX的基础上增加中文的支持。 前言 最早的电子游戏完全由硬件构成,但微处理器(microprocessor)的高速发展完全改变了游戏的面貌。现在的游戏是在多用途的PC和专门的电子游戏主机(video game console)上玩的,凭借软件带来绝妙的游戏体验。从最初的游戏诞生至今已有半个世纪,但很多人仍然认为游戏是一个未成熟的产业。即使游戏可能是个年轻的产业,若仔细观察,也会发现它正在高速发展。 现时游戏已成为一个上百亿美元的产业,覆盖不同年龄、性别的广泛受众。 千变万化的游戏,可以分为从纸牌游戏到大型多人在线游戏(massively multiplayer online game,MMOG)等多个种类(category)和“类型(genre)”(注1),也可以运行在任何装有微芯片(microchip)的设备上 。你现在可以在PC、手机及多种特别为游戏而设计的手持/电视游戏主机上玩游戏。家用电视游戏通常代表最尖端的游戏科技,又由于它们是周期性地推出新版本,因此有游戏机“世代”(generation)的说法。最新一代(注2)的游戏机包括微软的Xbox 360和索尼的PlayStation 3,但一定不可忽视长盛不衰的PC,以及最近非常流行的任天堂Wii。 最近,剧增的下载式休闲游戏,使这个多样化的商业游戏世界变得更复杂。虽然如此,大型游戏仍然是一门大生意。今天的游戏平台非常复杂,有难以置信的运算能力,这使软件的复杂度得以进一步提升。所有这些先进的软件都需要由人创造出来,这导致团队人数增加,开发成本上涨。随着产业变得成熟,开发团队要寻求更好、更高效的方式去制作产品,可复用软件(reusable software)和中间件(middleware)便应运而生,以补偿软件复杂度的提升。 由于有这么多风格迥异的游戏及多种游戏平台,因此不可能存在单一理想的软件方案。然而,业界已经发展出一些模式 ,也有大量的潜在方案可供选择。现今的问题是如何找到一个合适的方案去迎合某个项目的需要。再进一步,开发团队必须考虑项目的方方面面,以及如何把各方面集成。对于一个崭新的游戏设计,鲜有可能找到一个完美搭配游戏设计各方面的软件包。 现时业界内的老手,入行时都是“开荒牛”。我们这代人很少是计算机科学专业出身(Matt的专业是航空工程、Jason的专业是系统设计工程),但现时很多学院已设有游戏开发的课程和学位。时至今日,为了获取有用的游戏开发信息,学生和开发者必须找到好的途径。对于高端的图形技术,从研究到实践都有大量高质量的信息。可是,这些信息经常不能直接应用到游戏的生产环境,或者没有一个生产级质量的实现。对于图形以外的游戏开发技术,市面上有一些所谓的入门书籍,没提及参考文献就描述很多内容细节,像自己发明的一样。这种做法根本没有用处,甚至经常带有不准确的内容。另一方面,市场上有一些高端的专门领域书籍,例如物理、碰撞、人工智能等。可是,这类书或者啰嗦到让你难以忍受,或者高深到让部分读者无法理解,又或者内容过于零散而难于融会贯通。有一些甚至会直接和某项技术挂钩,软硬件一旦改动,其内容就会迅速过时。 此外,互联网也是收集相关知识的绝佳工具。可是,除非你确实知道要找些什么,否则断链、不准确的资料、质量差的内容也会成为学习障碍。 好在,我们有Jason Gregory,他是一位拥有在顽皮狗(Naughty Dog)工作经验的业界老手,而顽皮狗是全球高度瞩目的游戏工作室之一。Jason在南加州大学教授游戏编程课程时,找不到概括游戏架构的教科书。值得庆幸的是,他承担了这个任务,填补了这个空白。 Jason把应用到实际发行游戏的生产级别知识,以及整个游戏开发的大局编集于本书。他凭经验,不仅融汇了游戏开发的概念和技巧,还用实际的代码示例及实现例子去说明怎样贯通知识来制作游戏。本书的引用及参考文献可以让读者更深入探索游戏开发过程的各方面。虽然例子经常是基于某些技术的,但是概念和技巧是用来实际创作游戏的,它们可以超越个别引擎或API的束缚。 本书是一本我们入行做游戏时想要的书。我们认为本书能让入门者增长知识,也能为有经验者开拓更大的视野。 Jeff Lander(注3) Matthew Whiting(注4) 译注:Genre一词在文学中为体裁。电影和游戏里通常译作类型。不同的游戏类型可见1.2节。 译注:按一般说法,2005年至今属于第7个游戏机世代。这3款游戏机的发行年份为Xbox 360(2005)、PlayStation 3(2006)、Wii(2006)。有关游戏机世代可参考维基百科。 译注:Jeff Lander现时为Darwin 3D公司的首席技术总监、Game Tech公司创始人,曾为艺电首席程序员、Luxoflux公司游戏性及动画技术程序员。 译注:Matthew Whiting现时为Wholesale Algorithms公司程序员,曾为Luxoflux公司首席软件工程师、Insomniac Games公司程序员。 序言 欢迎来到《游戏引擎架构》世界。本书旨在全面探讨典型商业游戏引擎的主要组件。游戏编程是一个庞大的主题,有许多内容需要讨论。不过相信你会发现,我们讨论的深度将足以使你充分理解本书所涵盖的工程理论及常用实践的方方面面。话虽如此,令人着迷的漫长游戏编程之旅其实才刚刚启程。与此相关的每项技术都包含丰富内容,本书将为你打下基础,并引领你进入更广阔的学习空间。 本书焦点在于游戏引擎的技术及架构。我们会探讨商业游戏引擎中,各个子系统的相关理论,以及实现这些理论所需要的典型数据结构、算法和软件接口。游戏引擎与游戏的界限颇为模糊。我们将把注意力集中在引擎本身,包括多个低阶基础系统(low-level foundation system)、渲染引擎(rendering engine)、碰撞系统(collision system)、物理模拟(physics simulation)、人物动画(character animation),及一个我称为游戏性基础层(gameplay foundation layer)的深入讨论。此层包括游戏对象模型(game object model)、世界编辑器(world editor)、事件系统(event system)及脚本系统(scripting system)。我们也将会接触游戏性编程(gameplay programming)的多个方面,包括玩家机制(player mechanics)、摄像机(camera)及人工智能(artificial intelligence,AI)。然而,这类讨论会被限制在游戏性系统和引擎接口范围。 本书可以作为大学中等级游戏程序设计中两到三门课程的教材。当然,本书也适合软件工程师、业余爱好者、自学的游戏程序员,以及游戏行业从业人员。通过阅读本书,资历较浅的游戏程序员可以巩固他们所学的游戏数学、引擎架构及游戏科技方面的知识。专注某一领域的资深程序员也能从本书更为全面的介绍中获益。 为了更好地学习本书内容,你需要掌握基本的面向对象编程概念并至少拥有一些C++编程经验。尽管游戏行业已经开始尝试使用一些新的、令人兴奋的编程语言,然而工业级的3D游戏引擎仍然是用C或C++编写的,任何认真的游戏程序员都应该掌握C++。我们将在第3章重温一些面向对象编程的基本原则,毫无疑问,你还会从本书学到一些C++的小技巧,不过C++的基础最好还是通过阅读[39]、[31]及[32]来获得。如果你对C++已经有点生疏,建议你在阅读本书的同时,最好能重温这几本或者类似书籍。如果你完全没有C++经验,在看本书之前,可以考虑先阅读[39]的前几章,或者尝试学习一些C++的在线教程。 学习编程技能最好的方法就是写代码。在阅读本书时,强烈建议你选择一些特别感兴趣的主题付诸实践。举例来说,如果你觉得人物动画很有趣,那么可以首先安装OGRE,并测试一下它的蒙皮动画示范。接着还可以尝试用OGRE实现本书谈及的一些动画混合技巧。下一步你可能会打算用游戏手柄控制人物在平面上行走。等你能玩转一些简单的东西了,就应该以此为基础,继续前进!之后可以转移到另一个游戏技术范畴,周而复始。这些项目是什么并不重要,重要的是你在实践游戏编程的艺术,而不是纸上谈兵。 游戏科技是一个活生生、会呼吸的家伙 ,永远不可能将之束缚于书本之上 。因此,附加的资源、勘误、更新、示例代码、项目构思等已经发到本书的网站。 目录 推荐序1 iii推荐序2 v译序 vii序言 xvii前言 xix致谢 xxi第一部分 基础 1第1章 导论 31.1 典型游戏团队的结构 41.2 游戏是什么 71.3 游戏引擎是什么 101.4 不同游戏类型中的引擎差异 111.5 游戏引擎概观 221.6 运行时引擎架构 271.7 工具及资产管道 46第2章 专业工具 532.1 版本控制 532.2 微软Visual Studio 612.3 剖析工具 782.4 内存泄漏和损坏检测 792.5 其他工具 80第3章 游戏软件工程基础 833.1 重温C++及最佳实践 833.2 C/C++的数据、代码及内存 903.3 捕捉及处理错误 118第4章 游戏所需的三维数学 1254.1 在二维中解决三维问题 1254.2 点和矢量 1254.3 矩阵 1394.4 四元数 1564.5 比较各种旋转表达方式 1644.6 其他数学对象 1684.7 硬件加速的SIMD运算 1734.8 产生随机数 180第二部分 低阶引擎系统 183第5章 游戏支持系统 1855.1 子系统的启动和终止 1855.2 内存管理 1935.3 容器 2085.4 字符串 2255.5 引擎配置 234第6章 资源及文件系统 2416.1 文件系统 2416.2 资源管理器 251第7章 游戏循环及实时模拟 2777.1 渲染循环 2777.2 游戏循环 2787.3 游戏循环的架构风格 2807.4 抽象时间线 2837.5 测量及处理时间 2857.6 多处理器的游戏循环 2967.7 网络多人游戏循环 304第8章 人体学接口设备(HID) 3098.1 各种人体学接口设备 3098.2 人体学接口设备的接口技术 3118.3 输入类型 3128.4 输出类型 3168.5 游戏引擎的人体学接口设备系统 3188.6 人体学接口设备使用实践 332第9章 调试及开发工具 3339.1 日志及跟踪 3339.2 调试用的绘图功能 3379.3 游戏内置菜单 3449.4 游戏内置主控台 3479.5 调试用摄像机和游戏暂停 3489.6 作弊 3489.7 屏幕截图及录像 3499.8 游戏内置性能剖析 3499.9 游戏内置的内存统计和泄漏检测 356第三部分 图形及动画 359第10章 渲染引擎 36110.1 采用深度缓冲的三角形光栅化基础 36110.2 渲染管道 40410.3 高级光照及全局光照 42610.4 视觉效果和覆盖层 43810.5 延伸阅读 446第11章 动画系统 44711.1 角色动画的类型 44711.2 骨骼 45211.3 姿势 45411.4 动画片段 45911.5 蒙皮及生成矩阵调色板 47111.6 动画混合 47611.7 后期处理 49311.8 压缩技术 49611.9 动画系统架构 50111.10 动画管道 50211.11 动作状态机 51511.12 动画控制器 535第12章 碰撞及刚体动力学 53712.1 你想在游戏中加入物理吗 53712.2 碰撞/物理中间件 54212.3 碰撞检测系统 54412.4 刚体动力学 56912.5 整合物理引擎至游戏 60112.6 展望:高级物理功能 616第四部分 游戏性 617第13章 游戏性系统简介 61913.1 剖析游戏世界 61913.2 实现动态元素:游戏对象 62313.3 数据驱动游戏引擎 62613.4 游戏世界编辑器 627第14章 运行时游戏性基础系统 63714.1 游戏性基础系统的组件 63714.2 各种运行时对象模型架构 64014.3 世界组块的数据格式 65714.4 游戏世界的加载和串流 66314.5 对象引用与世界查询 67014.6 实时更新游戏对象 67614.7 事件与消息泵 69014.8 脚本 70714.9 高层次的游戏流程 726第五部分 总结 727第15章 还有更多内容吗 72915.1 一些未谈及的引擎系统 72915.2 游戏性系统 730参考文献 733中文索引 737英文索引 755 参考文献 Tomas Akenine-Moller, Eric Haines, and Naty Hoffman. Real-Time Rendering (3rd Edition). Wellesley, MA: A K Peters, 2008. 中译本:《实时计算机图形学(第2版)》,普建涛译,北京大学出版社,2004. Andrei Alexandrescu. Modern C++ Design: Generic Programming and Design Patterns Applied. Resding, MA: Addison-Wesley, 2001. 中译本:《C++设计新思维:泛型编程与设计模式之应用》,侯捷/於春景译,华中科技大学出版社,2003. Grenville Armitage, Mark Claypool and Philip Branch. Networking and Online Games: Understanding and Engineering Multiplayer Internet Games. New York, NY: John Wiley and Sons, 2006. James Arvo (editor). Graphics Gems II. San Diego, CA: Academic Press, 1991. Grady Booch, Robert A. Maksimchuk, Michael W. Engel, Bobbi J. Young, Jim Conallen, and Kelli A. Houston. Object-Oriented Analysis and Design with Applications (3rd Edition). Reading, MA: Addison-Wesley, 2007. 中译本:《面向对象分析与设计(第3版)》,王海鹏/潘加宇译,电子工业出版社,2012. Mark DeLoura (editor). Game Programming Gems. Hingham, MA: Charles River Media, 2000. 中译本:《游戏编程精粹 1》, 王淑礼译,人民邮电出版社,2004. Mark DeLoura (editor). Game Programming Gems 2. Hingham, MA: Charles River Media, 2001. 中译本:《游戏编程精粹 2》,袁国忠译,人民邮电出版社,2003. Philip Dutré, Kavita Bala and Philippe Bekaert. Advanced Global Illumination (2nd Edition). Wellesley, MA: A K Peters, 2006. David H. Eberly. 3D Game Engine Design: A Practical Approach to Real-Time Computer Graphics. San Francisco, CA: Morgan Kaufmann, 2001. 国内英文版:《3D游戏引擎设计:实时计算机图形学的应用方法(第2版)》,人民邮电出版社,2009. David H. Eberly. 3D Game Engine Architecture: Engineering Real-Time Applications with Wild Magic. San Francisco, CA: Morgan Kaufmann, 2005. David H. Eberly. Game Physics. San Francisco, CA: Morgan Kaufmann, 2003. Christer Ericson. Real-Time Collision Detection. San Francisco, CA: Morgan Kaufmann, 2005. 中译本:《实时碰撞检测算法技术》,刘天慧译,清华大学出版社,2010. Randima Fernando (editor). GPU Gems: Programming Techniques, Tips and Tricks for Real-Time Graphics. Reading, MA: Addison-Wesley, 2004. 中译本:《GPU精粹:实时图形编程的技术、技巧和技艺》,姚勇译,人民邮电出版社,2006. James D. Foley, Andries van Dam, Steven K. Feiner, and John F. Hughes. Computer Graphics: Principles and Practice in C (2nd Edition). Reading, MA: Addison-Wesley, 1995. 中译本:《计算机图形学原理及实践──C语言描述》,唐泽圣/董士海/李华/吴恩华/汪国平译,机械工业出版社,2004. Grant R. Fowles and George L. Cassiday. Analytical Mechanics (7th Edition). Pacific Grove, CA: Brooks Cole, 2005. John David Funge. AI for Games and Animation: A Cognitive Modeling Approach. Wellesley, MA: A K Peters, 1999. Erich Gamma, Richard Helm, Ralph Johnson, and John M. Vlissiddes. Design Patterns: Elements of Reusable Object-Oriented Software. Reading, MA: Addison-Wesley, 1994. 中译本:《设计模式:可复用面向对象软件的基础》,李英军/马晓星/蔡敏/刘建中译,机械工业出版社,2005. Andrew S. Glassner (editor). Graphics Gems I. San Francisco, CA: Morgan Kaufmann, 1990. Paul S. Heckbert (editor). Graphics Gems IV. San Diego, CA: Academic Press, 1994. Maurice Herlihy, Nir Shavit. The Art of Multiprocessor Programming. San Francisco, CA: Morgan Kaufmann, 2008. 中译本:《多处理器编程的艺术》,金海/胡侃译,机械工业出版社,2009. Roberto Ierusalimschy, Luiz Henrique de Figueiredo and Waldemar Celes. Lua 5.1 Reference Manual. Lua.org, 2006. Roberto Ierusalimschy. Programming in Lua, 2nd Edition. Lua.org, 2006. 中译本:《Lua程序设计(第2版)》,周惟迪译,电子工业出版社,2008. Isaac Victor Kerlow. The Art of 3-D Computer Animation and Imaging (2nd Edition). New York, NY: John Wiley and Sons, 2000. David Kirk (editor). Graphics Gems III. San Francisco, CA: Morgan Kaufmann, 1994. Danny Kodicek. Mathematics and Physics for Game Programmers. Hingham, MA: Charles River Media, 2005. Raph Koster. A Theory of Fun for Game Design. Phoenix, AZ: Paraglyph, 2004. 中译本:《快乐之道:游戏设计的黄金法则》,姜文斌等译,百家出版社,2005. John Lakos. Large-Scale C++ Software Design. Reading, MA: Addison-Wesley, 1995. 中译本:《大规模C++程序设计》,李师贤/明仲/曾新红/刘显明译,中国电力出版社,2003. Eric Lengyel. Mathematics for 3D Game Programming and Computer Graphics (2nd Edition). Hingham, MA: Charles River Media, 2003. Tuoc V. Luong, James S. H. Lok, David J. Taylor and Kevin Driscoll. Internationalization: Developing Software for Global Markets. New York, NY: John Wiley & Sons, 1995. Steve Maguire. Writing Solid Code: Microsoft's Techniques for Developing Bug Free C Programs. Bellevue, WA: Microsoft Press, 1993. 国内英文版:《编程精粹:编写高质量C语言代码》,人民邮电出版社,2009. Scott Meyers. Effective C++: 55 Specific Ways to Improve Your Programs and Designs (3rd Edition). Reading, MA: Addison-Wesley, 2005. 中译本:《Effective C++:改善程序与设计的55个具体做法(第3版)》,侯捷译,电子工业出版社,2011. Scott Meyers. More Effective C++: 35 New Ways to Improve Your Programs and Designs. Reading, MA: Addison-Wesley, 1996. 中译本:《More Effective C++:35个改善编程与设计的有效方法(中文版)》,侯捷译,电子工业出版社,2011. Scott Meyers. Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library. Reading, MA: Addison-Wesley, 2001. 中译本:《Effective STL:50条有效使用STL的经验》,潘爱民/陈铭/邹开红译,电子工业出版社,2013. Ian Millington. Game Physics Engine Development. San Francisco, CA: Morgan Kaufmann, 2007. Hubert Nguyen (editor). GPU Gems 3. Reading, MA: Addison-Wesley, 2007. 中译本:《GPU精粹3》,杨柏林/陈根浪/王聪译,清华大学出版社,2010. Alan W. Paeth (editor). Graphics Gems V. San Francisco, CA: Morgan Kaufmann, 1995. C. Michael Pilato, Ben Collins-Sussman, and Brian W. Fitzpatrick. Version Control with Subversion (2nd Edition). Sebastopol , CA: O'Reilly Media, 2008. (常被称作“The Subversion Book”,线上版本.) 国内英文版:《使用Subversion进行版本控制》,开明出版社,2009. Matt Pharr (editor). GPU Gems 2: Programming Techniques for High-Performance Graphics and General-Purpose Computation. Reading, MA: Addison-Wesley, 2005. 中译本:《GPU精粹2:高性能图形芯片和通用计算编程技巧》,龚敏敏译,清华大学出版社,2007. Bjarne Stroustrup. The C++ Programming Language, Special Edition (3rd Edition). Reading, MA: Addison-Wesley, 2000. 中译本《C++程序设计语言(特别版)》,裘宗燕译,机械工业出版社,2010. Dante Treglia (editor). Game Programming Gems 3. Hingham, MA: Charles River Media, 2002. 中译本:《游戏编程精粹3》,张磊译,人民邮电出版社,2003. Gino van den Bergen. Collision Detection in Interactive 3D Environments. San Francisco, CA: Morgan Kaufmann, 2003. Alan Watt. 3D Computer Graphics (3rd Edition). Reading, MA: Addison Wesley, 1999. James Whitehead II, Bryan McLemore and Matthew Orlando. World of Warcraft Programming: A Guide and Reference for Creating WoW Addons. New York, NY: John Wiley & Sons, 2008. 中译本:《魔兽世界编程宝典:World of Warcraft Addons完全参考手册》,杨柏林/张卫星/王聪译,清华大学出版社,2010. Richard Williams. The Animator's Survival Kit. London, England: Faber & Faber, 2002. 中译本:《原动画基础教程:动画人的生存手册》,邓晓娥译,中国青年出版社,2006. 勘误 第1次印册(2014年2月) P.xviii: 译注中 Wholesale Algoithms -> Wholesale Algorithms P.10: 最后一段第一行 微软的媒体播放器 -> 微软的Windows Media Player (多谢读者OpenGPU来函指正) P.15: 1.4.3节第三点 按妞 -> 按钮 (多谢读者一个小小凡人来函指正) P.40: 正文最后一行 按扭 -> 按钮 P.50: 1.7.8节第二节第一行 同是 -> 同时 (多谢读者czfdd来函指正) P.98: 代码 writeExampleStruct(Example& ex, Stream& ex) 中 Stream& ex -> Stream& stream (多谢读者Snow来函指正) P.106: 第一段中有六处 BBS -> BSS,最后一段代码的注释也有同样错误 (多谢读者trout来函指正) P.119: 译注中 软体工程 -> 软件工程 (多谢读者Snow来函指正) P.214: 正文第一段有两处 虚内存 -> 虚拟内存 (多谢读者Snow来函指正) P.216: 脚注24应标明为译注 (多谢读者Snow来函指正) P.221: 第一段代码的第二个断言应为 ASSERT(link.m_pPrev != NULL); (多谢读者Snow来函指正) P.230: 5.4.4.1节 第二段 软体 -> 软件 P.286: 脚注4应标明为译注 (多谢读者Snow来函指正) P.322: 第二段 按扭事件字 -> 按钮事件 P.349: 9.8节第二段第二行两处 部析器 -> 剖析器 (多谢读者Snow来函指正) P.738-572: 双数页页眉 参考文献 -> 中文索引 P.755-772: 双数页页眉 参考文献 -> 英文索引 P.755: kd tree项应归入K而不是Symbols 以上的错误已于第2次印册中修正。 第2次印册及之前 P.11: 第四行 细致程度 -> 层次细节 (这是level-of-detail/LOD的内地通译,多谢读者OpenGPU来函指正) P.12: 正文第一段及图1.2标题 使命之唤 -> 使命召唤 (多谢读者OpenGPU来函指正) P.12: 正文第一段 战栗时空 -> 半条命 (多谢读者OpenGPU来函指正) P.16: 第一点 表面下散射 -> 次表面散射 (多谢读者OpenGPU来函指正) P.17: 1.4.4节第五行 次文化 -> 亚文化 (此译法在内地更常用。多谢读者OpenGPU来函提示) P.22: 战栗时空 -> 半条命 P.24: 战栗时空2 -> 半条命2 P.34: 1.6.8.2节第一行 提呈 -> 提交 (这术语在本书其他地方都写作提交。多谢读者OpenGPU来函提示) P.35: 第七行 提呈 -> 提交 (这术语在本书其他地方都写作提交。多谢读者OpenGPU来函提示) P.50: 战栗时空2 -> 半条命2 P.365: 第四段第二行: 细致程度 -> 层次细节 P.441: 10.4.3.2节第三行 细致程度 -> 层次细节 P.494: sinusiod -> sinusoid (多谢读者OpenGPU来函指正) P.511: 11.10.4节第一行 谈入 -> 淡入 (多谢读者Snow来函指正) P.541: 战栗时空2 -> 半条命2 P.627: 战栗时空2 -> 半条命2 P.654: 第二行 建康值 -> 血量 (原来是改正错别字,但译者发现应改作前后统一使用的“血量”。多谢读者Snow来函指正) P.692: 第二行 内部分式 -> 内部方式 (多谢读者Snow来函指正) P.696: 14.7.6节第四行 不设实际 -> 不切实际 (多谢读者Snow来函指正) 以上的错误已于第3次印册中修正。 其他意见 P.220: 正文第一段 m_root.m_pElement 和 P.218 第一段代码中的 m_pElem 不统一。原文有此问题,但因为它们是不同的struct,暂不列作错误。 (多谢读者Snow来函提示) P.331: 8.5.8节第二段中 “反覆”较常见的写法为“反复”,但前者也是正确的,暂不列作错误。 (多谢读者Snow来函提示) P.390: 10.1.3.3节静态光照第二段中“取而代之,我们会使用一张光照纹理贴到所有受光源影响范围内的物体上。这样做能令动态物体经过光源时得到正确的光照。” 后面的一句与前句好像难以一起理解。译者认为,作者应该是指,使用同一静态光源去为静态物件生成光照纹理,以及用于动态对象的光照,能使两者的效果维持一致性。译者会考虑对译文作出改善或加入译注解译。(多谢读者店残来函查询) P.689: 第五行 并行处理世代 -> 并行处理时代 是对era较准确的翻译。 (多谢读者Snow来函提示) 本篇文章为转载内容。原文链接:https://blog.csdn.net/mypongo/article/details/38388381。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-02-12 23:04:05
327
转载
转载文章
...blog.csdn.net/slzlincent/article/details/104364909。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。 s_msckf:采用多状态约束的双目vio系统 !!!注意imuCallback:接收IMU数据,将IMU数据存到imu_msg_buffer中,这里只会利用开头200帧IMU数据进行静止初始化,不做其他处理。featureCallback:接收双目特征,进行后端处理。利用IMU进行EKF Propagation,利用双目特征进行EKF Update。静止初始化(initializeGravityAndBias):将前200帧加速度和角速度求平均, 平均加速度的模值g作为重力加速度, 平均角速度作为陀螺仪的bias, 计算重力向量(0,0,-g)和平均加速度之间的夹角(旋转四元数), 标定初始时刻IMU系与world系之间的夹角. 因此MSCKF要求前200帧IMU是静止不动的 sudo apt-get install libsuitesparse-devcd ~/catkin_ws/srcgit clone KumarRobotics/msckf_viocd ..catkin_make --pkg msckf_vio --cmake-args -DCMAKE_BUILD_TYPE=Release激活环境变量很关键source /devel/setup.bashroslaunch msckf_vio msckf_vio_euroc.launch注意文件路径rosrun rviz rviz -d rviz/rviz_euroc_config.rviz (改成你自己的rviz文件)rosbag play ~/data/euroc/MH_04_difficult.bag(改成你自己的rosbag文件) 可以看到,s_msckf的输出是没有轨迹的,可以增加如下脚本,将/odom存为/path,在rviz订阅即可可视化轨迹 脚本来自其issue:https://github.com/KumarRobotics/msckf_vio/issues/13 !/usr/bin/env pythonimport rospyfrom nav_msgs.msg import Odometry, Pathfrom geometry_msgs.msg import PoseStampedclass OdomToPath:def __init__(self):self.path_pub = rospy.Publisher('/slz_path', Path, latch=True, queue_size=10)self.odom_sub = rospy.Subscriber('/firefly_sbx/vio/odom', Odometry, self.odom_cb, queue_size=10)self.path = Path()def odom_cb(self, msg):cur_pose = PoseStamped()cur_pose.header = msg.headercur_pose.pose = msg.pose.poseself.path.header = msg.headerself.path.poses.append(cur_pose)self.path_pub.publish(self.path)if __name__ == '__main__':rospy.init_node('odom_to_path')odom_to_path = OdomToPath()rospy.spin() 或者增加一个draw_path的功能包: cpp为: include <stdio.h>include <stdlib.h>include <unistd.h>include <ros/ros.h>include <ros/console.h>include <nav_msgs/Path.h>include <std_msgs/String.h>include <nav_msgs/Odometry.h>include <geometry_msgs/Quaternion.h>include <geometry_msgs/PoseStamped.h>nav_msgs::Path path;ros::Publisher path_pub;ros::Subscriber odomSub;ros::Subscriber odom_raw_Sub;void odomCallback(const nav_msgs::Odometry::ConstPtr& odom){geometry_msgs::PoseStamped this_pose_stamped;this_pose_stamped.header= odom->header;this_pose_stamped.pose = odom->pose.pose;//this_pose_stamped.pose.position.x = odom->pose.pose.position.x;//this_pose_stamped.pose.position.y = odom->pose.pose.position.y;//this_pose_stamped.pose.orientation = odom->pose.pose.orientation;//this_pose_stamped.header.stamp = ros::Time::now();//this_pose_stamped.header.frame_id = "world";//frame_id 是消息中与数据相关联的参考系id,例如在在激光数据中,frame_id对应激光数据采集的参考系 path.header= this_pose_stamped.header;path.poses.push_back(this_pose_stamped);//path.header.stamp = ros::Time::now();//path.header.frame_id= "world";path_pub.publish(path);//printf("path_pub ");//printf("odom %.3lf %.3lf\n",odom->pose.pose.position.x,odom->pose.pose.position.y);}int main (int argc, char argv){ros::init (argc, argv, "showpath");ros::NodeHandle ph;path_pub = ph.advertise<nav_msgs::Path>("/trajectory",10, true);odomSub = ph.subscribe<nav_msgs::Odometry>("/firefly_sbx/vio/odom", 10, odomCallback);//ros::Rate loop_rate(50);while (ros::ok()){ros::spinOnce(); // check for incoming messages//loop_rate.sleep();}return 0;} cmakelists.txt cmake_minimum_required(VERSION 2.8.3)project(draw) Compile as C++11, supported in ROS Kinetic and newer add_compile_options(-std=c++11) Find catkin macros and libraries if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz) is used, also find other catkin packagesfind_package(catkin REQUIRED COMPONENTSgeometry_msgsroscpprospystd_msgsmessage_generation)catkin_package( INCLUDE_DIRS include LIBRARIES learning_communicationCATKIN_DEPENDS geometry_msgs roscpp rospy std_msgs message_runtime DEPENDS system_lib) Build include_directories(include${catkin_INCLUDE_DIRS})add_executable(draw_path draw.cpp)target_link_libraries(draw_path ${catkin_LIBRARIES}) package.xml <?xml version="1.0"?><package><name>draw</name><version>0.0.0</version><description>The learning_communication package</description><!-- One maintainer tag required, multiple allowed, one person per tag --><!-- Example: --><!-- <maintainer email="jane.doe@example.com">Jane Doe</maintainer> --><maintainer email="hcx@todo.todo">hcx</maintainer><!-- One license tag required, multiple allowed, one license per tag --><!-- Commonly used license strings: --><!-- BSD, MIT, Boost Software License, GPLv2, GPLv3, LGPLv2.1, LGPLv3 --><license>TODO</license><!-- Url tags are optional, but multiple are allowed, one per tag --><!-- Optional attribute type can be: website, bugtracker, or repository --><!-- Example: --><!-- <url type="website">http://wiki.ros.org/learning_communication</url> --><!-- Author tags are optional, multiple are allowed, one per tag --><!-- Authors do not have to be maintainers, but could be --><!-- Example: --><!-- <author email="jane.doe@example.com">Jane Doe</author> --><!-- The _depend tags are used to specify dependencies --><!-- Dependencies can be catkin packages or system dependencies --><!-- Examples: --><!-- Use build_depend for packages you need at compile time: --><!-- <build_depend>message_generation</build_depend> --><!-- Use buildtool_depend for build tool packages: --><!-- <buildtool_depend>catkin</buildtool_depend> --><!-- Use run_depend for packages you need at runtime: --><!-- <run_depend>message_runtime</run_depend> --><!-- Use test_depend for packages you need only for testing: --><!-- <test_depend>gtest</test_depend> --><buildtool_depend>catkin</buildtool_depend><build_depend>geometry_msgs</build_depend><build_depend>roscpp</build_depend><build_depend>rospy</build_depend><build_depend>std_msgs</build_depend><run_depend>geometry_msgs</run_depend><run_depend>roscpp</run_depend><run_depend>rospy</run_depend><run_depend>std_msgs</run_depend><build_depend>message_generation</build_depend><run_depend>message_runtime</run_depend><!-- The export tag contains other, unspecified, tags --><export><!-- Other tools can request additional information be placed here --></export></package> vins_fusion: 双目vio等多系统 mkdir -p vins-catkin_ws/srccd vins-catkin_ws/srcgit clone https://github.com/HKUST-Aerial-Robotics/VINS-Fusion.gitcd ..catkin_makesource devel/setup.bash按照readme 3.1 Monocualr camera + IMUroslaunch vins vins_rviz.launchrosrun vins vins_node ~/catkin_ws/src/VINS-Fusion/config/euroc/euroc_mono_imu_config.yaml (optional) rosrun loop_fusion loop_fusion_node ~/catkin_ws/src/VINS-Fusion/config/euroc/euroc_mono_imu_config.yaml rosbag play YOUR_DATASET_FOLDER/MH_01_easy.bag 3.2 Stereo cameras + IMUroslaunch vins vins_rviz.launchrosrun vins vins_node ~/catkin_ws/src/VINS-Fusion/config/euroc/euroc_stereo_imu_config.yaml (optional) rosrun loop_fusion loop_fusion_node ~/catkin_ws/src/VINS-Fusion/config/euroc/euroc_stereo_imu_config.yaml rosbag play YOUR_DATASET_FOLDER/MH_01_easy.bag 3.3 Stereo camerasroslaunch vins vins_rviz.launchrosrun vins vins_node ~/catkin_ws/src/VINS-Fusion/config/euroc/euroc_stereo_config.yaml (optional) rosrun loop_fusion loop_fusion_node ~/catkin_ws/src/VINS-Fusion/config/euroc/euroc_stereo_config.yaml rosbag play YOUR_DATASET_FOLDER/MH_01_easy.bag<img src="https://github.com/HKUST-Aerial-Robotics/VINS-Fusion/blob/master/support_files/image/euroc.gif" width = 430 height = 240 /> 4. KITTI Example 4.1 KITTI Odometry (Stereo)Download [KITTI Odometry dataset](http://www.cvlibs.net/datasets/kitti/eval_odometry.php) to YOUR_DATASET_FOLDER. Take sequences 00 for example,Open two terminals, run vins and rviz respectively. (We evaluated odometry on KITTI benchmark without loop closure funtion)roslaunch vins vins_rviz.launch(optional) rosrun loop_fusion loop_fusion_node ~/catkin_ws/src/VINS-Fusion/config/kitti_odom/kitti_config00-02.yamlrosrun vins kitti_odom_test ~/catkin_ws/src/VINS-Fusion/config/kitti_odom/kitti_config00-02.yaml YOUR_DATASET_FOLDER/sequences/00/ 4.2 KITTI GPS Fusion (Stereo + GPS)Download [KITTI raw dataset](http://www.cvlibs.net/datasets/kitti/raw_data.php) to YOUR_DATASET_FOLDER. Take [2011_10_03_drive_0027_synced](https://s3.eu-central-1.amazonaws.com/avg-kitti/raw_data/2011_10_03_drive_0027/2011_10_03_drive_0027_sync.zip) for example.Open three terminals, run vins, global fusion and rviz respectively. Green path is VIO odometry; blue path is odometry under GPS global fusion.roslaunch vins vins_rviz.launchrosrun vins kitti_gps_test ~/catkin_ws/src/VINS-Fusion/config/kitti_raw/kitti_10_03_config.yaml YOUR_DATASET_FOLDER/2011_10_03_drive_0027_sync/ rosrun global_fusion global_fusion_node<img src="https://github.com/HKUST-Aerial-Robotics/VINS-Fusion/blob/master/support_files/image/kitti.gif" width = 430 height = 240 /> 5. VINS-Fusion on car demonstrationDownload [car bag](https://drive.google.com/open?id=10t9H1u8pMGDOI6Q2w2uezEq5Ib-Z8tLz) to YOUR_DATASET_FOLDER.Open four terminals, run vins odometry, visual loop closure(optional), rviz and play the bag file respectively. Green path is VIO odometry; red path is odometry under visual loop closure.roslaunch vins vins_rviz.launchrosrun vins vins_node ~/catkin_ws/src/VINS-Fusion/config/vi_car/vi_car.yaml (optional) rosrun loop_fusion loop_fusion_node ~/catkin_ws/src/VINS-Fusion/config/vi_car/vi_car.yaml rosbag play YOUR_DATASET_FOLDER/car.bag 本篇文章为转载内容。原文链接:https://blog.csdn.net/slzlincent/article/details/104364909。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-09-13 20:38:56
310
转载
转载文章
...blog.csdn.net/qq_27717967/article/details/79167605。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。 1、插件说明 jstree官方地址:https://www.jstree.com bootstrap官方地址:https://v3.bootcss.com font-awesome官方地址:http://www.fontawesome.com.cn/faicons/ github项目地址:https://github.com/chengchuanqiang/jstreeDemo 2、jstreedemo主要文件 2.1、html页面代码 <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>jstree demo</title><link rel="stylesheet" href="jstree/dist/themes/default/style.min.css" /><link rel="stylesheet" type="text/css" href="bootstrap-3.3.7-dist/css/bootstrap.min.css" /> <link rel="stylesheet" type="text/css" href="font-awesome-4.7.0/css/font-awesome.min.css" /> </head><body><div class="container"> <div class="row" style="height: 100px;"></div><div class="row"><div > <button class="btn btn-info" onclick="node_create()"> 新增 </button><button class="btn btn-info" onclick="node_rename()"> 编辑</button><button class="btn btn-info" onclick="node_delete()"> 删除</button></div></div><div class="row" style="height: 5px;"></div><div class="row"> <div class="col-md-3"> <!-- 描述:搜索框 --> <div class="input-group row"> <span class="input-group-addon" id="basic-addon1"><i class="glyphicon glyphicon-screenshot"></i></span> <input type="text" class="form-control" placeholder="请输入功能名称..." id="search_ay" aria-describedby="basic-addon1"> </div> <!--描述:jstree 树形菜单容器--> <div id="jstree_demo_div" class="row"> </div> </div> <div lass="col-md-9"> <button class="btn btn-tab" var='json/data.json'>data.json</button> <!--点击切换资源--> <button class="btn btn-tab" var='json/data2.json'>data2.json</button> <!--点击切换资源--> <button class="btn refresh "><i class="glyphicon glyphicon-refresh"></i></button> <!--点击刷新资源--> </div> </div> </div> <script src="jquery/jquery.min.js"></script><script src="jstree/dist/jstree.min.js"></script><script src="jstreeDemo.js?20180125"></script></body></html> 2.2、jstreeDemo.js代码 function jstree_fun(url){var $tree = $("jstree_demo_div").jstree({"core":{//'multiple': false, // 是否可以选择多个节点//"check_callback": true, // 允许拖动菜单 唯一 右键菜单"check_callback" : true,//设置为true,当用户修改数时,允许所有的交互和更好的控制(例如增删改)"themes" : { "stripes" : true },//主题配置对象,表示树背景是否有条带"data" : {//'url' : url,//'data' : function(node){//return { 'id' : node.id };//}"url" : url,"dataType" : "json"},"check_callback" : function(operation, node, node_parent, node_position, more){if(operation === "move_node"){var node = this.get_node(node_parent);if(node.id === ""){alert("根结点不可以删除");return false;}if(node.state.disabled){alert("禁用的不可以删除");return false;} }else if(operation === "delete_node"){var node = this.get_node(node_parent);if(node.id === ""){alert("根结点不可以删除");return false;} }return true;} },"plugins": [ //插件 "search", //允许插件搜索 // "sort", //排序插件 "state", //状态插件 "types", //类型插件 "unique", //唯一插件 "wholerow", //整行插件"contextmenu"],types:{ "default": { //设置默认的icon 图 "icon": "glyphicon glyphicon-folder-close", } } });$tree.on("open_node.jstree", function(e,data){ //监听打开事件var currentNode = data.node; data.instance.set_icon(currentNode, "glyphicon glyphicon-folder-open"); });$tree.on("close_node.jstree", function(e,data){ //监听关闭事件 var currentNode = data.node; data.instance.set_icon(currentNode, "glyphicon glyphicon-folder-close"); });$tree.on("activate_node.jstree", function(e, data){var currentNode = data.node; //获取当前节点的json .node //alert(currentNode.a_attr.id) //alert(currentNode.a_attr.href) //获取超链接的 .a_attr.href "链接" .a_attr.id ID //alert(currentNode.li_attr.href) //获取属性的 .li_attr.href "链接" .li_attr.id ID });// 创建$tree.on("create_node.jstree", function(e, data){alert("创建node节点");});// 修改$tree.on("rename_node.jstree", function(e, data){alert("修改node节点");});// 删除$tree.on("delete_node.jstree", function(e, data){alert("删除node节点");});// 查询节点名称var to = false;$("search_ay").keyup(function(){if(to){clearTimeout(to);}to = setTimeout(function(){$tree.jstree(true).search($('search_ay').val()); //开启插件查询后 使用这个方法可模糊查询节点 },250);});$('.btn-tab').click(function(){ //选项事件 //alert($(this).attr("var")) $tree.jstree(true).destroy(); //可做联级 $tree = jstree_fun($(this).attr("var"));//可做联级 //alert($(this).attr("var")) }); $('.refresh').click(function(){ //刷新事件 $tree.jstree(true).refresh () }); return $tree; }function node_create(){var ref = $("jstree_demo_div").jstree(true);var sel = ref.get_selected();if(!sel.length){alert("请先选择一个节点");return;}sel = sel[0];sel = ref.create_node(sel);if(sel){ref.edit(sel); } }function node_rename(){var ref = $("jstree_demo_div").jstree(true);var sel = ref.get_selected();if(!sel.length){alert("请先选择一个节点");return;}sel = sel[0];ref.edit(sel);}function node_delete(){var ref = $("jstree_demo_div").jstree(true);var sel = ref.get_selected();if(!sel.length){alert("请先选择一个节点");return;}sel = sel[0];if(ref.get_node(sel).parent==''){alert("根节点不允许删除");return;}ref.delete_node(sel);}// 初始化操作function init(){var $tree = jstree_fun("json/data.json");}init(); 3、图片效果展示 本篇文章为转载内容。原文链接:https://blog.csdn.net/qq_27717967/article/details/79167605。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-09-08 13:23:58
53
转载
转载文章
...blog.csdn.net/john_dwh/article/details/127460821。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。 All the charts, single package It’s easy with amCharts 5 – all chart types come in a single, easy to understand package! No need to figure out product line up – just get amCharts 5 for everything. And since it was designed to work with modern web dev toolkits like React, Angular, Vue it will just fall into place, right out of the box. X/Y Line & Smoothed line Area Column & Bar Scatter & Bubble Candlestick & OHLC Step (incl. w/ no-riser) Floating & Gantt Waterfall Error Stacked (regular or 100%) Heatmap … and any combination of the above Percent Pie & Donut Nested donut Funnel Pyramid Pictorial Geo maps Map chart Geo heat map Map combined with charts Maps is an add-on and requires separate license. Other Sankey diagram Chord, Chord directed, and Chord non-ribbon diagrams Pack Treemap Tree Sunburst Partition Force-directed tree Radar & Polar Word cloud Venn diagram Efficiency built-in Canvas rendering amCharts 5 uses browser’s Canvas API which in most cases is way faster than SVG. Less moving parts in the DOM tree, faster rendering. Layering Common element groups are isolated into separate independent canvases, so that heavily updated sections do not trigger expensive repaints in places that do not change. Fast data processing Data processing in amCharts 5 is designed to be as efficient as possible. Incremental updates, lack of repetitive aggregations, and lightweight data object use makes data processing fast and very memory-efficient. Faster dashboards amCharts 5 is capable of running scores of charts on the same page, without crippling the browser, due to its lightweight approach to data parsing and rendering. Tiny binaries We made amCharts 5 really small – the core functionality compiles to a file of only around 400KB. Each niche functionality is separated into files, so you load only what you really need. Users will surely appreciate faster load times. Better tree-shaking We also designed amCharts 5 to be extremely tree-shakable. If you are using Webpack or similar packager, only code that is really needed will be included into your final application. The most advanced chart package Classics with some new twists XY charts are now so powerful and flexible, you can plot any data on them. Number, date, duration, or category axes are supported, in all directions. Pie charts are now fully nestable, with support for custom start and end angles, to create half circles. New geo maps Our maps use GeoJSON format. Being open and widely accepted standard it opens up a lot of possibilities and sources for ready-made and custom maps. Furthermore, maps are now very flexible, with multi-series support, configurable down to the nut and bolt. (Maps is and add-on to amCharts 5: Charts which requires separate license) More about amCharts 5: Maps Pictorials Create multi-layer, multi-series pictorial charts. Any SVG path can be used as a shape for your chart. Sankey Diagrams Stunning flow diagrams, in horizontal and vertical. With draggable, fully configurable nodes. Enhanced radar charts With stacked column, bands, axes, and other dramatic enhancements, radar charts are now way more useful. Treemaps Completely zoomable, multi-level, highly configurable. Heatmaps Automatically build heat-maps, with custom axes, color ranges, and awesome new interactive Heat Legend. Create heatmaps using colors, or point size or both. Universal and flexible heat rules allow attaching any value in data to any property or properties on any element. Chord diagrams Visualize your 2-way relational data in a neat circular Chord diagrams. We do have different variations of the classic diagram: Chord, Chord directed, and Chord non-ribbon. True funnel charts amCharts 5 offers true Funnel charts the way they were meant to be. Slice’s area size represents the value, so each step’s influence on overall volume reduction is more prominent than with basic funnels. Trapezoid form can also be configured to further emphasize reduction. Complete it with other visual elements, like fully configurable slice lines, multiple series support, togglable legends, and many many more options. Customizable beauty built-in Powerful theme engine amCharts 5 comes with a bunch of beautiful themes as well as a super flexible theme engine, which you can use. We devised a CSS-like rule-based theme targeting system in themes. Using, creating, customizing themes or standalone rules has never been so easy. The new system allows applying defaults to elements based on their type, features, or position in a virtual element tree. Fresh new look Default looks designed to look fresh, like something out of tomorrow. Carefully selected color schemes and default settings were specifically chosen to make the charts stand out. Silk-smooth animations Every setting – colors, positions, sizes, opacity, and many more – is animatable to ensure smooth transitions. No choppy, stepped animations – everything is fluid, including zoom and toggling of series and other items. Flexibility Element templates Most elements are created using templates: a collection of default settings, events, and adapters. Changing template automatically propagates changes to actual elements, making it easy to do batch updates. Everything’s configurable Numerous configuration options allow inventive uses, bordering on new chart types. Angles, colors, positions, radii, a-n-y-t-h-i-n-g can be set to bend classic and new chart types exactly the way you need them. Element states Easily change how an element looks like under different circumstances, e.g. on some interaction, hover, click, or related to data (eg. column look if a value is down). The engine will automatically apply the required properties as needed, animating between old and new values smoothly. Create and apply custom states via the API. Multi-type multi-axis support Add any number of axes of any type. Create overlaid comparison of different time scales. Use any mix of dimensional values: numbers, dates, categories, or duration. Adapters “Adapters” functionality allows plugging in custom code to dynamically override just about any setting or data value. Text formatting All text labels – tooltips, axis labels, titles, etc. – now support rich text formatting options, like changing colors, font weight, or applying just about any styling option from the CSS arsenal. In addition to formatting support, labels can now contain in-line placeholders for real data, with the ability to apply custom formatting to values. Accessibility & Interactivity Accessibility Accessibility was riding shotgun when amCharts 5 was being developed. All interactive elements are TAB-selectable, with customizable roles, order, and screen-reader texts. Everything that can be moved by touch or mouse, can be moved by keyboard. Everything that can be clicked or toggled, can be interacted with with keyboard, too. Touch support Charts have been designed to work with touch devices out-of-the-box. They will work not only on phones or tablets, but also touch capable computers. Under the hood Built with TypeScript Supports strong type and error checking in TypeScript applications. Enjoy code completion, error checking and dynamic help popups in major IDEs. Full support for TypeScript and ES6 modules. 100% for JavaScript Can be fully used in any vanilla JavaScript application. amCharts 5 does not use or rely on globals, external frameworks or 3rd party libraries. Universal rendering engine Can be used to build dynamic, interactive Canvas-based interfaces and applications. Add various elements to the screen, make them interactive, with a few lines of code. Make them clickable, draggable, hoverable, using built-in interactivity functionality. Our universal layout engine will place, size and arrange elements according to set rules. 本篇文章为转载内容。原文链接:https://blog.csdn.net/john_dwh/article/details/127460821。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-09-17 18:18:34
351
转载
转载文章
...了一份关于常见Web应用漏洞及其修复策略的报告,其中特别强调了SQL注入和文件上传漏洞的严重性,并提供了最新的防范措施和最佳实践。 在实战层面,OWASP Top 10项目持续更新其针对Web应用程序最常见的安全风险列表,SQL注入始终位列其中。研究人员建议开发者采用参数化查询、ORM工具以及输入验证等手段来防止此类攻击。此外,对于文件上传漏洞,应当限制上传文件类型、使用白名单机制并对上传内容进行严格的安全检查,避免恶意代码执行。 同时,在全球范围内,随着《通用数据保护条例》(GDPR)等法规的实施,企业对数据安全的重视程度日益提高,对潜在安全风险如SQL注入的防护已不再仅仅是技术问题,更是法律合规的重要组成部分。因此,企业和开发者需要定期进行安全审计和漏洞扫描,确保系统无类似安全隐患。 在教育领域,诸如Vulnhub这样的平台为学习者提供虚拟靶场环境,帮助他们通过实战演练提升发现并修补这些漏洞的能力。此外,许多在线课程和研讨会也开始深度剖析实际案例,讲解如何从防御和攻击两个角度理解和应对SQL注入、文件上传等关键Web应用安全挑战,以培养更多具备实战能力的网络安全人才。
2023-01-02 12:50:54
497
转载
转载文章
在.NET开发中,网页日历控件作为用户界面交互的重要组成部分,其易用性、兼容性和功能性一直是开发者关注的重点。梅花雪Web Calendar ver 3.0是一个较早且颇受欢迎的日历插件,然而随着技术的不断进步,如今已有更多现代化和功能丰富的日历组件可供选择。例如,jQuery UI Datepicker是一个广泛应用于现代Web项目中的日期选择器,不仅提供了灵活的主题定制,还支持多语言及多种日期格式设置。 对于.NET Core或ASP.NET MVC等新一代框架下的开发者,可考虑采用Bootstrap DateTimePicker或者Microsoft自家的Blazor组件库中的内置日期时间选择器,这些都已实现与现代前端框架深度集成,提供更好的用户体验和更强大的API支持。 此外,在处理日期和时间数据时,遵循W3C推荐的语义化HTML5规范也显得尤为重要,比如使用标签,这样不仅能提高无障碍访问性,还能利用现代浏览器原生的日期选择器功能,减少JavaScript依赖,提升性能表现。 综上所述,尽管梅花雪Web Calendar曾是经典的选择,但在今天的技术背景下,我们鼓励开发者持续关注并采用最新的日历控件技术,以满足不断提升的用户需求和体验标准。同时,在设计和开发过程中,应注重结合实际业务场景,合理运用各种日历组件的优势,以达到最佳实践效果。
2023-04-22 09:54:29
484
转载
转载文章
...新过程。 Java.net.preferIPv4Stack , 这是一个Java系统属性,当设置为“true”时,指示Java应用程序优先使用IPv4协议栈进行网络通信。在本文中,添加该参数到idea.vmoptions文件有助于确保Android Studio在访问更新服务器时首选IPv4协议,这对于某些仅支持IPv4或者在IPv6环境下存在兼容性问题的情况尤为关键。 更新源(Updates Source) , 在软件开发环境中,更新源是指软件获取新版本、补丁或组件升级信息的远程URL地址。对于Android Studio来说,通过修改idea.vmoptions中的-Didea.updates.url和-Didea.patches.url参数,可以重新指向Google官方或其他可靠的更新源地址,以便于开发者及时获取并应用最新的稳定版或预览版更新内容。在本文情境下,如果默认的HTTP更新源无法正常工作,还可以尝试将更新源切换至HTTPS以解决连接问题。
2023-02-08 20:46:33
126
转载
转载文章
...的特性。文中提到的.NET 4.0引入了var 和 dynamic等关键字支持动态类型,这意味着开发者在编写代码时无需预先声明变量的具体数据类型,编译器或运行时环境会根据实际赋值自动推断或允许类型转换,从而提高了开发灵活性和效率。 弱类型语言 , 弱类型语言是一种对数据类型的检查相对宽松的语言,通常在编译阶段不强制要求变量具有固定的数据类型,并且允许不同类型的数据之间进行隐式转换。如文章中所述的VB.NET和PHP,在Web开发早期广泛应用,因其可以快速实现页面功能展示、方便修改等特点而受到青睐。 运行时编译 , 运行时编译(Runtime Compilation)是程序在运行过程中动态生成并执行代码的一种机制。文中提及的Razor引擎即采用了类似PHP的运行时编译技术,使得ASP.NET MVC框架下的视图模板能够在服务器端实时编译成可执行代码,这样开发者能够即时看到代码修改的效果,极大地提升了Web开发的迭代速度和便捷性。 第三方框架 , 第三方框架是指由非官方或社区成员创建的软件开发工具包,这些工具包提供了针对特定应用场景的预封装功能和解决方案。在本文中,虽然Java语言本身并不具备与.NET 4.0类似的动态类型原生支持,但通过使用第三方框架,开发者可以在一定程度上模拟实现类似的功能,以适应Web开发的需求和特点。 学院派 , 学院派在此处指的是遵循传统计算机科学教育理念,注重编程规范、强类型语言的正确性、健壮性和安全性的开发者群体。他们往往经过严格的科班训练,强调理论基础扎实和技术严谨性。 野路子派 , 野路子派则是指那些没有受过正规科班教育或不完全遵循传统开发理念,更倾向于灵活、敏捷开发方式的开发者群体。他们在Web开发实践中可能更多地依赖直觉、经验和创新思维,对于快速迭代、可视化以及实时修改等方面有较高的敏感度和执行力,因此能在Web开发领域取得成功。
2023-03-25 14:09:17
54
转载
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
nc host port
- 通过netcat工具连接到远程主机和端口。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
2023-04-28
2023-08-09
2023-06-18
2023-04-14
2023-02-18
2023-04-17
2024-01-11
2023-10-03
2023-09-09
2023-06-13
2023-08-07
2023-03-11
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"