Translate

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: 






Tuesday, August 29, 2017

Building a docker Image with iis and pre-requisites

Steps to do: 

- Run the container with the command  docker run -it 4f222 cmd.exe 
- Image which is run here microsoft/windowsservercore
- this should open the command prompt 
- then the navigate through the command prompt (to c:\ProgramFiles\powershell\powershell.exe) to get a powershell command prompt
- In the powershell execute: Install-WindowsFeature -Name Web-Server, Web-Mgmt-Tools
- Above commnand should enable IIS Server on the container and also install management tool for that 
- To test the successful installation of the web-server try executing the iisreset in the prompt, you should be able to see the iisreset message then. 
- To know the full folder name of the docker image we need to run the command: docker inspect -f '{{.Id}}'  e9bb03ced109(ContainerID)
- Best option is to mount a folder to the image and then have it as a part of the image so that it can be accessed within the image. 
- command to run in the mount mode: docker run -it 4f222 powershell.exe --mount type=bind,source=c:\Hackathon,target=c:\Hackathon (Some how this did not work today)
- Trying another suggestion form StackOverflow: https://stackoverflow.com/questions/40313633/how-to-copy-files-from-local-machine-to-docker-container-on-windows
- Container name is required to execute the command, to get the container name: 
docker ps --format "{{.Names}}"
- Modified command for this machine: 
docker cp c:\Hackathon sharp_euclid:c:\Hackathon

Tuesday, June 13, 2017

Containers on Windows

Learning stuff about containers and trying to figure out how to run a asp.net webapi inside them. 

Links which I am referring as I am moving forward: 


Here's a link talks about creating VM with containers on Azure: https://blogs.msdn.microsoft.com/jcorioland/2016/10/13/getting-started-with-windows-containers/





Run command for the docker has many switches: 

Wednesday, July 09, 2014

Web.config Transformation Syntax for Web Project Deployment Using Visual Studio

Needed to do some work on the web.config transformations, I was finding difficulty in locating the complete set of functions which can be set to either xdt:Transform or on xdt:Locator. \

Finally found a cool link on msdn which served my purpose: 

Another link which helped: 

Thanks
Dibyendu

Friday, March 28, 2014

Self answered question on Stackoverflow: how-to-get-typeas-in-request-gettype-of-a-request-message-in-service-behavior

Stackoverflow is the lifeline of all the developers these days. I created a question and answered it for myself and this is my first attempt at asking a question and answering it, till date no one has upvoted the answer but I would still like to paste the link here: 


Thanks
Dibyendu

Thursday, March 13, 2014

Faking Static constructor

I have been fixing up some legacy test cases written against Typemock 6.0.8 and was planning to get it running against Typemock 7.4.3. 

As always legacy code was faking some objects which were internally referring objects which had static constructors. 

Couple of links which helped me here : 




Thanks
Dibyendu

Wednesday, February 12, 2014

Visual Studio TFS: Why no keyboard shortcut to view the Source Control Explorer?

A common thing which I lookup multiple times and thanks to  Ian Goodsell for blogging : 
http://blog.iangoodsell.com/2009/08/visual-studio-tfs-why-no-keyboard.html


And one request to VS team please make the dialog little larger so that a developer can see at least 10 commands.
This does not help:

Thanks
Dibyendu

Tuesday, December 24, 2013

WCF Extensibility

Behaviors
Enter WCF extensibility points.
What is covered:
-          Service description vs Runtime
-          Behavior Interfaces
-          Runtime Extensibility
o   Interceptors
o   Formatters
o   Instancing
o   Error Handling
o   Some Others
-          Metadata Extensibility
-          Serialization Extensibility
-          WCF Channel  Programming Model
What is not  covered:
-          Some lesser-used interfaces
-          Security

