Wednesday, May 21, 2008

Design Patterns Series - part 1

What is Design Patterns :
Design patterns are recurring solutions to software design problems you find again and again in real-world application development. It is a proven solution for a specific problem in specific context. There are lot of design patterens in world. Here i am going to discuss GOF(Gang of Four) design patterens.

Types of Design Patterns:
I. Creational
II. Structural
III. Behavioral

I. Creational Patterns:
1. Abstract Factory -
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

2. Builder - Separate the construction of a complex object from its representation so that the same construction process can create different representations.

3. Factory Method - Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

4. Prototype - Specify the kind of objects to create using a prototypical instance, and create new objects by copying this prototype.

5. Singleton - Ensure a class has only one instance and provide a global point of access to it.

II. Structural Patterns:
1. Adapter - Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.

2. Bridge - Decouple an abstraction from its implementation so that the two can vary independently.

3. Composite - Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

4. Decorator - Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

5. Facade - Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use.

6. FlyWeight - Use sharing to support large numbers of fine-grained objects efficiently.

7. Proxy - Provide a surrogate or placeholder for another object to control access to it.

III. Behavioral Patterns:
1. Chain of Resp -
Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.

2. Command - Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

3. Interpreter - Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.

4. Iterator - Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

5. Mediator - Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.

6. Memento - Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later.

7. Observer - Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

8. State -Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

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

10. Template Method - Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

11. Visitor - Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.

Posted by at 09:08:39 | Permalink | No Comments »

Tuesday, May 13, 2008

object class

object class: Supports all classes in the .NET Framework class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy.

Members and Methods:
Equals
Finalize
GetHashCode
GetType
ReferenceEquals
ToString

Posted by at 08:26:06 | Permalink | No Comments »

Self Join - Sql server

Self-joins : A self-join is a query in which a table is joined  to itself.  Self-joins are used to compare values in a column with other values in the same column in the same table

Example:  In this example i am tring to insert data into Employee table with emp id, manager id. Manager id referes same tables emplid. Finally by using innerjoin i wanted to get data with manager name rather than manager id.

1. Create table
CREATE TABLE dbo.Employee

(

empId int NOT NULL IDENTITY (1, 1),

empName nvarchar(50) NOT NULL,

managerId int NULL

) ON [PRIMARY]

2. Insert Data into Table
1,Madhu,NULL
2,Bala,1
3,Krishna,1
4,Ram,1

3. SQL Query - Self Join

select a.empId, a.empName as Employee , b.empName as ManagerName

from Employee a, Employee b where b.empId=a.managerId


4. Output
2,Bala,Madhu
3,Krishna,Madhu
4,Ram,Madhu

Posted by at 06:11:33 | Permalink | No Comments »

Friday, April 25, 2008

enum - most useful functions

When i am doing .NET programming, many times i have get use of common tasks required related to ‘enum’. Then i taught of writing some common functions related to enum reading, parsing, iterating enum etc. Here we go …

What is enum: enumuration is comprised of a number of named constants.

Creating Enumuration :
public enum UIType
{
None,
Label,
DropDown,
TextBox,
CheckBox,
ListBox,
DateTimePicker
}

Convert Enumuration Item to string :
string itemValue = UIType.CheckBox.ToString();

Convert string to Enumuration instance:
returnValue = (UIType)Enum.Parse(typeof(UIType), str, true);

Note:
// While parsing enum it throws an ArgumentException if the string is found not to be one of the members of the enum. you must handle it.

Iterating Enum and reading data from Enum:
foreach
(string s in Enum.GetNames( typeof(UIType)))
dropdownlist1.Items.Add(s);

Convert integer to Enum instance:
UIType chkbox=(UIType)Enum.ToObject(typeof(UIType), (int)UIType.CheckBox);

 

Posted by at 10:58:42 | Permalink | No Comments »

Thursday, April 10, 2008

Maintain SQL Server 2005 DB changes in log table

Maintaining SQL Server DDL command changes in log file is most important and now it becomes very easy in SQL Server 2005 by using EVENTDATA () function.
 
