Tải bản đầy đủ (.pdf) (485 trang)

NET core 2 0 by example

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (23.16 MB, 485 trang )


.NETCore2.0ByExample






LearntoprograminC#and.NETCorebybuildingaseriesofpractical,crossplatformprojects











RishabhVerma
NehaShrivastava

















BIRMINGHAM-MUMBAI



.NETCore2.0ByExample
Copyright©2018PacktPublishing
Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,ortransmittedinanyformorbyanymeans,
withoutthepriorwrittenpermissionofthepublisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.
Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyoftheinformationpresented.However,the
informationcontainedinthisbookissoldwithoutwarranty,eitherexpressorimplied.Neithertheauthors,norPacktPublishingorits
dealersanddistributors,willbeheldliableforanydamagescausedorallegedtohavebeencauseddirectlyorindirectlybythisbook.
PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthecompaniesandproductsmentionedinthisbookby
theappropriateuseofcapitals.However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.
CommissioningEditor:AaronLazar
AcquisitionEditor:ChaitanyaNair
ContentDevelopmentEditor:RohitKumarSingh
TechnicalEditor:RomyDias
CopyEditor:SafisEditing
ProjectCoordinator:VaidehiSawant
Proofreader:SafisEditing
Indexer:PratikShirodkar
Graphics:JasonMonteiro,TomScaria
ProductionCoordinator:DeepikaNaik

Firstpublished:March2018
Productionreference:1160318
PublishedbyPacktPublishingLtd.
LiveryPlace
35LiveryStreet
Birmingham
B32PB,UK.
ISBN978-1-78839-509-0
www.packtpub.com


mapt.io

Maptisanonlinedigitallibrarythatgivesyoufullaccesstoover5,000booksandvideos,aswell
asindustryleadingtoolstohelpyouplanyourpersonaldevelopmentandadvanceyourcareer.For
moreinformation,pleasevisitourwebsite.


Whysubscribe?
SpendlesstimelearningandmoretimecodingwithpracticaleBooksandVideosfrom
over4,000industryprofessionals
ImproveyourlearningwithSkillPlansbuiltespeciallyforyou
GetafreeeBookorvideoeverymonth
Maptisfullysearchable
Copyandpaste,print,andbookmarkcontent


PacktPub.com
DidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFandePubfiles
available?YoucanupgradetotheeBookversionatwww.PacktPub.comandasaprintbookcustomer,

youareentitledtoadiscountontheeBookcopy.Getintouchwithusatformore
details.
Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signupforarangeof
freenewsletters,andreceiveexclusivediscountsandoffersonPacktbooksandeBooks.


Contributors


Abouttheauthors
RishabhVermaisaMicrosoftcertifiedprofessionalandworksatMicrosoftasadevelopment
consultant,helpingtodesign,develop,anddeployenterprise-levelapplications.Hehas10years'
hardcoredevelopmentexperienceonthe.NETtechnologystack.Heispassionateaboutcreating
tools,VisualStudioextensions,andutilitiestoincreasedeveloperproductivity.Hisinterestsare
.NETCompilerPlatform(Roslyn),VisualStudioExtensibility,andcodegeneration.
Nowordscandescribemygratitudetomyparents,ShriRakeshChandraVermaandSmt.
PratibhaVerma,whosupportedmeduringthewritingofthisbook.Theirhardworkoverthe
yearshasbeentheinspirationbehindmetakingupthischallengingwork.Iwouldalsoliketo
offerspecialthankstomybrother,ShriRishiVerma,whokeptmotivatingmedayinanddayout.
Ialsowanttothankmycolleagues,managers,andteamatMicrosoftfortheirsupport.

NehaShrivastavaisaMicrosoftcertifiedprofessionalandworksasasoftwareengineerforthe
WindowsDevicesGroupatMicrosoftIndiaDevelopmentCenter.Shehas7years'development
experienceandhasexpertiseinthefinancial,healthcare,ande-commercedomains.NehadidaBE
inelectronicsengineering.HerinterestsaretheASP.NETstack,Azure,andcross-platform
development.Sheispassionateaboutlearningnewtechnologiesandkeepsherselfuptodatewith
thelatestadvancements.
Iwouldliketothankmyparents,ShriO.P.ShrivastavaandSmt.ArchanaShrivastava,fortheir
continuoussupportandmotivation.Their"NeverSayDie"mantrakeepsmeupandrunning.
Heartfeltthankstomybrother,Dr.UtkarshShrivastava,mysister-in-law,Dr.Samvartika

Shrivastava,andmylittleangelSarvagya,fortheircontinuoussupportandwordsof
encouragement.Thisbookwouldn'thavebeenpossiblewithouttheblessingsofmybeloved
Dadi!


