Friday, October 1, 2010

Introducing jQuery

It is JavaScript that brings a HTML page to 'life'. Whether it is client-side validation, animating the page elements or calling the server in the background to get updated page, one can use JavaScript to achieve all this and much more. However, using JavaScript in its 'raw' state compels the developer to write multiple lines to implement each of the afore-mentioned functionality and for each application. The pit-fall in such an approach is that each application will have its own pattern and trying to reuse JavaScript code developed for one application, will ultimately result in re-factoring most of the code so that it meets the requirements of both the applications. This is where JavaScript libraries come into picture. These libraries encapsulate the ordinary yet oft used functionalities (e.g. validation, selection of elements etc.) and provide simplified API to access these functionalities. Among the JavaScript libraries, one of the most used is jQuery. In this discussion, the focus will be on the basics of jQuery. The first section will be about the whys and wherefores of the jQuery. The second section will provide details about using various functionalities of jQuery. That’s the agenda for this discussion.

jQuery – the Whys and Wherefores

To understand how jQuery can ease web client (JavaScript based) development, one has to understand two aspects of jQuery. They are:

1. Functionalities

2. Modules

Understanding the functionalities/services provided by jQuery will tell you what jQuery provides and understanding the modules that constitute jQuery will tell you how to access the services provided by jQuery. Here are the details.

1. Functionalities

The functionalities provided by jQuery can be classified into following

a. Selection

b. Attributes handling

c. Element manipulation

d. Ajax

e. Callbacks

f. Event Handling

Among the above listed functionalities, selection, element manipulation and event handling makes common tasks very easily implementable or trivial.

a. Selection

Using this functionality one can select one or multiple HTML elements. The raw JavaScript equivalent of the selection functionality is

document.getElementByID(‘’) or

document.getElementByTagName(‘’)

b. Attributes handling

One of most required task in JavaScript is to change the value of an attribute of a tag. The conventional way is to use getElementByID to get the element and then use index to get to the required attribute. jQuery eases it by using selection and attributes handling functionality in conjunction.

c. Element handling

There are scenarios where the values of tags need to be modified. One of such scenarios is rewriting text of a

tag based on selection from combo box. That is where element handling functionality of jQuery comes handy. Using the element handling or DOM scripting, as it is popularly known, one can not only access a tag but also perform manipulation such as appending child tags to multiple occurrences of a specific tag without using for loop.

d. Ajax

Ajax is of the concept and implementation that brought the usefulness of JavaScript to the fore. However, it also brought the complexities and the boilerplate code required for using Ajax to its full potential. The Ajax related functionalities of jQuery encapsulates away the boilerplate code and lets one concentrate on the result of the Ajax call. The main point to keep in mind is that encapsulation of the setup code does not mean that one cannot access the Ajax related events. jQuery takes care of that too and one can register to the Ajax events and handle them.

e. Callbacks

There are many scenarios in web development, where you want to initiate another task on the basis of completion of one task. An example of such a scenario involves animation. If you want to execute a task after completion of an animation, you will need callback function. The core of jQuery is implemented in such a way that most of the API supports callbacks.

f. Event handling

One of the main aspects of JavaScript and its relationship with HTML is the events triggered by the form elements can be handled using JavaScript. However, when multiple elements and multiple events come into picture, the code complexity becomes very hard to handle. The core of jQuery is geared towards handling the events in such a way that complexity can be maintained at manageable levels.

Now that we have discussed the main functionalities of jQuery, let us move onto the main modules of jQuery and how the functionalities map onto the functionalities.

2. Modules

The modules contain APIs that have one-to-one mapping with the functionalities (most of the time). The main modules of jQuery are

a. Selectors

b. Attributes/CSS

c. Manipulation

d. Ajax

e. Callback

f. Event Handling

The names are indicators as to which functionalities they map to. Here are the details

a. Selectors

