Sie sind auf Seite 1von 28

Programming questions

Uputstvo: Dodati vae odgovore KAO KOMENTAR.


https://docs.google.com/document/d/1kYECUdstl6Z_J9L1GwYgLq0t5JAsWpDwVicO33UMRA/edit?usp=sharing

Sadraj
Object oriented programming
Classes and objects?
Encapsulation?
Inheritance?
Abstract class?
Interface?
Polymorphism?
Overloading?
Difference between stack and heap memory
Virtual functions
Class access modifiers
Difference between pass by value and pass by reference
Composition and Aggregation
Software design patterns
Singleton
Command
Bridge
Composite
Proxy
Mediator
Strategy
Data Types
Single linked list
Doubly linked list
HashMap
Set
Dictionary
Tuple
Stack
Dequeue
Queue
XML
XSLT
xQuery
xPath
HTML
What is HTML
Most used HTML tags:
New HTML 5 elements
Regular Expression

Select href attribute value from link


Positive lookahead
Negative lookahead
MySQL
Create database
Create table
Select from table
Aggregate functions
Views
Triggers
Order of query execution
Temporary tables
Table locking
What is ACID
Atomicity
Consistency
Isolation
Durability
What are dirty reads
What are dirty writes
Differences between most common storage engines
Transactions
Web app security
What is XSS and how to prevent
What is Sql Injection and how to prevent
What is Cookie Injection and how to prevent
Path Disclosure
What is CSRF and how to prevent
Denial of Service
What is session hijacking and how to prevent
What is session fixation and how to prevent
Overposting
Web development
JRE
JDK
Java Servlets
MVC
POST and GET difference
HTTP
Parallel processing
Threads
Thread synchronization
Thread Pool
Hibernate

ORM
ORM parts and levels
Hibernate xml mapping file
Hibernate configuration
Hibernate Core Interfaces
Session Interface
Hibernate comunication with RDBMS
HQL
Maping Java Objects with Database tables
jQuery
Closure in JS
Classes in JS
Select by element id
Select by element class
Relationship selectors
nTH selector
DOM ready vs DOM load
Sorting by custom function
C#
Data Types
Delegates
Lambda Expressions
Event handlers

Object oriented programming


Classes and objects?
A class is a construct that enables you to create your own custom types by grouping together
variables of other types, methods and events. A class is like a blueprint. It defines the data and
behavior of a type. An instance is a specific object built from a specific class. It is assigned to
a reference variable that is used to access all of the instance's properties and methods. When
you make a new instance the process is called instantiation and is typically done using the new
keyword.

Encapsulation?
Encapsulation is a strategy used as part of abstraction. Encapsulation refers to the state of
objects - objects encapsulate their state and hide it from the outside; outside users of the class
interact with it through its methods, but cannot access the classes state directly. So the class
abstracts away the implementation details related to its state.

Inheritance?

The Inheritance is ability of a new class to be created, from an existing class by extending it.
Inheritance comes from the fact that the subclass (the newly created class) contains the
attributes and methods of the parent class. The main advantage of inheritance is the ability to
define new attributes and new methods for the subclass which are then are used together with
the inherited attributes and methods.

Abstract class?
Abstract classes, which declared with the abstract keyword, cannot be instantiated. It can only
be used as a super-class for other classes that extend the abstract class. Abstract class is the
concept and implementation gets completed when it is being realized by a subclass. Subclass
must override all its abstract methods/properties and may override virtual methods/properties.

Interface?
Interfaces are similar to classes but they can not have state or implementation. This means they
can only contain method prototypes (no implementation, just method signature). An interface
act as a contract between a class and the outside world. When a class implements an interface,
it promises to provide the behavior published by that interface (implement interface methods
behaviour).

Polymorphism?
Polymorphism is a concept in object oriented programming in which classes have different
functionality while sharing a common interface. Code working with the different classes does not
need to know which class it is using since theyre all used the same way.

Overloading?
Overloading is a concept where within one class there can be one or more methods with
the same name, that differ only on number or types of their parameters. This way, there can
be a group of methods that have the same name, and similar functionality within one class.
Example of overloading methods can be DrawRectangle(int left, int top, int bottom, int right) and
DrawRectangle(Point topLeft, Point bottomRight).
http://stackoverflow.com/questions/154577/polymorphism-vs-overriding-vs-overloading/
154939#154939

Difference between stack and heap memory


The stack is the memory set aside as scratch space for a thread of execution. When a function
is called, a block is reserved on the top of the stack for local variables and some bookkeeping
data. When that function returns, the block becomes unused and can be used the next time
a function is called. The stack is always reserved in a LIFO order; the most recently reserved
block is always the next block to be freed. This makes it really simple to keep track of the stack;
freeing a block from the stack is nothing more than adjusting one pointer.
The heap is memory set aside for dynamic allocation. Unlike the stack, there's no enforced
pattern to the allocation and deallocation of blocks from the heap; you can allocate a block at