Aboutthereviewer
PavolRovenskyisasoftwaredeveloperlivingintheUK.OriginallyfromSlovakia,heearneda
degreeinradioelectronicsfromCzechTechnicalUniversityandstudiedmedicinefromthe
CharlesUniversityinPrague.
HehasworkedintheCzechRepublic,Iceland,Switzerland,andtheUK,mostlydeveloping
softwareforthebiotech/pharmasectorandcontractinginvarioussoftwarecompanies,hehas
professionalexperiencespanning25years.
Hehasworkedwithvarioustechnologies,includingC++,Java,PowerBuilder,C#,WiXToolset,
.NETFramework,ORMs.
HisinterestinaccountingandbusinessmanagementledhimtodevelopProudNumbers,whichisa
reportingtoolformanagementaccountants.
Iwouldliketothankmywife,Jana,anddaughter,Emma,fortheirpatienceandencouragement.







Packtissearchingforauthorslikeyou
Ifyou'reinterestedinbecominganauthorforPackt,pleasevisitauthors.packtpub.comandapplytoday.
Wehaveworkedwiththousandsofdevelopersandtechprofessionals,justlikeyou,tohelpthem
sharetheirinsightwiththeglobaltechcommunity.Youcanmakeageneralapplication,applyfora
specifichottopicthatwearerecruitinganauthorfor,orsubmityourownidea.



Preface
InthisevergrowingworldofIT,wehavenumerousdifferentplatforms,frameworks,and
languagesonwhichapplicationsarebuiltbasedonthebusinessneeds,requirements,andthe
developer'sinterest.Toremovethisbarrierofdifferentplatforms,Microsoftcameupwiththe
fastest,latest,andgreatestversionof.NET,the.NETCorecross-platformopensourceframework.
Usingthisframework,beginner-leveldeveloperscanworkondifferentplatforms,andexperienced
developersandarchitectscanconsumetheirAPIsandlibrariesacrossdifferentplatforms.This
bookcoverssimpleexamplesofusing.NETCoretobuildmodern,internet-connected,andcloudbasedapplications.Thebookwillhelpusdevelopsimpleyetinterestingapplicationstoprovide
thereaderswithworkingcodeexamples.WewilldevelopaTic-Tac-Toegametobeginwith,then
buildareal-timechatapplication,LetsChat(forchattingwithouronlineFacebookbuddies),a
samplechatbot,andadummymoviebookingapplication.


Whothisbookisfor
Thisbookisfordevelopersandarchitectswhowanttolearnhowtobuildcross-platformsolutions
usingMicrosoft.NETCore.Itisassumedthatyouhavesomeknowledgeofthe.NETFramework,
OOP,andC#(orasimilarprogramminglanguage).Thisbookisalsousefulfordeveloperswho
wanttodevelopacross-platformapplicationthatsupportsalreadyexistinglibrariesorlibraries
thattheyhavecreatedondifferentplatforms.Thebookcoversawidebreadthoftopicsand
attemptstoexplainallthefundamentalsneededtobuilda.NETCoreapp.Thebookalso
introducesyoutoSignalRCore,EntityFrameworkCore,containers,F#functionalprogramming,
andtipsandtricksfordevelopingon.NETCore.


Whatthisbookcovers
,GettingStarted,discussesalltheprerequisitesrequiredforalltheexamplesinthisbook,
forexample,settingupanUbuntuVMusingVirtualBoxandthroughHyper-VonWindows,and
installing.NETCore2.0andtools.WewillalsobeintroducedtoF#anditsfeaturesinbrief,see
howF#isdifferentfromotherobject-orientedprogramminglanguages,andlookatthedifferences

betweenC#andF#.WewillalsocreateasimplesampleapplicationusingF#,inordertoget
familiarwiththeF#syntax.
Chapter1

,NativeLibrariesin.NETCore,demonstrateswhatthencurseslibraryisandhowto
extendtheconsolecapabilitiesof.NETCorebyimplementingthencursesnativelibraryonLinux,
andalsohowtointeroperatewithexistingnativeandMonolibraries.Wewillbuildasample
nativelibraryandapplicationthatimplementsthisnewsamplelibrary.
Chapter2

,BuildingOurFirst.NETCoreGame–Tic-Tac-Toe,illustrates.NETCoreusingan
examplegameapp,Tic-Tac-Toe.WewillbeintroducedtoSignalRCoreandlearnhowitcanbe
usedtodevelopareal-timewebapplication.InsteadofusingamonochromaticXandO,players
canusetheirimagestoplaythegame.Withthisexamplegameapp,wewillgetanoverviewofthe
code(classes,interfaces,models,andsoon)andwilllearnaboutcompiling,building,andtesting
theapplication,whichappliesto.NETCoreingeneral.
Chapter3

