Dec 28, 2013

Design Patterns in CSharp

What is design Pattern in c#?

Design Patterns are categorized into 3 types and they are:
  1. Creational Design Patterns.
  2. Structural Design Patterns.
  3. Behavioral Design Patterns.
What are Creational Design Patterns?

These patterns deal with the process of objects creation. The flowing are the different types of Creational Design patterns.
  1. Abstract Factory Pattern: - Create instances of several classes belonging to different families.
  2. Factory Pattern: - Create instances of derived classes.
  3. Builder Pattern: - Separates an object construction from its representation.
  4. Lazy Pattern: - Create a duplicate object or clone of the object.
  5. Prototype Pattern: - Specify the kind of objects to create using a prototypical instance, and create new objects by copying this prototype.
  6. Singleton Pattern: - Ensures that a class can have only one instance.
What are Structural Design Patterns?

These patterns deal with the composition of objects structures. The flowing are the different types of Structural Design patterns.
  1. Adapter Pattern: - Interfaces of classes vary depending on the requirement.
  2. Bridge Pattern: - Class level abstraction is separated from its implementation.
  3. Composite Pattern: - Individual objects & a group of objects are treated similarly in this approach.
  4. Decorator Pattern: - Functionality is assigned to an object.
  5. Facade Pattern: - A common interface is created for a group of interfaces sharing a similarity.
  6. Flyweight Pattern: - The concept of sharing a group of small sized objects.
  7. Proxy Pattern: - When an object is complex and needs to be shared, its copies are made. These copies are called the proxy objects.
What are Behavioral Design Patterns?

These patterns deal with the process of communication, managing relationships, and responsibilities between objects. The flowing are the different types of Behavioral Design patterns.
  1. Chain Or Responsibilities Pattern: - In this pattern, objects communicate with each other depending on logical decisions made by a class.
  2. Command Pattern: - In this pattern, objects encapsulate methods and the parameters passed to them.
  3. Observer Pattern: - Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
  4. Interpreter Pattern: - A way to include language elements in a program.
  5. Iterator Pattern: - Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
  6. Mediator Pattern: - Define an object that encapsulates how a set of objects interact. In other words, it defines simplified communication between classes.
  7. Memento Pattern: - Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.
  8. State Pattern: - Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
  9. Strategy Pattern: - Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
  10. Visitor Pattern: - Defines a new operation to a class without change.
  11. Template Method Pattern: - Defer the exact steps of an algorithm to a subclass.


Sep 9, 2012

What is Trigger?

A Trigger is a SQL procedure that initiates an action when an events INSERT, DELETE , UPDATE occurs. Triggers are stored in and managed by the DBMS.Triggers are used to maintain the referential integrity of data by changing the data in a systematic fashion. A trigger cannot be called or executed; the DBMS automatically fires the trigger as a result of a data modification to the associated table. Triggers can be viewed as similar to stored procedures in that both consist of procedural logic that is stored at the database level. Stored procedures, however, are not event-driven and are not attached to a specific table as triggers. Stored procedures are explicitly executed by invoking the procedure while triggers are implicitly executed. In addition, triggers can also execute stored procedures.

Nested Trigger: A trigger can also contain INSERT, UPDATE and DELETE logic within itself, so when the trigger is fired because of data modification it can also cause another data modification, thereby firing another trigger. A trigger that contains data modification logic within itself is called a nested trigger.

Two types of Triggers

1) DML Trigger
DML is abbreviation of Data Manipulation Level. DML contains the actual data which is stored in the database schema. UPDATE, INSERT, DELETE, SELECT clause are used to manipulate database. 
There are two types of DML Triggers
    1.Instead of Trigger:- Instead of Triggers are fired in place of the triggering action such as an insert, update, delete.
    2.After Trigger:-  After triggers execute following the triggering action, such as an insert, update, delete.

2) DDL Trigger
DDL is abbreviation of Data Definition Level. DDL contains schema of the database object. It was always dream of all DBA, when change in mission critical schema of the database or server is attempted it is prevented immediately informing DBA and users automatically. DDL Trigger can now make this dream true. Definition of DDL Trigger is a special kind of trigger that fire in response to Data Definition Language (DDL) statements. They can be used to perform administrative tasks in the database such as auditing and regulating database operations.