Service description vs Runtime
-          Service (client) Description
o   All the things needed to start the service (client)
o   Ednpoints (Address/Binding/Contract)
o   Local Behaviors
-          Before “Open”
o   Description can be changes at will
o   Service not “running”
-          After “Open”
o   Runtime is initialized
o   Description is immutable
o   Listeners are started
o   The Service is started
-          WCF provides 4 interfaces to interact with the Service or Client descriptions
o   Service
o   Endpoint
o   Contract
o   operation
-          Each Interface has 4 methods which follow the same pattern.
-          public interface I[Service/Contract/Endpoint/Operation]Behavior
o   void validate(Description) : Prevent host or client from opening if it finds something invalid in the service description
o   void AddBindingParameters(Description, BindingParameterCollection): This gives an opportunity to the behavior to add more information to the Binding channels.
o   void ApplyDispatchBehavior(Description, Runtime):  This is the place where the behavior gets hooked up  to the runtime in the corresponding scope.
o   void ApplyClientBehavior(Description, Runtime) * {This is only client side}
-          Called during Open (Be it at the service side or the client side)
-          Ordering
o   Validate à AddBindingParameters à  Apply[Client/Dispatch]Behavior
o   Serviceà  Contract à Endpoint à Operation

-          Service Behavior
o   Service-wide operations
§  Metadata : Validation of the metadata exchange across the communication
§  Throttling
§  Debug
o   Public interface IServiceBehavior
§  Validate
§  AddBindingParameters
§  ApplyDispatchBehavior
o   Added via code, configuration, attributes
WCF Runtime   
WCF is a message stack with many message blocks from client calling the operation to the service call getting executed on the server.
We will see the most used blocks through which the messages pass.
·         WCF Runtime
·         Message Object
·         Message Inspectors
·         Parameter Inspector
·         Message Formatters
Client Proxy Call à Parameter Inspector à Fomatter à Message Inspector à WCF stack à Message Inspector à Formatter à Parameter Inspector à Service Operation

First question is what is a Message, what is the structure and Characteristics of the message.?
·          
·         System.ServiceModel.Channel.Message à Abstract Class
·         SOAP/XML
·         Parts
o   Header – Buffered
o   Body
o   Properties : Dictionary not part of SOAP specification
·         Single-use : Once the message is used and read then it cannot be used any more. One can manipulate message headers at will.
·         Message Versions:  different versions of SOAP protocol which are envelopes like SOAP 1.1, 1.2 or none (message is not SOAP message but POX- Plain old XML)
·         XML
Message Inspectors :
Most used WCF extension from the WCF Runtime.
·         Usage: inspect, modify, replace messages
·         Scenarios: Logging, custom auth, tweaking messages, correlation between request and response
·         Server Side
o   MessageInspector is represented by the Interface: IDispatchMessageInspector
§  AfterReceiveRequest
§  BeforeSendReply
o   Dispatch behaviors are typically added as endpoint behavior as a part of ApplyDispatchBehavior to the DispatchRuntime object.
·         ClientSide
o   MessageInspector is represented by the Interface:  IClientMessageInspector
§  BeforeSendRequest
§  AfterReceiveReply
o   MessageInspectores are added as a part of service endpoint to the clientRuntime object.
o   Correlation object Used as correlation so that request can be set with something specific after the prior reply is received.
Parameter Inspector
Parameter inspectors are same as message inspectors but they are called on CLR objects not the message objects. They are easier to use as they do not require any knowledge about messages. Unlike Message inspector they are less powerful as they have less access to message itself.
·         Usage: Inspect and Modify operations inputs and outputs.
o   Return value cannot be modified
·         Scenarios: logging, parameter validation.
·         Same Interface for Client and Server : IParameterInspector
o   IParameterInspector
§  BeforeCall
§  AfterCall
·         Adding parameter inspectors often done in OperationBehavior
o   Server: DispatchOperation
o   Client: ClientOperation
·         Like MessageInspector ParameterInspector has a Correlation object is returned by BeforeCall and Passed to AfterCAll.