EVENTDATA()
is a function is provided by SQL Server 2005, It provides
Information about an event that fires a DDL trigger is captured by using the EVENTDATA function. This function returns an xml value. The XML schema includes information about the following:
·         The time of the event.
·         The System Process ID (SPID) of the connection when the trigger executed.
·         The type of event that fired the trigger.

Steps for implementation of storing DDL log changes in Table

1.      Create table to store DDL Transactions


   CREATE
TABLE [dbo].[DDLLog](
   [logId] [int] IDENTITY(1,1) NOT NULL,
   [logData] [xml] NOT NULL,
   CONSTRAINT [PK_DDLLog] PRIMARY KEY CLUSTERED
   ([logId] ASC)) ON [PRIMARY]

2.     
Create Trigger to fetch DDL commands info and store in DDLLog table  

   CREATE
TRIGGER [Trig_DDLLog]
   ON DATABASE FOR DDL_DATABASE_LEVEL_EVENTS
   AS
   INSERT INTO dbo.DDLLog(logData)
   SELECT EVENTDATA()
   GO
   ENABLE TRIGGER [Trig_DDLLog] ON DATABASE

3.     
Create a test table to check 

   create table testTable (id int, description varchar(100))

4.     
Watch DDLLog table for log entry …it is available in XML format like below.

<
EVENT_INSTANCE>
<EventType>CREATE_TABLEEventType>
      <PostTime>2008-04-10T11:48:08.463PostTime>
      <SPID>53SPID>
      <ServerName>BSIAP021ServerName>
      <LoginName>saLoginName>
      <UserName>dboUserName>
      <DatabaseName>AdventureWorksDatabaseName>
      <SchemaName>dboSchemaName>
      <ObjectName>testTableObjectName>
      <ObjectType>TABLEObjectType>
      <TSQLCommand>
            <SetOptions ANSI_NULLS=ONANSI_NULL_DEFAULT=ON
            ANSI_PADDING=ONQUOTED_IDENTIFIER=ONENCRYPTED=FALSE
            />
<CommandText>create table testTable (id int, description varchar(100))
            CommandText>
      TSQLCommand>
EVENT_INSTANCE>

References: http://technet.microsoft.com/en-us/library/ms187909.aspx

Now it is so simple to maintain SQL Server DDL changes log 

 

*** END ***

Posted by at 05:04:38 | Permalink | No Comments »

Wednesday, April 9, 2008

Introducing SQL Server 2005 “Schema” and usage

A schema is nothing more than a named, logical container in which you can create database objects. A new schema is created using the CREATE SCHEMA DDL statement. Beginning in SQL Server 2005, each object belongs to a database schema. A database schema is a distinct namespace that is separate from a database user. Schemas can be created and altered in a database, and users can be granted access to a schema. A schema can be owned by any user, and schema ownership is transferable.


SQL Server 2005 has given us the ability to create schemas independent of the user, and by this we achieve separation of schemas and users. This gives us some considerable advantages:

  1. The first benefit is the ability to subdivide your database into logic of interest, rather as the Erwin modeling tool lets you create subject areas.
  2. You can provide better security at Schema level.
  3. Dropping database users is greatly simplified; dropping a database user does not require the renaming of objects contained by that user’s schema. Thus it is no longer necessary to revise and test applications that refer explicitly to schema-contained objects after dropping the user that created them
  4. Multiple users can share a single default schema for uniform name resolution.
  5. Shared default schemas allow developers to store shared objects in a schema created specifically for a specific application, rather than in the DBO schema
  6. Permissions on schemas and schema-contained objects can be managed with a higher degree of granularity than in earlier releases.
  7. Fully qualified name of object in SQL Server 2000 and earlier looks like
    [Server].[DatabaseName].[OwnerName].[ObjectName]
  8. SQL Server 2005’s fully qualified name for object looks like below
    [Server].[DatabaseName].[Schema].[ObjectName]
  9. You can able to transfer Schema ownership

