Thursday, March 25, 2010

Abstract V/S Interface

Abstract Class

These classes are either partially implemented, or not at all implemented.

  • This class can contain declarations and also implementations.
  • An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.
  • A non-abstract class derived from an Abstract class must include implementations for all inherited abstract methods.
  • Abstract class can contain abstract methods, abstract property as well as other members (just like normal class).

Interface

Interface is a pure abstract entity:

  • An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. It contains only the declaration.
  • We cannot make instance of an Interface. We must inherit to use Interface.
  • A class which implements the interface should implement all the members of an Interface.
  • Members of an Interface are always public.
  • The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesnt support multiple inheritance, interfaces are used to implement multiple inheritance.

Few Advantages

An advantage of Abstract class over Interface :


If you want to have additional functionalities for the interface, you must implement the new ones in all of the classes that implement the changed interface. The code will not work until you make the change. But if you want to have additional functions to the Abstract class, you can have default implementation. Your code still might work without many changes.


An advantage of Interface over Abstract class :


A class can inherit multiple interfaces but can inherit only one class.

Both Together

  • When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.
  • When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.
  • There are some similarities and differences between an interface and an abstract class that I have arranged in a table for easier comparison:

Feature

Interface

Abstract class

Multiple inheritance

A class may inherit several interfaces.

A class may inherit only one abstract class.

Default implementation

An interface cannot provide any code, just the signature.

An abstract class can provide complete, default code and/or just the details that have to be overridden.

Access Modifiers

An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public

An abstract class can contain access modifiers for the subs, functions, properties

Core VS Peripheral

Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.

An abstract class defines the core identity of a class and there it is used for objects of the same type.

Homogeneity

If various implementations only share method signatures then it is better to use Interfaces.

If various implementations are of the same kind and use common behavior or status then abstract class is better to use.

Speed

Requires more time to find the actual method in the corresponding classes.

Fast

Adding functionality (Versioning)

If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.

If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.

Fields and Constants

No fields can be defined in interfaces

An abstract class can have fields and constants defined


Conclusion

  • Abstract class gives an Identity to the derived object.
  • Interface extends the ability of an object.
  • Interfaces give polymorphic behavior.
  • Abstract class also gives polymorphic behavior. But it is more meaningful to say that Abstract class simplifies versioning, as the base class is flexible and inheriting class can create many versions of it by additional functions and also by implementing Interfaces.
  • Interfaces and Abstract Classes both promote re usability.

ALL THE BEST

Thursday, October 22, 2009

Thumbnail Images Display in ListView

In this post i am showing how to display thumbnails of images which are stored in database using ListView control.

















UI Design: I am using a picture Box,ImageList and list view.

ImageList is renamed as imagethumbnails
List view is renamed as listviewthumbnails.

Changes done in some properties of listviewthumbnails ( list view) are:
Multiselect = False.
Showitemtooltips =true.
Sorting = Ascending.

Expand the SmallImageList property and set the followings:
Name=imagethumbnails
ColorDepth=Depth 32Bit
ImageSize=150 x 150
Note:If we don't set these properties we get blurred thumbnail images.

as we are displaying thumbnail images in listviewthumbnail (List view) ,make it of same size as picturebox. and send the picturebox background.



Code Part:
//On Thumbnail button click
