any time and free it at any time. This makes it much more complex to keep track of which parts
of the heap are allocated or free at any given time; there are many custom heap allocators
available to tune heap performance for different usage patterns.

Virtual functions
A virtual function provides a default implementation and it can exist on either an abstract class
or a non-abstract class. It provides the functionality that may or may not be good enough for the
child class. So if it is good enough, use this method, if not, then override me, and provide your
own functionality.. When calling the function on the instance of the subclass it will call either
function declared in subclass (if it has overridden it) or in the parent class.

Class access modifiers


All types and type members have an accessibility level, which controls whether they can be
used from other code in your assembly or other assemblies. Some of class access modifiers
are: public, private, protected, internal.

Difference between pass by value and pass by reference


Pass by value means use a copy of the original value stored in memory - ie allocate some more
memory, copy the value in there and use that memory for the duration of the function. Thus, the
original variable isn't affected by the function.
Pass by reference means use the actual memory storing the value - so if the function changes
the value then the change is immediate and preserved when the function exits.

Composition and Aggregation


http://www.c-sharpcorner.com/UploadFile/pcurnow/compagg07272007062838AM/
compagg.aspx
Inheritance, as many agree, gives us an "is-a" relationship between parent and subclass.
Composition gives us a "part-of" relationship, and aggregation gives us "has-a" relationship.
That means that after a parent class of a composition relationship gets destroyed, subclass
also cease to exist. On the other hand after a parent class of an aggregation relationship gets
destroyed, subclass doesn't cease to exist.

Software design patterns


Singleton
The singleton pattern is one of the simplest design patterns and it ensures that a class has only
one instance, and provides a global point of access to it.
http://sourcemaking.com/design_patterns/singleton

Command
Command decouples the object that invokes the operation from the one that knows how to
perform it. It is mostly used to enable undoable operations.
http://sourcemaking.com/design_patterns/command

Bridge
The bridge pattern is a design pattern used in software engineering which is meant to "decouple
an abstraction from its implementation so that the two can vary independently".The bridge uses
encapsulation, aggregation, and can use inheritance to separate responsibilities into different
classes.
When a class varies often, the features of object-oriented programming become very useful
because changes to a program's code can be made easily with minimal prior knowledge about
the program. The bridge pattern is useful when both the class as well as what it does vary
often. The class itself can be thought of as the implementation and what the class can do as the
abstraction. The bridge pattern can also be thought of as two layers of abstraction.
http://sourcemaking.com/design_patterns/bridge

Composite
Composite objects are objects that contain other objects. The Composite pattern composes
objects into tree structures and lets clients treat individual objects and compositions uniformly.
Ie. complex shape object can contain many different shapes inside. Each shape (complex and
simple) will have a draw method. Composite pattern inside ComplexShape will inside its Draw
method call Draw function of all simple shapes contained within.
http://sourcemaking.com/design_patterns/composite

Proxy
Provide a surrogate or placeholder for another object to control access to it.
http://sourcemaking.com/design_patterns/proxy

Mediator
Define an object that encapsulates how a set of objects interact. Mediator promotes loose
coupling by keeping objects from referring to each other explicitly, and it lets you vary their
interaction independently.
http://sourcemaking.com/design_patterns/mediator

Strategy
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy
lets the algorithm vary independently from clients that use it.

Data Types
Single linked list
Type of list. In a singly linked list each node in the list stores the contents of the node and a
pointer or reference to the next node in the list. It does not store any pointer or reference to the
previous node.

Doubly linked list

Linked data structure that consists of a set of sequentially linked records called nodes. Each
node contains two fields, called links, that are references to the previous and to the next node
in the sequence of nodes. Nodes contain data structures, that is any primitive type or complex
type (object, structure)

HashMap
Hashed Associative Container that associates objects of type Key with objects of type Data.
Hash_map is a Pair Associative Container, meaning that its value type is pair<const Key,
Data>. It is also a Unique Associative Container, meaning that no two elements have keys that
compare equal using EqualKey.

Set
Abstract data structure that can store certain values, without any particular order, and no
repeated values.

Dictionary
Tuple
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.

Stack
Abstract data type or collection in which the principal (or only) operations on the collection are
the addition of an entity to the collection, known as push and removal of an entity.

Dequeue
Abstract data structure that implements a queue for which elements can only be added to or
removed from the front (head) or back (tail).

Queue
Abstract data type or collection in which the entities in the collection are kept in order and the
principal (or only) operations on the collection are the addition of entities to the rear terminal
position.

