Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

OOP.

Object-Oriented Programming.
Object-oriented programming is a programming paradigm based on the concept of "objects", which may contain data, in the
form of fields, often known as attributes; and code, in the form of procedures, often known as methods. A feature of objects is
that an object's procedures can access and often modify the data fields of the object with which they are associated.
The most popular OOP languages are class-based, meaning that objects are instances of classes, which typically also determine
their type.
Features: Polymorphism, Encapsulation and Inheritance.
Polymorphism.
It is the provision of a single interface to entities of different types.
Static Polymorphism. The response to a function is determined at the compile time (Function Overloading).
Dynamic Polymorphism. C# allows you to create abstract classes that are used to provide partial class implementation of an
interface. Implementation is completed when a derived class inherits from it.

Value Types and Reference Types.


Value Type: A data type is a value type if it holds the data within its own memory allocation.
Reference Type: A reference type contains a pointer to another memory location that holds the data.
Structs vs. classes.
Classes Only: support inheritance, are reference (pointer) types, the reference can be null.
Structs Only: cannot support inheritance, are value types, are passed by value (like integers), cannot have a null reference
(unless Nullable is used).
Both Classes and Structs: can contain methods and events, can support interfaces.
Delegates.
Are similar to pointers to functions. A delegate is a reference type variable that holds the reference to a method. The reference
can be changed at runtime.

SOLID principles.
5 principles.
Single of Responsibility: It states that every object should have a single responsibility, and that responsibility should be entirely
encapsulated by the class.
There should never be more than one reason for a class to change. Robert C. Uncle Bob Martin.
Open / Closed: states that software entities (classes, modules, functions, etc.) should be open for extension, but closed for
modification.
Liskov Substitution Principle: states that Subtypes must be substitutable for their base types.
Substitutability Child classes must not: remove base class behavior and violate base class invariants.
Example.
In mathematics, a Square is a Rectangle. Indeed it is a specialization of a rectangle. The "is a" makes you want to model this
with inheritance. However if in code you made Square derive from Rectangle, then a Square should be usable anywhere you
expect a Rectangle. This makes for some strange behavior.
Imagine you had SetWidth and SetHeight methods on your Rectangle base class; this seems perfectly logical. However if your
Rectangle reference pointed to a Square, then SetWidth and SetHeight doesn't make sense because setting one would change
the other to match it. In this case Square fails the Liskov Substitution Test with Rectangle and the abstraction of having Square
inherit from Rectangle is a bad one.
Interface Segregation: states that clients should not be forced to depend on methods they do not use.

Dependency Inversion: High-level modules should not depend on low-level modules. Both should depend on abstractions.
Abstractions should not depend on details. Details should depend on abstractions.
The separation of all layers into their own package encourages re-utilization of any layer, providing robustness and mobility.

Explain concept of IoC.


http://martinfowler.com/bliki/InversionOfControl.html
Inversion of Control is a design principle where a program receives the flow of control from a framework. If you apply this
principle you inverts control compare with a traditional procedure programming. For example, when you create a framework
and this framework has events that client subscribes them you are using Inversion of Control. Another example is the Template
Method design pattern.
Martin Fowler represents Inversion of Control with this phrase: don't call us, well call you.
Dont confuse Inversion of Control with Inversion of Control Container (IoC Container) such as Unity. This framework is a
specific style of inversion of control (dependency injection). An IoC container constructs your objects for you, which inverts
the usual flow of control.
Explain Unity or other DI framework.
Unity is a dependency injection container that you can use to make a loose couple application.
You have to use it when you want to instantiate classes that are located in other layers or when you are implementing unit
testing in your project.
What is a DTO?
A data transfer object (DTO) is an object that carries data between processes. The difference between data transfer objects and
business objects or data access objects is that a DTO does not have any behavior except for storage and retrieval of its own
data.

