Monday, October 25, 2010

C# Essentials

Some self explanatory C# fundamentals diagrams:
Introducing C#:

Data Types:

Operators and Control Flow:

Method and Parameters:

Classes:

Inheritance:

Interfaces:

Value Types:

Well-Formed Types:

Exception Handling:

Generics:

Delegates and Lambda Expressions:

Events:

Collection Interfaces with Standard Query Operators:

LINQ with Query Expressions:

Custom Collections:

Reflection, Attributes, and Dynamic Programming:

Multithreading:

Synchronization and More Multithreading Patterns:

Platform Interoperability and Unsafe Code:

The Common Language Infrastructure:

Friday, October 22, 2010

High Level Component of SQL Server Architecture

SQL Server is split into two main engines: the Relational Engine and the Storage engine.


The Relational Engine:
    The relational Engine is also sometimes call the query processor because its primary function is query optimization and execution. It contains a Command Parser to check query syntax and prepare query trees, a Query Optimizer that is arguably the crown jewel of any database system, and a Query Executor responsible for execution.
1. Command Parser:
The Command Parser’s role is to handle T-SQL language events. It first checks the syntax and returns any errors back to the protocol layer to send to the client. If the syntax is valid, then the next step is to generate a query plan or find an existing plan. A Query plan contains the details about how SQL Server is going to execute a piece of code. It is commonly referred to as an execution plan.
Plan Cache: Creating execution plans can be time consuming and resource intensive, so The Plan Cache, part of SQL Server’s buffer pool, is used to store execution plans in case they are needed later.
2. Query Optimizer:
    The Query Optimizer is one of the most complex and secretive parts of the product. It is what’s known as a “cost-based” optimizer, which means that it evaluates multiple ways to execute a query and then picks the method that it deems will have the lowest cost to execute. This “method” of executing is implemented as a query plan and is the output from the optimizer.
3. Query Executor:
    The Query Executor’s job is self-explanatory; it executes the query. To be more specific, it executes the query plan by working through each step it contains and interacting with the Storage Engine to retrieve or modify data.
The Storage Engine:
    The Storage engine is responsible for managing all I/O to the data, and contains the Access Methods code, which handles I/O requests for rows, indexes, pages, allocations and row versions, and a Buffer Manager, which deals with SQL Server’s main memory consumer, the buffer pool. It also contains a Transaction Manager, which handles the locking of data to maintain Isolation (ACID properties) and manages the transaction log.
1. Access Methods:
    Access Methods is a collection of code that provides the storage structures for data and indexes as well as the interface through which data is retrieved and modified. It contains all the code to retrieve data but it doesn’t actually perform the operation itself; it passes the request to the Buffer Manager.
2. Buffer Manager:
    The Buffer Manager manages the buffer pool, which represents the majority of SQL Server’s memory usage. If you need to read some rows from a page the
Buffer Manager will check the data cache in the buffer pool to see if it already has the page cached in memory. If the page is already cached, then the results are passed back to the Access Methods. If the page isn’t already in cache, then the Buffer Manager will get the page from the database on disk, put it in the data cache, and pass the results to the Access Methods.
Data Cache: The data cache is usually the largest part of the buffer pool; therefore, it’s the largest memory consumer within SQL Server. It is here that every data page that is read from disk is written to before being used.
3. Transaction Manager:
    The Transaction Manager has two components that are of interest here: a Lock Manager and a Log Manager.
The Lock Manager is responsible for providing concurrency to the data, and it delivers the configured level of isolation by using locks. The Access Methods code requests that the changes it wants to make are logged, and the Log Manager writes the changes to the transaction log. This is called Write-Ahead Logging.
The Protocol Layer:
When the protocol layer in SQL Server receives your TDS (Tabular Data Stream) packet, it has to reverse the work of the SNI at the client and unwrap the packet to find out what request it contains. The protocol layer is also responsible for packaging up results and status messages to send back to the client as TDS messages.
TDS (Tabular Data Stream) Endpoints: TDS is a Microsoft-proprietary protocol originally designed by Sybase that is used to interact with a database server.

Tuesday, September 21, 2010

Dynamic Programming


Dynamic Programming is method of solving complex problems by breaking them down into a series of overlapping sub-problems, and build up solutions to larger and larger sub-problems.
    It is a powerful design technique that can be used to solve problems of computational nature. And it is typically applied to optimization problems.

Keys of Dynamic Programming:
1. Optimal substructure
    An optimal solution to a problem (instance) contains optimal solutions to subproblems.
2. Overlapping subproblems
    A recursive solution contains a “small” number of distinct subproblems repeated many times.