,Let'sChatWebApplication,introduceswebdevelopmentwithASP.NETCore.Thisis
donethroughasimplechatapplication,Let'sChat,onWindows.Wealsocoverprojectsetup,
applicationarchitectureanditsdescription,SignalRCore,DependencyInjection,configuration,
logging,andmore.WewillalsogetfamiliarwiththefundamentalsofthefeaturesofASP.NET
Core,whichareintroducedwhiledevelopingthecomponentsoftheapplication.
Chapter4

,DevelopingtheLet'sChatWebApplication,demonstratesnumerousexamplesandcode
snippetsinordertofundamentalsandfeaturesofASP.NETCore.Bytheendofthischapter,the
Let'sChatapplicationwillbereadyforuse.Wewillalsogetacquaintedwithtesting,hosting,
security,andtheperformanceaspectsofwebdevelopment.
Chapter5


,TestingandDeploying–TheLet'sChatWebApplication,explainsthe.NETCore
deploymentmodel.WewilldeploytheLet'sChatapplication.WewillbeintroducedtoDocker
containers.WewillalsodevelopanddeployaASP.NETCore-basedchatbotandintegrateitwith
theLet'sChatapplication.
Chapter6

,TotheCloud,teachesyouwhatthecloudisandwhythemodern-daydevelopershouldbe
conversantwithcloudtechnologies.WewillgetstartedwithAzure,andmakeourselvesawareof
theAzuremanagementportal.WewilllearntocreateaVMfromtheportalandseethatitis
automatedusingPowerShellorotherlanguagesusingtheAzureSDK.WewillthenmanagetheVM
Chapter7


usingPowerShellandseehowtostartandstopit.Wewillalsolearnhowtocreateawebappin
AzurefromVisualStudio2017itselfandlearnhowtopublishprofiles.Finally,wewillhavean
overviewofAppServices,andtakeaquicklookatAzurestorage.
,MovieBookingWebApp,discussesEntityFramework(EF)andEntityFramework
Core.Wewilllearnaboutthefeaturesofanddifferencesbetweenthetwo.Wewillalsolearnthat
weshoulduseEFCoreonlyifEFcannotbeusedorthereisapressingcross-platformrequirement
touseEFCore.WewilllearnhowtoperformCRUDoperationsusingEFCorebycreatinga
simpleapp.Wewillthendevelopasimplemoviebookingappandlearnhowtodeployitusing
VisualStudio.WewillalsoseehowwecanmonitorourwebappbyenablingApplication
Insights.
Chapter8

,Microserviceswith.NETCore,givesanoverviewofthemicroservicearchitectureand
howitisanextensionofSOAandovercomesthelimitationsoftraditionalmonolithicapps.We
willlearnabouttheimportantarchitecturaldifferencesbetweenASP.NETandASP.NETCore.We
willlookattipstokeepinmindwhiledevelopingASP.NETCore2.0applications,duetothe

architecturaldifferences.Wewillthendiscusshandyinformation,steps,andtipstoimprovethe
performanceofASP.NETCoreapps,afewtipsonAzureaswell,andthenanewexperimental
projectoftheASP.NETCoreteam,whichiscalledBlazor.We'llwrapupthechapterwitha
discussiononthe.NETCore2.1roadmapandthefeaturesexpectedinthisnewversion.
Chapter9

,FunctionalProgrammingwithF#,discussesfunctionalprogramminganditsfeatures,
suchashigher-orderfunctions,purity,lazyevaluation,andcurrying.WewilllearnaboutF#basics,
suchasclasses,letanddobindings,generictypeparameters,propertiesinF#,howtowrite
functionsandlambdaexpressionsinF#,andexceptionhandling.Also,we'lllookatdifferenttypes
ofdataprovidersinF#andhowdifferenttypesofdataparserwork.Wewillalsolearnabout
queryingSQLServervNextwithF#.
Chapter10


Togetthemostoutofthisbook
Thisbookisaimedatexperienceddeveloperswhousedifferentplatforms—Windows,Linux,
Ubuntu,macOS—andwanttotryMicrosoft.NETCore2.0crossplatform.DevelopersusingC#,
C,orC++fordevelopmentwhoareinterestedinextendingtheirknowledgeoffunctional
programming,beginnerswhowanttounderstandF#andfunctionalprogramming,weassumethat
youhaveabasicunderstandingofC#andareawareofthe.NETframeworkandWindows.


Downloadtheexamplecodefiles
Youcandownloadtheexamplecodefilesforthisbookfromyouraccountatwww.packtpub.com.Ifyou
purchasedthisbookelsewhere,youcanvisitwww.packtpub.com/supportandregistertohavethefiles
emaileddirectlytoyou.
Youcandownloadthecodefilesbyfollowingthesesteps:
1.
2.

3.
4.

