Monday, 8 July 2013

Generics in c# with simple example

Generics were first introduced into the C# language in .NET 2.0. Most developers are confused about C# Generics. Generics allow us to define type-safe classes without worrying about type safety and performance. In other words, generics allow you to write a class or method that can work with any data type. By creating a generic class, you can create a collection that is type-safe at compile-time. The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. These should be used whenever possible in place of classes such as ArrayList in the System.Collections namespace. The generic class introduces a type parameter. 

Example
As shown in the following code:
  • Create a Generic Interface
  • Create a Generic Class and derive the interface into the Generic Class
  • Implement the methods of the Interface in the Generic Class
    // Generic Interface   
    interface ICustomInterface<T>
    {
        void Add(T item);
        void Remove(T item);
    }
    // Generic Class   
    class UserList<T> : ICustomInterface<T>
    {
        public int count;
        ArrayList list = new ArrayList();
        //Property to get the length of the list       
        public int Count
        {
            get           

            {
                return list.Count;
            }
        }
        //Generic method
        public void Add(T item)
        {
            list.Add(item);
        }
        //generic Method       
        public void Remove(T item)
        {
            list.Remove(item);
        }        
    }


In the code above, the UserList Class is built on ArrayList. ArrayList can store any type of object in it. Here T is the type you need to provide when creating the object. Now create the object for the UserList class and use the methods as follows.


// No boxing, no casting          
//Create a UserList object for integers

UserList<int> list = new UserList<int>();
//Add two integer values           
 list.Add(1);
list.Add(2);
//Write count of the list
Console.WriteLine(list.Count);
//Remove the items from list       
list.Remove(1);
list.Remove(2);          
// Try to add string to the list 
//compile time exception will rise
//(Argument '1': cannot convert from 'string' to 'int')
//
list.Add("text");

We can store any type of the objects into the UserList<T> object by giving the type you want to store while creating the UserList<T> objects. Generics can also be used in structures and delegates etcetera.

Benefits of Generics
The benefits of generics are:

  • Code reuse, type safety, and performance.
  • You can create your own generic interfaces, classes, methods, events and delegates.
  • The most common use of generics is to create collection classes.
  • Generic classes may be constrained to enable access to methods on particular data types.
  • Generics provide no boxing, no casting advantage.
  • Generics are checked at compile time.
------
Srinubabu Ravilla
Software Developer

Simple Tooltip Using HTML and CSS

A tooltip is a pop-up message that is shown when the user hovers the mouse over an element such as a TextBox or a Button etcetera.

In this article I show you how to create a simple tooltip using HTML and CSS.

Observe the following table. Here we have placed the Input (Text) controls (txtUsername, txtPassword) inside the anchor tag. 
We have added a class name (tooltip) to the anchor tag and given some text to the the alt attribute. Using an alt attribute we will display a tooltip for the Input (Text) controls.


<html>
<head>
</head>
<body>
    <table style="width270px;">
        <tr>
            <td>
                Username:
            </td>
            <td>
                <a href="#" alt="Please enter username" class="tooltip">
                    <input id="txtUsername" type="text" /></a>
            </td>
        </tr>
        <tr>
            <td>
                Password:
            </td>
            <td>
                <a href="#" alt="Please enter password" class="tooltip">
                    <input id="txtPassword" type="text" /></a>
            </td>
        </tr>
        <tr>
            <td>
            </td>
            <td>
                <input id="Button1" type="button" value="Login" />
            </td>
        </tr>
    </table>
</body>

</html>

 Now our page looks in browser as follows

 1.png
Now we will add some CSS style to the anchor tags; see:

.tooltip
{
 display: inline;
 position: relative;
 text-decoration: none;
 top: 0px;
 left: 4px;
}
Now by using the anchor tags we will display the tooltip for the Input (Text) controls.

Observe the following style of the anchor tags:

 .tooltip:hover:after
 {
 background: #333;
 background: rgba(0,0,0,.8);
 border-radius: 5px;
 top: -5px;
 color: #fff;
 content: attr(alt);
 left: 160px;
 padding: 5px 15px;
 position: absolute;
 z-index: 98;
 width: 150px;
 }