As the name indicates, selectors provide the functionality to select elements. As mentioned earlier, selectors are denoted by dollar ($) sign. Some of the commonly used selectors are

· all selector – selects all the elements

· :first and :last selectors – select the first and last occurrence of a recurring element/tag.

· :eq (index) – selects the element with the index having the value passed as argument.

· #id – selects the element whose id is passed.

Following statements show how selectors are commonly used

$("p")

The above statement selects all

elements.

$("p.start")

It selects all

elements with class whose name is “start”.

$("p#demo")

It selects the first

element with "demo" as id.

b. Attributes/CSS:

The attribute handling functionality can be found in the API of this module. It also provides manipulation of CSS classes attached to the elements or attributes. Some of the most commonly used API is

· .attr( attributeName ) – gets the value of an attribute for the first element having the attribute with name equal to the passed attribute name

· .addClass (classname) – sets the CSS class of a particular element.

· .val() - gets the current value of the first element in the set of matched elements. It is primarily used to get the values from form elements.

· .css(name, value) - sets the style property that matches the name of the style passed to the value passed for style

Following is an example of css() API

$("p").css("background-color","yellow");

It will set the style of all the

elements. In this case the style is background color. Its value is set to yellow.

c. Manipulation

The API related to DOM scripting can be found in this module. In other words, the API in this module is used to manipulate DOM in one way or other. One point to keep in mind is that many of the API in this module overlaps with API in Attributes/CSS module. Some of the most commonly used API is:

· .after(content) – adds the specified content after each of the elements from a set of matched elements.

· clone() – duplicates the elements in a set o matched elements.

· replaceWith(newContent) – replaces each element from a set of matched elements with the specified content.

The term “set of matched elements” means that these APIs need to be used along with selectors. A selector may return more than one element. Hence, the returned values are collectively termed as set. For example, the following statement appends “This is appended” to all the

elements

$("p").append("This is appended ");

And the following replaced all the values between

and <

d. Ajax

The Ajax related functionality can be found in this module. Following are the most commonly used APIs

· get() – retrieve data from the server specified by the URL, with the data passed.

· Post() – same as get but uses POST HTTP method to retrieve the data.

For example, the following statements depict the use of get() API

$.get(

"http://mysite.org/test.php",

function(data) { alert(data); },

);

In the above example, get takes two parameters – URL of the remote site and the callback that performs some operation on the data passed into the callback by get API. Here the URL is “http://mysite.org/test.php” and the operation performed is alerting the user.

e. Callbacks

One of the aspects of jQuery that is heavily used is callbacks. A callback is a function that is registered with another method and gets called when a specific condition, such as response from the server is fulfilled. Following statements display callback in its simplest form

$("p#test").hide(1000,function(){

alert("The paragraph is now hidden");

});

The hide() API takes two arguments, speed with which the element has to be hidden and the method that needs to be called when the task of hiding is done. In the above example, when the

element with id as test is hidden an alert is displayed. In this case callback function is directly defined within hide().

f. Event handling

As stated before, event handling is part of the core functionalities of jQuery. However, to use it, one point needs to be understood. It is the place (within the HTML document) where event and its handler will be attached. The answer to this question is the correct place is the section which gets called before body section is called and it is the head section.

To attach a handler with an event, the statements need to be place within the ready() function of document DOM element. For example, following statements attach the click event of button to its handler

$(document).ready(function(){

$("button#test").click(function(){

$("p").hide();

});

});

The click event button with id ‘test’ is attached to the handler using callback functionality which in turn is defined inside the callback for ready(). One point to keep in mind is that any kind event handling code must be defined inside ready() and read() itself must be a part of the head section ().

This completes the bird’s eye view of the APIs of jQuery. Next section will deal with the steps in using jQuery and some its APIs. It will also cover how to use some of the APIs discussed in this section.

Developing with jQuery – Step-by-Step:

The steps to use jQuery include downloading and installing (in some cases), referencing the jQuery library and calling the API. Following are the details

