Thursday, June 28, 2012

SQL Server BACKUP LOG command

Overview
There are only two commands for backup, the primary is BACKUP DATABASE which backs up the entire database and BACKUP LOG which backs up the transaction log.  The following will show different options for doing transaction log backups.

Explanation
 The BACKUP LOG command gives you many options for creating transaction log backups.  Following are different examples.

Create a simple transaction log backup to disk
The command is BACKUP LOG databaseName.  The "TO DISK" option specifies that the backup should be written to disk and the location and filename to create the backup is specified.  The file extension is "TRN".  This helps me know it is a transaction log backup, but it could be any extension you like.  Also, the database has to be in the FULL or Bulk-Logged recovery model and at least one Full backup has to have occurred.
BACKUP LOG AdventureWorks 
TO DISK = 'C:\AdventureWorks.TRN'
GO

Create a log backup with a password
This command creates a log backup with a password that will need to be supplied when restoring the database.
BACKUP LOG AdventureWorks 
TO DISK = 'C:\AdventureWorks.TRN'
WITH PASSWORD = 'Q!W@E#R$'
GO

Create a log backup with progress stats
This command creates a log backup and also displays the progress of the backup.  The default is to show progress after every 10%.
BACKUP LOG AdventureWorks 
TO DISK = 'C:\AdventureWorks.TRN'
WITH STATS
GO

Here is another option showing stats after every 1%.
BACKUP LOG AdventureWorks 
TO DISK = 'C:\AdventureWorks.TRN'
WITH STATS = 1
GO

Create a backup and give it a description
This command uses the description option to give the backup a name.  This can later be used with some of the restore commands to see what is contained with the backup.  The maximum size is 255 characters.
BACKUP LOG AdventureWorks 
TO DISK = 'C:\AdventureWorks.TRN'
WITH DESCRIPTION = 'Log backup for AdventureWorks'
GO

Create a mirrored backup
This option allows you to create multiple copies of the backups, preferably to different locations.
BACKUP LOG AdventureWorks 
TO DISK = 'C:\AdventureWorks.TRN'
MIRROR TO DISK =  'D:\AdventureWorks_mirror.TRN'
WITH FORMAT
GO

Specifying multiple options
 This example shows how you can use multiple options at the same time.
BACKUP LOG AdventureWorks 
TO DISK = 'C:\AdventureWorks.TRN'
MIRROR TO DISK =  'D:\AdventureWorks_mirror.TRN'
WITH FORMAT, STATS, PASSWORD = 'Q!W@E#R$'
GO

SQL Server BACKUP DATABASE command

OverviewThere are only two commands for backup, the primary is BACKUP DATABASE.  This allows you to do a complete backup of your database as well as differential, file, etc. backups depending on the options that you use.

ExplanationThe BACKUP DATABASE command gives you many options for creating backups.  Following are different examples.

Create a full backup to diskThe command is BACKUP DATABASE databaseName.  The "TO DISK" option specifies that the backup should be written to disk and the location and filename to create the backup is specified.
BACKUP DATABASE AdventureWorks 
TO DISK = 'C:\AdventureWorks.BAK'
GO

Create a differential backup
This command adds the "WITH DIFFERENTIAL" option.
BACKUP DATABASE AdventureWorks 
TO DISK = 'C:\AdventureWorks.BAK' 
WITH DIFFERENTIAL 
GO

Create a file level backup
This command uses the "WITH FILE" option to specify a file backup.  You need to specify the logical filename within the database which can be obtained by using the command sp_helpdb 'databaseName', specifying the name of your database.
BACKUP DATABASE TestBackup FILE = 'TestBackup' 
TO DISK = 'C:\TestBackup_TestBackup.FIL'
GO

Create a filegroup backup
This command uses the "WITH FILEGROUP" option to specify a filegroup backup.  You need to specify the filegroup name from the database which can be obtained by using the command sp_helpdb 'databaseName', specifying the name of your database.
BACKUP DATABASE TestBackup FILEGROUP = 'ReadOnly' 
TO DISK = 'C:\TestBackup_ReadOnly.FLG'
GO

Create a full backup to multiple disk files
This command uses the "DISK" option multiple times to write the backup to three equally sized smaller files instead of one large file.
BACKUP DATABASE AdventureWorks 
TO DISK = 'C:\AdventureWorks_1.BAK',
DISK = 'D:\AdventureWorks_2.BAK',
DISK = 'E:\AdventureWorks_3.BAK'
GO

Create a full backup with a password
This command creates a backup with a password that will need to be supplied when restoring the database.
BACKUP DATABASE AdventureWorks 
TO DISK = 'C:\AdventureWorks.BAK'
WITH PASSWORD = 'Q!W@E#R$'
GO

Create a full backup with progress stats
This command creates a full backup and also displays the progress of the backup.  The default is to show progress after every 10%.
BACKUP DATABASE AdventureWorks 
TO DISK = 'C:\AdventureWorks.BAK'
WITH STATS
GO

Here is another option showing stats after every 1%.
BACKUP DATABASE AdventureWorks 
TO DISK = 'C:\AdventureWorks.BAK'
WITH STATS = 1
GO

Create a backup and give it a description
This command uses the description option to give the backup a name.  This can later be used with some of the restore commands to see what is contained with the backup.  The maximum size is 255 characters.
BACKUP DATABASE AdventureWorks 
TO DISK = 'C:\AdventureWorks.BAK'
WITH DESCRIPTION = 'Full backup for AdventureWorks'
GO

Create a mirrored backup
This option allows you to create multiple copies of the backups, preferably to different locations.
BACKUP DATABASE AdventureWorks 
TO DISK = 'C:\AdventureWorks.BAK'
MIRROR TO DISK =  'D:\AdventureWorks_mirror.BAK'
WITH FORMAT
GO