MICROSERVICES.
Microservices.
Architecture pattern where the application is divided into a set of collaborating services. Each service is in charge of an specific
functionality. They communicate synchronously or asynchronously. They are independent of each other (own database). If is is
necessary they could have a mechanism for maintain the consistency between different services using database replication or
application-level events..
Martin Fowler says he likes to think SOA to be a superset of microservices.
https://www.youtube.com/watch?v=wgdBVIX9ifA&feature=youtu.be&t=13m10s
SOA vs Microservice.

SOA (monolith) - easy to develop, easy to maintain consistent, easy to refactor.


Microservice - more flexibility because of its partial deployment, availability, they preserve modularity and its also able to work
on multiple platforms.
Microservice is a small independently deployable unit. You can think SOA like a superset of microservices, so the difference lies
in the size and scope of them.

DESIGN PATTERNS.
Design Patterns.
Each pattern describes a problem which occurs over and over again in our
environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million
times over, without ever doing it the same way twice.
Creational Patterns. Abstract Factory pattern.
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
http://lineadecodigo.com/patrones/patron-abstract-factory/
Creational Patterns. Singleton pattern.
Ensure a class has only one instance and provide a global point of access to it.
http://www.dofactory.com/net/singleton-design-pattern
Creational Patterns. Factory Method
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer
instantiation to subclasses.
http://www.dofactory.com/net/factory-method-design-pattern
Behavioral Patterns. Strategy pattern.
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary
independently from clients that use it.
http://www.dofactory.com/net/strategy-design-pattern
http://www.codeproject.com/Articles/776819/Strategy-Pattern-Csharp
Behavioral Patterns. Observer pattern.
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and
updated automatically.
http://www.dofactory.com/net/observer-design-pattern
Behavioral Patterns. Visitor.
Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation
without changing the classes of the elements on which it operates.
http://www.dofactory.com/net/visitor-design-pattern

Dependency Injection.
It is a design pattern that demonstrates how to create loosely coupled classes.
It is useful for unit testing, since we are passing interfaces instead of concrete classes. We are able to mock those interfaces
with fake data.
The dependency injection could be implemented passing the interfaces using the constructor (recommended) or properties.

DATABASE.
Database. Can a Store Procedure be invoked from a Function?
No. The execution of a function is not supposed to modify data in any way, and allowing you to run a stored procedure would
let you do it.
Database. DataSet vs Recordset.
A Recordset is a data structure that belongs to ADO and represents a table.
A DataSet is a data structure that belongs to ADO.net and it is capable of contain more than one data structure such as
DataTable.
Database. DataView.
A DataView enables you to create different views of the data stored in a DataTable.
Using a DataView, you can expose the data in a table with different sort orders, and you can filter the data by row state or
based on a filter expression.
There are two ways of creating a DataView:
var dataView = dataSet.Tables["Customers"].DefaultView;
var dataView = new DataView(dataSet.Tables["Customers"],
"Country = 'USA'",
"ContactName",
DataViewRowState.CurrentRows);

MVC and WebApi.


MVC Routing mechanism and MVC Routing configuration.
When the framework receives a request, it routes it to an action. To determine which action to invoke, the framework uses a
routing table.
The routing logic is a bit different when we use WebApi (Http method) than when we use MVC (URI path).
MVC HTTP Routing configuration.

The route processing the URLs map to a controller, and then to the action which matches the HTTP verb of the request and the
most parameters of the request is selected.

WebApi HTTP Routing configuration.


The reason for using "api" in the route is to avoid collisions with ASP.NET MVC routing.

The route processing the URLs map to a controller, and then to the action which matches the HTTP verb.
We could use the convention of adding the HTTP action verbs as a prefix of the method GetAllCustomers or
PostSaveCustomer. One alternative to that is using attributes like [HttpGet] or [HttpPost].
In the last project, we used [RoutePrefix] and [Route] attributes in each controller
Difference between ApiController and Controller in MVC.
The main difference that you will notice is that the WebApi methods do not return Views. They return just data.
They serialized the data and send it in the corresponding format (Accept header) requested by the call made from the browser
Difference between implementing a WebApi controller and MVC controller returning json.

