Translate

Thursday, January 06, 2022

Dependency Injection

One of the places I interviewed asked to present a small write up on DI, expectation was to be small and concise, here's what I came up with: 

What is dependency injection in C#, and what are the benefits of dependency injection?


Dependency Injection is a software design principle and pattern that enables developers to write loosely coupled code. 

It supports the notion of program to an interface and not an implementation. 

Dependency Injection addresses following problems: 

- The application uses an interface or base class to abstract the dependency implementation 

- Registration of the dependecy in DI container, once all the implementations of the service are registered the DI container can be built

- Injection of the service into the constructor of the class where it's used. The DI framework takes care of instatiation and disposing of the instance. 

Here are some of the advantages of the DI : 

- Late Binding : Implemented Services can be swapped with other services if needed. This is helpful in case if there's a requirement to use ORACLE instead of SQL. 

- Extensibility : Code can extended and reused in ways not specifically planned for.

- Parallel Development: Since the components are dependent on each others interfaces the development can happen parallely. This is especially helpful in large organizations. 

- Testability: Classes can be unit tested. Since the dependcies are abstracted using interfaces writing unit tests on the classes become easier by using mocking frameworks. 

Friday, December 17, 2021

Interview Attempt

I went into the Interview not knowing what to expect and expecting that with the level of preparation I had I will fail. I was desperate for a failure (surprising right) to know what plays out in a coding interview in US.

To my surprise I was asked few .Net Questions initially: 

- Explain the whole .Net Ecosystem with what's happening with .NetFramework, .Net Standard, .Net Core and .Net 6.0. Why and how we came to a state where we are. 

- What is Boxing and UnBoxing

- Explain the IDisposable pattern, Why can't we use the finalize method instead of implementing the IDisposable patterrn? 

- Have you ever encountered a problem with Memory Leak and what tools did you use to solve it and what was your approach. 

- What is dependency Injection and What are the advantages of that, how can you implement that in a feature.

- How do you keep yourself updated with the latest technology updates and what are your go to resources for the latest developments.

This was followed by a coding round where in I was provided with LeetCode problem number 253: https://leetcode.com/problems/meeting-rooms-ii/

Definitely I did not do well cause of lack of preparation and did receive an honest feedback from the interviewer, I did not generate enough test data for the coding puzzle, should have solved simpler cases and then moved onto the complicated cases. Also while considering the timing I took DateTime as a input, Interviewer suggested I could have started with the int solved few cases and then moved onto the DateTime. 

Friday, October 29, 2021

What happens when you type webapplication.com in your browser

I will be describing the lifecycle using the ASP.Net MVC framework hosted on IIS on Windows. I will be describing the case under the assumption that the application is using .Net Framework 4.7.2 and not .Net Core. I am doing this based on what I have worked on in my current role. 

https://webapplication.com/ 

- The browser expects the URL to be in the format : scheme://host:port/path?query#fragment

- In this case the scheme is https which determines the default port to be used is 443. In this case the host is webapplication 

- The URL format above is adhered in this case and now the browser knows the hostname which it needs to resolve to an IP Address.

The browser will start to find the IP Address from the cache of browser or the next is to lookup in the host file of the machine, Windows has a local host file. 

- Once the cache lookup fails the browser sends a DNS request which using UDP.  The request is forwarded to the ISP's DNS Server. 

- Assuming that the request message is received by a DNS Server the server looks for the IP address associated with the requested hostname, if the address is found then the response is sent back else DNS recursively forwarded to the next configured DNS server until the address is found. 

- Assuming that the response of the UDP request is back the requesting client will now have a target IP Addressed which will be cached so that next set of requests do not have to go through multiple DNS hops. 

- Now that the client has an IP Address, browser can send the https request which is a application level protocol and uses transport layer security. The request at lower level uses the TCP which is a transport layer protocol which ensures the delivery of data in the same order as it was sent. 