Specifying multiple options
This next example shows how you can use multiple options at the same time.
BACKUP DATABASE AdventureWorks 
TO DISK = 'C:\AdventureWorks.BAK'
MIRROR TO DISK =  'D:\AdventureWorks_mirror.BAK'
WITH FORMAT, STATS, PASSWORD = 'Q!W@E#R$'
GO

Shortcut to Show and Hide SSMS Results Pane

Problem

When using SSMS the query window is usually made up of the Editor on the top half and after you execute code Results are displayed on the bottom half. The problem with this is that if you need to modify the code in the Editor section the display is limited because the results pane takes up the bottom half of the window. You could resize the results section, but in this tip we look at a simple shortcut to show and hide the results pane.

Solution

The simple solution is to use the Ctrl+R shortcut to toggle between showing and hiding the results pane.
Here is a sample query window in SSMS with just the Editor section.
a sample query window in ssms
After we execute the code, half of the screen is now taken up by the Results pane.
toggle between showing and hiding the results pane when using ssms
If we just use Ctrl+R we can toggle between showing and hiding the results pane and therefore you can see more of the Editor section when you are using SQL Server Management Studio.

Thursday, June 7, 2012

Page Life Cycle

Here I have listed how the event is fire in page life cycle

OnInit Event Fire On a Page Life Cycle

i) Master Page User Control-init
ii) Page User COntrol-init
iii)Master Page -init
iv) Page - init


Page Load Event Fire On A Page life Cycle.

i) Page -Load
ii) Master Page-Load
iii)Page User Control - Load
iv) Master page User COntrol - Load


Data Binding Event Fire On A Page Life Cycle

i) Page - DataBinding
ii) Master Page - DataBinding
iii)Page User Control - Data Binding
iv) Master Page User COntrol - DataBinding

Unload Event Fire On A Page life Cycle

i) Master Page User Control-Unload
ii) Page User Control-Unload
iii)Master Page -Unload
iv) Page - Unload


A pictorial Presentation Of page life Cycle





Tuesday, June 5, 2012

Difference between Abstract Class and Interface:

Most of the people confuses with Abstract class and interface. Here I am planning to share some information with examples, I hope this will help you more………