WebApi serialization depends on Accept header of HTTP request. If you want to return the data in json
format from a MVC controller, you need to set that the object that the method returns is a JsonResult
and use the Json method from the controller that serializes the object to json format.
ViewBag.
It is a wrapper around the ViewData object that allows you to create dynamic properties for the ViewBag. We use it to pass
data from the controller to the view.
ViewData is a Dictionary that has a key/value pair as string/object pair.
Differences between REST and SOAP.
REST (Representational State Transfer): architectural style and approach to communications. It is also known as Restful.
Typically communicates over HTTP with the HTTP verbs (GET/POST/PUT/DELETE) the web browsers use to send or retrieve
data.
SOAP (Simple Object Access Protocol): is a protocol specification for exchanging structured information in the implementation
of web services in computer networks.
Security. Both SOAP and REST support SSL, but SOAP supports WS-Security which adds some enterprise security features. It also
provides a standard implementation of data integrity and data privacy.

Reliable Messaging. Rest doesnt have a standard messaging system and expects clients to deal with communication failures by
retrying. SOAP has successful/retry logic built in and provides end-to-end reliability even through SOAP intermediaries.
When would you use MVC and when WebApi.
MVC. When we develop a web application that renders html from the server.
WebApi. When we develop a SPA (Single Page Application)

Entity Framework.
Explain different EF approaches.
Code First. Helps you to create the entities in your application by focusing on the domain requirements. Once your entities have
been defined and the configurations specified, you can create the database on the fly using both.
Database First. You can use this approach if the database is already designed and we have access to it. The Entity Data Model
(EDM) is created from the database. Manual changes to the database is possible easily and you can always update the EDM if
need be. To do this, simply update the EDM from the database in the Visual Studio IDE.
Model First. You can create the EDM first, then generate the database from it. You would typically create an empty EDM using
the Entity Data Model Wizard in Visual Studio, define the entities and their relationships in Visual Studio, then generate the
database from this defined model.

New database

Model First.
Create model in designer.
Database created from model.
Classes auto-generated from model.

Code First
Define classes and mapping in code
Database created from model
Use Migrations to evolve database

Existing
database

Database First
Reverse engineer model in designer.
Classes auto-generated from model.

Code First
Define classes and mapping in code
Reverse engineer tools available

Explain Data migration in Code First.


The Code First Migrations feature solves this problem by enabling Code First to update the database schema instead of
dropping and re-creating the database.
Steps.
- Disable the database initializer.
- Open Package Manager Console and run these 2 commands.
enable-migrations (creates a Migrations folder and puts in that folder a Configuration.cs file that you can edit to
configure Migrations).
- The Configuration class includes a Seed method. This method enables you to add data after Code First creates or updates the
database.
When you executed the add-migration command, Migrations generated the code that would create the database from scratch.
This code is also in the Migrations folder, in the file named <timestamp>_InitialCreate.cs. The Up method of the InitialCreate
class creates the database tables that correspond to the data model entity sets, and the Down method deletes them.
The update-database command runs the Up method to create the database and then it runs the Seed method to populate the
database.

http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/migrations-and-deployment-with-theentity-framework-in-an-asp-net-mvc-application
Explain how objects are related to the EF context.
Possible answer:
You need to attach the object to the context so it knows this object as an entity.

.Net Language.
What is an Interface? When do they help?
An interface is a contract. An interface contains only the signature of methods, properties. A class or struct that implements the
interface must implement the members of the interface that are specified in the interface definition.
When you develop you must avoid declare as variables a concrete class, you have to declare an interface so then you can apply:
dependency injection, design pattern, etc. Your code follows SOLID principles such as Liskov substitution principle. Also, you get
a loose coupling interconnection among layers.
What is an abstract class?
An abstract class is a class that you cant instantiate so you can use it as an interface.
Differences between interfaces and abstract classes.
An abstract class can implement code, an interface cant.
Which are Expression Trees?
Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a
binary operation such as x < y.

