1. Trang chủ
  2. » Công Nghệ Thông Tin

Transitioning to NET core on red hat enterprise linux

137 96 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 137
Dung lượng 3,03 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Starting with a basic “Hello World” console application, it moves along through ASP.NET, MVC, and Entity Framework applications,eventually arriving at a full-featured application running

Trang 2

Programming

Trang 4

Transitioning to NET Core on Red Hat Enterprise Linux

Don Schenck

Trang 5

Transitioning to NET Core on Red Hat Enterprise Linux

by Don Schenck

Copyright © 2017 O’Reilly Media All rights reserved

Printed in the United States of America

Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North,Sebastopol, CA 95472

O’Reilly books may be purchased for educational, business, or salespromotional use Online editions are also available for most titles(http://oreilly.com/safari) For more information, contact our

corporate/institutional sales department: 800-998-9938 or

corporate@oreilly.com.

Editors: Nan Barber and Susan Conant

Production Editor: Melanie Yarbrough

Copyeditor: Gillian McGarvey

Proofreader: Jasmine Kwityn

Interior Designer: David Futato

Cover Designer: Karen Montgomery

Illustrator: Rebecca Demarest

September 2016: First Edition

Trang 6

Revision History for the First Edition

2016-09-20: First Release

2016-10-21: Second Release

2016-12-06: Third Release

The O’Reilly logo is a registered trademark of O’Reilly Media, Inc

Transitioning to NET Core on Red Hat Enterprise Linux, the cover image,

and related trade dress are trademarks of O’Reilly Media, Inc

While the publisher and the author have used good faith efforts to ensure thatthe information and instructions contained in this work are accurate, the

publisher and the author disclaim all responsibility for errors or omissions,including without limitation responsibility for damages resulting from the use

of or reliance on this work Use of the information and instructions contained

in this work is at your own risk If any code samples or other technology thiswork contains or describes is subject to open source licenses or the

intellectual property rights of others, it is your responsibility to ensure thatyour use thereof complies with such licenses and/or rights

978-1-491-97055-3

[LSI]

Trang 7

What to Expect from This Book

This book is targeted at — but not limited to — NET developers with anylevel of experience Starting with a basic “Hello World” console application,

it moves along through ASP.NET, MVC, and Entity Framework applications,eventually arriving at a full-featured application running in a Linux container.Because the code in this book is limited to C#, your existing knowledge of.NET and C# will largely determine the speed at which you progress throughthis volume More experienced developers will be interested in the few keydifferences when developing for Linux (and there are quite a few), whereasbeginning developers can use this book to learn more advanced programmingtechniques — the fact that those techniques are related to NET Core is justicing on the cake

If you’ve spent most of your time writing code in a language other than C#,with Linux as your native operating system, don’t fret Though knowledge ofC# is highly recommended, even a novice developer with a desire to learncan use this volume, perhaps in concert with another manual that guides thereader in C# development

Trang 8

Some Assumptions

This book assumes some previous experience with the NET Framework.Again, while it’s technically not necessary to have prior knowledge when youbegin reading, you will need to be familiar with NET (either by experience

or education) to understand what’s happening Again, not to worry — theknowledge needed isn’t as deep as you might fear Grasp a few key conceptsand you’ll be good to go

For the purposes of simplicity, the Linux distribution used in the exampleswill be Red Hat Enterprise Linux (RHEL) Any adjustments necessary forother Linux distributions will be pointed out as we go

Trang 9

Your Environment

To follow along with the narrative and code, you need to install the Red HatContainer Development Kit (CDK) and clone or download a repository fromGitHub Step-by-step instructions are provided in Chapter 1

Trang 10

The following typographical conventions are used in this book:

Text will be in the typeface you are reading now

// Code is formatted like this:

Used for program listings, as well as within paragraphs to refer to

program elements such as variable or function names, databases, datatypes, environment variables, statements, and keywords

Constant width bold

Shows commands or other text that should be typed literally by the user

Constant width italic

Shows text that should be replaced with user-supplied values or by

values determined by context

Trang 12

.NET Core Is the Future

In November 2014, Microsoft announced that the NET Framework would betransitioned to an open source development model This announcement wasmet with surprise and open arms by the NET community Although

Microsoft had, up to that moment, done an admirable job of soliciting inputfrom developers about NET features and bugs, making the source availablemeant a much higher level of engagement The standard open source model

of using a GitHub repo — with issues, milestones, pull requests, and therelated discussions — meant that anyone, anywhere could have instant andtransparent access to the development team Developers could participate indiscussions and research defects and workarounds Schedules and roadmapswould now be available to everyone, leading to more realistic expectations.Surprise announcements would give way to planned milestones

Meanwhile, developers outside the NET world saw this as an opportunity tobring their open source experience and knowledge to one of the more

pervasive software development platforms The free exchange of ideas, codereviews, and sense of community found its place inside the Microsoft-centricdeveloper’s world The infusion of non-.NET developers meant that “dotnetters” could gain a broader view of development in general This is a verygood thing

This is the new model This is the future

.NET Core is not just another NET Framework Rather, it is the future of.NET Microsoft has stated that the previous framework, 4.6.1, will still besupported, and bug fixes will be applied, but any new NET features will bereserved for NET Core Using NET Core as your basis for future work is inline with Microsoft’s stated intentions While migrating existing code to.NET Core may or may not be a good idea, future development should bebased on NET Core if possible In short, this is the NET Framework Period.Full stop

Trang 13

What’s Missing

Because some parts of NET are either specific to Windows or outdated, noteverything made the journey from proprietary software to the open sourcemodel and NET Core 1.0

Here’s a list of some of the things that didn’t make the transition:

MWF (Windows Forms)

Web forms

WCF (SOAP)

In addition, some things haven’t been ported yet — perhaps the biggest being

SignalR Microsoft has publicly stated that SignalR will be ported to NET

Core

NOTE

From this point on, unless the difference is worth noting, references to NET CoreCLR,

CoreFX, and the like, will be simplified to “.NET”.

Trang 14

coding, but it also results in performance improvements The trade-off isworth the cost: writing code is easier than optimizing code.

Trang 15

Chapter 1 Setting Up Your

Trang 16

Your Red Hat Account

Before you can download the RHEL image and the CDK, you need to

register at the Red Hat Developer website This is free; all you need is anemail address and a password You can opt out of the Red Hat Developersnewsletter if you wish, but I suggest keeping it — at least initially

This gives you access to all the tools and help, including the CDK (withRHEL), forums, knowledge base, and more

Keep your username and password handy; you’ll need them every time youstart your VM in order to register with Red Hat and enable your subscription

Trang 17

Installing the CDK

The Red Hat CDK includes a copy of RHEL 7 that’s been preloaded with thedocker command and OpenShift It runs the RHEL VM using Vagrant andVirtual Box Fortunately, if you’re not familiar with these technologies, theCDK makes the process of installing them transparent Basically, you

download, install, and run

Once you’ve registered and logged in, select the TECHNOLOGIES menuand the Red Hat Container Development Kit option, as shown in Figure 1-1

Figure 1-1 Select Red Hat Container Development Kit

Trang 18

This takes you to the Container Development Kit page.

At the top, click the GET STARTED button to reveal your choice of

Windows or Mac/Linux assets From there, simply follow the screen prompts

to download the CDK, as shown in Figure 1-2

Figure 1-2 Container Development Kit download page

After the CDK installer is downloaded (the installer is

development-suite-1.0.0-GA-bundle-installer.exe, which is about 1.4 GB in size), open it and

follow the prompts to install the CDK on your Windows machine You’llneed your Red Hat username and password to get started, as you can see inFigure 1-3

Trang 19

Figure 1-3 Sign in to start the CDK installation

Trang 20

Disable Hyper-V

Before you can use Vagrant, you’ll need to disable Hyper-V on yourWindows machine Use the Windows Features Control Panel applet to dothis, as shown in Figure 1-4

Figure 1-4 Disable Hyper-V

If you need to switch between enabling and disabling Hyper-V, there’s ahelpful guide at Scott Hanselman’s blog

Trang 21

Start Your VM

Now that you’ve installed everything, you can start the VM Assuming thatyou used the default values during the installation, open a command prompt,navigate to the proper folder, and launch the VM using the vagrant upcommand:

PS C:\DevelopmentSuite\cdk\components\rhel\rhel-ose> vagrant up Bringing machine 'default' up with 'virtualbox' provider

==> default: Clearing any previously set forwarded ports

==> default: Clearing any previously set network interfaces

==> default: Preparing network interfaces based on configurat default: Adapter 1: nat

default: Adapter 2: hostonly

==> default: Forwarding ports

default: SSH username: vagrant

default: SSH auth method: password

default: Warning: Connection timeout Retrying

default: Warning: Remote connection disconnect Retrying

==> default: Machine booted and ready!

==> default: Registering box with vagrant-registration

default: Would you like to register the system now (defau default: username: **redacted**

default: password:

[default] GuestAdditions 5.0.26 running - OK.

==> default: Checking for guest additions in VM

==> default: Configuring and enabling network interfaces

==> default: Copying TLS certificates to C:/DevelopmentSuite/

==> default: Rsyncing folder: /cygdrive/c/DevelopmentSuite/cdk/

==> default: Mounting SMB shared folders

default: C:/shared => /shared

==> default: Machine already provisioned Run `vagrant provis

==> default: flag to force provisioning Provisioners marked

==> default: Running provisioner: shell

default: Running: inline script

==> default: Running provisioner: shell

default: Running: inline script

==> default:

==> default: Successfully started and provisioned VM with 2

==> default: To modify the number of cores and/or available

Trang 22

==> default: VM_CPU respectively VM_MEMORY.

==> default: You can now access the OpenShift console on: https

Trang 23

RUN AS ADMINISTRATOR

Get in the habit of opening the command prompt — I suggest using PowerShell — by

using the “Run as Administrator” option because you’ll need administrator privileges later when you are editing and debugging from Windows.

Now you can use ssh to get into the VM The easiest option is to use thevagrant ssh command, which will open an ssh session inside the VM, asshown in Figure 1-5

Figure 1-5 Using vagrant SSH to start a bash session on the VM

At this point, the VM is set up and running and you’re ready to begin yourtransition to NET on Linux

Trang 24

Getting the Source Code

Once you are inside the VM, you can go ahead and fetch the source codeassociated with this book You can do this by running the following

command:

git clone https://github.com/donschenck/NetOnLinuxBook

You’ll now have a directory, NetOnLinuxBook, that contains subdirectories

for this book

NOTE

When applicable, at the beginning of each chapter, you will see a note directing you to the source code from the repo that is associated with that chapter.

Trang 25

Chapter 2 Getting Started: From Zero to “Hello World” in One

Chapter

Trang 26

From Zero to “Hello World” in One Chapter

One of the benefits of NET Core is the ability to get a simple consoleapplication up and running in a matter of seconds While more complexapplications require a deeper understanding of the framework and the

language (C#, in our case), the building and execution of a simple “HelloWorld” application can be done with very little effort This chapter will getyou up and running in one quick session

Trang 27

ASSOCIATED SOURCE CODE

The source code can be found in the /NetOnLinuxBook/HelloWorld/ directory.

Trang 28

Overview of NET

When Microsoft introduced the NET Framework in 2002, it marked a newera in software development for Microsoft-centric developers The movemarked a shift in thinking, allowing Windows Forms developers to createwebsites in a way that was somewhat familiar Dragging text areas and

buttons onto a form and adding code-behind code made the transition almostseamless, if somewhat unconventional In fact, it was sometimes referred to

as “Windows for the Web.”

Fast-forward 12 years, and Microsoft announces that NET will be open

source It now supports MVC, ORM, CSS, and every other TLA (three-letteracronym) one can imagine

What happened?

In short, as has been said, “Open source won.”

With the fight over, Microsoft has pivoted quickly and is now releasing

pieces of the NET framework at a much faster pace, with thousands of

developers from all over the world contributing

In November 2015, when Microsoft and Red Hat announced a partnership (toreplace an adversarial relationship), it became clear that NET was not onlymoving into the world of open source but that being able to run NET

programs on Linux — with the full blessings and support of Microsoft and

Red Hat — was actually going to happen.

And that’s where we find ourselves today, with both Microsoft and Red Hatembracing Linux and NET As a developer, you have the opportunity towiden your skillset and marketplace There’s no reason to wait, as both NETand Red Hat Enterprise Linux (RHEL) can be obtained at no cost It’s time toget started

Trang 29

Installing NET

Installing the framework is easier and quicker than ever; that’s because it’sbeen separated into small layers It’s helpful to understand these layers of.NET Each layer exists separately from the other and evolves at a differentpace Each has a separate code base and GitHub repo, as shown in Figure 2-1

Figure 2-1 The layers of the new world of NET

Trang 30

.NET CLR

This is where the Common Language Runtime (CoreCLR) lives It includesthe garbage collector, the Just-In-Time (JIT) compiler, base data types, andsome low-level classes

Trang 31

.NET CoreFX

The System.* and Microsoft.* libraries that run on NET Core and enable you

to run your applications When you type using System.<foo> in your

program, you are accessing the libraries at this level CoreFX includes classesfor collections (System.Collections), filesystems (System.IO), XML

(System.Xml), asynchronous processing (System.Threading), and more Youcan see the entire list of libraries at the GitHub repo At this level, basic

console applications (such as the ubiquitous “Hello World” app) can run

Trang 32

.NET CLI

The command-line interface, which allows you to build and launch yourapplications Compiling programs, pulling NuGet packages, running tests,running your applications — all these tasks use the dotnet CLI As a

developer, you’ll likely spend a great deal of time here or use an IDE thatleverages the CLI

Trang 33

ASP.NET Core

These are the libraries that allow you to write web services and websites.Because it is totally modular, ASP.NET Core allows you to include only thepieces you need — for example, running a static website — while excludingthe bits you don’t need This reduces size, increases performance, and makesdeployment faster

Trang 34

Any tools that make your life easier as a developer — whether they are a part

of Visual Studio or Visual Studio Code, or other tools (such as yeoman) —reside at this level This level is not only optional, but tools may or may not

be available depending on your operating system and toolset Whereas in thebeginning, NET development tools from Microsoft were tightly coupled withthe framework and Visual Studio, now they are totally separate (this has

actually been the case since 2008)

Trang 35

HELP, I DON’T REALLY KNOW LINUX THAT WELL!

New to Linux? That’s OK; we all were at one point in our lives Don’t fret — you can download a free Linux Cheat Sheet at the Red Hat Developer’s website.

Trang 36

Installation Instructions

Assuming you have a Red Hat Enterprise Linux 7 subscription, follow theseinstructions to install NET Core Note that you will need administrator

privileges to perform the installation:

sudo subscription-manager list available

This displays a list of all available subscriptions Near the end of the listing, aPool ID is revealed, as in this example output shown in Figure 2-2

Figure 2-2 subscription-manager list available output showing Pool ID

Using the Pool ID, run the following command:

sudo subscription-manager attach pool=<Pool ID>

Now you can enable the package and perform the installation:

sudo subscription-manager repos

enable=rhel-7-server-dotnet-rpms

sudo yum install -y scl-utils

sudo yum install -y rh-dotnetcore10

Finally, to make the framework available to your command line, use thefollowing command, which will enable the framework in a new bash session:sudo scl enable rh-dotnetcore10 bash

Trang 37

Every time you open a bash session in the VM, you’ll need to run the thiscommand Not only is this a nuisance, but it won’t work if you wish to debugyour code from within Visual Studio To avoid this issue, add the following

line to the file ~/.bashrc in your VM:

source scl_source enable rh-dotnetcore10

This will download and install the latest RHEL-approved NET Core

distribution and make it available You can verify your installation (and seewhat version you are using) by using the version command:

dotnet version

Trang 38

Other Linux Distros

The easiest way to install on other distros is to visit the NET website andfollow the screen prompts

WHAT IF I DON’T HAVE RHEL?

If you don’t have a machine running RHEL, or if you’d like to create a Virtual Machine on your Windows machine and use it to run RHEL (I strongly recommend this route), visit the Red Hat NET website and follow the prompts to download and install RHEL While you’re at it, I recommend grabbing and installing the Container Development Kit (CDK) You can use it later when working with Linux containers.

Trang 39

Keeping Current

To keep up to date with the progress of NET, visit the project current releasepage on GitHub

Trang 40

Your First NET Application on Linux

Be prepared to be underwhelmed Creating your first NET application, thestandard “Hello World” application, on Linux involves only three steps (five

if you include creating a directory and moving into it)

Actually, the creation of the source code is only one command:

Ngày đăng: 04/03/2019, 16:03

TỪ KHÓA LIÊN QUAN