Message Formatters
Message formatters are the gateway between WCF messages and world of CLR objects.
·         Usage: convert between CLR objects and Message
·         Unlike Inspectors MessageFormatters are not optional but each operation has one and only one instance MessageFormatter.
·         Scenarios: supporting different formats, like passing some information as a part of httpHeaders.
·         Server Side
o   MessageFormatter is represented by the interface: IDispatchMessageFormatter
§  DeserializeRequest
§  SerializeReply
o   Message formatters can be accessed using the DispatchOperation in the Endpoint and operation behavior.
·         Client Side
o   MessageFormatter is represented by the interface: IClientMessageFormatter
§  DeserializeRequest
§  SerializeReply
o   Message formatters can be accessed using the ClientOperation in the Endpoint and operation behavior.
·         One difference between Inspectors and formatters is that it does not provide the Correlation object between request and reply.








Monday, September 23, 2013

Design Pattern Notes

I have been going through the Design Patterns Library course hosted by Pluralsight. Below is a small descriptions and a note to understand various patterns.

I hope that I should be able to cover all the patterns as the list of patterns are quite extensive and I recommend all of you to get a license of Pluralsight so that you can be exposed to the sea of courses they have. 
(Excuse me upfront for the typos as the notes were taken in notepad++ while I was going through the patterns, once I finish the important patterns I intent to reformat this post and make it more pleasant for all of us)



Adapter Pattern: 
--------------------------------------
- The Adapter Pattern is used to wrap a needed class with one that implements a required interface. 
- By writing client classes so that they depend on adapters, we future proof these classes, ensuring 
they can be made to work with as-yet-unwritten implementation libraries. 

Related PAtterns to the AdapterPattern: 
- Repository Pattern
- The repository pattern is a verfy common use of Adapter Pattern
- Strategy Pattern
- The adapter pattern is often passsed into a class that depends on it, thus implementing the strategy pattern.
- Facade Pattern
- Adapter and facade pattern are both wrappers. The facade pattern attempts to simplyfy the interface and often wraps many classes, while the Adapter 

typically wraps a single Adaptee, and is not generally concerned with simplyfying the interface.

Bridge Pattern: 
--------------------------------------
DEcouple an abstraction from its implementation so that 2 can vary independently. Abstractions and implemenation are decoupled. 

Abstract one more level of interface so that 1st level of abstraction is dependent on the 2nd level of abstraction 

This abstraction is going to use one more level of Abstraction as its implementation.\

Abstraction -> Abstraction -> Implementation 

For one level of abstraction there's no need of Bridge pattern. 
Common usgaes of bridge pattern: 
- User Interfaqce 
- Neat explanantion of the pattern is also given at: http://www.oodesign.com/bridge-pattern.html

Builder Pattern: 
--------------------------------------
Problem 1: too Many paramteres
Problem 2: Order Dependent
Problem 3: Different Constructions

Spearates the construction of a complex object from its representation so that same construction process can create different representations. 
Construction of the object is a process OR logic.
Representation of the object is data. 

Separate logic from data, reuse the logic to produce different data. 

Instead of telling the subway guy on what all you need after asking for each ingredient you are going to give him an list of ingredients so that the conversation is 

much shorter. 

Chain of Responsibility Pattern: 
--------------------------------------
Provides a simple mechanism of decoupling the sender of the message from the receiver 
Ordered list of methods 

Sender --> Receiver1 --> Receiver2 --> Receiver3 

Lets say in the above scenario the message sent by the sender is handled by the Receiver2 and so the receiver 3 is not needed.
Sender only is exposed to the Receiver1 and so is the Receiver2 knows only about Receiver3. This brings us to the traits of Chain of Responsibility. 

- Sender is aware of only one receiver 
- Each receiver is only aware of the next receiver
- Receivers process the message or just send it down the chain
- The sender does not know who received the message.
- The first receiver to handler the message terminates the chain
- The orcer of the receiver list matters


Command Pattern: 
--------------------------------------

