100% found this document useful (3 votes)
44 views

PDF Beginning Database Programming Using ASP NET Core 3 With MVC Razor Pages Web API jQuery Angular SQL Server and NoSQL 1st Edition Bipin Joshi download

NET

Uploaded by

jernieaskale
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
44 views

PDF Beginning Database Programming Using ASP NET Core 3 With MVC Razor Pages Web API jQuery Angular SQL Server and NoSQL 1st Edition Bipin Joshi download

NET

Uploaded by

jernieaskale
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Download the full version of the textbook now at textbookfull.

com

Beginning Database Programming Using ASP NET


Core 3 With MVC Razor Pages Web API jQuery
Angular SQL Server and NoSQL 1st Edition
Bipin Joshi
https://textbookfull.com/product/beginning-
database-programming-using-asp-net-core-3-with-
mvc-razor-pages-web-api-jquery-angular-sql-server-
and-nosql-1st-edition-bipin-joshi/

Explore and download more textbook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Pro ASP NET Core MVC Develop cloud ready web applications
using Microsoft s latest framework ASP NET Core MVC Sixth
Edition Adam Freeman
https://textbookfull.com/product/pro-asp-net-core-mvc-develop-cloud-
ready-web-applications-using-microsoft-s-latest-framework-asp-net-
core-mvc-sixth-edition-adam-freeman/
textbookfull.com

Pro ASP.NET Core 3: Develop Cloud-Ready Web Applications


Using MVC, Blazor, and Razor Pages — Eighth Edition Adam
Freeman
https://textbookfull.com/product/pro-asp-net-core-3-develop-cloud-
ready-web-applications-using-mvc-blazor-and-razor-pages-eighth-
edition-adam-freeman/
textbookfull.com

Ultimate ASP NET Core Web API 2nd Edition Marinko


Spasojevic

https://textbookfull.com/product/ultimate-asp-net-core-web-api-2nd-
edition-marinko-spasojevic/

textbookfull.com

Latin American Perspectives on Law and Religion Rodrigo


Vitorino Souza Alves

https://textbookfull.com/product/latin-american-perspectives-on-law-
and-religion-rodrigo-vitorino-souza-alves/

textbookfull.com
Convective Heat Transfer From Rotating Disks Subjected To
Streams Of Air 1st Edition Stefan Aus Der Wiesche

https://textbookfull.com/product/convective-heat-transfer-from-
rotating-disks-subjected-to-streams-of-air-1st-edition-stefan-aus-der-
wiesche/
textbookfull.com

Endovascular Aortic Repair Current Techniques with


Fenestrated Branched and Parallel Stent Grafts Factor

https://textbookfull.com/product/endovascular-aortic-repair-current-
techniques-with-fenestrated-branched-and-parallel-stent-grafts-factor/

textbookfull.com

Secularism and Cosmopolitanism Critical Hypotheses on


Religion and Politics Étienne Balibar

https://textbookfull.com/product/secularism-and-cosmopolitanism-
critical-hypotheses-on-religion-and-politics-etienne-balibar/

textbookfull.com

Business Process Management Forum: BPM Forum 2020,


Seville, Spain, September 13–18, 2020, Proceedings Dirk
Fahland
https://textbookfull.com/product/business-process-management-forum-
bpm-forum-2020-seville-spain-september-13-18-2020-proceedings-dirk-
fahland/
textbookfull.com

Adjusting to a World in Motion: Trends in Global Migration


and Migration Policy 1st Edition Douglas J. Besharov

https://textbookfull.com/product/adjusting-to-a-world-in-motion-
trends-in-global-migration-and-migration-policy-1st-edition-douglas-j-
besharov/
textbookfull.com
Hattiesburg An American City in Black and White Quinn

https://textbookfull.com/product/hattiesburg-an-american-city-in-
black-and-white-quinn/

textbookfull.com
Bipin Joshi

Beginning Database Programming


Using ASP.NET Core 3
With MVC, Razor Pages, Web API, jQuery, Angular,
SQL Server, and NoSQL
Bipin Joshi
Thane, India

Any source code or other supplementary material referenced by the


author in this book is available to readers on GitHub via the book’s
product page, located at www.​apress.​com/​9781484255087 . For more
detailed information, please visit http://​www.​apress.​com/​source-code
.

ISBN 978-1-4842-5508-7 e-ISBN 978-1-4842-5509-4


https://doi.org/10.1007/978-1-4842-5509-4

© Bipin Joshi 2019

This work is subject to copyright. All rights are reserved by the


Publisher, whether the whole or part of the material is concerned,
specifically the rights of translation, reprinting, reuse of illustrations,
recitation, broadcasting, reproduction on microfilms or in any other
physical way, and transmission or information storage and retrieval,
electronic adaptation, computer software, or by similar or dissimilar
methodology now known or hereafter developed.

Trademarked names, logos, and images may appear in this book. Rather
than use a trademark symbol with every occurrence of a trademarked
name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no
intention of infringement of the trademark. The use in this publication
of trade names, trademarks, service marks, and similar terms, even if
they are not identified as such, is not to be taken as an expression of
opinion as to whether or not they are subject to proprietary rights.

While the advice and information in this book are believed to be true
and accurate at the date of publication, neither the authors nor the
editors nor the publisher can accept any legal responsibility for any
errors or omissions that may be made. The publisher makes no
warranty, express or implied, with respect to the material contained
herein.

Distributed to the book trade worldwide by Springer Science+Business


Media New York, 233 Spring Street, 6th Floor, New York, NY 10013.
Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-
[email protected], or visit www.springeronline.com. Apress Media,
LLC is a California LLC and the sole member (owner) is Springer
Science + Business Media Finance Inc (SSBM Finance Inc). SSBM
Finance Inc is a Delaware corporation.
At the holy feet of Lord Shiva, Goddess Parvati, and Gurudev Dattatreya.
—Bipin Joshi
Introduction
Welcome toBeginning Database Programming Using ASP.NET Core 3 !
Modern web application development is dominated by open source
frameworks that evolve at a rapid pace. At times, it becomes
challenging and overwhelming even for experienced developers to keep
themselves updated with the latest happenings in the technologies and
frameworks of their interest. It goes without saying that beginners
aiming to grasp the fundamentals of such technologies and frameworks
often look for resources that can introduce them to the subject quickly
and efficiently.
This book is about Microsoft’s latest web development framework –
ASP.NET Core 3.0. While developing real-world web applications using
ASP.NET Core, you have many options to choose from: MVC, Razor
Pages, Web API, Blazor, jQuery, Angular, Entity Framework (EF) Core,
SQL Server data provider, Azure SQL Databases, Cosmos DB, MongoDB,
and more. The book attempts to address the difficulties faced by
beginners when they decide to jump to the ASP.NET Core family of
technologies. It discusses topics that are most frequently needed by
beginners. To that end, this book teaches you to
Work with data entry forms and form validations
Perform CRUD (Create, Read, Update, and Delete) database
operations
Use jQuery Ajax and Angular with ASP.NET Core applications
Implement user authentication and authorization
Store data in NoSQL databases such as Cosmos DB and MongoDB
Deploy ASP.NET Core web applications to Internet Information
Services (IIS) and Azure App Service
What makes this book special is the approach it takes while
introducing these technical features. Rather than presenting these
features and available options in isolation, this book utilizes them in an
integrated manner by building a small CRUD-focused sample
application – Employee Manager.
Throughout this book, you build multiple versions of Employee
Manager, each version using a particular set of technologies, features,
and options. For example, in one of the chapters, you build Employee
Manager using ASP.NET Core MVC. In another chapter, you build the
same application using ASP.NET Core Razor Pages. In yet another
chapter, you build Employee Manager using Blazor, and so on. I hope
that this approach will help you to get introduced to various aspects of
ASP.NET Core quickly and efficiently.
Who Is This Book For?
This book is intended for beginner-level software developers wanting
to get introduced to web development using ASP.NET Core and related
technologies. This book doesn’t aim at taking a deep dive into the
subject; rather, it attempts to quickly familiarize you with an array of
technologies, features, and options that can be used while building
modern web applications using ASP.NET Core. I make the following
assumptions about you:
You are familiar with C# programming language.
You possess a basic understanding of ASP.NET and how web
applications work.
You are familiar with Visual Studio IDE. Although the book explains
some features of Visual Studio as and when they are required, you
should know the basics such as creating/opening project files,
compiling and debugging source code, and running an application
from within the Visual Studio.
You know how to work with Microsoft SQL Server tables and stored
procedures.
Additionally, in some chapters, familiarity with JavaScript would be
a plus.