Here we are providing a style whenever the user hover the mouse over the anchor tags.

We are specifying some style using the :after selector. 

In the preceding style we have given a border and a border radius etcetera. 

Here we have set the content attribute to content: attr(alt); this property will display the tooltip by using the alt attribute of the anchor tag.

Whatever you give to the alt tag of the anchor element it will be displayed as a tooltip.

Now we will add one arrow to the tooltip as follows using the :before selector:

.tooltip:hover:before
{
 border: solid;
 border-color: transparent black;
 border-width: 6px 6px 6px 0;
 bottom: 20px;
 content: "";
 left: 155px;
 position: absolute;
 z-index: 99;
 top: 3px;
}


Finally script of our page is:

<html>
<head>
    <style type="text/css">
        .tooltip
        {
            displayinline;
            positionrelative;
            text-decorationnone;
            top0px;
            left4px;
        }
        .tooltip:hover:after
        {
            background#333;
            backgroundrgba(0,0,0,.8);
            border-radius5px;
            top-5px;
            color#fff;
            contentattr(alt);
            left160px;
            padding5px 15px;
            positionabsolute;
            z-index98;
            width150px;
        }
        .tooltip:hover:before
        {
            bordersolid;
            border-colortransparent black;
            border-width6px 6px 6px 0;
            bottom20px;
            content"";
            left155px;
            positionabsolute;
            z-index99;
            top3px;
        }
    </style>
</head>
<body>
    <table style="width270px;">
        <tr>
            <td>
                Username:
            </td>
            <td>
                <a href="#" alt="Please enter username" class="tooltip">
                    <input id="txtUsername" type="text" /></a>
            </td>
        </tr>
        <tr>
            <td>
                Password:
            </td>
            <td>
                <a href="#" alt="Please enter password" class="tooltip">
                    <input id="txtPassword" type="text" /></a>
            </td>
        </tr>
        <tr>
            <td>
            </td>
            <td>
                <input id="Button1" type="button" value="Login" />
            </td>
        </tr>
    </table>
</body>

</html>

Save this script as .html file or download the attachment and open in browser then mouse over on to the username and password Textboxes we will get the tooltip as follows. 
Mouse over on to the Username Textbox.
2.png
Mouse over on to the Password Textbox
3.png
So this is the simple way to display the tooltip using HTML and CSS.

We can use this tooltips procedure for images also.

------
Srinubabu Ravilla
Software Developer

Tuesday, 2 July 2013

Create Simple PDF File Using iTextSharp Library

In this article I will show you how to create a simple PDF file using the iTextsharp library.

iTextSharp

iTextSharp is a library that allows you to create and manipulate PDF documents.

It enables developers looking to enhance web applications and other applications with dynamic PDF document generation and/or manipulation.

Before proceeding you should have the iTextSharp library file.

You can download the iTextSharp.dll from http://itextpdf.com/download.php.
  1. Open VisualStudio and then create a new ASP.NET web application.
  2. Add a reference to the iTextSharp.dll file to your project.
  3. Add the following namespaces before proceeding: 