- A command line order management system
- A system in which you pass in a command to be done. 
- In such systems we should be wary of a very big switch case statements which decide what to do based on the input passed.

Intent of the PAttern: 
- Represent an action (piece of logic) as an object
- DEcouples the clients that execute command from the details and dependencies of the command logic
- Enables delayed execution 
- Can queue command for later execution 
- If command objects are also persistent, can delay acrosds the process restarts

Also knows as Action OR Transaction PAttern
Applicable on 
- Logging the actions 
- Validation 
- Undo functionality in the website 

Client --> Command { Validate(), Execute(), Undo()} --> (dependencies)
  --> (dependencies)

- Key notion of command pattern is that somebody can call a method without dealing with any extra data.
- There is no parameter to be passed which makes it different from the Strategy pattern (here execution path is defined based on the parameter passed)
- COmmands must be completely self contained 
- The client does not pass in any argumemnts, the context from the caller is not required 
- Easy to add new commands (open/closed principal)

Related Patterns: 
- Factory pattern : Factories are ofyten useful to construct the command objects 
- Null Objects: Often times returning a "null command" can be useful instead of retuning a null
- Composite Command: Command with child commands

http://www.oodesign.com/command-pattern.html


Composite Pattern: 
--------------------------------------
- Compose objects into tree structures to represent part-whole hierarchies. 
- Composite lets clients treat indivisual objects and compositions of objects uniformly. (GOF)
- If you are sending emails to individuals instead of using the group aliases then you need to apply composite pattern to your life. 
- Using group aliases is the live example of using the composite pattern, the sends just sends an email to the group and the e-mail has the logic to iterate over the 

members of group and make sure that email is individually sent to each of the member.
When to Use Composite Pattern: 
- When you have groups and collections 
- Can you add an Interface
- trees
- Distribution 

Basic is to define an interface (component) and have a leaf (simple object implement it) and then create a composite object which implements the interface and also has 

a property which is of the type of component.



Decorator Pattern: 
--------------------------------------

Structural Pattern : DEcorator object is used without touching the existing class. 

Small Pizza company: Large, Medium and Small Pizza deriving from Base class Pizza. 

Problem is when toppings are introduced: Cheese, Ham and Peppers

Now with 3 Pizzas we have 3 toppings each combination is a unique pizza. 
This will result in class explosion and will become very hard to maintain. 


Intent: 
- Add functionality to existing objects dynamically at runtime without effecting the other classes. 
- Alternative approach to sub classing 
- Inheritance based design leads to an explosion of the classes.
- Flexible design 
- Support Open Close Principle --> Open for extension but closed for modification 

Applicability
- Legacy systems 
- Add functionality to controls. 
- Sealed Classs

IExtenderProvider interface uses decorator pattern, for more info on the interface below are the links: 
http://www.codeproject.com/aspnet/FixingIExtenderProvider.asp 
http://www.codeproject.com/aspnet/ExtenderProviderComponent.asp

How does it work: 
- It wraps the object -- Also known as wrapper object 


Lazy LOad Pattern: 
--------------------------------------

Lazy Initialization Pattern : 

- Simplest approach 
- Every property checks to see if its backing firlds has been initialized 
- If so it calculates or fetches the value for the field before retunung.
- Violates don't repeat yourself principle 
- Requires all access to tge value ti go through the property
- Within the class nothing but the property should access the field. 
- Requires knowledge of whether the fields has been calculated
- Typically check if the field is null
- If null is a legal value then another approach is required, like using the flag if the value is populated or not. 



Virtual Proxy Pattern: 
- Proxy looks like real object
- Creates Indentity problem in the application 
- Proxy isn't the real object 
- OverRide the equality method (Equals)
- Proxy Design PAttern
- May need to create many virtual proxies
- Best done via some kind of code generation 
- MAny OR/M tools create dynamic proxies at runtime (nHibernate, Entity Framework)