XML
XSLT
Is a language for transforming XML documents into other XML documents, or other objects
such as HTML for web pages, plain text or other outputs.

xQuery

Query and functional programming language that is designed to query and transform collections
of structured and unstructured data, usually in the form of XML.

xPath
Is a query language for selecting nodes from an XML document. In addition, XPath may be
used to compute values (e.g., strings, numbers, or Boolean values) from the content of an XML
document. The XPath is based on a tree representation of the XML document, and provides the
ability to navigate around the tree, selecting nodes by a variety of criteria.

HTML
What is HTML
HTML is a language for describing web pages. HTML is written in the form of HTML elements
consisting of tags enclosed in angle brackets (like <html>). HTML tags most commonly come in
pairs like <h1>and </h1>, although some tags represent empty elements and so are unpaired,
for example <img>. The first tag in a pair is the start tag, and the second tag is the end tag (they
are also called opening tags and closing tags).
The purpose of a web browser is to read HTML documents and compose them into visible or
audible web pages. The browser does not display the HTML tags, but uses the tags to interpret
the content of the page. HTML describes the structure of a website semantically along with cues
for presentation, making it a markup language rather than a programming language.

Most used HTML tags:


<html>. . . </html>
The entire HTML document.
<head> . . . </head>
The head, or prologue, of the HTML document.
<body> . . . </body>
All the other content in the HTML document.
<title> . . . </title>
The title of the document
<h1> . . . </h1>
First-level heading large text size
<h2> . . . </h2>
Second-level heading
<p> . . . (</p>)
Paragraph Hitting a return in the HTML file will not make a new
paragraph when the file is viewed. You need to use this tag to make a new paragraph.
<br>
Line Break This tag will show a blank line.
<hr>
Horizontal Rule Creates a horizontal line on the page.
<a href=> . . . </a>
Link (a=Anchor) links the current HTML file to another file.
Example: <a href="menu.html">Go back to Main Menu</a> This will display the file which is
named in the quotes.
<img src="image.gif">Inline Image Put the name of the graphic (.gif or .jpg) in the quotes.

New HTML 5 elements


<canvas>
<audio>
<source>
<track>
<video>

Defines graphic drawing using JavaScript


Defines sound or music content
Defines sources for <video> and <audio>
Defines tracks for <video> and <audio>
Defines video or movie content

<datalist>
<article>
<aside>
<details>
<dialog>
<figcaption>
<figure>
listings, etc.
<footer>
<header>
<main>
<mark>
<menuitem>
menu
<meter>
<nav>
<progress>
<section>
<summary>
<time>

Defines pre-defined options for input controls


Defines an article in the document
Defines content aside from the page content
Defines additional details that the user can view or hide
Defines a dialog box or window
Defines a caption for a <figure> element
Defines self-contained content, like illustrations, diagrams, photos, code
Defines a footer for the document or a section
Defines a header for the document or a section
Defines the main content of a document
Defines marked or highlighted text
Defines a command/menu item that the user can invoke from a popup
Defines a scalar measurement within a known range (a gauge)
Defines navigation links in the document
Defines the progress of a task
Defines a section in the document
Defines a visible heading for a <details> element
Defines a date/time

Regular Expression
http://www.regular-expressions.info/
https://www.debuggex.com/

Select href attribute value from link


If link is <a href="select this">Some text</a>
(?<=href=").*(?=")

Positive lookahead
Matches a group after main expression but doesnt include it in result.

Negative lookahead
Negative lookahead is used if you want to match something not followed by something else.

MySQL
Create database
CREATE DATABASE dbZveen;

Create table
CREATE TABLE tblStaff (id INT, name VARCHAR(15), lastname VARCHAR(30), address
VARCHAR(50), sex CHAR(1), birth DATE);

Select from table


SELECT id, name, lastname, address, sex, birth FROM tblStaff;

Aggregate functions
Aggregate functions are used to calculate data based on record grouping
http://www.mysqltutorial.org/mysql-aggregate-functions.aspx
SELECT COUNT(sex) FROM tblStaff GROUP BY sex;
Above count number of records belonging to specific sex

Views
Views are stored queries that when invoked produce a result set. A view acts as a virtual table.
// Creates view
CREATE VIEW MaleStaff AS
SELECT * FROM tblStaff
WHERE sex = m;
// Shows only male records from tblStaff
SELECT * FROM MaleStaff;

Triggers
A trigger is a special kind of stored procedure that automatically executes when an event occurs
in the database server. Triggers execute when a user tries to modify data through INSERT,
UPDATE, or DELETE statements on a table or view. Triggers also respond to Transact-SQL
CREATE, ALTER, and DROP statements and some other system events like LOGIN.
// Triger which updates another tbl after insertion in tblStaff