Loginorregisteratwww.packtpub.com.
SelecttheSUPPORTtab.
ClickonCodeDownloads&Errata.
EnterthenameofthebookintheSearchboxandfollowtheonscreeninstructions.

Oncethefileisdownloaded,pleasemakesurethatyouunziporextractthefolderusingthelatest
versionof:
WinRAR/7-ZipforWindows
Zipeg/iZip/UnRarXforMac
7-Zip/PeaZipforLinux
ThecodebundleforthebookisalsohostedonGitHubat />.0-By-Example.Wealsohaveothercodebundlesfromourrichcatalogofbooksandvideosavailable
atCheckthemout!


Downloadthecolorimages
WealsoprovideaPDFfilethathascolorimagesofthescreenshots/diagramsusedinthisbook.
Youcandownloadithere: />Images.pdf.


Conventionsused
Thereareanumberoftextconventionsusedthroughoutthisbook.
:Indicatescodewordsintext,databasetablenames,foldernames,filenames,file
extensions,pathnames,dummyURLs,userinput,andTwitterhandles.Hereisanexample:"By
doingthisin_Layout.cshtml,weensurethatthisfunctionalityiscommonacrossallthepages."
CodeInText

Ablockofcodeissetasfollows:

#include<stdio.h>
inthello()
{
return15;
}

Whenwewishtodrawyourattentiontoaparticularpartofacodeblock,therelevantlinesor
itemsaresetinbold:
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes=>
{

Anycommand-lineinputoroutputiswrittenasfollows:
mcs-out:helloNative.exeInteropWithNativeSO.cs

Bold:Indicatesanewterm,animportantword,orwordsthatyouseeonscreen.Forexample,
wordsinmenusordialogboxesappearinthetextlikethis.Hereisanexample:"EnterDisplay
NameandContactEmail,andclickontheCreateAppIDbutton."
Warningsorimportantnotesappearlikethis.

Tipsandtricksappearlikethis.



Getintouch
Feedbackfromourreadersisalwayswelcome.

Generalfeedback:Emailandmentionthebooktitleinthesubjectofyour
message.Ifyouhavequestionsaboutanyaspectofthisbook,pleaseemailusat

Errata:Althoughwehavetakeneverycaretoensuretheaccuracyofourcontent,mistakesdo
happen.Ifyouhavefoundamistakeinthisbook,wewouldbegratefulifyouwouldreportthisto
us.Pleasevisitwww.packtpub.com/submit-errata,selectingyourbook,clickingontheErrataSubmission
Formlink,andenteringthedetails.
Piracy:IfyoucomeacrossanyillegalcopiesofourworksinanyformontheInternet,wewould
begratefulifyouwouldprovideuswiththelocationaddressorwebsitename.Pleasecontactusat
withalinktothematerial.
Ifyouareinterestedinbecominganauthor:Ifthereisatopicthatyouhaveexpertiseinandyou
areinterestedineitherwritingorcontributingtoabook,pleasevisitauthors.packtpub.com.


Reviews
Pleaseleaveareview.Onceyouhavereadandusedthisbook,whynotleaveareviewonthesite
thatyoupurchaseditfrom?Potentialreaderscanthenseeanduseyourunbiasedopiniontomake
purchasedecisions,weatPacktcanunderstandwhatyouthinkaboutourproducts,andourauthors
canseeyourfeedbackontheirbook.Thankyou!
FormoreinformationaboutPackt,pleasevisitpacktpub.com.


GettingStarted
Inthischapter,wearegoingtolearnabouttoolsusedtoperformdevelopmenttasksfor.NETCore
2.0onWindowsandLinuxoperatingsystems.Also,wewilllearnhowtosetupLinuxand
virtualizationusingVirtualBoxandHyper-V.Thischapterwillcoverhowtoinstall.NETCore2.0
andtoolsforWindowsandLinux(Ubuntu).Wewilllearnaboutthevirtualmachine(VM)setup
forUbuntuandcreateyourfirstsimple.NETCore2.0runningapplicationcode.Wewillconfigure
theVMtomanageyourfirstapplication.Thepurposeofthischapteristogetageneralideaofthe
requiredtoolsandhowtoinstall.NETcore2.0SDKforWindowsandLinux,andgiveyoubasic

F#understanding.
Thischapterwillcoverthefollowing:
DownloadingtherequiredtoolsforWindowsandLinux
Installing.NETCore2.0andtools(Windows)
SettingupanUbuntuLinuxVM
Installing.NETCore2.0andtools(Linux)
Creatingsimplerunningcode
F#primer


DownloadingrequiredtoolsforWindows
andLinux
Inthissection,wewilldiscusstheprerequisitestobedownloadedforbothWindowsandLinux
operatingsystemstostartdevelopmentwith.NETCore2.0.WewillstartwithWindowsandthen
movetoLinux.


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×