Transaction in SQL Server

 

Definition:

The Transaction must contain a series of properties known as ACID.

ACID (an acronym for Atomicity Consistency Isolation Durability) is a concept that Database Professionals generally look for when evaluating databases and application architectures. For a reliable database all this four attributes should be achieved.

 

Atomicity (each transaction is “all or nothing”):

If one part of the transaction fails, the entire transaction fails, and the database state is left unchanged.

For example, in an application that transfers funds from one account to another, the atomicity property ensures that, if a debit is made successfully from one account, the corresponding credit is made to the other account.

Consistency

Data is in a consistent state when a transaction starts and when it ends.

For example, in an application that transfers funds from one account to another, the consistency property ensures that the total value of funds in both the accounts is the same at the start and end of each transaction.

Isolation

Every transaction has a well-defined boundary. One transaction will never affect another transaction running at the same time.

Durability

Durability means that once a transaction has been committed, it will remain so, even in the event of power loss, crashes, or errors. In a relational database, for instance, once a group of SQL statements execute, the results need to be stored permanently (even if the database crashes immediately thereafter). To defend against power loss, transactions (or their effects) must be recorded in a non-volatile memory.

Example:

BEGIN TRANSACTION

 –Transaction statements

 IF @@ERROR!=0

BEGIN

ROLLBACK TRANSACTION

END

ELSE

BEGIN

COMMIT TRANSACTION

END

Nested Transaction:

Nested transactions usually occur when one stored procedure begins a transaction and then calls other procedures also using transactions before committing the initial transaction. However, a single stored procedure could also have multiple transactions open at the same time.

The transaction is either committed or rolled back based on the action taken at the end of the outermost transaction.

  •  If the outer transaction is committed, the inner nested transactions are also committed. 
  • If the outer transaction is rolled back, then all inner transactions are also rolled back, regardless of whether or not the inner transactions were individually committed.

 @@TRANCOUNT – Records the Current transaction nesting level

BEGIN TRAN –  @@TRANCOUNT 

COMMIT TRAN – @@TRANCOUNT – 1

 ROLLBACK TRAN @@TRANCOUNT

BEGIN TRAN

    INSERT INTO People VALUES(‘Tom’)

BEGIN TRAN

   INSERT INTO People VALUES(‘Dick’)

ROLLBACK TRAN

COMMIT TRAN

 If you execute the above sample you will find that it generates the error:

 

The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.

This error suggests that the final line of the script, which commits the outer transaction failed because the outer transaction no longer exists. Indeed. When you try to rollback a nested transaction, all active transactions are cancelled.

Transaction Savepoints:

Savepoints offer a mechanism to roll back portions of transactions.

SAVE TRANSACTION Savepoint_name

 ROLLBACK TRANSACTION savepoint_name – To roll back to the savepoint instead of rolling back to the start of the transaction

 Example:

BEGIN TRAN

PRINT‘First Transaction: ‘+CONVERT(VARCHAR,@@TRANCOUNT)

NSERTINTO People VALUES(‘Tom’)

SAVE TRAN Savepoint1  

PRINT‘Second Transaction: ‘+CONVERT(VARCHAR,@@TRANCOUNT)

INSERTINTO People VALUES(‘Dick’)

ROLLBACK TRAN Savepoint1

 PRINT‘After Rollback: ‘+CONVERT(VARCHAR,@@TRANCOUNT)

COMMIT TRAN

PRINT‘After Commit: ‘+CONVERT(VARCHAR,@@TRANCOUNT)

/* MESSAGES

First Transaction: 1

Second Transaction: 1

After Rollback: 1

After Commit: 0 */

Search

Loading

//

 

globalization

Definition:

            Globalization is the process of designing and developing an application that supports localized user interfaces and regional data for users in multiple cultures. In the .NET Framework, the CultureInfo class represents information about a specific culture. This information includes the writing system, calendars in use, date and time formatting conventions, numeric and currency conventions, and sorting rules.

 

The System.Globalization namespace contains classes that define culture-related information, including

*      Language

*      Country/region

*      Calendars in use,

*      Format patterns for dates,

*      Currency, and numbers,

*      And the sort order for strings.

Use these classes to simplify the process of developing a world-ready application. By passing a CultureInfo object representing the current culture to methods in this namespace, you can initiate the correct set of rules and data for the current user’s culture.