Virtual Proxy Consequences: 
- Managing Identities can present Challenges --> Overriding GetEquals and GetHashCode 
- Need to create many virtual proxies, one for each class that is proxied
- Above stated points are not present for collections: 
- Collections are value objects and do not have an identity.
- Typically there are fewer collections than objects 
- Collections typically provide largest performance benefit from the lazy loading. 

Value Holder LAzy Load PAttern: 
--> No need to use this if we are using .Net 4.0 if .Net 4.0 is in use then directly use Lazy
-  Provides lazy load functionality without encapsulation which means the client knows about the lazy loading. 
- Calling code knows it is working with a Value Holder  type 
- Requires creating several new Types: 
- Value Holder 
- IValueHolder 
- Factory or MapperClasses
- Value Holder uses IValueHolder via Strategy Pattern to load value when accessed.
- ValueHolder and IValueHolder are resuable
- ValueHolder is similar to Lazy and IValueHolder is similar to the lambda expression which is passed which knows how to load the lazy type. 
- ValueHolder and IValueLoader are resuable.

Ghosts Pattern: 

- A ghost is a real object in a partial state.
- An object which knows about its own state. 
- Intially ghost contains its Id.
- Whenever any property is accessed, the ghost class loads all of its state from persistence. 
- Essentially, the object is its  own virtual proxy
- Avoids identity concerns of its own virtual proxy,
- This violates the Single responsibility cause the object is needed for self loading and plus loading the state of its own properties. 


Mediator PAttern: 
--------------------------------------
Motivating Example
- When you have many objects of a similar typpe that need to communicate with each other 
- The communication between objects is complex
Definition: 
- Define an object that encapsulates how a set of objects interacts. Mediator promotes loose coupling by keeping objects from referring to each other explicitly,
and it lets you vary their interaction independently. 

Components in Mediator Pattern: 
- Colleagues 
- Individual compnents that need to communicate with each other Airbus, Fighter 
- Implement the same base type(abstract class or interface)
- HAve a knowledge of the Mediator component rather than knowing of each other. 
- Mediator 
- Single centralized component that managed communication between the colleague components
- abstraction of mediator is necessary so that the colleagues work with the abstracted mediator rather than concrete one. 

Advantages: 
- Hides all the coordination between colleagues 
- Decoupled colleagues 
- Mediator's one to many relationship with colleague is preferred to colleagues relating in a many-to-many fashion.

Disadvantage: 
- The mediator can become very large and very complicated as more colleagues are handled. 

Overall mediator enhances decoupling 


Memento Pattern: 
--------------------------------------

Undo and Redo functionality 
Motivating Example: 
- It would be useful to rollback one or more objects within your application to previous state(for example, to implement Undo)
- Providing undo functionality within one or more calsses would violate the single responsibility principle 
- Providing full access to objects internal state violates the encapsulation principle
- The Memento pattern describes a way to capture the objects internal state without violating encapsulation or SRP. 

Intent: 
- Without violating the encapsulation, capture and externalize an objects internal state so that the object can be restored to this state later. 
- The memento pattern involves 2 objects : originator and caretaker. Thr originator represents object whose state is being tracked.
The care taker performs the operation on the originator but needs to be able to undo operations. 

Applicability: When to use the Memento Pattern: 
- in case of an application whose state needs to be tracked, you need to be able to track the state of an object or your application and restire previous states as 

needed. 
- You want to abstract and reuse the Undo/Redo functionality
- Follow SRP and Don't repeat yourself
- You do not wish to break encapsulation and expose your classes internal state globally 

How the memento is used: 

- Memento itself holds the state of the originator 
- Ideally ony the originator should have access to the internal details of its state within the Memento
- The caretakers interface to Memento should not allow it to access the internal state of the Originator
- The originator can create Mementos or restore its given state given a Memento
- The care taker maintains the memento objects without operating on their contents. 

Common Usage of Memento is Undo and Redo functionality: 