CREATE TRIGGER update_staff_count AFTER INSERT ON tblStaff


FOR EACH ROW BEGIN
UPDATE tblStaffCount
SET numberOfStaff = numberOfStaff + 1;
END;

Order of query execution


The following steps show the logical processing order - order which parts of sql query are
executed first. Results are stored in virtual tables and accessible on the following processings.
http://msdn.microsoft.com/en-us/library/ms189499.aspx
1. FROM

2. ON
3. JOIN
4. WHERE
5. GROUP BY
6. WITH CUBE or WITH ROLLUP
7. HAVING
8. SELECT
9. DISTINCT
10. ORDER BY
11. TOP

Temporary tables
You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible
only to the current session, and is dropped automatically when the session is closed. It behaves
like normal tables.

Table locking
MySQL enables client sessions to acquire table locks explicitly for the purpose of cooperating
with other sessions for access to tables, or to prevent other sessions from modifying tables
during periods when a session requires exclusive access to them.

What is ACID
In the context of transaction processing, the acronym ACID refers to the four key properties of
a transaction: atomicity, consistency, isolation, and durability. It is a set of properties that
guarantee that database transactions are processed reliably.

Atomicity
Atomicity requires that each transaction is "all or nothing": if one part of the transaction fails,
the entire transaction fails, and the database state is left unchanged. An atomic system must
guarantee atomicity in each and every situation, including power failures, errors, and crashes.

Consistency
The consistency property ensures that any transaction will bring the database from one valid
state to another. Any data written to the database must be valid according to all defined rules ie.
that string isnt written into number column.

Isolation
The isolation property ensures that the concurrent execution of transactions results in a system
state that would be obtained if transactions were executed serially, i.e. one after the other.

Durability
Durability means that once a transaction has been committed, it will remain so, even in the
event of power loss, crashes, or errors.

What are dirty reads


In some concurrency modes you could query the same data twice within one transaction and
get different results.

What are dirty writes


Means to overwrite a changes of an entity in database while in Optimistic Concurrency
Dirty writes occur in optimistic concurrency model, after a user receives a value from the
transaction, and another user modifies information of that transaction before the first user has
attempted to.

Differences between most common storage engines


MyISAM and InnoDB are two most popular storage engines
MyISAM

Innodb

Not *ACID compliant and nontransactional

*ACID compliant and hence fully transactional with


ROLLBACK and COMMIT and support for Foreign Keys

MySQL 5.0 Default Engine

Rackspace Cloud Default Engine

Offers Compression

Offers Compression

Requires full repair/rebuild of indexes/


tables

Auto recovery from crash via replay of logs

Changed Db pages written to disk


instantly

Dirty pages converted from random to sequential before


commit and flush to disk

No ordering in storage of data

Row data stored in pages in PK order

Table level locking

Row level locking

Transactions
A transaction is a unit of work that is performed against a database. Transactions are units or
sequences of work accomplished in a logical order and each unit of work must be successful for
whole transaction to succeed. Transactions usually consists of many SQL commands that need
to be executed together and if everything is successful COMMIT command applies changes to
the database.

Web app security


What is XSS and how to prevent
Cross-site scripting (XSS) is a vulnerability found in web applications. It enables attackers
to use the software flaw to inject scripts into pages. Example is search page where software
doesnt sanitize the input and displays the search term on page. Attacker could create a search
term with script that will send the victims cookie for that site (containing login) to the attacker. He

will send the malicious link to victim and he clicks it to access the page, when the page loads,
the script will execute and send victims cookie to attacker.
Prevention is done by sanitizing input, removing javascript tags and following general guidelines
for sanitizing user input.

What is Sql Injection and how to prevent


SQL injection is software flaw when user input is directly appended to the SQL command and
sent to server without previous sanitation. This enables the attacker to change original intent of
SQL command, ie. instead of password validation on login to allow login as if the password is
correct.
Prevention is done by sanitizing user input, escaping SQL control characters and by not sending
plain SQL to server (using the functions for query creation and setting parameters).

What is Cookie Injection and how to prevent


Attacker access the site and gets his cookie. He later tricks user into going to the target site
(maybe through proxy filtering) and set his cookie in victims request. If the victim logs into the
site server associates that forged cookie is logged in. This means that attacker is also logged in
as he is having exactly the same cookie.
Prevention is that for any security related event regenerate the cookie. In previous example
when user has logged in he will receive new cookie (which is logged in) and attacker couldnt
login as his cookie is invalid.