3. Bottom Up Fashion
    Computing the solution in a bottom-up fashion to solve the problem.

Areas:
  • Bio-informatics
  • Control theory
  • Information theory
  • Operations research
  • Computer science: theory, graphics, AI, systems
Some famous dynamic programming algorithms:
  • Unix diff for comparing two files
  • Viterbi for hidden Markov models
  • Smith-Waterman for sequence alignment
  • Bellman-Ford for shortest path routing in networks
  • Cocke-Kasami-Younger for parsing context free grammars

Wednesday, August 11, 2010

HTML/XHTML Declaration

According to HTML standards, each HTML document requires a document type declaration. The "DOCTYPE" begins the HTML document and tells a validator which version of HTML to use in checking the document's syntax.
  • The doctype declaration should be the very first thing in an HTML document, before the <html> tag.
  • The doctype declaration is not an HTML tag; it is an instruction to the web browser about what version of the markup language the page is written in.
  • The doctype declaration refers to a Document Type Definition (DTD). The DTD specifies the rules for the markup language, so that the browsers can render the content correctly.
Document Type Definitions (DTD)
  • A DTD specifies the syntax of a web page in SGML(Standard Generalized Markup Language)
  • DTDs are used by SGML applications, such as HTML, to specify rules for documents of a particular type, including a set of elements and entity declarations
  • An XHTML DTD describes in precise, computer-readable language, the allowed syntax of XHTML markup
There are three DTDs:
  • STRICT : Use the strict DOCTYPE when you want really clean markup, free of presentational clutter. Use it together with CSS.
  • TRANSITIONAL : Use the transitional DOCTYPE when you want to still use HTML's presentational features.
  • FRAMESET : Use the frameset DOCTYPE when you want to use HTML frames.

Doctypes Available in the W3C Recommendations:
HTML 4.01 Strict
This DTD contains all HTML elements and attributes, but does NOT INCLUDE presentational or deprecated elements (like font). Framesets are not allowed.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
"http://www.w3.org/TR/html4/strict.dtd">

HTML 4.01 Transitional
This DTD contains all HTML elements and attributes, INCLUDING presentational and deprecated elements (like font). Framesets are not allowed.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">

HTML 4.01 Frameset 
This DTD is equal to HTML 4.01 Transitional, but allows the use of frameset content.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" 
"http://www.w3.org/TR/html4/frameset.dtd">

XHTML 1.0 Strict
This DTD contains all HTML elements and attributes, but does NOT INCLUDE presentational or deprecated elements (like font). Framesets are not allowed. The markup must also be written as well-formed XML.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

XHTML 1.0 Transitional
This DTD contains all HTML elements and attributes, INCLUDING presentational and deprecated elements (like font). Framesets are not allowed. The markup must also be written as well-formed XML.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

XHTML 1.0 Frameset
This DTD is equal to XHTML 1.0 Transitional, but allows the use of frameset content.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">

XHTML 1.1
This DTD is equal to XHTML 1.0 Strict, but allows you to add modules (for example to provide ruby support for East-Asian languages).
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

Thursday, July 8, 2010

SQL Server : Transform Columns into Rows

Suppose, we have the table “tblSample” with the following data.
SeqMonthNew Policy CountNew PremiumClaims RecordedClaims CostLoss Ratio
12010/06/011000100000.9566666.9866.66
22010/05/011100200000.91055555.9827.77
32010/04/011200300000.91544444.9814.81
42010/03/011300400000.92033333.988.33
52010/02/011400500000.92522222.984.44
62010/01/011500600000.93011111.981.85


The query to transform the Columns of this table to Rows:

SELECT   Seq
        ,ROW_NUMBER() OVER(PARTITION BY [Month] ORDER BY Seq) AS 'RowNumber'
        ,CONVERT(VARCHAR, [Month], 111) AS [Month], Title, aValue
INTO #temp
FROM
     (SELECT  Seq 
             ,[Month]
             ,[New Policy Count]
             ,[New Premium]          
             ,[Claims Recorded]    

             ,[Claims Cost] 
             ,[Loss Ratio]
      FROM tblSample) p
      UNPIVOT      
     (aValue FOR  Title IN ([New Policy Count],[New Premium],[Claims Recorded],[Claims Cost],[Loss Ratio]))
AS unpvt

DECLARE @SQLQuery     VARCHAR(MAX)
       ,@PivotColumns VARCHAR(MAX)

