Showing posts with label c#. Show all posts
Showing posts with label c#. 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.


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 :-



















Sep 22, 2011

Displaying the HTML format content into Rich text box using c#

In general way .net programmers use the built-in web browser control to display the HTML format content in the windows applications.it is very simple to do.But the web browser control visual appearance (font wise) is not same as the windows controls (Label,Rich Text Box) appearance.we never get windows font look using web browser control because always there is difference between web and windows visualization.
To over come this apply the simple trick here.
  1.  Place the rich text box control in the form.
  2. Create the Web Browser control form the code behind
  3.  Bind the html content to web browser.
  4. Select and copy the html content Using the HTML document ExecCommand()
  5. Paste content to rich text box using the paste() method of Rich text box
Here is the code looks like.

var webBrowser = new WebBrowser();
webBrowser.CreateControl(); // only if needed
webBrowser.DocumentText = "<html><body><b>DotnetCyphers</b></body></html>";
while (webBrowser.DocumentText != "<html><body><b>DotnetCyphers</b></body></html>")

Application.DoEvents();
webBrowser.Document.ExecCommand("SelectAll", false, null);
webBrowser.Document.ExecCommand("Copy", false, null);
richTextBox1.Paste();
richTextBox1.ReadOnly = true;

ExecCommand() executes a command on the current document,/current selection/ the given range.

Aug 9, 2011

Understanding Web Communications

Like all client-server applications, web applications have two distinct components:
Client Also known as the front-end interface, the web browser presents the user interface, accepts user input, and sends data to the server for processing.
Server Also known as the back end, the web server responds to requests from clients for specific pages. It responds with an HTML page that includes instructions for how to generate the user interface.

The web browser (the client) and the web server communicate by using Hypertext Transfer Protocol (HTTP), a text-based network protocol assigned to TCP port 80. If the server has a certificate, the client and server can use HTTP Secure (HTTPS) to authenticate the server and encrypt communications. HTTPS is assigned to TCP port 443.

Communications typically follow these steps:
1. A user enters an address, such as http://www.dotnetcypher.com/, into the web browser.
2. The web browser connects by using HTTP and sends a GET request, such as GET / (to retrieve the root page), to the web server.
3. The web server processes the requested page. This action might cause the server to return static HTML or image files, or it might execute application code(ASP.NET code) that performs workflow tasks or connects to a database.
4. The web server uses HTTP to send a response back to the web browser. If the request was processed successfully, the web server returns the HTTP status code 200, along with an HTML document. If the server cannot find the page, it returns the code 404. If the user requests an outdated or relocated page, the server returns the code 302 and the new URL so that the browser can access the correct page. This is known as redirection. Several other responses are possible as well, depending on the particular situation.
5. The user’s web browser then processes the response by displaying the HTML page (if the code was 200), showing an error message (if the code was 404), or loading a different page (if the code was 302). Other server responses are similarly handled by the browser, depending upon the response.

This process is repeated each time the user clicks a button or link(any of post back behavior control).

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...!