- The browser in this case opens a TCP connection which is a 3 way hand shake, here's an example of how this interaction looks like 

 First Step: Browser: ---(Sends SYN=1234) ---> :Server 

 Second Step: Server: ---(Sends SYN=4011 ACK=1235)--> :Browser 

 Third Step : Browser: -- (Sends ACK=4012) --> :Server 

- Now that a 3 way handshake is completed an connection is established, now we are ready to send a https request. Ahh wait, Not quite yet because we are using https here.

- Since the scheme in the URL was https After the TCP handshake there's a TLS HandShake, with TLS the client and server 

adhere to the common ground of secure communitcation. Here's a small snippet of what a TLS HandShake looks like : 

Client Hello ---(TLS Version, Cipher Suites, Client Random) --> Server 

Server Hello --- (SSL Certificate, Cipher, Server Random) --> Client 

Authentication --> Client verifies the SSL Certficate 

Client --> Sends a premaster secret which is encrypted using the cipher and public key

Server --> decrypts the premaster secret using the private key. 

Both Client and server generate session key using the information exchanged above, the result should be the same. 

Client sends a finished message with SessionKey 

Server sends finished message with a sessionKey. 

Symmertic encryption is acheived and communication can continue using the session keys. 

- The client now sends a https request which contains http Method (GET, PUT, POST or DELETE), in this case its a GET since the browser is requesting a resource from the server. 

In this case the http request may look like 

GET http/1.1

Host: webapplication.com

- Assuming that the web application is hosted by an IIS Server and is build using the ASP.Net MVC. 

- The httpRequest reaches the IIS Server which based on the domain identifies the correct web application to service the request. 

- I will not go into the detail of how IIS processes the request, instead we will assume that IIS makes sure that the request reaches the correct the web application. 

- Now we will dive into begining from receiving the http request from the browser to sending the http response back within the the ASP.Net MVC pipeline.

- At a highlevel MVC Pipeline has the following processes in order : Routing --> Controller Initializtion --> Action Execution --> Result Execution --> View Initializtion and Rendering.

- https://webapplication/ , assuming there's no overriding of the default route map, UrlRoutingModule starts matching the perfect URL pattern from the RouteTable,

the request will be routed to https://webapplication.com/home/Index, Controller which will be Initialzed is HomeController and the Action is Index 

- Once the URLRoutingModule finds the controller the appropriate controller is instantiated, appropriate action on the controller is invoked in this case Index. 

- Assuming the browser requested a resource which does not require authentication or authorization to access. Hence no authentication and authorization filters will be called. 

- As stated earlier in assumption that this is a GET operation the model binders will not play a role. 

- After the execution of Action the ActionResult is generated. This step completes the action execution. 

- ActionResult can be of many times for example ViewResult, RedirectToRoute, JsonResult. Let's make an assumption that we get a ViewResult back. 

- ViewEngine along with HTMLTagHelpers render the view and create a http Response with Body and applicable httpHeaders. 

- Once the response is generated At TCP layer the client receives the data which contains the httpResponse Header. 

- Assuming that the response is fully received by the client then there's a way 4 handshake to close the connection between the browser and the server. 

    (FIN <--> ACK)

Above discription is a simple interaction in a non-persistance interaction. 


Sources: 

https://en.wikipedia.org/wiki/URL#:~:text=A%20typical%20URL%20could%20have,and%20a%20file%20name%20(%20index.

https://github.com/hardikvasa/http-connection-lifecycle

https://dev.to/dangolant/things-i-brushed-up-on-this-week-the-http-request-lifecycle-#fnref10

https://www.cloudflare.com/learning/ssl/what-happens-in-a-tls-handshake/

https://www.cloudflare.com/learning/ssl/keyless-ssl/

https://www.c-sharpcorner.com/article/mvc-architecture-its-pipeline4/


Saturday, June 13, 2020

Apigee Learning and references.

At work there's an ongoing project to expose our existing set of Rest API's to outside world. The chosen product for API management is apigee. I wanted to learn more about this product and started looking around. 

I am documenting the set of resources that I completed: 