Web site globalization refers to enabling a web site to deal with non-English speaking visitors, i.e. internationalizing the site’s back-end software, designing a multi-lingual architecture, and localizing the site’s static or dynamic content.

 

What is the difference between globalization and localization?

 

  • Globalization is the process of making a product multi-lingual. All language-related aspects of the program are separated from the code, and all aspects, which vary with target country, are handled in a country-independent way.
  • Localization is the process of adapting a global product for a particular language and country. Localization includes translations and other conversion, and takes into account local practices and culture, providing a product, which is comfortable to use in the target country.
  • Translation is involved in most aspects of localization. Accuracy and appropriateness of translation are key to overall product quality.
  • Retrofitting is an informal term for localization of a product, which was not designed to be global. It is the first step taken by most companies entering the global marketplace.

dot Net Framework

Definition:

            This is the environment for building, deploying and running Web Services and other applications. It contains three main parts

·          CLR

·          Framework Classes

·          unified class libraries

 

Common Language Runtime (CLR):

            The common language runtime is the execution engine for .NET Framework applications. It provides a number of services, including the following:

o    Code management (loading and execution)

o    Application memory isolation

o    Verification of type safety

o    Conversion of IL to native code

o    Access to metadata (enhanced type information)

o    Managing memory for managed objects

o    Enforcement of code access security

o    Exception handling, including cross-language exceptions

o    Interoperation between managed code, COM objects, and pre-existing   DLLs (unmanaged code and data)

o    Automation of object layout

o    Support for developer services (profiling, debugging, and so on)

       CLS and CTS are there in CLR.

 

Common Language Specification (CLS):

            It is the set of guidelines for the language supporting the CLS to follow, so that it can communicate with other .NET languages in a seamless manner. The CLS is a set of constructs and constraints that serves as a guide for library writers and compiler writers.

 

Common Type System (CTS): 

            The common type system is a rich type system, built into the common language runtime that supports the types and operations found in most programming languages.

 

Types of Application in .Net Frame work

o    Console application

o    Windows Application

o    Web application

o    Class library

User control

Finance Terms definition

Credit Risk:

The risk of the loss arising on account of non-payment of interest or principle dues by the debtor, the two components of credit risk are “Ability to pay” and “willingness to pay”.

Credit score:

A credit score is a numerical expression on a statistical analysis of a entities credit files, to represent the creditworthiness of the entity.    The scores range from 300-850, lower score indicating that higher chance of defaulting on a loan and the higher score representing a better chance that the lender will get repaid back.

Collateral:

The property/assets made available by the barrower as a security against a loan, which can be seized in case of default.

Debt Instruments:

A written promise to repay a debt, for example bills, bonds, notes, CDs, Commercial papers and bankers acceptance.

Contingent Liability:

Contingent Liability is a liability, which may or may not occur. It will be decided by the future actions of the organization. That means, the future action will decide an activity as liability or not

Liability:

The word liability refers to fault. The person, who is at fault, is liable to another because of her/his actions or failure to act. The liability simply describes some form of obligation or responsibility. It represents the payment provided for damage caused through actions or negligence.

Obligation:

            The action of binding oneself by social, legal or moral tie (OR) The constraining power of promise, contract or sense of duty (OR) Any debt, written promise or duty

Credit Exposure:

            The potential for loss in the event of default

Credit Risk:

            Risk due to uncertainty in a counterparty’s ability to meet its obligations

Expected Loss:

            Expected value of losses due to default over a specified horizon given the exposure and historical performance. This can be thought of us what is expected to be lost on average

EL = PD * LGD * EAD

Probability of Default (PD):

            The likelihood that a barrower will not be able to pay its credit obligations, commonly measured as a percentage applied to the next 12 months.

Loss Given Default (LGD):

            The fraction of credit exposure that will not be recovered in the event of default on a specified obligation

            The loss sustained by the lender after the barrower defaults

Exposure at Default (EAD):

            The amount of credit a lender has extended or is obligated to extend at the time of default.     

C# Glassaries

Meta Data:

            Definition:

                        It contains the data about the object that is the Name of an object, the bases, interfaces implemented in that object and also the types and members of an object etc. 