Simple abstract class looks like this:
public abstract class KarateFight{
public void bowOpponent(){
//implementation for bowing which is common for every participant       }
public void takeStand(){
//implementation which is common for every participant
}
public abstract boolean fight(Opponent op);
//this is abstract because it differs from person to person
}

The basic interface looks like this:
public interface KarateFight{
public boolean fight(Opponent op);
public Integer timeOfFight(String person);
}

The differences between abstract class an interface as fallows:
1.  Abstract class has the constructor, but interface doesn’t.
2.  Abstract classes can have implementations for some of its members (Methods), but the interface can’t have implementation for any of its members.
3.  Abstract classes should have subclasses else that will be useless..
4. Interfaces must have implementations by other classes else that will be useless
5. Only an interface can extend another interface, but any class can extend an abstract class..
6.  All variable in interfaces are final by default
7. Interfaces provide a form of multiple inheritance. A class can extend only one other class.
8. Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
9.  A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
10. Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast.
11. Accessibility modifier(Public/Private/internal) is allowed for abstract class. Interface doesn’t allow accessibility modifier
12.  An abstract class may contain complete or incomplete methods. Interfaces can contain only the signature of a method but no body. Thus an abstract class can implement methods but an interface can not implement methods.
13.  An abstract class can contain fields, constructors, or destructors and implement properties. An interface can not contain fields, constructors, or destructors and it has only the property’s signature but no implementation.
14. Various access modifiers such as abstract, protected, internal, public, virtual, etc. are useful in abstract Classes but not in interfaces.
15.  Abstract scope is upto derived class.
16.  Interface scope is upto any level of its inheritance chain.

Java Abstract Class and Interface Interview Questions

What is the difference between Abstract class and Interface
Or
When should you use an abstract class, when an interface, when both?
Or
What is similarities/difference between an Abstract class and Interface?
Or
What is the difference between interface and an abstract class?

1. Abstract class is a class which contain one or more abstract methods, which has to be implemented by sub classes. An abstract class can contain no abstract methods also i.e. abstract class may contain concrete methods. A Java Interface can contain only method declarations and public static final constants and doesn't contain their implementation. The classes which implement the Interface must provide the method definition for all the methods present.
2. Abstract class definition begins with the keyword "abstract" keyword followed by Class definition. An Interface definition begins with the keyword "interface".
3. Abstract classes are useful in a situation when some general methods should be implemented and specialization behavior should be implemented by subclasses. Interfaces are useful in a situation when all its properties need to be implemented by subclasses
4. All variables in an Interface are by default - public static final while an abstract class can have instance variables.
5. An interface is also used in situations when a class needs to extend an other class apart from the abstract class. In such situations its not possible to have multiple inheritance of classes. An interface on the other hand can be used when it is required to implement one or more interfaces. Abstract class does not support Multiple Inheritance whereas an Interface supports multiple Inheritance.
6. An Interface can only have public members whereas an abstract class can contain private as well as protected members.
7. A class implementing an interface must implement all of the methods defined in the interface, while a class extending an abstract class need not implement any of the methods defined in the abstract class.
8. The problem with an interface is, if you want to add a new feature (method) in its contract, then you MUST implement those method in all of the classes which implement that interface. However, in the case of an abstract class, the method can be simply implemented in the abstract class and the same can be called by its subclass
9. Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast
10.Interfaces are often used to describe the peripheral abilities of a class, and not its central identity, E.g. an Automobile class might
implement the Recyclable interface, which could apply to many otherwise totally unrelated objects.
Note: There is no difference between a fully abstract class (all methods declared as abstract and all fields are public static final) and an interface.
Note: If the various objects are all of-a-kind, and share a common state and behavior, then tend towards a common base class. If all they
share is a set of method signatures, then tend towards an interface.
Similarities:
Neither Abstract classes nor Interface can be instantiated.

What does it mean that a method or class is abstract?
An abstract class cannot be instantiated. Only its subclasses can be instantiated. A class that has one or more abstract methods must be declared abstract. A subclass that does not provide an implementation for its inherited abstract methods must also be declared abstract. You indicate that a class is abstract with the abstract keyword like this:
    public abstract class AbstractClass
Abstract classes may contain abstract methods. A method declared abstract is not actually implemented in the class. It exists only to be overridden in subclasses. Abstract methods may only be included in abstract classes. However, an abstract class is not required to have any abstract methods, though most of them do. Each subclass of an abstract class must override the abstract methods of its superclasses
or itself be declared abstract. Only the method’s prototype is provided in the class definition. Also, a final method can not be abstract and vice versa. Methods specified in an interface are implicitly abstract.
. It has no body. For example,
public abstract float getInfo()

What must a class do to implement an interface?
The class must provide all of the methods in the interface and identify the interface in its implements clause.

What is an abstract method?
An abstract method is a method whose implementation is deferred to a subclass.

What is interface? How to support multiple inhertance in Java?
Or
What is a cloneable interface and how many methods does it contain?
An Interface are implicitly abstract and public. Interfaces with empty bodies are called marker interfaces having certain property or behavior. Examples:java.lang.Cloneable,java.io.Serializable,java.util.EventListener. An interface body can contain constant declarations, method prototype declarations, nested class declarations, and nested interface declarations.
Interfaces provide support for multiple inheritance in Java. A class that implements the interfaces is bound to implement all the methods defined in Interface.
Example of Interface:
public interface sampleInterface {
public void functionOne();
public long CONSTANT_ONE = 1000;
}

What is an abstract class?
Or
Can you make an instance of an abstract class?
Abstract classes can contain abstract and concrete methods. Abstract classes cannot be instantiated directly i.e. we cannot call the constructor of an abstract class directly nor we can create an instance of an abstract class by using “Class.forName().newInstance()” (Here we get java.lang.InstantiationException). However, if we create an instance of a class that extends an Abstract class, compiler will initialize both the classes. Here compiler will implicitly call the constructor of the Abstract class. Any class that contain an abstract method must be declared “abstract” and abstract methods can have definitions only in child classes. By overriding and customizing the abstract methods in more than one subclass makes “Polymorphism” and through Inheritance we define body to the abstract methods. Basically an abstract class serves as a template. Abstract class must be extended/subclassed for it to be implemented. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated. Abstract class is a class that provides some general functionality but leaves specific implementation to its inheriting classes.
Example of Abstract class:
abstract class AbstractClassExample{
protected String name;
public String getname() {
return name;
}
public abstract void function();
}
Example: Vehicle is an abstract class and Bus Truck, car etc are specific implementations
No! You cannot make an instance of an abstract class. An abstract class has to be sub-classed.
If you have an abstract class and you want to use a method which has been implemented, you may
need to subclass that abstract class, instantiate your subclass and then call that method.

What is meant by "Abstract Interface"?
Firstly, an interface is abstract. That means you cannot have any implementation in an interface.
All the methods declared in an interface are abstract methods or signatures of the methods.

How to define an Interface?
In Java Interface defines the methods but does not implement them. Interface can include constants.
A class that implements the interfaces is bound to implement all the methods defined in Interface.
Example of Interface:
public interface SampleInterface {
public void functionOne();
public long CONSTANT_ONE = 1000;
}

Can Abstract Class have constructors? Can interfaces have constructors?
Abstract class's can have a constructor, but you cannot access it through the object, since you cannot instantiate abstract class. To access the constructor create a sub class and extend the abstract class which is having the constructor.
Example
public abstract class AbstractExample {
public AbstractExample(){
System.out.println("In AbstractExample()");
}
}
public class Test extends AbstractExample{
public static void main(String args[]){
Test obj=new Test();
}
}

If interface & abstract class have same methods and those methods contain no implementation, which one would you prefer?
Obviously one should ideally go for an interface, as we can only extend one class. Implementing an interface for a class is very much effective rather than extending an abstract class because we can extend some other useful class for this subclass

Monday, June 4, 2012

Design pattern in simple examples

Instead of defining what is design pattern lets define what we mean by design and what we mean by pattern. According to me design is blue print or sketch of something so it can be defined as creation of something in mind. Moving to pattern, we can define it as guideline, or something that repeats. Now the definition of design pattern becomes creating something in mind that repeats or in other words capturing design ideas as a "pattern" to the problems.

Some problem patterns happen over and over again in a given context and Design Pattern provides a core of the solution in such a way that you can use the core solution every time but implementation should and may vary and the main reason behind that is we have the core solution and not the exact solution. We can discuss an example here about database normalization. Normalization is a pattern (Core solution to database design) but what level of normalization you need (exact solution) depends on your requirement and context.

In this article I will be discussing the following Design patterns ( or common problems and there common solutions which are time tested and have worked when applied ).
I will not be defining the design patterns because you can always find them in any standard book but I will be dealing with the actual use and examples of them. To understand the article in a better I would suggest you first download the demo project. To see any sample you make the project as the StartUp project and compile the project and execute it. The solution is build using Microsoft Visual Studio 2005. I have purposely used the abstract classes over interface so the class diagram of the samples looks exactly similar to one suggested by gang of four. If you find a class whose Name is IClassName please don't get upset but its done purposefully to make the class diagrams. In the article I have tried to use as many pictures as possible because "A picture is worth a thousand words"

Creational Patterns

Abstract Factory

- Do we need to create families of objects.

Factory method takes care of one product where as the abstract factory Pattern provides a way to encapsulate a family of products.

Typically the class diagram looks like



Example

We have a requirement where we need to create control library and the same library supports multiple platforms but the client code should not be changed if we import from one operating system to the other. The solution is



The client uses the GuiFactory to get the required factory of the supported operating system and calls the same Show Method. Now depending on the platform we change the factory but the client implementation remains the same. If support for new operating system is to be added we need the new factory and the exact implementation of the buttons and without changing the existing code we can support the new platform.

Builder

- Do we need to create object in several steps.

Builds a class based on requirements where Director asks the builder to build each of the parts. Mainly the builder pattern is not used independently but other patterns may have builder pattern as a part where they create the complicated objects using the builder.

Typically the class diagram looks like



Example



Who is what?

Waiter is Director
PizzaBuilder is Builder
CheesePizzaBuilder and MixedPizzaBuilder are Concretebuilder
Pizza is product

When Waiter (Director) is asked to serve it creates the Pizza (Product) using the PizzaBuilder.

Another example could be Maze which is a complicated object build from walls and rooms.

Factory

- Do we need to have derived classes figure out what to instantiate and decouple client from instantiated class.

Client uses the factory to create products and its the factory which decides when the actual product is needed for instantiation. This way client decouples the instance and can be saved from some of the crucial operations of object copy if the type of object may change after creation.

Typically the class diagram looks like



Example



Who is what?

ComputerFactory (Creator)
ConcreteComputerFactory (ConcreteCreator)
Processor (Product)
ConcreteProcessor (ConcreteProduct)

When the GetProcessor of ComputerFactory is called its the ConcreteComputerFactory creates the ConcreteProcessor and the creation of ConcreteProcessor is delayed till we call the GetProcessor() function.

Another good example could be logging, where we create the instance of the logger factory but instantiate the logger class when actual logging is done.

Prototype

- Do we have too many classes to instantiate / or is the object creation a cumbersome process.

Mainly we don't create the objects of a class directly but clone the existing object and change the state of the object as needed. The main application of such pattern is when the object creation is costly. As an example we have a database class the constructor sets up the database for the class. Now for each new user logging to the system once the system is up we don't setup the database but just clone the first object and change the user specific details like user name / password to validate the user.

Typically the class diagram looks like



Example



I would not explain here who is what because its pretty much evident.

Singleton

- Do we need to limit the no of objects of a class.

Ensures only one (n = 1..n) instance. The pattern explains how you can achieve the singleton class. It says to have the constructor as private and have a static method to access the instance of the class using that method.

Typically the class diagram looks like



Example



I would not explain here who is what because its pretty much evident.

Structural Patterns

Adapter

- Do we have the right stuff but wrong interface.

We use the adapter design pattern where the requirements is to convert between one interface to another. Adapter pattern is never implemented when designing a new system but with the changing requirements we have deferring interfaces then adapter comes into picture.

Typically the class diagram looks like



Example

We have used some library where we have Add function which takes two integer and provides the sum of them. Now when upgrading the libray we find that the library has changed the Add function such that it takes 2 floating point number. Now one option could be to change all the client code where we have used the Add method or other option is to have an Adapter.



CalcAdapter calls the necessary library function after making the necessary changes (in our example conversion between the data types)

Bridge

- Do we have one variation using another variation in a varying way.

Decouple an abstraction from its implementation so that two can vary independently. In strategy pattern we decouple the behavior but in Bridge we decouple the abstraction.

Typically the class diagram looks like



Example

In Abstract Factory we discussed about the problem of creating a control library for various operating system. Now creating the library from the scratch is never a good idea and so we may need to use some of the existing infrastructure or library available. We may use the XWindow toolkit or MacWindow toolkit as the base depending on the user platform and toolkit available.

The DrawRect actually uses the DrawLine function which actually is dependent on the type of implementation and we seperate the implementation from the abstraction and have a link ( or bridge ) between the two.



Composite

- Do we have units and groups and want to treat them the same way.

Compose the objects in a tree structure where individual objects as well as the composed objects behave uniformly. Composed objects delegates the requests to the individual leaf objects.

Typically the class diagram looks like



Example

We have some simple graphics and have some graphics which are composed of these simple graphics and as a client both should behave uniformly.



Folder browsing could be other example where from the client's point of view its an operation on the folder tree irrespective of its folder ( composite object ) or file ( leaf object ).

Decorator

- Do we need multiple additional functions we may need to apply, but which and how many we add varies, without sub classing.

Attach additional responsibilities to an object dynamically. It has the capability of performing some additional operations before or after the basic operation.

Typically the class diagram looks like



Example

Say we have a FileReader class where the file can be read based on the combination of applying any of the formulas like it could be
  • Zipped.
  • Encrypted.
  • Zipped and encrypted.
  • encrypted then zipped and ecrypted again.

The solution is Decorator pattern where we apply the options based on the requirement.

Code: CSharp
FileReader file = new FileReader(); // Zip the File ZipReader zip = new ZipReader(file); // Encrypt the zip file EncryptedReader enc = new EncryptedReader(zip); enc.Read();
Code: CSharp
FileReader file = new FileReader(); // Encrypt the file enc = new EncryptedReader(file); // Zip the encrypted file zip = new ZipReader(enc); zip.Read();
We can apply any combination as and when needed and also new methods of encryption is very simple. Just add the new class as sibling of EncryptedReader



Facade

- Do we want simplify, beautify or OO-fy an existing class or subsystem.

When client is decoupled from the system using an inter mediator its called facade. Facade behaves as a door to subsystem and provides a single interface to complex interface in the subsystem. Here a point to note is that the subsystem should not have a dependency on the FACADE and if thats the case then the facade is a part of the sub-system and it should move into the sub-system and we should have a new facade class.

Also Facade is not the only entry point to the sub-system but is a convenient point of communication to the subsystem and client can always have the direct access to the subsystem.

This methods helps in developing the subsystem independently without affecting the clients using them.

Typically the class diagram looks like



Example

We have a Car System creation where the car is created based on the complex subsystems like wheel, steering, chassis, body ...



Flyweight

- Do we have too many part objects.

Any objects state can be classified into two types of data that it can store one is intrinsic (static and independent of object) and one is extrinsic (non-static and depend on the state of the object) then flyweight pattern can be applied. The design pattern is useful when we have large no of objects which can be grouped once the extrinsic state is removed and it uses de-encapsulation to split the objects.

Typically the class diagram looks like



Example

We have some shape objects and the shape objects are really costly and so we can have the shape object split itself such that some data which is independent of the state of the object is kept in the object and other data is provided externally. Say in our shape object how the shape is drawn is same but where the shape is drawn is dependent on the state of the object and so the print method should know where to print which is extrinsic and should be supplied.



Proxy

- Do we need to optionally add some new functionality to something that already exists. Do we need to control how an object is accessed.

It provides a placeholder for another objects and the proxy object gives the impression to the client that actual request is handled by the proxy but it just delegates the request to the real subject.

Typically the class diagram looks like



Example

Say we have a system setup where we send and receive data over the network. Now due to some security reasons data are encrypted and so now they need to be decrypted before processing and so now we are in trouble because all the client code needs to be changed to decrypt the data or we may need to change the stable library code which use to send/recieve the data. Now the solution could be to have the proxy which will do the additional responsibility given to the system and then send the data using the well tested system in place.



We should be using the proxy system where we think we may need to add some additional responsibilities later.

Behavioral Patterns

Chain of Responsibility

- Do we have diff. objects that can do the job but we do not want the client object know which is actually going to do it.

Avoid coupling the sender of a request to its reciever by giving more than one object a chance to handle the request. Helps in reducing the coupling though they are chained, but does not know about other objects apart fron the fact that they derive from the common interface.

Best example could be Context help where the each help component tries to perform the request and when fail they pass the request in the chain to other members.

Typically the class diagram looks like



Example

In the banking system where cheque's for clearing is approved by the person but if the cheque amount is beyond certain limit, the approving responsibility moves the person higher in authority in the bank.

Windows messaging system works in the similar method where the messages are processed by the controls if the point likes with the bounds of the control or goes to the parent.



Command

- Do we need to decouple request from handler.

Encapsulate requests for service from an object inside other object(s) and manipulate requests. Command objects are mainly helpful in undo/redo operation where the previous state can be saved for reloading or even the necessary command(s) can be stored in stack for the same.

Typically the class diagram looks like



Example

Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.



The other example could be the operations on the images.

Interpreter



As the name suggest it interpret your expression. Some expressions are atomic and some complex which are made up of atomic and it interprets the atomic and complex expressions uniformly. It mainly uses in the compilers / parsers / Macro expansions.



I have not provided any sample because this one is not that often used just for completeness of the article have mentioned the pattern here.

Iterator

- Do we want to separate collection from client that's using.

Provide a way to access the elements of an aggregate objects sequentially without exposing its representation. We can make the client independent on the movement of the cursors like forward traversal / backward traversal as well as the internal implementation of the list.

Typically the class diagram looks like



Example



I would not explain here who is what because its pretty much evident and nowadays any modern language supports this and so you could use the foreach loop. In C-Sharp if you would like to have a class that will be a list you need to use the IEnumerator and IEnumerable interfaces and then it will support the foreach loop.

List should implement IEnumerable and the Iterator should implement IEnumerator.

Mediator

- Do we have a lot of coupling in who must talk to whom.

Define objects in the subsystem where the set of objects interact. This pattern is much similar to the Facade but in facade the sub-system knows nothing about the Facade but here the sub-system communicate through the mediator and the client also communicate through the mediator. Mediator hides the complicated communication in the subsystem where as facade sub-system classes are open to the client as well, So Facade is an optional point of communication where as Mediator is only point of communication to the subsystem.

Typically the class diagram looks like



Example

Now don't blame me if for the third time I take the example of the control library where we have a dialog and some controls over the dialog. The controls can be interacted through the DialogMediator. Now if the siblings of the Dialog would like to interact they do so through the DialogMediator because its the DialogMediator who has the information about the rest of the sub-system



Memento



Delegate some activity to some other class like some helper classes to do the job.

The memento pattern is used to encapsulate the current state of an object in a memento object in order to be able to restore the object state later without exposing the internal representation of the object to the outside world. The memento pattern is useful when you have an object which you would to take a "snapshot" of so that at a later time you could use the snapshot to restore it to its original state, such as an undo or rollback operation.

Typically the class diagram looks like



Example

Suppose you have a an object which stores form information and you would like to allow the user to make changes in the form and then if they make a mistake later you can put back in the original form values. Well, you could serialize the form object and then un-serialize it later but this is obviously messy and not a good solution. Another possible solution would be to have an outside object use the form's accessors methods to pull out what you need to save the state but this causes high coupling between the class saving the state and the form; any changes in the form would require changes in the other class. We need something that will allow you to save the state and restore it later without having to get involved in the details. This is where the memento pattern comes in.



Observer

- Do various entities need to know about events that have occurred? How to keep dependent object up-to-date.

When we have one to many dependency between objects so when the object changes, its dependents are notified of the update automatically. The best example is something like Excel with data in one cells and we have multiple charts which gets updated when there is change in the data. This design pattern is more useful if we have one sided broadcast communication and is useful when we have one to many relationship.

Typically the class diagram looks like



Example

When any data is changed in the XMLDoc object it calls the Notify Method of the base class which has the list of the active observers attached to the XMLDoc and calls the Update method of all the view of the data.



State

- Do we have a system with lots of states where keeping track of code for differrent states is difficult.

Allow the object to alter it behavior when its internal state change.

Typically the class diagram looks like



Example

We have a Printer system where we have the following states for the printer and based on the actions taken in particular state, the state of the printer changes accordingly.



Instead of having the state defined in the printer itself we keep the state of the printer into separate object and separate the responsibilities. "Have objects for state."



Strategy

- Do we have a varying rule or algorithm.

Define a family of algorithms, encapsulate each one and make them interchangeable. It allows us to change the algorithm independently with out changing the client using it. It converts the generalization of the template method to composition or aggregation.

It has various uses like it allows the algorithm to vary frequently and is a very good alternate solution to sub-classing.

Typically the class diagram looks like



Example

We have a payment system where we have an Invoice class where we calculate the total of the amount payable but the requirement is such the amount calculation depends on the type of customer and discount offer. Also over the time the offers / discount may differ and may need to change the offer at run-time. The solution is



Now if have some special offer coming for the season sale all we need to do is add a new class derived from NetPayable and then add the necessary calculation logic in that class and this way we can have the new algorithm added dynamically.

Template Method

- Do we have a skeleton of the algorithm and want to leave upto the sub classes how each step behaves.

Define the skeleton of the algorithm in an operation and deferring the exact implementations of the steps of the algorithms to its subclasses. Template method uses the HR policy of "we will call you" which means the exact implementations of the algorithm will be called by the base class.

Typically the class diagram looks like



Example

Printing algorithm for various types of documents where the algorithm is fixed of printing the header then body and at last the footer which is defined in the base class the exactly how the headers are printed is defined in the supported document classes.



Visitor

- Do we have new tasks that we will need to apply to our existing classes.

Represent an operation to be performed on the element of an object and helps you add new methods to existing hierarchy without affecting the existing hierarchy. This also de-encapsulate where we break the class so that some future functionality can be added but it has the disadvantage that concrete elements cannot be added without changing the interface. Use of the pattern should be done if you have the concrete elements fixed but you may need to add the new functionality to the existing object.

Typically the class diagram looks like



Example

We have the number of objects supported in the drawing system fixed but we need to add the depth in the way the object does it operations like scale or drawing of the object. We could have the same class do both the job but we need some specialist in the field doing the job. A mathematician is good at doing the scaling but not at drawing or vice versa and so here we use the visitor pattern.



Accept method actually calls the correct implementation based on the visitor passed, so its the client who tells if he needs to draw or scale.

GOLDEN RULE(s) of design pattern
  1. Client should always call the abstraction (interface) and not the exact implementation.
  2. Future changes should not impact the existing system.
  3. Change always what is changing.
  4. Have loose coupling
    • Inheritance ( Very coupled )
    • Composition
    • Aggregation
    • Association
    • Dependency
    • Realization ( Least couple )

How and when to use Singleton classes

It’s a pretty well known pattern, but I want to discuss what a Singleton class is first. In a nutshell, a Singleton class is a class that will only have one instance of the class. In certain cases, we want to make sure that we cannot instantiate multiple copies of the object, so we limit it to just one copy. Instead of having a public constructor for our class, we use a private constructor. Then we use a public method (usually named getInstance()) to make sure there is only one copy.


Here is how it looks:
1
2
3
4
5
6
7
8
9
10
11
public class Singleton {
   private static final Singleton instance;   
 