Creating schema
CREATE SCHEMA Marketing
GO

Adding table object

CREATE TABLE Marketing.Leads

(
    LeadId INT,
    LeadDescription NVARCHAR(50)
)
GO


Accessing table object

SELECT * FROM Marketing.Leads
GO

After you have created schemas, your database looks like below



*** END ***

Posted by at 16:00:00 | Permalink | No Comments »

Sunday, March 30, 2008

creating MSDN-style documentation from .NET assemblies - SandCastle

Introduction: Sandcastle is a command line based tool created by Microsoft, used for creating MSDN-style documentation from .NET assemblies and their associated XML comments files. Sandcastle Help File Builder is to provide graphical and command line based tools to build a help file in an automated fashion.

Simple steps to generate help files for your assemblies 
=====================================

I. Softwares to be installed:
SandCastle - http://www.codeplex.com/Sandcastle
SandCstle help file builder - http://www.codeplex.com/SHFB

II. Configuration in Visual studio
Configure Visual studio to generate XML comment file along with assemblies

Project properties -> Build tab -> check “XML documentation file”

III. Configure SandCastle Help Builder
Create a new project and add your assembly to the project. Once you added assemblyname it appears with xml comment file. It looks like ”MyAssembly.dll, MyAssembly.xml”.

IV. Finally build help file
In SandCastle Help Builder -> Goto “Documentation” menu -> Build Project

Once you build project, It saves help project file as well once it gets build you will have your html help file.

****END**** 

 

Posted by at 15:15:34 | Permalink | No Comments »

SubSonic step by step

  

SubSonic step by step

I. SubSonic is a toolset that helps to

  1. Generate DAL layer
  2. Maintains and Generates SQL Script for DB Versioning
  3. Dynamic Query tool helps to use SQL Server etc without knowing SQL
  4. OR Mapper that extends to views and stored procedures

II. Installation

  1. Download SubSonic @ http://www.codeplex.com/subsonic/Release/ProjectReleases.aspx?ReleaseId=5636
  2. Install SubSonic by walking through steps, by default it stores at “Program Files\SubSonic\SubSonic 2.1 Beta 2\SubSonic”

III. Configuring inside Visual Studio 2005/ 2008 to use SubSonic

  1. Create new Website project
  2. Create another new class library project say ‘NorthWindDAL’ and add to solution as shown below (this project is going to act as DAL layer for web project)

  1. Add application configuration file to ‘NorthWindDAL’ class library (app.config)
  2. Create folder in NorthWindDAL project to keep all Subsonic generated classes
  3. Add below configuration sections to app.config file of NorthWindDAL project
    1. Add configsection

<configSections>
                  <section name=SubSonicService
                         type=SubSonic.SubSonicSection,SubSonic
                         requirePermission=false/>

   </configSections> 

  1. add Connection strings section

<connectionStrings>
<add name=NorthWind               connectionString=Server=yourserverName;Database=dbName;UID=youruserName;PWD=yourPassword;/>

   </connectionStrings> 

  1. add Subsonic service provider

<SubSonicService defaultProvider=NorthWind>
            <providers>
                  <clear/>
                  <add name=NorthWind
                         type=SubSonic.SqlDataProvider, SubSonic
                         connectionStringName=NorthWind
                         generatedNamespace=NorthWind  />
            </providers>
   </SubSonicService>

  1. Goto Bin folder of NorthWindDAL project and give reference to ‘SubSonic.dll’ available at “Program Files\SubSonic\SubSonic 2.1 Beta 2\SubSonic”
  2. and add reference to System.Web and System.Configuration

IV. Adding SubSonic Commander as external tool in Visual studio

Now you are ready for generate code.

When you click on External tool ‘SubSonicDAL’ , it generates code in specified folder that is ‘NorthWind’

That’s it…..  so simple

Posted by at 11:45:46 | Permalink | No Comments »

Tuesday, March 25, 2008