Manifest:

            Definition:

                        It contains the information about the assembly like identity of an assembly, Scope of the assembly and also contains the security permissions.

 JIT Compiler:

            Definition:

                        During Run Time, the CLR invokes the JIT compiler to convert the MSIL into Native code (i.e. Executable Binary Code). When the Function is called, the IL of the function’s body is converted to Native code Just In Time.

            Types:

    • PreJIT
    • EconoJIT
    • Standard JIT

Class:

Definition:

            Class is the collection of object and it will contain member variables and member functions.

List of Classes available:

            Static class: Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state

            Sealed class: Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as sealed class, this class cannot be inherited.

            Abstract class: Abstract class can simply defined as incomplete class. It contains one or more incomplete methods called abstract methods. It leaves the implementation of these methods to derived or sub classes. Since abstract classes are incomplete, they can not be instantiated        

Polymorphism:

Definition:

            It means “Ability to take more than one form”. An operation may exhibit different behavior and different instances. Behavior is depends upon the operation.

 

Polymorphism is the ability for classes to provide different implementations of methods that are called by the same name.

Types:

1.       Compile Time Polymorphism

2.       Runtime Polymorphism

Implementation:

            Compile time polymorphism is done by functions and operators overloading.

            Runtime time polymorphism is done using inheritance and virtual functions.

Assemblies:

            Definition:

                        It is the building block of an application which provides all required execution information to “CLR” and also the Assembly is physical grouping of logical units.

  Types:

  •  Public Assembly

This is used by multiple applications and this is stored in Global Assembly Catch (GAC). We have to give cryptographically Strong Name for these shared assemblies.

  • Private Assembly:

This is used by a single application and this assembly is stored in that application installation folde

See more Here

 

 

Xml Basics

XML

Definition:
XML stands for Extensible Markup Language. XML is a markup language much like HTML. XML was designed to describe data. XML tags are not predefined in XML. You must define your own tags. XML is self describing. XML uses a DTD (Document Type Definition) to formally describe the data.

Xml Document:

Xml Document is composed of markups and contents. Six kinds of markups can occur in xml Document.

1. Document Type Declaration
2. Elements
3. Entity References
4. comments
5. Processing Instruction
6. Conditional Section

The elements should follow the following rules:

• Every start-tag must have a matching end-tag.
• Tags cannot overlap. Proper nesting is required.
• XML documents can only have one root element.
• Element names must obey the following XML naming conventions:
o Names must start with letters or the “_” character. Names cannot start with numbers of punctuation characters.
o After the first character, numbers and punctuation characters are allowed.
o Names cannot contain spaces.
o Names should not contain the “:” character as it is a “reserved” character.
o Names cannot start with the letters “xml” in any combination of case.
o The element name must come directly after the “<” without any spaces between them.
• XML is case sensitive.
• XML preserves white space within text.
• Elements may contain attributes. If an attribute is present, it must have a value, even if it is an empty string “”.

What is Element?

Elements are the logical components of XML documents. When all of our documents are abstracted into smaller parts, we can manipulate their content from whichever perspective we require. The smaller parts of our larger documents can be represented in XML using “elements.”
Elements consist of words that serve as the “names” for your element “tags” and are surrounded on either side by “less than” (<) and “greater than” (>) characters. These start and end tags may be used to encapsulate character data (text), as in the following example.

<Summary>Text goes in here</Summary>

What is Attributes?

Attributes provide a means of assigning “extra” information to elements in order to further describe properties of those elements. Attribute-value pairs can be associated with elements by including them inside of an element’s start tag.
XML attributes are normally used to describe XML elements, or to provide additional information about elements.

XML Schema:

Xml Schema is an Xml based alternative to DTD. Xml Schema describes the structure of the Xml Document. Xml schema language is also referred to as Xml Schema Definition (XSD).

Xml Schema defines the following

• Elements and attributes that can appear in a Document.
• Child Elements
• The order and number of child elements
• Whether an element is empty or can include Text.
• Data types for elements and attributes
• Default and fixed values for elements and attributes.
Xml Schema Elements:

The First Element in an Xml Schema file is schema element.
Xmlns- xml Namespace

<xsd: schema xmlns: xsd =“ http://www.w3.org/2001/XMLSchema“ >

</xsd: schema>
The main sub elements in xml schema
1. element: declares an element
2. attribute: declares an attribute
3. complexType: The elements that can contain other elements and attributes.
4. simpleType: the elements that can not contain other elements or attributes. These elements are the basic types, including string, data, integer etc.
The xsd: annotation and xsd: documentation tags are used for providing description of the document.