   private Singleton(){}
 
   public static Singleton getInstance() {
     if (instance == null)
       instance = new Singleton();
     return instance;
   }
 }
 
As you can see, the constructor is private, so we are unable instantiate it in the normal fashion. What you have to do is call it like this:
1
public Singleton singleton = Singleton.getInstance();
When you do this, the getInstance() method then checks to see if the parameter ‘instance’ is null. If it is, it will create a new one by calling the private constructor. After that, it just returns it. Of course, if it is not null, it just returns the existing instance of it. This insures that there is only one copy of the object within your program.

Of course, this post wouldn’t have much meat to it if thats what I left it at. So lets talk about some of the uses of a Singleton class. Also you might at some point as ‘why not just make it static?’, which is a common question, so I will go over that about that as well.

First, what are the uses of a Singleton?. Singleton classes are normally used for things such as a Factory classes, Builder classes and things like that. A few real world examples include the the SessionFactory class in Hibernate – it’s actually a singleton. Or with log4j, when you call its logger, it uses a singleton class to return it. If anyone has used Cairngorm within Flex/Actionscript 3, its model locator is a Singleton.

So why do we want to use singleton’s in these instances? Lets look at the ModelLocator example within Cairngorm. The model locator is used within Cairngorm to keep the state of data within our Flex application. But the reason why its kept in this one object is that it is used across multiple components. The data in one component is usually important to another component, so everything is managed in one central object. It’s quick to realize why we only want one of these in our program. If not, it would be pretty tough to maintain state if other components are affecting data providers that others are using.

Another question that usually comes up when it comes to using a Singleton is “Why not just use a static class?”. Static classes still have many uses and lots of times, people get confused and will use a Singleton as much as possible. One easy rule of thumb you can follow is if it doesn’t need to maintain state, you can use a Static class, otherwise you should use a Singleton.

So here is a quick list of uses for static classes:
Math.pow(double a, double b);
Interger.parseInt(String s);
Interger.toString(int i);

As you can see, the state of these methods don’t matter. You just want to use them to perform a simple task for you. But if you coding your application and you are using a central object where state does matter(such as the ModelLocator example), then its best to use a Singleton.

The next reason you may want to use a Singleton is if it is a particularly “heavy” object. If your object is large and takes up a reasonable amount of memory, you probably only one of those objects floating around. This is the case for things like a if you have a factory method that is particularly robust, you want to make sure that its not going to be instantiated multiple times. A Singleton class will help prevent such the case ever happening.

The Singleton is a simple and powerful design pattern. Newer programmers may not realize what potential it has and will over look it. Others may love it so much and end of overusing it in the wrong way.

Sunday, June 3, 2012

ASP.NET Interview Questions on Data Access Security

What are the best practices to follow to secure connection strings in an ASP.NET web application?
1. Always store connection strings in the site's Web.config file. Web.config is very secure. Users will not be able to access web.config from the browser.
2. Do not store connection strings as plain text. To help keep the connection to your database server secure, it is recommended that you encrypt connection string information in the configuration file.
3. Never store connection strings in an aspx page.
4. Never set connection strings as declarative properties of the SqlDataSource control or other data source controls.
Why is "Connecting to SQL Server using Integrated Security" considered a best practice?Connecting to SQL Server using integrated security instead of using an explicit user name and password, helps avoid the possibility of the connection string being compromised and your user ID and password being exposed.

What is the advantage of storing an XML file in the applications App_Data folder?
The contents of the App_Data folder will not be returned in response to direct HTTP requests.