.NET 3.5 Features - JSON Serialization

Serialization & Deserialization:
The process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, are converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created. Serialization/Deserialization is used to transport or to persist objects.

Types of Serialization :
1. Binary Serialization
2. SOAP Serialization
3. XML Serialization
4. Custom Serialization

.NET 3.5 has new object called DataContractJsonSerliaizer used to JSON serialization for Ajax calls / Javascript calls.

Here i am writing JSONHelper class to Serialize and Deserialize
Add Reference: System.Runtime.Serialization.dll(.NET 3.0), System.ServiceModel.Web.dll(.NET 3.5)

using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
public class JSONHelper
{
    public static string Serialize(T obj)
    {
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());   
    MemoryStream ms = new MemoryStream();
    serializer.WriteObject(ms, obj);
    string retVal = Encoding.Default.GetString(ms.ToArray());
    return retVal;
    }

    public static T Deserialize(string json)
    {

    T obj = Activator.CreateInstance();
    MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));

    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    obj = (T)serializer.ReadObject(ms);
    ms.Close();

    return obj;
    }

}

Below class going to use for serialization and Deserialization


[DataContract]
public class Book
{

    private int _id;    private string _name;
    public Book() {}

    public Book(int id, string name)
    {
    _id = id;
    _name = name;
    }

   

    [DataMember]   
    public int Id
    {
    get { return _id; }

    set { _id = value; }
    }

    [DataMember]

    public string Name
    {
    get { return _name; }

    set { _name = value; }
    }
}

How to Use JSONHelper class to Serialize

Book b1 = new Book(1, “ASP.NET 3.5″);
string jsonOutput = JSONHelper.Serialize<Book>(b1);

Serialization output:
{”Id”:1,”Name”:”ASP.NET 3.5″}

How to Use JSONHelper class to Deserialize
Book b2 = JSONHelper.Deserialize<Book>(jsonOutput);

 

Posted by at 02:46:50 | Permalink | No Comments »

Wednesday, January 9, 2008

Maintain your DDL commands log & Restrict DDL commands in SQL Server 2005

Maintain your DDL commands log :

1. Create Audit Schema( which ever schema name you like it)
CREATE SCHEMA Audit

GO

2. Create table to hold DDL command log data
CREATE TABLE [Audit].[DDLLog](
[id] [int] IDENTITY(1,1) NOT NULL,
[logData] [xml] NOT NULL,
CONSTRAINT [PK_DDLLog] PRIMARY KEY CLUSTERED
([id] ASC)) ON [PRIMARY]
GO

3. Create trigger to store DDL command in table when any DDL command executed in DB
CREATE TRIGGER [Trig_DDLLog]
ON DATABASE FOR DDL_DATABASE_LEVEL_EVENTS
AS
INSERT
INTO [Audit].[DDLLog](logData)
SELECT EVENTDATA()
GO

4. Enable Trigger
ENABLE TRIGGER [Trig_DDLLog] ON DATABASE

Thats all. Now on if you use any DDL command on DB, it maintains log in Audit.DDLLog table.
____________________________________________________________

Restrict DDL commands :

Below Trigger restrict user from Droping tables and Altering tables. If you wanted to do that you must disable trigger first before you proceed to Alter or Drop table.

CREATE TRIGGER Trig_RestrictDropAlterTable

ON DATABASE

FOR DROP_TABLE, ALTER_TABLE

AS

PRINT ‘You must disable Trigger “Trig_RestrictDropAlterTable” to drop or alter tables!’

ROLLBACK


To Disable Trigger
DISABLE TRIGGER [Trig_RestrictDropAlterTable ] ON DATABASE

To provide next level of security from Droping and Altering tables, you can create schema, and give permissions to only one main user on newly created schema. Create this trigger under that schema. So others don’t have permission to disable trigger. So others can’t be able to modify DB structures. Only main users will disable trigger and do nessasary changes in structures.

*** END ***
Posted by at 16:00:00 | Permalink | No Comments »