Software Required
In order to work through the examples discussed in this book, you need
the following software:
Visual Studio 2019 for Windows (make sure to apply the latest
updates)
.NET Core 3.0 and ASP.NET Core 3.0
SQL Server 2012 or later with the Northwind database
Access to the Azure portal, Azure SQL Databases, and Azure Cosmos
DB in the examples that use these technologies
MongoDB database server in the example that uses it as a data store
jQuery 3.x and Angular 8 in the chapters where these are used
Any modern web browser
I have used Visual Studio 2019 Enterprise edition to create all the
example projects. However, you can use any edition of Visual Studio
2019 for Windows such as Community or Professional edition. IIS
Express has been used as the development web server. Most of the
examples presented in this book use the Northwind sample database,
and I strongly suggest that you install it in your SQL Server. I have used
the Firefox browser in my illustrations and screenshots, but you can use
any other modern browser.

Structure of This Book


As mentioned earlier, this book teaches you about the ASP.NET Core
family of technologies by building the Employee Manager sample
application. In all, there are ten chapters, out of which the first two are
introductory chapters. Chapters 3 – 9 guide you to build various
versions of Employee Manager, each version making use of a particular
set of technologies, features, and options. Chapter 10 covers
deployment. These ten chapters are briefly outlined as follows:
Chapter 1 : This chapter gives you a quick introduction to ASP.NET
Core in terms of its prominent features and primary development
options. You also build a “Hello World” example using ASP.NET Core
MVC, Razor Pages, and Web API.
Chapter 2 : This chapter explains the Employee Manager application.
It takes a quick look at the Employees table of the Northwind
database and also discusses its columns that are used for the sake of
CRUD operations. Various pages of the application such as employee
listing page, Insert New Employee page, user registration page, and
sign-in page are discussed in terms of their functionality. It then
proceeds to summarize various technology features and options
available to you for building this application. The chapter also guides
you to host your source code into GitHub repositories.
Chapter 3 : This chapter teaches you to develop Employee Manager
using ASP.NET Core MVC. It illustrates various features such as using
Tag Helpers to build user interfaces (UIs), creating an Entity
Framework Core model, and model validation using data
annotations. You also learn to use ASP.NET Core Identity for user
authentication and authorization.
Chapter 4 : In this chapter, you develop Employee Manager using
ASP.NET Core Razor Pages. This chapter also teaches how an EF Core
model can be created using reverse engineering techniques. This
example also illustrates asynchronous operations (async/await) in
Razor Pages and ASP.NET Core Identity.
Chapter 5 : In this chapter, you develop Employee Manager using
ASP.NET Core Web API. The application consists of two parts – Web
API and client. Web API performs the CRUD operations using
repositories, raw SQL queries, and stored procedures. The client
application is developed using ASP.NET Core MVC and uses HTML
Helpers to build the user interface. The client application uses
HttpClient to invoke Web API. The client also demonstrates how to
write asynchronous actions (async/await) in the MVC controller.
Chapter 6 : This chapter teaches you to develop Employee Manager
using jQuery and Web API. Data entry forms are designed using
HTML5 markup. Data validations are performed using jQuery
validation plugin. Communication between the client and the server
is facilitated using jQuery Ajax. The CRUD operations are wrapped
inside an asynchronous Web API and use asynchronous methods of
Entity Framework Core. User authentication is implemented using
JSON Web Tokens (JWTs).
Chapter 7 : In this chapter, you develop Employee Manager using
Angular and Web API. Data entry forms are designed using Angular
reactive forms. Form validations are performed using Angular’s built-
in validation techniques. Angular invokes Web API to perform CRUD
operations. Communication between the client and the server is
facilitated using Angular’s HttpClient. User authentication is
implemented using the JWT authentication scheme.
Chapter 8 : This chapter teaches you to develop Employee Manager
using Blazor. The application uses Blazor’s server-side hosting
model. You learn to develop Razor Components. Data entry forms
complete with validations are developed using Blazor’s input
components. The CRUD operations are encapsulated in a repository
injected into Razor Components. User authentication and
authorization are implemented using ASP.NET Core Identity and
policy-based authorization.
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Chapter 9 : In this chapter, you develop Employee Manager using
three different data stores: Azure SQL Database, Azure Cosmos DB,
and MongoDB. First, you learn to perform CRUD operations on Azure
SQL Databases using the Microsoft.Data.SqlClient data provider. Then
you learn two ways to access data residing in Azure Cosmos DB,
namely, Cosmos DB client library and EF Core provider for Cosmos
DB. Finally, you also learn to access data from MongoDB using
MongoDB driver for .NET Core.
Chapter 10 : This chapter is about deploying Employee Manager you
developed in earlier chapters. As an example it illustrates how the
ASP.NET Core MVC version of Employee Manager can be deployed to
Internet Information Services (IIS) followed by deploying to Azure
App Service.

Downloading the Source Code


The complete source code for the book is available for download at the
book’s companion web site. Visit www.apress.com , and go to this
book’s information page. Then click the Download source code option
to go to the book’s source code available on GitHub.

Contacting the Author