 What is Script injection?
A script injection attack attempts to send executable script to your application with the intent of having other users run it. A typical script injection attack sends script to a page that stores the script in a database, so that another user who views the data inadvertently runs the code.
What is SQL injection?A SQL injection attack attempts to compromise your database by creating SQL commands that are executed instead of, or in addition to, the commands that you have built into your application.What are the best practices to keep in mind when accepting user input on a web application?
1.
Always use validation controls whenever possible to limit user input to acceptable values.
2. Always check the IsValid property of the aspx page. Run the server side code only if the IsValid property value is true. A value of false means that one or more validation controls have failed a validation check.
3. Always perform server side validation irrespective of client side validation being performed or not. This will protect your web application even if the client has by passed the client side validation by disabling javascript in the web browser.
4. Also make sure to re validate user input in the business logic layer of your application.
What are the steps to follow to avoid Script Injection attacks?
1.
Encode user input with the HtmlEncode method. This method turns HTML into its text representation.
2. If you are using the GridView control with bound fields, set the BoundField object's HtmlEncode property to true. This causes the GridView control to encode user input when the row is in edit mode.
What are the steps to follow to avoid SQL Injection attacks?Always use parameterized queries or stored procedures instead of creating SQL commands by concatenating strings together.

Can you encrypt view state data of an aspx page?
Yes, you encrypt view state data of an aspx page by setting the page's ViewStateEncryptionMode property to true.

ASP.NET Interview Questions on caching

What is caching?
High-performance Web applications should be designed with caching in mind. Caching is the technique of storing frequently used items in memory so that they can be accessed more quickly. Caching is important to Web applications because each time a Web form is requested, the host server must process the Web form’s HTML and run Web form code to create a response. By caching the response, all that work is bypassed. Instead, the request is served from the reponse already stored in memory.

Caching an item incurs considerable overhead, so it’s important to choose the items to cache wisely. A Web form is a good candidate for caching if it is frequently used and does not contain data that frequently changes. By storing a Web form in memory, you are effectively freezing that form’s server-side content so that changes to that content do not appear until the cache is refreshed.

What directive is used to cache a web form?
The @OutputCache page directive is used to cache a Web form in the server’s memory.

What is the use of duration attribute of @OutputCache page directive?
The @OutputCache directive’s Duration attribute controls how long the page is cached. For example if you set the duration attribute to 60 seconds, the Web form is cached for 60 seconds.

The first time any user requests the Web form, the server loads the response in memory and retains that response for 60 seconds. Any subsequent requests during that time receive the cached response.

After the cache duration has expired, the next request for the Web form generates a new response, which is then cached for another 60 seconds. Thus the server processes the Web form once every 60 seconds at most.


What are the 2 required attributes of the @OutputCache directive?
The @OutputCache directive has two required attributes:
1.
Duration
2.
VaryByParam.

How do you cache multiple responses from a single Web form?
The VaryByParam attribute lets you cache multiple responses from a single Web form based on varying HTTP POST or query string parameters. Setting VaryByParam to None caches only one response for the Web form, regardless of the parameters sent.

You can also cache multiple responses from a single Web form using the VaryByHeaders or VaryByCustom attribute.

The VaryByCustom attribute lets you cache different responses based on a custom string. To use VaryByCustom, override the GetVaryByCustomString method in the Web application’s Global.asax file.

Is it possible to cache a web form without using @OutputCache directive?
Yes, you can cache a web form using the Response object’s Cache property, which returns an HttpCachePolicy object for the response. The HttpCachePolicy object provides members that are similar to the OutputCache directive’s attributes.

Give a simple example to show how to cache a web form without using @OutputCache directive?
For example, the following code caches the Web form’s response for 60 seconds:
private void Page_Load(object sender, System.EventArgs e)
{
// Cache this page
DateTimeLabel.Text = System.DateTime.Now.ToString();
// Set OutputCache Duration. Response.Cache.SetExpires(System.DateTime.Now.AddSeconds(60));
// Set OutputCache VaryByParams.
Response.Cache.VaryByParams["None"] = true;
// Set OutputCache Location.
Response.Cache.SetCacheability(HttpCacheability.Public);
}

The preceding code is equivalent to the following OutputCache directive:
@ OutputCache Duration="5" VaryByParam="None" Location="Any"

What is @OutputCache directive’s Location attribute and the HttpCachePolicy object’s SetCacheability property used for?
The @OutputCache directive’s Location attribute and the HttpCachePolicy object’s SetCacheability property determine where Microsoft ASP.NET stores cached responses. By default, ASP.NET caches responses at any available location that accepts cache items - the client, proxy servers, or the host server. In practice, those locations might or might not allow caching, so you can think of the Location/SetCacheability setting as more of a request than a command.

What is HttpCachePolicy object’s SetAllowResponseInBrowserHistory method used for?
You can override the cache location settings using the HttpCachePolicy object’s SetAllowResponseInBrowserHistory method. Setting that method to True allows the response to be stored in the client’s history folder even if the location setting is None or Server.

What are the advantages and disadvantages of a layered architecture

The following are the advantages of a layered architecture:

Layered architecture increases flexibility, maintainability, and scalability. In a Layered architecture we separate the user interface from the business logic, and the business logic from the data access logic. Separation of concerns among these logical layers and components is easily achieved with the help of layered architecture.



Multiple applications can reuse the components. For example if we want a windows user interface rather than a web browser interface, this can be done in an easy and fast way by just replacing the UI component. All the other components like business logic, data access and the database remains the same. Layered architecture allows to swap and reuse components at will.

Layered architecture enables teams to work on different parts of the application parallely with minimal dependencies on other teams.

Layered architecture enables develop loosely coupled systems.

Different components of the application can be independently deployed, maintained, and updated, on different time schedules.

Layered architecture also makes it possible to configure different levels of security to different components deployed on different boxes. sO Layered architecture, enables you to secure portions of the application behind the firewall and make other components accessible from the Internet.

Layered architecture also helps you to test the components independently of each other.

The following are the disadvantages of a layered architecture:                

There might be a negative impact on the performance as we have the extra overhead of passing through layers instead of calling a component directly.

Development of user-intensive applications can sometime take longer if the layering prevents the use of user interface components that directly interact with the database.

The use of layers helps to control and encapsulate the complexity of large applications, but adds complexity to simple applications.

Changes to lower level interfaces tend to percolate to higher levels, especially if the relaxed layered approach is used.

F Written Test HR Round Subscribe C# Videos C# Programs Support Us What is the difference between layers and tiers

Layers refer to logical seperation of code. Logical layers help you organise your code better. For example an application can have the following layers.


1)Presentation Layer or UI Layer
2)Business Layer or Business Logic Layer
3)Data Access Layer or Data Layer