- Multiple Undo/Redo is often implemented using a stack
- When a change is performed:
- A memento containing the current state is added to the Undo stack
- When an undo operation is performed: 
- the current state is replaced with the state of the memento removed from the Undo stack 
- If Redo is implemented, the current state is stored in a Redo stack.
- When a Redo operation is performed
- The current state is replaced with the state of the memento removed from the Redo stack
- The current state is stored in the Undo stack.

Collaboration: 

- Whenever a change is made from the requested state, A care taker requests a Memento from the Originator
- The caretaker stores one or more Mementos until they are needed. 
- If or when requred the Caretaker passes the Memento back to the originator
- It may be possible that Memento stored by caretaker may not be used if there is no redo or undo functionality 
- Mementos should be value objects, holding state but no behavior. 
- Only the originator which created a memento should be able to assign or retreive its state. 


Model View Presenter Pattern: 
--------------------------------------

Model View View Model Pattern:
--------------------------------------

- a set of guidelines to code for an application
- Where did MVVM come from?
- What is MVVM?
- Components of MVVM ?

History:
- 2004 Martin Fowler - Presentation Model
- Separates a view from it's state and behavior
- Not dependent on specific UI Framework
- 2005 John Gossman unveiled the MVVM pattern
- Tailored for WPF and Silverlight platforms

Intent:
- Separate Concerns
- View
- View's state and Behavior
- Data
- Unit testing and UI testing
- Maintenance
- Extensibility
- Enables designer/developer workflow
- Take advantage of WPF/silverlight databinding --> Also supports input validation

Structure:
- View
- ViewModel
- Model

- Model :
- HAs no reference to the View or ViewModel
- Model can be represented by Domain specific objects
- Model can be represented as Data centric object (model is XML or data access layer)
- Model's purpose is to represent Data points
- ITs single purpose is to represnt datapoint
- View :
- May or Maynot have a reference to the ViewModel
- Doesnot have a reference to the Model
- It consists of only visual elements of display like buttons windowns and everything
- Responsible for showing and collection data to and from user.
- in silver light the data bindings are specified but the details are hidden from the UI.
- Binding the viewModel set by DataContext
- The ViewModel:
- Has a reference to the Model
- May or may not have a reference to the view
- Contains properties and commands  and other abstratctions to make the communication easy between the view and the model.
- At minimum the view should implement the INotifyChanged interface because the ViewModel is bound to notify the view of a change.
- Although the ViewModel contains the state and the data for the UI is should have a UI control as a base object.


To Create the connection between the view and viewModel (Binding the view to ViewModel):
- Declaratively in XAML --> View first approach --> ViewModel as a resource --> Static resource on the View
- Cannot control instantiation
- Cannot pass parameter
- Imperatively in code
- The view model is assigned in the views code behing after the Initialization method
- View Model Locator --> Service Locator renamed for MVVM
- DataTemplates
- Inversion of Control
- Factory with Inversion of Control
- and more ..

Communication:
- Events
- Commands
- Execute
- CanExecute

Consequences
- Pro:
- Reduce Code behind
- Model doesnot need to change to support a view
- Designers design and coders code
- Reduces development time
- Multitargeting and project linking
-Con:
- Create more files
- Simple tasks can be complicated
- Lack of standardization
= Specific to WPF and Silverlight platforms 


Prototype Pattern:
--------------------------------------
- Overview of the Prototype PAttern
- SPecify the kinds of objects to create using a prototypical instance and create new objects by

copying this prototype --> Cloning or Making a copy instead of newing the object up
- Its easier to make a copy of the object than going through the whole construction process this is why

this pattern is used.
- Problem 1: COnstruction cost of an object is expensive
- Problem 2: State is important copy the state.
- Problem 3: Hiding the constructor
- Prototype design --> Just implement a Icloneable Interface and while implementing Clone method return

MemberwiseClone()
- You can do a deep copy and shallow copy --> MemberwiseClone does only shallow copy is specified only at one

level
- Examples are present in javascript, javascript is a prototypical language. --> Structuring Javascript is a

course on pluralsight.