1. Downloading and installing jQuery

This step is not mandatory. The reason for this step being optional is that there are alternative ways to reference jQuery library which will be discussed as a part of next step. To download jQuery, one has to download it from the following URL

http://docs.jquery.com/Downloading_jQuery#Current_Release

Unzip it to the local folder from where it will be referenced. That completes the step for downloading and installing.

2. Referencing the Library

There are two ways to reference jQuery. They are

a. Local reference

c. Remote reference

Both use src attribute of

b. Remote reference

When the library is hosted on another site ( e.g. code.google.com) and the URL is used to access the functionalities of the library, it is known as remote referencing. The steps to remotely refer jQuery hosted at code.google.com are as follows

i. Refer to the jQuery hosted on code.google.com using the src attribute of the

The main point to remember is that the URL for the jQuery library may change based on the version of jQuery.

ii. Call the initialization function i.e. ready() after the referencing statement. The following example shows both the steps together

3. Calling the API

To call the API, one can use one of the following ways

a. Fully qualified name

When calling the API with fully qualified name, the statement starts with jQuery. The following statement calls the selector using fully qualified name

jQuery(‘:first’)

b. Using Dollar sign

The dollar sign ($) can be used to call the APIs, instead of using ‘jQuery’. The following statement uses dollar sign to call the selector instead of jQuery

$(‘:first’)

4. Putting it all Together:

Let’s put all the steps together. The following example will implement a simple time server. There are two files –one that sits at the server and the one executed at the client. They are

1. SimpleTimeServer.php – it will reside at the server and respond with the current server time.

2. Client.html – it will send request to the server for current server time via Ajax and display the response it
receives.

First is the SimpleTimeServer.php. It will have the following code

$time_now=mktime(date('h')+5,date('i')+30,date('s'));

$time_now_str = date('l M dS, Y, h:i:s A',$time_now)

print $time_now_str;

?>

It uses the mktime function to get the current date time and the date function to convert it to human readable string.

Next is Client.html. Following is the code

Current Date and Time

width="100%" align="center">

The core of the client is the getTime function. It make call to the server using the get API and displays the received value using the manipulator html(). Then the function uses setTimeOut() to call itself at specified interval. The getTime() is called when the body section loads, thus once the body is loaded the time is displayed at a specific interval.

That completes the example. What I discussed here is just the tip of the ice-berg. In the next article, the selectors will be covered in details. Till then…

Saturday, January 23, 2010

Moving on...

I have moved on to wordpress. Please update your bookmarks

http://aprajshekhar.wordpress.com

Wednesday, August 20, 2008

Database Programming in C# with MySQL : Using OleDB

Persisting the data processed by an application has become the norm of the day. The storage can be either file-system using normal files or databases. The functionalities provided by database packages make them more attractive proposition. With the advent of Open Source database products such as MySQL, use of database for data persistence more or less ubiquitous. Hence, no language or platform can ignore providing libraries to access databases especially MySQL and .Net, as a platform and C#, as a language, are no exceptions. There are three main Data Providers, as the database access APIs are known as in .Net, which are SQL Data Provider, OleDB Data Provider and ODBC Data Provider. Of these I would be focusing on OleDB Data Provider and on using it to work with MySQL database. First section would provide insight into the various APIs that forms the OleDB. Second section would detail the steps required to access MySQL using OleDB. In the last section, I would develop a real-world application that implements the theory provided in first two sections. That’s the outline for this discussion.

OleDB – What is it:

OleDB is one of the three Data Providers supported by .Net. It is part of System.Data namespace specifically all the classes of OleDB come under System.Data.OleDb namespace. OleDB had been around before .Net come picture. What OleDB provider does is that it provides mechanism to access OleDB data source (Databases that could be connected through OleDB) in managed space of .Net. in essence, OleDB Data Provider sits between .Net based application and OleDB. The main classes that form OleDB Data Provider are:

1. OleDbConnection

2. OleDbCommand

3. OleDbDataAdapter

4. OleDbDataReader

Most of the classes are arranged in a hierarchical manner, that is, one provides the instance of the other. For example, OleDbCommand provides instance of OleDbDataReader.

1. OleDbConnection:

It represents a connection with a data source such as a database server. Each connection represented by OleDbConnection’s instance is unique. When an instance of OleDbConnection is created all its attributes are given or set to their default values. If the underlying OleDB provider doesn’t support certain properties or methods the corresponding properties and methods of OleDbConnection would be disabled. To create an instance of OleDbConnection, its constructor has to be called with connection string. Connection string specifies the parameters needed to connect with the data source. Following statement shows such an example:

OleDbConnection conn = new OleDbConnection( "Provider=MySqlProv;" +

"Data Source=localhost;" +

"User id=UserName;" +

"Password=Secret;"

);

The above example provides a connection to MySQL server at local machine.

2. OleDbCommand:

OleDbCommand represents a command to be executed against a data source connected through OleDbConnection instance. In the context of databases the command can be an SQL statement or a Stored Procedure. To get an instance of OleDbCommand, its constructor has to be called with instance of OleDbConnection class and the string containing the SQL query to be executed. For example, the following statement creates an instance of OleDbCommand named command:

string queryString = "SELECT OrderID, CustomerID FROM Orders";

OleDbCommand command = new OleDbCommand(queryString, conn);

3. OleDbDataAdapter:

It represents a set of commands and a connection that is used to fill a DataSet. In other words it is a bridge between DataSet and the data source to retrieve and update the data. The constructor of the OleDbDataAdapter needs to be called with SQL select statement and OleDbConnection instance. To cite an example following creates an instance of OleDbDataAdapter named adapter

OleDbDataAdapter adapter = new OleDbDataAdapter(queryString, conn);

4. OleDbDataReader:

It provides a mechanism to read forward only stream of records and columns from the data source. To obtain an instance of OleDbDataReader, executeReader() method of OleDbCommand has to be called. Following statement does the same:

OleDbDataReader reader = command.ExecuteReader();

One point to keep in mind while using OleDbDataReader is that while it is being used, the corresponding connection would be kept busy, as it uses a stream to communicate with data source.

So now as the main classes have been discussed, next step is in understanding how MySQL and OleDB Data Provider link with each other. What OleDB Data Provider does exactly is that it calls the underlying OleDB Provider. So it is the OleDB provider that communicates with the data source. For each database system, the OleDB Provider has to be provided by vendor of the database. In this case the vendor is MySQL. Hence unless MySQL provides the OleDB provider, OleDB Data Provider wont be able to communicate with database server. The Provider supplied by MySQL has to be registered with .Net so that OleDB Data Provider can call the Provider. The other term for the OleDB Provider is Database Driver. In case of MySQL it is also known as MySQL connector. Next I will be discussing the steps to access MySQL.

Accessing MySQL – Step by Step:

As the Data Provider in discussion is OleDB, the steps to access MySQL doesn’t change from accessing any other databases. The point of difference comes in connection string. Lets look at the steps:

1. Creating the Connection object

2. Instantiating the Command object

3. Obtaining the DataReader object

4. Retrieving the records

The connection string comes into picture at first step. And it is the connection string that decides which underlying Driver has to be called.

1. Creating the Connection object:

Creating a connection object really means obtaining an instance of OleDbConnection class. The constructor takes connection string as parameter. Connection string is composed of the following:

a. Provider – it specifies the vendor of the driver. In case of MySQL, the value

would be MySqlProv.

b. Data Source - the name of the machine where the server is residing.

c. User Id – the user name with which to connect to the database

d. Password – the password with which to connect with database

The connection string is a collection of name value pairs separated by semicolon. For example, to connect with a database at localhost with user name as root and no password, the connection string would be:

string strConnect = "Provider=MySqlProv;" +

"Data Source=localhost;" +

"User id=root;" +

"Password=;"

And OleDbConnection instance that can be obtained by using the connection string would be thus:

OleDbConnection conn = new OleDbConnection( strConnect);

2. Instantiating Command Object:

The next step in accessing MySQL is creating an instance of OleDbCommand class so that an SQL statement to be executed at database. To obtain an instance of OleDbConnection, its constructor needs, the SQL statement to be executed and the connection through which the database can be connected. For example, the following statements create an instance of OleDbCommand named command:

string strSQL= “Select * from user_master”;

OleDbCommand command = new OleDbCommand(strSQL, conn);

3. Obtaining Data Reader Object:

Next step is to retrieve the result. But for that a stream is required that fetches data from the database. This requirement can be met by obtaining an object of OleDbDataReader. As discussed in first section, it is a forward only stream using which the rows and columns returned by the executed command can be read. To get an instance of OleDbDataReader, ExecuteReader() method of OleDbCommand instance. So accordingly to get an instance named reader, the statement would be:

OleDbDataReader reader = command.ExecuteReader();

4. Retrieving the records:

The records can be retrieved using the Read() method of OleDbDataReder. It returns true if more records are available else returns false. To access the specific column GetString() method of OleDbDataReder. It takes column no. as the argument. For example, following code block reads the value of second column of each row (columns are zero indexed):

while( reader.Read())

Console.WriteLine(reader.GetString(1));

For extracting data from columns having type different from varchar, OleDb Data Provider gives different .Net types mapped to SQL types.

That brings us to the end of second section. In the next section, I would be developing a small application that would use MySQL OleDB Data Provider to access MySQL database server.

MySQL Access – In Real World:

The example I will be developing would primarily focus on a class that returns OleDbConnection, OleDbCommand and OleDbDataReader instances. It contains two classes:

Data – It creates and returns instances of OleDbConnection, OleDbCommand and

OleDbDataReader.

DataTest – It tests the functionalities provided by Data class.

Lets start with Data class. Its parameterized constructor creates the connection string from the parameters passed and instantiates OleDbConnection connection class using the string. The getDataReader method returns a OleDbDataReader instance based on the OleDbCommand instance passed. Here is the class:

using System;

using System.Data;

using System.Data.OleDb;

namespace MySQLApp

{

///

/// Creates and returns OleDbConnection, OleDbCommand and ///OleDbDataReader

///

public class Data

{

private OleDbConnection connection=null;

private OleDbCommand command=null;

string connectionString=null;

public Data()

{

connectionString="";

}

public Data(string host, string userId, string password)

{

connectionString=" Provider=MySqlProv; Data Source="+host+"; User id="+userId+"; Password="+password+";";

connection=new OleDbConnection(connectionString);

command=new OleDbCommand();

}

public OleDbCommand getCommand(string sqlString)

{

command.Connection=connection;

command.CommandText=sqlString;

return command;

}

public OleDbDataReader getReader(OleDbCommand command)

{

return command.ExecuteReader();

}

}

}


The next class is the DataTest. It creates an instance of the Data class and executes an SQL statement using it. Here is the code:

using System;

namespace MySQLApp