The aboove three layers reside in their own projects, may be 3 projects or even more. When we compile the projects we get the respective layer DLL. So we have 3 DLL's now.


Depending upon how we deploy our application, we may have 1 to 3 tiers. As we now have 3 DLL's, if we deploy all the DLL's on the same machine, then we have only 1 physical tier but 3 logical layers.


If we choose to deploy each DLL on a seperate machine, then we have 3 tiers and 3 layers.


So, Layers are a logical separation and Tiers are a physical separation. We can also say that, tiers are the physical deployment of layers.

Tiers:
1) Presenation Tier or UI Tier (Hosts the Presentation Layer or UI Layer). This can be considered as web server in case of an ASP.NET web application.
2) Application Tier or Business Tier (Hosts Business Layer or Business Logic Layer).
3) Data Access Tier or Data Tier (Hosts Data Access Layer or Data Layer).
4) Database Tier - SQL Server or Oracle (or any other database) which has tables, stored procedures and other database objects.


In general the following are the responsibilities of each layer or tier:


1)Presentation Layer or Tier is usually responsible for interacting with the user.
2)Business Layer or Tier is responsible for implementing the business logic of the application.
3)Data Access Layer or Tier is responsible for encapsulating the code that accesses the persistent data stores such as a relational database.

What is the process for strong naming an assembly