private void btnThumbnails_Click(object sender, EventArgs e)
  1. {
  2. try
  3. {

  4. listviewthumbnails.BringToFront();

  5. DataTable dtthumb = new DataTable( );
  6. dtthumb = getallimages( ) ;/
  7. thumbcount = dtthumb.Rows.Count;

  8. int counter = 0;
  9. int i = 0;
  10. Image img = null;

  11. if (!processedthumbnailed) //process it only once,to improve the performance on next click
  12. {
  13. while (counter <>
  14. {
  15. if (dtthumb.Rows != null)
  16. {

  17. img = (System.Drawing.Image)(RetrieveImage(dtthumb.Rows[i][0] as byte[]));
  18. Image imgthumb = img.GetThumbnailImage(110, 110, null, new IntPtr());
  19. imagethumbnails.Images.Add(imgthumb);
  20. imagethumbnails.ImageSize = new Size(150, 150);
  21. ListViewItem item = new ListViewItem(" ");
  22. item.ToolTipText = Convert.ToString(dtthumb.Rows[i][1]);
  23. item.ImageIndex = counter;
  24. listviewthumbnails.TileSize = new Size(100, 100);
  25. listviewthumbnails.Items.Add(item);
  26. i++;
  27. }
  28. processedthumbnailed = true;
  29. counter++;
  30. }
  31. }

  32. listviewthumbnails.SmallImageList = imagethumbnails;
  33. listviewthumbnails.View = View.List;
  34. listviewthumbnails.Visible = true;

  35. }
  36. catch (Exception ex)
  37. {
  38. MessageBox.Show(ex.Message);
  39. }
  40. }

//reconstructing image from byte array

private System.Drawing.Image RetrieveImage(byte[] NodeIcon)
{
System.Drawing.Image image = null;
byte[] imageData = (byte[])NodeIcon;

if (imageData == null)
return image;

MemoryStream memStream = new MemoryStream(imageData);
image = System.Drawing.Image.FromStream(memStream);
return image;
}


public DataTable getallimages( )
{
try
{
DataTable dt = new DataTable();
MySqlDataAdapter MDDataAdapter = new MySqlDataAdapter();

MySqlConnection Conn = new MySqlConnection("datasource=localhost;username=root;" +
"password=root;database=telemedicine");
MalDet.Open();
MySqlCommand mdCommand = new MySqlCommand("SP_GetAllImages", Conn;
mdCommand.CommandType = CommandType.StoredProcedure;

MDDataAdapter.SelectCommand = mdCommand;
MDDataAdapter.Fill(dt);

mdCommand.ExecuteNonQuery();
Conn.Close();
return (dt);

}
catch (Exception ex)
{
return null;
}

}

//Double click on selected thumbnail image to view large image















private void listviewthumbnails_DoubleClick(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt = getallimages(1);
listviewthumbnails.SendToBack();
int index = Convert.ToInt32(listviewthumbnails.SelectedIndices[0]);
Image ima = (System.Drawing.Image)(RetrieveImage(dt.Rows[index][0] as byte[]));
pictureBox1.Refresh();
pictureBox1.Image = ima;
}

}



Code Explanation:

private void btnThumbnails_Click(object sender, EventArgs e)
{
Get all the images from the database by calling "getallimages( )" , which returns datatable containing image data. Assign the returned datatable to newly created datatable "dtthumb".


In "While loop" retrieve each image from datatable "dtthumb" by calling "RetrieveImage " function, which returns Image by passing image byte array and then assing it to "img".

Create a thumbnail image for that returned image by using "GetThumbnailImage" inbuilt function.
Add the thumbnail image to " imagethumbnails"(Imagelist).

Set width and height of the thumbnail image.


Create new "ListViewItem" object by passing null string Assigning image name to tooltip text (dtthumb.Rows[i][1] gives image name and dtthumb.Rows[i][0] gives image data )

Set the index of the image that is displayed for the item(ListViewItems)


Add items to listviewthumbnails.


Set the "processedthumbnailed" variable to true so that next time when we click on thumbnail
button it will display already processed images.

Display all the images as small icons in the "ListView" control by setting the view to list.

}



NOTE:We are using "processedthumbnailed" bool variable to check whether thumbnails are already processed.we don't need to process the same thumbnails when we click "Thumbnail" button again,because thumbnail images are already present in "listviewthumbnail" , which we can display directly.

private System.Drawing.Image RetrieveImage(byte[] NodeIcon)
{
Create new instance of MemoryStream of bytearray. Constructing an image from memory byte stream(Converting byte array stream to an image)
}


private void listviewthumbnails_DoubleClick(object sender, EventArgs e)
{

Get all the images from the database by calling "getallimages( )" , which returns datatable containing image data. Assign the returned datatable to newly created datatable "dt".

Get the index of the selected or double clicked thumbnail image.

Fetch the image using it's index position in datatable dt , reconstruct the image by calling "RetrieveImage( )" function by passing byte array of image data and assign the reconstructed large original image to image "ima".


Display large image of double clicked thumbnail image in to picturebox.


}

public DataTable getallimages( )
{


Create the MySql connection and open the connection Call the stored procedure "SP_GetAllImages" Fill the datatable"dt" with the returned result set. return the datatable

}

NOTE:Stored procedure "SP_GetAllImages" contains the query " select ImageData, ImageId from images" which fetches ImageData and Image Name.