You can compile and run code represented by expression trees. This enables dynamic modification of executable code, the
execution of LINQ queries in various databases, and the creation of dynamic queries.
An expression tree is a data structure that represents executable code.
In other words you can use expression trees to parse an expression and translate to another language. For example:
A LINQ to SQL query is not executed inside your C# program. Instead, it is translated into SQL, sent across a wire, and executed
on a database server. In other words, the following code is never actually executed inside your program:

It is first translated into the following SQL statement and then executed on a server:

The code found in a query expression has to be translated into a SQL query that can be sent to another process as a string. In
this case that process happens to be a SQL server database. It is obviously going to be much easier to translate a data structure
such as an expression tree into SQL than it is to translate raw IL or executable code into SQL
Expression Tree example (a + b):

PostBack
A PostBack is any request for a page that is not the first request. A PostBack will always be in response to a user action
(triggered most commonly by a Button, AutoPostBack control or Ajax).
Which are Lambda expressions?
A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda
expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. Lambda
expressions are particularly helpful for writing LINQ query expressions.
The big advantage of lambda expressions in normal coding is that the syntax is more readable and less verbose. This becomes
quickly more important the more complex code becomes.
How Expressions Trees and Lambda Expressions are related?
A lambda expression is an anonymous function that you can use to create expression trees.
Which is a Generic class?
Generic classes encapsulate operations that are not specific to a particular data type. The most common use for generic classes
is with collections.
Typically, you create generic classes by starting with an existing concrete class, and changing types into type parameters one at
a time until you reach the optimal balance of generalization and usability.
What is the difference between IEnumerable<> and IList<> ?

IEnumerable<T> is the base interface that the following extend or implement. It doesn't allow for direct access and is read only.
So use this only if you intend to iterate over the collection.
ICollection<T> extends IEnumerable<T> but in addition allows for adding, removing, testing whether an element is present in
the collection and getting the total number of elements. It doesn't allow for directly accessing an element by index. That would
be an O(n) operation as you need to start iterating over it until you find the corresponding element.
IList<T> extends ICollection<T> (and thus it inherits all its properties) but in addition allows for directly accessing elements by
index. It's an O(1) operation.
How a Generic parameter could be limited to a certain type family?
public class MyGenericClass<T> where T : BaseType
Explain Using statement
When you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the
Dispose method on the object in the correct way.
File and Font are examples of managed types that access unmanaged resources. All such types must implement the IDisposable
interface.
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object.
using (Font font1 = new Font("Arial", 10.0f))
{
byte charset = font1.GdiCharSet;
}
Explain Lock statement
The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section.
If another thread tries to enter a locked code, it will wait, block, until the object is released.
class Account
{
decimal balance;
private Object thisLock = new Object();
public void Withdraw(decimal amount)
{
lock (thisLock)
{
if (amount > balance)
{
throw new Exception("Insufficient funds");
}
balance -= amount;
}
}
}
Explain difference between managed and unmanaged code.
Managed code is what Visual Basic .NET and C# compilers create. It runs on the CLR (Common Language Runtime), which,
among other things, offers services like garbage collection, run-time type checking, and reference checking. So, think of it as,
"My code is managed by the CLR."
Unmanaged code compiles straight to machine code. So, by that definition all code compiled by traditional C/C++ compilers is
'unmanaged code'. Also, since it compiles to machine code and not an intermediate language it is non-portable.

Entrevista Facu.