What is the process for strong naming an assembly ?
or
What is the purpose of strong naming tool ( sn.exe ) in .NET ?

In .NET, the assembly name usually consists of 4 parts as listed below.
1. Simple Textual Name
2. Version Number (The version number is also divided into 4 parts)
3. Culture
4. Public Key Token

If an assembly contains, all the 4 parts, then the assembly is a strongly named assembly, other wise the assembly is called as a weak named assembly. In general, when you compile any .NET application, the generated assembly by default will have the Simple Textual Name, Version Number and Culture but not the public key token. If you have to sign the assembly with a public key token, you first have to generate the key pair using key generation tool called strong naming tool (sn.exe). The generated key pair will consist of a private and a public key and are written into a key file. Key files have the extension of .snk.

We now have to associate the key file with the project, so that when we compile the project, the generated assembly is signed using the key pair. To do this, In AssemblyInfo.cs file of the project, specify AssemblyKeyFile attribute as shown below.
              [assembly: AssemblyKeyFile("MyKey.snk")]

The last and final step is to build the project which will automatically sign the assembly using the key file. This process generates the strongly named assembly.



In short, there are 3 simple steps to generate a strongly named assembly.
1. Generate the key pair using strong naming tool, SN.exe.

2. Associate the generated Key file to the project using AssemblyKeyFile, which is present in AssemblyInfo.cs file.

