Full-Stack C#/ .NET Prep
When creating a new controller, what class do you inherit from?
"regular" Controller inheirts from Controller ApiController inherits from ApiController
How do you capture the first time the html document is ready to be manipulated? Write out two different ways to accomplish this task.
$( document ).ready() All three of the following syntaxes are equivalent: $( document ). ready( handler ) $().ready( handler ) ( this not recommended ) $( handler )
How many times does the "document ready" event fire?
--once
What does it mean to be a .NET MVC application?
An application written in C# that implements the MVC design pattern, which has a high degree of separation of concern(Follow up: The Model is properties of data, the Controller is business logic, and the View is for presentation.)
In .Net how many interfaces can a class implement?
Multiple
What are all the different types of validations that these attributes let you perform?
StringLength (designates max and min numbers of characters) required Range Regularexpression Datatype(such as email and phone number) EnumDataType Customvalidation Validation(Serves as a base class for validation attributes)
What is a Database?
A database is a collection of information that is organized so that it can easily be accessed, managed, and updated.
What are breakpoints?
A debugging tool that stops at the point in code (so that you can inspect if certain lines were hit and what values they have at various points)
What is the relationship between a View and a Model in a typical MVC application?
A model contains the data or properties. The controller passes the model to the view.
What are C# extension methods?
An extension method extends the functionality of an object by allowing you to add abstract class methods to existing types without modifying the original type. You must define extension methods as static, and the first parameter is preceded with "this" and specifies on which type the extension method operates.
ApiController
ApiControllers are specialized in returning in data. Provide a REST-ful API by convention. "Regular" Controller - contains ActionResult classes that return a View.
What is a model?
Properties of data
What are "Joins" used?
SQL joins are used to combine rows from two or more tables.
What is a SQL Injection Attack?
SQl Injection is an attack in which malicious code is inserted into strings that are later passed to an instance of SQL Server for parsing and execution in order to effect the execution of predefined SQL commands. A SQL Injection attack is a form of attack that comes from user input that has not been checked to see that it is valid. The objective is to fool the database system into running malicious code that will reveal sensitive information or otherwise compromise the server.
What namespace do these attributes live in? (i.e. What namespace do the data attributes (server validation) in .NET belong to (What library?))
using System.ComponentModel.DataAnnotations
Over what port number is a normal web request made to a webserver?
80
What are the different types of HTTP methods? When would you use these over others?
GET - to retrieve data from db (or data source) POST - to insert data into db PUT - update existing records DELETE - delete (duh!)
Why are generics so important?
Generics are beneficial because they maximize code reusability in that you can write one class that can be used for multiple types. It also allows you to create generic collection classes. Use generic types to maximize code reuse, type safety, and performance.
What does it mean 'to be a strongly typed language?
Highly dependent on type. Every variable is defined by its type.
How do you declare a variable in Javascript? Is variable declaration required in Javascript?
var. You don't have to declare a variable with 'var'.
What do you use to debug Javascript?
Chrome Developer Tools
What does a 500 response code mean?
Internal error
Does .Net support other types of Web Applications?
Yes, Web Forms(still seperation of concern, but all routing is gone)
What is the difference between the css attributes "display" and "visibility"?
"display: none;" hides the element and does NOT take up any space. Display can be set to: none, block, inline. If "display:none", whatever was in that place on the browser is removed and the next visible content is reformatted upwards in its place. "visibility: hidden;" hides an element, but it will still take up the same space as before. Visibility can be set to: visible, hidden. If "visibility:hidden ", there will be an empty space where the content lives, but the page will not be reformatted.
What are the ul and ol elements? How do they differ?
"ul" is an unordered list and "ol" is an ordered list. "ul" is a list with bullet points and "ol" arranges the item by number.
How would you use it to hide an element if you have an element's click event wired up?
$("#element").on("click", hideMe); var hideMe = function() { $(this).addClass("hidden"); }
Write a selector that limits this search to a div whose id is "targetContainer"?
$("#targetContainer") or $("div#targetContainer img[src=^photos]")
Write a selector that will select all elements with a class name of "findme".
$(".findme")
Write a selector that will find img elements within div a class name of "imgHolder"
$("div.imgHolder img")
Write code to find the checkboxes on a page that are checked.
$('input[type=checkbox]:checked')
What types of Serialization are you familiar with?
$.serialize() - Only form elements are examined for inputs they contain. A form is serialized to a name-value pair string that can be sent to a server in an Ajax request. Other types: i. SOAP serialization ii. Binary Serialization iii. XML Serialization iv. JSON Serialization
What are nullable types?
(*Nullable types refer to C# and .NET.) A nullable type can store null. Nullable types are constructed by specifying the question mark after a value type. For example, the nullable int can be specified with the syntax "int?". Bool?, Guid?, int?, decimal? are examples of nullable types. Value types are Nullable types. Nullable types have these properties: .HasValue and .Value
Describe the main difference or considerations between the two languages?
--C# is strongly-typed language, and javascript is a non-typed scripting language
If this class was going to participate in Model binding in the MVC request life cycle, is it currently setup to report as invalid when no data is sent to the Server? (Assuming First/Last Name is required)
--No Validation using DataAnnotations i. Decorate or "Annotate" your models with a specific set of Attributes that tell the .Net Framework what you expect from each property ii. Invoke a check of these Attribute or rules at the controller level before you do anything else and return an error if the data is not valid. To check if the data was properly submitted we invoke the check and respond appropriately.
In an MVC app, what information is used to route your request?
-The Route pattern -Http Method -Data/Parameters
What different kinds of loops are there? Demonstrate 3 in JS.
-for loop -while loop (potentially executes one, as long as the condition is met) -do while(executes one, then evaluates the condition) -Note: A "break" statement stops the loop at a certain point but doesn't exit the function. The "return" keyword exits the function. The "continue" keyword skips past the current iteration in the loop but does not exit the function.
LINQ Lambda expressions
// Find duplicates var duplicates = list.GroupBy(x=>x) .Where(g=>g.Count()>1) .Select(y=>y.Key) .ToList(); //Remove duplicates var uniqueVals = myCustomerList.GroupBy(cust => cust.CustomerId).Select(grp => grp.First()); //Another way to remove duplicates in List: using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { // List with duplicate elements. List<int> list = new List<int>(); list.Add(1); list.Add(2); list.Add(3); list.Add(3); list.Add(4); list.Add(4); list.Add(4); foreach (int value in list) { Console.WriteLine("Before: {0}", value); } // Get distinct elements and convert into a list again. List<int> distinct = list.Distinct().ToList(); foreach (int value in distinct) { Console.WriteLine("After: {0}", value); } } } Output Before: 1 Before: 2 Before: 3 Before: 3 Before: 4 Before: 4 Before: 4 After: 1 After: 2 After: 3 After: 4
What are the first 4 numeric values of an Enum like this?
0,1,2,4,8,16...
Describe the Request-Response lifecycle of a typical request made by your browser.
1. A Request (which contains the HTTP request method, cookies, url, and data all inside headers) is made to the web server. 2. When it gets to the web server, the domain portion of the URL is used to route the request to a web application. 3. Inside the web application, the router takes over and matches the route and the HTTP method from the route table to an endpoint. 4. If the method takes non-model parameters, the parameters are also considered in routing. 5. Authentication then Authorization of the request takes place. 6. Model binding/parameter binding take place. 7. It proceeds to send data to the specific method in the controller and it completes the request by sending an appropriate response to the browser. (discuss possible things that can happen inside the MiC (endpoint) i.e. model-validation, service calls)
What is the response code for a request that received a successful or "OK" response?
200
How do you maintain state in the web application?
4 things help us maintain state in the request itself- cookies, url, the query string, and variables passed back and forth from the page to the server. State can also be maintained on the server by keeping static variables/members, (they retain their value across different page requests so this allows different requests at different times to have access to the same data/value) We can put things in cache, and use the concept of a session which allows you to store information specific to the user in memory. The Application itself, the context in which all your .Net code runs also has a Dictionary that you can use to hold data, any data, that will survive across different requests.
What are the new media elements in HTML5?
<audio> (defines sound or music content), <embed> (defines containers for external applications like plug-ins), <source> (defines sources for <video> and <audio>), <track> (defines tracks for <video> and <audio>), <video> (defines video or movie content)
Do all tags require a closing tag? If not, which ones don't?
<link> <p> <li> <br> <hr> and <input> do not require end tags
What is the difference between == and === ?
== checks the value, === checks the value and type. For example, 1 == "1" is true, but 1 === "1" is false.
What is a foreign Key?
A FOREIGN KEY in one table to a PRIMARY KEY in another table.
What is the difference between a POST and a GET?
A GET requests data from a specified resource. A POST submits data to be processed to a specified resource.
What is an "if" statement?
A conditional statement that uses if-then-else logic. If true or if false, do x, else do something else or nothing.
What are Collections in .Net?
A container with multiple elements. For example, a list <T> or dictionary <T,K>. Collections don't necessarily have a key, but they do have an index. Look in atlassian for more on collections.
What are generics in .Net?
A generic class allows you to specify the type of the class at the time it's instantiated.
What are <hr/> tags?
A horizontal rule: It's a line on the page like a ruler line. Signifies a thematic break in the page content.
What is a static member or property in .Net?
A member or a property that does not need to be instantiated when it is used. a static class remains in memory for the lifetime of the application domain in which your program resides.
What is Razor?
A parsing engine for your view.
What is a relational Database?
A relational database is a collection of data items organized as a set of formally-described tables from which data can be accessed or reassembled in many different ways without having to reorganize the database tables. The standard user and application program interface to a relational database is the structured query language(SQL). SQL statements are used both for interactive queries for information from a relational database and for gathering data for reports.
What is a switch/case statement?
A statement that can have multiple execution paths unlike an "if else" statement. For each case, something will execute. (*see http://www.w3schools.com/js/js_switch.asp)
What is a database "table"
A table contains one or more data categories in columns. Each row contains a unique instance of data for the categories defined by the columns.
What is Micro Templating? When and why would you use this technique?
A template engine which embeds javascript. Used to generate html from your js objects For example: angular uses "mustache" syntax embedded in html {{someObject.someProperty}}
What are cookies? What are they used for?
A very small text file placed on your hard drive by a Web Page server. It is essentially your identification card. In this file, various information can be stored, from pages visited on the site, to information voluntarily given to the site. Used to keep track of your movements within the site, help you resume where you left off, remember your registered login (authentication), theme selection, preferences, and other customization functions.
What is a strongly typed view? How would you define your view as such?
A view bound to a view model. You can only reference one view model per view. Define it by saying @model at the top and declaring the namespace of a model
What is the generic name of the library used in .Net that is used to communicate with Databases?
ADO.NET
What is AJAX? When do you use it? Why would you use it?
AJAX stands for Asynchronous Javascript and XML. AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. Example: Capital.Page.saveProduct = function (myData, UId) { var url = "/api/products/Page2/" + UId; var settings = { cache: false , contentType: "application/x-www-form-urlencoded;charset=UTF-8" , data: myData , dataType: "json" , success: Capital.Page.AjaxSuccess , error: Capital.Page.AjaxError , type: "POST" }; $.ajax(url, settings); }
How would you include a javascript file into your web page?
Add it to the bottom of the page because the page loads (appears to load) faster.
What is a doctype?
At the top of the html file, it specifies the version of the markup language you are using. <!DOCTYPE html> is the one for html5
LINQ (C#)
Basic: class LowNums { static void Main() { // A simple data source. int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; // Create the query. // lowNums is an IEnumerable<int> var lowNums = from num in numbers where num < 5 select num; // Execute the query. foreach (int i in lowNums) { Console.Write(i + " "); } } } // Output: 4 1 3 2 0
Are Namespaces a client side or server side construct
Both Client and Server
Explain the purpose of the following headers: Cache-Control, Cookie, Content-Type
Cache-control: cache has to do with storage. It tells your web browser a page is good for a few days. A lot of our requests will tell them not to cache because it's dynamic and we want a new copy all the time. Cookie: user information, settings and authentication. The files stored on your hard drive for authentication Content-Type: the format such as JSON or XML
What is a best practice protocol to follow for checking in code?
Clean, rebuild, shelve, get latest, test, resolve issues, clean and rebuild, and then check in
What are interfaces?
Contracts Classes can implement interfaces. A class can implement multiple interfaces. Interfaces can not be instantiated and cannot contain implementation logic.
How does the web server know who you are across different web requests?
Cookies
How do you declare a variable in TSQL?
DECLARE @x int
If you wanted to delete information from a table what statement would you use?
DELETE FROM [Table_name] (WHERE condition)
What is data normalization?
Database normalization, or data normalization, is a technique to organize the contents of the tables for transactional databases and data warehouses - to avoid redundancy When you normalize a database, you have four goals: arranging data into logical groupings such that each group describes a small part of the whole minimizing the amount of duplicate data stored in a database organizing the data such that, when you modify it, you make the change in only one place --building a database in which you can access and manipulate the data quickly and efficiently without compromising the integrity of the data in storage. Normalization is usually for minimizing errors and data duplication, to DENormalize is for reporting.
What is attribute routing?
Decorating the route with a prefix, method, Id, or parameter. Attribute routing supports multiple routes per method. (On startup, the application reads your routes and creates an entry in your route table so the routing mechanism can read from it when it needs to. It points to the method in the controller. The router is inside the application.)
IoC and DI
Dependency Injection (DI) is a software design pattern that allow us to develop loosely coupled code. DI is a great way to reduce tight coupling between software components. DI also enables us to better manage future changes and other complexity in our software. The purpose of DI is to make code maintainable. The Dependency Injection pattern uses a builder object to initialize objects and provide the required dependencies to the object means it allows you to "inject" a dependency from outside the class. For example, Suppose your Client class needs to use a Service class component, then the best you can do is to make your Client class aware of an IService interface rather than a Service class. In this way, you can change the implementation of the Service class at any time (and for how many times you want) without breaking the host code.
What do you look for when debugging Javascript?
Errors in the console, breakpoints, inspect elements of the html, watch window, Net tab
What is IEnumerable and what significance does it hold?
Exposes an enumerator, which supports a simple iteration over a non-generic collection. (IEnumerable is the base interface for all non-generic collections that can be enumerated.) When you instantiate/create an array or List<T>, it automatically implements IEnumerable which allows you to iterate through it.
When should you use HTML tables?
For reporting, show true grid like data. However, this design is often unresponsive. HTML tables do not allow the columns to stack.
What are generics?
Generics allow you to delay the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type. You write the specifications for the class or the method, with substitute parameters for data types. When the compiler encounters a constructor for the class or a function call for the method, it generates code to handle the specific data type. It helps you to maximize code reuse, type safety, and performance. You can create generic collection classes. The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. You can create your own generic interfaces, classes, methods, events and delegates.
How do you restart your website?
Go into IIS. Or clean and rebuild.
How do you access the underlying value of a Nullable Type?
Guid.Empty, Property.Value()
Describe the relationships between HTML, CSS and Javascript
HTML(Hypertext Markup Language) - used for structuring content CSS (Cascading Style Sheets) - used for applying visual styles Javascript - interacts with and manipulate HTML
Use "break" to exit the loop but continue executing code inside the function. Use a "return" to stop execute coding completely and leave the function. Use "continue" to skip the current iteration, but continue the loop.
How do you exit a loop before its normal loop cycle completes?
What protocol is normally used in a web request?
Http
Write examples of each join.
INNER JOIN: SELECT column_name(s) FROM table1 t1 INNER JOIN table2 t2 ON t1.column_name=t2.column)name; LEFT JOIN: SELECT column_name(s) FROM table1 t1 LEFT OUTER JOIN table2 t2 ON t1.column_name=t2.column_name; RIGHT JOIN: SELECT column_name(s) FROM table1 t1 RIGHT OUTER JOIN table2 t2 ON t1.column_name=t2.column_name; FULL JOIN: SELECT column_name(s) FROM table1 FULL OUTER JOIN table2 ON table1.column_name=table2.column_name;
What are the different types of Joins?
INNER JOIN: returns all rows when there is at least one match in BOTH tables LEFT JOIN: Return all rows from the left table, and the matched rows from the right table RIGHT JOIN: Return all rows from the right table, and the matched rows from the left able FULL JOIN: return all rows when there is a match in ONE of the tables
What is a named function in JavaScript?
If it doesn't have a name, it's an anonymous function. A function that has a name such as "var x = function() {};" can be called upon by invoking x like x(). Specifically a NAMED FUNCTION looks like: function myFunc() { } A FUNCTION EXPRESSION looks like: var myFunc = function() {}
Asynchronous controllers and methods: Processing Asynchronous Requests
In applications where thread starvation might occur, you can configure actions to be processed asynchronously. An asynchronous request takes the same amount of time to process as a synchronous request. For example, if a request makes a network call that requires two seconds to complete, the request takes two seconds whether it is performed synchronously or asynchronously. However, during an asynchronous call, the server is not blocked from responding to other requests while it waits for the first request to complete. Therefore, asynchronous requests prevent request queuing when there are many requests that invoke long-running operations. When an asynchronous action is invoked, the following steps occur: The Web server gets a thread from the thread pool (the worker thread) and schedules it to handle an incoming request. This worker thread initiates an asynchronous operation. The worker thread is returned to the thread pool to service another Web request. When the asynchronous operation is complete, it notifies ASP.NET. The Web server gets a worker thread from the thread pool (which might be a different thread from the thread that started the asynchronous operation) to process the remainder of the request, including rendering the response.
Where can you define where an html form sends its data? Describe all known ways.
In the action attribute of the form. <form action="demo_form.asp" method="get"> *see http://www.w3schools.com/tags/att_form_method.asp
If you were to encounter a Resource Not Found error/page while developing your application what would you do to resolve this issue?
In this case, I would go to the controller, make sure the route is correctly typed, make sure the view controller returns a view, make sure it's executing the correct http request method. If parameters are required but not passed in, it will create a 404 error as well.
What are indexes?
Indexes are created on columns in tables or views. The index provides a fast way to look up data based on the values with those columns. For example, if you create an index on the primary key and then search for a row of data based on one of the primary key values, SQL Server first finds that value in the index, and then uses the index to quickly locate the entire row of data. Without the index, a table scan would have to be performed in order to locate the row, which can have a significant effect on performance. you would add indexes to columns that you would filter or join off of.
What are the principles of object oriented programming (OOP)?
Inheritance, encapsulation, reusability, abstraction, polymorphism (IERAP) Abstraction and encapsulation are complementary concepts: abstraction focuses on the observable behavior of an object... encapsulation focuses upon the implementation that gives rise to this behavior (abstraction)... encapsulation is most often achieved through information hiding, which is the process of hiding all of the secrets of object that do not contribute to its essential characteristics.
What are the advantages of being strongly typed?
It imposes a rigorous set of rules on a programmer, thus guarantees a certain consistency of results.
What is inheritance?
It is a class inheriting all the properties of another class. You gain access to all the public and protected members of the base class
What is Twitter Bootstrap?
It is a free collection of tools for creating websites and web apps. It contains html and css based design templates for typography, forms, buttons, navigation and other interface components.
What is a modal window?
It is a pop up window in your browser. You have to click out of it before you can go back to your webpage. It should go closer to the top of the html so that the page loads faster.
What is a view?
It is presentation. You put the display or UI logic in the view in an MVC application.
What is authorization? At what level does it typically happen in a .Net MVC application? How does one implement this?
It means you must be logged in to access that method. It happens in the method signature or on top of the entire controller. Add [Authorize] to your method signature or on top of the entire controller.
What does this CSS selector do: $("img[src=^photos]")
It selects all the images with an src attribute of photos. ^ is a regular expression query to find all my image whose src attribute starts with "photos".
What is the CSS attribute "clear" used for?
It specifies which side of an element other floating elements are not allowed. Use it to create separation on a page. You can clear: left, clear: right, clear: both. (*Meaning, you can clear content to the left or right or to a new line. Clear is like a blank div.) *Note: Float is like pull-right or pull-left and is commonly used on buttons.
What is Web.Config? What do you use it for?
It stores passwords, account information, connection strings, and settings.
What is knockout?
Knockout.js is a javascript library that uses html data binding (like AngularJS). It uses a MVVM design pattern. It is a quick and easy way to update the UI or manipulate the DOM.
In order to have the inputs of an html form send its data to the server what should you be sure to do?
Make sure it has a name attribute.
How many layout files can your application have?
Many
How many attributes can an html element have?
Multiple
What are Namespaces? What are they used for?
Namespaces are heavily used in C# programming in two ways. First, the .NET framework uses namespaces to organize its many classes Second, declaring your own namespaces can help you control the scope of class and method names in larger programming projects. Use the namespace keyword to declare a namespace, as in the following example: namespace SampleNamespace { class SampleClass { } }
Do all tags require an ID attribute?
No
Should you wrap a div element in an anchor?
No
Would this method work if you were to switch out browsers in the middle of a session?
No, they are browser specific.
Why would we go through the process of normalizing our data?
Normalization is part of successful database design; without normalization, database systems can be inaccurate, slow, and inefficient, and they might not produce the data you expect.
How would you give this new object a new property?
Object.property = value;
Asynchronous controllers and methods: How Requests Are Processed by the Thread Pool s
On the Web server, the .NET Framework maintains a pool of threads that are used to service ASP.NET requests. When a request arrives, a thread from the pool is dispatched to process that request. If the request is processed synchronously, the thread that processes the request is blocked while the request is being processed, and that thread cannot service another request. This might not be a problem, because the thread pool can be made large enough to accommodate many blocked threads. However, the number of threads in the thread pool is limited. In large applications that process multiple simultaneous long-running requests, all available threads might be blocked. This condition is known as thread starvation. When this condition is reached, the Web server queues requests. If the request queue becomes full, the Web server rejects requests with an HTTP 503 status (Server Too Busy).
How many id attributes can an element have?
One
How many layout files can a view be associated with at any one time?
One
In .Net how many classes can one class inherit from?
One
What is Serialization?
Packaging data for transport. Serialization is the process of converting an object into a form that can be readily transported. The $.serialize() method creates a text string of name/value pairs that can be sent to a server in an ajax request. It can act on a jQuery object that has selected individual form controls, such as <input>, <textarea>, and <select>:$("input, text, select").serialize(); it is typically easier, however, to select the <form> itself for serialization: $("#formData").serialize();
What does the keyword "this" refer to in Javascript?
Refers to the element that was clicked upon, jquery executes a function in the context of that element.
What are the possible values for the POSITION attribute?
Relative, absolute, fixed, static, initial, and inherit. They are css attributes.
What is the truncate statement used for? What is the key difference between this and your other options to remove data?
Removes all rows from a table without logging the individual row deletions. TRUNCATE TABLE is similar to the DELETE statement(with no WHERE clause); however, TRUNCATE TABLE is faster and uses fewer system and transaction log resources.
What is an "em" tag?
Renders as emphasized text or italic.
What does a 404 response code mean?
Resource not found. The router can't find the url you are searching for. When the web server can't find the url.
If you want to visualize the changes you have made to a file in comparison to the last change what would you do?
Right click on file, view history and compare changes
What are the basic parts of a simple TSQL Query?
SELECT [column] FROM [table]
What language do you use to communicate with the database?
SQL
What language is used to write Stored Procedures?
SQL & T-SQL
If your web page was taking too long to download, what would you do to try and determine what was taking so long?
See if I 7f you have a "GET" that is loading. You can place a breakpoint in the controller on the line of code that is doing your "GET." Attach this breakpoint to w3wp.exe. Your database call could be taking too long.
How would you show a modal window in your web application?
Select the id and use a .show() or .modal('show') jquery statement.
What are arrays?
Series of items with an index beginning at 0.
How do you make sure you include this file on all web pages?
Shared Layout, footer, head. Basically, put the file in the shared folder.
Write the code to connect to SQL Server database in C#.
SqlConnection conn = new SqlConnection(connectionString); conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "stored proc name"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@nameOfParam", new object()); IDataReader reader = cmd.ExecuteReader(); while(reader.Read()) { //read data } conn.Close();
What online resources do you use in your everyday programming?
Stack overflow, google, documentation based on a specific js library, js lint, jsoneditoronline.org, bootstrap, font awesome, msdn, jsfiddle, jquery documentation, w3schools, api.jquery.com, technet, sqlauthority.
What is the string builder?
StringBuilder sb = new StringBuilder("some string"); sb.Append("some more stuff"); sb.AppendLine(); console.WriteLine(sb.ToString()); The String object is immutable. Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly. The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop. String builder creates an array of characters and it adds to it. It is static. When it runs out of slots, it creates a bigger array and takes existing strings and shoves it inside. It's efficient because it is just creating one object at a time and it is simply adding to one array which increases memory.
What are the new Form Elements introduce in HTML5?
The <datalist> element specifies a list of pre-defined options for an <input> element. The <keygen> element is to provide a secure way to authenticate users. <output> element represents the result of a calculation (like one performed by a script).
Dependency Inversion Principle (DIP)
The Dependency Inversion Principle states that: High level modules should not depend upon low level modules. Both should depend upon abstractions. Abstractions should not depend upon details. Details should depend upon abstractions. The Dependency Inversion principle (DIP) helps us to develop loosely coupled code by ensuring that high-level modules depend on abstractions rather than concrete implementations of lower-level modules. The Inversion of Control pattern is an implementation of this principle.
What is a Primary Key?
The PRIMARY KEY constraint uniquely identifies each record in a database table. A primary key column cannot NULL values. Most tables should have a primary key, and each table can have only ONE primary key. Column or set of columns that uniquely a record.
Asynchronous controllers and methods: Asynchronous requests - the code
The async and await keywords in C# are the heart of async programming. By using those two keywords, you can use resources in the .NET Framework or the Windows Runtime to create an asynchronous method almost as easily as you create a synchronous method. Asynchronous methods that you define by using async and await are referred to as async methods. // Three things to note in the signature: // - The method has an async modifier. // - The return type is Task or Task<T>. (See "Return Types" section.) // Here, it is Task<int> because the return statement returns an integer. // - The method name ends in "Async." async Task<int> AccessTheWebAsync() { // You need to add a reference to System.Net.Http to declare client. HttpClient client = new HttpClient(); // GetStringAsync returns a Task<string>. That means that when you await the task you'll get a string (urlContents). Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com"); // You can do work here that doesn't rely on the string from GetStringAsync. DoIndependentWork(); // The await operator suspends AccessTheWebAsync. // - AccessTheWebAsync can't continue until getStringTask is complete. // - Meanwhile, control returns to the caller of AccessTheWebAsync. // - Control resumes here when getStringTask is complete. // - The await operator then retrieves the string result from getStringTask. string urlContents = await getStringTask; // The return statement specifies an integer result. // Any methods that are awaiting AccessTheWebAsync retrieve the length value. return urlContents.Length; }
What is lazy loading?
The design pattern commonly used to defer initialization of an object until the point at which it is needed. This contributes to efficiency in the application's operation, as all the things needed load first and things that aren't needed don't load until the point at which they are needed.
What is responsive design? What are the pros and cons of this technique?
The website responds according to the size and screen you are looking at. Your website interface will respond to your view port. It implies you will need more time, more testing on different size screens. It is faster than having to do something for each size screen individually. Sometimes on a small screen, a con could be that some things are hidden. Sometimes there is content that never shows up on a mobile client, even though it gets sent to the browser on your phone, so it's a waste of bandwidth.
What is the z-index property?
The z-index property specifies the stack order of an element. An element with greater stack order is always in front of an element with a lower stack order. Meaning, a z-index: 5 is closer to the observer than z-index: -1. Note: z-index only works on positioned elements (position:absolute, position:relative, or position:fixed). Default value: auto; Inherited: no; Animatable: yes.
Stack vs Heap
These are two places the .NET framework stores items in memory as your code executes. http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx?ArticleID=9adb0e3c-b3f6-40b5-98b5-413b6d348b91 Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer's RAM. Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and it's allocation is dealt with when the program is compiled. When a function or a method calls another function which in turns calls another function etc., the execution of all those functions remains suspended until the very last function returns its value. Variables allocated on the heap have their memory allocated at run time and accessing this memory is a bit slower, but the heap size is only limited by the size of virtual memory. Element of the heap have no dependencies with each other and can always be accessed randomly at any time. The Heap is like the heap of clean laundry on our bed that we have not taken the time to put away yet; we can grab what we need quickly. The Stack is like the Stack of shoe boxes in the closet where we have to take off the top one to get to the one underneath it. Stack Heap Value Types Reference Types DateTime class int interface smallint delegate Guid object struct string (*Have to use .HasValue and .Value) (*Can contain value types)
What are regular expressions? When would you use them?
They are a tool used for quickly and efficiently parsing text that are driven through a syntax of pattern queries. They are typically used for validating strings from form inputs.
What are connection strings?
They are a way to connect to the database from your application.
What are CSS Media queries?
They are what powers responsive design. It queries your media to apply rules based on which device/(viewport) you are working with. (Responsive design is the first thing on bootstrap.com)
As a developer, where can you find the cookies you have per site/Url?
They can be seen in 1 of several places in your developer tools. You could download cookie chrome extensions to manage and view easier.
What are HTTP headers?
They contain cookies, data, a url, and the http request method.
Are there any benefits to doing this?
This is beneficial because it creates a separation of concern. Test the areas separately, modularity- I have a thing that does a particular task and that task should be well defined and specific
IoC and DI: Constructor Injection
This is the most common DI. Dependency Injection is done by supplying the DEPENDENCY through the class's constructor when instantiating that class. Injected component can be used anywhere within the class. Should be used when the injected dependency is required for the class to function. It addresses the most common scenario where a class requires one or more dependencies. public interface IService { void Serve(); } public class Service : IService { public void Serve() { Console.WriteLine("Service Called"); //To Do: Some Stuff } } public class Client { private IService _service; public Client(IService service) { this._service = service; } public void Start() { Console.WriteLine("Service Started"); this._service.Serve(); //To Do: Some Stuff } } class Program { static void Main(string[] args) { Client client = new Client(new Service()); client.Start(); Console.ReadKey(); } } The Injection happens in the constructor, by passing the Service that implements the IService-Interface. The dependencies are assembled by a "Builder" and Builder responsibilities are as follows: knowing the types of each IService according to the request, feed the abstract IService to the Client
Asynchronous controllers and methods: Choosing Synchronous or Asynchronous Action Methods
This section lists guidelines for when to use synchronous or asynchronous action methods. These are just guidelines; you must examine each application individually to determine whether asynchronous action methods help with performance. In general, use synchronous pipelines when the following conditions are true: -The operations are simple or short-running. -Simplicity is more important than efficiency. -The operations are primarily CPU operations instead of operations that involve extensive disk or network overhead. Using asynchronous action methods on CPU-bound operations provides no benefits and results in more overhead. In general, use asynchronous pipelines when the following conditions are true: -The operations are network-bound or I/O-bound instead of CPU-bound. -Testing shows that the blocking operations are a bottleneck in site performance and that IIS can service more requests by using asynchronous action methods for these blocking calls. -Parallelism is more important than simplicity of code. -You want to provide a mechanism that lets users cancel a long-running request.
How would you give all instances of a JS "person" object a new property?
Through a prototype property. Object.prototype.name = value;
How do you horizontally center a div on a page? How about vertically?
To horizontally center a div apply "margin: 0px auto" to the div. To vertically center a div, apply "display: table-cell; vertical-align: middle" to the outer div.
How can you test if an instance of an object implements a particular interface?
To test if an object implements a certain interface: Iperson p = myObject as Iperson; if(p != null) { //getting here means that myObject implements Iperson } if(myObject is IMyInterface) { // object myObject implements IMyInterface } To test if a type implements a certain interface: if(typeof(IMyInterface).IsAssignableFrom(typeof(MyType))) { // type MyType implements IMyInterface } If you got a generic object and want to do a cast as well as a check if the interface you cast to is implemented the code is: var myCastedObject = myObject as IMyInterface; if(myCastedObject != null) { // object myObject implements IMyInterface }
What is source control?
Tracks versions of your code. What providers are you aware of? Team Foundation Server, Git (not yet but we will be) What does it mean to check in code? Upload your code to the server.
What does your typical error handling code look like?
Try catch statements, if else statements, nullable types
What is a Null Reference Exception?
Trying to refer to something that is not there or a reference to an object that is null or does not exist. To prevent this from happening, write: if (object != null) { obj.prop = 1 }
What are the different types of statements available to you in TSQL?
UPDATE INSERT SELECT DELETE
How do you keep a div to display with a maximum height of 100px and hide all other content?
Use css to target the div class and set height to 100px and set overflow to hidden: max-height: 100px; overflow: hidden;
What are span tags and when would you use them?
Use it when you have a block of text that you want to be able to call out and style with css. (*span does not "break")
How would you fade in an element?
Use jquery .fadeIn()
How do you know if your jQuery selector found any matching elements?
Use jquery selector.length
What are some out of the box ways to style text differently in HTML?
Use the style attribute in the html tag - which should never be used on a production website.
What does it mean to exercise defensive programming?
Use validation and error handling code.
What are the different parts of a connection string?
User Id, Password, Database, Server. (*You can have multiple databases at a server.)
How do you protect yourself against these?
Using a combination of stored procedures and parameters. Stored procedures alone will not protect against SQL injection attacks, because you still need to use the stored procedure correctly.
How do you send email on the server?
Using a third party service, like SendGrid. You need a connection and a template, username and password, and you send email as html. You can specify your username and password in the Web.Config file. Using a third party service, like SendGrid. You need a connection and a template, username and password, and you send email as html. You can specify your username and password in the Web.Config file. Another option: using the SmtpClient. Here's some sample code: public void sendMessage(string sender, string subject, string body) { List<Contact> contacts = loadContacts(); SmtpClient client = new SmtpClient(); MailMessage message = new MailMessage(); message.Subject = subject; message.Body = body; MailAddress from = new MailAddress(sender); message.From = from; foreach (Contact contact in contacts) { message.To.Add(contact.email); } try { client.Send(message); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
Where do you put your display or UI logic/business rules in a MVC app?
View
When would you use a Nullable Type?
When would you use a Nullable Type?
Read the error message. Insert a breakpoint in the browser or through w3wp.exe (attach to process). Take steps based on where the error is.
When you encounter an error what are the steps you take to resolve the error?
LINQ (C#)/ WHERE Clause
Within a single where clause, you can specify as many predicates as necessary by using the && and || operators. In the following example, the query specifies two predicates in order to select only the even numbers that are less than five. C# class WhereSample2 { static void Main() { // Data source. int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; // Create the query with two predicates in where clause. var queryLowNums2 = from num in numbers where num < 5 && num % 2 == 0 select num; // Execute the query foreach (var s in queryLowNums2) { Console.Write(s.ToString() + " "); } Console.WriteLine(); // Create the query with two where clause. var queryLowNums3 = from num in numbers where num < 5 where num % 2 == 0 select num; // Execute the query foreach (var s in queryLowNums3) { Console.Write(s.ToString() + " "); } } } // Output: // 4 2 0 // 4 2 0
What are the benefits of JSON Serialization over XML Serialization?
XML(Extensible Markup Language) serialization serializes only the public fields and property values of an object into an XML stream. XML serialization does not include type information. The biggest reason that JSON is now being used over XML is that JSON is inherently more effecient. It is lightweight, fewer bits are being transferred, and less machine time is required to process data(on either end).
Can Layout files be strongly typed as well?
Yes
Over what port number is a normal web request made to a webserver? 80. Can you change this?
Yes, in IIS
Can a function call itself?
Yes, it is called recursion. This can be dangerous; you need a condition that allows you to break out of the function. Otherwise you will be stuck in an infinite loop.
Is there a way that you can cancel the action of a submit button? What is the default action of a submit button vs a regular button?
Yes, use event.preventDefault(). A "submit" button will submit the form and take you to the top of the page, but a regular button will only do what it is wired up to do.
Can you change the orientation of either of these elements?
Yes, using: "list-style-type: none" and "display: inline"
Can you capture the click event of a div element?
Yes: ("#myDivId").on("click", fx)
What is an abstract class and is this different than an interface?
You can not instantiate an abstract class, you can inherit from, you can build upon.
Where do you include your Javascript files on an html page? CSS files? Where does the spec say you should include these files?
You put JS files at the bottom of an html page so that the html elements get a chance to load and begin rendering before all of the JavaScript files begin slowing down the page loading. CSS files go in a separate file but get referenced in the head tag.
How do you store Flags in an Enum?
[Flags] public enum UserStatus: short { NotSet = 0, [Description("Inactive")] Inactive = 1, [Description("Active")] Active = 2 }
Decorate this class to the following specs: First/Last Name should be at least 3 chars long and no more than 50, Age should be at least 18 years old
[StringLength(50, MinimumLenth = 3)] public string FirstName {get; set;} [StringLength(50, MinimumLength = 3)] public string LastName {get; set;} [Range(18, 120)]Model public int Age { get; set; }
Write out an example class diagram (a diagram showing how several classes are related) for:
a base class Person, class Employee, class Manager, class Robot. Include an interface for "people", an interface for "robots". Be sure to have an example of how you leverage inheritance class Person : IPeople class Robot : IRobot class Employee : Person class Manager : Employee
How does your browser manage cookies across all the sites you visit?
at the domain
What do you use to debug C#?
breakpoints and attach to process in visual studio. Select w3wp.exe (world wide web worker process)
How do you change the color of a font in CSS?
color: hexcode (i.e. #f45234)
How many normal forms are there?
five (Follow up explanation: The normal forms defined in relational database theory represent guidelines for record design in coherence with data normalization.) http://www.bkent.net/Doc/simple5.htm
For numbers 1-100, console.log "Fizz" if the number is divisible by 2, "Buzz" if divisible by 3, "Fizz Buzz" if divisible by 2 and 3, or the number if not divisible by neither 2 nor 3.
for (var i = 1; i <= 100; i++) { if (i % 2 == 0 && i % 3 == 0) { console.log ("Fizz Buzz"); } else if (i % 2 == 0) { console.log ("Fizz"); } else if (i % 3 == 0) { console.log ("Buzz"); } else { console.log (i); } }
What are fundamentals that a developer should consider when working to wire up model binding correctly?
having the corresponding properties in html <input> tags nested in <form> tags ensure that the "name" attribute matches the property in the model
What are the basic elements that exist in all HTML pages between the start and closing <html> tags
head body
What are the .NET objects and classes used to communicate and execute commands at the database?
http:www.csharp-station.com/Tutorial/AdoDotNet/lesson01 The SqlConnection Object The SqlCommand Object The SqlDatareader Object The DataSet Object The SqlDataAdapter Object The SqlParameter Object
Write the same add function in C#
https://dotfiddle.net/JIVKQk public class Program { public static void Main() { Console.WriteLine("Hello World"); int sum = Add(1,2,5); Console.WriteLine(sum); } public static int Add(int a, int b, int? c = null) { int x = a + b + (c ?? 0); return x; } }
Entity Framework
is an Object/Relational Mapping (ORM) framework that enables developers to work with relational database. It enabling developers to deal with data as objects and properties. Using the Entity Framework, developers issue queries using LINQ, then retrieve and manipulate data as strongly typed objects using C#. It eliminates the need for most of the data-access code that developers usually need to write. A good tutorial with very detailed step-by-step example: http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application
What is jQuery? Is it required to build HTML pages? Is it required to build interactivity into your web pages?
jQuery - jQuery is a concise and fast Javascript library that can be used to simplify event handling, HTML document traversing, Ajax interactions and animation for speedy website development. No, not required for inactivity
How would you declare an array in JavaScript? In C#?
javascript: var x = new Array(); --or-- var x = [1,2,3]; C#: string[] x = new string[3]; (*means create an array with 3 items)
What is a Sql Server Stored Procedure?
prepared SQl code that you save to perform repetitive tasks or to perform database operations used in conjuction with web applications.
How many of each can one table have?
primary key: one foreign key: Microsoft say: "Although a table can contain an unlimited number of FOREIGN KEY constraints, the recommended maximum is 253. Depending on the hardware configuration hosting SQL Server, specifying additional FOERIGN KEY constraints may be expensive for the query optimizer to process"
give an example of a Raw ADO Command?
private void showMeDaMoney() { SqlConnection conn = new SqlConnection("connect string in here"); //Instantiate a SQLConnection Object by using new instance declaration conn.Open(); //open the connection SqlCommand cmd = conn.CreateCommand(); //add CreateCommand to the connection cmd.CommandText = "stored proc name"; //add the stored procedure name cmd.CommandType = CommandType.StoredProcedure; //declare the SQL Command Type cmd.Parameters.AddWithValue("@nameofParam", new object()); // Add each parameter and the respective values to the cmd IDatareader reader = cmd.Executereader(); //Instantiate the reader (using IDatareader interface), to get query results while(reader.read()) { //read data while there is a data to be read } conn.Close(); //have a nice day, close connection }
Write out the .Net class for that Contact object in the previous question.
public class Contact { public string FirstName {get; set;} public string LastName {get; set;} public int Age {get; set;} public Contact[ ] Reports {get; set;} } Contact Bob = new contact();
What would you have to do to make this model report as "invalid" in such case?
public class EmployeeController : ApiController { public HttpResponseMessage Post(employee emp) if( !ModelState.IsValid) { //the code would execute inside this part of the if statement when the data being sent over is not valid. //if is a convention to send back the ModelState property of the Controller in this situation as it will have your error message //that you defined in your DataAnnotation attributes return Request.CreateErrorResponse(HttpStatusCode.OK, response); } } See https://sabiola.atlassian.net/wiki/display/TTs/Server+Side+validation+101
How do you declare a variable in C#?
state its type first
What is Model Binding? What is it important?
the ASP.NET MVC framework provides the model binding that greatly simplifies the process of data type conversion and mapping the input values to properties. The framework retrieves the data, maps data to object properties, validates the data and passes the model object to the controller as parameter. Model binding creates and populates the objects that the controller actions require. Model binding retrieves data from requests, populates controller action parameters, takes care of the property mapping and type casting typically involved in working with ASP.NET request data.
Write out JavaScript function that accepts two numbers, adds these numbers and returns the result.
var add = function(a, b) { var x = a + b; return x; }
Adjust the Add function from the previous answer to accept an optional third parameter and to throw an error if it is not passed at least two arguments.
var add = function(a, b, c){ if(a == null || b == null ) { throw new Error("Must provide at least two arguments"); } var x = a + b + ( c || 0 ); return x; }
Write the function that outputs the Fibonacci numbers:
var fibonacci = function() { var a =0; var b=1; console.log(a); console.log(b); var x = a+b; while (x<= 100) { console.log(x); a=b; b=x; x=a+b; } }
SOME RANDOM SAMPLE JAVASCRIPT FUNCTIONS
var meltastic = { common: {} }; meltastic.common.getQueryParam = function(param) { var query = window.location.search.substring(1); var vars = query.split("&"); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split("="); if (pair[0] == param) { return pair[1]; } } return (false); };
How do you declare a new object in JavaScript?
var x = {key: value, key: value}; --or-- var x = new Object();
Write out the JSON for the following Contact object: Bob Smith is 30 years old and has two direct reports. They are Sally Smith, 30 y/o and Jane Doe 34 y/o
{ "firstName": "Bob", "lastName": "Smith", "age": 30 "reports": [ { "firstName": "Jane", "lastName": "Doe", "age": 34 } ] }