using System;
using iTextSharp.text.pdf;
using System.IO;
using iTextSharp.text;
using System.Diagnostics;
  1. In the designer, drag and drop two buttons as follows:
    iTextSharp.jpg
     
  2. For the Generate PDF File button, write the following code to generate the PDF file:protected void btnGeneratePDFFile_Click(object sender, EventArgs e)
{
    //Create document
    Document doc = new  Document();
    
//Create PDF Table
    PdfPTable tableLayout = new PdfPTable(4);

    //Create a PDF file in specific path
    PdfWriter.GetInstance(doc, new FileStream(Server.MapPath("Sample-PDF-File.pdf"), FileMode.Create));

    //Open the PDF document
    doc.Open();

    //Add Content to PDF
    doc.Add(Add_Content_To_PDF(tableLayout));

    // Closing the document
    doc.Close();

    btnOpenPDFFile.Enabled = true;
    btnGeneratePDFFile.Enabled = false;
}
private PdfPTable Add_Content_To_PDF(PdfPTable tableLayout)
{
    float[] headers = { 20, 20, 30, 30 };  //Header Widths
    tableLayout.SetWidths(headers);        //Set the pdf headers
    tableLayout.WidthPercentage = 80;       //Set the PDF File witdh percentage

   //Add Title to the PDF file at the top
   tableLayout.AddCell(new PdfPCell(new Phrase("Creating PDF file using iTextsharp"new Font(Font.HELVETICA, 13, 1, new iTextSharp.text.Color(153, 51, 0)))) { Colspan = 4, Border = 0, PaddingBottom = 20, HorizontalAlignment = Element.ALIGN_CENTER });         

   //Add header
   AddCellToHeader(tableLayout, "Cricketer Name");
   AddCellToHeader(tableLayout, "Height");
   AddCellToHeader(tableLayout, "Born On");
   AddCellToHeader(tableLayout, "Parents");           

   //Add body
   AddCellToBody(tableLayout, "Sachin Tendulkar");
   AddCellToBody(tableLayout, "1.65 m");
   AddCellToBody(tableLayout, "April 24, 1973");
   AddCellToBody(tableLayout, "Ramesh Tendulkar, Rajni Tendulkar");

   AddCellToBody(tableLayout, "Mahendra Singh Dhoni");
   AddCellToBody(tableLayout, "1.75 m");
   AddCellToBody(tableLayout, "July 7, 1981");
   AddCellToBody(tableLayout, "Devki Devi, Pan Singh");

   AddCellToBody(tableLayout, "Virender Sehwag");
   AddCellToBody(tableLayout, "1.70 m");
   AddCellToBody(tableLayout, "October 20, 1978");
   AddCellToBody(tableLayout, "Aryavir Sehwag, Vedant Sehwag");

   AddCellToBody(tableLayout, "Virat Kohli");
   AddCellToBody(tableLayout, "1.75 m");
   AddCellToBody(tableLayout, "November 5, 1988");
   AddCellToBody(tableLayout, "Saroj Kohli, Prem Kohli");

   return tableLayout;
}

// Method to add single cell to the header
private static void AddCellToHeader(PdfPTable tableLayout,string cellText)
{          
    tableLayout.AddCell(new PdfPCell(new Phrase(cellText, new Font(Font.HELVETICA, 8, 1, iTextSharp.text.Color.WHITE))) {HorizontalAlignment = Element.ALIGN_CENTER, Padding=5, BackgroundColor =new iTextSharp.text.Color(0, 51, 102) });
}

// Method to add single cell to the body
private static void AddCellToBody(PdfPTable tableLayout, string cellText)
{           
    tableLayout.AddCell(new PdfPCell(new Phrase(cellText, new Font(Font.HELVETICA, 8, 1, iTextSharp.text.Color.BLACK))) { HorizontalAlignment = Element.ALIGN_CENTER,Padding = 5, BackgroundColor = iTextSharp.text.Color.WHITE });
}

Don't be confused by the code above, I am extracting the methods for reusability purposes.

I will explain whats happening in the preceding methods.

btnGeneratePDFFile_Click

In this method I am creating the PDF file in a specific location. Then I am calling the Add_Content_To_PDF method.

Add_Content_To_PDF

In this method I am giving the sizes of the cells as well as PDF file width and then I am adding content to the PDF file usigng the two methods AddCellToHeader and AddCellToBody.

AddCellToHeader

In this mehtod I am adding a single cell to the PDF header with some style.

AddCellToBody

In this mehtod I am adding a single cell to the PDF body with some style. 
  1. Now in the Open PDF button click write the following code to open the PDF that has been created:protected void btnOpenPDFFile_Click(object sender, EventArgs e)
    {
        //Open the PDF file
        Process.Start(Server.MapPath("Sample-PDF-File.pdf"));
        btnGeneratePDFFile.Enabled = true;
        btnOpenPDFFile.Enabled = false;
    }

  2. Save the files and run the project. Click on Generate PDF; your PDF file will be generated. Then click on the Open PDF file, you will get the created PDF. 
  3. If your code is not working download the project from here Download
So in this way we can create a PDF simply by using the iTextSharp library.