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

Building single page app with ASP NET MVC 5 and angular

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 (6.74 MB, 196 trang )




Contents

Chapter1:GettingStarted
WHATDOyoufindinthisCHAPTER?
Introduction


WhatisSPA
TechnologiesusedtobuildSPA
GlimpseofMovieReviewApp
Summary

Chapter2:CreatingSolutionfromblankslate
WHATDOyoufindinthisCHAPTER?
Introduction
SolutionCreation
AddingProjectReferences
AddingPackages
ImportantTools
DataTechnologies
CreatingModels
CreatingEntityFramework
DatabaseInitializer
ImplementingRepositoryPattern
CreatingUnitofWorkPattern(UOW)
Summary

Chapter3:ImplementingWebAPI


WHATDOyoufindinthisCHAPTER?
Introduction
Creating1stWebAPIController
ImplementingHTTPPutRequest
ImplementingHTTPPostRequest
ImplementingHTTPDeleteRequest
ImprovisingWebAPIs
AddingMoreControllers
TestingWebAPIswithQUnit
Summary

Chapter4:GettingStartedwithAngularJS
WHATDOyoufindinthisCHAPTER?


Introduction
GettingstartedwithPLNKR
GettingstartedwithUIDesign
Creating1stAngularController
Data-BindingusingAngular
RetrievingDatafromAPI
Summary

Chapter5:DeeperintoAngularJS
WHATDOyoufindinthisCHAPTER?
AngularJSRouting
AddingMoreRoutes
Clientsidevalidation
SavingDatausingAngular
CreatingAngularJSService

CreatingMovieEditFeature
CreatingReviewsWorkflow
Summary

Chapter6:UnitTesting
WHATDOyoufindinthisCHAPTER?
Introduction
CreatingTestProject
InstallingChutzpahTestAdapter
Writing1stJavaScriptTest
WritingAngularTest
Using$httpBackendService
WritingControllerTests
CodeCoverage
Summary

NoofPages:-200




WHOSHOULDTAKETHISBOOK

BuildingSPAusingMVC5andAngularisdesignedtobuildtheapplicationrightfrom
the grass root level. This Book is actually targeted to those people who are comfortable
withASP.NETMVCandAngularasthisneedsbasicknowledgeofboththetechnology.
Throughoutthisbookmyfocuswillbeonteachingyoumakingafullblownapplication
rather than explaining basics. For basics you can check my other book HandsonWith
ASP.NETMVC.ThisbooktalksbasicsingreatdetailswithlivedemoinAzure.Youcan
refer this book at this URL I would recommend you to download the

app from github URL shown below to help you while building
/>











Chapter1:GettingStarted

WHATDOyoufindinthisCHAPTER?

Introduction
WhatisSPA
TechnologiesusedtobuildSPA
GlimpseofMovieReviewApp
Summary



Introduction:HimynameisRahulSahayandIamgoingtointroducethiswholenewstoryofbuilding
Single Page Application right from the scratch. Here, in this context I am going to talk
aboutbunchofdifferentclient/serversidetechnologiesanddemonstratehowthesesmall
pieces marry together and creates a robust End to End application. So, without wasting
timelet’sgetstarted.


WhatisSPA:SinglePageAppisallaboutuserexperience.Peoplewillloveyourappifyougivethem
nice user experience which not only fits nicely in your laptop or desktop rather it goes
nicely with multitude of devices like tabs, phones etc without breaking any single
functionality. As shown in the below diagram, these are basic requirements for building
anySPA.





Reliability:-Peopleknowthatit’sreliableandit’sgoingtowork.Thiskindof
reliabilityonlycomeswithpositiveexperience.
Responsiveness:-Responsivenessmeansit’sgoingtoworkquicklyforthem.
Quickisthekeythingwhichanyuserexpecttohaveintheappwhichheis


using.
Reach:-Reachisoftensubstitutedwithmobility.Mobilityisagainoneofthe
keyingredientwhicheveryuserislookingfor.Theyalwayswanttohavethe
datahandywithirrespectiveofwhatdevicetheyareon.
Available:-Thisthingisreallyimportantwhenitcomestothepointat
workingoffline.So,deliveringagooduserexperienceismustwhilebuilding
SPA.
“So, in a nutshell a Single Page App is web application which fits in a single page
providingafluidUXbyloadingallthenecessarydatainasingleload.”

Now,apartfromthistherearemanyotherattributeslinkedtoSPA.Theyare:MaintainHistory:-Whenyouflipbetweenpages,itmaintainsyourhistoryin
thesameorderhowyouvisitedthem.Actually,it’snotgoingondifferent
pagesratheritsloadingdifferentinformation’sonthesamepage.But,itlooks

