forked from sonusathyadas/Microservices-Training-Materials
-
Notifications
You must be signed in to change notification settings - Fork 0
/
basics.txt
733 lines (660 loc) · 22.8 KB
/
basics.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
HTML 5
- Simplified DOCTYPE declaration
- <!doctype html>
- Semantic tags
- div and span
- header , nav, footer, article, section, aside
- figure and figcaption
- Media elements
- audio - mp3, ogg,
- video - mp4, ogg,
- canvas elements
- draw images and graphics in web pages
- Form controls
- Url, search, number, range, date, datetime, color, email
- form validation attributes - required, min, max
- Placeholder attribute
- formmethod, formaction, novalidate
- Web Storage - localStorage, sessionStorage, WebDatabase
- Web Sockets
- Caching feature
CSS 3
- Cascading Style Sheets
- Inline, Internal or External
- Selector
- tag selector
- class selector
- id selector
- global selector
- Psuedo classes and elements
- Psuedo classes define the state of an elements
- active, disabled, hover, visited etc
- Psuedo elements are used to specify the position
- nth-clild, first-child, last-child
- selector:<pseudo class/element>
- a:hover, a:visited, p:first-child
- Box model in CSS
- Div with width and height
- where the box need to be placed: margin
- where the content of box need to be aligned : padding
JQuery
- Library vs Framework
- jQuery is a library of JavaScript functions
- Functions for formatting, DOM manipulation, AJAX , Form utilities
- Library is available as production version or developer version
- Production version is minified file ( jquery.min.js)
- Developer version is uncompressed file (jquery.js)
- In production we can also use the CDN Urls.
- No more document.getElementById() , use selectors
- Selectors can be Id, class or tag name
- Use the $() symbol or jQuery() to call jQuery functions
Angular
- SPA application
- One index page and multiple child views
- Child views will be included within the index view based on the route .
- When ever the route change happens the view gets replaced.
Eshop
- Main Module
Components - Home, About, Product, Search
Services - ProductService, AuthService
Directives
Pipes
- OrderModule
- Components - Order History, OrderDetails, TrackOrder
- Services - OrderService
- Directives
- Pipes
- Payment Module
- Components - Payment View, Refund Status View,
- Services - PaymentService
- Modules
- Container for Components, Services, Pipes and Directives
- Angular Apps are writing in TS, DART, JS
- TS is a compiled Language from Microsoft
- It is TypeSafe
- Dev --> TS --> Compiled --> JS
- Every component, service, directive, pipe must be part of one module.
- Features
- SPA
- DI Support
- Data binding - One way and Two way
- Forms
- Modularity
- Routing
- HTML 5 and ES6 specification
- CLI support - help you to generate components, services, pipes and directive etc using command.
- Install and run the Angular CLI
- ng --version
- npm install -g @angular/cli (visit: https://cli.angular.io)
- Create angular project
ng new <project-name> [--minimal --skip-install]
- Generate components
ng generate component <component-name>
OR
ng g c <component-name>
eg: ng g c home -> HomeComponent
(home.component.ts)
(home.component.html)
(home.component.css)
(home.component.spec.ts) <- Test class
ng g c list-view ->ListViewComponent
(list-view.component.ts)
(list-view.component.html)
(list-view.component.css)
(list-view.component.spec.ts)
- Generate Services
ng generate service <service-name>
OR
ng g s <service-name>
eg: ng g s payment -> PaymentService
(payment.service.ts)
(payment.service.spec.ts)
- Generate Directives
ng g d <directive-name>
- Generate Pipes
ng g pipe <pipe-name>
- Generate class
ng g class <class-name>
- Generate modules
ng g module <module-name>
- Run the application
ng serve OR ng s
- Build the applications
ng build
- Run all the tests (Unit testing)
ng test
- Module decorator
- @NgModule
- declarations - Array -> List of components, directives , pipes
- providers - Array -> List of services (explicitly registered)
- imports - Array - Imported modules
- exports - Array - Exported components, pipes, services and directives
- bootstrap - Array - Bootstraped components
- Component decorator
- @Component()
- selector
- styles
- styleUrls
- template
- templateUrls
- providers
- Directives
- used to add behaviour to existing elements or add a new element.
- Threee types of directives
1) Attribute directive - ngStyle, ngClass, ngModel, ngHide
<input type="text" [ngModel]="name" />
<div [ngStyle]="{color:cname}"></div>
2) Structural directive - used to modify the DOM (add/remove elements)
eg: *ngIf, *ngFor
<div *ngIf="age>30">Show me in page</div>
3) Component directive
- Has a view file (html)
- The component we create is actually a directive
- It is possible to create custom directives
- Binding
- One way binding
- interpolation - {{ variable}}
- Property binding - [propertyName]="value" (input binding)
- Event binding - (eventName)="eventHandlerFn()" (output binding)
- Two way binding
- combine property & event binding - [(attribute)]="handler"
- Pipes
- Simple TS classes used to format the outputs.
- Pipes are used in templates to format the text.
- Built-in pipes
- async
- uppercase, lowercase, titlecase
- currency, number, percent
- date
- Pipes are applied using the | symbol
- Can use more than one pipes (chaining of pipes)
- Routing
- package @angular/router
- import RouterModule and configure the routes
- Create a custom router module and configure routes and
import the custom module to main module
- Forms
- Forms can be created using two methods
- Template driven forms - FormsModule - @angular/forms
- Reactive forms - ReactiveFormsModule - @angular/forms
- Dependency Injection
- Angular Services are injectable classes.
- Inject the service objects into other class constructors (components, pipe, directive, service)
- Constructor injection
- Assume we have a service 'DataManager'
We want to inject in the HomeComponent class.
export class HomeComponent{
constructor(private dm:DataManager)
{
}
save(){
this.dm.getMessage();
}
}
- Services
- Simple typescript classes with reusable functions
- Services classes need to be decorated with @Injectable()
- Services can be registered globally or locally ( in module or component)
- Singleton by default
- Life Cycle Hooks in Angular Component
- OnInit interface
- ngOnInit()
- OnDestroy
- ngOnDestroy()
- onChanges
- ngOnChanges()
- RxJS
- RxJS is a library for creating asynchronous applications.
- Promises and Observable are two ways of implementing async operations.
- Promises are built-in to JavaScript now.
- But for using Observables we need to use RxJS library.
-
products:Product[]=[6];
doSomething()
{
console.log("Started");
getData()
.then(successCallback, errorCallback);
console.log("Finished");
}
doSomething(){
console.log("Started");
getData()
.subscribe(successCallback, errorCallback);
console.log("Finished");
}
- Http Interceptor
- Interceptor is an Angular Service
- Whenever an Http Operation is executed the interceptor executes
- Acting like a middleware for every HTTP call
- Pre process the request and Post process the response
example
Intercept(req, next){
const httpsReq = req.clone({
url: req.url.replace("http://", "https://"),
setHeaders: { "Authorization": `Bearer ${token}` }
});
return next.handle(httpsReq)
.pipe(
map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
let camelCaseObject = mapKeys(event.body, (v, k) => camelCase(k));
const modEvent = event.clone({ body: camelCaseObject });
return modEvent;
}
})
);
}
- Resolvers
- Used to resolve the data when routing.
- executes when a route is activated and before the component is loaded.
- Guard Services
- CanActivate and CanDeactivate
- CanActivateChild and CanLoad
- Unit testing
- Unit testing - Karma, Jasmine, Mocha, Chai
- Integration testing - Protractor
- use 'npm test' or use 'ng test' to run all unit testing cases.
- describe() - used to create a test suite
- beforeEach() - executed before each unit test function
- beforeAll() - executed only before first test funtion.
- afterEach()
- afterAll()
- it() - unit test function
it('description', testfunction());
if('should print Hello', ()=>{
//Test logic goes here
})
-----------------------------------------------------------------------------------
MongoDB
- Data Storages
- File based
- Querying data is difficult.
- Plain text files, less security.
- Difficult to perform CRUD operation
- Relation databases
- CRUD operations easy
- Querying data is faster.
- use of SQL language
- Relationships can be implemented.
- Normalized data for integrity and consistancy.
- Better security, backup feature, partitioned storage.
- Data is structured
- NoSQL storage
- unstructured , high volume of data
- better for modern apps like social media, online food order, shopping apps etc
- All related data stored in single place.
- primarily JSON is used for storing it.
{
id: 123,
user:{
name:"Ajay",
id:12,
email:"[email protected]"
},
postedDate:"2019-05-20 21:40 PM",
type:"Image",
url:"http://testapp.com/abc.jpg",
comments:[
{
id:585, uid:32, text:"Very good", date:'2019-05-20 22:30 PM",replies:[
{ id:32, uid:546, replytext:"Thanks", replyDate:"2019-05-22 9:40 AM"},
{ id:32, uid:546, replytext:"Thanks", replyDate:"2019-05-22 9:40 AM"},
]
},
{
id:3456, uid:3286, text:"Very good, where are you", date:'2019-05-20 22:30 PM",replies:[
{ id:32, uid:546, replytext:"Thanks, i am in mumbai", replyDate:"2019-05-22 9:40 AM"},
]
},
{
id:3456, uid:3286, text:"Very good, where are you", date:'2019-05-20 22:30 PM",replies:[
{ id:32, uid:546, replytext:"Thanks, i am in mumbai", replyDate:"2019-05-22 9:40 AM"},
]
}
],
likes:[
{uid:3232, when:'2019-05-43 05:40 PM" },
{uid:212, when:'2019-05-43 05:40 PM" },
{uid:3333, when:'2019-05-43 05:40 PM" },
{uid:54565, when:'2019-05-43 05:40 PM" },
{uid:556, when:'2019-05-43 05:40 PM" }
],
shares:[
{}
{}
]
}
- NoSQL Data Storage options
- Document type storage (MongoDB, DocumentDB/CosmosDB SQL API)
- Key-Value storage - Redis cache, Azure Table API storage
- Column family storage - Cassandra
- Graph storage (Neo4j, Gremlin)
- MongoDB (Document Storage)
- Mongodb community and enterprise
- Current version is 4.x
- Storing data in BSON ( Binary Json)
- MongoDB Server and mongoDB client is available
- Server - mongod.exe
- Client - mongo.exe (CLI)
- You can download third party GUI tools - MongoChef, NoSQL Booster , MongoCompass, Mongo3T( Studio3T)
- VS code provides an extension for CosmosDB which also connects mongoDB
.NET Core
-------------------------------------------------
- Why .NET Core?
- Modern apps
- containerized (Docker)
- Cross platform support
- Mobile based apps (apps should be light weight)
- Apps are cloud based
- Support for multiple deployment platform
- Loosely coupled applications
- Microservices based apps
- Features
- Open Source
- Light weight framework
- Cross platform support
- Cloud based (cloud oriented)
- Containerization support
- Simplified project structure
- CLI based development
- Microservices development support
- Project types
- Console apps
- Web apps
- MVC
- Web API
- SPA
- Class Libraries
- .NET Core (Current 2.2 next release is 3.0)
- in 3.0, added windows forms
- ML.NET
- .NET Core uses nuget packages of .NET Framework
- .NET Core apps can run on .NET Framework
- Create Standard class libraries to share the libraries with .NET framework
- .NET Core Project Structure
- Program.cs -> Main()
- WebHostBuilder created.
- Application configurations.
- host configurations.
- Logging Configurations
- DefaultWebHostBuilder().Build().Run()
- Startup.cs
- ConfigureServices()
- Used to configure the Services used in the application
- Database Server
- Caching Service
- MVC Routing
- Custom Services.
- Configure()
- Used to build the request pipeline.
- Configuring the middleware
- Constructor()
- appsettings.json
- Contains the configurations such as ConnectionStrings, AppSettings etc
- Depends on running env we can choose the appsettings file
- appsettings.json - Dev
- appsettings.production.json -Prod
- appsettings.staging.json - Staging
- ASPNETCORE_ENVIRONMENT environment variable defines which is the current environment
- *.csproj
- List of packages used.
- Metapackage - Microsoft.AspNetCore.App
- Controllers, Models, Views
- wwwroot folder
- Static file of the web application
- js, css, images, text, html
- Middleware
- a function that executes when request is coming and response is gone.
- Use, Map, MapWhen, Run methods can be used.
- Run()
- Short circuit method that terminates the request flow and generates the response.
- Configuration Sources
- Multiple Configuration providers
- XML file
- INI file
- JSON file
- Environment variable
- CommandLine args
- Filekey
- Azure KeyVault
- Dictionary (In memory collection)
- Main -> WebHost.createDefaultBuilder() returns a preconfigured web host.
- appsettings.json
- "SqlConnection":"DataSource=localhost;User Id=sa; Password=Password@123"
- EnvironmentVariable
- "SqlConnection" :"DataSource=129.54.33.24; UserId=sa;Password=Hexa@123"
-CommandLine args
- "SqlConnection" :"DataSource=129.54.33.55; UserId=sa;Password=Hexa@123"
- Dependency Injection
- Dependency Injection is not a built in feature of .NET Framework.
- Need to use third-party DI services (package) such as Ninject, Unity
- DI is a built in feature of .NET Core.
- .NET Core uses a built-in DI Service ( IoC container)
- .NET Core we can replace built-in IoC container with third party containers such as Autofac.
- Scope, lifetime and number of instance of service objects are managed by IoC container.
- Easily replace one service implementation with another.
- Scopes
- Singleton - Only one instance for the entire application
- Scoped - One instance per request scope.
- Transient - Create service instances wherever it is requested.
- DI service injection
- Constructor injection.
- Method injection
- Replace with Autofac
- Logging
- ILogger<Type>
- Log providers
- Console
- Debug
- EventSourceLogger
- Publish methods
- 2 ways
- Portable (Framework dependant)
- Self Contained
- Framework dependant
- Runtime must be installed in every machine to run the application.
- When run the 'dotnet publish' by default creates a framework dependant deployment
- You need a runtime in the running machine.
- Publish code size is small.
- To execute the published app, we need to use 'dotnet app.dll'.
- Self-contained
- The publish command published the app along with the runtime.
- While publishing you need to specify the runtime identifier.
- eg: dotnet publish -r Win10-x64
- While publishing it generates a self executable exe file not DLL
- No 'dotnet' command is required to run it. Just double click or execute in command prompt
- dotnet publish
- move to bin/Debug/netcoreapp2.2/publish
- execute the app using 'dotnet ConsoleApp.dll'
- dotnet publish -r win10-x64 --self-contained
- move to bin/Debug/netcoreapp2.2/win10-x64/publish
- execute by just typing the exe file name 'ConsoleApp.exe'
- MVC
- Tag Helpers instead of Helper methods
- View Imports razor file introduced
- DistributedCache configuration
- DeveloperException page middleware
- StatusCode error pages
- RouteConfig.cs file is removed , mvc routes are configured using Middleware
- Tag Helpers
- Custom tag helpers
- Cahing
- Used to improve the performance(reduce response time) of the application
- Types of caching in .NET Core
- Response caching - [OutputCache Duration="" VaryByParam=""] in MVC 5
- cache tag helper
- In memory Non-distributed cache
- Distributed Cache
- InMemory DistributedCache (Not for production, only for Dev and Test)
- Sql Server DistributedCache (Recommended for Prod) - Relational Database
- dotnet sql-cache create "connectionstring" schema tablenme
- dotnet sql-cache create "Data Soruce=XXX" dbo CacheTable
- Redis DistributedCache (Recommended for Prod) - NoSQL Database (Key-Value)
- IDistributedCache Interface
- InMemoryDistributedCache
- SqlServerDistributedcache
- RedisDistributedCache
- Hosting
- Host is reponsible to start and configure the server.
- In .NET Core we have 2 types of Host
- Web Host
- Configured with a HTTP request pipeline.
- Only webhost is able to handle the Http request.
- Either we can create the instnce of Web Host explicitly using 'new'
- But, .NET Core provides a WebHost object returned by WebHost.CreateDefaultBuilder()
- Default WebHost object returned by CreateDefaultBuilder() method is preconfigured.
- Already configured with Kestral, Logging, Host configuration, Configuration sources etc.
- But, we can customize the configuration
- GenericHost
- Decoupled the Http Pipeline
- Best suited for creating background apps such as apps monitoring the queues, schedules task
- State Management
- Query String - NO
- Cookies - NO
- Session - YES
- You must configure Distributed cache.
- Enable the Session service using AddSession()
- Enable the Session Middleware using UseSession() method
- Hidden Controls -NO
- TempData
- Can persist the data untill it consumes.
- It can carry the data even in the redirection scenarios where ViewBag and ViewData cannot be used.
- In .NET Core TempData is implemented with Providers
- CookieBasedTempDataProvider (Default)
- SessionBasedTempDataProvider
- HttpContext.Items
- Used to pass the data from Middleware to Action.
- Cache - Already Done
- DI
- Create a Singleton service
- all controller use the same instance
- Data is shared using the common instance
- Microservices using .NET Core
- What is Monolithic application development? - Done
- What are challenges of using Monolithic apps?
- Tight coupling
- Dependency increased
- Scaling independent modules not possible
- Less or no technology or language choice
- Deployment
- Shared Database
- Testability
- Service Oriented Architecture
- Each module is developed as independent projects (services)
- They are independently deployable
- All services will expose well defied endpoints such as HTTP/HTTPS
- What is Microservices architecture?
- Create service that are independently developed, deployed and tested.
- What are the features of Microservices?
- Fine grained format of SOA
- Language and technology agnostic
- Polyglot persistance
- Independently scalable services
- Deployment is faster because deploying services independently
- Deployment of one service will not cause the downtime of other services.
- Independently testable
- Services can communicate each other using well known communication methods
- Synchronous communication
- RESTful services
- .NET remoting (only for .NET microservices)
- Asynchronous communication
- Message Queue communication
- Event based communication
- Monolithic vs SOA vs Microservices
- Case study
- Event Management Application
- EventAPI
- CreateEvents()
- DeleteEvent()
- UpdateEvent()
- RegisterEvent()
- ViewDetails()
- IdentityAPI
- RegisterUser()
- LoginUser()
- UpdateProfile()
- EventUI
- Angular 7 UI
- Web API
- Used to create RESTful services
- Web API Service Controllers are inherited from ControllerBase
- No more RoutePrefix, use Route attribute for controller
eg: [Route("api/[controller]")] -> api/events
- [ApiController] attribute which defines the response type of the result
- conversion of request data to JSON
- No more route attribute for Actions, Define routes in Http attributes itself
eg: [HttpGet("/{id}")]
- Only JsonFormatter is by default added, Add Xml formatter explicitly
- Action return types can be
- Specific types
- IActionResult
- ActionResult<T> - new
- EF
- REST - HTTP
- Headers
- In key-value format
- Content-Type : application/json
- Accept : Expected MIME type
- Aurhorization: "Scheme Value"
- Bearer JWT Token
- Basic (U/pwd)
- HTTP Status Codes
- 1xx - Informative
- 2xx - Success (OK -200, Created -201)
- 3xx - Redirect - (Permenant, Temporary, Cached)
- 4xx - Client Error (404 -Not Found, 401-unauthorized, 403-Forbidden, 400- BadReqeust)
- 5xx - Server Error (500- Internal Server Error, 501- Server Timeout)
- HTTP Methods
- GET - Access data from server
- POST - Add data to server
- PUT - Replace data in server
- PATCH - Update the existing
- DELETE - Remove item from server
- URL
- Endpoint: Method + URL
GET /api/products - Get all products
POST /api/products - Add a new product
GET /api/products/{id} - Get item by id
PUT /api/products/{id} - Update/replace item
DELETE /api/products/{id} - Delete the item
- MIME types
- major type/minor type
- Major types
- text
- plain (text/plain)
- xml (text/xml)
- html (text/html)
- json (text/json)
- css (text/css)
- javascript (text/javascript)
- audio
- midi (audio/midi)
- wav (audio/wav)
- mp3 (audio/mp3)
- video
- avi (video/avi)
- mp4 (video/mp4)
- wmv (video/wmv)
- image
- png (image/png)
- jpg (image/jpg)
- gif (image/gif)
- bmp (image/bmp)
- application
- word doc
- pdf
- zip file
- exe files
- EF
- Code migrations
- VS : PowerShell Package Manager Console
- VS Code: Dotnet CLI commands
- To Add migrations
- PM : Add-Migration "InitialCreate"
- CLI : dotnet ef migrations add "InitialCreate"
this generates a Migrations folder with a migration file.
Name: <Timestamp>-InitialCreate.cs
- create the tables
- PM : Update-database
- CLI : dotnet ef database update