Path Disclosure
Path Disclosure (PD) is the revelation of the full operating path of a vulnerable script. the PD
bug is executed by injecting unexpected characters into certain web site parameters. the script
doesn't expect the injected character and returns an error that includes information about the
error along with the script path. Full path disclosure should be prevented by making sure that
the administrators are the only ones who can see error logs, not the page viewers.

What is CSRF and how to prevent


A Cross Site Request Forgery (CSRF) Attack is a type of web application vulnerability where
the victim unintentionally runs a script in their browser that takes advantage of their logged in
session to a particular site. CSRF attacks can be performed over GET or POST requests.
A prevention measure could be the implementation and inclusion of tokens in a users
(current) session. Tokens are long cryptographic values that are difficult to guess. These will
be generated when a users session begins and will be associated with this particular users
session. This challenge token will be included in each request, which will be used by the server
side to verify the legitimacy of the end-users request.

Denial of Service
Denial of Service (DoS) attack is an attempt to make machine or network resource disfunctional
(unavailable to its users) usually by sending large amount of packet requests so that target
cannot respond to legitimate traffic. Those attacks usually lead to server overload, which either
consume all server resources or force a server restart. Prevention is to use smart firewalls.

What is session hijacking and how to prevent


Session hijacking is the exploitation of a valid computer session - sometimes also called a
session key - to gain unauthorized access to information of services in a computer system,
usually by packet sniffing. It is used to refer to a cookie theft, used to authenticate a user on
remote server. Best prevention method is data encryption and regenerating session id on
security events like login or access to sensitive data.

What is session fixation and how to prevent


Session fixation attacks forces victim to use predefined (attackers) session identifier (SID).
When victim logs in, attacker is also gained access to the system as he know what SID is the
victim using. Prevention is to regenerate session id on security events.

Overposting
In web apps when users submits a form he passes data on the server. Server code can
populate object with this data as a mass assignment which means if data received from the
client matches property of an object then it will assign value of the data to that object. Problem
is when ie. user is creating account he can overpost some fields with form like IsAdmin=true,
Admin=true and mass assignment will apply that to the object and persist it to database giving
that user admin privileges.
Prevention is to use whitelisting of parameters when using mass assignments.

Web development
JRE
Java Runtime Environment. It is basically the Java Virtual Machine where your Java programs
run on. It also includes browser plugins for Applet execution.

JDK
It's the full featured Software Development Kit for Java, including JRE, and the compilers and
tools (like JavaDoc, and Java Debugger) to create and compile programs.
Usually, when you only care about running Java programs on your browser or computer you
will only install JRE. It's all you need. On the other hand, if you are planning to do some Java
programming, you will also need JDK.

Java Servlets
Java Servlet is server side technologies to extend the capability of web servers by providing
support for dynamic response and data persistence.
The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing our
own servlets.
All servlets must implement the javax.servlet.Servlet interface, which defines servlet lifecycle
methods. When implementing a generic service, we can extend the GenericServlet class
provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet()
and doPost(), for handling HTTP-specific services.

Most of the times, web applications are accessed using HTTP protocol and thats why we mostly
extend HttpServlet class. Servlet API hierarchy is shown in below image.

MVC
MVC is an architectural pattern which separates the representation and user interaction. Its
divided into three broader sections, Model, View, and Controller. Below is how each one of them
handles the task.
The View is responsible for the look and feel.
Model represents the real world object and provides data to the View.
The Controller is responsible for taking the end user request and loading the appropriate
Model and View.

There are six broader events which occur in MVC application life cycle below diagrams
summarize it.

Any web application has two main execution steps first understanding the request and
depending on the type of the request sending out appropriate response. MVC application life
cycle is not different it has two main phases first creating the request object and second sending
our response to the browser.
Creating the request object: -The request object creation has four major steps. Below is the
detail explanation of the same.
Step 1 Fill route: - MVC requests are mapped to route tables which in turn specify which
controller and action to be invoked. So if the request is the first request the first thing is to fill the
route table with routes collection. This filling of route table happens in the global.asax file.
Step 2 Fetch route: - Depending on the URL sent UrlRoutingModule searches the route table
to create RouteData object which has the details of which controller and action to invoke.
Step 3 Request context created: - The RouteData object is used to create the
RequestContext object.
Step 4 Controller instance created: - This request object is sent to MvcHandler instance
to create the controller class instance. Once the controller class object is created it calls the
Execute method of the controller class.
Creating Response object: - This phase has two steps executing the action and finally
sending the response as a result to the view.
There are two big benefits of MVC:
Separation of concerns is achieved as we are moving the code-behind to a separate
class file. By moving the binding code to a separate class file we can reuse the code to a
great extent.
Automated UI testing is possible because now the behind code (UI interaction code) has
moved to a simple .NET class. This gives us opportunity to write unit tests and automate
manual testing.
MVC is an evolution of a three layered traditional architecture. Many components of the three
layered architecture are part of MVC. So below is how the mapping goes:

Functionality

Three layered
architecture

Look and Feel

User interface

View

UI logic

User interface

Controller

Business
validations

logic

/ Middle layer

tiered Model view controller architecture

Model

Request is first sent to

User interface

Controller

Accessing data

Data access layer

Data Access Layer

POST and GET difference

GET is a safe method (idempotent) where POST is non-idempotent method.


We can send limited data with GET method and its sent in the header request URL
whereas we can send large amount of data with POST because its part of the body.
GET method is not secure because data is exposed in the URL and we can easily
bookmark it and send similar request again, POST is secure because data is sent in
request body and we cant bookmark it.

GET is the default HTTP method whereas we need to specify method as POST to send
request with POST method.
Hyperlinks in a page uses GET method.

HTTP
Hypertext Transfer Protocol (HTTP) is a networking protocol for distributed, collaborative,
hypermedia information systems. HTTP is the foundation of data communication for the World
Wide Web.
The standards development of HTTP has been coordinated by the Internet Engineering Task
Force (IETF) and the World Wide Web Consortium, culminating in the publication of a series of
Requests for Comments (RFCs), most notably RFC 2616 (June 1999), which defines HTTP/1.1,
the version of HTTP in common use
HTTP is a stateless protocol. A stateless protocol does not require the server to retain
information or status about each user for the duration of multiple requests. For example,
when a web server is required to customize the content of a web page for a user, the web
application may have to track the user's progress from page to page. A common solution is the
use of HTTP cookies. Other methods include server side sessions, hidden variables (when the
current page is a form), and URL-rewriting using URI-encoded parameters, e.g., /index.php?
session_id=some_unique_session_code.

Parallel processing
Threads
In computer science, a thread of execution is the smallest unit of processing that can be
scheduled by an operating system. It generally results from a fork of a computer program
into two or more concurrently running tasks. The implementation of threads and processes
differs from one operating system to another, but in most cases, a thread is contained inside
a process. Multiple threads can exist within the same process and share resources such as
memory, while different processes do not share these resources. In particular, the threads of
a process share the latter's instructions (its code) and its context (the values that its variables
reference at any given moment).
To give an analogy, multiple threads in a process are like multiple cooks reading off the
same cookbook and following its instructions, not necessarily from the same page.
On a single processor, multithreading generally occurs by time-division multiplexing (as
in multitasking): the processor switches between different threads. This context switching
generally happens frequently enough that the user perceives the threads or tasks as running at
the same time. On a multiprocessor or multi-core system, the threads or tasks will actually run

at the same time, with each processor or core running a particular thread or task.
https://www.princeton.edu/~achaney/tmve/wiki100k/docs/
Thread_%28computer_science%29.html
// Create the thread object, passing in the some method in c#
// via a ThreadStart delegate. This does not start the thread.
Thread oThread = new Thread(new ThreadStart(method));
// Start the thread
oThread.Start();

Thread synchronization
When we have multiple threads that share data, we need to provide synchronized access to the
data. We have to deal with synchronization issues related to concurrent access to variables and
objects accessible by multiple threads at the same time. This is controlled by giving one thread
a chance to acquire a lock on the shared resource at a time.
Thread can be synchronized through the usage of Critical Section, MUTEX, Semaphore or
Event objects
Treads can be, through the usage of following methods put in a certain states that are
mentioned in States of a Thread section.
Methods

Suspend() -> Suspends the execution of a thread till Resume() is called on that.
Resume() -> Resumes a suspended thread. Can throw exceptions for bad state of the
thread.
Sleep() -> A thread can suspend itself by calling Sleep(). Takes parameter in form of
milliseconds. We can use a special timeout 0 to terminate the current time slice and give
other thread a chance to use CPU time
Join()-> Called on a thread makes other threads wait for it till it finishes its task.

States of a Thread
States of a thread can be checked using ThreadState enumerated property of the Thread object
which contains a different value for different states.
Aborted -> Aborted already.
AbortRequested -> Responding to an Abort() request.
Background -> Running in background. Same as IsBackground property.
Running -> Running after another thread has called the start()
Stopped -> After finishing run() or Abort() stopped it.
Suspended -> Suspended after Suspend() is called.
Unstarted -> Created but start() has not been called.

WaitSleepJoin -> Sleep()/Wait() on itself and join() on another thread. If a thread


Thread1 calls sleep() on itself and calls join() on the thread Thread2 then it enters
WaitSleepJoin state. The thread exists in this state till the timeout expires or another
thread invokes Interrupt() on it.
It is wise to check the state of a thread before calling methods on it to avoid
ThreadStateException.