To get started create a trial account on apigee, google has been pretty kind with the eval accounts. One can be created by going to this link here

You'll get an activation link on the email entered and then once the account is activated google will provision a tenant (not sure if this is the right word here may be Organization may be a better word) for you. 

It takes a little bit of time to complete the provision but be patient and let google do the hard work for you :)


Once I had my eval Organization created, I followed steps here. Following the steps gives you an idea about the layout of the apigee UI. I highly recommend going through the Basic Concepts section too. 

I also found that there's a leaning track (again not sure if I am using the right word) on Coursera which has a set of courses which targets API development with apigee. 

(I have not completed this yet but hopefully I will and then update this post about how this course was). 

Tuesday, June 02, 2020

HTTP PATCH

Implementing a client for an http PATCH route got me confused that which is the correct way to implement. 

Here are couple of links which helped me grasp this concept: 
https://sookocheff.com/post/api/understanding-json-patch/


Another one: https://medium.com/hepsiburadatech/you-know-nothing-engineers-http-patch-d2ebab99c1d5

Here's the package which was used to implement the server as well as client for the http PATCH: 

https://github.com/KevinDockx/JsonPatch

Thursday, October 03, 2019

Async and Await notes

- Await Keyword introduces continuation which is executed after the async operation 
- The coninuation is executed on the original context in this example that is the UI thread. 
- The await keyword introduces a coninuation allowing to get back to original context. 
- Marking a method as async introduces the capability of using the await keyword to leverage the asynchronous principles. 
- Avoid async void at all cost 
- Using Async void is allowed only for Event HAndlers 
- Methods marked as async taks will automatically have a Task returned without explicitly having to return anything,  then the caller can await the Task 
- If we do not use await keyword on async methods the inner exceptions will be swallowed. Always use the await keyword to validate your tasks. 
- Exceptions occuring in an async void cannot be caught 
- Do Not 
- No Async void 
- Avoid .Result or .Wait 

- Do 
- Async and Await together 
- Always return a Task from an Async method 
- Async and await all the way up. 

- Task Represents an asynchronous operation 
- Task.Run() queues the work passed as the action to run on a different thread by using the thread pool 
- Before Loading 
- Task.Run() queues the work which completes instantly 
- After Loaded --> Executes immediately after Task.Run()
- A task can easily for block the UI so be very careful when wrapping synchronos code and make sure it does not contain blocking code
- ContinueWith creates a continuation which runs asynchronously this means that it also returns a Task. 
- Calling the Result property on a task is not a problem as long as the task has finished its asynchronous operation. 
- A big difference between using await and ContinueWith is the fact that ContinueWith is not back on the original context.
- In case of ContinueWith if there's an error in the async operation then we need to define the TaskContinuationOptions to specify what needs to be done in case of exception. 
- Using await together with try and catch is recommended and does not wrap exception in an aggregate exception. 
- Whenever you use the ContinueWith make sure to validate tasks even when not using async and awat by chaining on a continuation, 
- CancellationTokenSource is used to signal that you want to cancel the operations that utilize the token.
- CancellationTokenSource is coupled with CancellationToken which is passed to async operations to indicate that operation is cancelled or not. 


Friday, June 22, 2018

Basics of git and setting it up with VSCode


  1. Course from Pluralsight : https://app.pluralsight.com/library/courses/git-fundamentals/table-of-contents
  2. Installer from the following link:  https://gitforwindows.org/
  3. Setting VS code as a default editor from the Link: https://blog.soltysiak.it/en/2017/01/set-visual-studio-code-as-default-git-editor-and-diff-tool
Have been learning about GIT and a lot of good links were shared by my colleagues, to get a good introduction to git I bought this ebook: https://abookapart.com/products/git-for-humans

Follwing links are easy to read and useful to have consistency across the team: 
Associating Text Editors with Git

Git Log pretty formatting

Advanced Git Logs

A Note about git commit messages:

How to Write Commit Messages

Data Integrity of Git is pretty well described in the talk: