Tuesday, November 29, 2016

Mocking Unit Tests: HttpClient and 2+ parameters

If you have an HTTP Client unit test, you can try the option of making a Wrapper interface in your solution like this here: http://stackoverflow.com/questions/10693955/stubbing-or-mocking-asp-net-web-api-httpclient. As for two parameters in the unit test, you can do the following..

Monday, October 24, 2016

Mocking Unit Tests: Get value out of a mocked method

Let's say you have a Save method, and you are unit testing it, and you want to get the "entity" that is getting passed in as a parameter to use in your test.



You can do this in your unit test:

Monday, August 1, 2016

Simple Calculator with Order of Operations in C#



Here is the Calculator with order of operations for multiplication, division, addition, and subtraction. No parenthesis, exponents, or other things included. This is using the tree method. We check for the operation that would be done last from right to left, and this is the first node of the tree. Keep in mind: "multiplication and division are of equal precedence, as are addition and subtraction." Here is an example of how the tree works:
Source: http://math.hws.edu/eck/cs225/s03/binary_trees/expressionTree.gif

This is the Program.cs file below.



This is some class file, for ex. Calc.cs below:



Monday, July 25, 2016

Simple Budget Calculator in C#



Here's another word problem similar to the calculator with word problem and solution included!

I would like a budget calculator for this month to see how much over or under budget I was last month. The application will prompt me for my total budget for last month when I start the application.

Once I enter my total budget, it will ask me the following:
  • How much did you spend on groceries?
  • How much did you spend eating out?
  • How much did you spend on fuel?
  • How much did you spend on entertainment?
At the end, the application will tell me how much money I either over-spent or under-spent. Make sure it works for both over- and under- spending. For example, the console should look like this:


This is the Program.cs file below.



This is some class file, for ex. BudgetClass.cs below:



Simple Calculator without Order of Operations in C#



I have recently started a new job, and with it I decided to do mentoring for a junior developer program. Because of this, I will be working on puzzles / mini-apps with them and I will be posting my solutions to them here for anyone else to use :). It is easiest for me to guide when I solve the problem beforehand. Below is a C# calculator without order of operations (to keep it simple this is a good starting place). Next will be one with order of operations using the tree method.

This is the Program.cs file below.



This is some class file, for ex. Calculator.cs below:



Thursday, June 9, 2016

If I could change one thing with software...


If I could change one thing with software... I would fix the medical system as much as software could.

I would make it so patients knew ahead of time how much their visit would cost, taking into account the specific doctor's office and their insurance. It shouldn't take months later to be mailed a bill. No one would consider it reasonable to buy groceries and mysteriously get a bill in the mail months later and have no scope of how much it would cost.

I would make a portal that makes it easy to find a good doctor who takes your insurance. The portal would keep track of all your insurance company info and claims. You could find a doctor who has reviews and where you can make appointments online easily without waiting hours on the phone. I'd make one large comprehensive medical form you could fill out once and then it will send to any doctors you need to see so you don't fill out the form 20x for the same issue in different offices.

I would make a universal medical records system that is ported immediately to a central system. If a patient landed in a hospital, their blood type, contraindicated medications, and medical history would be immediately known. It should be able to be looked up by even a finger print to avoid as many John Does.

I would force insurance companies, pharmacies, doctor's offices, hospitals, medical imaging, dentists, and patients to have a synchronized easy to use system where each part communicated with each other.

I would make a company that just buys out the old almost noncollectable debt on the cheap, and ask for donations just to buy and forgive more medical debt. We shouldn't go into financial stress or bankruptcy in order to stay healthy and keep our families healthy. But I need more than just software to make this happen. I need strong belief in this, tons of support, a way to get through politics, laws, and a massive security system to protect everyone's information.

Just a small fun rant :).

Tuesday, May 3, 2016

How do self-taught developers actually get jobs?


I posted again on Quora to give some more insight about how a self-taught developer can get a job and some specifics. Hope this can help someone both with the tips and in believing they can do it! There are some really great answers on stories from other users, check them out! Click to:

See My Response

(Posting a link to the actual post so I can update it as needed in one place!)

Monday, May 2, 2016

Running Web Job on Schedule


To get a Web Job, start by making a Web App. The Web Job is associated with the Web App. You can either actually use the Web App, or just make an empty one as a placeholder for your Web Job. Web Jobs can be used for: continuously running a background task at a certain time interval in the cloud. In order to run a web job on a schedule, you have to include the Web Job NuGet package. You can either setup a normal console application, or setup a "web jobs" console application (which has the Web Job references already added for you along with the JobHostConfiguration code below). You can add the [TimerTrigger] attribute as a parameter into the main function you would like to use. Make sure to put the JobHostConfiguration into the Main method, if you do not then your web job will likely continuously loop and not work.

Sunday, April 3, 2016

C# ASP.NET Web Developer Study Guide



2/7/2017 NOTE: Please see here for updated version of study guide. The same study guide is posted here as a word document and has been expanded by about 3x.

I wanted to compile a list of the technologies and concepts I need and use as a software engineer.  As someone who is self-taught, without any formal education, I wanted a place to put all of the information I need in an organized place.  These are notes from a large variety of places pasted in here, it is literally a study guide from the places I thought could explain a concept the best.  It is pretty lengthy, as a word document it was about 30 pages.

This list is by no means complete. I just wanted to share what I have in case it can help someone out.  This would be useful for people who are reviewing topics to see if they have gaps, for people looking to get into web development and are unsure of the total scope ("go learn C#" isn't very specific, this is a much more detailed outline!).  It never hurts to have more tools in the toolbox to make your applications better or to understand the underlying concepts of what you are doing.

Apologies for blank spots on the "Basics" section (and other random sections), I didn't spend a lot of time completing those because I know these sections well and I wasted to flesh out other sections such as delegates and generics instead.  Document is below, enjoy!!!

--

C# and ASP.NET Study Guide

Basics
     Constructors
     Initialization
     Declaration
o      Var a, String b, Int c, etc.
     Object
     Destructors
o       A destructor runs after a class becomes unreachable. It has the special "~" character in its name. The exact time it is executed is not specified. But it always runs when the class is not reachable in memory by any references.
     Main
     .NET framework
     Everything inherits from?
o      System.Object
     Circular reference?
o      Two or more resources are dependent on each other and this causes a lock condition, therefore making the resources unusable.
     “as” vs “is” operators
o      “as” is for casting object to type or class
o      “is” is for checking object with type and this returns Boolean value
     Loops
o      For
o      Foreach
o      While
o      Do while
o      “continue” and “break”
       “continue” statement is used to pass the control to next iteration. This statement can be used with – “while”, “for”, “foreach” loops.
       “break” statement is used to exit the loop.

Object Oriented Principles
     OOD
     Planning a design around the objects, what they contain, and how they will interact within an application.  Building the methods around the objects based on what those need to do.  Using SOLID principles to keep strong decoupling and very reusable / interchangeable parts.
     Abstraction
o      Finding a common pattern and providing the means to alter this in a reusable way with normal systematic variation
     Encapsulation
o      Hiding implementation that is not needed and showing only the necessary details to the client.
     Inheritance
o      Inheriting from base/parent classes. Specific reusable parts.
     Polymorphism
o      Method overloading and overriding, being able to make methods more resuable.

Accessors
     Public
o      Can be accessed anywhere
     Private
o      Can be accessed within same class
     Protected
o      Only current class or inheriting children classes
     Internal
o      Within the same assembly.
     Protected Internal
o      Can be accessed in same assembly or by child classes inheriting from base class

Classes / Methods / Variables
     Namespaces
o      Containers for classes / grouping related classes, logical boundary for a group of classes.
o      System namespace lives in assembly mscorlib.dll
     Assembly
o      Output until of deployment and used for versioning. Contains the MSIL code.
     Class vs. Struct
o      Structs are value types (Section 11.3.1).
o      All struct types implicitly inherit from the class System.ValueType (Section 11.3.2).
o      Assignment to a variable of a struct type creates a copy of the value being assigned (Section 11.3.3).
o      The default value of a struct is the value produced by setting all value type fields to their default value and all reference type fields to null(Section 11.3.4).
o      Boxing and unboxing operations are used to convert between a struct type and object (Section 11.3.5).
o      The meaning of this is different for structs (Section 11.3.6).
o      Instance field declarations for a struct are not permitted to include variable initializers (Section 11.3.7).
o      A struct is not permitted to declare a parameterless instance constructor (Section 11.3.8).
o      A struct is not permitted to declare a destructor (Section 11.3.9).

 Do not define a structure unless the type has all of the following characteristics:
        It logically represents a single value, similar to primitive types (integer, double, and so on).
        It has an instance size smaller than 16 bytes.
        It is immutable.
        It will not have to be boxed frequently.
     Abstract vs. Interface
o      Interface is more flexible. Can inherit more than one. Cannot contain any implementation, simply a contract.
o      Abstract class is more rigid, can contain implementation, and you can only inherit from one.
Let's take your example of a Dog and a Cat class, and let's illustrate using C#:
Both a dog and a cat are animals, specifically, quadruped mammals (animals are waaay too general). Let us assume that you have an abstract class Mammal, for both of them:
public abstract class Mammal
This base class will probably have default methods such as:
      Feed
      Mate
All of which are behavior that have more or less the same implementation between either species. To define this you will have:
public class Dog : Mammal
public class Cat : Mammal
Now let's suppose there are other mammals, which we will usually see in a zoo:
public class Giraffe : Mammal
public class Rhinoceros : Mammal
public class Hippopotamus : Mammal
This will still be valid because at the core of the functionality Feed() and Mate() will still be the same.
However, giraffes, rhinoceros, and hippos are not exactly animals that you can make pets out of. That's where an interface will be useful:
public interface IPettable
{
    IList<Trick> Tricks{get; set;}
    void Bathe();
    void Train(Trick t);
}
The implementation for the above contract will not be the same between a cat and dog; putting their implementations in an abstract class to inherit will be a bad idea.
Your Dog and Cat definitions should now look like:
public class Dog : Mammal, IPettable
public class Cat : Mammal, IPettable
Theoretically you can override them from a higher base class, but essentially an interface allows you to add on only the things you need into a class without the need for inheritance.
Consequently, because you can usually only inherit from one abstract class (in most statically typed OO languages that is... exceptions include C++) but be able to implement multiple interfaces, it allows you to construct objects in a strictly as required basis.
     Sealed class
o      Cannot be inherited
     Sealed method
o      Cannot be overridden
     Static
o      Static class = all members are also made static
o      Static variable will have single instance
     Partial classes
o      Split business logic into multiple files with same class name + “partial”
     Void
o      Will not return any value
     Constant variable
o      Making an entity constant. We cannot modify the value later in the code. Value assigning is mandatory to constant variables.
     Readonly variable
o      Can be changed during runtime and value to readonly variables can be assigned in the constructor or at the time of declaration.
     Ref parameter
o      Passed into a method and does not need to be initalized
     Out parameter
o      Needs to be initialized before used
     “This” refers to the current instantiated class
o      Cannot be used in a static class since static classes aren’t instantiated
     Async and Await
o      Makes it possible for the method to run on another thread (multithreading).  Prevents the main thread from getting blocked/slowed down by starting another thread if needed to run function on. Returns a Task<T> (object that represents an asynchorous operation).  Async goes on method signature. Await is in the method somewhere, where you need to use it. 
     Virtual
o      The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class. For example, this method can be overridden by any class that inherits it:
public virtual double Area()
{
    return x * y;
}
     Override
o      The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.
     Recursion
      
      


Types
     Reference Types
o      String, Class, Interface, Object, Delegate
o      All arrays, even if their elements are value types
o      Stored on the Heap (“r is closer to h in alphabet”)
     Value Types
o      All the numbers (int, decimal, double, long, float) AND enum AND byte. “A number is a VALUE.”
o      Stored on the Stack
     Boxing / Unboxing
o      Boxing: converting from value type to reference type
     “You can put an “object” in a box, an object is a reference type. Boxing = changing to reference type”
o      Unboxing: converting reference type to value type
     Primitive Types
o      PrimitiveTypeName ::= NumericTypeName | Boolean | Date | Char | String
NumericTypeName ::= IntegralTypeName | FloatingPointTypeName | Decimal
IntegralTypeName ::= Byte | Short | Integer | Long
FloatingPointTypeName ::= Single | Double
     Strings vs. Stringbuilder / Immutable
o      Strings are immutable, another copy of it is created every time (means a new object in memory is made each time)
o      StringBuilder is a mutable string of characters and this class cannot be inherited. Allows Insert, Remove, Append, and Replace. Can use ToString() method for final string from string builder.
     Array
o      Stores values of the same data type and the length must be defined
     Jagged Array
o      An array of arrays
     ArrayList
o      Can store values of different data types, and length does not have to be defined
     System.Array.Clone() vs System.Array.CopyTo()
o      CopyTo copies elements of one array to another. Clone creates a new array with all the elements that were in the first array.
     Hashset
o      **USE when you want to find duplicates. When you add to the hashset, a Boolean is returned true/false for if there is a duplicate.
o      Faster than lists and dictionaries to use key to get value.
o      Do not get to pick your key. All keys are distinct from one another.
     Key and value. Key is a hash based off value. Object.GetHashCode will get the hash based off a value, and run it through an algorithm. 
o      If object A = object b, hash of A = hash of object B
     Dictionaries
     Hashtable
o      It is an older .NET Framework type. Old slow version of Dictionary.  
                 

     Collections
     http://www.claudiobernasconi.ch/2013/07/22/when-to-use-ienumerable-icollection-ilist-and-list/
     Enumerables
     IEnumerable
     What inherits from this? When should you return this type?
     IQueryable
     Inherits from IEnumerable.
     Enum
o      Named constants / enumerator lists/ value types that cannot be inherited.
     Generics
o      System.Collections.Generic
o      Generics introduce <T> type parameters, which make it possible to design classes/methods that defer the specification of one or more types until the class or method is declared and instantiated. For example, by using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations.
o      The most common use of generics is to create collection classes.
o      Use generic types to maximize code reuse, type safety, and performance. You can create your own generic interfaces, classes, methods, events and delegates. May be constrained to enable access to methods on particular data types.  Information on the types that are used in a generic data type may be obtained at run-time by using reflection.
o     
     Delegate (known as function pointer in C/C++)
o      A delegate is a class that can hold a reference to a method. Unlike other classes, a delegate class has a signature, and it can hold references only to methods that match its signature. A delegate is basically a type-safe function pointer or callback in C# (pointer in in C/C++ is not type safe).  
o      Can be used for to handle call/invoke multiple methods on one event, can define async methods, decouple and implement generic behaviors, invoke methods at runtime, can used in LINQ expression tree, can be used in many design patterns.
o      Types of delegates
       Single Delegate
     Can be used to invoke a single method
       Multicast Delegate
     Can be used to invoke multiple methods
     Multiple objects can be assigned to one delegate instance by using the + operator.  The multicast delegate contains a list of the assigned delegates. When the multicast delegate is called, it invokes the delegates in the list, in order. Only delegates of the same kind can be combined. The - operator can be used to remove a component delegate from a multicast delegate.
                                                 
       Generic Delegate – not required to define delegate instance in order to invoke these methods
     Func
o      Method that can be called on arguments and returns a result.
o      The Func delegate defines a method that can be called on arguments and returns a result. In the given code example, delegate Func<interest,double> is defined with Interest type as argument and double as return type.
     Action
o      The Action delegate defines a method that can be called on arguments but does not return a result. In the given code example, delegate Action<string> is defined with string as argument.
     Predicate
o      The Predicate delegate defines a method that can be called on arguments and always returns Boolean type result. In the given code example, delegate Predicate<string> checkValidDate is defined with stringtype as argument and returns bool type.
     Events vs. Delegates
o      An Event declaration adds a layer of abstraction and protection on the delegate instance. This protection prevents clients of the delegate from resetting the delegate and its invocation list and only allows adding or removing targets from the invocation list.
o      Delegates are, conceptually, function templates; that is, they express a contract a function must adhere to in order to be considered of the "type" of the delegate.
o      Events represent ... well, events. They are intended to alert someone when something happens and yes, they adhere to a delegate definition but they're not the same thing.
     Events
o      An event is a message sent by an object to signal the occurrence of an action. The action could be caused by user interaction, such as a mouse click, or it could be triggered by some other program logic. The object that raises the event is called the event sender. The object that captures the event and responds to it is called the event receiver.
o      In event communication, the event sender class does not know which object or method will receive (handle) the events it raises. What is needed is an intermediary (or pointer-like mechanism) between the source and the receiver. The .NET Framework defines a special type (Delegate) that provides the functionality of a function pointer.
     Casting
     Tuple
o      A tuple is a data structure that has a specific number and sequence of elements. An example of a tuple is a data structure with three elements (known as a 3-tuple or triple) that is used to store an identifier such as a person's name in the first element, a year in the second element, and the person's income for that year in the third element. The .NET Framework directly supports tuples with one to seven elements. In addition, you can create tuples of eight or more elements by nesting tuple objects in the Rest property of a Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> object.
o      Uses
       To provide easy access to, and manipulation of, a data set.
       To pass multiple values to a method through a single parameter. For example, the Thread.Start(Object) method has a single parameter that lets you supply one value to the method that the thread executes at startup time. If you supply a Tuple<T1, T2, T3> object as the method argument, you can supply the thread’s startup routine with three items of data.
     Attributes
o      Attributes are used to convey the info for runtime about the behavior of elements like – “methods”, “classes”, “enums” etc.
o      Attributes can be used to add metadata like – comments, classes, compiler instruction etc.
     Method Overloading
     Method Overriding
     Anonymous Type
o      Var myTestCategory = new { CategoryId = 1, CategoryName = “Category1”};
     Copy Constructor
o      If the constructor contains the same class in the constructor parameter then it is called as copy constructor.


Services
     RESTful Web API (Representational State Transfer)
o       Representation = how the resources get manipulated.  Resource state is transferred between client and server. Usually JSON or XML.   *Resource based.
       Resource: person (Bob)
       Service: contact info (GET)
       Representation: JSON of name, address, phone, number
o      Nouns: ex. Person, user, or address resource
o      Verbs: GET, POST, PUT, DELETE
o      POST vs PUT
       Do you name your URL objects you create explicitly, or let the server decide? If you name them then use PUT. If you let the server decide then use POST.
       PUT is idempotent, so if you PUT an object twice, it has no effect. This is a nice property, so I would use PUT when possible.
       You can update or create a resource with PUT with the same object URL
       With POST you can have 2 requests coming in at the same time making modifications to a URL, and they may update different parts of the object.
o      OPTIONS tells you things such as "What methods are allowed for this resource".
o      The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response.
     SOAP (Simple Object Access Protocol)
o      When data is sent over the Internet, each unit transmitted includes both header information and the actual data being sent. The header identifies the source and destination of the packet, while the actual data is referred to as the payload. In general, payload is the data that is carried on behalf of an application and the data received by the destination system.
o      So I am trying to say that, sending data over the network in Json format is cheaper than sending it in Xml format in terms of payload.
o      Here is the first benefit or advantages of REST over SOAP. SOAP only support XML, but REST supports different format like text, JSON, XML etc. And we already know, if we use Json then definitely we will be in better place in terms of payload.
o      Now, SOAP supports only XML, but it also has its own advantages.
o      Really! How?
o      SOAP relies on XML in three ways Envelope – that defines what is in the message and how to process it.
o      A set of encoding rules for data types, and finally the layout of the procedure calls and responses gathered.
o      This envelope is sent via a transport (HTTP/HTTPS), and an RPC (Remote Procedure Call) is executed and the envelope is returned with information in a XML formatted document.
o      Here important point is that one of the advantages of SOAP is the use of the “generic” transportbut REST uses HTTP/HTTPS. SOAP can use almost any transport to send the request but REST cannot. So here we got an advantage of using SOAP.
o      As I already mentioned in above paragraph “REST uses HTTP/HTTPS”, so go bit deeper on these words.
o      When we are talking about REST over HTTP, all security measures applied HTTP are inherited and this is known as transport level security and it secures messages only while it is inside the wirebut once you delivered it on the other side you don’t really know how many stages it will have to go through before reaching the real point where the data will be processed. And of course all those stages could use something different than HTTP.So Rest is not safer completely, right?
o      But SOAP supports SSL just like REST additionally it also supports WS-Security which adds some enterprise security features. WS-Security offers protection from the creation of the message to it’s consumption. So for transport level security whatever loophole we found that can be prevented using WS-Security.
o      Apart from that, as REST is limited by it's HTTP protocol so it’s transaction support is neither ACID compliant nor can provide two phase commit across distributed transnational resources.
o      But SOAP has comprehensive support for both ACID based transaction management for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources.  I am not drawing any conclusion, but I will definitely prefer SOAP based web service while security, transaction etc are the main concerns.
       In computer science, ACID (Atomicity, Consistency, Isolation, Durability) is a set of properties that guarantee that database transactions are processed reliably. In the context of databases, a single logical operation on the data is called a transaction
     WCF

Design patterns
     MVC
o      MVC is a software architecture - the structure of the system - that separates domain/application/business (whatever you prefer) logic from the rest of the user interface. It does this by separating the application into three parts: the model, the view, and the controller.
o      Controllers process incoming requests, handle user input and interactions, and execute appropriate application logic. Acontroller class typically calls a separate view component to generate the HTML markup for the request.
o      The model manages fundamental behaviors and data of the application. It can respond to requests for information, respond to instructions to change the state of its information, and even to notify observers in event-driven systems when information changes. This could be a database, or any number of data structures or storage systems. In short, it is the data and data-management of the application.
o      The view effectively provides the user interface element of the application. It'll render data from the model into a form that is suitable for the user interface.
o      The controller receives user input and makes calls to model objects and the view to perform appropriate actions.
o      Return more than one view per controller?
o      Not normally, one ActionResult = one view. But you can make a new ActionREsult class and edit it to return more partials. http://www.codeproject.com/Tips/712187/Returning-More-Views-in-an-ASP-NET-MVC-Action
o      Advantage over web forms?
       Unit testable.
o      What can you return?
       ActionResult, anything else etc.
o      ActionResult?
    
o      Can you have more than one controller per view?
       No? You can only return one thing per method.
     MVVM
o      Model is a set of classes representing the data coming from the services or the database.
o      View is the code corresponding to the visual representation of the data the way it is seen and interacted with by the user.

o      ViewModel serves as the glue between the View and the Model. It wraps the data from the Model and makes it friendly for being presented and modified by the view. ViewModel also controls the View's interactions with the rest of the application (including any other Views).
Unit Testing
     From my experience, 2 principles from SOLID play major role in designing testable code:
o      Interface segregation principle - you should prefer many, client-specific interfaces instead of fewer, general-purpose ones. This goes in pair with Single Responsibility Principle and helps you design feature/task-oriented classes, which in return are much easier to test (as compared to the more general ones, or often abused "managers" and "contexts") - less dependencies, less complexity, more fine-grained, obvious tests. In short, small components lead to simple tests.
o      Dependency inversion principle - design by contract, not by implementation. This will benefit you the most when testing complex objects and realizing you don't need whole graph of dependencies just to set it up, but you can simply mock the interface and be done with it.
     Types of Unit Tests
o      Positive – giving the system valid data
o      Negative – giving the system invalid data
o      Exception – hitting the exception statements

Gang of Four
Creational Patterns
The first type of design pattern is the creational pattern. Creational patterns provide ways to instantiate single objects or groups of related objects. There are five such patterns:
o      Abstract Factory. The abstract factory pattern is used to provide a client with a set of related or dependent objects. The "family" of objects created by the factory are determined at run-time.
o      Builder. The builder pattern is used to create complex objects with constituent parts that must be created in the same order or using a specific algorithm. An external class controls the construction algorithm.
o      Factory Method. The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.
o      Prototype. The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone. This practice is particularly useful when the construction of a new object is inefficient.
o      Singleton. The singleton pattern ensures that only one object of a particular class is ever created. All further references to objects of the singleton class refer to the same underlying instance.
Structural Patterns
The second type of design pattern is the structural pattern. Structural patterns provide a manner to define relationships between classes or objects.
o      Adapter. The adapter pattern is used to provide a link between two otherwise incompatible types by wrapping the "adaptee" with a class that supports the interface required by the client.
o      Bridge. The bridge pattern is used to separate the abstract elements of a class from the implementation details, providing the means to replace the implementation details without modifying the abstraction.
o      Composite. The composite pattern is used to create hierarchical, recursive tree structures of related objects where any element of the structure may be accessed and utilized in a standard manner.
o      Decorator. The decorator pattern is used to extend or alter the functionality of objects at run-time by wrapping them in an object of a decorator class. This provides a flexible alternative to using inheritance to modify behavior.
o      Facade. The facade pattern is used to define a simplified interface to a more complex subsystem.
o      Flyweight. The flyweight pattern is used to reduce the memory and resource usage for complex models containing many hundreds, thousands or hundreds of thousands of similar objects.
o      Proxy. The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. The proxy provides the same public interface as the underlying subject class, adding a level of indirection by accepting requests from a client object and passing these to the real subject object as necessary.
Behavioural Patterns
The final type of design pattern is the behavioural pattern. Behavioural patterns define manners of communication between classes and objects.
o      Chain of Responsibility. The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler.
o      Command. The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use.
o      Interpreter. The interpreter pattern is used to define the grammar for instructions that form part of a language or notation, whilst allowing the grammar to be easily extended.
o      Iterator. The iterator pattern is used to provide a standard interface for traversing a collection of items in an aggregate object without the need to understand its underlying structure.
o      Mediator. The mediator pattern is used to reduce coupling between classes that communicate with each other. Instead of classes communicating directly, and thus requiring knowledge of their implementation, the classes send messages via a mediator object.
o      Memento. The memento pattern is used to capture the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation.
o      Observer. The observer pattern is used to allow an object to publish changes to its state. Other objects subscribe to be immediately notified of any changes.
o      State. The state pattern is used to alter the behaviour of an object as its internal state changes. The pattern allows the class for an object to apparently change at run-time.
o      Strategy. The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time.
o      Template Method. The template method pattern is used to define the basic steps of an algorithm and allow the implementation of the individual steps to be changed.
o      Visitor. The visitor pattern is used to separate a relatively complex set of structured data classes from the functionality that may be performed upon the data that they hold.

SOLID

              
CQRS
Use in some rare cases, and not in the whole app. Builds on domain driven driven and bounded context. Can use in insurance policy management.   Like any pattern, CQRS is useful in some places, but not in others. Many systems do fit a CRUD mental model, and so should be done in that style. CQRS is a significant mental leap for all concerned, so shouldn't be tackled unless the benefit is worth the jump. While I have come across successful uses of CQRS, so far the majority of cases I've run into have not been so good, with CQRS seen as a significant force for getting a software system into serious difficulties.

In particular CQRS should only be used on specific portions of a system (a BoundedContext in DDD lingo) and not the system as a whole. In this way of thinking, each Bounded Context needs its own decisions on how it should be modeled.  
1.       Difficult business logic CQRS forces you to not mix domain logic and infrastructural operations.
2.       Scalability matters With CQRS you can achieve great read and write performance. Command handling can be scaled out on multiple nodes. And as queries are read only operations they can be optimized to do fast read operations.
From my point of view it adds two major benefits.(Among with a lot of others)
3.       Extreme scaling ability
4.       Very useful when it come to distibuted teams.



SignalR
ASP.NET SignalR is a library for ASP.NET developers to add real-time web functionality to their applications. Real-time web functionality is the ability to have server-side code push content to the connected clients as it happens, in real-time.[1]
SignalR takes advantage of several transports, automatically selecting the best available transport given the client's and server's best available transport. SignalR takes advantage of WebSocket (a single TCP connection), an HTML5 API that enables bi-directional communication between the browser and server. SignalR will use WebSockets under the covers when it's available, and gracefully fall back to other techniques and technologies when it isn't, while the application code remains the same
http://kevgriffin.com/why-should-asp-net-developers-consider-signalr-for-all-projects/

Use for chat messages, game, anything with quick need to ping in info

Getting Data
     Entity Framework
o       
     ORM
     ADO.NET
     LINQ
     LINQ to SQL
     Entity Framework vs LINQ to SQL
o     LINQ to SQL is the quick-and-easy way to do it. This means you will get going quicker, and deliver quicker if you are working on something smaller.
o     Entity Framework is the all-out, no-holds-barred way to do it. This means you will take more time up-front, develop slower, and have more flexibility if you are working on something larger.
     Code First
     POCOs
     Using statement
o      Calls the Dispose method internally (ensures correct use of IDisposable objects / even if exception is thrown while calling methods on the object, Dispose is still called). 
o      Specifies scope of useage of resource.
o      Can use to open DB connection:
       using (SqlConnection con = new SqlConnection(connectionString))
     DbContext and DbSet
o      Intuitively, a DbContext corresponds to your database (or a collection of tables and views in your database) whereas a DbSet corresponds to a table or view in your database. So it makes perfect sense that you will get a combination of both!
o       You will be using a DbContext object to get access to your tables and views (which will be represented by DbSet's) and you will be using your DbSet's to get access, create, update, delete and modify your table data.


Compiler / Memory / Stuff
     Managed code
o      C# code is managed code because the compiler – CLR will compile the code to Intermediate Language.
     C# compiler
o      CSC (“C Sharp Compiler”).
     Thread
o      Execution path of a program. Each thread defines a unique flow of control.
o      The first thread to be executed in a process is called the main thread.
o      When a C# program starts execution, the main thread is automatically created. The threads created using the Thread class are called the child threads of the main thread. You can access a thread using the CurrentThread property of the Thread class.
o      4 states of a thread
       The Unstarted State: It is the situation when the instance of the thread is created but the Start method is not called.
       The Ready State: It is the situation when the thread is ready to run and waiting CPU cycle.
       The Not Runnable State: A thread is not executable, when:
     Sleep method has been called
     Wait method has been called
     Blocked by I/O operations
       The Dead State: It is the situation when the thread completes execution or is aborted.
     Multithreading
o      The lock statement will make sure one thread will not intercept the other thread which is running the part of code. So lock statement will make the thread wait, block till the object is being released.
     Heap vs. Stack
public void Method1()
{
    // Line 1
    int i=4;

    // Line 2
    int y=2;

    //Line 3
    class1 cls1 = new class1();
}
It’s a three line code, let’s understand line by line how things execute internally.
      Line 1: When this line is executed, the compiler allocates a small amount of memory in the stack. The stack is responsible for keeping track of the running memory needed in your application.
      Line 2: Now the execution moves to the next step. As the name says stack, it stacks this memory allocation on top of the first memory allocation. You can think about stack as a series of compartments or boxes put on top of each other.
Memory allocation and de-allocation is done using LIFO (Last In First Out) logic. In other words memory is allocated and de-allocated at only one end of the memory, i.e., top of the stack.
      Line 3: In line 3, we have created an object. When this line is executed it creates a pointer on the stack and the actual object is stored in a different type of memory location called ‘Heap’. ‘Heap’ does not track running memory, it’s just a pile of objects which can be reached at any moment of time. Heap is used for dynamic memory allocation.
One more important point to note here is reference pointers are allocated on stack. The statement, Class1 cls1; does not allocate memory for an instance of Class1, it only allocates a stack variable cls1 (and sets it tonull). The time it hits the new keyword, it allocates on "heap".
Exiting the method (the fun): Now finally the execution control starts exiting the method. When it passes the end control, it clears all the memory variables which are assigned on stack. In other words all variables which are related to int data type are de-allocated in ‘LIFO’ fashion from the stack.
The big catch – It did not de-allocate the heap memory. This memory will be later de-allocated by the garbage collector.
Now many of our developer friends must be wondering why two types of memory, can’t we just allocate everything on just one memory type and we are done?
If you look closely, primitive data types are not complex, they hold single values like ‘int i = 0’. Object data types are complex, they reference other objects or other primitive data types. In other words, they hold reference to other multiple values and each one of them must be stored in memory. Object types need dynamic memory while primitive ones needs static type memory. If the requirement is of dynamic memory, it’s allocated on the heap or else it goes on a stack.
 

     Object pool
o      Object pool is used to track the objects which are being used in the code. So object pool reduces the object creation overhead.
     Resource loading
o      Eager loading
o      Lazy loading
     CTS
o      The Common Type System (CTS) standardizes the data types of all programming languages using .NET under the umbrella of .NET to a common data type for easy and smooth communication among these .NET languages.
     CLS
o      Common Language System. One of the important goals of .NET Framework is to support Multiple Languages. This is achieved by CLS. For multiple languages to interoperate, it is necessary that they should go on in common in certain features such as Types that are used. For example, every language has its own size and range for different data types. Thus CLS is the agreement among language designers and class library designers concerning these usage conventions.
     Assemblies
o      Naming:
       Strong names: While using shared assemblies, in order to avoid name collisions strong names are used. Strong Names are based on private key cryptography, ie. private assemblies are simply given the same name as their main file name.
     GAC (Global Assembly Cache)
o      Memory that is used to store the assemblies that are meant to be used by various applications.
o      Every computer that has CLR installed must have a GAC. GAC is a location that can be seen at “C:\Windows\assembly” for .Net applications with frameworks up to 3.5. For higher frameworks like 4 and 4.5 the GAC can be seen at: “C:\Windows\Microsoft.NET\assembly\GAC_MSIL”
o      To install assembly in Cache, use  Gacutil. To run Gacutil, goto "Visual Studio Command Prompt" and type "gacutil -i <assembly_name>", where (assembly_name) is the DLL name of the project. To uninstall assembly, type gacutil –u <assembly name> in  Visual Studio Command Prompt.

     CLR
o      The CLR stands for Common Language Runtime and it is an Execution Environment.
o      The main function of Common Language Runtime (CLR) is to convert the Managed Code into native code and then execute the program. The Managed Code compiled only when it is needed, that is it converts the appropriate instructions when each function is called. The Common Language Runtime (CLR)’s just in time (JIT) compilation converts Intermediate Language (MSIL) to native code on demand at application run time.
     MSIL
o      When a program is complied in .Net, the source code will be converted into an intermediate language called Microsoft Intermediate Language (MS-IL) by Just-In time Compiler (JIT). The dot net framework is built in such a way that the code is Just-In time complied, which means that it get complied when it is called rather than at the start up. A portion of the code will get complied only once and it will exist till the application exit. This will have a significant improvement in performance since the entire section of the code won't get executed in most cases.
o      When we compile our .NET code then it is not directly converted to native/binary code; it is first converted into intermediate code known as MSIL code which is then interpreted by the CLR. MSIL is independent of hardware and the operating system. Cross language relationships are possible since MSIL is the same for all .NET languages. MSIL is further converted into native code.
     JIT
o      3 types of JIT:
       Pre-JIT -  Complies complete source code into native code at the time of deployment.
       Econo-JIT - Complies methods that are called at runtime.
       Normal-JIT - Complies methods that are called at runtime and get stored in cache. Next time when the same method is called, it will be taken from cache.
     Garbage Collector
o      Garbage Collector is used in dot net Framework for memory management. While running an application, applications make a request for memory for its internal use. Framework allocates memory from the heap. Once the process is completed, allocated memory needs to be reclaimed for future use. The process of reclaiming unused memory is taken care by the Garbage Collector.
o      It is not recommended to call gc explicitly, but if you call
GC.Collect();
GC.WaitForPendingFinalizers();
       it will call GC explicitly throughout your code, don't forget to call GC.WaitForPendingFinalizers(); after GC.Collect().Dispose.  simply blocks until all objects in the finalisation queue have been finalised (objects which might have been put there by your previous call to Collect). If you want a chance for those objects to be collected then you need another call to Collect after calling WaitForPendingFinalizers.
o      Uses interface IDisposable and frees up both managed and unmanaged code (ex database connection, files, etc.)
     Finalize
o      Called internally by the garbage collector and cannot be called from the code.
     Reflection
o      Reflection is used to dynamically load a class, create object and invoke methods at runtime. It can also be used to read its own meta data to find assemblies, modules and type information at runtime.
     Exceptions
o      Try/catch block
o      Throw preserves original stack trace info
o      Throw ex resets the stack trace (so your errors would appear to originate from HandleException)
o      Inner exception

       An inner exception is the exception that caused the current exception.
       It is used in cases when you want to surface a different exception than the one that your code caught but you don't want to throw away the original context.
       In order for a new exception to have information about a previous one, like you said, you pass it as constructor parameter to the new one.
       Usually, a null inner exception means that the current exception is root cause of the exceptional situation.
       Types of exceptions
     NullReferenceException
     ArgumentNullException
     DivideByZeroException
     IndexOutOfRangeException
     InvalidOperationException
     StackOverflowException etc.
o      Only one catch block can be executed
o      Finally block will always be executed no matter what. Use this if you want to close a connection to DB / release file handlers / etc.
       Can have an error in finally block.
     Compile Time vs Run Time and their Errors
o      The kind of code suitable for reasoning by human beings (let's call it "source code") needs to pass through several stages of translation before it can be physically executed by the underlying hardware (such as CPU or GPU):
o      Source code.
o      [Optionally] intermediate code (such as .NET MSIL or Java bytecode).
o      Machine code conformant to the target instruction set architecture.
o      The microcode that actually flips the logical gates in silicon.
o      These translations can be done in various phases of the program's "lifecycle". For example, a particular programming language or tool might choose to translate from 1 to 2 when the developer "builds" the program and translate from 2 to 3 when the user "runs" it (which is typically done by a piece of software called "virtual machine"1 that needs to be pre-installed on user's computer). This scenario is typical for "managed" languages such as C# and Java.
o      Or it could translate from 1 to 3 directly at build time, as common for "native" languages such as C and C++.
o      The translation between 3 and 4 is almost always done by the underlying hardware. It's technically a part of the "run time" but is typically abstracted away and largely invisible to the developer.
o      The term "compile time" typically denotes the translation from 1 to 2 (or 3). There are certain checks that can be done at compile time before the program is actually run, such as making sure the types of arguments passed to a method match the declared types of method parameters (assuming the language is "strongly typed"). The earlier the error is caught, the easier it is to fix, but this has to be balanced with the flexibility, which is why some "scripting" languages lack comprehensive compile-time checks.
o      The term "run-time" typically denotes the translation from 2 (or 3) all the way down to 4. It is even possible to translate directly from 1 at run-time, as done by so called "interpreted languages".
o      There are certain kinds of problems that can't be caught at compile time, and you'll have to use appropriate debugging techniques (such debuggers, logging, profilers etc...) to identify them at run-time. The typical example of a run-time error is when you try to access an element of a collection that is not there, which could then manifest at run-time as an exception and is a consequence of the flow of execution too complex for the compiler to "predict" at compile time.
o      The "debug time" is simply a run-time while the debugger is attached to the running program (or you are monitoring the debug log etc.).
Database
     SQL Queries
     Normal Form
1st NF – no duplicate rows, have primary key
2nd NF- no partial dependency of any column on primary key.  Plus stuff from 1NF.
3rd NF – All nonprimary fields are dependent on the primary key. All stuff from 2nd NF.
     Indexes
o      With a clustered index the rows are stored physically on the disk in the same order as the index. There can therefore be only one clustered index.
o      With a non clustered index there is a second list that has pointers to the physical rows. You can have many non clustered indexes, although each new index will increase the time it takes to write new records.
o      It is generally faster to read from a clustered index if you want to get back all the columns. You do not have to go first to the index and then to the table.
o      Writing to a table with a clustered index can be slower, if there is a need to rearrange the data.
o      When to use clustered index:
       It's the most replicated data structure in your SQL Server database. The clustering key will be part of each and every non-clustered index on your table, too.
       You should use extreme care when picking a clustering key - it should be:
       narrow (4 bytes ideal)
       unique (it's the "row pointer" after all. If you don't make it unique SQL Server will do it for you in the background, costing you a couple of bytes for each entry times the number of rows and the number of nonclustered indices you have - this can be very costly!)
       static (never change - if possible)
       ideally ever-increasing so you won't end up with horrible index fragmentation (a GUID is the total opposite of a good clustering key - for that particular reason)
       it should be non-nullable and ideally also fixed width - a varchar(250) makes a very poor clustering key

     Triggers
     Joins
     Unions
o      The SQL UNION clause/operator is used to combine the results of two or more SELECT statements without returning any duplicate rows.
o      To use UNION, each SELECT must have the same number of columns selected, the same number of column expressions, the same data type, and have them in the same order, but they do not have to be the same length.
     “Having” Clause
o      The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions. 
       HAVING is used to check conditions after the aggregation takes place.
       WHERE is used before the aggregation takes place.
o      Aggregate functions: Count(), Sum(), avg(), Min(), Max()


Web   SPAs

Decrease load time and/or weight

Single page applications are more capable of decreasing load time of pages and the amount of data transfer from server to client.
Some of the most heavily impacting features of this method include :
·         storing any global functionality once it is loaded the first time,
·         allowing easier data transfer between pages and a more complex user interface
·         removing the cost of loading a whole page after a postback when you only need specific components
o    

Services over page handling

In my opinion using services is pretty much a requirement for organized and modulated code in a website. The standard get and post methods used in backwards compatible website can also use these services to hit services representing business objects instead of pages.This allows your code to be more generalized across modules concerning the same objects.

My list of best practices

As for best practices.. there are quite a few optimizations that could and should be made to a design intending to use this method, such as :
·         storing information as it comes, obliterating when no longer relevant
·         loading in script, html and js files through ajax only when needed
·         using data loaded on one page in another if it can be instead of reloading for each new "page"
·         minimalist data structure for the UI since it is a means for displaying and not for processing.
·         don't obsess with validation on the UI because your services should already be built to validate any information submitted to it


Angular JS
·         AngularJS extends HTML by providing directives that add functionality to your markup and allow you to create powerful dynamic templates. You can also create your own directives, crafting reusable components that fill your needs and abstracting away all the DOM manipulation logic.
·         It also implements two-way data binding, connecting your HTML (views) to your JavaScript objects (models) seamlessly. In simple terms, this means that any update on your model will be immediately reflected in your view without the need for any DOM manipulation or event handling (e.g., with jQuery).
·         A module is a collection of services, directives, controllers, filters, and configuration information. angular.module is used to configure the $injector.
·         Inject 2 modules into one app
o   You can create a top level module that will have your two modules as injected dependencies:
var app = angular.module('app', ['phonecat', 'computer']);
and then in your html use:ng-app="app"
o    
·         Unit testing – Jasmine & Karma

Performance
        Big O notation
        O(1) takes the same amount of time to do function no matter what, for ex a whole array is manipuilated.
        O(n) amount of time is proportional to amount of items
        https://www.interviewcake.com/article/java/big-o-notation-time-and-space-complexity
        Algorithms basics
        Increasing performance of databses

JavaScript

NoSQL

Coding How To’s:
     How to sort array elements in descending order?
       .Sort() method, then .Reverse() method on array
     Fizz Buzz?
     How to make a linked list

Miscellaneous
     Project you have worked on
       Translator app / make flash cards
     Project you would make with endless resources
       Healthcare synced app with insurance / doctors / universal healthcare
     Open source projects you are aware of
     Tech article you have read about recently
     Tech news / blog you follow



Projects
     Angular JS with MVC project with shopping cart with Entity Framework DB call
     MVC project with registrations / login with LINQ to SQL DB call
     REST API call
     Email client
     Calculator
     Input/Output reading files and writing to them
     Code First SQL – create DB from framework