3. Build the project.

Once, you have strongly named the assembly, you can copy it to GAC. There are 2 ways to copy an assembly into GAC.
1. Using simple drag and drop : Drag the generated assembly into the GAC folder. Usually the path for GAC is c:\windows\assembly. On some machines this could be c:\winnt\assembly.

2. Use GAC utility : Use GAC Utility tool(gacutil.exe) as shown below in visual studio command prompt.
               gacutil.exe -i C:\MyAssembly.dll (- i stands for install)

Once, you have successfuly copied the assembly into GAC, notice the four parts of the assembly name. The culture column could be empty, indicating that the assembly is language neutral.

Explain Dependency Injection with an example

One of the very common interview questions, asked these days. This is the most common approach used today to solve dependencies between objects. In many of the enterprise class ASP.NET application, Dependency Injection is a common standard to follow. Let us understand Dependency Injection with an example.


In the example above, Employee class depends on EmployeeDAL class to get the data from the database. In GetAllEmployees() method of the Employee class, we create an instance of the EmployeeDAL (Employee Data Access Layer) class and then invoke SelectAllEmployees() method. This is tight coupling, EmployeeDAL is tightly copuled with the Employee class. Everytime the EmployeeDAL class changes, the Employee class also needs to change. EmployeeDAL cannot be mocked and hence unit testing becomes cumbersome and time consuming.

The same example can be re-written using dependency injection as shown below. First thing to notice is that, we are using interface types instead of concrete types. Using interfaces help us to plugin any implemenation of the interface, with less or no code modification at all. We are not creating the instance of the EmployeeDAL in the Employee class, instead we are passing it as a parameter to the constructor of the Employee class. As, we are injecting an instance of a class into a class that depends on it, we can call this process as Dependency Injection.


Dependency Injection is of 2 types.
1. Constructor Injection
2. Setter Injection.

We have already seen how to use Constructor Injection in the example above. An, example for Setter Injection is shown below. We are injecting an object instance through the Setter property, instead of a constructor. Hence, we call Setter Injection. It is very important to use the property EmployeeDataObject to access the instance of IEmployeeDAL, rather than the private variable employeeDAL. The property checks to see if employeeDAL is null, and throws the exception accordingly.