This picture describes in detail about the states of the thread [ Collected from Thinking in C#
by Bruce Eckel ]
Properties of a Thread

Thread.CurrentThread -> Static method gives the reference of the thread object which is
executing the current code.
Name -> Read/Write Property used to get and set the name of a thread
ThreadState -> Property used to check the state of a thread.
Priority -> Property used to check for the priority level of a thread.
IsAlive -> Returns a Boolean value stating whether the thread is alive or not.
IsBackground -> Returns a Boolean value stating the running in background or
foreground.

PriorityLevels of Thread
Priority levels of thread is set or checked by using an enumeration i.e. ThreadPriority. The valid
values are for this enumeration are;

Highest
AboveNormal
Normal
BelowNormal
Lowest

Thread Pool
A thread pool is a group of pre-instantiated, idle threads which stand ready to be given work.
These are preferred over instantiating new threads for each task when there is a large number
of short tasks to be done rather than a small number of long ones. This prevents having to incur
the overhead of creating a thread a large number of times.
Implementation will vary by environment, but in simplified terms, you need the following:
A way to create threads and hold them in an idle state. This can be accomplished by
having each thread wait at a barrier until the pool hands it work. (This could be done with
mutexes as well.)
A container to store the created threads, such as a queue or any other structure that has
a way to add a thread to the pool and pull one out.
A standard interface or abstract class for the threads to use in doing work. This might
be an abstract class called Task with an execute() method that does the work and then
returns.
When the thread pool is created, it will either instantiate a certain number of threads to make
available or create new ones as needed depending on the needs of the implementation.
When the pool is handed a Task, it takes a thread from the container (or waits for one to
become available if the container is empty), hands it a Task, and meets the barrier. This causes
the idle thread to resume execution, invoking the execute() method of the Task it was given.
Once execution is complete, the thread hands itself back to the pool to be put into the container
for re-use and then meets its barrier, putting itself to sleep until the cycle repeats.

Hibernate
Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that
allows you to map plain old Java objects to relational database tables using (XML) configuration
files.Its purpose is to relieve the developer from a significant amount of relational data
persistence-related programming tasks.
http://www.javabeat.net/hibernate-interview-questions/

ORM
ORM stands for object/relational mapping. ORM is the automated persistence of objects in a
Java application to the tables in a relational database.

ORM parts and levels

An ORM solution consists of the followig four pieces:


API for performing basic CRUD operations
API to express queries refering to classes
Facilities to specify metadata
Optimization facilities : dirty checking,lazy associations fetching
The ORM levels are:
Pure relational (stored procedure.)
Light objects mapping (JDBC)
Medium object mapping
Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)

Hibernate xml mapping file


Hibernate mapping file tells Hibernate which tables and columns to use to load and store
objects. Typical mapping file look as follows:

Hibernate configuration
The most common methods of Hibernate configuration are:
Programmatic configuration
XML configuration (hibernate.cfg.xml)

Hibernate Core Interfaces

The five core interfaces are used in just about every Hibernate application. Using these
interfaces, you can store and retrieve persistent objects and control transactions.
Session interface
SessionFactory interface
Configuration interface
Transaction interface
Query and Criteria interfaces

Session Interface

The Session interface is the primary interface used by Hibernate applications. It is a singlethreaded, short-lived object representing a conversation between the application and the
persistent store. It allows you to create query objects to retrieve persistent objects.
Session session = sessionFactory.openSession();
Session interface role:
Wraps a JDBC connection
Factory for Transaction
Holds a mandatory (first-level) cache of persistent objects, used when navigating the
object graph or looking up objects by identifier

Session Factory
The Session interface is the primary interface used by Hibernate applications. It is a singlethreaded, short-lived object representing a conversation between the application and the
persistent store. It allows you to create query objects to retrieve persistent objects.
Session session = sessionFactory.openSession();
Session interface role:
Wraps a JDBC connection
Factory for Transaction
Holds a mandatory (first-level) cache of persistent objects, used when navigating the
object graph or looking up objects by identifier

Hibernate comunication with RDBMS


The general flow of Hibernate communication with RDBMS is :
Load the Hibernate configuration file and create configuration object. It will automatically
load all hbm mapping files
Create session factory from configuration object
Get one session from this session factory

Create HQL Query


Execute query to get list containing Java objects

HQL
Hibernate offers a query language that embodies a very powerful and flexible mechanism to
query, store, update, and retrieve objects from a database. This language, the Hibernate query
Language (HQL), is an object-oriented extension to SQL.
http://www.tutorialspoint.com/hibernate/hibernate_query_language.htm

Maping Java Objects with Database tables