You can reach me via my web site – www.binaryintellect.net .
You can also follow me on Facebook, Twitter, and LinkedIn (visit my
web site for the links).
Table of Contents
Chapter 1:​Introduction to ASP.​NET Core
Overview of ASP.​NET Core
ASP.​NET Core MVC
ASP.​NET Core Razor Pages
ASP.​NET Core Web API
Creating an ASP.​NET Core MVC Project
Creating an ASP.​NET Core Razor Pages Project
Creating an ASP.​NET Core Web API Project
Installing the Northwind Database
Summary
Chapter 2:​Sample Application
Features of Employee Manager
Understanding the Employees Table
Adding a Countries Table
Signing In to Employee Manager
Creating a New User Account
Listing All the Employees
Inserting a New Employee
Updating Existing Employee
Deleting Existing Employee
Signing Out of Employee Manager
Technology Options Used to Develop Employee Manager
Rendering HTML Forms
Performing CRUD Operations
Using JavaScript Libraries and Frameworks
User Authentication
Deployment
ASP.​NET Core MVC
ASP.​NET Core Razor Pages
ASP.​NET Core Web API
jQuery
Angular
Blazor
Azure SQL Database
Azure Cosmos DB
MongoDB
Hosting Code in a Private GitHub Repository
Summary
Chapter 3:​ASP.​NET Core MVC
Create an ASP.​NET Core Web Application
Create an Entity Framework Core Model
Create an EmployeeManager Controller
Add a _​ViewImports File
Displaying a List of Employees
Insert a New Employee
Update an Existing Employee
Delete an Existing Employee
Add Razor Layout and View Start
Enable Client-Side Validations
Store the Database Connection String in appsettings.​json
Configure Application Startup
Add ASP.​NET Core Identity Support
Add AppIdentityUser, AppIdentityRole, and
AppIdentityDbCon​text Classes
Add ASP.​NET Core Identity Configuration to Startup
Add Database Tables to Store User and Role Details
Add SecurityControll​er to the Controllers Folder
Create a User Registration Page
Create a Sign-In Page
Add a Sign Out Button
Authenticate and Authorize Users
Protect the Application Against Cross-Site Request Forgery
Run the Application
Summary
Chapter 4:​ASP.​NET Core Razor Pages
Create a ASP.​NET Core Web Application
Reverse Engineering the Entity Framework Core Model
Create Pages and EmployeeManager Folders
Add a _​ViewImports File
Displaying a List of Employees
Inserting a New Employee
Updating an Existing Employee
Deleting an Existing Employee
Add Razor Layout and View Start
Client-Side Validations, Style Sheet, and appsettings.​json
Configure Application Startup and Error Handling
Add ASP.​NET Core Identity Support
Add AppIdentityUser, AppIdentityRole, and
AppIdentityDbCon​text Classes
Add ASP.​NET Core Identity Configuration and Database
Tables
Add the Security Subfolder to the Pages folder
Create a User Registration Page
Create a Sign-In Page
Signing the User Out of the Application
Authenticating and Authorizing Users
Run the Application
Summary
Chapter 5:​ASP.​NET Core Web API
Application Architecture
ASP.​NET Core and REST Services
Understanding the JSON Format
Role of the Repository
Creating an EmployeeManager.​Api Project
Creating the EF Core Model and Repositories
Creating EmployeeSqlRepos​itory and CountrySqlReposi​tory
Creating EmployeeStProcRe​pository and CountryStProcRep​
ository
Registering Repositories with the DI Container
Creating Employees Web API and Countries Web API
Running the Employees Web API
Creating a Client for Web API
Creating View Models
Adding the EmployeeManagerC​ontroller
Setting Up the HttpClient
Displaying a List of Employees
Inserting a New Employee
Updating an Existing Employee
Deleting an Existing Employee
FillCountriesAsy​nc() Helper Method
Integrating ASP.​NET Core Identity
Running the Application
Summary
Chapter 6:​jQuery
Overview of Ajax
Create an ASP.​NET Core Web Application
Employees Web API and Countries Web API
EmployeeManager Controller
Add a jQuery Library to the Project
Display a List of Employees
Insert a New Employee
Update an Existing Employee
Delete an Existing Employee
Overview of the JSON Web Token (JWT)-Based Authentication
What Is JWT?​
Add Support for JWT Authentication
Storing User Details
Enable and Configure JWT Authentication
Create a New User Account
Signing In to the Application
Signing Out of the Application
Enforce Authentication on All Pages
Summary
Chapter 7:​Angular
Overview of the Project Structure
Create ASP.​NET Core Web API Application
Enabling CORS in Web API Project
Running Web API Application
Create Angular Application
Angular Application Architecture
Editing Angular Project Files in Visual Studio
Add Employee, Country, and User Classes
Add Service to Invoke Employees Web API
Add Service to Invoke Security Web API
Display a List of Employees
Insert a New Employee
Update an Existing Employee
Delete an Existing Employee
Sign-In Component
Sign-Out Component
Understanding app.​module.​ts
Routing
Running the Angular Application
Integrating Angular Application with ASP.​NET Core
Application
Summary
Chapter 8:​Blazor
Blazor Hosting Models
Client Side (Blazor WebAssembly)
Server Side (Blazor Server)
Overview of Razor Components
Component Lifecycle Methods
Employee Manager Project Structure
Entity Framework Core Model and Repositories
Display a List of Employees
Insert a New Employee
Update an Existing Employee
Delete an Existing Employee
Apply CSS and Layout to Razor Components
Integrating ASP.​NET Core Identity
Add IdentityDbContex​t and Associated Classes
Add Register and SignIn View Models
Add Register, SignIn, and SignOut Razor Pages
Add _​Layout, _​ViewStart, and _​ViewImports Files
Register and Configure ASP.​NET Core Identity
Secure CRUD Razor Components
Display the User Name and Sign Out Button
Configure Initial Sign-In Prompt
Use Policy-Based Authorization
Summary
Chapter 9:​Azure SQL Database, Azure Cosmos DB, and MongoDB
Creating Azure SQL Database
Connecting to Azure SQL Database Using SQL Server
Management Studio
Employee Manager Using Azure SQL Database
Employee and Country Model Classes
Creating EmployeeReposito​ry and CountryRepositor​y
EmployeeManagerC​ontroller Class
Database Connection String
Overview of NoSQL Databases
Cosmos DB
MongoDB
Creating a Cosmos DB Account
Employee Manager Using Cosmos DB
Cosmos DB Connection Details
Microsoft.​Azure.​DocumentDB.​Core Client Library
Employee and Country Model Classes
Creating the EmployeeManagerC​ontroller
Adding Support for Authentication and Authorization
Storing User Details
Creating the SecurityControll​er
Using the EF Core Provider for Cosmos DB
Creating the AppDbContext
Performing CRUD Operations
Installing and Running MongoDB
Performing CRUD Operations
Summary
Chapter 10:​Deployment
Deploy Employee Manager to IIS
Create a Target SQL Server Database
Create an IIS Site
Publish Employee Manager from Visual Studio
Redeploying the Application
Deploy Employee Manager to Azure App Service
Storing Connection String in App Service
Redeploying the Application
Summary
Index
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
About the Author and About the Technical
Reviewer

About the Author


Bipin Joshi
is an independent software consultant, trainer, author, yoga mentor, and
meditation teacher who writes about seemingly unrelated topics:
software development and yoga! He conducts online training courses to
help developers learn the .NET family of technologies better and faster.
Currently, his focus is ASP.NET, C#, Azure, data access technologies,
design patterns, and architectural patterns. More details about his
online training courses are available at www.binaryintellect.com
.
Bipin has been programming since 1995 and has worked with the
.NET framework since its inception. He is a published author and has
authored or co-authored more than 12 books and numerous articles on
.NET technologies. He regularly writes about ASP.NET and other
cutting-edge web technologies on his web site –
www.binaryintellect.net . Bipin is a Microsoft Most Valuable
Professional (MVP) and a former Microsoft Certified Trainer (MCT).
Having embraced the yoga way of life, he enjoys the intoxicating
presence of God and writes about yoga on his web site –
www.bipinjoshi.org . Bipin has also penned a few books on yoga
and teaches meditation to selected individuals. He can be reached
through his web sites.

About the Technical Reviewer


Alex Thissen
has been involved in application development since the late 1990s and
worked as a lead developer, trainer, coach, and architect at large
enterprises and small companies. He spends his time teaching other
developers the details of the Microsoft development platform and
frameworks and coaches architects to
design and build modern distributed
applications at cloud scale. He has
received the Microsoft Most Valuable
Professional award for Visual Studio and
Development Technologies since 2006.
In his spare time, Alex likes to participate
in all kinds of sport and loves playing
and programming new and retro video
games.
© Bipin Joshi 2019
B. Joshi, Beginning Database Programming Using ASP.NET Core 3
https://doi.org/10.1007/978-1-4842-5509-4_1

1. Introduction to ASP.NET Core


Bipin Joshi1

(1) Thane, India

This chapter introduces you to the basics of ASP.NET Core. It discusses


the main development options available in ASP.NET Core, namely, MVC,
Razor Pages, and Web API. Since you are going to work extensively with
ASP.NET Core projects in the later chapters, it is worthwhile to learn
how to create an ASP.NET Core web application using the Visual Studio
IDE. To that end, this chapter helps you to
Understand main development options available in ASP.NET Core.
Create an ASP.NET Core MVC application.
Create an ASP.NET Core Razor Pages application.
Create an ASP.NET Core Web API application.
Install the Northwind sample database.

Overview of ASP.NET Core


ASP.NET Core is a framework for building modern web applications and
services. It’s part of .NET Core and is a cross-platform and open source
framework. This means you can develop and deploy your web
applications targeting all the popular operating systems such as
Windows, Linux, and macOS.
ASP.NET Core is a redesigned and rewritten framework for building
modern web applications. Although we won’t discuss each and every
feature of the framework here, some of its important technical features
are listed as follows:
Cross-platform framework. You can develop and run web
applications on Windows, Linux, and macOS.
Open source with a lot of community involvement.
Built-in dependency injection (DI) framework.
ASP.NET Core includes a built-in web server called Kestrel. You can
use Kestrel by itself or host your web applications under IIS, Nginx,
or Apache.
Multiple development options for UI including MVC, Razor Pages, and
Blazor. (Of course, you can also use client-side JavaScript frameworks
to develop the front-end.)
Unified programming model for MVC web applications and Web APIs.
High-performance modular request pipeline suitable for modern,
cloud-optimized applications.
Figure 1-1 shows the layers of ASP.NET Core.

Figure 1-1 Layers of .NET Core and ASP.NET Core

