Showing posts with label csharp. Show all posts
Showing posts with label csharp. Show all posts

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.


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.

Aug 8, 2011

Find out the open files in the specified directory path using c#

Every developer getting following errors frequently. i.e."The file could not be accessed."File "can not be deleted"
Recently i also faced the same problem in one of my project task where i worked with some of open pdf files.Generally we will get these type of errors ,due to the following reasons
1. File is opened already.
2. File is using by another process
Finally find out the following simple and great example in c#..
This example is using the try-catch blocks.

Check all files from the specified folder:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; //Required for directory and file operations

namespace File_operations
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo Dir = new DirectoryInfo("C:\\Applictions\\SampleFiles");\\ Folder Path
FileInfo[] filePaths = Dir.GetFiles("*.*");\\Get all the files
foreach (FileInfo file in filePaths)
{
if (IsFileOpen(file))
Console.WriteLine("File is opened");
else
Console.WriteLine("File is not opened");
}
Console.ReadLine();
}

public static bool IsFileOpen(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
return true;//file is opened
}
finally
{
if (stream != null)
stream.Close();
}
return false;//file is not opened
}
}
}



Find out specified format of files:

Change the following lines of code in the above example to get specific format files from a folder.
FileInfo[] filePaths = Dir.GetFiles("*.pdf");//Get all the pdf files from the folder
FileInfo[] filePaths = Dir.GetFiles("*.doc");//Get all the word document files from the folder
FileInfo[] filePaths = Dir.GetFiles("*.jpg");//Get all the jpg image files from the folder


please feel free to leave comments...!