Data reader
data table conectado solo hacia adelante
Data set no conectado
Store procedure (PIVOT) invertir las columnas con las vistas.
Vista: se guarda un query en una vista y la consultas desde ahi.
Store procedure estan compilados, se ejecutan compilados.
https://technet.microsoft.com/en-us/library/jj835095(v=sql.110).aspx
https://technet.microsoft.com/en-us/library/ms188250(v=sql.105).aspx
ADO.NET
namespace:
using system.data.sqlclient
Class for database conection
sqlConnection
CONECTION TO DATABASE
Var cnn = new SQLConection(conectionString,)
Open to open db
Close to close db
SQLCommand
method to execute query to db executeNonQuery
For recover data from db we use DataSet and DataReader
DataReader mantiene la conexion con base de datos en el momento de la consulta
DataSet utiliza un SQLDataadapter para recuper la info, pero luego se desconecta de la memoria
Se puede mantener abierto un DataReader a la vez y cerrarlo para abrir otro (close)
MultipleActiveResultSet to open more than one dataReader at the same time. Se setea en el conectionString.
Var command = new SqlCommand(queryString,conn)
Var reader = command.executeReader();
While(reader.Read())
{
}
reader.close();
DataSet is a data structure of data base in memory that can contain another structure of data inside it (DataTable and
DataView)
DataView is a view of DataTable (DefaultView)
DataTable has DataRow and DataColum and can creata a DataVIew of that.
Use the .fill method form SQLDataAdapter to fill the DataSet.

SqlParameter foo = new SqlParameter(parameterName, dbType, size);


this.Add(foo);
SqlCommand testCMD = new SqlCommand ("TestProcedure3", PubsConn);
testCMD.CommandType = CommandType.StoredProcedure;
strRowAffect =testCMD.ExecuteNonQuery ().ToString() ;

private static DataSet SelectRows(DataSet dataset,


string connectionString,string queryString)
{
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(
queryString, connection);
adapter.Fill(dataset);
return dataset;
}
}
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter(v=vs.110).aspx
Update(dataSet) to fill database from DataSet.
Create datadabase
Clase helper to encapsulate common queries to database.
Run store procedure ExecuteReader() ExecuteNonQuery(para escibir) devuelve un entero q es la cantidad de registros
afectados
ExecuteScalar() devuelve la primer columna del primer registro.
Ioc: Delegar el control al framework para q llame para poder continuar.
Observer:Publicador y subscriptor, ejemplo seguir un canl de twitter.
Cluster la base de datos esta ordanada fisicamente por el index, por lo general todo primary key se crea como cluster.
No Cluster se usa cuaquier otro tipo de indice, q ayuda a acelerar la consulta pero no esta ordenada fisicamente por ese
indice. Un indice puede tener mas de una columna.
Primary Key vs Unique
Primary key no acepta null
Unique puede haber un null

UI
How to declare a global variable in Javascript?
A variable declared outside a function, becomes GLOBAL.

A global variable has global scope: All scripts and functions on a web page can access it.
It is possible to do OOP in javascript? How?
Yes. Supports Inheritance (objects can inherit features from other objects), Polymorphism (objects can share the same
interfacehow they are accessed and usedwhile their underlying implementation of the interface may differ), and
Encapsulation (each object is responsible for specific tasks).
http://javascriptissexy.com/oop-in-javascript-what-you-need-to-know/ (Encapsulation and Inheritance)
http://www.codeproject.com/Articles/315169/Polymorphism-in-JavaScript (Polymorphism)
Which is the scope of any variable in javascript?
- Local JavaScript Variables. Variables declared within a JavaScript function, become LOCAL to the function.
- Global JavaScript Variables. A variable declared outside a function, becomes GLOBAL.
Which are the differences between Angular.js and Knockout.js?
Angularjs is a Framework. Knockout is a library.
Knockout has a singular purpose - data binding. It wraps all of your data in functions, and you interact with those functions.
Angular 'does everything'. It has a system of Dependency Injection. It has a templating system. It attempts to handle application
organization with gestures like controllers, services, factories and directives. It has a fully features system of organizing
modules. It handles application url/routing. This is especially true is you use ui-router.
Which architecture pattern is used in Angular.js?
MVC. It is popular because it isolates the application logic from the user interface layer and supports separation of concerns.

You might also like