As you can see from Figure 1-1, the bottommost layer is the
operating system. Because .NET Core is a cross-platform framework,
this could be Windows, Linux, or macOS. Your web application code is
going to be the same regardless of the underlying operating system.
To develop and run .NET Core applications, you must have language
compilers and other necessary runtime components. They are installed
when you install .NET Core on the machine.
The next layer primarily consists of the .NET Core libraries and
framework-level services. These libraries provide you several features
including data types and file IO. ASP.NET Core makes use of the .NET
Core libraries and hence is shown sitting on top of this layer.
ASP.NET Core offers three main development options, namely,
ASP.NET Core MVC, ASP.NET Core Razor Pages, and ASP.NET Core Web
APIs. These options make the top layer of the diagram.
ASP.NET Core is built considering modularity. Most of the ASP.NET
Core applications (MVC/Razor Pages/Web APIs) make use of
functionality that resides in NuGet packages.
From the preceding discussion, you know that there are three
primary development options – MVC, Razor Pages, and Web APIs. Let’s
discuss each of them briefly before we go into the code-level details.

Note You can also use Blazor to build interactive rich client-side UI
using C#, HTML, and CSS. However, Blazor is a relatively new
addition to the ASP.NET Core family and hence is not discussed in
this chapter. You learn more about Blazor in Chapter 8.

ASP.NET Core MVC