touserthatit’spresentingdifferentpagestothem.

PersistingInformation:-Persistinginformationisalsoveryimportantaspectof
theSPA.Itdoesn’tmeanthatyouneedtosaveeachandeverythingatcache
butyoucanstoreimportantthingsinthecachetoimprovetheperformance.

MostlyloadedonPageLoad:-Mostlyloadedonthepageloadmeansmajority
ofinformationuserrequiredtousegetsloadedinitiallyitselftoavoidroundtrip
backtotheserver.

DependentElements:-Asandwhenuserrequirestoaccessdifferentfeatures
oftheapplication,appwillgoanddownloadfortheuser.

TechnologiesusedtobuildSPA:MovieReviewappisbuiltusingtonsofdifferentclientsideandserversidetechnologies.
SomeoftheseIhavelistedbelow:
ClientSideTechnologies:HTML5&CSS
Modernizer&LESS
MediaQueries
ResponsiveDesign
AngularJS
ToastrJS
JQuery


QUnitJS
JQuery.MockJSON
ChangeTracking
Andmanyoutoftheboxthings



ServerSideTechnologies:SQLServer
EntityFramework–CodeFirstApproach
RepositoryPattern
UnitofWorkPattern
WebAPI
JSON&AJAX
NuGet
NinjectIOC
POCOModels
GlimpseofMovieReviewApp:I think it would be good idea you to show you finished app before directly jump in
creating the same. Here is the URL />where I have hosted my app. Now, when you click on this, you will land on the below
shownpage.






Above shown screen shot is the home page of the app. Now, when you click on the
Movieslink,itwilltakeyoutothebelowshownpage.



Once, page gets loaded, little toast message at the bottom right of the screen pops up
sayingMovies Fetched Successfully. Now, from this screen you can do all the CRUD
Operation. Here the very 1st link is Add Movie, which will give user flexibility to go
aheadandaddanynewmovieasshownbelow.


Now,let’ssupposeifwetrytoposttheFormasitisblank,thenitwon’tallow,because

abovefieldsarerequiredasmarkedbyitsCSScolorandstarmarkaswell.Now,onceI
enteranyinformation,differentvalidationwillgettriggered




EvenatthismomentIcannotsubmittheformastheformisinvalid.Once,Imodifyand
entervaliddetails,thenformerrormessagesanditserrorcolor(Red)willdisappear.



Now,atthisinstantIcangoaheadandsubmitthemovie.OnceIclicksubmitbutton;one
toastmessagewillappearsayingDataSavedSuccessfullyandwillgetredirectedbackto
movieslink.






NextistheEditlinkcorrespondingtothemovie.Whenyouclickonthis,itwillpresent
thebelowscreenforeditingthesame.


Here, also each and every validation will be there, what we have seen during creation.
However, you can go ahead and edit anything over here, let’s say I change the year to
2002andupdate.


Once I update the movie it will save the same in database and then get redirected to

Movieslinkasshownbelow.




However, let me change the same back to the original one as it’s not correct. Similarly,
youcangoaheadanddeletethemoviefromtheEditlinkaswell.NexttoEditlink,there
islinkforReviewsaswell.Fromthislinkyoucangoaheadandaddnewreviewasshown
below.


Here,whenIclickonAddNewReview,itwilltakemetothebelowform.



Aboveformhasalsogotdifferentsetofvalidationsasshownbelow.



Oncedoneallthecorrections,itwillbelikethis



Aftersuccessful,submission,itwillredirectbacktothemovieslink.



AfteraddingReview,positionofnewlyaddedmoviemovesupinthelistasbehindthe
sceneorderbyclauseisworkingontotalnoofreviews.Now,whenIclickontheReviews
linkagain,itwillshowmethereviewwhichIhaveadded.





Here,correspondingtotheReview,newEditlinkalsogotenabledforeditingordeleting
theReview.ThisalsoworkssamewhatIexplainedaboveforMovie.AboutApplinklists
allthedetailsoftheapplicationlikewhattechnologiesusedwhattoolsyouneed,whereto
downloadthecodeetc….







IhavealsousedQUnitLibrarytotestmyWebAPIs.Belowistheglimpseforthesame.



When you click on any individual test, it will present you the detailed results as shown
belowinthescreenshot.




Andifthereisanythingwrongwithanyendpoints,let’ssupposethatdoesn’texist;easiest
waytobreakthetest,thenitwillbelike





YoucanalsoverifytheseAPIslikeshownbelow
/>



Similarly different endpoints can be tested. Apart from Web API tests. I have also used
Jasmine to test my Angular code. You will also learn how to test client side JavaScript
codewithVisualStudio.Here,IhaveusedChutzpahtointegrateJavaScriptTestswith
VisualStudio.Belowistheglimpseforthesame.




Now,whenIcheckcodecoverageresultsformytests,Chutzpahwillopenanewwindow
inbrowserwiththecodecoverageresultsfortheclientsideasshownbelowinthescreen
shot.



Theoneswhicharehighlightedinredaretheoneswhicharenotcovered100%,sowhenI
clickonanyofthislink,itwillopenthecodeinbrowserandshowwhatiscoveredand
whatisnot




GlimpseofMovieReviewSolution:-



Letmegoaheadandshowyouthesolutionstructureoffinishedapp.Belowinthescreen
shot,Ihave5differentprojects.Eachishavingitsondependencyandresponsibility.


Here, the highlighted one is the web project which is dependent on other infrastructure
projects Data, Contracts and Model. Data project is the place where in you maintain
initial seed data, Entity Framework DBContext and many more things involve direct
interfacing down the layer with database. Data Contract is the place where in you
manage your repositories and apply Unit of Work Pattern on repositories like movies
andmoviereviews.ModelistheplacewhereyouwillbehavingyourPOCOs(PlainOld
CLRObjects).Thisistheplacewhereinyouaremaintainingallpropertiesattributedto
thetables.Belowistheglimpseofallprojectsinitsexpandedform.



Summary:Inthissection,wehaveseenthebitsandbytesoftheSinglePageApplicationwhichwe
are going to make using tons of client/server side framework. We have also seen the
glimpseofappandsolution.Inthenextsection,we’llbeginthelearningbycreatingthe
application right from the scratch. I would recommend you to download the app from
github
URL
shown
below
to
help
you
while
building
.









Chapter2:CreatingSolutionfromtheblankslate



WHATDOyoufindinthisCHAPTER?

Introduction
SolutionCreation
AddingProjectReferences
AddingPackages
ImportantTools
DataTechnologies
CreatingModels
CreatingEntityFramework
DatabaseInitializer
ImplementingRepositoryPattern
CreatingUnitOfWorkPattern(UOW)
Summary

Introduction:Inthismodule,we’llbeginwithblanksolutionasshownbelowinthescreenshot.Now,in
thisblanksolutionwe’lladdcoupleofdifferentprojectstocompletethesolutionstructure
ofourmovieapp.Then,we’llcompletethenecessaryreferencesofprojectstoeachother.
After,resolvingallprojectdependencieswe’llbeginbyinstallingnecessaryclient/server

sidecomponentsusingNuget.

SolutionCreation:Inthissection,we’llstartcreatingthecompletearchitecturerightfromtheblankslate.So,
withoutwastingtimelet’sgetstarted.BelowinthescreenshotIhavestartedcreatingthe
applicationwithwebproject.




Here, I’ll be selecting Web API template just to make sure that I have necessary
configurations in place for building my APIs which will talk back and forth with User
Interface.I’llpickdefaultimplementationasshownbelowinthescreenshot.However,if
younoticethatIhavealsoleftUnitTestprojectuncheckedasI’llintroducenewtechnique
totestmyAPIs.LaterI’lladdTestProjectseparately.



Once,theprojectgetscreatedsuccessfully,itwillpresentonedefaultreadmeHTMLpage
as shown below in the screen shot with default files and configurations as shown in
solutionexplorertab.


Let’sexaminefewkeypiecesoftheproject.BydefaultitgavemetwocontrollersValues
ControllerandHomeControllerasshownbelowbutwe’llbedeletingtheseandwriting
oursrightfromthescratch.










Also, there is one more important piece which I want you to focus is the App_Start
folder.ThiscontainsalltheconfigsrelatedfilesorbasicallystartupfilesIwouldsay.


Let’s talk about them in briefly now, however we’ll discuss the same in great details in
comingchapterswiththeirusage.

BundleConfig:-Thisistheplacewhichwilltakecareofbundlingand
minificationofallscriptsandcss.

FilterConfig:-FilterconfigisthesectionwhichwillhelpwithFilter
registrationifanyweareusingintheapp.


RouteConfig:-Routeconfigisthenerveoftheappasitwilldecideallthe
routingarchitectureoftheapplication.Throughoutinourapplicationwe’llbe
usingitheavily.Sostaytunedwe’lldiscussthesameindetailwhenwestart


×