For example

<xsd: schema xmlns:xsd=”http://www.w3.org/2001/XMLSchema”&gt;
<xsd: annotation>
<xsd: documentation xml: lang =”en”>
Bookstore schema for book.xml
</xsd: documentation>
</xsd: annotation>
</xsd: schema>

In our XML example the element bookstore is a complexType element because it contains book sub-elements.

<xsd: element name=”bookstore” type=”bookstoreinfo”/>
<xsd: complexType name=”bookstoreinfo”>
<xsd: sequence>
<xsd: element name=”book” type=”bookinfo”/>
</xsd: sequence>
</xsd: complexType>

Our book element is also a complexType element.

<xsd: complexType name=”bookinfo”>
<xsd: sequence>
<xsd: element name=”title” type=”titleinfo”>
<xsd: element name=”author” type=”xsd:string”/>
<xsd: element name=”year” type=” xsd:string”/>
<xsd: element name=”price” type=” xsd:string”/>
</xsd: sequence>
</xsd: complexType>

The sub-elements author, year and price are of type xsd:string. The sub-element title is of complexType because it has an attribute named id. To define an attribute use the following:

<xsd: attribute name=”id” type=”xsd: string” use=”required”/>
Use value required means this attribute is mandatory. By default attributes are optional.

The main difference between XML and HTML:

XML is not a replacement for HTML. XML and HTML were designed with different goals:
• XML was designed to describe data and to focus on what data is. HTML was designed to display data and to focus on how data looks.
• HTML is about displaying information, XML is about describing information.

Use of XML:

• XML can keep data separated from your HTML
• XML can be used to store data inside HTML documents
• XML can be used as a format to exchange information
• XML can be used to store data in files or in databases

Find whether the class inherited from a particular interface

/* interface and ‘is’ operator*/

Definition:
By using ‘is’ operator we can find that, whether the class is inherited from a particular interface/class.

EXAMPLE 1:

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace LearningConcepts
{

interface INode
{

string Text
{
get;
set;
}

object Tag
{
get;
set;
}

int Height
{
get;
set;
}

int Width
{
get;
set;
}

float CalculateArea();

}

public class Node : INode
{

public Node()
{ }
public string Text
{
get {return m_text;}
set {m_text = value;}
}

private string m_text;
public object Tag
{

get{return m_tag;}
set{m_tag = value;}

}

private object m_tag = null;
public int Height
{

get {return m_height;}
set {m_height = value;}

}

private int m_height = 0;
public int Width
{
Get {return m_width;}
Set {m_width = value;}

}

private int m_width = 0;
public float CalculateArea()
{

if ((m_width < 0) || (m_height < 0))
return 0;

return m_height * m_width;

}

}
class ClonableNode :ICloneable
{
public object Clone()
{
return null;
}

// INode members
}

class Program
{
static void Main(string[] args)
{
Node nodeC=new Node();
if (nodeC is INode)
Console.WriteLine(“nodeC is object of INode type”);
//this will be displayed
else
Console.WriteLine(“nodeC isn’t object of INode type”);
}
}
}

Reflection

10. Reflection

 

Definition:

            We can access some data about object at runtime by using Reflection.

That information contain

·          Data of the class

·          Names of the Methods that are inside the class

·          Constructor of that Object.

To write a C# .Net program this uses reflection,

                        The program should use the namespace System.Reflection.

To get type of the object,

                         The typeof operator can be used.                                

             There is one more method GetType ().

          uses to get data about object’s type

By using Reflection we can do the following

·         Can get all methods from a class

·         Can get all Fields and Properties from a class

·         Can get information about assembly

·         Can create instance for a class

·         Can execute a class method indirectly

·         Can get type information: base type, is abstract, is com object, is sealed, is class

·         Can get all implemented interfaces and inherited base classes 

Oops Concepts

7. Oops Concepts

ABSTRACT CLASS:

            Abstract class can simply defined as incomplete class. It contains one or more incomplete methods called abstract methods. It leaves the implementation of these methods to derived or sub classes. Since abstract classes are incomplete, they can not be instantiated.

They must be sub-classed in order to use their functionality. So the abstract class can not be sealed. We can declare a reference of the type of abstract class and it can point to the object of the class that has inherited the abstract class.