ASP.NET Core MVC allows you to build web applications using the
Model-View-Controller (MVC) pattern. Although detailed discussion of
the MVC pattern is beyond the scope of this book, a brief discussion of
MVC as applicable to ASP.NET Core follows.
The responsibility of a web application built using ASP.NET Core
MVC is divided into three components: model, view, and controller.
Model represents the application’s data and could be anything from a
primitive type to a complex object. View houses the application’s user
interface (UI) and usually displays data held by the model. View also
accepts user input and commands. Controller mediates between a
model and a view. Its job is to prepare the model required for a view
and also to act upon the user input and commands as captured by the
view. It also decides the program flow by deciding which model and
Random documents with unrelated
content Scribd suggests to you:
Some were condemned for dishonesty and appropriation of the
public treasure. Others, among them the son of Al-Mansur, and
another Abdallah, who was of royal lineage and noted for his
avarice, fled to the Christian court for protection. Garcia Fernandez,
Count of Castile, entertained the son of the minister, until the
presence of a great Moslem army admonished him that the privilege
of asylum must yield to political necessity. As soon as the misguided
youth fell into the hands of his father he was beheaded. Then, with
exquisite cruelty, Al-Mansur devised a scheme of retaliation, which,
in spite of its malice, was singularly appropriate. He determined to
inflict upon the Count of Castile himself all the pangs resulting from
paternal disappointment and filial ingratitude. He instigated Sancho,
the son of Garcia, to form a party and drive his father from power.
The nobility unanimously declared for Sancho; a Mussulman force
sustained his pretensions; Al-Mansur seized Clunia and San
Estevan as his share of the spoil; and Garcia, having been wounded
and made captive in a skirmish, died soon afterwards in the hands of
the Saracens. The perfidy of Sancho was rewarded with the
government of Castile, which he held as a feudatory of the Khalif.
The fugitive King, Bermudo, whose usurpation had been attended
with a series of misfortunes, and whose dominions had, with the
exception of a contracted region of which Astorga was the centre,
been divided between his rebellious vassals and the Moors, in
defiance of the menaces of Al-Mansur, still continued to afford
protection to Abdallah, the only survivor of the principal conspirators.
The approach of the Mussulman troops and the seizure and sack of
Astorga, convinced the obstinate monarch of the expediency of
submission. Abdallah was surrendered, taken to Cordova, placed
upon a camel, and conducted through the streets of that city,
preceded by heralds who proclaimed him a traitor to his sovereign
and an apostate to his faith. His life was spared, but he was tortured
during the entire administration of Al-Mansur by being kept in daily
fear of execution; a fate which he endeavored to avert by the most
humiliating expressions of contrition, and by exhibitions of grovelling
servility which, so far from exciting the pity of the minister, only
increased his contempt.
A new and implacable adversary, and one whose position placed
her beyond the reach of the minister’s vengeance, now arose to defy
his power. The Sultana Aurora—who united to her amorous
susceptibilities all the obstinacy and vindictiveness of the Basques,
to which race she belonged—had for many years entertained the
closest relations with the favorite whose fortunes she had founded,
and whose success she had so zealously promoted. Their intimacy,
even during the lifetime of Al-Hakem, had been the scandal of the
capital. But the lady, like many of her sex, was inconstant, and other
lovers, including the kadi Ibn-al-Salim, also stood high in her favor.
As soon as Al-Mansur no longer required her services to advance
his interests, he had the imprudence to neglect his haughty mistress.
Deeply piqued, she began to meditate revenge. Her social rank, the
inviolability of her person, and her residence in the palace gave her
advantages which she was not slow to improve. With all the fiery
energy of her nature she represented to the Khalif the degradation of
the position he had been compelled to assume, and urged him to
assert his rights as a sovereign. Hischem, who had hitherto evinced
no dissatisfaction with his condition, was roused from his lethargy.
Under his mother’s dictation, he made a formal demand on the
minister for the prerogatives which the latter had usurped. The
viceroy of Africa, Ziri-Ibn-Atia, instigated by the agents of the
Sultana, rose in rebellion, and proclaimed himself the supporter of
the laws of the empire and the champion of its injured monarch. The
ingenuity of Aurora provided her partisans with an abundant supply
of money. The vaults of the palace of Medina-al-Zahrâ, where was
the national treasury, contained six million pieces of gold. They were
deposited in earthenware jars, sealed with wax and impressed with
the royal signet. The astute princess removed a hundred of the jars,
whose contents amounted to the sum of eighty thousand dinars,
broke the seals, covered the gold with honey, drugs, and syrups,
and, having attached to each an appropriate label, caused them to
be conveyed by her slaves to a palace in the city, whence they were,
without delay, transported to Africa. The rage of Al-Mansur on finding
himself thus outwitted by a woman was extreme, but it availed him
nothing. He could not venture to offer violence or even reproaches to
the mother of his sovereign whose servant he was in name. The
trend of recent events suggested that Hischem might have
consented that the money be employed for the recovery of his
imperial dignity. Desirous of obtaining the sanction of law in a matter
of such vital importance, Al-Mansur called the great officers of state
together. To them he represented that the women of the harem were
plundering the treasury, and requested permission to remove the
gold from the palace. This was readily granted; but when the officers
exhibited their warrant, they were refused admission to the vaults, on
the plea that the Khalif had not authorized the removal of the
treasure. Foiled once more, the minister—whose genius, fertile in
expedients and undaunted by reverses, never once despaired of
success—devised a plan whose audacity would have appalled a less
determined mortal. Perfectly familiar with all the approaches to the
palace, he penetrated by a secret passage to the apartments of the
Khalif. His unexpected appearance and menacing aspect terrified
the imbecile prince, who protested that he had no desire to thwart
the designs of the minister, and, without hesitation, signed an order
for the removal of the gold. The politic Al-Mansur, at the same time,
extorted from him an edict by which he unreservedly renounced, in
favor of the hajib, all practical control of the government of the
empire. This explicit and indisputable confirmation of the authority of
the latter at once legalized every act which he had already
committed in a public capacity. In a measure, it invested his person
with the sanctity that appertained to his master, and rendered all
liable to the penalty of treason whose intemperate language or
whose violence should be directed against the authorized
representative of absolute sovereignty.
An enterprise of surpassing difficulty and danger, and one which
the bravest of the Ommeyade khalifs had never ventured to
undertake, was now planned by the greatest statesman and warrior
of his age. The shrine of St. James of Compostella was one of the
most renowned for wealth and sanctity in Christendom. In the
marvels which had attended its foundation, in the fame of its
miracles, in the number and potency of its sacred relics, in the
touching interest attaching to its legends, it scarcely yielded to the
sacred traditions of the Eternal City. A countless multitude of pilgrims
from every country where the name of the Saviour was revered had
for generations deposited their oblations upon its altars. The modest
chapel which had marked the site of the apostle’s grave soon after
its discovery during the reign of the pious Alfonso had been replaced
by a stately cathedral of marble, decorated with all the rude
magnificence of which the decadent art of the age was capable. A
numerous priesthood, the splendor of whose appointments and the
luxury of whose lives indicated a dispensation with the vow of
poverty, ministered to the wants of the pilgrims, and acknowledged,
with affected gratitude and humility, the bestowal of their donations
and the performance of their vows.
The reverence entertained by the Spanish Christians for the
sepulchre of St. James far exceeded that with which the most fanatic
Mussulman regarded the Prophet’s tomb at Medina. Already,
industriously propagated by monkish imposture and popular
credulity, wondrous tales were whispered of the appearance of the
apostle on a milk-white steed at the head of the Christian squadrons,
an infallible harbinger of victory, and a delusion of ominous import to
the Saracen intruders in the Peninsula. History affords no parallel to
the momentous effects produced by the adoption of this frivolous
legend. The circumstances of its origin, which contemptuously
violated every probability of time or place; its universal acceptance
by individuals of every rank in life; its subsequent extension to the
distant lands of an unknown world; the blind and unquestioning faith
with which the impossible miracles of its subject were received, offer
an eloquent commentary on the boundless influence of the Catholic
hierarchy and the debased superstition of the age.
The destruction of the church of Santiago was now the aim of Al-
Mansur. The depressing influence of such a signal triumph over the
adversaries of Islam, it was thought with much reason, would be
incalculable. The immunity enjoyed by the Christian sanctuary of
Spain was attributed by its votaries to the protection afforded by the
body of the saint, far more than to the natural difficulties which an
enemy must surmount to reach his shrine. Even could an invasion
occur and the desecration of the cathedral be threatened, it was
firmly believed that the miraculous intervention of Heaven—more
marked even than that which deterred the Romans from rebuilding
the temple of Jerusalem—would avert such a calamity from one of
the holiest places of the Christian world. The removal of these
impressions, by demonstrating the incapacity of St. James to defend
his own relics, must certainly weaken the faith of the multitude in his
ability to protect the lives of others. The prestige derived from the
interposition of supernatural influence would be seriously impaired.
The menacing spectre of the patron of Spain would no longer inspire
the fanaticism of his followers to strike terror into the Saracen
armies. These conclusions of Al-Mansur, while founded on reason, in
the end proved fallacious. The superstitious veneration, which,
confirmed by blind ignorance and credulity for centuries, now
exercised its power over an entire people, was too deeply rooted to
be more than temporarily affected by the most glaring sacrilege.
The campaign was carefully planned. Every precaution was taken
to provide against any possibility of failure. Marching westward, the
several divisions of Moslem cavalry assembled at Coria. At Oporto
they were joined by the fleet, in which the infantry had already
embarked. A number of Christian vassals, attended by their
retainers, responded to the summons of their suzerain, and lent their
reluctant aid to the injury of their faith and the destruction of their
countrymen. The Douro was crossed upon a bridge constructed of
ships. Roads were cut through rocky and precipitous mountains.
Broad estuaries and rivers were forded. The country, which had long
suffered from repeated forays, was depopulated, and could offer no
resistance. When the mountains of Galicia appeared in the distance,
the resolution of the Christian allies faltered. Some of the counts
entered into a secret correspondence with the enemy. Their designs
were betrayed, and a number of Leonese nobles underwent the
extreme penalty of treason. This salutary example insured the
wavering loyalty of their companions, who henceforth found it
expedient to conceal their real sentiments under an appearance of
obedience and alacrity.
The region now traversed by the Moslems had hitherto been safe
from their inroads. This circumstance, the sacred character of the
territory, and the wealth of the clergy had attracted to the vicinity of
Santiago a large and busy population. Ecclesiastical establishments
abounded. Along the hill-sides were countless hermitages, shrines,
and chapels. Almost every valley was occupied by a monastery or a
convent. The lands susceptible of cultivation were tilled by slaves or
dependents of the religious houses, whose condition differed little
from that of hereditary servitude. The mansions of the prelates of
high rank exhibited a palatial magnificence, and were not
infrequently tenanted by occupants of the softer sex, whose charms
of face and figure indicated an appreciation of female beauty hardly
to be expected from their pious companions.
The utter demoralization of the Christian kingdoms through
domestic feuds and incessant warfare, added to the terror inspired
by the name of Al-Mansur, precluded the possibility of effectual
resistance. The inhabitants, taking with them their portable property
and the bones of their saints and kings, fled to the mountains or to
islands off the sea-coast. Santiago was completely deserted. The
invaders obtained a rich booty from the shrines of innumerable
chapels and monasteries. Every building in the city, including the
famous cathedral, was razed to the ground. The latter was
constructed of marble and granite. Its plan and decoration exhibited
the corrupt taste and barbaric splendor inherited from the Visigoths,
whose faults of design had been aggravated by the native rudeness
of the Galician architects. In front of the high altar stood the statue of
the saint, carved by the pious but unpractised hand of a Gothic
sculptor, and enclosed in a shrine of massy silver. Every portion of it
except the face was painted or profusely gilded. One hand clasped a
Bible, the other was raised aloft in the attitude of benediction. The
kisses of innumerable pilgrims had almost obliterated the coarse and
grotesque features of the image. By its side were disposed the
emblems of the vagrant apostle, the staff, the calabash, the scallop
shells. Its head was partially enveloped with a hood identical in
shape with that worn by every pilgrim and glittering with jewels.
The statue and the tomb of the apostle escaped desecration,
through the policy of Al-Mansur, who feared to exasperate his allies,
already shocked by the sacrilegious deeds of their infidel
companions in arms. This forbearance of the Moslem general was
afterwards distorted by the clergy into a stupendous miracle. The
Mauritanian cavalry plundered the neighboring settlements and
intercepted many parties of fugitives, including not a few
ecclesiastics, whose faith in the supernatural virtues of the image
and the relics of the saint vanished quickly before the gleaming
lances of the Saracen cavalry.
The return of the army to Cordova was signalized by a military
demonstration that rivalled the pomp of a Roman triumph. In the rear
of the troops, chained together by fifties, thousands of Christian
captives, laden with the spoils and trophies of victory, trudged
painfully along. Some carried the sacrilegious plunder of many a
venerated shrine. Others supported upon their shoulders the
ponderous gates of the city of Santiago. Others, again, sank under
the weight of the bells of the cathedral, into whose molten mass, as
yet unformed, pious devotees of either sex had cast their treasure
and their jewels; whose clangor had solemnized the installation of
many a prelate and the sepulture of many a saint; had aroused the
enthusiasm and the devotion of pilgrims of every clime; had, until this
fatal hour, been heard in a land believed to be exempt from the
outrages of the infidel, but were now destined to be exhibited in his
greatest temple as tokens of the supremacy attained by the most
implacable foe of Christianity. In the addition to the Great Mosque,
then building under the direction of Al-Mansur, these souvenirs of the
most memorable campaign undertaken by the arms of the Western
Khalifate were deposited, amidst the frenzied acclamations of the
people. The gates were used to form a portion of the ceiling, and
from them, sustained by chains of bronze, the great bells were hung
inverted, to be utilized as lamps during the ceremonies of the
numerous festivals prescribed by the Moslem ritual.
The career of the Mauritanian rebel Zira-Ibn-Atia, whom the
prodigality of the Sultana Aurora had enabled to assert his
independence, under pretext of liberating the Khalif, was not of long
duration. The first army sent over by Al-Mansur to chastise his
insolence met with disaster. The second, commanded by his own
son, Abd-al-Melik-al-Modhaffer, vanquished the forces of Zira after a
desperate struggle. The latter, with the loss of his possessions, was
also stripped of his power, and died soon after of wounds received in
battle.
Early in the spring of the year 1002 the indefatigable Al-Mansur
again invaded the territory of the Christians. This time his hostility
was directed against the shrine of St. Emilian, the patron saint of
Castile, whose church was in the village of Canales. The town, the
chapel, and the convents, with all their paraphernalia of priestly
imposture and superstition, were destroyed. But the renowned
commander, whose prowess had so long sustained the reputation of
the Moslem arms, had fought his last campaign. A painful malady,
whose cause was unknown, and whose symptoms baffled the skill of
the best physicians of Cordova, had some months before attacked
him. The exposure and excitement of this expedition increased its
violence. The illustrious sufferer became so weak that he was forced
to travel in a litter. It was evident from his emaciated form and
incessant agony that he was fast approaching his end. At Medina-
Celi the army halted. Its general could proceed no farther. A
universal feeling of sorrow arose as the sad tidings of the condition
of the dying chieftain spread throughout the camp.
The memory of the turbulent populace of the capital, and the
consciousness that it had required all the energy of his determined
character to triumph over his domestic enemies, embittered the last
moments of Al-Mansur. He dreaded the inauguration of anarchy and
the resultant partition of the khalifate. He was only too well
acquainted with the instability of the vast and magnificent fabric of
greatness which his genius had reared. With a view to preserve as
long as possible for his sons the power he was unable to legally
transmit, he directed Abd-al-Melik to hasten at once to Cordova and
assume command of the garrison. To his second son, Abd-al-
Rahman, he transferred his authority over the army. Many wise
injunctions were imparted by their dying parent to these two young
officers, whose military character had been formed under his own
eye during many eventful campaigns. The elder, who was not an
unworthy descendant of so great a sire, profited largely by his
opportunities. The younger, unequal to the task of government, was
destined to realize the worst expectations his acquaintances had
formed of his erratic and licentious nature.
His instructions ended, the strength of Al-Mansur gave way, and
he received with calm resignation the inexorable summons of the
Angel of Death. For years he had entertained a presentiment that he
should end his days at the head of his army, perhaps in the heat of
battle. It was not only his hope, but he made it the subject of his daily
petitions, that Allah would vouchsafe to him the glorious privilege of
dying in war against the infidel, thereby to merit the recompense of
martyrdom. In expectation of a favorable answer to his prayers, the
arrangements for his burial were always ready. His shroud was
invariably included among the effects of his camp equipage. It was of
linen made from flax grown on his paternal estate at Torrox and
woven by the hands of his own daughters. His conscience told him
that the material thus produced and prepared was not tainted with
the bloody reminiscences that popular report insinuated too often
attached to his other possessions. The provident statesman, whose
aspirations were not confined to matters terrestrial, and carrying into
his relations with Allah the same prudence which had distinguished
his earthly career, neglected no precaution to insure his salvation. A
well-known text of the Koran declares that he who appears before
the Almighty with the dust of the Holy War upon his feet shall be
exempt from the tortures of eternal fire. To secure this advantage on
the Day of Judgment, Al-Mansur carried with him in all his
campaigns a silver casket of elegant design, into which, every
evening when the army halted, his attendants carefully collected the
dust which had accumulated upon his garments during the day.
Enveloped in the shroud prepared for so many years, and sprinkled
with this holy dust, the body of the great Moslem general was laid at
rest in the city of Medina-Celi.
The character of Mohammed-Ibn-Amir-Al-Mansur has already
been partially delineated in these pages. In it both good and evil
were unsparingly mingled. Beyond measure shrewd, politic,
audacious, and resolute, he was an adept in instigating others to the
commission of discreditable acts by which he profited, while his
instruments alone endured the odium attaching to them. By the
irresistible force of intellect he had risen from obscurity to the
enjoyment of imperial power. No act of wanton cruelty ever polluted
his administration. Yet such was his firmness and the fear in which
he was held that no sedition during his ascendency disturbed the
peace of the khalifate. His conduct on all occasions where his
personal interests were not immediately concerned was, for the most
part, guided by the principles of equity. His own son was sacrificed to
the maintenance of public order. The deeds of violence and tyranny
for which he was so grossly abused were the results of political
necessity,—measures suggested by the pressing exigencies of the
occasion, and dictated by the instinct of self-preservation. Born in a
comparatively humble rank of life, his matrimonial alliances were
sought by princes. The daughters of Bermudo, King of the Asturias,
and Sancho, King of Navarre, were inmates of his harem. Despite
his talents as a statesman and his long series of military triumphs,
his popularity was superficial, and his position was maintained with
difficulty. He was everywhere designated by the significant and
opprobrious nickname of “The Fox.” His old literary associates
envied and maligned him. The courtiers were jealous of his rapidly
acquired fame, and sedulously depreciated his abilities. The
eunuchs justly attributed to his agency the impairment of their
political fortunes, and held him in detestation as the relentless
enemy of their caste. The aristocracy sneered at his pretensions and
privately denounced him as an insolent parvenu. The fanatical
populace repeated his alleged atheistic speeches with pious horror,
a feeling which even his ostentatious charity and apparently strict
observance of the duties of a faithful Mussulman could not
counteract. Inconsistent with the encouragement of literature, as the
narrow policy which delivered the scientific works of the library of Al-
Hakem to the tender mercies of ignorant bigots would seem to
indicate, Al-Mansur was, nevertheless, a munificent patron of letters.
His house was so frequented by men of genius and literary
proclivities that it was compared to an academy. He often visited the
University, listened to the lectures of the teachers, and rewarded the
proficiency of the students. By his express orders the recitations
were not suspended either at his entrance or his departure. Many of
the most accomplished scholars of the East and West continued
under his auspices, as they had done under those of Al-Hakem, to
adorn the court, and to delight with their learning the critical and
fastidious society of Cordova. A special fund, appropriated from the
public treasury, was assigned for the support of these distinguished
guests of the State. Famous grammarians, poets, and historians,
who found this a lucrative field for the exercise of their talents, took
up their residence in the capital. The reputations of the physicians
and surgeons of Andalusia, now greater than ever, had long since
spread to the remotest borders of Europe. Whenever Al-Mansur
undertook an expedition, there followed in his train a number of
bards and chroniclers, who could without delay record his
achievements, and celebrate in the most stirring and pathetic strains
of which the poesy of the Desert was capable the valor, the
generosity, the piety, of the renowned champion of the Moslem faith.
Forty-one of the most accomplished literary men of the empire
accompanied the army for this purpose during the Catalonian
campaign.
The enlargement of the Mosque, whose size was doubled by the
additions of Al-Mansur, was undertaken quite as much to restore his
failing credit with the ministers of religion as to accommodate the
vast and increasing crowds which on Fridays assembled in the
House of God. The land required for the extension was paid for at
twice the valuation, already sufficiently exorbitant, estimated by the
owners themselves. In the garden of an old woman, whose premises
it was absolutely necessary for the architect to secure, stood a
magnificent palm. At first she obstinately refused to sell her property,
but after repeated solicitations she consented to exchange it for
another residence in whose grounds was a tree of equal size and
beauty. But even amidst the tropical vegetation of the environs of
Cordova such a condition was not easily complied with. At length, in
the vicinity of Medina-al-Zahrâ, an estate which possessed the
desired requisite was procured at a fabulous price.
In imitation of his predecessors the khalifs, Al-Mansur performed
for weeks the duties of a common laborer on the foundation and the
superstructure of the Mosque. This addition, still intact, constructed
of coarse materials and unsymmetrical in form, is readily
distinguishable from the rest of the interior, whose sweeping
horseshoe arches and exquisite decorations are models of grace
and beauty. So meritorious was this work considered by the
Mussulman theologians, that they declared that its accomplishment
alone was sufficient to obtain for its author a seat in Paradise.
The energy of Al-Mansur was far from being consumed in military
expeditions and the pursuit of glory. In the frequent intervals of
peace his efforts were largely directed to improving the condition of
his subjects, the highest and most noble title to distinction to which a
ruler can aspire. He reformed the abuses which had crept into the
administration of justice. He checked the peculations which were
exhausting the treasury, by the institution of a rigid system of
accounts and the severe punishment of dishonest officials. He
sternly rebuked the intolerance of zealots who attempted to
establish, without his sanction, a policy of persecution for opinions
which they considered heretical. With his advent to power, the
malignant influence of the eunuchs was no longer felt in the
precincts of the court, and the uneasy genius of this pernicious class
was diverted from the tortuous paths of political intrigue to the
harmless and pleasing occupations of literature and art. He improved
the breed of horses by the importation of the purest blood of Arabia.
There was scarcely a river in Andalusia which could not boast of a
bridge either built or repaired by the orders of the able and tireless
minister. New highways were opened. Old ones were widened and
extended. By these wise acts of public utility not only was the march
of troops facilitated, but the trade of country and city was
prodigiously increased, with a corresponding diminution of the price
of provisions, whose abundance and cheapness materially benefited
all classes of the population. The best commentary on his
transcendent abilities is found in the fact that the empire which he
had ruled with such glory and success perished with him. His
majestic personality dominated everything. In the history of Islam no
similar example of universally recognized individual superiority has
ever been recorded. This extraordinary genius seemed impregnable
to the temptations which usually assail the favorites of fortune. He
was addicted to none of those unnatural vices whose practice defiled
the characters of even the greatest of the Ommeyades. His harem
was maintained rather as an accessory to his dignity than as an
instrument of his pleasures. His amour with Aurora, which had
provoked the sarcastic jests of the populace, had been from first to
last a mere matter of policy. The passion of the Sultana he had
deliberately used as the instrument of his ambition; when it had
served his purpose it was as deliberately cast aside. With every
opportunity for the accumulation of untold wealth, Al-Mansur
acquired no more than was necessary to sustain the pomp incident
to his exalted rank. Avarice had no place in his nature. His own
treasure as well as that of the government he freely dispensed in
charitable donations. The slightest act of extortion committed by one
of his subordinates was met with chastisement that barely left the
offender with life. No one who had merited his gratitude was ever
forgotten in the distribution of official honors. No one whose
insolence had at any time provoked his indignation went unpunished.
In the accomplishment of his ambition, he persistently ignored the
most obvious principles of morality. In his administration of petty
offices of the inferior magistracy and of the highest employments of
the state alike, he ordinarily observed the rules of the most impartial
justice. After every victory gained by his arms he liberated hundreds
of slaves.
A delusive appearance of moderation is suggested by the conduct
of Al-Mansur, when we reflect that he denied himself the more than
regal prestige which attached to the name of Commander of the
Faithful. There is no doubt, however, that he ardently coveted that
distinction. The possession of the substance of power did not satisfy
his lofty aspirations. He arrogated to himself the remaining titles of
the Khalif, as he had already appropriated the latter’s prerogatives.
He substituted his own seal for that of the injured Hischem. He boldly
assumed the right to appoint his son to the office of prime minister,
the very employment from which he himself derived his entire
authority. The brilliancy of his achievements, the extent of his
renown, the autocratic exertion of his power, had awed and dazzled
his subjects, but had not secured their attachment. The masses
openly applauded and secretly detested him. The various nations
composing the population of Moorish Spain, while mutually hostile in
many respects, were firmly united in their reverence for the
inalienable rights of the crown. The religious character which
invested the Khalif deepened and intensified this feeling. The
sagacity of Al-Mansur did not suffer him to be deluded with the idea
that he could violate with impunity the most sacred opinions and
prejudices of the people. Moreover, an ancient tradition, universally
believed, declared that a change of the dynasty portended the
speedy destruction of the khalifate. The man who in defiance of
these ideas could attempt open usurpation was a public enemy,
something worse, if possible, than a traitor. For these cogent
reasons, therefore, Al-Mansur did not seize the royal office, which,
had he been able to assume it, might perhaps have retained the
succession in his own family. As it was, he weakened the veneration
entertained for the principle of legitimacy, without acquiring for his
descendants any permanent advantage in return for the sacrifice. No
one realized these facts so thoroughly as himself. The future of the
empire engrossed his thoughts. It presented itself to his mind amidst
the deliberations of the Divan, in the literary discussions of the
University, in the manœuvres on the field of battle. It disturbed his
slumbers. It embittered his dying moments. The mortal torture he
endured from the reflection that by his agency the integrity of the
khalifate had been irretrievably impaired, and that he could not
transmit the inheritance of his glory, was almost as intense as any he
could have experienced through remorse for crimes perpetrated in
the pursuit of his unrighteous ambition.
The history of the campaigns of Al-Mansur differs materially from
that of the military enterprises of his predecessors. Heretofore, in all
important wars, the Christians were the aggressors. But under the
minister of Hischem the Moslems always led the attack. Other rulers
had negotiated treaties either prompted by victory or compelled by
defeat. In twenty-five years he never made terms with the infidel. His
success became habitual, and infused a just confidence into his own
followers, while in a corresponding degree it disheartened the
enemy. Almost for the first time in the annals of Islam the peremptory
injunction of the Koran was fulfilled to the letter. The effects of one
campaign were not repaired before the calamities of another were at
hand. The frontier to the Christian states receded. The great cities of
Zamora, Leon, Astorga, Barcelona, Pampeluna, Santiago were
levelled with the dust. Cathedrals and monasteries were plundered
of wealth bestowed by pious sovereigns and generations of grateful
devotees. The incomes of the priesthood ceased on account of the
devastation of their estates. With the ruin of the religious houses and
the impoverishment of their occupants, the Christian worship
declined. The prestige of the ecclesiastical order was weakened, and
over an extensive region once abounding with churches and
convents scarcely a reminiscence of Christianity survived. By the
successive desecration of the two holiest shrines in Europe, the faith
of the multitude in the boasted efficacy of relics, in the celestial
intercession of saints, and even in the value of religion itself, was
seriously shaken. The misfortunes of the clergy—who still, however,
retained a portion of their ancient discipline—reacted on the other
divisions of society, already sufficiently demoralized. The monarch
and the nobles evinced a disposition to resist the insolent demands
of the priesthood, and have been, in consequence, anathematized
by prelates and defamed by chroniclers. The king seized without
ceremony the property of his subjects. The barons plundered the
royal estates, and cast lots for the serfs and the flocks which they
had appropriated. In less than twenty years the Christians lost all
they had gained in the previous three hundred. Even the defiles of
their mountains were occupied by Moorish garrisons, and the
Asturian peasant was compelled to purchase the uncertain privilege
of procuring his own sustenance by the surrender of the larger share
of the results of his labor. Such were the effects of the policy of Al-
Mansur on the two rival nations of the Peninsula, a policy whose
benefits perished with the author, but whose evils were destined to
be augmented and perpetuated through a long period of national
misfortune and disorder.
Berber immigration, encouraged by the conspicuous favor
enjoyed by the African divisions of the army, as well as by the rich
rewards of successful warfare, and which was fated to inflict such
disasters upon the dismembered monarchy, increased beyond
precedent during the administration of Al-Mansur. Entire tribes
passed the Strait to share the tempting spoil of the Holy War. There
was no room for these ferocious soldiers in the crowded cities. Even
in the country, so thickly populated, space could hardly be found for
their encampments. Their tents were pitched in the pastures and on
the slopes of the sierra. Their fierce aspect appalled all who beheld
them. Their costumes and their arms were strange and foreign.
Ignorant of Arabic, the guttural accents of their Mauritanian dialect
grated upon the ears of the polished Andalusian. In times of the
greatest victories, when the people were intoxicated with success,
there were discerning men who dreaded the ascendency of such
dangerous allies. It was, however, the inexhaustible supply of African
recruits which secured the unbroken series of triumphs that
signalized the career of Al-Mansur. Their numbers were
overwhelming. In a review held before an expedition into the North,
six hundred thousand troops were mustered in the plain of Cordova.
The news of the death of the potent minister was received by the
majority of the inhabitants of the capital with a feeling of exultation.
With the multitude, his eminent services could not atone for the
obscurity of his birth or the splendor of his fortune. The animosities
of contending sects, the jealousies of competing tradesmen, the
envy of the masses towards the powerful, the disdain of the wealthy
for the poor, were forgotten in the common desire to humiliate the
family of the great chieftain through whose genius the Moslem
empire had enjoyed such an extraordinary measure of prosperity
and fame. An insurrection broke out. The mob, surrounding the
palace, demanded that the Khalif in person should assume the
direction of affairs. But the latter, who now, more than ever, felt his
incompetency to govern, again voluntarily renounced the rights of
sovereignty. The tumult increased; the garrison was called out, and
Al-Modhaffer signalized his accession as hajib by the massacre of
several hundred citizens. This example of severity was not soon
forgotten; the spirit of revolt was crushed, and Al-Mansur, who on his
death-bed had foreseen the occurrence of a similar catastrophe,
thus averted by his prophetic wisdom a rebellion, which, unchecked,
must have been productive of appalling consequences. The prince,
Al-Modhaffer, inherited in no small degree the military talents and
capacity for civil affairs possessed by his father, whose maxims he in
the main adopted. Few details exist relative to his administration,
which, however, was eminently popular and successful. The
expeditions he made into the Christian territory were not attended
with the brilliant results which characterized the exploits of his father.
Neither profit nor glory could be derived from the invasion of a desert
and the chase of bands of wandering robbers. These forays,
however, served the useful purpose of intimidation, and impeded the
recovery of the Christian power. Relieved from the prodigality and
great military expenses incurred by the aggressive policy of Al-
Mansur, the inexhaustible resources of the Peninsula were permitted
to develop to the utmost. Commerce, manufactures, agriculture,
flourished to a degree heretofore unknown. The rule of Al-Modhaffer
is regretfully alluded to by subsequent writers as coincident with the
golden age of Moslem annals.
After a reign of seven years, Al-Modhaffer died, under
circumstances which raised a strong suspicion of poison. By a
previous arrangement, which popular rumor suggested as the motive
of his death, his office was transferred to his brother, Abd-al-
Rahman. The latter was the offspring of a Christian princess, the
daughter of Sancho, King of Navarre. By his vices and his
blasphemy he had incurred the dislike of the people and provoked
the execration of the theologians. The former, in memory of his
infidel grandfather, fastened upon him the diminutive “Sanchol,” an
epithet of contempt. The latter recounted with indignant horror his
immoderate indulgence in wine and his open ridicule of the sacred
ceremonies of Islam. Aware of his unpopularity, Abd-al-Rahman
nevertheless continued to outrage public sentiment, and made no
attempt to gain the attachment of his subjects or to conciliate his
ecclesiastical adversaries. He even had the audacity to ask of
Hischem his investiture and acknowledgment as heir presumptive to
the throne. The Khalif was prevailed upon, partly by sophistry, partly
by threats, to comply with this extravagant and impolitic demand,
and an edict was drawn up in due form and published, proclaiming
the detested Sanchol heir to the titles and the authority of the
illustrious dynasty of the Ommeyades.
No measure could have been devised by his most bitter enemy so
fatal to the aspirations of its promoter as this concession wrung from
a reluctant and persecuted sovereign. It was alike an insult to
religion and to loyalty. It attacked the sacred character of the
Successor of the Prophet, while attempting to abrogate the
prerogatives which, in the eye of the devoted subject, were
inseparable from the condition of sovereignty. Sanchol further
increased the prevailing discontent by compelling the soldiers to
discard the helmet for the turban, an innovation which, appropriating
a distinctive portion of the attire of theologians, was generally
regarded as a flagrant act of sacrilege.
Careless of public opinion, and confident of the stability of his
power, Sanchol began to entertain aspirations to military distinction.
He led an expedition into the Asturias, the results of which were not
flattering to his vanity. The mountain defiles, filled with snow,
impeded his progress, and the scarcity of provisions, which he had
neglected to provide in sufficient quantities, finally compelled him to
retreat. In the mean time Cordova was in revolt. A band of
conspirators headed by Mohammed, a great-grandson of Abd-al-
Rahman III., surprised the citadel. The unfortunate Hischem, the
puppet of every faction, was compelled to abdicate. The religious
fanatics and the populace hailed the change of government with
extravagant expressions of joy, a feeling by no means shared by the
wealthy and intelligent, who anticipated with undisguised concern the
destructive tyranny of a succession of military adventurers.
The first act of Mohammed was the seizure of Zahira. The
stronghold of the Amirides was entered and sacked by an infuriated
rabble. For four days the beautiful palace founded by Al-Mansur was
at the mercy of the revolutionists and outlaws of the capital. The long
rows of villas, which, embosomed in shady groves of palm- and
orange-trees, stretched away to the Guadalquivir, were visited with
the same destruction. Everything portable, even to the woodwork,
was removed. No estimate could be made of the plunder secured by
the mob, who ransacked every apartment; but the soldiers of
Mohammed delivered to their master two million one hundred
thousand pieces of silver and a million five hundred thousand pieces
of gold. The torch was then applied and the entire suburb was
reduced to ashes. The stones were gradually appropriated for the
construction of other buildings, and in a few years the memory as
well as the ruins of the seat of the Amirides had completely
vanished.
When the intelligence of these events was transmitted to Sanchol
at Toledo, he set out at once with his army for Cordova. The march
had scarcely begun before he experienced the full extent of his
unpopularity, which heretofore he had refused to believe. His force
was diminished daily by desertions. Many of the soldiers who
remained refused to obey their officers. At a short distance from the
capital, the Berbers, on whom he placed his main reliance, left the
camp at midnight, and morning found the commander with a slender
retinue, whose number did not equal that of his ordinary body-guard.
Notwithstanding these ominous indications, the infatuation of
Sanchol, who fancied that the people of Cordova would, by the mere
effect of his presence, be induced to return to their allegiance, urged
him on to his ruin. He was seized by the troops of Mohammed,
beheaded, his body clothed in rags and nailed to a stake, and then
placed with the head—which was impaled on a pike—in one of the
most public quarters of the city. With the death of Sanchol, the rule of
the Amirides, who, in a subordinate capacity, had for a generation
exercised despotic power, and whose policy was destined to visit
upon their countrymen a long series of misfortunes, terminated
forever.
The pernicious effects of the practical usurpation of Al-Mansur
now became apparent. The ambition of every aspiring partisan was
encouraged by the example of that gifted leader whose extraordinary
talents had raised him to such a height of affluence and renown.
Mohammed was no sooner fairly seated upon the throne, when
the populace again began to murmur. The excitement of revolution,
once enjoyed, was too pleasant to be abandoned for the severe
restraints of law and social order. And in reality only too much cause
existed for popular dissatisfaction. The new sovereign was cruel,
rapacious, dissolute. He took the heads of rebellious vassals sent
him by his generals, had them cleansed, and the skulls—in which
flowers had been planted—arranged in fantastic designs in the
garden of his palace. His drunken and licentious orgies were the
reproach of the court. He alienated the theologians, who soon
discovered that they had made a bad exchange for even the
dissipated and impious Sanchol. He persecuted the Berbers, who
had inherited the vices and the unpopularity of the eunuchs, but who
for a quarter of a century had been the support of the monarchy. To
avoid the possible restoration of Hischem, he publicly announced his
death, substituted for his corpse that of a Christian killed for the
occasion, and who bore a striking likeness to the Khalif, and
celebrated his obsequies with all the magnificence due to departed
royalty. The performance of the rites of Mussulman burial over the
body of an infidel was, in the eyes of every true believer, a deed of
unparalleled infamy. The unpopularity of Mohammed increased daily.
A sedition broke out headed by Hischem, a grandson of Abd-al-
Rahman III., who boldly demanded the crown of his kinsman. The
usurper pretended to accede, and secretly despatched emissaries to
incite the Berbers to plunder the capital. The scheme was
successful; at the first appearance of these detested foreigners in
the market-place, the tradesmen arose in a body and, aided by the
royal body-guard, drove the Africans from the city. The pretender
was taken in the confusion attending the skirmish and immediately
executed.
His place was filled by Suleyman, another prince of the
Ommeyade line. Negotiations were entered into with the Count of
Castile, who, in consideration of the surrender of certain territory,
agreed to furnish a large contingent of men and horses. As soon as
their organization was effected, the Berbers marched on the capital.
A battle was fought on the plain of Cantich, but the disorderly rabble
of Cordova were unable to resist the fierce onset of the African
cavalry, and ten thousand of the partisans of Mohammed fell by the
sword or perished in the Guadalquivir. Mohammed then liberated
Hischem, whose supposed corpse he had buried, resigned his
dignity, and proclaimed the son of Al-Hakem sovereign of Spain. But
the ruse had no effect. The Cordovans admitted the Berbers, and
Suleyman occupied the palace of the khalifs.
Henceforth the story of the Peninsula is one of anarchy and ruin.
Every province, every hamlet, was a prey to the hatred of contending
parties intensified by the daily infliction of mutual outrages. Christian

You might also like