SET    @PivotColumns = ''
SELECT @PivotColumns = @PivotColumns+ '['+ [Month] +'],' FROM (SELECT
DISTINCT [Month] FROM #TEMP) a
SET    @PivotColumns = SUBSTRING(@PivotColumns, 1,LEN(@PivotColumns) - 1)

SET @SQLQuery = 'SELECT Title,' + @PivotColumns +
             'FROM (SELECT [Month], RowNumber, Title, aValue FROM #temp) s
              PIVOT (SUM(aValue) FOR [Month] IN ('
+ @PivotColumns + ')) p
              ORDER BY RowNumber'
EXEC (@SQLQuery)
DROP TABLE #temp
The final output looks like:
Title2010/01/012010/02/012010/03/012010/04/012010/05/012010/06/01
New Policy Count150014001300120011001000
New Premium600000.9500000.9400000.9300000.9200000.9100000.9
Claims Recorded30252015105
Claims Cost11111.9822222.9833333.9844444.9855555.9866666.98
Loss Ratio1.854.448.3314.8127.7766.66

Tuesday, June 29, 2010

Patterns : a look


A pattern is an especially clever and insightful way of solving a particular class of problems. It represents a complete idea within a program, and thus it can sometimes appear at the analysis phase or high-level design phase. It can exist at many levels from very low-level specific solutions to broadly generalized system issues. A patterns cover various ranges of scale and abstraction and are grouped into three categories:
    1. Architectural Pattern
        An architectural pattern expresses a fundamental structural organization schema for software systems. It provides a set of predefined subsystems, specifies their responsibilities, and includes rules and guidelines for organizing the relationships between them.
    2. Design Patterns
        A Design pattern provides a scheme for refining the subsystems or components of a software system, or the relationships between them. It describes a commonly-recurring structure of communication components that solves a general design problem within a particular context.
    3. Idioms
        An idioms is a low-level pattern specific to a programming language. An idiom describes how to implement particular aspects of components or the relationships between them using the features of the given language.

Some useful definitions of Design Patterns have emerged as the literature in this field has expanded.
  • “Design patterns are recurring solutions to design problems you see over and over.” (The Smalltalk Companion)
  • “Design patterns constitute a set of rules describing how to accomplish certain tasks in the realm of software development.” (Pree 1994)
  • “Design patterns focus more on reuse of recurring architectural design themes, while frameworks focus on detailed design and implementation.” (Coplien and Schmidt 1995)
  • “A pattern addresses a recurring design problem that arises in specific design situations and presents a solution to it.” (Buschmann et al., 1996)
  • “Patterns identify and specify abstractions that are above the level of single classes and instances, or of components.” (Gamma et al., 1993)

Tuesday, June 1, 2010

SQLOS : A User-mode Operating System for SQL Server

    The SQLOS is core to SQL Server's architecture, and first implemented in SQL Server 2005. It is a framework used by components in SQL Server for scheduling, I/O, and memory management. Because of the highly specialized requirements of SQL Server, it implements its own thread and memory management system. It is used for low-level operations such as scheduling, I/O completion, memory management, buffer pool management, resource management, synchronization primitives and deadlock detection. In summary, the SQLOS is a thin user-mode layer that sits between SQL Server and Windows.
    SQLOS also recognizes and accommodates NUMA (non-uniform memory access) architectures, to handle the systems which scale above 32 cores. In database, scheduled query run must be complete before starting the next one. SQLOS manages that with its schedulers: each logical CPU (one care in multi-core chip) has a non-preemptive scheduler in SQLOS that assigns one thread at a time to the CPU. SQLOS schedulers are hyper-threading aware, and can move a task from a hyper-threaded CPU to a "real" CPU that becomes idle.
The benefits of SQLOS include 
  • performance (primary goal)
  • enhanced scheduling and processor locality 
  • a dedicated administrative connection
  • support for hot adding of memory and CPU resources
  • a hosting interface for services such as CLR and SQL Server 2008 Reporting Services

    Reporting Services are runs under SQLOS rather than IIS, to handle large report request in a reasonable way. IIS is not designed to service long-running requests like database reports. Only Microsoft SQL Server can benefit from SQLOS. It is a tightly coupled, private layer of SQL Server. Even an extended stored procedure (a function in a DLL that SQL Sever launches) get called, it is thrown on the mercy of the Windows scheduler rather than receiving the benefit of SQLOS's non-preemptive scheduler.

    SQLOS is not a way to port the SQL Server architecture to other platforms like Linux or Mac OS so it's not an OS abstraction layer. It doesn't wrap all the OS APIs like other frameworks such as .NET, which is why it's referred to as a "thin" user-mode layer.