{

///

///Creates an instance of Data class to execute a simple SQL ///statement.

///

class DataTest

{

///

/// The main entry point for the application.

///

[STAThread]

static void Main(string[] args)

{

Data data=new Data("localhost","root","root123");

data.getReader(data.getCommand("select * from

user"));

while( reader.Read())

Console.WriteLine(reader.GetString(1));

}

}

}


That brings us to the end of this discussion. The application developed here would form the basis of the advanced operations using DataAdapter in the next part of this discussion. Till then…

This article can be found at:
http://www.aspfree.com/c/a/Database/
Database-Programming-in-C-Sharp-with-MySQL-Using-OleDB/

Saturday, August 16, 2008

Image Manipulation using GDI+ - the C# way : Basics

Image manipulation is considered one of the difficult tasks in Graphics Programming. This is more so if the Operating System under consideration is Windows. The reason is that to achieve efficiency nothing can find a better option than Windows API. The APIs provided by Windows comes under the GDI roof. GDI is short for Graphics Device Interface. However, GDI works at low level graphics. So to use it good understanding of how Windows work is required. Even with MFC, GDI is a bit complicated. But with evolution of GDI+ the scenario is changing. The major change between GDI and GDI+ is that GDI exposes only APIs for unmanaged code whereas GDI+ provides for both managed as well as unmanaged code. Hence GDI+ is oriented towards .Net based languages. And in the world of .Net, one of the best options is C#. So in this discussion, I would be focusing on how to use the basic image manipulations using GDI+ library in C#. The first section would focus on the terminology used by GDI+ and image manipulation in general. In the second section I would detail the steps involved in image manipulation using GDI+. The last section would be about using the basic image manipulation within a real world application. That’s the outline for this discussion.

Image Manipulation using GDI+ - the Terminology:

Before understanding how to use GDI+ APIs for image manipulation, it is better to understand what GDI+ really is and what constitutes its vocabulary. If we consider basic image manipulation, there four points that need to be understood which are:

1. GDI+

2. Vector Graphics

3. Raster Graphics

4. Imaging

The second, third and fourth are integral part of image manipulation vocabulary. The fourth term in itself consists of many terms, some which would be discussed in this section.

1. GDI+:

By definition “GDI+ is a library that provides an interface that allows programmers to write Windows and Web graphics applications that interact with graphical devices such as printers, monitors, or files”. In essence, it provides a layer of abstraction over varied devices with which GUI needs to work. This abstraction works by converting the data into device compatible form. The device then turns the data into human readable form. The implementation of GDI+ is in the form of C++ classes that can be used from .Net environment. In .Net library, GDI+ classes are exposed through the System.Drawing and its namespaces.

2. Vector Graphics:

By definition “Graphics in which an image is stored as a series of numbers defining size, position, and shape”. In other words, in Vector graphics the image contains position vectors describing the image, where a vector represents both quantity and direction. For example, instead of containing a bit in a file for say a line being drawn, a vector graphics file describes a series of points to be connected. Also since the file contains vector commands, the size of the file becomes small.

3. Raster Graphics:

Raster is grid of x- and y- co-ordinates on a display space which, in this case is the display device. A Raster Graphics file contains information identifying which of these coordinates to illuminate using monochrome (black and white) or spectro-chrome (color) values. Raster images are also known as Bit-mapped images or Bitmaps because it contains information directly mapped to the display device’s grid. Due to this they have larger size than that of Vector Graphic files.

4. Imaging:

Imaging is the process of viewing and manipulating the images. In managed GDI+, imaging has two facets – Basic and Advanced. The processes in Basic covers loading and saving, zooming, scaling etc. whereas that in Advanced covers color palette, metafiles and tagged images. The basic functionalities are encapsulated in Image class. It provides methods to load, save and create images. The subclasses of Image class i.e. Bitmap and Metafile provides the functionality for displaying and manipulating the images.

That was a bird’s eye view of the recurring terms in the world of GDI+ and image manipulation. In the next section I will discuss about steps in loading and manipulating it using flipping as well as rotating the image.

Image Manipulation Using GDI+ - Step By Step:

Now lets have a look at steps at using the GDI+ for image manipulation. There are four main steps:

1. Overriding the Paint event of Form

2. Obtaining the Graphics object

3. Obtaining the Image object

4. Apply manipulation methods

First two steps is required whenever one has to work with GDI+. However, the last two comes into picture only when image manipulation has to be done. So here are the details:

1. Overriding the Paint event of form:

In .Net applications, drawing is done on a Form’s surface. This is same for both web applications as well as desktop application. The function where the actual drawing code can be hooked into is the Paint method. So, first step is to override this method to get foothold into the draw process within the application. This can be achieved either by supplying Paint handler to the Form’s paint method or by overriding OnPaint method. Though its better to provide Paint handler.

2. Obtaining the Graphics object:

The next step is to obtain the object of Graphics class. Because only through the Graphics object that the drawing methods can be called. To show an image it has to be drawn on to the Form. That can only be done using the DrawImage method of an object of Graphic class. An object of Graphics object is associated with a form. So it can be obtained by-

a. Using PaintEventArgs argument passed into the Paint handler

b. Using PaintArgs argument passed into the OnPaint method

c. Using CreateGraphics method of a Form.

The example of the first method would be thus:

private void form1_Paint(object sender, PaintEventArgs e)

{

Graphics g = e.Graphics;

}

where form1_Paint is the handler for Paint event of Form form1. The Graphics property of the PaintEventArgs returns a Graphics object associated with the Form object. The second way can be exemplified as :

protected override void OnPaint(PaintEventArgs e)

{

Graphics g = e.Graphics;

}

The main difference between first and second is that in the second way, the OnPaint method is overridden. The example for the third way would be :


Graphics g = this.CreateGraphics();

Where this refers to the Form in which this statement has been embedded. The CreateGraphics() method returns a method object of the Form. The only drawback of this approach is that the Graphics object would have to be disposed manually using dispose method of the Graphics object. I prefer the first method. Hence I would be using it henceforth.


3. Obtaining the Image object:

Image object can be obtained in three different ways using the static methods provided by Image class:

a. FromFile method returns an Image from the file specified as argument.


b. FromHbitmap creates and returns an Image object from a window handle to a

bitmap.


c. FromStream creates an Image object from a stream of bytes (in a file or a

database).


Among these, the first method is most commonly used if the image is available as a file, whereas the third method comes handy in web applications where the images would be stored as a column value of a table. The following statements creates an object of Image class using the first method:


Image curImage = Image.FromFile(“flower.bmp”);


4. Apply manipulation methods:

For the sole purpose of imaging, the Image class provides many methods. The most common in imaging are Flip and Rotate. The Image class provides for these by the following method – RotateFlip. The parameter to this method defines whether the flip as well as rotation both has to be done or only one of flip and rotation has to be applied. It also defines through what degrees flip or rotate has to be done. The following table provides most common arguments to the RotateFlip method as well as their description. The argument being passed are the members of RotateFlipType.




Member

Description

Rotate180FlipNone

180-degree rotation without flipping

Rotate180FlipX

180-degree rotation with a horizontal flip

Rotate180FlipXY

180-degree rotation with horizontal and vertical flips

Rotate180FlipY

180-degree rotation with a vertical flip

Rotate270FlipNone

270-degree rotation without flipping

Rotate270FlipX

270-degree rotation with a horizontal flip

Rotate270FlipXY

270-degree rotation with horizontal and vertical flips

Rotate270FlipY

270-degree rotation with a vertical flip

Rotate90FlipNone

90-degree rotation without flipping

Rotate90FlipX

90-degree rotation with a horizontal flip

Rotate90FlipXY

90-degree rotation with horizontal and vertical flips

Rotate90FlipY

90-degree rotation with a vertical flip

RotateNoneFlipNone

No rotation and no flipping

RotateNoneFlipX

No rotation, with a horizontal flip

RotateNoneFlipXY

No rotation, with horizontal and vertical flips

RotateNoneFlipY

No rotation, with a vertical flip


For example to flip and rotate an image through 90 degrees on both X- and Y- axes the statement would be:


curImage.RotateFlip(RotateFlipType.Rotate90FlipXY);


where curImage is an object of the type Image and the argument tells the RotateFlip method that the image has to be rotated through 90 degrees and need to be flipped both vertically and horizontally.


That brings us to the end of this section. In the next section I would develop an application that would load, flip and rotate the loaded image.


Image Manipulation – In the Real World:

Starting from this part onwards, I would be developing an image manipulation application using C# and GDI+. The basic version that would be developed now would provide the following features:


1. Load an image file

2. Rotate the loaded image 90 degrees

3. Flip the image along X- axis


First the menus have to be setup as shown in the figure below.

Fig1 – GDI_1.jpg

Fig2 - GDI_1_RotateFlip.jpg


The names of the menus are:


mnuLoad – the submenu that would show the Open dialog box and loads the file

mnu90rotate – rotates the image by 90 degrees.

mnuXfilp- flips the image along X-axis.


Here is the handler for loading the image:


private void mnuLoad_Click(object sender,

System.EventArgs e)

{

// Create OpenFileDialog

OpenFileDialog opnDlg = new OpenFileDialog();

// Set a filter for images

opnDlg.Filter =

"All Image files|*.bmp;*.gif;*.jpg;*.ico;"+

"*.emf;,*.wmf|Bitmap Files(*.bmp;*.gif;*.jpg;"+

"*.ico)|*.bmp;*.gif;*.jpg;*.ico|"+

"Meta Files(*.emf;*.wmf;*.png)|*.emf;*.wmf;*.png";

opnDlg.Title = "ImageViewer: Open Image File";

opnDlg.ShowHelp = true;

// If OK, selected

if(opnDlg.ShowDialog() == DialogResult.OK)

{

// Read current selected file name

curFileName = opnDlg.FileName;

// Create the Image object using

// Image.FromFile

try

{

curImage = Image.FromFile(curFileName);

}

catch(Exception exp)

{

MessageBox.Show(exp.Message);

}

}

// Repaint the form, which forces the paint

// event handler

Invalidate();

}

The name of the file returned by the open file dialog is set as the current file name. then it is used to load the file using the FromFile function of the Image class. The returned image is assigned to the curImage variable which is of type Image and its scope is of class level. Next Inavlidate() method is called so that paint event is fired. Following the code, embedded in the Form’s Paint method handler, that actually draws the image:


private void Form1_Paint(object sender,

System.Windows.Forms.PaintEventArgs e)

{

Graphics g = e.Graphics;

if(curImage != null)

{

// Draw image using the DrawImage method

g.DrawImage(curImage,

AutoScrollPosition.X,

AutoScrollPosition.Y,

curImage.Width,

curImage.Height );

}

}


The logic checks whether the current image is null or not. If not null, the DrawImage method of Graphic class is given the curImage as the Image to be loaded. The Graphic object is obtained from the Graphics property of PaintEventArgs object. Next the handler for rotating the image – it is embedded in the handler for the mnu90rotate menu item. Here is the code:


// Rotate 90 degrees

private void mnu90rotate_Click(object sender,

System.EventArgs e)

{

if(curImage != null)

{

curImage.RotateFlip(

RotateFlipType.Rotate90FlipNone);

Invalidate();

}

}


The image is rotated using the RotateFlip method of Image class. Since curImage is of Image class type, hence the method can be directly called on the Image object. Next it calls the Inavlidate() method to redraw the image.


Last comes the flip logic. It is embedded in the handler for the mnuXflip menu item.


// Flip X

private void mnuXflip_Click(object sender,

System.EventArgs e)

{

if(curImage != null)

{

curImage.RotateFlip(

RotateFlipType.RotateNoneFlipX);

Invalidate();

}

}

That’s all for the example. This sets up the stage for image manipulation using GDI+ in C#. However certain aspects of the problem of image manipulation have been left out including saving the image and how GDI+ works. These will be the topics that will be tackled in the next part of this series. Till then…

Note: You can find the article on: http://www.aspfree.com/c/a/C-Sharp/Basic-Image-Manipulation-using-GDI-and-C/