We can add more functionality in abstract class without destroying child classes that were using old class.

Abstract class class_name

{                              

                                 // Constructor, constructor overloading and static constructor definition

                                 // Abstract method declaration;

                                 // Variable declaration;

                                 // Ordinary method declaration with their definition;

                                 // Static and virtual method declaration with their definition;

}

Few things about abstract class

*    Abstract class having declaration for abstract method.

*    You should define the abstract method using override keyword.

*    Abstract class support ordinary constructor, static constructor and constructor overloading.

*    Except private, all the access modifiers are allowed.

*    Ordinary methods will be having the definition part.

*    To declare the variables.

*    Static and virtual methods also to allow.

*    You can declare the interface inside the abstract class.

*    You should inherit the abstract class in derived class.

*    You can’t inherit more than one abstract class in derived class.

*    You can’t create the object for the abstract class, but you can create the reference for the abstract class.

SEALED CLASS:

            Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as sealed class, this class cannot be inherited.

STATIC CLASS:

The main features of a static class are:

·         They only contain static members.

·         They cannot be instantiated.

·         They are sealed.

·         They cannot contain Instance Constructors

Creating a static class is therefore much the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.

The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.

Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state

STATIC CONSTRUCTOR:

            It is possible to write a static no-parameter constructor for a class. One reason for writing a static constructor would be if your class has some static fields or properties that need to be initialized from an external source before the class is first used. It will be called automatically before the first instance is created.

Use of Static constructors:

*    Static constructor is used to initialize static data.

*    To perform particular action that needs performed once only

*    Another use of static constructor is, when the class is using a log file and the constructor is used to write entries to this file.

PRIVATE CONSTRUCTOR:

            A class can have private constructor also. It prevents the class from being instantiated by callers.

There are some cases where the private constructors can be useful:

*    Class containing only static utility methods

*    To implement singleton class.

POLYMORPHISM:

Definition:

It means “Ability to take more than one form”. An operation may exhibit different behavior and different instances. Behavior is depends upon the operation.

Polymorphism is the ability for classes to provide different implementations of methods that are called by the same name.

Types:

1.      Compile Time Polymorphism

2.      Runtime Polymorphism

Compile Time Polymorphism:

            Compile time polymorphism is functions and operators overloading.

Runtime polymorphism:

            Runtime time polymorphism is done using inheritance and virtual functions.

Overloading:

               Two or more methods within the same class can share the same name, as long as their parameter declarations are different.
*    number of parameters
*    type of parameters
Overriding:

            Mainly the overriding is to achieve Runtime Polymorphism. It allows a subclass to re-define a method it inherits from its super class

·If the super class method is public, the overriding method must be public
·If the super class method is protected, the overriding method may be protected or public
·If the super class method is package, the overriding method may be package, protected, or public
·If the super class methods is private, it is not inherited and overriding is not an issue

 

Overloading Vs. Overriding:

*    Overloading is nothing but static binding.

*    Overriding is dynamic binding which will be resolved at run-time.

 

*    Overloading deals with multiple methods in the same class with the same name but different signatures.

*    Overriding deals with two methods, one in a parent class and one in a child class, which have the same signature.

 

*    Overloading lets you define a similar operation in different ways for different data.

*    Overriding lets you define a similar operation in different ways for different object types.

Dynamic Binding/Late Binding:

                        It means that the code associated with a given procedure Call at Runtime.

Static Binding:

               It means that the code associated with a given procedure call during compile time itself.

VIRTUAL FUNCTION:

A virtual function is a member function of the base class and which is redefined by the derived class. When a derived class inherits the class containing the virtual function, it has ability to redefine the virtual functions. A virtual function has a different functionality in the derived class according to the requirement. The virtual function within the base class provides the form of the interface to the function. Virtual function implements the philosophy of one interface and multiple methods (polymorphism).

The virtual functions are resolved at the run time. This is called dynamic binding. The functions which are not virtual are resolved at compile time which is called static binding. A virtual function is created using the keyword virtual which precedes the name of the function.

Comparison of interface with class (interface vs. class):

  • An interface cannot inherit from a class.
  • An interface can inherit from multiple interfaces.
  • A class can inherit from multiple interfaces, but only one class.
  • Interface members must be methods, properties, events, or indexers.
  • All interface members must have public access (the default).
  • By convention, an interface name should begin with an uppercase I.