Feb 28, 2012

How to convert the object to xml and xml to object.


Convert the object to xml using XML Serializer class. XML Serialization coverts (Serializes) the public fields and properties of an object, or parameters and return values of method, into an XML stream.

The following namespaces are required for this xml serialization.
using System.IO;
using System.Xml;
using System.Xml.Serialization;

To show this conversion, creating sample class called student. It looks like following
Student class:-

/// class for student properties
public class Student
{
public int StudentId { set; get; }
public string StudentName { set; get; }
public DateTime DOB { set; get; }
public string address { set; get; }
}


Object to Xml:-
Now create the following class instances for the serialization of the object
1) XmlDocument object to represents the converted xml
2) XmlSerializer object to covert (Serialize) the public fields and properties of an object, or parameters and
return values of method, into an XML stream.
3) MemoryStream object to hold the serialized stream in memory.
After creating all the above instances call the serialize method of XmlSerializer object with parameters stream and object, it converts the object to stream and store into passed stream object and set the stream position to begin.
Now load this stream in to xml document by calling the Load() of XmlDocument object.

/// Method to convert the object to xml using XmlSerializer.
public static XmlDocument ConvertToXml(Student student)
{
MemoryStream ObjStream = new MemoryStream();
XmlDocument ObjDocument = new XmlDocument();
XmlSerializer ObjSerializer = new XmlSerializer(student.GetType());
ObjSerializer.Serialize(ObjStream, student);
ObjStream.Seek(0, SeekOrigin.Begin);
ObjDocument.Load(ObjStream);
return ObjDocument;
}

Xml to object:-
Deserialize to the object from the xmlDocument object or xml file using the Deserialize method of XmlSerializer class and StringReader object which holds the xml content.

/// Method to convert the xml to object using XmlSerializer.
public static Student ConvertToObject(XmlDocument document)
{
Student ObjStudent = new Student();
StringReader ObjReader = new StringReader(document.InnerXml);
XmlSerializer ObjSerializer = new XmlSerializer(typeof(Student));
ObjStudent = (Student)ObjSerializer.Deserialize(new XmlTextReader(ObjReader));
return ObjStudent;
}

Call these methods form any of the class like following

/// Fill the student class object with values
Student student = new Student();
student.StudentId = 1;
student.StudentName = "Tom Smith";
student.DOB = DateTime.Now;
student.address = "Chennai,India";

/// Call the Convert to xml method
XmlDocument xmlDocument = new XmlDocument();
xmlDocument = XmlOperation.ConvertToXml(student);

/// Call the Convert to object method
Student student1 = new Student();
student1 = XmlOperation.ConvertToObject(xmlDocument);


Oct 29, 2011

"using" keyword in c#

All the c# programmers daily coding life start's with "using" why i am saying like this,the first word of the every c# code file is "using". so we have to know what is this first word ? How to use it?.That's what i am trying to explain in this post here.
In c#,we can use the using keyword as two possible ways are as a Directive and as a Statement.
1) using as a directive:
1) As all the programmers know using is used to importing the namespaces.we can use types available in that namespaces by declaring the namespace with "using"
           Example:- using System.Web; 
For example here i am importing the System.Web namespace,now i can use all the types like HtmlString, HttpApplication, HttpApplicationState etc. of Web namespace in further coding of current file.

2) Also use to define the alias for the nested namspaces.
           Example:- using MyControls=MyComponent.Web.UI.Controls.;
In the above example, we can use Mycontrols instead of using MyComponent.Web.UI.Controls to use Controls class like.
MyComponent.Web.UI.Controls objControl=new MyComponent.Web.UI.Controls();
MyControls objControl=new MyControls();
2) using as a statement:
When we use "using" as Statement it defines the scope and allows the programmer to release the resources used by the object in the defined scope.
with out using keyword:
A simple and straightforward  approach to connect to a database server and read data
  SqlConnection con = new SqlConnection(conString);
  SqlDataReader reader = null;
 SqlCommand cmd = new SqlCommand(cmdString,con);
 con .Open();
 reader = cmd.ExecuteReader();
 while (reader.Read())
      {
           //Do 
       }
  reader.Close();
 con .Close(); 