First we need to write Java domain objects (beans with setter and getter).
Write hbm.xml, where we map java class to table and database columns to Java class
variables.

<hibernate-mapping>
<class name="com.test.User" table="user">
<property column="USER_NAME" length="255"
name="userName" not-null="true" type="java.lang.String"/>
<property column="USER_PASSWORD" length="255"
name="userPassword" not-null="true" type="java.lang.String"/>
</class>
</hibernate-mapping>

jQuery
jQuery is not a language, but it is a well written JavaScript code. As quoted on official jQuery
website, "it is a fast and concise JavaScript Library that simplifies HTML document traversing,
event handling, animating, and Ajax interactions for rapid web development."
In order to work with jQuery, you should be aware of the basics of JavaScript, HTML and CSS.
It was released in January 2006 at BarCamp NYC by John Resig.
jQuery is very compact and well written JavaScript code that increases the productivity of the
developer by enabling them to achieve critical UI functionality by writing very small amount of
code.
It helps to improve the performance of the application
It helps to develop most browser compatible web page
It helps to implement UI related critical functionality without writing hundreds of lines of
codes
It is fast

It is extensible jQuery can be extended to implement customized behavior


Other advantages of jQuery are:
No need to learn fresh new syntaxes to use jQuery, knowing simple JavaScript syntax is
enough
Simple and cleaner code, no need to write several lines of codes to achieve complex
functionality

Closure in JS
Classes in JS
Select by element id
$( "#myDiv" ) //expand

Select by element class


$( ".myDiv" ) // expand

Relationship selectors
$("div span:nth-child(2)") // expand or merge with nTH selecor

nTH selector
DOM ready vs DOM load
The document ready event executes already when the HTML-Document is loaded and the
DOM is ready, even if all the graphics havent loaded yet. If you want to hook up your events for
certain elements before the window loads, then $(document).ready is the right place.
$(document).ready(function() {
// executes when HTML-Document is loaded and DOM is ready
alert("document is ready");
});

The window load event executes a bit later when the complete page is fully loaded, including all
frames, objects and images. Therefore functions which concern images or other page contents
should be placed in the load event for the window or the content tag itself.
$(window).load(function() {
// executes when complete page is fully loaded, including all frames, objects and images
alert("window is loaded");
});

Sorting by custom function

C#
Data Types
In C#, variables are categorized into the following types:

Value types (bool, byte, char, decimal, double, float, int, long, short, ulong, ushort, uint
etc).
Reference types (object, string, dynamic)
Pointer types (*)

Delegates
Delegates are similar to pointers to functions. Delegates are used to pass methods as
arguments to other methods. Syntax for delegate declaration is:
delegate <return type> <delegate-name> <parameter list>

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.

Event handlers
To respond to an event, you define an event handler method in the event receiver. This method
must match the signature of the delegate for the event you are handling. In the event handler,
you perform the actions that are required when the event is raised, such as collecting user input
after the user clicks a button. To receive notifications when the event occurs, your event handler
method must subscribe to the event.
There are two types of event handlers:Static and Dynamic.
Static event handlers are in effect for the entire life of the class whose events they handle.
Dynamic event handlers are explicitly activated and deactivated during program execution,
usually in response to some conditional program logic. For example, they can be used if event
notifications are needed only under certain conditions or if an application provides multiple event
handlers and run-time conditions define the appropriate one to use.
Declaring an event To declare an event inside a class, first a delegate type for the event must
be declared, if none is already declared.

public delegate void ChangedEventHandler(object sender, EventArgs e);


The delegate type defines the set of arguments that are passed to the method that handles the
event. Multiple events can share the same delegate type, so this step is only necessary if no
suitable delegate type has already been declared.
Next, the event itself is declared.
public event ChangedEventHandler Changed;
Invoking an event Once a class has declared an event, it can treat that event just like a field
of the indicated delegate type. The field will either be null, if no client has hooked up a delegate
to the event, or else it refers to a delegate that should be called when the event is invoked.
Thus, invoking an event is generally done by first checking for null and then calling the event.
if (Changed != null)
Changed(this, e);
Hooking up to an event From outside the class that declared it, an event looks like a field, but
access to that field is very restricted. The only things that can be done are:
Compose a new delegate onto that field.
Remove a delegate from a (possibly composite) field.
This is done with the += and -= operators. To begin receiving event invocations, client code
first creates a delegate of the event type that refers to the method that should be invoked from
the event. Then it composes that delegate onto any other delegates that the event might be
connected to using +=.
// Add "ListChanged" to the Changed event on "List":
List.Changed += new ChangedEventHandler(ListChanged);
more on
http://www.codeproject.com/Articles/20550/C-Event-Implementation-Fundamentals-BestPractices

Das könnte Ihnen auch gefallen