However, the above given code may generate error.
If any exception occurs inside while block it throws exception the connection.close() process will not executed due to the exception.To avoid this situation, we can take the help of the try....catch... finally block   by closing the connection inside the finally block or inside the catch block.
with using keyword:
"Using" keyword takes the parameter of type IDisposable.Whenever you are using any IDisposable type object you should use the "using" keyword  to handle automatically when it should close or dispose.Internally using keyword calls the Dispose() method to dispose the IDisposable object.
So the code will be modified like :
using(SqlConnection con= new SqlConnection(conString) )
         {
            SqlCommand cmd = new SqlCommand(cmdString, con);
            con.Open();
             using (SqlDataReader reader = cmd.ExecuteReader())
             {
                 while (reader.Read())
                 {
                   // statements
                 }
             }
        }
 In the above code  if any exception occurs then dispose() will be called and connection will closed automatically.

Multiple objects can be used in with a using statement, but they must be declared inside the using statement.
In the above example also we used multiple objects are cmd,reader.so we removed the both objects closed methods.
Example:-
using (Type t1 = v1, t2 = v2, …, tN = vN) 
{
//statements
}
or                                  
using (Type r1 = v1)
{
   using (Type t2 = v2)
    {
      …......
         using (Type tN = vN)
           {
           // statement
            }
       }
 }
Above both code examples are equal.

Sep 23, 2011

Light box Effect in .net Windows application

Lightbox is an effect that fades the pagein the background to show you new content in the foreground.
We may call it Lightbox, or Greybox, or Thickbox, but it’s always the same effect

We can add this effect easily in web application using javascript, css or any of third party plugins like Jquery, ajax. Now we can see how to add the Light Box effect in Windows Forms in sinple way with out using any javascript or any third party dll's.
  1. Create two forms namely Form1 and Form2.
  2.  Set following properties for the Form2.
  • BackColor=ControlDark  (what color we want to show,we can select that color)
  • FormBorderStyle=None
  • ShowInTaskbar=False
  • SizeGripStyle=Hide
  • StartPosition=Manual
  • Opacity=50%(opacity value depends on visiblity of background form controls).
    3. Place the button in the Form1,write the following code in the button click event

    private void button1_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2();
            form2.SuspendLayout();
            int BorderWidth = 0;
           
//Get the border width values of the form
            if (this.VerticalScroll.Visible == true)
                BorderWidth = (this.Width - (this.ClientSize.Width + 
                                         SystemInformation.VerticalScrollBarWidth)) / 2;
            else
                BorderWidth = (this.Width - this.ClientSize.Width) / 2;
           
//Get the Title bar height of the form
            int TitlebarHeight = this.Height - this.ClientSize.Height - 2 * BorderWidth;
           
//Setting the Current form(Form1) bounds to the Form2 bounds
            if (this.VerticalScroll.Visible == true)
                form2.SetBounds(this.Left, this.Top + TitlebarHeight + BorderWidth, this.ClientSize.Width+ SystemInformation.VerticalScrollBarWidth + BorderWidth * 2,this.ClientSize.Height + BorderWidth);
            else
                form2.SetBounds(this.Left, this.Top + TitlebarHeight + BorderWidth, this.ClientSize.Width+BorderWidth * 2, this.ClientSize.Height + BorderWidth);           
            form2.PerformLayout();
            form2.Owner = this;
            form2.Show();
            // Here we can show popup window /Dialog box/another form also like Message Box shown in this code.
            MessageBox.Show(this,"This is the light box effect","DotNetCypher", MessageBoxButtons.OK ,MessageBoxIcon.Information);
            form2.Close();//disableing the effect
        }
Here are the output forms looks like..

Before Light Box:-



After Light Box :-